hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
923433a7221839ecea016f238b781386f1016346 | 296 | java | Java | iutools-core/src/main/java/org/iutools/datastructure/trie/RW_TrieNodeException.java | alaindesilets/iutools | 3cd8aa2431b7fbeaecf2208258a8878730f6745f | [
"MIT"
] | 2 | 2020-07-26T22:50:30.000Z | 2020-08-01T23:23:35.000Z | iutools-core/src/main/java/org/iutools/datastructure/trie/RW_TrieNodeException.java | alaindesilets/iutools | 3cd8aa2431b7fbeaecf2208258a8878730f6745f | [
"MIT"
] | 16 | 2020-08-06T00:46:07.000Z | 2020-12-12T12:00:59.000Z | iutools-core/src/main/java/org/iutools/datastructure/trie/RW_TrieNodeException.java | alaindesilets/iutools | 3cd8aa2431b7fbeaecf2208258a8878730f6745f | [
"MIT"
] | 2 | 2020-07-15T17:53:05.000Z | 2020-11-21T16:57:31.000Z | 21.142857 | 56 | 0.756757 | 996,854 | package org.iutools.datastructure.trie;
public class RW_TrieNodeException extends Exception {
public RW_TrieNodeException(String mess, Exception e) {
super(mess, e);
}
public RW_TrieNodeException(String mess) {
super(mess);
}
public RW_TrieNodeException(Exception e) {
super(e);
}
}
|
923433c203e9e7550ca7c1bb08d546554390d436 | 1,103 | java | Java | order-service/src/main/java/com/haipings/order/service/model/entity/Order.java | haipings/hello-micro-service | b1108f41d01192a8a7369c8d0494f0439a307102 | [
"Apache-2.0"
] | null | null | null | order-service/src/main/java/com/haipings/order/service/model/entity/Order.java | haipings/hello-micro-service | b1108f41d01192a8a7369c8d0494f0439a307102 | [
"Apache-2.0"
] | null | null | null | order-service/src/main/java/com/haipings/order/service/model/entity/Order.java | haipings/hello-micro-service | b1108f41d01192a8a7369c8d0494f0439a307102 | [
"Apache-2.0"
] | null | null | null | 19.350877 | 92 | 0.62466 | 996,855 | package com.haipings.order.service.model.entity;
import java.util.List;
public class Order {
private Integer id;
private String orderNo;
private Double totalPrice;
private List<Product> productList;
public Order() {
}
public Order(Integer id, String orderNo, Double totalPrice, List<Product> productList) {
this.id = id;
this.orderNo = orderNo;
this.totalPrice = totalPrice;
this.productList = productList;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getOrderNo() {
return orderNo;
}
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
public Double getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(Double totalPrice) {
this.totalPrice = totalPrice;
}
public List<Product> getProductList() {
return productList;
}
public void setProductList(List<Product> productList) {
this.productList = productList;
}
}
|
923434dacd178f729cbf992110c675bccef5d927 | 3,300 | java | Java | modules/core/src/main/java/org/apache/ignite/internal/processors/cache/binary/BinaryMetadataHolder.java | treelab/ignite | ec89c8586df89899ae56ebbc598639e0afea5901 | [
"CC0-1.0"
] | 4,339 | 2015-08-21T21:13:25.000Z | 2022-03-30T09:56:44.000Z | modules/core/src/main/java/org/apache/ignite/internal/processors/cache/binary/BinaryMetadataHolder.java | treelab/ignite | ec89c8586df89899ae56ebbc598639e0afea5901 | [
"CC0-1.0"
] | 1,933 | 2015-08-24T11:37:40.000Z | 2022-03-31T08:37:08.000Z | modules/core/src/main/java/org/apache/ignite/internal/processors/cache/binary/BinaryMetadataHolder.java | treelab/ignite | ec89c8586df89899ae56ebbc598639e0afea5901 | [
"CC0-1.0"
] | 2,140 | 2015-08-21T22:09:00.000Z | 2022-03-25T07:57:34.000Z | 30 | 118 | 0.661212 | 996,856 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.cache.binary;
import java.io.Serializable;
import org.apache.ignite.internal.binary.BinaryMetadata;
/**
* Wrapper for {@link BinaryMetadata} which is stored in metadata local cache on each node.
* Used internally to track version counters (see javadoc for {@link MetadataUpdateProposedMessage} for more details).
*/
final class BinaryMetadataHolder implements Serializable {
/** */
private static final long serialVersionUID = 0L;
/** */
private final BinaryMetadata metadata;
/** */
private final int pendingVer;
/** */
private final int acceptedVer;
/** */
private final transient boolean removing;
/**
* @param metadata Metadata.
* @param pendingVer Version of this metadata - how many updates were issued for this type.
* @param acceptedVer Pending updates count.
*/
BinaryMetadataHolder(BinaryMetadata metadata, int pendingVer, int acceptedVer) {
this(metadata, pendingVer, acceptedVer, false);
}
/**
* @param metadata Metadata.
* @param pendingVer Pending updates count.
* @param acceptedVer Version of this metadata - how many updates were issued for this type.
* @param removing Flag means the metadata is removing now.
*/
private BinaryMetadataHolder(BinaryMetadata metadata, int pendingVer, int acceptedVer, boolean removing) {
assert metadata != null;
this.metadata = metadata;
this.pendingVer = pendingVer;
this.acceptedVer = acceptedVer;
this.removing = removing;
}
/**
* @return Holder metadata with remove state where remove pending message has been handled.
*/
BinaryMetadataHolder createRemoving() {
return new BinaryMetadataHolder(metadata, pendingVer, acceptedVer, true);
}
/**
*
*/
BinaryMetadata metadata() {
return metadata;
}
/**
*
*/
int pendingVersion() {
return pendingVer;
}
/**
*
*/
int acceptedVersion() {
return acceptedVer;
}
/**
* @return {@code true} is the metadata is removing now.
*/
boolean removing() {
return removing;
}
/** {@inheritDoc} */
@Override public String toString() {
return "[typeId=" + metadata.typeId() +
", pendingVer=" + pendingVer +
", acceptedVer=" + acceptedVer +
", removing=" + removing +
"]";
}
}
|
923434ebef66fb681e74f2dc9f8d497cac6c8eb0 | 375 | java | Java | src/main/java/com/github/jeuxjeux20/loupsgarous/game/tags/revealers/LGTagRevealersModule.java | jeuxjeux20/LoupGarous | 8620c2dc849e123ac20c52c9798396811a801e35 | [
"MIT"
] | null | null | null | src/main/java/com/github/jeuxjeux20/loupsgarous/game/tags/revealers/LGTagRevealersModule.java | jeuxjeux20/LoupGarous | 8620c2dc849e123ac20c52c9798396811a801e35 | [
"MIT"
] | null | null | null | src/main/java/com/github/jeuxjeux20/loupsgarous/game/tags/revealers/LGTagRevealersModule.java | jeuxjeux20/LoupGarous | 8620c2dc849e123ac20c52c9798396811a801e35 | [
"MIT"
] | null | null | null | 26.785714 | 68 | 0.741333 | 996,857 | package com.github.jeuxjeux20.loupsgarous.game.tags.revealers;
public final class LGTagRevealersModule extends TagRevealersModule {
@Override
protected void configureBindings() {
bind(TagRevealer.class).to(TagRevealerAggregator.class);
}
@Override
protected void configureTagRevealers() {
addTagRevealer(MaireTagRevealer.class);
}
}
|
92343907b47072b000484a4e2c4b03ad1398aab9 | 1,706 | java | Java | src/test/java/com/mumukiller/alert/service/StockServiceIT.java | mumukiller/stock-patterns-alert | ac94b67a7a56e1fe99c7ca5df91cf0efbf5ac503 | [
"MIT"
] | 3 | 2017-12-24T14:32:21.000Z | 2021-03-17T14:38:59.000Z | src/test/java/com/mumukiller/alert/service/StockServiceIT.java | mumukiller/stock-patterns-alert | ac94b67a7a56e1fe99c7ca5df91cf0efbf5ac503 | [
"MIT"
] | null | null | null | src/test/java/com/mumukiller/alert/service/StockServiceIT.java | mumukiller/stock-patterns-alert | ac94b67a7a56e1fe99c7ca5df91cf0efbf5ac503 | [
"MIT"
] | 1 | 2020-04-20T17:51:18.000Z | 2020-04-20T17:51:18.000Z | 29.929825 | 103 | 0.743259 | 996,858 | package com.mumukiller.alert.service;
import com.google.common.collect.ImmutableList;
import com.mumukiller.alert.repository.StockRepository;
import com.mumukiller.alert.transport.Stock;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import rx.observers.TestSubscriber;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
/**
* Created by Mumukiller on 15.07.2017.
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class StockServiceIT {
@Autowired
private StockService stockService;
@Test
public void checkList() throws Exception {
assertEquals(4, stockService.getMonitoredStockCodes().size());
}
@Test
public void checkEmpty() throws Exception {
assertFalse(stockService.getRealtimeStockSample("ANY").isPresent());
}
@Test
public void checkEmptyList() throws Exception {
assertEquals(0, stockService.getRealtimeStocksSamples(ImmutableList.of("ANY", "ANY")).count());
}
@Test
public void checkEmptyStream() throws Exception {
TestSubscriber<Map<String, Stock>> testSubscriber = new TestSubscriber<>();
stockService.getStockSamplesObservable()
.subscribe(testSubscriber);
testSubscriber.assertNoErrors();
final List<Map<String, Stock>> result = testSubscriber.getOnNextEvents();
assertEquals(0, result.size());
}
}
|
923439d4da96fbb13ec93915293387374ea847af | 104 | java | Java | java/NASAM/main/src/org/evensen/prng/SplittablePrng.java | pellevensen/NASAM | d68e1ed256c510c8a05994103d261dfb35df5511 | [
"Apache-2.0"
] | 1 | 2021-06-19T18:11:01.000Z | 2021-06-19T18:11:01.000Z | java/NASAM/main/src/org/evensen/prng/SplittablePrng.java | pellevensen/NASAM | d68e1ed256c510c8a05994103d261dfb35df5511 | [
"Apache-2.0"
] | null | null | null | java/NASAM/main/src/org/evensen/prng/SplittablePrng.java | pellevensen/NASAM | d68e1ed256c510c8a05994103d261dfb35df5511 | [
"Apache-2.0"
] | null | null | null | 17.333333 | 62 | 0.759615 | 996,859 | package org.evensen.prng;
public interface SplittablePrng<T extends SplittablePrng<T>> {
T split();
}
|
923439dd0b75905d9c90040f5b42c12cbf035a8c | 309 | java | Java | src/main/java/it/davidenastri/javaspringdependencyinjectionexamples/services/ConstructorInjectedGreetingService.java | ltpitt/java-spring-dependency-injection-examples | 9c8af06c015e85216fa2bfe26d6b1af3d34c136b | [
"MIT"
] | null | null | null | src/main/java/it/davidenastri/javaspringdependencyinjectionexamples/services/ConstructorInjectedGreetingService.java | ltpitt/java-spring-dependency-injection-examples | 9c8af06c015e85216fa2bfe26d6b1af3d34c136b | [
"MIT"
] | null | null | null | src/main/java/it/davidenastri/javaspringdependencyinjectionexamples/services/ConstructorInjectedGreetingService.java | ltpitt/java-spring-dependency-injection-examples | 9c8af06c015e85216fa2bfe26d6b1af3d34c136b | [
"MIT"
] | null | null | null | 22.071429 | 76 | 0.783172 | 996,860 | package it.davidenastri.javaspringdependencyinjectionexamples.services;
import org.springframework.stereotype.Service;
@Service
public class ConstructorInjectedGreetingService implements GreetingService {
@Override
public String sayGreeting() {
return "Hello World - Constructor";
}
}
|
923439e954ef5f3dcf8ce05ac32413db858de636 | 314 | java | Java | app/src/main/java/com/example/wenda01/beans/weather/Now.java | nuolade/medicalHelper | 40cb12a6aa799b81804507d34d904f93f5f56b8d | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/wenda01/beans/weather/Now.java | nuolade/medicalHelper | 40cb12a6aa799b81804507d34d904f93f5f56b8d | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/wenda01/beans/weather/Now.java | nuolade/medicalHelper | 40cb12a6aa799b81804507d34d904f93f5f56b8d | [
"Apache-2.0"
] | null | null | null | 19.625 | 50 | 0.681529 | 996,861 | package com.example.wenda01.beans.weather;
import com.google.gson.annotations.SerializedName;
public class Now {
@SerializedName("tmp")
public String temperature;
@SerializedName("cond")
public More more;
public class More{
@SerializedName("txt")
public String info;
}
}
|
92343b5fb195c93104a299413a7a9cf199aadbfe | 1,281 | java | Java | src/main/java/com/example/application/views/about/AboutView.java | Pedroloma/Seriepedia | 0ded5da584b0d597560180b987d6368f3de64dc3 | [
"Unlicense"
] | null | null | null | src/main/java/com/example/application/views/about/AboutView.java | Pedroloma/Seriepedia | 0ded5da584b0d597560180b987d6368f3de64dc3 | [
"Unlicense"
] | null | null | null | src/main/java/com/example/application/views/about/AboutView.java | Pedroloma/Seriepedia | 0ded5da584b0d597560180b987d6368f3de64dc3 | [
"Unlicense"
] | null | null | null | 37.676471 | 95 | 0.739266 | 996,862 | package com.example.application.views.about;
import com.example.application.views.main.MainView;
import com.vaadin.flow.component.dependency.CssImport;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.html.Image;
import com.vaadin.flow.component.html.Label;
import com.vaadin.flow.component.html.Span;
import com.vaadin.flow.component.orderedlayout.FlexComponent;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
@Route(value = "about", layout = MainView.class)
@PageTitle("About")
@CssImport("./styles/views/about/about-view.css")
public class AboutView extends Div {
public AboutView() {
Span span = new Span();
span.setText("This website is only for learning and practising the Vaadin framework.");
HorizontalLayout horizontalLayout = new HorizontalLayout();
setId("about-view");
Label label = new Label("All data in this web is provided by \"themoviedb.org\"");
Image image = new Image();
image.setSrc("images/the_movie_db.svg");
horizontalLayout.add(label, image);
horizontalLayout.setAlignItems(FlexComponent.Alignment.CENTER);
add(span, horizontalLayout);
}
}
|
92343c71dbb7442f65dc0de192538ef10ff10997 | 5,270 | java | Java | src/main/java/com/castellanos94/problems/PSP.java | castellanos94/jemoa | dc2e96eae16c62a675df457612abd3f9dd2afe18 | [
"MIT"
] | 3 | 2021-08-30T08:50:31.000Z | 2022-03-27T07:00:56.000Z | src/main/java/com/castellanos94/problems/PSP.java | castellanos94/jemoa | dc2e96eae16c62a675df457612abd3f9dd2afe18 | [
"MIT"
] | 7 | 2020-10-24T22:01:14.000Z | 2021-12-20T03:43:18.000Z | src/main/java/com/castellanos94/problems/PSP.java | castellanos94/jemoa | dc2e96eae16c62a675df457612abd3f9dd2afe18 | [
"MIT"
] | null | null | null | 38.188406 | 112 | 0.580645 | 996,863 | package com.castellanos94.problems;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import com.castellanos94.datatype.Data;
import com.castellanos94.datatype.IntegerData;
import com.castellanos94.instances.PSPInstance;
import com.castellanos94.solutions.BinarySolution;
import com.castellanos94.utils.Tools;
/*
*@author Castellanos Alvarez, Alejandro
*@since 22/03/2020
*/
public class PSP extends Problem<BinarySolution> {
public PSP(PSPInstance instance) {
this.instance = instance;
this.numberOfObjectives = instance.getData("nObj").intValue();
this.numberOfDecisionVars = instance.getData("nProjects").intValue();
this.objectives_type = new int[numberOfObjectives];
for (int i = 0; i < objectives_type.length; i++) {
objectives_type[i] = Problem.MAXIMIZATION;
}
this.numberOfConstrains = 1;
}
@Override
public void evaluate(BinarySolution solution) {
Data[] objs = new Data[numberOfObjectives];
for (int i = 0; i < objs.length; i++) {
objs[i] = new IntegerData(0);
}
Data[][] projects = instance.getDataMatrix("projects");
Data current_budget = new IntegerData(0);
for (int i = 0; i < this.numberOfDecisionVars; i++) {
if (solution.getVariable(0).get(i)) {
current_budget = current_budget.plus(projects[i][0]);
for (int j = 0; j < numberOfObjectives; j++) {
objs[j] = objs[j].plus(projects[i][3 + j]);
}
}
}
solution.setResource(0, current_budget);
solution.setObjectives(new ArrayList<>(Arrays.asList(objs)));
}
@Override
public void evaluateConstraint(BinarySolution sol) {
Data budget = instance.getData("budget");
IntegerData current_budget = new IntegerData(0);
Data[][] projects = instance.getDataMatrix("projects");
IntegerData[][] areas = (IntegerData[][]) instance.getDataMatrix("areas");
IntegerData[][] regions = (IntegerData[][]) instance.getDataMatrix("regions");
Data areaSum[] = new Data[areas.length];
for (int i = 0; i < areaSum.length; i++) {
areaSum[i] = new IntegerData(0);
}
Data regionSum[] = new Data[regions.length];
for (int i = 0; i < regionSum.length; i++) {
regionSum[i] = new IntegerData(0);
}
for (int i = 0; i < numberOfDecisionVars; i++) {
if (sol.getVariable(0).get(i)) {
// if (sol.getVariables().get(i).compareTo(one) == 0) {
current_budget = (IntegerData) current_budget.plus(projects[i][0]);
int area = projects[i][1].intValue() - 1;
int region = projects[i][2].intValue() - 1;
areaSum[area] = areaSum[area].plus(projects[i][0]);
regionSum[region] = regionSum[region].plus(projects[i][0]);
}
}
Data penaltie = new IntegerData(0);
int penalties = 0;
if (current_budget.compareTo(budget) > 0) {
penalties++;
penaltie = budget.minus(current_budget);
}
for (int i = 0; i < regionSum.length; i++) {
if (regionSum[i].compareTo(regions[i][0]) < 0) {// limite inferior
penaltie = penaltie.plus(regionSum[i].minus(regions[i][0]));
penalties++;
}
if (regionSum[i].compareTo(regions[i][1]) > 0) { // limite superior
penaltie = penaltie.plus(regions[i][1].minus(regionSum[i]));
penalties++;
}
}
for (int i = 0; i < areaSum.length; i++) {
if (areaSum[i].compareTo(areas[i][0]) < 0) {
penaltie = penaltie.plus(areaSum[i].minus(areas[i][0]));
penalties++;
}
if (areaSum[i].compareTo(areas[i][1]) > 0) {
penaltie = penaltie.plus(areas[i][1].minus(areaSum[i]));
penalties++;
}
}
sol.setNumberOfPenalties(penalties);
sol.setPenalties(penaltie);
}
@Override
public BinarySolution randomSolution() {
BinarySolution sol = new BinarySolution(this);
List<Integer> positions = IntStream.range(0, numberOfDecisionVars).boxed().collect(Collectors.toList());
Collections.shuffle(positions);
Data[][] projects = instance.getDataMatrix("projects");
Data budget = instance.getData("budget");
IntegerData current_budget = new IntegerData(0);
for (int i = 0; i < positions.size(); i++) {
if (Tools.getRandom().nextDouble() < 0.5
&& projects[positions.get(i)][0].plus(current_budget).compareTo(budget) <= 0) {
sol.getVariable(0).set(positions.get(i));
current_budget = (IntegerData) current_budget.plus(projects[positions.get(i)][0]);
}
}
sol.setResource(0, current_budget);
return sol;
}
@Override
public BinarySolution getEmptySolution() {
return new BinarySolution(this);
}
} |
92343cf18dd3c275d8f45b2075e77b79cdbe7171 | 1,516 | java | Java | buttermilk-core/src/main/java/com/cryptoregistry/ec/Secp160k1.java | buttermilk-crypto/buttermilk | 4c35b82be32c421c6630beab83110ea7a898f0ce | [
"Apache-2.0"
] | null | null | null | buttermilk-core/src/main/java/com/cryptoregistry/ec/Secp160k1.java | buttermilk-crypto/buttermilk | 4c35b82be32c421c6630beab83110ea7a898f0ce | [
"Apache-2.0"
] | null | null | null | buttermilk-core/src/main/java/com/cryptoregistry/ec/Secp160k1.java | buttermilk-crypto/buttermilk | 4c35b82be32c421c6630beab83110ea7a898f0ce | [
"Apache-2.0"
] | null | null | null | 29.461538 | 78 | 0.684073 | 996,864 | /*
* This file is part of Buttermilk
* Copyright 2011-2014 David R. Smith All Rights Reserved.
*
*/
package com.cryptoregistry.ec;
import java.math.BigInteger;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.math.ec.ECConstants;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.util.encoders.Hex;
public class Secp160k1 extends ECParametersHolderBase {
private static final String NAME = "secp160k1";
private Secp160k1(ECDomainParameters params) {
super(params);
}
static Secp160k1 instance() {
ECDomainParameters p = init(NAME);
return new Secp160k1(p);
}
private static ECDomainParameters init(String name) {
// p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1
BigInteger p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73");
BigInteger a = ECConstants.ZERO;
BigInteger b = BigInteger.valueOf(7);
byte[] S = null;
BigInteger n = fromHex("0100000000000000000001B8FA16DFAB9ACA16B6B3");
BigInteger h = BigInteger.valueOf(1);
ECCurve curve = new ECCurve.Fp(p, a, b);
ECPoint G = curve.decodePoint(Hex.decode("04"
+ "ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6b"
+ "ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7"));
return new NamedECDomainParameters(curve, G, n, h, S, name);
}
@Override
public ECDomainParameters createParameters() {
return cached;
}
}
|
92343dcc809d76ad44c3c394d2ad4e1ad74de082 | 2,106 | java | Java | src/main/java/aramframework/com/sec/dpt/service/DeptService.java | aramsoft/aramcomp | e8ae6be64a0e389384d8ee1ef8064fa3a4405ba8 | [
"Apache-2.0"
] | 11 | 2016-01-01T15:57:10.000Z | 2016-10-13T04:34:38.000Z | src/main/java/aramframework/com/sec/dpt/service/DeptService.java | aramsoft/aramcomp | e8ae6be64a0e389384d8ee1ef8064fa3a4405ba8 | [
"Apache-2.0"
] | 17 | 2016-01-06T05:33:53.000Z | 2022-01-04T16:57:12.000Z | src/main/java/aramframework/com/sec/dpt/service/DeptService.java | aramsoft/aramcomp | e8ae6be64a0e389384d8ee1ef8064fa3a4405ba8 | [
"Apache-2.0"
] | 4 | 2016-01-03T23:35:14.000Z | 2016-01-11T13:35:50.000Z | 19.867925 | 62 | 0.700855 | 996,865 | package aramframework.com.sec.dpt.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import aramframework.com.sec.dpt.dao.DeptMapper;
import aramframework.com.sec.dpt.domain.DeptVO;
import egovframework.rte.fdl.cmmn.EgovAbstractServiceImpl;
import egovframework.rte.fdl.cmmn.exception.FdlException;
import egovframework.rte.fdl.idgnr.EgovIdGnrService;
import egovframework.rte.psl.dataaccess.util.EgovMap;
/**
* 부서관리에 관한 비지니스클래스를 정의한다.
*
* @author 아람컴포넌트 조헌철
* @since 2014.11.11
* @version 1.0
*/
@Service
public class DeptService extends EgovAbstractServiceImpl {
@Autowired
private DeptMapper deptMapper;
/** Message ID Generation */
@Autowired
private EgovIdGnrService deptIdGnrService;
/**
* 부서를 관리하기 위해 등록된 부서목록을 조회한다.
*
* @param deptVO
*/
public List<EgovMap> selectDeptList(DeptVO deptVO) {
return deptMapper.selectDeptList(deptVO);
}
/**
* 부서목록 총 갯수를 조회한다.
*
* @param deptVO
*/
public int selectDeptListCnt(DeptVO deptVO) {
return deptMapper.selectDeptListCnt(deptVO);
}
/**
* 등록된 부서의 상세정보를 조회한다.
*
* @param deptVO
*/
public DeptVO selectDept(DeptVO deptVO) {
return deptMapper.selectDept(deptVO);
}
/**
* 부서정보를 신규로 등록한다.
*
* @param deptVO
*/
public void insertDept(DeptVO deptVO) {
try {
deptVO.setOrgnztId(deptIdGnrService.getNextStringId());
} catch (FdlException e) {
throw new RuntimeException(e);
}
deptMapper.insertDept(deptVO);
}
/**
* 기 등록된 부서정보를 수정한다.
*
* @param deptVO
*/
public void updateDept(DeptVO deptVO) {
deptMapper.updateDept(deptVO);
}
/**
* 기 등록된 부서정보를 삭제한다.
*
* @param deptVO
*/
public void deleteDept(DeptVO deptVO) {
deptMapper.deleteDept(deptVO);
}
/**
* 기 등록된 부서정보를 삭제한다.
*
* @param deptVO
*/
public void deleteDepts(String orgnztIds) {
String[] strOrgnztIds = orgnztIds.split(";");
DeptVO dmVO = new DeptVO();
for (int i = 0; i < strOrgnztIds.length; i++) {
dmVO.setOrgnztId(strOrgnztIds[i]);
deptMapper.deleteDept(dmVO);
}
}
}
|
92343e3b1a8d8719e90ff5e6c2642f69573b1cee | 2,085 | java | Java | grouper-misc/grouper-pspng/src/main/java/edu/internet2/middleware/grouper/pspng/lbmq/AbstractPollable.java | ACNSMiddleware/grouper | 25ddc83fec1389e48482d659c790e53a50a079f7 | [
"Apache-2.0"
] | 63 | 2015-02-02T17:24:08.000Z | 2022-02-18T07:20:13.000Z | grouper-misc/grouper-pspng/src/main/java/edu/internet2/middleware/grouper/pspng/lbmq/AbstractPollable.java | ACNSMiddleware/grouper | 25ddc83fec1389e48482d659c790e53a50a079f7 | [
"Apache-2.0"
] | 92 | 2015-01-21T14:40:00.000Z | 2022-02-10T23:56:03.000Z | grouper-misc/grouper-pspng/src/main/java/edu/internet2/middleware/grouper/pspng/lbmq/AbstractPollable.java | ACNSMiddleware/grouper | 25ddc83fec1389e48482d659c790e53a50a079f7 | [
"Apache-2.0"
] | 70 | 2015-03-23T08:50:33.000Z | 2022-03-18T07:00:57.000Z | 34.75 | 119 | 0.63789 | 996,866 | package edu.internet2.middleware.grouper.pspng.lbmq;
import java.util.NoSuchElementException;
import java.util.Queue;
/**
* This class provides skeletal implementations of some {@link Pollable} operations. The implementations in this class
* are appropriate when the base implementation does <em>not</em> allow <tt>null</tt> elements. Methods {@link #remove
* remove}, and {@link #element element} are based on {@link #poll poll}, and {@link #peek peek}, respectively, but
* throw exceptions instead of indicating failure via <tt>false</tt> or <tt>null</tt> returns.
*
* <p>
* A <tt>Pollable</tt> implementation that extends this class must minimally define methods {@link Queue#peek} and
* {@link Queue#poll}. Typically, additional methods will be overridden as well.
*
* @param <E>
* the type of elements held in this collection
*/
public abstract class AbstractPollable<E> implements Pollable<E> {
/**
* Retrieves and removes the head of this queue. This method differs from {@link #poll poll} only in that it throws
* an exception if this queue is empty.
*
* <p>
* This implementation returns the result of <tt>poll</tt> unless the queue is empty.
*
* @return the head of this queue
* @throws NoSuchElementException
* if this queue is empty
*/
public E remove() {
E x = poll();
if (x != null)
return x;
else
throw new NoSuchElementException();
}
/**
* Retrieves, but does not remove, the head of this queue. This method differs from {@link #peek peek} only in that
* it throws an exception if this queue is empty.
*
* <p>
* This implementation returns the result of <tt>peek</tt> unless the queue is empty.
*
* @return the head of this queue
* @throws NoSuchElementException
* if this queue is empty
*/
public E element() {
E x = peek();
if (x != null)
return x;
else
throw new NoSuchElementException();
}
}
|
92343ed721cc9e6ffe80eb4508d214ad878af945 | 339 | java | Java | service-news/src/main/java/com/leiran/news/controller/AbstractController.java | ice-fun/leiCloud | 0e52a581ba9af73afaa4c920aacd3457aa81f83e | [
"Apache-2.0"
] | null | null | null | service-news/src/main/java/com/leiran/news/controller/AbstractController.java | ice-fun/leiCloud | 0e52a581ba9af73afaa4c920aacd3457aa81f83e | [
"Apache-2.0"
] | null | null | null | service-news/src/main/java/com/leiran/news/controller/AbstractController.java | ice-fun/leiCloud | 0e52a581ba9af73afaa4c920aacd3457aa81f83e | [
"Apache-2.0"
] | 1 | 2021-10-09T11:12:28.000Z | 2021-10-09T11:12:28.000Z | 16.95 | 43 | 0.761062 | 996,867 | package com.leiran.news.controller;
import com.leiran.news.service.NewsService;
import com.leiran.security.util.RedisUtils;
import javax.annotation.Resource;
/**
* author:lei ran
*/
public abstract class AbstractController {
@Resource
protected NewsService newsService;
@Resource
protected RedisUtils redisUtils;
}
|
92343fc46bf354dfc0c230105a49fef4f11fbce2 | 2,191 | java | Java | utils/src/main/java/hexagon/utils/Log.java | HexagonNico/HexagonEngine | a0382be4a38c18a74e512faa7111b86443622dc8 | [
"MIT"
] | null | null | null | utils/src/main/java/hexagon/utils/Log.java | HexagonNico/HexagonEngine | a0382be4a38c18a74e512faa7111b86443622dc8 | [
"MIT"
] | null | null | null | utils/src/main/java/hexagon/utils/Log.java | HexagonNico/HexagonEngine | a0382be4a38c18a74e512faa7111b86443622dc8 | [
"MIT"
] | null | null | null | 24.344444 | 106 | 0.671839 | 996,868 | package hexagon.utils;
import java.io.PrintStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* Utility class to print messages to the console with additional information.
*
* @author Nico
*/
public final class Log {
/**
* Prints an info message to the console.
*
* @param message The message to print.
*/
public static void info(String message) {
print(System.out, "Info", message);
}
/**
* Prints a warning message to the console.
* Used for non serious errors.
*
* @param message The message to print.
*/
public static void warning(String message) {
print(System.out, "Warning", message);
}
/**
* Prints an error message to the console.
*
* @param message The message to print.
*/
public static void error(String message) {
print(System.err, "Error", message);
}
/**
* Prints a fatal error to the console.
* Used for errors that inevitably cause the program to stop.
*
* @param message The message to print.
*/
public static void fatal(String message) {
print(System.err, "Fatal", message);
}
/**
* Prints a message to the console, avoids duplicate code.
*
* @param stream Print stream, {@code System.out} or {@code System.err}
* @param level Level of severity, changes the beginning of the message
* @param message The message to print
*/
private static void print(PrintStream stream, String level, String message) {
stream.println("[" + getTime() + "] [HexagonEngine] [" + getCaller() + "] [" + level + "]: " + message);
}
/**
* Gets the name of the caller class.
*
* @return Full name of the caller class.
*/
private static String getCaller() {
try {
return Class.forName(Thread.currentThread().getStackTrace()[4].getClassName()).getSimpleName();
} catch (ClassNotFoundException e) {
return "Unknown caller";
}
}
/**
* Gets the current time.
*
* @return Current system time.
*/
private static String getTime() {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
return dtf.format(now);
}
/**This class should not be instantiated */
private Log() {}
}
|
9234403bfd09ee3befe439ab0b5d9127d7ad3c4c | 876 | java | Java | android/capacitor/src/main/java/com/getcapacitor/annotation/CapacitorPlugin.java | pwandl/capacitor | a37e188bf1ab57465e86f6b2ab7c4c2308a21173 | [
"MIT"
] | null | null | null | android/capacitor/src/main/java/com/getcapacitor/annotation/CapacitorPlugin.java | pwandl/capacitor | a37e188bf1ab57465e86f6b2ab7c4c2308a21173 | [
"MIT"
] | 32 | 2020-12-15T07:09:48.000Z | 2022-01-31T10:12:22.000Z | android/capacitor/src/main/java/com/getcapacitor/annotation/CapacitorPlugin.java | pwandl/capacitor | a37e188bf1ab57465e86f6b2ab7c4c2308a21173 | [
"MIT"
] | null | null | null | 25.764706 | 74 | 0.679224 | 996,869 | package com.getcapacitor.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Base annotation for all Plugins
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface CapacitorPlugin {
/**
* Request codes this plugin uses and responds to, in order to tie
* Android events back the plugin to handle
*/
int[] requestCodes() default {};
/**
* Permissions this plugin needs, in order to make permission requests
* easy if the plugin only needs basic permission prompting
*/
Permission[] permissions() default {};
/**
* The request code to use when automatically requesting permissions
*/
int permissionRequestCode() default 9000;
/**
* A custom name for the plugin, otherwise uses the
* simple class name.
*/
String name() default "";
}
|
9234406b90252ccbaa8a5e66fd38ba6535d773e7 | 4,090 | java | Java | src/main/java/com/tokyo/beach/restaurants/restaurant/RestaurantsController.java | pivotal-tokyo/osusume-java-spring | a1561e41ed63b028998f4a61ad5203ffed6e4f9e | [
"BSD-2-Clause"
] | null | null | null | src/main/java/com/tokyo/beach/restaurants/restaurant/RestaurantsController.java | pivotal-tokyo/osusume-java-spring | a1561e41ed63b028998f4a61ad5203ffed6e4f9e | [
"BSD-2-Clause"
] | null | null | null | src/main/java/com/tokyo/beach/restaurants/restaurant/RestaurantsController.java | pivotal-tokyo/osusume-java-spring | a1561e41ed63b028998f4a61ad5203ffed6e4f9e | [
"BSD-2-Clause"
] | 1 | 2017-12-15T11:09:24.000Z | 2017-12-15T11:09:24.000Z | 42.164948 | 122 | 0.757702 | 996,870 | package com.tokyo.beach.restaurants.restaurant;
import com.tokyo.beach.restaurants.photos.PhotoDataMapper;
import com.tokyo.beach.restaurants.photos.PhotoUrl;
import com.tokyo.beach.restaurants.s3.S3StorageRepository;
import com.tokyo.beach.restutils.RestControllerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.http.HttpStatus.OK;
import static org.springframework.web.bind.annotation.RequestMethod.*;
@CrossOrigin
@RestController
@RequestMapping("/restaurants")
public class RestaurantsController {
private RestaurantRepository restaurantRepository;
private final PhotoDataMapper photoDataMapper;
private final S3StorageRepository s3StorageRepository;
@Autowired
public RestaurantsController(
RestaurantRepository restaurantRepository,
PhotoDataMapper photoDataMapper,
S3StorageRepository storageRepository
) {
this.restaurantRepository = restaurantRepository;
this.photoDataMapper = photoDataMapper;
this.s3StorageRepository = storageRepository;
}
@RequestMapping(value = "", method = GET)
public List<SerializedRestaurant> getAll() {
Number userId = getCurrentUserId(RequestContextHolder.getRequestAttributes());
return restaurantRepository.getAll(userId.longValue());
}
@RequestMapping(value = "{id}", method = GET)
public SerializedRestaurant getRestaurant(@PathVariable String id) {
Number userId = getCurrentUserId(RequestContextHolder.getRequestAttributes());
Optional<SerializedRestaurant> maybeRestaurant = restaurantRepository.get(Long.parseLong(id), userId.longValue());
maybeRestaurant.orElseThrow(() -> new RestControllerException("Invalid restaurant id."));
return maybeRestaurant.get();
}
@RequestMapping(value = "", method = POST)
@ResponseStatus(CREATED)
public SerializedRestaurant create(@RequestBody NewRestaurantWrapper restaurantWrapper) {
Number userId = getCurrentUserId(RequestContextHolder.getRequestAttributes());
return restaurantRepository.create(restaurantWrapper.getRestaurant(), userId.longValue());
}
@RequestMapping(value = "{id}", method = PATCH)
@ResponseStatus(OK)
public SerializedRestaurant updateRestaurant(
@PathVariable String id,
@RequestBody NewRestaurantWrapper restaurantWrapper
) {
return restaurantRepository.update(new Long(id), restaurantWrapper.getRestaurant());
}
@RequestMapping(value = "{restaurantId}/photoUrls/{photoUrlId}", method = DELETE)
@ResponseStatus(HttpStatus.OK)
public void deletePhotoUrl(@PathVariable String restaurantId, @PathVariable String photoUrlId) {
Optional<PhotoUrl> maybePhotoUrl = photoDataMapper.get(Long.parseLong(photoUrlId));
if (maybePhotoUrl.isPresent()) {
photoDataMapper.delete(Long.parseLong(photoUrlId));
s3StorageRepository.deleteFile(maybePhotoUrl.get().getUrl());
}
}
@RequestMapping(value = "{restaurantId}", method = DELETE)
@ResponseStatus(HttpStatus.OK)
public void deleteRestaurant(@PathVariable String restaurantId) {
Number userId = getCurrentUserId(RequestContextHolder.getRequestAttributes());
restaurantRepository.delete(Long.parseLong(restaurantId), userId.longValue());
}
private Number getCurrentUserId(RequestAttributes requestAttributes) {
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
return (Number) request.getAttribute("userId");
}
}
|
923440e238265549c806ed9a5dec063d1990abd7 | 2,636 | java | Java | hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/common/ContainerTestUtils.java | DadanielZ/hadoop | 4a70a0d81601f20ba8cecb37fae12b6a8be327b4 | [
"Apache-2.0"
] | 4 | 2019-07-05T07:05:29.000Z | 2019-09-03T03:41:04.000Z | hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/common/ContainerTestUtils.java | DadanielZ/hadoop | 4a70a0d81601f20ba8cecb37fae12b6a8be327b4 | [
"Apache-2.0"
] | 127 | 2019-02-12T07:39:37.000Z | 2021-08-02T16:57:33.000Z | hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/common/ContainerTestUtils.java | DadanielZ/hadoop | 4a70a0d81601f20ba8cecb37fae12b6a8be327b4 | [
"Apache-2.0"
] | 4 | 2017-02-15T23:14:28.000Z | 2019-12-12T19:26:13.000Z | 38.202899 | 80 | 0.774659 | 996,871 | /**
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.hadoop.ozone.container.common;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.retry.RetryPolicies;
import org.apache.hadoop.ipc.ProtobufRpcEngine;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.ozone.container.common.statemachine
.EndpointStateMachine;
import org.apache.hadoop.ozone.protocolPB
.StorageContainerDatanodeProtocolClientSideTranslatorPB;
import org.apache.hadoop.ozone.protocolPB.StorageContainerDatanodeProtocolPB;
import org.apache.hadoop.security.UserGroupInformation;
import java.net.InetSocketAddress;
/**
* Helper utility to test containers.
*/
public final class ContainerTestUtils {
private ContainerTestUtils() {
}
/**
* Creates an Endpoint class for testing purpose.
*
* @param conf - Conf
* @param address - InetAddres
* @param rpcTimeout - rpcTimeOut
* @return EndPoint
* @throws Exception
*/
public static EndpointStateMachine createEndpoint(Configuration conf,
InetSocketAddress address, int rpcTimeout) throws Exception {
RPC.setProtocolEngine(conf, StorageContainerDatanodeProtocolPB.class,
ProtobufRpcEngine.class);
long version =
RPC.getProtocolVersion(StorageContainerDatanodeProtocolPB.class);
StorageContainerDatanodeProtocolPB rpcProxy = RPC.getProtocolProxy(
StorageContainerDatanodeProtocolPB.class, version,
address, UserGroupInformation.getCurrentUser(), conf,
NetUtils.getDefaultSocketFactory(conf), rpcTimeout,
RetryPolicies.TRY_ONCE_THEN_FAIL).getProxy();
StorageContainerDatanodeProtocolClientSideTranslatorPB rpcClient =
new StorageContainerDatanodeProtocolClientSideTranslatorPB(rpcProxy);
return new EndpointStateMachine(address, rpcClient, conf);
}
}
|
9234436a7e30c1fcb1e54dc47d2b2242a81469a1 | 1,703 | java | Java | src/main/java/com/github/EPLBot/command/LastRoundCommand.java | DenZhukov/EPLBot | 7fa07c8d0a9319d9a8851b73256e5392ce0aba6b | [
"Apache-2.0"
] | null | null | null | src/main/java/com/github/EPLBot/command/LastRoundCommand.java | DenZhukov/EPLBot | 7fa07c8d0a9319d9a8851b73256e5392ce0aba6b | [
"Apache-2.0"
] | null | null | null | src/main/java/com/github/EPLBot/command/LastRoundCommand.java | DenZhukov/EPLBot | 7fa07c8d0a9319d9a8851b73256e5392ce0aba6b | [
"Apache-2.0"
] | null | null | null | 40.547619 | 123 | 0.677628 | 996,872 | package com.github.EPLBot.command;
import com.github.EPLBot.service.SendBotMessageService;
import com.github.EPLBot.sportapiclient.SportClient;
import com.sportdataapi.data.Match;
import org.telegram.telegrambots.meta.api.objects.Update;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import static com.sportdataapi.data.MatchStatus.ENDED;
public class LastRoundCommand implements Command{
private final SendBotMessageService sendBotMessageService;
private final SportClient sportClient;
public LastRoundCommand(SendBotMessageService sendBotMessageService, SportClient sportClient) {
this.sendBotMessageService = sendBotMessageService;
this.sportClient = sportClient;
}
@Override
public void execute(Update update) {
List<Match> matchesMap = sportClient.getMatchesList(sportClient.getIdSeason(), ENDED).stream()
.sorted(new Comparator<Match>() {
@Override
public int compare(Match o1, Match o2) {
return o2.getStart().getTime().hashCode() - o1.getStart().getTime().hashCode();
}
})
.limit(10).collect(Collectors.toList());
String roundMatches = matchesMap.stream()
.map(match -> String.format("%s %s %d:%d\n", match.getHomeTeam().getName(), match.getGuestTeam().getName(),
match.getResults().getScores().getHomeScore(), match.getResults().getScores().getGuestScore()))
.collect(Collectors.joining());
sendBotMessageService.sendMessage(update.getMessage().getChatId().toString(), roundMatches);
}
}
|
92344371b5b87ffd984e1b6ee26b9364ae3ffc6f | 872 | java | Java | src/main/java/dev/necro/coyotelib/client/ClientProxy.java | QbDesu/CoyoteLib | 58ef6947a1f5cc1a53d042160a83059e4e8a2b82 | [
"Unlicense"
] | null | null | null | src/main/java/dev/necro/coyotelib/client/ClientProxy.java | QbDesu/CoyoteLib | 58ef6947a1f5cc1a53d042160a83059e4e8a2b82 | [
"Unlicense"
] | 1 | 2021-11-18T21:43:53.000Z | 2021-11-18T23:11:01.000Z | src/main/java/dev/necro/coyotelib/client/ClientProxy.java | QbDesu/CoyoteLib | 58ef6947a1f5cc1a53d042160a83059e4e8a2b82 | [
"Unlicense"
] | null | null | null | 36.333333 | 89 | 0.805046 | 996,873 | package dev.necro.coyotelib.client;
import dev.necro.coyotelib.client.debug.overlay.CustomDebugOverlayHandler;
import dev.necro.coyotelib.client.game_rules.GameRuleRegistrationHandlerClientFix;
import dev.necro.coyotelib.common.CommonProxy;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
public class ClientProxy extends CommonProxy {
@Override
public void registerListeners(IEventBus modEventBus){
super.registerListeners(modEventBus);
modEventBus.addListener(this::clientSetup);
MinecraftForge.EVENT_BUS.addListener(GameRuleRegistrationHandlerClientFix::init);
}
public void clientSetup(final FMLClientSetupEvent event) {
CustomDebugOverlayHandler.init(event.getMinecraftSupplier().get());
}
}
|
92344708b8c947e747b8ce89b3aee96d95904040 | 1,434 | java | Java | src/test/java/io/r2dbc/h2/codecs/InstantCodecTest.java | gaybro8777/r2dbc-h2 | 6770428fe3e14d34d81c3a4567b0683ea42ef0eb | [
"Apache-2.0"
] | null | null | null | src/test/java/io/r2dbc/h2/codecs/InstantCodecTest.java | gaybro8777/r2dbc-h2 | 6770428fe3e14d34d81c3a4567b0683ea42ef0eb | [
"Apache-2.0"
] | 1 | 2022-01-21T23:45:14.000Z | 2022-01-21T23:45:14.000Z | src/test/java/io/r2dbc/h2/codecs/InstantCodecTest.java | gaybro8777/r2dbc-h2 | 6770428fe3e14d34d81c3a4567b0683ea42ef0eb | [
"Apache-2.0"
] | null | null | null | 30.510638 | 119 | 0.675035 | 996,874 | package io.r2dbc.h2.codecs;
import org.h2.value.Value;
import org.h2.value.ValueNull;
import org.h2.value.ValueTimestampTimeZone;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
class InstantCodecTest {
@Test
void decode() {
assertThat(new InstantCodec().decode(ValueTimestampTimeZone.parse("2018-10-31 11:59:59+00:00"), Instant.class))
.isEqualTo(Instant.parse("2018-10-31T11:59:59Z"));
}
@Test
void doCanDecode() {
OffsetDateTimeCodec codec = new OffsetDateTimeCodec();
assertThat(codec.doCanDecode(Value.TIMESTAMP_TZ)).isTrue();
assertThat(codec.doCanDecode(Value.UNKNOWN)).isFalse();
assertThat(codec.doCanDecode(Value.INT)).isFalse();
}
@Test
void doEncode() {
assertThat(new InstantCodec().encode(Instant.parse("2018-10-31T11:59:59Z")))
.isEqualTo(ValueTimestampTimeZone.parse("2018-10-31 11:59:59+00:00"));
}
@Test
void doEncodeNoValue() {
assertThatIllegalArgumentException().isThrownBy(() -> new InstantCodec().doEncode(null))
.withMessage("value must not be null");
}
@Test
void encodeNull() {
assertThat(new InstantCodec().encodeNull())
.isEqualTo(ValueNull.INSTANCE);
}
} |
923448ac4ae2d428fa833929f016f1cff1debc9e | 351 | java | Java | src/main/java/com/fizal/xunit/dbunit/model/StringPrinter.java | fizalihsan/XUnitTools | 80eefc20f3830c705f17a8a93897d9f46c298b16 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/fizal/xunit/dbunit/model/StringPrinter.java | fizalihsan/XUnitTools | 80eefc20f3830c705f17a8a93897d9f46c298b16 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/fizal/xunit/dbunit/model/StringPrinter.java | fizalihsan/XUnitTools | 80eefc20f3830c705f17a8a93897d9f46c298b16 | [
"Apache-2.0"
] | null | null | null | 21.9375 | 63 | 0.663818 | 996,875 | package com.fizal.xunit.dbunit.model;
import org.springframework.format.Printer;
import java.util.Locale;
/**
* Created by fmohamed on 9/20/2016.
*/
public class StringPrinter implements Printer<String> {
@Override
public String print(String value, Locale locale) {
return value == null ? "''" : "'" + value.trim() + "'";
}
}
|
923448d23e8b27cbe9b280b88537f4fc492f8159 | 4,721 | java | Java | aws-ssm-association/src/main/java/com/amazonaws/ssm/association/ReadHandler.java | reillynoah/aws-cloudformation-resource-providers-ssm | 80850e3e8b04117d2ddbc6d99a59f0772869306a | [
"Apache-2.0"
] | 23 | 2020-05-18T04:43:47.000Z | 2022-02-23T04:50:52.000Z | aws-ssm-association/src/main/java/com/amazonaws/ssm/association/ReadHandler.java | reillynoah/aws-cloudformation-resource-providers-ssm | 80850e3e8b04117d2ddbc6d99a59f0772869306a | [
"Apache-2.0"
] | 12 | 2020-07-20T21:16:03.000Z | 2022-02-22T20:05:50.000Z | aws-ssm-association/src/main/java/com/amazonaws/ssm/association/ReadHandler.java | reillynoah/aws-cloudformation-resource-providers-ssm | 80850e3e8b04117d2ddbc6d99a59f0772869306a | [
"Apache-2.0"
] | 24 | 2020-05-14T00:06:18.000Z | 2022-03-24T17:28:30.000Z | 44.961905 | 122 | 0.76488 | 996,876 | package com.amazonaws.ssm.association;
import com.amazonaws.ssm.association.translator.AssociationDescriptionTranslator;
import com.amazonaws.ssm.association.translator.ExceptionTranslator;
import com.amazonaws.ssm.association.util.ResourceHandlerRequestToStringConverter;
import com.amazonaws.ssm.association.util.ResourceModelToStringConverter;
import com.amazonaws.ssm.association.util.SsmClientBuilder;
import com.amazonaws.util.StringUtils;
import software.amazon.awssdk.services.ssm.SsmClient;
import software.amazon.awssdk.services.ssm.model.AssociationDescription;
import software.amazon.awssdk.services.ssm.model.DescribeAssociationRequest;
import software.amazon.cloudformation.exceptions.BaseHandlerException;
import software.amazon.cloudformation.proxy.AmazonWebServicesClientProxy;
import software.amazon.cloudformation.proxy.HandlerErrorCode;
import software.amazon.cloudformation.proxy.Logger;
import software.amazon.cloudformation.proxy.OperationStatus;
import software.amazon.cloudformation.proxy.ProgressEvent;
import software.amazon.cloudformation.proxy.ResourceHandlerRequest;
/**
* Handles read requests for a given resource.
*/
public class ReadHandler extends BaseHandler<CallbackContext> {
private static final SsmClient SSM_CLIENT = SsmClientBuilder.getClient();
private final AssociationDescriptionTranslator associationDescriptionTranslator;
private final ExceptionTranslator exceptionTranslator;
private final ResourceHandlerRequestToStringConverter requestToStringConverter;
/**
* Constructor to use by dependencies. Processes Read requests.
*/
ReadHandler() {
this.associationDescriptionTranslator = new AssociationDescriptionTranslator();
this.exceptionTranslator = new ExceptionTranslator();
this.requestToStringConverter = new ResourceHandlerRequestToStringConverter(new ResourceModelToStringConverter());
}
/**
* Used for unit tests.
*
* @param associationDescriptionTranslator Translates AssociationDescription into ResourceModel objects.
* @param exceptionTranslator Translates service model exceptions.
* @param requestToStringConverter ResourceHandlerRequestToStringConverter used to convert requests to Strings.
*/
ReadHandler(final AssociationDescriptionTranslator associationDescriptionTranslator,
final ExceptionTranslator exceptionTranslator,
final ResourceHandlerRequestToStringConverter requestToStringConverter) {
this.associationDescriptionTranslator = associationDescriptionTranslator;
this.exceptionTranslator = exceptionTranslator;
this.requestToStringConverter = requestToStringConverter;
}
@Override
public ProgressEvent<ResourceModel, CallbackContext> handleRequest(
final AmazonWebServicesClientProxy proxy,
final ResourceHandlerRequest<ResourceModel> request,
final CallbackContext callbackContext,
final Logger logger) {
logger.log(String.format("Processing ReadHandler request: %s", requestToStringConverter.convert(request)));
final ResourceModel requestModel = request.getDesiredResourceState();
final ProgressEvent<ResourceModel, CallbackContext> progressEvent = new ProgressEvent<>();
progressEvent.setStatus(OperationStatus.FAILED);
final String associationId = requestModel.getAssociationId();
if (StringUtils.isNullOrEmpty(associationId)) {
progressEvent.setErrorCode(HandlerErrorCode.NotFound);
progressEvent.setMessage("AssociationId must be present to read the existing association.");
return progressEvent;
}
final DescribeAssociationRequest describeAssociationRequest =
DescribeAssociationRequest.builder()
.associationId(associationId)
.build();
try {
final AssociationDescription association =
proxy.injectCredentialsAndInvokeV2(describeAssociationRequest, SSM_CLIENT::describeAssociation)
.associationDescription();
final ResourceModel existingModel =
associationDescriptionTranslator.associationDescriptionToResourceModel(association);
progressEvent.setResourceModel(existingModel);
progressEvent.setStatus(OperationStatus.SUCCESS);
} catch (Exception e) {
final BaseHandlerException cfnException = exceptionTranslator
.translateFromServiceException(e, describeAssociationRequest, requestModel);
logger.log(cfnException.getCause().getMessage());
throw cfnException;
}
return progressEvent;
}
}
|
9234492400c6bc22edfae49f66dc09e8f8e0fd1b | 1,593 | java | Java | android_smart_phone/mediapipe/mediapipe/examples/android/src/java/com/google/mediapipe/apps/wearableai/database/voicecommand/VoiceCommandCreator.java | cyxstudio/WearableIntelligenceSystem | 8ad44a1ed9d13d964356875d0184ef0e5673f11f | [
"MIT"
] | null | null | null | android_smart_phone/mediapipe/mediapipe/examples/android/src/java/com/google/mediapipe/apps/wearableai/database/voicecommand/VoiceCommandCreator.java | cyxstudio/WearableIntelligenceSystem | 8ad44a1ed9d13d964356875d0184ef0e5673f11f | [
"MIT"
] | null | null | null | android_smart_phone/mediapipe/mediapipe/examples/android/src/java/com/google/mediapipe/apps/wearableai/database/voicecommand/VoiceCommandCreator.java | cyxstudio/WearableIntelligenceSystem | 8ad44a1ed9d13d964356875d0184ef0e5673f11f | [
"MIT"
] | null | null | null | 43.054054 | 219 | 0.774639 | 996,877 | package com.google.mediapipe.apps.wearableai.database.voicecommand;
//originally from MXT: Memory Expansion Tools
//Jeremy Stairs (stairs1) and Cayden Pierce
//https://github.com/stairs1/memory-expansion-tools
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.Task;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import android.util.Log;
public class VoiceCommandCreator {
public static final String TAG = "WearableAi_VoiceCommandCreator";
public static void create(String commandName, String commandSpoken, String wakeWord, boolean isMaster, String argKey, String argValue, long timestamp, String medium, long transcriptId, VoiceCommandRepository repo) {
/*
Location may return right away or in a minute, null or not
Because of this, insert each voicecommand without location synchronously, and after getting id back
get location and update the voicecommand with location results whenever they arrive.
*/
VoiceCommandEntity voiceCommand = new VoiceCommandEntity(commandName, commandSpoken, wakeWord, isMaster, argKey, argValue, timestamp, medium, transcriptId);
long id = repo.insert(voiceCommand); // This insert blocks until database write has completed
Log.d(TAG, "Saved voice command to database");
}
}
|
923449c3550615166c0cf643f117d9cb2dcf34b7 | 458 | java | Java | Progetto/src/Components/GPU.java | matteolucchini/Progetto2.0 | cbe6e5388590bce2b05436cc65ccaf1de2e241f3 | [
"BSD-2-Clause"
] | null | null | null | Progetto/src/Components/GPU.java | matteolucchini/Progetto2.0 | cbe6e5388590bce2b05436cc65ccaf1de2e241f3 | [
"BSD-2-Clause"
] | null | null | null | Progetto/src/Components/GPU.java | matteolucchini/Progetto2.0 | cbe6e5388590bce2b05436cc65ccaf1de2e241f3 | [
"BSD-2-Clause"
] | null | null | null | 21.809524 | 69 | 0.528384 | 996,878 | package Components;
import Resources.Resource;
public class GPU extends AbstractComponent {
public GPU(String[] input) {
super(input);
resource = new Resource.Builder()
.withokGPU(true)
.withPower(0 - Integer.parseInt(caratteristiche[2]))
.withNPci(-1)
.build();
}
/*@Override
public int compareTo(Object o) {
return 0;
}*/
}
|
92344bef98dec4f33870f929d673ba21a84ccbe8 | 2,206 | java | Java | oj-leetcode-algorithm/src/main/java/com/nxy006/project/algorithm/leetcode/p0040/combination_sum_ii/RecursionSolution.java | nxy006/java-algorithm | 9759078d672f303ae6ac78f275d63872981ee609 | [
"MIT"
] | null | null | null | oj-leetcode-algorithm/src/main/java/com/nxy006/project/algorithm/leetcode/p0040/combination_sum_ii/RecursionSolution.java | nxy006/java-algorithm | 9759078d672f303ae6ac78f275d63872981ee609 | [
"MIT"
] | null | null | null | oj-leetcode-algorithm/src/main/java/com/nxy006/project/algorithm/leetcode/p0040/combination_sum_ii/RecursionSolution.java | nxy006/java-algorithm | 9759078d672f303ae6ac78f275d63872981ee609 | [
"MIT"
] | null | null | null | 38.034483 | 175 | 0.574343 | 996,879 | package com.nxy006.project.algorithm.leetcode.p0040.combination_sum_ii;
import com.nxy006.project.alogtithm.utils.CaseAssertUtils;
import com.nxy006.project.alogtithm.utils.StructConvertUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 递归解法
*
* Runtime 2 ms , beats 99.01 % of java submissions.
* Memory 39 MB , beats 81.59 % of java submissions.
* 07/15/2021 23:13
*/
public class RecursionSolution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(candidates);
process(candidates, target, 0, 0, res, new ArrayList<>(), new boolean[candidates.length]);
return res;
}
private void process(int[] candidates, int target, int i, int sum, List<List<Integer>> res, List<Integer> list, boolean[] exists) {
if (sum == target) {
res.add(new ArrayList<>(list));
}
for(; i < candidates.length; i++) {
// 如果与上一个数相同,且上一个数没有被选中,则当前数字也不能被选中
if (i != 0 && candidates[i-1] == candidates[i] && !exists[i-1]) {
continue;
}
if (sum + candidates[i] <= target) {
exists[i] = true;
list.add(candidates[i]);
process(candidates, target, i+1, sum + candidates[i], res, list, exists);
list.remove(list.size()-1);
exists[i] = false;
}
}
}
// ---------------------------------------------------------- TEST CASE ----------------------------------------------------------- //
public static void main(String[] args) {
// 官方用例
caseCheck(new RecursionSolution(), "[[1,1,6],[1,2,5],[1,7],[2,6]]", "[10,1,2,7,6,1,5]",8);
caseCheck(new RecursionSolution(), "[[1,2,2],[5]]", "[2,5,2,1,2]",5);
}
private static void caseCheck(RecursionSolution solution, String expected, String numsStr, int target) {
// TODO 实际应该是忽略顺序的比较
CaseAssertUtils.assertEquals(StructConvertUtils.convertToIntegerNestedList(expected), solution.combinationSum2(StructConvertUtils.convertToIntArray(numsStr), target));
}
}
|
92344cabffe385c67b2a032190decd5eab0859ca | 1,300 | java | Java | java-impl/src/main/java/org/jetbrains/java/generate/config/InsertNewMethodStrategy.java | consulo/consulo-java | e016b25321f49547a57e97132c013468c2a50316 | [
"Apache-2.0"
] | 5 | 2015-12-19T15:27:30.000Z | 2019-08-17T10:07:23.000Z | java-impl/src/main/java/org/jetbrains/java/generate/config/InsertNewMethodStrategy.java | consulo/consulo-java | e016b25321f49547a57e97132c013468c2a50316 | [
"Apache-2.0"
] | 47 | 2015-02-28T12:45:13.000Z | 2021-12-15T15:42:34.000Z | java-impl/src/main/java/org/jetbrains/java/generate/config/InsertNewMethodStrategy.java | consulo/consulo-java | e016b25321f49547a57e97132c013468c2a50316 | [
"Apache-2.0"
] | 2 | 2018-03-08T16:17:47.000Z | 2019-08-17T18:20:38.000Z | 30.952381 | 97 | 0.743846 | 996,880 | /*
* Copyright 2001-2013 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.jetbrains.java.generate.config;
import javax.annotation.Nonnull;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiMethod;
/**
* Interface that defines a policy for dealing with where to insert a new <code>toString()</code>
* method in the javafile.
*/
public interface InsertNewMethodStrategy
{
/**
* Applies the chosen policy.
*
* @param clazz PSIClass.
* @param newMethod new method.
* @param editor
* @return if the policy was executed normally (not cancelled)
*/
@javax.annotation.Nullable
PsiMethod insertNewMethod(PsiClass clazz, @Nonnull PsiMethod newMethod, Editor editor);
}
|
92344e10839d728677de70c167edebee63cec252 | 2,586 | java | Java | VRLauncher-you/app/src/main/java/com/vstar3d/Obj/Base.java | zoozooll/MyExercise | 1be14e0252babb28e32951fa1e35fc867a6ac070 | [
"Apache-2.0"
] | 2 | 2019-07-03T00:38:50.000Z | 2020-08-06T06:24:06.000Z | VRLauncher-you/app/src/main/java/com/vstar3d/Obj/Base.java | zoozooll/MyExercise | 1be14e0252babb28e32951fa1e35fc867a6ac070 | [
"Apache-2.0"
] | null | null | null | VRLauncher-you/app/src/main/java/com/vstar3d/Obj/Base.java | zoozooll/MyExercise | 1be14e0252babb28e32951fa1e35fc867a6ac070 | [
"Apache-2.0"
] | null | null | null | 25.60396 | 80 | 0.726218 | 996,881 | package com.vstar3d.Obj;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.util.Log;
import android.widget.Toast;
public class Base {
private static final String TAG = "Base";
public static final float MaxWidth=4000.0f;
public static Bitmap loadImageAssets(Context context,String ImgName)
{
Bitmap bmp=null;
try {
BufferedInputStream bis = new BufferedInputStream(context.getAssets().open(
ImgName));
bmp = BitmapFactory.decodeStream(bis);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bmp;
}
public static boolean getBluetoothEnabled()
{
BluetoothAdapter bluetoothAdapter = BluetoothAdapter
.getDefaultAdapter();
if (bluetoothAdapter != null)
{
return bluetoothAdapter.isEnabled();
}
return false;
}
public static Bitmap initBitmap() {
Bitmap bmp = Bitmap.createBitmap(50, 24, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
// canvas.drawColor(Color.BLACK);
Paint p = new Paint();
p.setColor(Color.WHITE);
p.setTextSize(20);
p.setTypeface(Typeface.DEFAULT_BOLD);
p.setAntiAlias(true);
String time = getCurrentTime();
canvas.drawText(time, 1, 18, p);
return bmp;
}
public static Bitmap initBitmap(String title) {
Bitmap bmp = Bitmap.createBitmap(70, 24, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
// canvas.drawColor(Color.BLACK);
Paint p = new Paint();
p.setColor(Color.WHITE);
p.setTextSize(16);
p.setTypeface(Typeface.DEFAULT_BOLD);
p.setAntiAlias(true);
int tw=(int)p.measureText(title);
int l=0;
if(tw>70)
l=0;
else
l=(70-tw)/2;
canvas.drawText(title, l, 18, p);
return bmp;
}
public static String getCurrentTime(){
long l = System.currentTimeMillis();
return new SimpleDateFormat("HH:mm", Locale.CHINA).format(new Date(l));
}
public static void startApp(Context context, String string) {
Intent intent = context.getPackageManager().getLaunchIntentForPackage(string);
if (intent == null) {
Toast.makeText(context, "打开应用失败,请检查是否正确安装", Toast.LENGTH_SHORT).show();
return;
}
context.startActivity(new Intent(intent));
}
}
|
92344e65f1d9374641137723296baee2bd4a49c9 | 2,720 | java | Java | struts/src/main/java/com/intellij/struts/dom/validator/Formset.java | MadRatSRP/intellij-obsolete-plugins | e0d0f87a908dbb3147e3d115f94452a2da79b7eb | [
"Apache-2.0"
] | 10 | 2019-11-21T16:35:34.000Z | 2022-02-28T14:13:32.000Z | struts/src/main/java/com/intellij/struts/dom/validator/Formset.java | MadRatSRP/intellij-obsolete-plugins | e0d0f87a908dbb3147e3d115f94452a2da79b7eb | [
"Apache-2.0"
] | 4 | 2019-12-04T10:43:12.000Z | 2020-08-12T13:48:35.000Z | struts/src/main/java/com/intellij/struts/dom/validator/Formset.java | MadRatSRP/intellij-obsolete-plugins | e0d0f87a908dbb3147e3d115f94452a2da79b7eb | [
"Apache-2.0"
] | 18 | 2019-10-30T21:30:30.000Z | 2022-03-19T08:28:06.000Z | 25.660377 | 140 | 0.681618 | 996,882 | /*
* Copyright 2000-2019 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.
*/
// Generated on Wed Apr 05 15:23:26 MSD 2006
// DTD/Schema : validator_1_2_0.dtd
package com.intellij.struts.dom.validator;
import com.intellij.ide.presentation.Presentation;
import com.intellij.struts.dom.StrutsRootElement;
import com.intellij.struts.dom.converters.StrutsElementNamer;
import com.intellij.util.xml.GenericAttributeValue;
import org.jetbrains.annotations.NotNull;
import java.util.List;
/**
* validator_1_2_0.dtd:formset interface.
* Type formset documentation
* <pre>
* The "formset" element defines a set of forms for a locale. Formsets for
* specific locales can override only those fields that change. The
* localization is properly scoped, so that a formset can override just the
* language, or just the country, or both.
* </pre>
*/
@Presentation(icon = "StrutsApiIcons.Validator.Formset",
provider = StrutsElementNamer.class)
public interface Formset extends StrutsRootElement {
/**
* Returns the value of the variant child.
* Attribute variant
*
* @return the value of the variant child.
*/
@NotNull
GenericAttributeValue<String> getVariant();
/**
* Returns the value of the country child.
* Attribute country
*
* @return the value of the country child.
*/
@NotNull
GenericAttributeValue<String> getCountry();
/**
* Returns the value of the language child.
* Attribute language
*
* @return the value of the language child.
*/
@NotNull
GenericAttributeValue<String> getLanguage();
/**
* Returns the list of constant children.
* Type constant documentation
* <pre>
* The "constant" element defines a static value that can be used as
* replacement parameters within "field" elements. The "constant-name" and
* "constant-value" elements define the constant's reference id and replacement
* value.
* </pre>
*
* @return the list of constant children.
*/
List<Constant> getConstants();
/**
* Adds new child to the list of constant children.
*
* @return created child
*/
Constant addConstant();
/**
* Returns the list of form children.
* Type form documentation
* <pre>
* The "form" element defines a set of fields to be validated. The name
* corresponds to the identifier the application assigns to the form.
* </pre>
*
* @return the list of form children.
*/
@NotNull
List<Form> getForms();
/**
* Adds new child to the list of form children.
*
* @return created child
*/
Form addForm();
}
|
92344f70b1c9e0c3daf2fb1f75bb912da25f3832 | 4,205 | java | Java | client/src/com/jchatting/util/RSA.java | hustcc/jchatting | de19de4e3d786712804afcf71c016bef2675a22b | [
"MIT"
] | 19 | 2016-05-15T02:54:57.000Z | 2020-03-26T13:44:31.000Z | server/src/com/jchatting/util/RSA.java | hustcc/jchatting | de19de4e3d786712804afcf71c016bef2675a22b | [
"MIT"
] | null | null | null | server/src/com/jchatting/util/RSA.java | hustcc/jchatting | de19de4e3d786712804afcf71c016bef2675a22b | [
"MIT"
] | 7 | 2016-09-26T06:31:02.000Z | 2021-07-23T17:24:59.000Z | 22.978142 | 72 | 0.629489 | 996,883 | /**
*
*/
package com.jchatting.util;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import javax.crypto.Cipher;
/**
* @author Xewee.Zhiwei.Wang
* @version 2011-10-6 下午06:14:02
*/
public class RSA {
public KeyPair keyPair = null;
/**
*
*/
public RSA() {
// TODO Auto-generated constructor stub
}
public RSAPublicKey getPublicKey() throws NoSuchAlgorithmException {
if (keyPair == null) {
generateKey();
}
return (RSAPublicKey)keyPair.getPublic();
}
public RSAPrivateKey getPrivateKey() throws NoSuchAlgorithmException {
if (keyPair == null) {
generateKey();
}
return (RSAPrivateKey)keyPair.getPrivate();
}
/**
* 生成密匙对
*
* @author Xewee.Zhiwei.Wang
* @version 2011-10-6 下午06:31:18
* @return
* @throws NoSuchAlgorithmException
*/
private KeyPair generateKey() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(2048, new SecureRandom());
this.keyPair = keyPairGen.generateKeyPair();
return this.keyPair;
}
/**
* 解密
*
* @author Xewee.Zhiwei.Wang
* @version 2011-10-6 下午06:37:02
* @param privateKey
* @param string
* @return
*/
public String decrypt(RSAPrivateKey privateKey, String string) {
if (string != null) {
byte[] data = decrypt(privateKey, string2Bytes(string));
if (data != null) {
return new String(data);
}
return null;
}
return null;
}
/**
* 加密
*
* @author Xewee.Zhiwei.Wang
* @version 2011-10-6 下午06:35:39
* @param publicKey
* @param string
* @return
*/
public String encrypt(RSAPublicKey publicKey, String string) {
if (string != null) {
byte[] data = encrypt(publicKey, string.getBytes());
if (data != null) {
return byte2String(data);
}
return null;
}
return null;
}
/**
* 使用RSAPublicKey加密
*
* @author Xewee.Zhiwei.Wang
* @version 2011-10-6 下午06:31:48
* @param publicKey
* @param data
* @return
*/
private byte[] encrypt(RSAPublicKey publicKey, byte[] data) {
if (publicKey != null) {
try {
Cipher cipher = Cipher.getInstance("RSA");
// 返回实现指定转换的 Cipher 对象。
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
// 用密钥初始化此 Cipher,第一个参数表示加密
return cipher.doFinal(data);
// 按单部分操作加密或解密数据,或者结束一个多部分操作。数据将被加密或解密(具体取决于此 Cipher 的初始化方式)。
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
/**
* 使用RSAPrivateKey解密
*
* @author Xewee.Zhiwei.Wang
* @version 2011-10-6 下午06:32:18
* @param privateKey
* @param raw
* @return
*/
private byte[] decrypt(RSAPrivateKey privateKey, byte[] raw) {
if (privateKey != null) {
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey); // 第一个参数表示解密
return cipher.doFinal(raw);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
/**
* 将bytes转化成string,便于网络传送
* @author Xewee.Zhiwei.Wang
* @version 2011-10-6 下午07:46:58
* @param bytes
* @return
*/
private String byte2String(byte[] bytes) {
StringBuilder sb = new StringBuilder();
// 构造一个不带任何字符的字符串生成器,其初始容量由 capacity 参数指定。
for (int i = 0; i < bytes.length; i++) {
sb.append((char)(bytes[i] & 0xff));
}
return sb.toString();
}
/**
* 将string转化成bytes,从网络中获得数据
* @author Xewee.Zhiwei.Wang
* @version 2011-10-6 下午07:47:22
* @param string
* @return
*/
private byte[] string2Bytes(String string) {
int length = string.length();
byte[] bytes = new byte[length];
for (int i = 0; i < bytes.length; i++) {
byte b = new Byte((byte)(string.charAt(i) & 0xff));
bytes[i] = b;
}
return bytes;
}
/**
* @return the keyPair
*/
public KeyPair getKeyPair() {
return keyPair;
}
/**
* @param keyPair the keyPair to set
*/
public void setKeyPair(KeyPair keyPair) {
this.keyPair = keyPair;
}
}
|
92344fd3f643613a74f138b5338e4c6a53912695 | 858 | java | Java | src/common/SharedResource.java | misko321/producers-consumers-rmi | 9820b147e4763829b9ac867cb8fc5c861d61cec6 | [
"MIT"
] | 3 | 2017-12-20T13:36:08.000Z | 2021-06-20T19:30:13.000Z | src/common/SharedResource.java | misko321/producers-consumers-rmi | 9820b147e4763829b9ac867cb8fc5c861d61cec6 | [
"MIT"
] | null | null | null | src/common/SharedResource.java | misko321/producers-consumers-rmi | 9820b147e4763829b9ac867cb8fc5c861d61cec6 | [
"MIT"
] | 4 | 2017-12-20T13:35:56.000Z | 2020-12-29T16:20:39.000Z | 20.428571 | 104 | 0.600233 | 996,884 | package common;
import semaphore.*;
public class SharedResource {
private Semaphore cs, full, empty;
private int items = 0;
public SharedResource(int bufferSize) {
cs = new FairSemaphore();
full = new FairSemaphore(0);
empty = new UnfairSemaphore(bufferSize);
}
public void add(int count) {
empty.acquire(count);
cs.acquire();
cs(count);
cs.release();
full.release(count);
}
public void remove(int count) {
full.acquire(count);
cs.acquire();
cs(-count);
cs.release();
empty.release(count);
}
private void cs(int count) {
System.out.print("(TID=" + Thread.currentThread().getId() + "): " + items);
items += count;
System.out.println(" -> " + items + " (" + (count > 0 ? "ADD " : "REMOVE ") + Math.abs(count) +")");
}
public int getItems() {
return items;
}
}
|
92345076037e2630bf24514a8050d2e8f5114475 | 9,128 | java | Java | lib/src/main/java/com/fuwafuwa/mqtt/MQTTService.java | sunshengfei/workflow-corex | 0fab2e4a29cc2812d602df28b2c15bdfbe82bfc2 | [
"Apache-2.0"
] | null | null | null | lib/src/main/java/com/fuwafuwa/mqtt/MQTTService.java | sunshengfei/workflow-corex | 0fab2e4a29cc2812d602df28b2c15bdfbe82bfc2 | [
"Apache-2.0"
] | null | null | null | lib/src/main/java/com/fuwafuwa/mqtt/MQTTService.java | sunshengfei/workflow-corex | 0fab2e4a29cc2812d602df28b2c15bdfbe82bfc2 | [
"Apache-2.0"
] | null | null | null | 39.175966 | 143 | 0.590162 | 996,885 | package com.fuwafuwa.mqtt;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LifecycleRegistry;
import androidx.lifecycle.OnLifecycleEvent;
import com.annimon.stream.Collectors;
import com.annimon.stream.Stream;
import com.fuwafuwa.mqtt.bean.ConnectActionState;
import com.fuwafuwa.mqtt.bean.MQTTConnectUserEntity;
import com.fuwafuwa.mqtt.broker.EmqttdBroker;
import com.fuwafuwa.mqtt.broker.PahoMosquittoBroker;
import com.fuwafuwa.mqtt.event.MQTTStateEvent;
import com.fuwafuwa.za.ActionEventType;
import com.fuwafuwa.za.LiveDataBus;
import com.fuwafuwa.za.MQTTClientActionEvent;
import com.fuwafuwa.utils.Loger;
import com.fuwafuwa.workflow.plugins.mqtt.payload.MQTTMessage;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
public class MQTTService extends Service implements LifecycleOwner, LifecycleObserver {
public final static String CONN = "CON_MQTT_CF";
private List<MQTTMessage> cachedSubscriptionTopics;
private String cachedSubscriptionId;
private MQTTConnectUserEntity connectPoint;
private IMQTTBrokerDelegate mqttBrokerDelegate;
private LifecycleRegistry mLifecycleRegistry;
private final AtomicBoolean locker = new AtomicBoolean();
private boolean isTerminal;
public static void startService(Context context, MQTTConnectUserEntity point) {
Intent service = new Intent();
service.setClass(context, MQTTService.class);
service.putExtra(CONN, point);
context.startService(service);
}
public static void stopService(Context context) {
Intent service = new Intent();
service.setClass(context, MQTTService.class);
context.stopService(service);
}
private void $prepareActionHandler() {
LiveDataBus.subscribe(MQTTClientActionEvent.class, this, event -> {
ActionEventType type = event.getEventType();
Object payload = event.getPayload();
isTerminal = false;
switch (type) {
case connect:
mqttBrokerDelegate.connect();
break;
case disconnect:
mqttBrokerDelegate.disconnect();
break;
case publish:
if (payload instanceof MQTTMessage) {
mqttBrokerDelegate.publish((MQTTMessage) payload);
}
break;
case subscribe:
if (payload instanceof MQTTMessage) {
MQTTMessage subscription = (MQTTMessage) payload;
try {
mqttBrokerDelegate.subscribe(subscription);
}catch (Exception e){
LiveDataBus.post(MQTTStateEvent.class, new MQTTStateEvent(connectPoint.get_id(), ConnectActionState.DISCONNECTED));
}
if (cachedSubscriptionTopics == null) {
cachedSubscriptionTopics = new ArrayList<>();
}
Long count = Stream.of(cachedSubscriptionTopics)
.filter(item -> subscription.getTopic().equalsIgnoreCase(item.getTopic()))
.collect(Collectors.counting());
if (count > 0) {
return;
}
cachedSubscriptionTopics.add(subscription);
}
break;
case unsubscribe:
if (payload instanceof MQTTMessage) {
mqttBrokerDelegate.unsubscribe(((MQTTMessage) payload).getTopic());
}
break;
case unsubscribe_all:
if (payload == null) {
mqttBrokerDelegate.unsubscribeAll(null);
} else if (payload instanceof String[]) {
mqttBrokerDelegate.unsubscribeAll((String[]) payload);
}
break;
case terminal:
isTerminal = true;
case close:
mqttBrokerDelegate.disconnect();
mqttBrokerDelegate.onDestroy();
stopSelf();
break;
}
});
}
@Override
public void onDestroy() {
try {
if (mqttBrokerDelegate == null) return;
mqttBrokerDelegate.disconnect();
mqttBrokerDelegate.onDestroy();
} catch (Exception e) {
e.printStackTrace();
mqttBrokerDelegate = null;
} finally {
if (connectPoint != null) {
connectPoint.setConnected(ConnectActionState.DISCONNECTED);
if (!isTerminal)
LiveDataBus.post(MQTTStateEvent.class, new MQTTStateEvent(connectPoint.get_id(), connectPoint.getConnected()));
}
}
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
MQTTConnectUserEntity locConn = (MQTTConnectUserEntity) intent.getSerializableExtra(CONN);
if (locConn != null) {
if (connectPoint != null && connectPoint.get_id().equals(locConn.get_id())) {
if (mqttBrokerDelegate != null && !mqttBrokerDelegate.isConnected()) {
mqttBrokerDelegate.connect();
return super.onStartCommand(intent, flags, startId);
}
}
connectPoint = locConn;
if (!connectPoint.get_id().equals(cachedSubscriptionId)) {
cachedSubscriptionTopics = null;
}
cachedSubscriptionId = connectPoint.get_id();
synchronized (locker) {
locker.set(false);
$prepareActionHandler();
locker.set(true);
}
// String client = SPBase.builder(this).getString(SPKey.MQTT_CLIENT, "");
if ("Emqx".equals(connectPoint.getBrokerType())) {
mqttBrokerDelegate = new EmqttdBroker(this, connectPoint);
} else {
mqttBrokerDelegate = new PahoMosquittoBroker(this, connectPoint);
}
// connectPoint.setConnected(ConnectActionState.CONNECTING);
// LiveDataBus.post(MQTTStateEvent.class, new MQTTStateEvent(connectPoint.get_id(), connectPoint.getConnected()));
mqttBrokerDelegate.connect();
} else {
if (connectPoint != null) {
if (!connectPoint.get_id().equals(cachedSubscriptionId)) {
cachedSubscriptionTopics = null;
}
if (mqttBrokerDelegate != null && !mqttBrokerDelegate.isConnected()) {
mqttBrokerDelegate.connect();
}
}
}
}
return super.onStartCommand(intent, flags, startId);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
if (mLifecycleRegistry == null) {
mLifecycleRegistry = new LifecycleRegistry(this);
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
mLifecycleRegistry.addObserver(this);
}
// mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
return mLifecycleRegistry;
}
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onLiveCreate() {
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
Loger.d("LiveCycle-MQTTService", "onLiveCreate");
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onLiveResume() {
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
mqttBrokerDelegate.onResume();
Loger.d("LiveCycle-MQTTService", "onLiveResume");
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onLivPause() {
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
mqttBrokerDelegate.onPause();
Loger.d("LiveCycle-MQTTService", "onLivPause");
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onLiveDestroy() {
Loger.d("LiveCycle-MQTTService", "onLiveDestroy");
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
if (mLifecycleRegistry != null) {
mLifecycleRegistry.removeObserver(this);
}
}
}
|
923451202578094e2b48a23a350f48d9d34ec108 | 5,845 | java | Java | src/main/java/org/bian/dto/BQTechnicalSpecificationRetrieveOutputModel.java | bianapis/sd-system-development-v2 | f84358dfc10f6bf01f18bfe2d8e59da7de6e4268 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/bian/dto/BQTechnicalSpecificationRetrieveOutputModel.java | bianapis/sd-system-development-v2 | f84358dfc10f6bf01f18bfe2d8e59da7de6e4268 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/bian/dto/BQTechnicalSpecificationRetrieveOutputModel.java | bianapis/sd-system-development-v2 | f84358dfc10f6bf01f18bfe2d8e59da7de6e4268 | [
"Apache-2.0"
] | null | null | null | 43.947368 | 209 | 0.864842 | 996,886 | package org.bian.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.bian.dto.BQTechnicalSpecificationRetrieveOutputModelTechnicalSpecificationInstanceAnalysis;
import org.bian.dto.BQTechnicalSpecificationRetrieveOutputModelTechnicalSpecificationInstanceRecord;
import org.bian.dto.BQTechnicalSpecificationRetrieveOutputModelTechnicalSpecificationInstanceReport;
import org.bian.dto.CRITSystemDevelopmentProjectCreateInputModelITSystemDevelopmentProjectInstanceRecord;
import javax.validation.Valid;
/**
* BQTechnicalSpecificationRetrieveOutputModel
*/
public class BQTechnicalSpecificationRetrieveOutputModel {
private CRITSystemDevelopmentProjectCreateInputModelITSystemDevelopmentProjectInstanceRecord iTSystemDevelopmentProjectInstanceRecord = null;
private BQTechnicalSpecificationRetrieveOutputModelTechnicalSpecificationInstanceRecord technicalSpecificationInstanceRecord = null;
private String technicalSpecificationRetrieveActionTaskReference = null;
private Object technicalSpecificationRetrieveActionTaskRecord = null;
private String technicalSpecificationRetrieveActionResponse = null;
private BQTechnicalSpecificationRetrieveOutputModelTechnicalSpecificationInstanceReport technicalSpecificationInstanceReport = null;
private BQTechnicalSpecificationRetrieveOutputModelTechnicalSpecificationInstanceAnalysis technicalSpecificationInstanceAnalysis = null;
/**
* Get iTSystemDevelopmentProjectInstanceRecord
* @return iTSystemDevelopmentProjectInstanceRecord
**/
public CRITSystemDevelopmentProjectCreateInputModelITSystemDevelopmentProjectInstanceRecord getITSystemDevelopmentProjectInstanceRecord() {
return iTSystemDevelopmentProjectInstanceRecord;
}
@JsonProperty("iTSystemDevelopmentProjectInstanceRecord")
public void setITSystemDevelopmentProjectInstanceRecord(CRITSystemDevelopmentProjectCreateInputModelITSystemDevelopmentProjectInstanceRecord iTSystemDevelopmentProjectInstanceRecord) {
this.iTSystemDevelopmentProjectInstanceRecord = iTSystemDevelopmentProjectInstanceRecord;
}
/**
* Get technicalSpecificationInstanceRecord
* @return technicalSpecificationInstanceRecord
**/
public BQTechnicalSpecificationRetrieveOutputModelTechnicalSpecificationInstanceRecord getTechnicalSpecificationInstanceRecord() {
return technicalSpecificationInstanceRecord;
}
public void setTechnicalSpecificationInstanceRecord(BQTechnicalSpecificationRetrieveOutputModelTechnicalSpecificationInstanceRecord technicalSpecificationInstanceRecord) {
this.technicalSpecificationInstanceRecord = technicalSpecificationInstanceRecord;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to a Technical Specification instance retrieve service call
* @return technicalSpecificationRetrieveActionTaskReference
**/
public String getTechnicalSpecificationRetrieveActionTaskReference() {
return technicalSpecificationRetrieveActionTaskReference;
}
public void setTechnicalSpecificationRetrieveActionTaskReference(String technicalSpecificationRetrieveActionTaskReference) {
this.technicalSpecificationRetrieveActionTaskReference = technicalSpecificationRetrieveActionTaskReference;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The retrieve service call consolidated processing record
* @return technicalSpecificationRetrieveActionTaskRecord
**/
public Object getTechnicalSpecificationRetrieveActionTaskRecord() {
return technicalSpecificationRetrieveActionTaskRecord;
}
public void setTechnicalSpecificationRetrieveActionTaskRecord(Object technicalSpecificationRetrieveActionTaskRecord) {
this.technicalSpecificationRetrieveActionTaskRecord = technicalSpecificationRetrieveActionTaskRecord;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Details of the retrieve action service response (lists returned reports)
* @return technicalSpecificationRetrieveActionResponse
**/
public String getTechnicalSpecificationRetrieveActionResponse() {
return technicalSpecificationRetrieveActionResponse;
}
public void setTechnicalSpecificationRetrieveActionResponse(String technicalSpecificationRetrieveActionResponse) {
this.technicalSpecificationRetrieveActionResponse = technicalSpecificationRetrieveActionResponse;
}
/**
* Get technicalSpecificationInstanceReport
* @return technicalSpecificationInstanceReport
**/
public BQTechnicalSpecificationRetrieveOutputModelTechnicalSpecificationInstanceReport getTechnicalSpecificationInstanceReport() {
return technicalSpecificationInstanceReport;
}
public void setTechnicalSpecificationInstanceReport(BQTechnicalSpecificationRetrieveOutputModelTechnicalSpecificationInstanceReport technicalSpecificationInstanceReport) {
this.technicalSpecificationInstanceReport = technicalSpecificationInstanceReport;
}
/**
* Get technicalSpecificationInstanceAnalysis
* @return technicalSpecificationInstanceAnalysis
**/
public BQTechnicalSpecificationRetrieveOutputModelTechnicalSpecificationInstanceAnalysis getTechnicalSpecificationInstanceAnalysis() {
return technicalSpecificationInstanceAnalysis;
}
public void setTechnicalSpecificationInstanceAnalysis(BQTechnicalSpecificationRetrieveOutputModelTechnicalSpecificationInstanceAnalysis technicalSpecificationInstanceAnalysis) {
this.technicalSpecificationInstanceAnalysis = technicalSpecificationInstanceAnalysis;
}
}
|
92345127ccc34f4ced828f7ba420736b1d5e6a05 | 1,798 | java | Java | src/main/java/br/com/cmabreu/webomt/ieee1516e/UpdateEnumerations.java | icemagno/webomt | 7c41f44dee4d3eab3cc077804b451b2fcc0352f2 | [
"Apache-2.0"
] | 2 | 2016-04-04T08:05:13.000Z | 2018-11-20T06:45:17.000Z | src/main/java/br/com/cmabreu/webomt/ieee1516e/UpdateEnumerations.java | icemagno/webomt | 7c41f44dee4d3eab3cc077804b451b2fcc0352f2 | [
"Apache-2.0"
] | null | null | null | src/main/java/br/com/cmabreu/webomt/ieee1516e/UpdateEnumerations.java | icemagno/webomt | 7c41f44dee4d3eab3cc077804b451b2fcc0352f2 | [
"Apache-2.0"
] | null | null | null | 28.09375 | 110 | 0.637375 | 996,887 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.10.06 at 09:06:12 AM BRT
//
package br.com.cmabreu.webomt.ieee1516e;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for updateEnumerations.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="updateEnumerations">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="Static"/>
* <enumeration value="Periodic"/>
* <enumeration value="Conditional"/>
* <enumeration value="NA"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "updateEnumerations")
@XmlEnum
public enum UpdateEnumerations {
@XmlEnumValue("Static")
STATIC("Static"),
@XmlEnumValue("Periodic")
PERIODIC("Periodic"),
@XmlEnumValue("Conditional")
CONDITIONAL("Conditional"),
NA("NA");
private final java.lang.String value;
UpdateEnumerations(java.lang.String v) {
value = v;
}
public java.lang.String value() {
return value;
}
public static UpdateEnumerations fromValue(java.lang.String v) {
for (UpdateEnumerations c: UpdateEnumerations.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
|
9234517f4a1e4d87a5fc6a0ed1d188eb6eab71fc | 2,079 | java | Java | android/app/src/main/java/darren/com/example/flutterflowermusic/FlutterPluginBasicTest.java | ditclear/flutter_flowermusic | 7f5fbeefdbc0a395adddfe98b3a3717d28ca1979 | [
"MIT"
] | 3 | 2019-10-05T20:06:44.000Z | 2021-07-13T13:23:28.000Z | android/app/src/main/java/darren/com/example/flutterflowermusic/FlutterPluginBasicTest.java | sa0012/flutter_flowermusic | 401d4f399ffba3c4b15170e8841ce861d0474940 | [
"MIT"
] | null | null | null | android/app/src/main/java/darren/com/example/flutterflowermusic/FlutterPluginBasicTest.java | sa0012/flutter_flowermusic | 401d4f399ffba3c4b15170e8841ce861d0474940 | [
"MIT"
] | 1 | 2020-07-14T08:04:39.000Z | 2020-07-14T08:04:39.000Z | 36.473684 | 98 | 0.680135 | 996,888 | package darren.com.example.flutterflowermusic;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import org.json.JSONObject;
import io.flutter.plugin.common.BasicMessageChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.StandardMessageCodec;
public class FlutterPluginBasicTest implements MethodChannel.MethodCallHandler {
public String CHANNEL = "darren.com.example.flutterFlowermusic/mutual";
MethodChannel channel;
Context myContext;
public void registerWith(PluginRegistry.Registrar registrar, Context con) {
this.myContext = con;
channel = new MethodChannel(registrar.messenger(), CHANNEL);
channel.setMethodCallHandler(this);
}
@Override
public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
if (methodCall.method.equals("GoodComment")) {
Log.d("GoodComment", "GoodComment");
//返回给flutter的参数
result.success("success");
}
if (methodCall.method.equals("share")) {
Log.d("share", "share");
System.out.println(String.valueOf(methodCall.arguments));
String id = (String) methodCall.argument("_id");
System.out.println(id);
String url = "http://chenliang.yishouhaoge.cn/#/" + "chenliang/music/single?id=" + id;
Intent share_intent = new Intent();
share_intent.setAction(Intent.ACTION_SEND);//设置分享行为
share_intent.setType("text/plain");//设置分享内容的类型
share_intent.putExtra(Intent.EXTRA_SUBJECT, "this song is so nice");//添加分享内容标题
share_intent.putExtra(Intent.EXTRA_TEXT, url);//添加分享内容
//创建分享的Dialog
share_intent = Intent.createChooser(share_intent, "分享");
this.myContext.startActivity(share_intent);
//返回给flutter的参数
result.success("success");
}
}
}
|
9234540b09feb7c2cc8900f8ef9ab846cc546576 | 1,955 | java | Java | warp10/src/main/java/io/warp10/script/functions/GET.java | CleverCloud/warp10-platform | 28e2b411ca069afe6d29d6d14a855987ef78b866 | [
"Apache-2.0"
] | null | null | null | warp10/src/main/java/io/warp10/script/functions/GET.java | CleverCloud/warp10-platform | 28e2b411ca069afe6d29d6d14a855987ef78b866 | [
"Apache-2.0"
] | null | null | null | warp10/src/main/java/io/warp10/script/functions/GET.java | CleverCloud/warp10-platform | 28e2b411ca069afe6d29d6d14a855987ef78b866 | [
"Apache-2.0"
] | null | null | null | 29.621212 | 113 | 0.667008 | 996,889 | //
// Copyright 2018 SenX S.A.S.
//
// 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.warp10.script.functions;
import io.warp10.script.NamedWarpScriptFunction;
import io.warp10.script.WarpScriptStackFunction;
import io.warp10.script.WarpScriptException;
import io.warp10.script.WarpScriptStack;
import java.util.List;
import java.util.Map;
/**
* Extracts a value from a map or list given a key.
*/
public class GET extends NamedWarpScriptFunction implements WarpScriptStackFunction {
public GET(String name) {
super(name);
}
@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {
Object key = stack.pop();
Object coll = stack.pop();
if (!(coll instanceof Map) && !(coll instanceof List) && !(coll instanceof byte[])) {
throw new WarpScriptException(getName() + " operates on a map, list or byte array.");
}
Object value = null;
if (coll instanceof Map) {
value = ((Map) coll).get(key);
} else {
if (!(key instanceof Number)) {
throw new WarpScriptException(getName() + " expects the key to be an integer when operating on a list.");
}
if (coll instanceof List) {
value = ((List) coll).get(((Number) key).intValue());
} else {
value = (long) (((byte[]) coll)[((Number) key).intValue()] & 0xFFL);
}
}
stack.push(value);
return stack;
}
}
|
923454bc84e834329fbb7a2a7763c1b545273d7b | 1,733 | java | Java | commons/util/src/main/java/net/automatalib/commons/util/collections/UnmodifiableListIterator.java | BenjaminAndre/automatalib | 168b86f1ff6e9211ed95687ac3796cec9b3245b0 | [
"Apache-2.0"
] | 54 | 2017-02-20T03:29:40.000Z | 2022-03-24T00:38:54.000Z | commons/util/src/main/java/net/automatalib/commons/util/collections/UnmodifiableListIterator.java | BenjaminAndre/automatalib | 168b86f1ff6e9211ed95687ac3796cec9b3245b0 | [
"Apache-2.0"
] | 27 | 2017-08-24T13:19:19.000Z | 2022-02-05T19:29:42.000Z | commons/util/src/main/java/net/automatalib/commons/util/collections/UnmodifiableListIterator.java | BenjaminAndre/automatalib | 168b86f1ff6e9211ed95687ac3796cec9b3245b0 | [
"Apache-2.0"
] | 32 | 2016-12-31T21:49:09.000Z | 2022-03-08T03:30:01.000Z | 29.372881 | 117 | 0.709175 | 996,890 | /* Copyright (C) 2013-2021 TU Dortmund
* This file is part of AutomataLib, http://www.automatalib.net/.
*
* 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 net.automatalib.commons.util.collections;
import java.util.ListIterator;
import com.google.common.collect.ForwardingListIterator;
/**
* Wraps a given {@link ListIterator} so that any mutating operations throw an {@link UnsupportedOperationException}.
*
* @param <T>
* type of elements in the given iterator
*
* @author frohme
*/
public class UnmodifiableListIterator<T> extends ForwardingListIterator<T> {
private final ListIterator<? extends T> delegate;
public UnmodifiableListIterator(ListIterator<? extends T> delegate) {
this.delegate = delegate;
}
@Override
@SuppressWarnings("unchecked")
protected ListIterator<T> delegate() {
return (ListIterator<T>) this.delegate;
}
@Override
public final void remove() {
throw new UnsupportedOperationException();
}
@Override
public final void set(T t) {
throw new UnsupportedOperationException();
}
@Override
public final void add(T t) {
throw new UnsupportedOperationException();
}
}
|
923454bf48204b4dfdee5b497a2c827f059494e4 | 9,191 | java | Java | kaleido-appengine/src/main/java/org/kaleidofoundry/core/store/GaeFileStore.java | jraduget/kaleido-repository | 19b0b931874fa76cf69fb36d70596760ebd506e7 | [
"Apache-2.0"
] | null | null | null | kaleido-appengine/src/main/java/org/kaleidofoundry/core/store/GaeFileStore.java | jraduget/kaleido-repository | 19b0b931874fa76cf69fb36d70596760ebd506e7 | [
"Apache-2.0"
] | 12 | 2021-05-10T09:05:24.000Z | 2022-02-09T23:00:58.000Z | kaleido-appengine/src/main/java/org/kaleidofoundry/core/store/GaeFileStore.java | jraduget/kaleido-repository | 19b0b931874fa76cf69fb36d70596760ebd506e7 | [
"Apache-2.0"
] | 1 | 2019-05-08T06:01:25.000Z | 2019-05-08T06:01:25.000Z | 37.210526 | 157 | 0.754978 | 996,891 | /*
* Copyright 2008-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.kaleidofoundry.core.store;
import static org.kaleidofoundry.core.store.FileStoreConstants.DEFAULT_BUFFER_SIZE;
import static org.kaleidofoundry.core.store.FileStoreConstants.DEFAULT_CHARSET;
import static org.kaleidofoundry.core.store.FileStoreContextBuilder.BufferSize;
import static org.kaleidofoundry.core.store.FileStoreContextBuilder.Charset;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import org.kaleidofoundry.core.context.RuntimeContext;
import org.kaleidofoundry.core.io.FileHelper;
import org.kaleidofoundry.core.io.MimeTypeResolver;
import org.kaleidofoundry.core.io.MimeTypeResolverFactory;
import org.kaleidofoundry.core.lang.annotation.NotYetImplemented;
import org.kaleidofoundry.core.util.StringHelper;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileReadChannel;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
import com.google.appengine.api.files.GSFileOptions.GSFileOptionsBuilder;
/**
* Google application file store service
* <br/>
* <b>References</b>
* <ul>
* <li>https://developers.google.com/appengine/docs/java/javadoc/com/google/appengine/api/files/FileService</li>
* <li>https://developers.google.com/storage/docs/hellogooglestorage/li>
* <li>https://developers.google.com/appengine/docs/java/javadoc/com/google/appengine/api/files/AppEngineFile/li>
* <li>https://developers.google.com/appengine/docs/java/javadoc/com/google/appengine/api/files/AppEngineFile.FileSystem/li>
* </ul>
* @author jraduget
*/
public class GaeFileStore extends AbstractFileStore {
protected final FileService fileService = FileServiceFactory.getFileService();
/**
* @param context
*/
public GaeFileStore(final RuntimeContext<FileStore> context) {
super(context);
}
/**
* @param baseUri
* @param context
*/
public GaeFileStore(final String baseUri, final RuntimeContext<FileStore> context) {
super(baseUri, context);
}
/*
* (non-Javadoc)
* @see org.kaleidofoundry.core.store.AbstractFileStore#getStoreType()
*/
@Override
public FileStoreType[] getStoreType() {
return new FileStoreType[] { FileStoreTypeEnum.gs };
}
/*
* (non-Javadoc)
* @see org.kaleidofoundry.core.store.AbstractFileStore#doGet(java.net.URI)
*/
@Override
protected ResourceHandler doGet(final URI resourceUri) throws ResourceNotFoundException, ResourceException {
FileReadChannel readChannel = null;
ResourceHandler resource;
MimeTypeResolver mimeTypeResolver = MimeTypeResolverFactory.getService();
try {
final String filepath = "/gs" + resourceUri.getPath();
final AppEngineFile readableFile = new AppEngineFile(filepath);
final String mimeType = mimeTypeResolver.getMimeType(FileHelper.getFileNameExtension(resourceUri.getPath()));
final String charset = context.getString(Charset, DEFAULT_CHARSET.getCode());
final int bufferSize = context.getInteger(BufferSize, DEFAULT_BUFFER_SIZE);
readChannel = fileService.openReadChannel(readableFile, false);
LOGGER.debug("gs filepath={}", filepath);
if (mimeTypeResolver.isText(mimeType)) {
LOGGER.debug("gs content type isText={}", true);
//resource = createResourceHandler(resourceUri.toString(), readChannel, Channels.newReader(readChannel, charset), charset);
resource = createResourceHandler(resourceUri.toString(), readChannel, new BufferedReader(Channels.newReader(readChannel, charset), bufferSize), charset);
} else {
LOGGER.debug("gs content type isText={}", false);
//resource = createResourceHandler(resourceUri.toString(), readChannel, Channels.newInputStream(readChannel));
resource = createResourceHandler(resourceUri.toString(), readChannel, new BufferedInputStream(Channels.newInputStream(readChannel), bufferSize));
}
// Set some meta datas
if (resource instanceof ResourceHandlerBean) {
// ((ResourceHandlerBean) resource).setLastModified(file.lastModified());
((ResourceHandlerBean) resource).setMimeType(mimeType);
}
return resource;
} catch (final FileNotFoundException fnfe) {
throw new ResourceNotFoundException(resourceUri.toString());
} catch (final IOException ioe) {
throw new ResourceException(resourceUri.toString(), ioe);
}
}
/*
* (non-Javadoc)
* @see org.kaleidofoundry.core.store.AbstractFileStore#doRemove(java.net.URI)
*/
@Override
@NotYetImplemented
protected void doRemove(final URI resourceUri) throws ResourceNotFoundException, ResourceException {
final String filepath = "/gs" + resourceUri.getPath();
final AppEngineFile readableFile = new AppEngineFile(filepath);
try {
fileService.delete(readableFile);
} catch (FileNotFoundException fnfe) {
throw new ResourceNotFoundException(resourceUri.toString());
} catch (IOException ioe) {
throw new ResourceException(ioe, resourceUri.toString());
}
}
/*
* (non-Javadoc)
* @see org.kaleidofoundry.core.store.AbstractFileStore#doStore(java.net.URI, org.kaleidofoundry.core.store.ResourceHandler)
*/
@Override
protected void doStore(final URI resourceUri, final ResourceHandler resource) throws ResourceException {
String bucketName = getBucketName();
String charset = context.getString(Charset, DEFAULT_CHARSET.getCode());
boolean isTextContent = false;
MimeTypeResolver mimeTypeResolver = MimeTypeResolverFactory.getService();
GSFileOptionsBuilder optionsBuilder = new GSFileOptionsBuilder().setBucket(bucketName).setKey(resource.getUri());
if (!StringHelper.isEmpty(resource.getMimeType())) {
optionsBuilder.setMimeType(resource.getMimeType());
isTextContent = mimeTypeResolver.isText(resource.getMimeType());
}
// optionsBuilder.setAcl("public_read");
if (isTextContent) {
optionsBuilder.setContentEncoding(charset);
}
final AppEngineFile writableFile;
FileWriteChannel writeChannel = null;
try {
writableFile = fileService.createNewGSFile(optionsBuilder.build());
writeChannel = fileService.openWriteChannel(writableFile, true);
if (isTextContent) {
final char[] cbuff = new char[context.getInteger(BufferSize, DEFAULT_BUFFER_SIZE)];
int lengthToWrite = resource.getReader(charset).read(cbuff);
PrintWriter out = new PrintWriter(Channels.newWriter(writeChannel, charset));
while (lengthToWrite != -1) {
out.write(cbuff, 0, lengthToWrite);
lengthToWrite = resource.getReader(charset).read(cbuff);
}
out.close();
} else {
final byte[] buff = new byte[context.getInteger(BufferSize, DEFAULT_BUFFER_SIZE)];
int lengthToWrite = resource.getInputStream().read(buff);
while (lengthToWrite != -1) {
writeChannel.write(ByteBuffer.wrap(buff, 0, lengthToWrite));
lengthToWrite = resource.getInputStream().read(buff);
}
}
} catch (final IOException ioe) {
throw new ResourceException(ioe, resourceUri.toString());
} finally {
if (writeChannel != null) {
try {
writeChannel.closeFinally();
} catch (final IOException ioe) {
throw new ResourceException(ioe, resourceUri.toString());
}
}
}
}
public ResourceHandler createResourceHandler(final String resourceUri, final FileReadChannel fileReadChannel, final Reader reader, final String charset) {
ResourceHandler resource = new GaeResourceHandlerBean(this, resourceUri, fileReadChannel, reader, charset);
openedResources.put(resourceUri, resource);
return resource;
}
public ResourceHandler createResourceHandler(final String resourceUri, final FileReadChannel fileReadChannel, final InputStream input) {
ResourceHandler resource = new GaeResourceHandlerBean(this, resourceUri, fileReadChannel, input);
openedResources.put(resourceUri, resource);
return resource;
}
/**
* @return gs bucket name of the resource store (it is extracted from the resource store base dir
*/
protected String getBucketName() {
String bucketName = getBaseUri();
for (FileStoreType type : getStoreType()) {
if (bucketName.startsWith(type.name())) {
bucketName = bucketName.replace(type.name(), "");
break;
}
}
bucketName = bucketName.replaceFirst(":/", "");
bucketName = bucketName.replaceFirst("://", "");
return bucketName;
}
}
|
9234553d449b4d03ed20ca40ed9aa2f95579b27d | 969 | java | Java | src/main/java/com/clavardage/core/database/queries/selects/ConversationsSelectQuery.java | gab48/Clavardage | 166604b34e536a89caccdc7c7c235af8713bf429 | [
"MIT"
] | null | null | null | src/main/java/com/clavardage/core/database/queries/selects/ConversationsSelectQuery.java | gab48/Clavardage | 166604b34e536a89caccdc7c7c235af8713bf429 | [
"MIT"
] | null | null | null | src/main/java/com/clavardage/core/database/queries/selects/ConversationsSelectQuery.java | gab48/Clavardage | 166604b34e536a89caccdc7c7c235af8713bf429 | [
"MIT"
] | null | null | null | 32.3 | 95 | 0.673891 | 996,892 | package com.clavardage.core.database.queries.selects;
import com.clavardage.core.database.queries.QueryParameters;
import java.sql.SQLException;
import java.util.ArrayList;
public class ConversationsSelectQuery extends SelectQuery {
private static final String QUERY = "SELECT room_id FROM chat_participant WHERE user_id=?";
private static final int NUMBER_OF_ARGUMENTS = 1;
public ConversationsSelectQuery() {
super(QUERY);
}
@Override
public void setParameters(QueryParameters parameters) {
ArrayList<Object> parametersList = parameters.getParam();
if (parametersList.size() != NUMBER_OF_ARGUMENTS) {
System.err.println(NUMBER_OF_ARGUMENTS + " arguments needed");
} else {
try {
this.statement.setString(1, (String) parametersList.get(0));
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
|
923455bc4ffe103f61281611a2568036817c59de | 6,715 | java | Java | src/main/java/codes/biscuit/skyblockaddons/misc/Updater.java | TimoLob/SkyblockAddons | cf4930c75762e1f36948c0633d56c86a92f4d50c | [
"MIT"
] | 1 | 2019-11-02T05:24:36.000Z | 2019-11-02T05:24:36.000Z | src/main/java/codes/biscuit/skyblockaddons/misc/Updater.java | TimoLob/SkyblockAddons | cf4930c75762e1f36948c0633d56c86a92f4d50c | [
"MIT"
] | null | null | null | src/main/java/codes/biscuit/skyblockaddons/misc/Updater.java | TimoLob/SkyblockAddons | cf4930c75762e1f36948c0633d56c86a92f4d50c | [
"MIT"
] | null | null | null | 50.11194 | 173 | 0.676694 | 996,893 | package codes.biscuit.skyblockaddons.misc;
import codes.biscuit.skyblockaddons.SkyblockAddons;
import codes.biscuit.skyblockaddons.core.Message;
import lombok.Getter;
import net.minecraft.event.ClickEvent;
import net.minecraft.event.HoverEvent;
import net.minecraft.util.ChatComponentText;
import net.minecraftforge.common.ForgeVersion;
import net.minecraftforge.fml.common.versioning.ComparableVersion;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static net.minecraftforge.common.ForgeVersion.Status.*;
/**
* This class is the SkyblockAddons updater. It reads the Forge Update Checker results for SkyblockAddons.
*/
public class Updater {
private static final Pattern VERSION_PATTERN = Pattern.compile("(?<major>[0-9])\\.(?<minor>[0-9])\\.(?<patch>[0-9]).*");
private SkyblockAddons main = SkyblockAddons.getInstance();
private boolean hasUpdate = false;
@Getter private String messageToRender;
private boolean isPatch = false;
private boolean sentUpdateMessage = false;
/**
* Returns whether there is an update available
*
* @return {@code true} if there is an update available, false otherwise.
*/
public boolean hasUpdate() {
return hasUpdate;
}
/**
* Processes the update checker result from the Forge Update Checker and sets the correct message to be displayed.
*/
public void processUpdateCheckResult() {
SkyblockAddons main = SkyblockAddons.getInstance();
ComparableVersion current = new ComparableVersion(SkyblockAddons.VERSION);
boolean isCurrentBeta = SkyblockAddons.VERSION.contains("b");
ComparableVersion latest = new ComparableVersion(isCurrentBeta ? main.getOnlineData().getLatestBeta() : main.getOnlineData().getLatestVersion());
main.getLogger().info("Checking to see if an update is available. Current version is "+current.toString()+". Latest version is "+latest.toString());
ForgeVersion.Status status;
int versionDifference = latest.compareTo(current);
if (versionDifference == 0) {
status = UP_TO_DATE;
} else if (versionDifference < 0) {
status = AHEAD;
} else {
status = OUTDATED;
}
if (status == ForgeVersion.Status.OUTDATED) {
hasUpdate = true;
String currentVersion = current.toString();
String latestVersion = latest.toString();
main.getLogger().info("Found an update: "+latestVersion);
try {
Matcher currentMatcher = VERSION_PATTERN.matcher(currentVersion);
Matcher latestMatcher = VERSION_PATTERN.matcher(latestVersion);
// Its a patch if the major & minor numbers are the same & the player isn't upgrading out of a beta.
if (currentMatcher.matches() && latestMatcher.matches() &&
currentMatcher.group("major").equals(latestMatcher.group("major")) &&
currentMatcher.group("minor").equals(latestMatcher.group("minor")) &&
!(currentVersion.contains("beta") && !latestVersion.contains("beta"))) {
isPatch = true;
}
} catch (Exception ex) {
ex.printStackTrace();
main.getLogger().warn("Couldn't parse update version numbers... This shouldn't affect too much.");
}
if (isPatch) {
messageToRender = Message.UPDATE_MESSAGE_PATCH.getMessage(latestVersion);
} else {
messageToRender = Message.UPDATE_MESSAGE_MAJOR.getMessage(latestVersion);
}
}
}
public void sendUpdateMessage() {
if (sentUpdateMessage) return;
if (main.getOnlineData().getVideoLink() == null) return;
String newestVersion = main.getOnlineData().getLatestVersion();
if (newestVersion == null) return;
sentUpdateMessage = true;
main.getUtils().sendMessage("§7§m------------§7[§b§l SkyblockAddons §7]§7§m------------", false);
ChatComponentText newUpdate = new ChatComponentText("§b" + Message.MESSAGE_NEW_UPDATE.getMessage(newestVersion) + "\n");
main.getUtils().sendMessage(newUpdate, false);
ChatComponentText buttonsMessage = new ChatComponentText("§b§l[" + Message.MESSAGE_DOWNLOAD_LINK.getMessage(newestVersion) + "]");
buttonsMessage.setChatStyle(buttonsMessage.getChatStyle().setChatClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, main.getOnlineData().getVideoLink()))
.setChatHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ChatComponentText("§7" +Message.MESSAGE_CLICK_TO_OPEN_LINK.getMessage()))));
buttonsMessage.appendSibling(new ChatComponentText(" "));
if (isPatch && main.getOnlineData().getDirectDownload() != null) {
ChatComponentText openModsFolder = new ChatComponentText("§c§l[" + Message.MESSAGE_DIRECT_DOWNLOAD.getMessage(newestVersion) + "]");
openModsFolder.setChatStyle(openModsFolder.getChatStyle().setChatClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, main.getOnlineData().getDirectDownload()))
.setChatHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ChatComponentText("§7" +Message.MESSAGE_CLICK_TO_OPEN_LINK.getMessage()))));
openModsFolder.appendSibling(new ChatComponentText(" "));
buttonsMessage.appendSibling(openModsFolder);
}
ChatComponentText openModsFolder = new ChatComponentText("§e§l[" + Message.MESSAGE_OPEN_MODS_FOLDER.getMessage(newestVersion) + "]");
openModsFolder.setChatStyle(openModsFolder.getChatStyle().setChatClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/sba folder"))
.setChatHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ChatComponentText("§7" +Message.MESSAGE_CLICK_TO_OPEN_FOLDER.getMessage()))));
buttonsMessage.appendSibling(openModsFolder);
main.getUtils().sendMessage(buttonsMessage, false);
ChatComponentText discord = new ChatComponentText("§b" + Message.MESSAGE_VIEW_PATCH_NOTES.getMessage() + " §9§l[" + Message.MESSAGE_JOIN_DISCORD.getMessage() + "]");
discord.setChatStyle(discord.getChatStyle().setChatClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://discord.gg/PqTAEek"))
.setChatHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ChatComponentText("§7" +Message.MESSAGE_CLICK_TO_OPEN_LINK.getMessage()))));
main.getUtils().sendMessage(discord, false);
main.getUtils().sendMessage("§7§m----------------------------------------------", false);
}
}
|
923458b5125763774ddd34cab90eb3af530e9def | 9,013 | java | Java | super-csv-benchmark/src/test/java/org/supercsv/benchmark/AbstractCsvWritingBenchmark.java | sharpTrick/super-csv | f18db724674dc1c4116e25142c1b5403ebf43e96 | [
"Apache-2.0"
] | 1 | 2017-01-11T22:11:39.000Z | 2017-01-11T22:11:39.000Z | super-csv-benchmark/src/test/java/org/supercsv/benchmark/AbstractCsvWritingBenchmark.java | sharpTrick/super-csv | f18db724674dc1c4116e25142c1b5403ebf43e96 | [
"Apache-2.0"
] | 1 | 2022-01-21T23:45:28.000Z | 2022-01-21T23:45:28.000Z | super-csv-benchmark/src/test/java/org/supercsv/benchmark/AbstractCsvWritingBenchmark.java | sharpTrick/super-csv | f18db724674dc1c4116e25142c1b5403ebf43e96 | [
"Apache-2.0"
] | 1 | 2018-12-07T04:30:50.000Z | 2018-12-07T04:30:50.000Z | 25.605114 | 77 | 0.662598 | 996,894 | /*
* Copyright 2007 Kasper B. Graversen
*
* 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.supercsv.benchmark;
import static org.junit.Assert.assertEquals;
import java.io.Writer;
import java.util.List;
import java.util.Map;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.CsvBeanWriter;
import org.supercsv.io.CsvListWriter;
import org.supercsv.io.CsvMapWriter;
import org.supercsv.io.ICsvBeanWriter;
import org.supercsv.io.ICsvListWriter;
import org.supercsv.io.ICsvMapWriter;
import org.supercsv.io.dozer.CsvDozerBeanWriter;
import org.supercsv.io.dozer.ICsvDozerBeanWriter;
import org.supercsv.prefs.CsvPreference;
import com.carrotsearch.junitbenchmarks.AbstractBenchmark;
/**
* Provides methods to benchmark all of Super CSV's writers.
* <p>
* The benchmarks use JUnitBenchmarks
* (http://labs.carrotsearch.com/junit-benchmarks-tutorial.html). As shown on
* the website, you can generate a Google charts graph from the results.
* <p>
* No assertions were required to prevent code being optimized away, but they
* were added to ensure the correct number of rows were written.
*
* @author James Bassett
*/
public class AbstractCsvWritingBenchmark extends AbstractBenchmark {
/**
* Times CsvListWriter.
*
* @param writer
* the writer
* @param preference
* the preferences
* @param header
* the header
* @param data
* the data to write
* @param rows
* the expected number of rows
* @throws Exception
*/
public void timeCsvListWriter(final Writer writer,
final CsvPreference preference, final String[] header,
final List<List<Object>> data, final int rows) throws Exception {
ICsvListWriter listWriter = null;
try {
listWriter = new CsvListWriter(writer, preference);
listWriter.writeHeader(header);
for (List<?> row : data) {
listWriter.write(row);
}
assertEquals(rows + 1, listWriter.getRowNumber());
} finally {
listWriter.close();
}
}
/**
* Times CsvListWriter using processors.
*
* @param writer
* the writer
* @param preference
* the preferences
* @param header
* the header
* @param data
* the data to write
* @param processors
* the cell processors
* @param rows
* the expected number of rows
* @throws Exception
*/
public void timeCsvListWriterUsingProcessors(final Writer writer,
final CsvPreference preference, final String[] header,
final List<List<Object>> data, final CellProcessor[] processors,
final int rows) throws Exception {
ICsvListWriter listWriter = null;
try {
listWriter = new CsvListWriter(writer, preference);
listWriter.writeHeader(header);
for (List<?> row : data) {
listWriter.write(row, processors);
}
assertEquals(rows + 1, listWriter.getRowNumber());
} finally {
listWriter.close();
}
}
/**
* Times CsvMapWriter.
*
* @param writer
* the writer
* @param preference
* the preferences
* @param header
* the header
* @param data
* the data to write
* @param rows
* the expected number of rows
* @throws Exception
*/
public void timeCsvMapWriter(final Writer writer,
final CsvPreference preference, final String[] header,
final List<Map<String, Object>> data, final int rows)
throws Exception {
ICsvMapWriter mapWriter = null;
try {
mapWriter = new CsvMapWriter(writer, preference);
mapWriter.writeHeader(header);
for (Map<String, ?> map : data) {
mapWriter.write(map, header);
}
assertEquals(rows + 1, mapWriter.getRowNumber());
} finally {
mapWriter.close();
}
}
/**
* Times CsvMapWriter using processors.
*
* @param writer
* the writer
* @param preference
* the preferences
* @param header
* the header
* @param data
* the data to write
* @param processors
* the cell processors
* @param rows
* the expected number of rows
* @throws Exception
*/
public void timeCsvMapWriterUsingProcessors(final Writer writer,
final CsvPreference preference, final String[] header,
final List<Map<String, Object>> data,
final CellProcessor[] processors, final int rows) throws Exception {
ICsvMapWriter mapWriter = null;
try {
mapWriter = new CsvMapWriter(writer, preference);
mapWriter.writeHeader(header);
for (Map<String, ?> map : data) {
mapWriter.write(map, header, processors);
}
assertEquals(rows + 1, mapWriter.getRowNumber());
} finally {
mapWriter.close();
}
}
/**
* Times CsvBeanWriter.
*
* @param writer
* the writer
* @param preference
* the preferences
* @param header
* the header
* @param data
* the data to write
* @param rows
* the expected number of rows
* @throws Exception
*/
public void timeCsvBeanWriter(final Writer writer,
final CsvPreference preference, final String[] header,
final List<?> data, final int rows) throws Exception {
ICsvBeanWriter beanWriter = null;
try {
beanWriter = new CsvBeanWriter(writer, preference);
beanWriter.writeHeader(header);
for (Object o : data) {
beanWriter.write(o, header);
}
assertEquals(rows + 1, beanWriter.getRowNumber());
} finally {
beanWriter.close();
}
}
/**
* Times CsvBeanWriter using processors.
*
* @param writer
* the writer
* @param preference
* the preferences
* @param header
* the header
* @param data
* the data to write
* @param processors
* the cell processors
* @param rows
* the expected number of rows
* @throws Exception
*/
public void timeCsvBeanWriterUsingProcessors(final Writer writer,
final CsvPreference preference, final String[] header,
final List<?> data, final CellProcessor[] processors, final int rows)
throws Exception {
ICsvBeanWriter beanWriter = null;
try {
beanWriter = new CsvBeanWriter(writer, preference);
beanWriter.writeHeader(header);
for (Object o : data) {
beanWriter.write(o, header, processors);
}
assertEquals(rows + 1, beanWriter.getRowNumber());
} finally {
beanWriter.close();
}
}
/**
* Times CsvDozerBeanWriter.
*
* @param writer
* the writer
* @param preference
* the preferences
* @param header
* the header
* @param beanClass
* the type of the bean being written
* @param data
* the data to write
* @param rows
* the expected number of rows
* @throws Exception
*/
public void timeCsvDozerBeanWriter(final Writer writer,
final CsvPreference preference, final String[] header,
final Class<?> beanClass, final List<?> data, final int rows)
throws Exception {
ICsvDozerBeanWriter dozerBeanWriter = null;
try {
dozerBeanWriter = new CsvDozerBeanWriter(writer, preference);
dozerBeanWriter.writeHeader(header);
dozerBeanWriter.configureBeanMapping(beanClass, header);
for (Object o : data) {
dozerBeanWriter.write(o);
}
assertEquals(rows + 1, dozerBeanWriter.getRowNumber());
} finally {
dozerBeanWriter.close();
}
}
/**
* Times CsvDozerBeanWriter using processors.
*
* @param writer
* the writer
* @param preference
* the preferences
* @param header
* the header
* @param beanClass
* the type of the bean being written
* @param data
* the data to write
* @param processors
* the cell processors
* @param rows
* the expected number of rows
* @throws Exception
*/
public void timeCsvDozerBeanWriterUsingProcessors(final Writer writer,
final CsvPreference preference, final String[] header,
final Class<?> beanClass, final List<?> data,
final CellProcessor[] processors, final int rows) throws Exception {
ICsvDozerBeanWriter dozerBeanWriter = null;
try {
dozerBeanWriter = new CsvDozerBeanWriter(writer, preference);
dozerBeanWriter.writeHeader(header);
dozerBeanWriter.configureBeanMapping(beanClass, header);
for (Object o : data) {
dozerBeanWriter.write(o, processors);
}
assertEquals(rows + 1, dozerBeanWriter.getRowNumber());
} finally {
dozerBeanWriter.close();
}
}
}
|
923458c21fba908274a18a56b1c1f7ffe08e1b30 | 305 | java | Java | src/main/java/com/macro/mall/tiny/modules/test/service/TestUserService.java | ershugong/spring-boot-cli | 904347134f2ec4a78d9721b34c737d8f9daed76e | [
"Apache-2.0"
] | null | null | null | src/main/java/com/macro/mall/tiny/modules/test/service/TestUserService.java | ershugong/spring-boot-cli | 904347134f2ec4a78d9721b34c737d8f9daed76e | [
"Apache-2.0"
] | null | null | null | src/main/java/com/macro/mall/tiny/modules/test/service/TestUserService.java | ershugong/spring-boot-cli | 904347134f2ec4a78d9721b34c737d8f9daed76e | [
"Apache-2.0"
] | null | null | null | 17.941176 | 61 | 0.72459 | 996,895 | package com.macro.mall.tiny.modules.test.service;
import com.macro.mall.tiny.modules.test.model.TestUser;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 服务类
* </p>
*
* @author macro
* @since 2021-05-13
*/
public interface TestUserService extends IService<TestUser> {
}
|
923459373016d7052cac032b0f3042c0ebf779aa | 1,942 | java | Java | src/main/java/ee/joonasvali/scene/Light.java | wrapperband/mirrors | 52905de799c5c741850fc84362dae7ea863b6ee2 | [
"Apache-2.0"
] | null | null | null | src/main/java/ee/joonasvali/scene/Light.java | wrapperband/mirrors | 52905de799c5c741850fc84362dae7ea863b6ee2 | [
"Apache-2.0"
] | null | null | null | src/main/java/ee/joonasvali/scene/Light.java | wrapperband/mirrors | 52905de799c5c741850fc84362dae7ea863b6ee2 | [
"Apache-2.0"
] | null | null | null | 23.682927 | 141 | 0.633883 | 996,896 | package ee.joonasvali.scene;
import org.newdawn.slick.Color;
import org.newdawn.slick.Graphics;
public class Light extends BasePhysical implements Activatable {
private double angle;
private double speed;
private double itensity;
private final double initialItensity;
private final double rate;
private Itensity0Action action;
private static Color[] colors = new Color[256];
static {
for (int i = 0; i < colors.length; i++) {
colors[i] = new Color(255,255,255,i);
}
}
public Light(double x, double y, double angle, double speed, double itensity, double itensityReductionRate, Itensity0Action onItensity0) {
super(x, y, 0, 1, 1);
this.itensity = itensity;
this.initialItensity = itensity;
this.rate = itensityReductionRate;
this.angle = angle;
this.speed = speed;
this.action = onItensity0;
}
@Override
public void render(Graphics g) {
int rate = (int) (itensity / initialItensity * 255);
g.setColor(colors[rate]);
g.drawRect((int)getX(), (int)getY(), 1, 1);
}
@Override
public void activate() {
double xVector = speed * Math.cos(Math.toRadians(angle));
double yVector = speed * Math.sin(Math.toRadians(angle));
x += xVector;
y += yVector;
itensity -= rate;
if(itensity <= 0) action.onItensity0(this);
}
public double getItensity() {
return itensity;
}
public void reduceItensity(double amount){
this.itensity = Math.max(this.itensity - amount, 0);
if(itensity <= 0) action.onItensity0(this);
}
public double getAngle() {
return angle;
}
public void setAngle(double angle) {
this.angle = angle;
}
public double getSpeed() {
return speed;
}
public void setSpeed(double speed) {
this.speed = speed;
if(this.speed < 0) { this.speed = 0;
action.onItensity0(this);
}
}
}
|
92345acab8abaaf365aa9b4efdc8db8bec7859ee | 2,879 | java | Java | src/main/java/com/thinkgem/jeesite/modules/path/web/PropertyController.java | ylz3468592/jeesite-master | 4923546d62a58cddbc846802766921c0d52e9545 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/thinkgem/jeesite/modules/path/web/PropertyController.java | ylz3468592/jeesite-master | 4923546d62a58cddbc846802766921c0d52e9545 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/thinkgem/jeesite/modules/path/web/PropertyController.java | ylz3468592/jeesite-master | 4923546d62a58cddbc846802766921c0d52e9545 | [
"Apache-2.0"
] | null | null | null | 34.686747 | 111 | 0.77909 | 996,897 | /**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.modules.path.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.path.entity.Property;
import com.thinkgem.jeesite.modules.path.service.PropertyService;
/**
* 存放路径Controller
* @author tzj
* @version 2018-02-06
*/
@Controller
@RequestMapping(value = "${adminPath}/path/property")
public class PropertyController extends BaseController {
@Autowired
private PropertyService propertyService;
@ModelAttribute
public Property get(@RequestParam(required=false) String id) {
Property entity = null;
if (StringUtils.isNotBlank(id)){
entity = propertyService.get(id);
}
if (entity == null){
entity = new Property();
}
return entity;
}
@RequiresPermissions("path:property:view")
@RequestMapping(value = {"list", ""})
public String list(Property property, HttpServletRequest request, HttpServletResponse response, Model model) {
Page<Property> page = propertyService.findPage(new Page<Property>(request, response), property);
model.addAttribute("page", page);
return "modules/path/propertyList";
}
@RequiresPermissions("path:property:view")
@RequestMapping(value = "form")
public String form(Property property, Model model) {
model.addAttribute("property", property);
return "modules/path/propertyForm";
}
@RequiresPermissions("path:property:edit")
@RequestMapping(value = "save")
public String save(Property property, Model model, RedirectAttributes redirectAttributes) {
if (!beanValidator(model, property)){
return form(property, model);
}
propertyService.save(property);
addMessage(redirectAttributes, "保存存放路径成功");
return "redirect:"+Global.getAdminPath()+"/path/property/?repage";
}
@RequiresPermissions("path:property:edit")
@RequestMapping(value = "delete")
public String delete(Property property, RedirectAttributes redirectAttributes) {
propertyService.delete(property);
addMessage(redirectAttributes, "删除存放路径成功");
return "redirect:"+Global.getAdminPath()+"/path/property/?repage";
}
} |
92345b478d55b6bcf48aafe4fb969a10436f8008 | 10,104 | java | Java | src/main/java/me/philippheuer/twitch4j/TwitchClient.java | SZOKOZ/twitch4j | 7d7080a0dfdb46c95ea8ad946082f9f10553a61f | [
"MIT"
] | 1 | 2018-09-26T18:09:14.000Z | 2018-09-26T18:09:14.000Z | src/main/java/me/philippheuer/twitch4j/TwitchClient.java | SZOKOZ/twitch4j | 7d7080a0dfdb46c95ea8ad946082f9f10553a61f | [
"MIT"
] | null | null | null | src/main/java/me/philippheuer/twitch4j/TwitchClient.java | SZOKOZ/twitch4j | 7d7080a0dfdb46c95ea8ad946082f9f10553a61f | [
"MIT"
] | null | null | null | 30.071429 | 191 | 0.74327 | 996,898 | package me.philippheuer.twitch4j;
import java.io.File;
import lombok.Getter;
import lombok.Setter;
import lombok.Singular;
import me.philippheuer.twitch4j.auth.CredentialManager;
import me.philippheuer.twitch4j.endpoints.ChannelEndpoint;
import me.philippheuer.twitch4j.endpoints.ChannelFeedEndpoint;
import me.philippheuer.twitch4j.endpoints.ChatEndpoint;
import me.philippheuer.twitch4j.endpoints.CommunityEndpoint;
import me.philippheuer.twitch4j.endpoints.GameEndpoint;
import me.philippheuer.twitch4j.endpoints.IngestEndpoint;
import me.philippheuer.twitch4j.endpoints.KrakenEndpoint;
import me.philippheuer.twitch4j.endpoints.SearchEndpoint;
import me.philippheuer.twitch4j.endpoints.StreamEndpoint;
import me.philippheuer.twitch4j.endpoints.TMIEndpoint;
import me.philippheuer.twitch4j.endpoints.TeamEndpoint;
import me.philippheuer.twitch4j.endpoints.UnofficialEndpoint;
import me.philippheuer.twitch4j.endpoints.UserEndpoint;
import me.philippheuer.twitch4j.endpoints.VideoEndpoint;
import me.philippheuer.twitch4j.events.EventDispatcher;
import me.philippheuer.twitch4j.message.MessageInterface;
import me.philippheuer.twitch4j.message.commands.CommandHandler;
import me.philippheuer.twitch4j.message.irc.listener.IRCEventListener;
import me.philippheuer.twitch4j.model.Channel;
import me.philippheuer.twitch4j.model.Community;
import me.philippheuer.twitch4j.model.Game;
import me.philippheuer.twitch4j.model.Ingest;
import me.philippheuer.twitch4j.model.Stream;
import me.philippheuer.twitch4j.model.Team;
import me.philippheuer.twitch4j.model.User;
import me.philippheuer.twitch4j.model.Video;
import me.philippheuer.twitch4j.modules.ModuleLoader;
import me.philippheuer.twitch4j.streamlabs.StreamlabsClient;
import me.philippheuer.util.rest.HeaderRequestInterceptor;
import me.philippheuer.util.rest.RestClient;
/**
* TwitchClient is the core class for all api operations.
* <p>
* The TwitchClient class is the central component, that grants access
* to the various rest endpoints, the twitch chat interface and the
* client related services. (CredentialManager/CommandHandler/...)
*
* @author Philipp Heuer [https://github.com/PhilippHeuer]
* @version %I%, %G%
* @since 1.0
*/
@Getter
@Setter
public class TwitchClient {
/**
* Service to dispatch Events
*/
private final EventDispatcher dispatcher = new EventDispatcher(this);
/**
* Services to store/request credentials
*/
private final CredentialManager credentialManager = new CredentialManager();
/**
* RestClient to build the rest requests
*/
private final RestClient restClient = new RestClient();
/**
* Twitch IRC Client
*/
private final MessageInterface messageInterface = new MessageInterface(this);
/**
* Integration: Streamlabs Client
*/
private StreamlabsClient streamLabsClient;
/**
* Twitch API Version
*/
public final int twitchEndpointVersion = 5;
/**
* Twitch Application - Client Id
* Default Value: Twitch Client Id
*/
@Singular
private String clientId = "jzkbprff40iqj646a697cyrvl0zt2m6";
/**
* Twitch Application - Client Secret
*/
@Singular
private String clientSecret;
/**
* Configuration Directory to save settings
*/
@Singular
private File configurationDirectory;
/**
* Command Handler (CHAT Commands and Features)
*/
private CommandHandler commandHandler = new CommandHandler(this);
/**
* NEW Feature: Modules.
*/
private final ModuleLoader moduleLoader = new ModuleLoader(this);
/**
* Class Constructor - Creates a new TwitchClient Instance for the provided app.
* <p>
* This will also initialize the rest interceptors, that provide oauth tokens/get/post parameters
* on the fly to easily build the rest requests.
*
* @param clientId Twitch Application - Id
* @param clientSecret Twitch Application - Secret
*/
public TwitchClient(String clientId, String clientSecret) {
this.clientId = clientId;
this.clientSecret = clientSecret;
// Provide Instance of TwitchClient to CredentialManager
credentialManager.setTwitchClient(this);
// EventSubscribers
// - Commands
dispatcher.registerListener(getCommandHandler());
// - IRC Event Listeners
dispatcher.registerListener(new IRCEventListener(this));
// Initialize REST Client
restClient.putRestInterceptor(new HeaderRequestInterceptor("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36"));
restClient.putRestInterceptor(new HeaderRequestInterceptor("Accept", "application/vnd.twitchtv.v5+json"));
restClient.putRestInterceptor(new HeaderRequestInterceptor("Client-ID", getClientId()));
}
/**
* Connect to other related services.
* <p>
* This methods opens the connection to the twitch irc server and the pubsub endpoint.
* Connect needs to be called after initalizing the {@link CredentialManager}.
*/
public void connect() {
getMessageInterface().connect();
}
/**
* Disconnect from other related services.
* <p>
* This methods closes the connection to the twitch irc server and the pubsub endpoint.
*/
public void disconnect() {
getMessageInterface().disconnect();
}
/**
* Reconnect to other related services.
* <p>
* This methods reconnects to the twitch irc server and the pubsub endpoint.
*/
public void reconnect() {
getMessageInterface().reconnect();
}
/**
* Returns an a new KrakenEndpoint instance.
* <p>
* The Kraken Endpoint is the root of the twitch api.
* Querying the Kraken Endpoint gives information about the currently used token.
*
* @return a new instance of {@link KrakenEndpoint}
*/
public KrakenEndpoint getKrakenEndpoint() {
return new KrakenEndpoint(this);
}
/**
* Returns an a new ChannelFeedEndpoint instance.
*
* @return a new instance of {@link ChannelFeedEndpoint}
* @deprecated Twitch removes Channel Feeds and Pulse. More info <a href="https://discuss.dev.twitch.tv/t/how-the-removal-of-channel-feed-and-pulse-affects-the-twitch-api-v5/16540">here</a>.
*/
@Deprecated
public ChannelFeedEndpoint getChannelFeedEndpoint() {
throw new UnsupportedOperationException("The endpoint has been Deprecated");
}
/**
* Returns an a new ChannelEndpoint instance - identifying the channel by the channel id.
* <p>
* The Channel Endpoint instances allow you the query or set data for a specific channel,
* therefore you need to provide information to identify a unique channel.
*
* @return a new instance of {@link ChannelEndpoint}
* @see Channel
*/
public ChannelEndpoint getChannelEndpoint() {
return new ChannelEndpoint(this);
}
/**
* Returns an a new GameEndpoint instance.
* <p>
* The Game Endpoint instance allows you to access information about the all available games on twitch.
*
* @return a new instance of {@link GameEndpoint}
* @see Game
*/
public GameEndpoint getGameEndpoint() {
return new GameEndpoint(this);
}
/**
* Returns an a new StreamEndpoint instance.
* <p>
* The Stream Endpoint provides information about all current live streams and related metadata.
* For more information about the data, check out the {@link Stream} model.
*
* @return a new instance of {@link StreamEndpoint}
* @see Stream
*/
public StreamEndpoint getStreamEndpoint() {
return new StreamEndpoint(this);
}
/**
* Returns an a new UserEndpoint instance.
* <p>
* The User Endpoint provides access to user-related informations and actions.
* For more information about the available methods, check out the {@link UserEndpoint}.
*
* @return a new instance of {@link UserEndpoint}
* @see User
*/
public UserEndpoint getUserEndpoint() {
return new UserEndpoint(this);
}
/**
* Returns an a new CommunityEndpoint instance.
* <p>
* The Community Endpoint allows you to fetch information or manage your communities using the api.
* The community methods usually return a {@link Community} model.
*
* @return a new instance of {@link CommunityEndpoint}
* @see Community
*/
public CommunityEndpoint getCommunityEndpoint() {
return new CommunityEndpoint(this);
}
/**
* Returns an a new IngestEndpoint instance.
* <p>
* The Ingest Endpoint allows you to fetch a list of the twitch ingest servers.
*
* @return a new instance of {@link IngestEndpoint}
* @see Ingest
*/
public IngestEndpoint getIngestEndpoint() {
return new IngestEndpoint(this);
}
/**
* Returns an a new SearchEndpoint instance.
* <p>
* The Search Endpoint allows you to search for {@link Channel}s,
* {@link Game}s or {@link Stream}s.
*
* @return a new instance of {@link SearchEndpoint}
* @see Stream
* @see Game
* @see Channel
*/
public SearchEndpoint getSearchEndpoint() {
return new SearchEndpoint(this);
}
/**
* Returns an a new TeamEndpoint instance.
* <p>
* The Team Endpoint provides a list of all teams and detailed information about single teams.
*
* @return a new instance of {@link TeamEndpoint}
* @see Team
*/
public TeamEndpoint getTeamEndpoint() {
return new TeamEndpoint(this);
}
/**
* Returns an a new VideoEndpoint instance.
* <p>
* The Video Endpoint provides access to videos that twitch users recoded.
*
* @return a new instance of {@link VideoEndpoint}
* @see Video
*/
public VideoEndpoint getVideoEndpoint() {
return new VideoEndpoint(this);
}
/**
* Returns an a new TMIEndpoint instance.
* <p>
* The Twitch Messaging Service (TMI) is the chat service used in twitch.
* This is an unofficial api and can break at any point without any notice.
*
* @return a new instance of {@link TMIEndpoint}
*/
public TMIEndpoint getTMIEndpoint() {
return new TMIEndpoint(this);
}
/**
* Returns an a new UnofficialEndpoint instance.
*
* @return a new instance of {@link UnofficialEndpoint}
*/
public UnofficialEndpoint getUnofficialEndpoint() {
return new UnofficialEndpoint(this);
}
/**
* Returns a new ChatEndpoint instance.
*
* @return a new instance of {@link ChatEndpoint}
*/
public ChatEndpoint getChatEndpoint() {
return new ChatEndpoint(this);
}
}
|
92345c184dce421b8567dcb92e898e9af54ac7dc | 2,810 | java | Java | rsqldb-parser/src/main/java/com/alibaba/rsqldb/parser/parser/expression/AndRelationParser.java | alibaba/rsqldb | 650c45232faba8036702a449c44f453d4765718d | [
"Apache-2.0"
] | 27 | 2021-10-13T03:59:43.000Z | 2022-03-03T06:50:34.000Z | rsqldb-parser/src/main/java/com/alibaba/rsqldb/parser/parser/expression/AndRelationParser.java | alibaba/rsqldb | 650c45232faba8036702a449c44f453d4765718d | [
"Apache-2.0"
] | 2 | 2021-12-06T07:11:28.000Z | 2022-01-22T17:44:23.000Z | rsqldb-parser/src/main/java/com/alibaba/rsqldb/parser/parser/expression/AndRelationParser.java | alibaba/rsqldb | 650c45232faba8036702a449c44f453d4765718d | [
"Apache-2.0"
] | 9 | 2021-11-11T02:12:03.000Z | 2022-02-24T11:10:59.000Z | 43.90625 | 103 | 0.701068 | 996,899 | /*
* 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 com.alibaba.rsqldb.parser.parser.expression;
import com.alibaba.rsqldb.parser.parser.builder.SelectSQLBuilder;
import com.alibaba.rsqldb.parser.parser.result.IParseResult;
import com.alibaba.rsqldb.parser.parser.result.ScriptParseResult;
import com.alibaba.rsqldb.parser.parser.sqlnode.AbstractSelectNodeParser;
import org.apache.calcite.sql.SqlBasicCall;
public class AndRelationParser extends AbstractSelectNodeParser<SqlBasicCall> {
@Override
public IParseResult parse(SelectSQLBuilder tableDescriptor, SqlBasicCall sqlBasicCall) {
String relation = sqlBasicCall.getOperator().getName().toLowerCase().equals("and") ? "&" : "|";
String expressionLeft = parseSqlNode(tableDescriptor, sqlBasicCall.getOperandList().get(0))
.getValueForSubExpression();
String expressionRight = parseSqlNode(tableDescriptor, sqlBasicCall.getOperandList().get(1))
.getValueForSubExpression();
ScriptParseResult scriptParseResult = new ScriptParseResult();
String scriptValue = "";
if (isExpression(expressionLeft)) {
scriptValue = expressionLeft + relation + expressionRight;
scriptParseResult.addScript("(" + scriptValue + ")");
} else {
scriptParseResult.addScript("(" + expressionLeft + relation + expressionRight + ")");
}
return scriptParseResult;
}
private boolean isExpression(String expressionLeft) {
return (expressionLeft.startsWith("(") && expressionLeft.endsWith(")"));
}
@Override
public boolean support(Object sqlNode) {
if (SqlBasicCall.class.isInstance(sqlNode)) {
SqlBasicCall sqlBasicCall = (SqlBasicCall)sqlNode;
if (sqlBasicCall.getOperator().getName().toLowerCase().equals("and")) {
return true;
}
if (sqlBasicCall.getOperator().getName().toLowerCase().equals("or")) {
return true;
}
}
return false;
}
}
|
92345d4141750373f7db31820989f36bd42e93c8 | 250 | java | Java | Ace IM MRIM Module/src/aceim/protocol/snuk182/mrim/inner/MrimException.java | plyhun/aceim | 58c57064caf8a8cf394bf71c02c583ccdd783907 | [
"Apache-2.0"
] | 6 | 2015-01-13T07:05:13.000Z | 2017-07-10T22:44:28.000Z | Ace IM MRIM Module/src/aceim/protocol/snuk182/mrim/inner/MrimException.java | plyhun/aceim | 58c57064caf8a8cf394bf71c02c583ccdd783907 | [
"Apache-2.0"
] | 2 | 2017-02-21T08:31:53.000Z | 2017-08-23T07:22:03.000Z | Ace IM MRIM Module/src/aceim/protocol/snuk182/mrim/inner/MrimException.java | plyhun/aceim | 58c57064caf8a8cf394bf71c02c583ccdd783907 | [
"Apache-2.0"
] | 5 | 2015-01-13T07:05:12.000Z | 2021-12-09T06:52:36.000Z | 17.857143 | 68 | 0.704 | 996,900 | package aceim.protocol.snuk182.mrim.inner;
public class MrimException extends Exception {
public MrimException(String string) {
super(string);
}
/**
*
*/
private static final long serialVersionUID = 1498888409339962037L;
}
|
92345dc2a1b43800f4c5006e7060e435eb410c49 | 917 | java | Java | Mage.Sets/src/mage/cards/s/SavageConception.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 1,444 | 2015-01-02T00:25:38.000Z | 2022-03-31T13:57:18.000Z | Mage.Sets/src/mage/cards/s/SavageConception.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 6,180 | 2015-01-02T19:10:09.000Z | 2022-03-31T21:10:44.000Z | Mage.Sets/src/mage/cards/s/SavageConception.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 1,001 | 2015-01-01T01:15:20.000Z | 2022-03-30T20:23:04.000Z | 25.472222 | 82 | 0.711014 | 996,901 |
package mage.cards.s;
import java.util.UUID;
import mage.abilities.effects.common.CreateTokenEffect;
import mage.abilities.keyword.RetraceAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.game.permanent.token.BeastToken;
/**
*
* @author Plopman
*/
public final class SavageConception extends CardImpl {
public SavageConception(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.SORCERY},"{3}{G}{G}");
// Create a 3/3 green Beast creature token.
this.getSpellAbility().addEffect(new CreateTokenEffect(new BeastToken()));
// Retrace
this.addAbility(new RetraceAbility(this));
}
private SavageConception(final SavageConception card) {
super(card);
}
@Override
public SavageConception copy() {
return new SavageConception(this);
}
}
|
92345e407b0ad79dd760a4137195affc135dbfcc | 3,880 | java | Java | TeamCode/src/main/java/org/firstinspires/ftc/teamcode6032/debug/comms/data/Packet.java | LightningHawks6032/FtcRobotController | 5606aef24bc16ed3ec49187a9e572f61b75ae679 | [
"MIT"
] | null | null | null | TeamCode/src/main/java/org/firstinspires/ftc/teamcode6032/debug/comms/data/Packet.java | LightningHawks6032/FtcRobotController | 5606aef24bc16ed3ec49187a9e572f61b75ae679 | [
"MIT"
] | 1 | 2021-12-09T03:40:35.000Z | 2021-12-14T02:28:52.000Z | TeamCode/src/main/java/org/firstinspires/ftc/teamcode6032/debug/comms/data/Packet.java | LightningHawks6032/FtcRobotController | 5606aef24bc16ed3ec49187a9e572f61b75ae679 | [
"MIT"
] | null | null | null | 36.952381 | 113 | 0.637887 | 996,902 | /*/
# Packet format: *ALWAYS USE BIG-ENDIAN
command name format: UPPER_CASE, LEN=4;
param format: `f{encoded float}`|`s{int for length}HelloWorld`|`i{encoded int}`; {f:float,s:string,i:integer}
id format: encoded random int not 0
Requests:
`>{command}{id|0}{nParams}{param}{param}`
Response:
`<{command}{id}{nParams}{param}{param}`
/*/
package org.firstinspires.ftc.teamcode6032.debug.comms.data;
import org.firstinspires.ftc.teamcode6032.debug.comms.RemoteDebuggerThread;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Random;
/**
* A class representing a single command, request, or response object from the app.
*/
public class Packet {
public static final Codec codec = new Codec();
private static final Random idRand = new Random();
/** Id of the request this packet is linked to. */
public final int requestId;
/** Parameters for the command */
public final PacketParam[] params;
/** If the packet is a request or response. */
public final Type type;
/** The command the packet is using. */
public final Command command;
/** Construct a new instance of Packet */
public Packet(Type typeIn, Command commandIn, PacketParam[] paramsIn, int requestIdIn) {
type = typeIn;
command = commandIn;
requestId = requestIdIn;
params = paramsIn;
}
/** Construct a request packet */
public Packet(Command commandIn, PacketParam[] paramsIn) {
this(Type.REQUEST,commandIn,paramsIn,idRand.nextInt());
}
/** Construct a response packet to request #`requestIdIn`. */
public Packet(int requestIdIn, Command commandIn, PacketParam[] paramsIn) {
this(Type.RESPONSE,commandIn,paramsIn,requestIdIn);
}
public void respond(Command cmd, PacketParam[] param) {
RemoteDebuggerThread.sendPacket(new Packet(Type.RESPONSE,cmd,param,requestId));
}
/** Enum for if the packet is a request or response. */
public enum Type { REQUEST, RESPONSE }
public static class Codec implements BufferCodec<Packet> {
@Override
public void encode(Packet data, DataOutputStream buf) throws IOException {
// Encode type.
if (data.type == null)
throw new IllegalStateException("Cannot encode Packet without type.");
else buf.writeByte(TypeCharConverter.packetTypeChar(data.type));
// Encode command
buf.writeBytes(data.command.id);
// Encode request id
buf.writeInt(data.requestId);
// Write int for number of params
buf.writeInt(data.params.length);
for (int i = 0; i < data.params.length; i++)
PacketParam.codec.encode(data.params[i],buf);
}
@Override
public Packet decode(DataInputStream buf) throws IOException {
// Decode type.
Type type = TypeCharConverter.packetTypeEnum((char) buf.readByte());
if (type == null) throw new IllegalStateException("Cannot decode Packet without type.");
// Decode command
byte[] cmdBytesIn = new byte[4];
//noinspection ResultOfMethodCallIgnored
buf.read(cmdBytesIn);
Command command = Command.get(new String(cmdBytesIn, StandardCharsets.US_ASCII));
// Decode request id
int requestId = buf.readInt();
// Decode params
int nParams = buf.readInt();
PacketParam[] params = new PacketParam[nParams];
for (int i = 0; i < nParams; i++)
params[i] = PacketParam.codec.decode(buf);
// Construct object and return.
return new Packet(type,command, params, requestId);
}
}
}
|
92345e4091fdcb72222635d3892dd0677d7144cb | 762 | java | Java | app/src/main/java/com/example/coolweather/db/Province.java | Quaternion2017/coolweather | 8a07cd8eb75d13b8515cca90e5c70e07d772ba0a | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/coolweather/db/Province.java | Quaternion2017/coolweather | 8a07cd8eb75d13b8515cca90e5c70e07d772ba0a | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/coolweather/db/Province.java | Quaternion2017/coolweather | 8a07cd8eb75d13b8515cca90e5c70e07d772ba0a | [
"Apache-2.0"
] | null | null | null | 19.05 | 53 | 0.66273 | 996,903 | package com.example.coolweather.db;
import android.animation.PropertyValuesHolder;
import org.litepal.crud.DataSupport;
/**
* Created by Administrator on 2018/1/9.
*/
public class Province extends DataSupport {
private int id;
private String provinceName;
private int provinceCode;
public int getId()
{
return id;
}
public void setId(int id){
this.id = id;
}
public String getProvinceName(){
return provinceName;
}
public void setProvinceName(String provinceName){
this.provinceName = provinceName;
}
public int getProvinceCode(){
return provinceCode;
}
public void setProvinceCode(int provinceCode){
this.provinceCode = provinceCode;
}
}
|
9234604726432bcfdd8ae59e5feb3a9de325eb87 | 79,661 | java | Java | sdnc-a1-controller/northbound/vnfapi/provider/src/test/java/org/onap/sdnc/vnfapi/VnfapiProviderTestBase.java | yanhuanwang/nonrtric | 2ff096967a06f9e13ac7deb4bba93c6d37f080f7 | [
"Apache-2.0"
] | null | null | null | sdnc-a1-controller/northbound/vnfapi/provider/src/test/java/org/onap/sdnc/vnfapi/VnfapiProviderTestBase.java | yanhuanwang/nonrtric | 2ff096967a06f9e13ac7deb4bba93c6d37f080f7 | [
"Apache-2.0"
] | 1 | 2020-07-18T16:15:30.000Z | 2020-07-18T16:15:30.000Z | sdnc-a1-controller/northbound/vnfapi/provider/src/test/java/org/onap/sdnc/vnfapi/VnfapiProviderTestBase.java | yanhuanwang/nonrtric | 2ff096967a06f9e13ac7deb4bba93c6d37f080f7 | [
"Apache-2.0"
] | null | null | null | 56.218066 | 131 | 0.749915 | 996,904 | /*-
* ============LICENSE_START=======================================================
* openECOMP : SDN-C
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights
* reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.onap.sdnc.vnfapi;
import com.google.common.base.Optional;
import com.google.common.util.concurrent.CheckedFuture;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.NetworkTopologyOperationInput;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.NetworkTopologyOperationOutput;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.PreloadNetworkTopologyOperationInput;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.PreloadNetworkTopologyOperationOutput;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.PreloadVfModuleTopologyOperationInput;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.PreloadVfModuleTopologyOperationOutput;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.PreloadVfModules;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.PreloadVnfInstanceTopologyOperationInput;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.PreloadVnfInstanceTopologyOperationOutput;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.PreloadVnfInstances;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.PreloadVnfTopologyOperationInput;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.PreloadVnfTopologyOperationOutput;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.PreloadVnfs;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.VNFAPIService;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.VfModuleTopologyOperationInput;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.VfModuleTopologyOperationOutput;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.VfModules;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.VnfInstanceTopologyOperationInput;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.VnfInstanceTopologyOperationOutput;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.VnfInstances;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.VnfTopologyOperationInput;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.VnfTopologyOperationOutput;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.Vnfs;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.network.request.information.NetworkRequestInformation;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.network.topology.identifier.NetworkTopologyIdentifier;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.network.topology.information.NetworkTopologyInformation;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.preload.data.PreloadData;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.preload.data.PreloadDataBuilder;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.preload.model.information.VnfPreloadList;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.preload.vf.module.model.information.VfModulePreloadList;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.preload.vnf.instance.model.information.VnfInstancePreloadList;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.request.information.RequestInformation;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.sdnc.request.header.SdncRequestHeader;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.service.data.ServiceData;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.service.data.ServiceDataBuilder;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.service.information.ServiceInformation;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.service.status.ServiceStatus;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.service.status.ServiceStatusBuilder;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.vf.module.identifiers.VfModuleIdentifiers;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.vf.module.model.infrastructure.VfModuleList;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.vf.module.preload.data.VfModulePreloadData;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.vf.module.preload.data.VfModulePreloadDataBuilder;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.vf.module.request.information.VfModuleRequestInformation;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.vf.module.service.data.VfModuleServiceData;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.vf.module.service.data.VfModuleServiceDataBuilder;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.vf.module.topology.information.VfModuleTopologyInformation;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.vnf.instance.identifiers.VnfInstanceIdentifiers;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.vnf.instance.model.infrastructure.VnfInstanceList;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.vnf.instance.preload.data.VnfInstancePreloadData;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.vnf.instance.preload.data.VnfInstancePreloadDataBuilder;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.vnf.instance.request.information.VnfInstanceRequestInformation;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.vnf.instance.service.data.VnfInstanceServiceData;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.vnf.instance.service.data.VnfInstanceServiceDataBuilder;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.vnf.instance.topology.information.VnfInstanceTopologyInformation;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.vnf.model.infrastructure.VnfList;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.vnf.model.infrastructure.VnfListKey;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.vnf.request.information.VnfRequestInformation;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.vnf.topology.identifier.VnfTopologyIdentifier;
import org.opendaylight.yang.gen.v1.org.onap.sdnctl.vnf.rev150720.vnf.topology.information.VnfTopologyInformation;
import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.powermock.reflect.Whitebox;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
public class VnfapiProviderTestBase {
@Rule public MockitoRule rule = MockitoJUnit.rule();
@Mock private DataBroker dataBroker;
@Mock private NotificationPublishService notificationPublishService;
@Mock private RpcProviderRegistry rpcProviderRegistry;
@Mock private VNFSDNSvcLogicServiceClient vnfsdnSvcLogicServiceClient;
@Mock private ReadWriteTransaction readWriteTransactionInCreateContainer;
@Mock private ReadWriteTransaction readWriteTransactionInDataChanged;
@Mock private CheckedFuture<Void, TransactionCommitFailedException> checkedFuture;
private VnfApiProvider vnfapiProvider;
private String vfModuleName;
private String vfModuleModelId;
private String vnfInstanceId;
private String vnfInstanceName;
private String vnfModelId;
private String svcRequestId;
private String serviceInstanceId;
private String vnfName;
private String vnfType;
private String vfModuleId;
@Before public void setUp() throws Exception {
doReturn(readWriteTransactionInCreateContainer).when(dataBroker).newReadWriteTransaction();
doReturn(checkedFuture).when(readWriteTransactionInCreateContainer).submit();
// mock readOnlyTransaction
ReadOnlyTransaction readOnlyTransaction = mock(ReadOnlyTransaction.class);
doReturn(readOnlyTransaction).when(dataBroker).newReadOnlyTransaction();
doReturn(checkedFuture).when(readOnlyTransaction).read(any(), any());
// mock writeTransaction
WriteTransaction writeTransaction = mock(WriteTransaction.class);
doReturn(writeTransaction).when(dataBroker).newWriteOnlyTransaction();
doReturn(checkedFuture).when(writeTransaction).submit();
vnfapiProvider = spy(new VnfApiProvider(dataBroker, notificationPublishService, rpcProviderRegistry,
vnfsdnSvcLogicServiceClient));
}
@After public void tearDown() throws Exception {
}
@Test public void close() throws Exception {
ExecutorService executor = Whitebox.getInternalState(vnfapiProvider, "executor");
BindingAwareBroker.RpcRegistration<VNFAPIService> vnfapiServiceRpcRegistration =
mock(BindingAwareBroker.RpcRegistration.class);
vnfapiProvider.rpcRegistration = vnfapiServiceRpcRegistration;
vnfapiProvider.close();
Assert.assertTrue(executor.isShutdown());
verify(vnfapiServiceRpcRegistration, times(1)).close();
}
/**
* Test Error case:
* <p>
* <code>input.getVnfInstanceRequestInformation() == null</code>
*
* @throws Exception
*/
@Test public void vnfInstanceTopologyOperationErrorOne() throws Exception {
VnfInstanceTopologyOperationInput vnfInstanceTopologyOperationInput =
mock(VnfInstanceTopologyOperationInput.class);
doReturn(null).when(vnfInstanceTopologyOperationInput).getVnfInstanceRequestInformation();
Future<RpcResult<VnfInstanceTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.vnfInstanceTopologyOperation(vnfInstanceTopologyOperationInput);
Assert.assertEquals("403", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals("invalid input, null or empty vnf-instance-id",
rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Error case:
* <p>
* <code>viid == null</code>
*
* @throws Exception
*/
@Test public void vnfInstanceTopologyOperationErrorTwo() throws Exception {
vnfInstanceId = "";
vnfInstanceName = "vnf-instance-name";
vnfModelId = "vnf-model-id";
VnfInstanceTopologyOperationInput vnfInstanceTopologyOperationInput =
mock(VnfInstanceTopologyOperationInput.class);
VnfInstanceRequestInformation vnfInstanceRequestInformation = mock(VnfInstanceRequestInformation.class);
doReturn(vnfInstanceName).when(vnfInstanceRequestInformation).getVnfInstanceName();
doReturn(vnfModelId).when(vnfInstanceRequestInformation).getVnfModelId();
doReturn(vnfInstanceId).when(vnfInstanceRequestInformation).getVnfInstanceId();
doReturn(vnfInstanceRequestInformation).when(vnfInstanceTopologyOperationInput)
.getVnfInstanceRequestInformation();
Future<RpcResult<VnfInstanceTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.vnfInstanceTopologyOperation(vnfInstanceTopologyOperationInput);
Assert.assertEquals("403", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals("invalid input, null or empty vnf-instance-id",
rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Error case:
* <p>
* <code>svcLogicClient.hasGraph("VNF-API",SVC_OPERATION,null,"sync" = false</code>
*
* @throws Exception
*/
@Test public void vnfInstanceTopologyOperationErrorThree() throws Exception {
vnfInstanceId = "vnf-instance-id";
vnfInstanceName = "vnf-instance-name";
vnfModelId = "vnf-model-id";
svcRequestId = "svc-request-id";
VnfInstanceTopologyOperationInput vnfInstanceTopologyOperationInput =
mock(VnfInstanceTopologyOperationInput.class);
VnfInstanceRequestInformation vnfInstanceRequestInformation = mock(VnfInstanceRequestInformation.class);
doReturn(vnfInstanceId).when(vnfInstanceRequestInformation).getVnfInstanceId();
doReturn(vnfInstanceName).when(vnfInstanceRequestInformation).getVnfInstanceName();
doReturn(vnfModelId).when(vnfInstanceRequestInformation).getVnfModelId();
doReturn(vnfInstanceRequestInformation).when(vnfInstanceTopologyOperationInput)
.getVnfInstanceRequestInformation();
SdncRequestHeader sdncRequestHeader = mock(SdncRequestHeader.class);
doReturn(sdncRequestHeader).when(vnfInstanceTopologyOperationInput).getSdncRequestHeader();
doReturn(svcRequestId).when(sdncRequestHeader).getSvcRequestId();
Future<RpcResult<VnfInstanceTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.vnfInstanceTopologyOperation(vnfInstanceTopologyOperationInput);
Assert.assertEquals("503", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertTrue(
rpcResultFuture.get().getResult().getResponseMessage().contains("No service logic active for VNF-API"));
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Success case
*
* @throws Exception
*/
@Test public void vnfInstanceTopologyOperationSuccess() throws Exception {
vnfInstanceId = "vnf-instance-id";
vnfInstanceName = "vnf-instance-name";
vnfModelId = "vnf-model-id";
svcRequestId = "svc-request-id";
VnfInstanceTopologyOperationInput vnfInstanceTopologyOperationInput =
mock(VnfInstanceTopologyOperationInput.class);
VnfInstanceRequestInformation vnfInstanceRequestInformation = mock(VnfInstanceRequestInformation.class);
doReturn(vnfInstanceId).when(vnfInstanceRequestInformation).getVnfInstanceId();
doReturn(vnfInstanceName).when(vnfInstanceRequestInformation).getVnfInstanceName();
doReturn(vnfModelId).when(vnfInstanceRequestInformation).getVnfModelId();
doReturn(vnfInstanceRequestInformation).when(vnfInstanceTopologyOperationInput)
.getVnfInstanceRequestInformation();
SdncRequestHeader sdncRequestHeader = mock(SdncRequestHeader.class);
doReturn(sdncRequestHeader).when(vnfInstanceTopologyOperationInput).getSdncRequestHeader();
doReturn(svcRequestId).when(sdncRequestHeader).getSvcRequestId();
doReturn(SdncRequestHeader.SvcAction.Activate).when(sdncRequestHeader).getSvcAction();
ReadOnlyTransaction readOnlyTransaction = mock(ReadOnlyTransaction.class);
doReturn(readOnlyTransaction).when(dataBroker).newReadOnlyTransaction();
doReturn(checkedFuture).when(readOnlyTransaction).read(any(), any());
WriteTransaction writeTransaction = mock(WriteTransaction.class);
doReturn(writeTransaction).when(dataBroker).newWriteOnlyTransaction();
doReturn(checkedFuture).when(writeTransaction).submit();
doReturn(true).when(vnfsdnSvcLogicServiceClient).hasGraph(any(), any(), any(), any());
Future<RpcResult<VnfInstanceTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.vnfInstanceTopologyOperation(vnfInstanceTopologyOperationInput);
Assert.assertEquals("200", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals(null, rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Error case:
* <p>
* <code>input.getVfModuleTopologyInformation() == null</code>
*
* @throws Exception
*/
@Test public void vfModuleTopologyOperationErrorOne() throws Exception {
VfModuleTopologyOperationInput vfModuleTopologyOperationInput = mock(VfModuleTopologyOperationInput.class);
doReturn(null).when(vfModuleTopologyOperationInput).getVfModuleRequestInformation();
Future<RpcResult<VfModuleTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.vfModuleTopologyOperation(vfModuleTopologyOperationInput);
Assert.assertEquals("403", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals("invalid input, null or empty vf-module-id",
rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Error case:
* <p>
* <code>vfid = ""</code>
* And
* <p>
* <code>viid = ""</code>
*
* @throws Exception
*/
@Test public void vfModuleTopologyOperationErrorTwo() throws Exception {
// vifd = ""
vfModuleName = "vfModuleName";
vfModuleModelId = "vfModuleModelId";
vfModuleId = "";
vnfInstanceId = "";
VfModuleTopologyOperationInput vfModuleTopologyOperationInput = mock(VfModuleTopologyOperationInput.class);
VfModuleRequestInformation vfModuleRequestInformation = mock(VfModuleRequestInformation.class);
doReturn(vfModuleRequestInformation).when(vfModuleTopologyOperationInput).getVfModuleRequestInformation();
VfModuleIdentifiers vfModuleIdentifiers = mock(VfModuleIdentifiers.class);
doReturn(vfModuleName).when(vfModuleIdentifiers).getVfModuleName();
doReturn(vfModuleModelId).when(vfModuleIdentifiers).getVfModuleModelId();
doReturn(vfModuleId).when(vfModuleRequestInformation).getVfModuleId();
Future<RpcResult<VfModuleTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.vfModuleTopologyOperation(vfModuleTopologyOperationInput);
Assert.assertEquals("403", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals("invalid input, null or empty vf-module-id",
rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
// viid = ""
vfModuleId = "vfModuleId";
doReturn(vfModuleId).when(vfModuleRequestInformation).getVfModuleId();
doReturn(vnfInstanceId).when(vfModuleRequestInformation).getVnfInstanceId();
rpcResultFuture = vnfapiProvider.vfModuleTopologyOperation(vfModuleTopologyOperationInput);
Assert.assertEquals("403", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals("invalid input, null or empty vnf-instance-id",
rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Error case:
* <p>
* <code>svcLogicClient.hasGraph("VNF-API", SVC_OPERATION, null, "sync") = false</code>
*
* @throws Exception
*/
@Test public void vfModuleTopologyOperationErrorThree() throws Exception {
// vifd = ""
vfModuleName = "vfModuleName";
vfModuleModelId = "vfModuleModelId";
vfModuleId = "vfModuleId";
vnfInstanceId = "vnfInstanceId";
VfModuleTopologyOperationInput vfModuleTopologyOperationInput = mock(VfModuleTopologyOperationInput.class);
VfModuleRequestInformation vfModuleRequestInformation = mock(VfModuleRequestInformation.class);
doReturn(vfModuleRequestInformation).when(vfModuleTopologyOperationInput).getVfModuleRequestInformation();
VfModuleIdentifiers vfModuleIdentifiers = mock(VfModuleIdentifiers.class);
doReturn(vfModuleName).when(vfModuleIdentifiers).getVfModuleName();
doReturn(vfModuleModelId).when(vfModuleIdentifiers).getVfModuleModelId();
doReturn(vfModuleId).when(vfModuleRequestInformation).getVfModuleId();
doReturn(vnfInstanceId).when(vfModuleRequestInformation).getVnfInstanceId();
// mock sdncRequestHeader
SdncRequestHeader sdncRequestHeader = mock(SdncRequestHeader.class);
doReturn(sdncRequestHeader).when(vfModuleTopologyOperationInput).getSdncRequestHeader();
doReturn(svcRequestId).when(sdncRequestHeader).getSvcRequestId();
Future<RpcResult<VfModuleTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.vfModuleTopologyOperation(vfModuleTopologyOperationInput);
Assert.assertEquals("503", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertTrue(
rpcResultFuture.get().getResult().getResponseMessage().contains("No service logic active for VNF-API"));
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Success case
*
* @throws Exception
*/
@Test public void vfModuleTopologyOperationSuccess() throws Exception {
vfModuleName = "vfModuleName";
vfModuleModelId = "vfModuleModelId";
vfModuleId = "vfModuleId";
vnfInstanceId = "vnfInstanceId";
VfModuleTopologyOperationInput vfModuleTopologyOperationInput = mock(VfModuleTopologyOperationInput.class);
VfModuleRequestInformation vfModuleRequestInformation = mock(VfModuleRequestInformation.class);
doReturn(vfModuleRequestInformation).when(vfModuleTopologyOperationInput).getVfModuleRequestInformation();
VfModuleIdentifiers vfModuleIdentifiers = mock(VfModuleIdentifiers.class);
doReturn(vfModuleName).when(vfModuleIdentifiers).getVfModuleName();
doReturn(vfModuleModelId).when(vfModuleIdentifiers).getVfModuleModelId();
doReturn(vfModuleId).when(vfModuleRequestInformation).getVfModuleId();
doReturn(vnfInstanceId).when(vfModuleRequestInformation).getVnfInstanceId();
// mock sdncRequestHeader
SdncRequestHeader sdncRequestHeader = mock(SdncRequestHeader.class);
doReturn(sdncRequestHeader).when(vfModuleTopologyOperationInput).getSdncRequestHeader();
doReturn(svcRequestId).when(sdncRequestHeader).getSvcRequestId();
doReturn(true).when(vnfsdnSvcLogicServiceClient).hasGraph(any(), any(), any(), any());
Future<RpcResult<VfModuleTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.vfModuleTopologyOperation(vfModuleTopologyOperationInput);
Assert.assertEquals("200", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals(null, rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Error case:
* <p>
* <code>input.getServiceInformation() == null</code>
*
* @throws Exception
*/
@Test public void vnfTopologyOperationErrorOne() throws Exception {
VnfTopologyOperationInput vnfTopologyOperationInput = mock(VnfTopologyOperationInput.class);
doReturn(null).when(vnfTopologyOperationInput).getServiceInformation();
Future<RpcResult<VnfTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.vnfTopologyOperation(vnfTopologyOperationInput);
Assert.assertEquals("403", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals("invalid input, null or empty service-instance-id",
rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Error case:
* <p>
* <code>input.getVnfRequestInformation() == null</code>
*
* @throws Exception
*/
@Test public void vnfTopologyOperationErrorTwo() throws Exception {
serviceInstanceId = "serviceInstanceId";
VnfTopologyOperationInput vnfTopologyOperationInput = mock(VnfTopologyOperationInput.class);
ServiceInformation serviceInformation = mock(ServiceInformation.class);
doReturn(serviceInformation).when(vnfTopologyOperationInput).getServiceInformation();
doReturn(serviceInstanceId).when(serviceInformation).getServiceInstanceId();
Future<RpcResult<VnfTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.vnfTopologyOperation(vnfTopologyOperationInput);
Assert.assertEquals("403", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals("invalid input, null or empty vf-module-id",
rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Error case:
* <p>
* <code>svcLogicClient.hasGraph("VNF-API", SVC_OPERATION, null, "sync") == false</code>
*
* @throws Exception
*/
@Test public void vnfTopologyOperationErrorThree() throws Exception {
serviceInstanceId = "serviceInstanceId";
String vnfId = "vnfId";
VnfTopologyOperationInput vnfTopologyOperationInput = mock(VnfTopologyOperationInput.class);
ServiceInformation serviceInformation = mock(ServiceInformation.class);
doReturn(serviceInformation).when(vnfTopologyOperationInput).getServiceInformation();
doReturn(serviceInstanceId).when(serviceInformation).getServiceInstanceId();
VnfRequestInformation vnfRequestInformation = mock(VnfRequestInformation.class);
doReturn(vnfRequestInformation).when(vnfTopologyOperationInput).getVnfRequestInformation();
doReturn(vnfId).when(vnfRequestInformation).getVnfId();
Future<RpcResult<VnfTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.vnfTopologyOperation(vnfTopologyOperationInput);
Assert.assertEquals("503", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertTrue(
rpcResultFuture.get().getResult().getResponseMessage().contains("No service logic active for VNF-API"));
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Success case
*
* @throws Exception
*/
@Test public void vnfTopologyOperationSuccess() throws Exception {
serviceInstanceId = "serviceInstanceId";
String vnfId = "vnfId";
VnfTopologyOperationInput vnfTopologyOperationInput = mock(VnfTopologyOperationInput.class);
ServiceInformation serviceInformation = mock(ServiceInformation.class);
doReturn(serviceInformation).when(vnfTopologyOperationInput).getServiceInformation();
doReturn(serviceInstanceId).when(serviceInformation).getServiceInstanceId();
VnfRequestInformation vnfRequestInformation = mock(VnfRequestInformation.class);
doReturn(vnfRequestInformation).when(vnfTopologyOperationInput).getVnfRequestInformation();
doReturn(vnfId).when(vnfRequestInformation).getVnfId();
doReturn(true).when(vnfsdnSvcLogicServiceClient).hasGraph(any(), any(), any(), any());
Future<RpcResult<VnfTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.vnfTopologyOperation(vnfTopologyOperationInput);
Assert.assertEquals("200", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals(null, rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Error case:
* <p>
* <code>input.getServiceInformation() == null</code>
*
* @throws Exception
*/
@Test public void networkTopologyOperationErrorOne() throws Exception {
VnfTopologyOperationInput vnfTopologyOperationInput = mock(VnfTopologyOperationInput.class);
doReturn(null).when(vnfTopologyOperationInput).getServiceInformation();
Future<RpcResult<VnfTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.vnfTopologyOperation(vnfTopologyOperationInput);
Assert.assertEquals("403", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals("invalid input, null or empty service-instance-id",
rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Error case:
* <p>
* <code>input.getNetworkRequestInformation() == null</code>
*
* @throws Exception
*/
@Test public void networkTopologyOperationErrorTwo() throws Exception {
serviceInstanceId = "serviceInstanceId";
NetworkTopologyOperationInput networkTopologyOperation = mock(NetworkTopologyOperationInput.class);
ServiceInformation serviceInformation = mock(ServiceInformation.class);
doReturn(serviceInstanceId).when(serviceInformation).getServiceInstanceId();
doReturn(serviceInformation).when(networkTopologyOperation).getServiceInformation();
Future<RpcResult<NetworkTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.networkTopologyOperation(networkTopologyOperation);
Assert.assertEquals("403", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals("invalid input, null or empty service-instance-id",
rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Error case:
* <p>
* <code>svcLogicClient.hasGraph("VNF-API", SVC_OPERATION, null, "sync") == false</code>
*
* @throws Exception
*/
@Test public void networkTopologyOperationErrorThree() throws Exception {
serviceInstanceId = "serviceInstanceId";
NetworkTopologyOperationInput networkTopologyOperationInput = mock(NetworkTopologyOperationInput.class);
ServiceInformation serviceInformation = mock(ServiceInformation.class);
doReturn(serviceInstanceId).when(serviceInformation).getServiceInstanceId();
doReturn(serviceInformation).when(networkTopologyOperationInput).getServiceInformation();
NetworkRequestInformation networkRequestInformation = mock(NetworkRequestInformation.class);
doReturn(networkRequestInformation).when(networkTopologyOperationInput).getNetworkRequestInformation();
doReturn("NetworkName").when(networkRequestInformation).getNetworkName();
SdncRequestHeader sdncRequestHeader = mock(SdncRequestHeader.class);
doReturn(SdncRequestHeader.SvcAction.Assign).when(sdncRequestHeader).getSvcAction();
doReturn(sdncRequestHeader).when(networkTopologyOperationInput).getSdncRequestHeader();
Future<RpcResult<NetworkTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.networkTopologyOperation(networkTopologyOperationInput);
Assert.assertEquals("503", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertTrue(
rpcResultFuture.get().getResult().getResponseMessage().contains("No service logic active for VNF-API"));
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Success case
*
* @throws Exception
*/
@Test public void networkTopologyOperationSuccess() throws Exception {
serviceInstanceId = "serviceInstanceId";
NetworkTopologyOperationInput networkTopologyOperationInput = mock(NetworkTopologyOperationInput.class);
ServiceInformation serviceInformation = mock(ServiceInformation.class);
doReturn(serviceInstanceId).when(serviceInformation).getServiceInstanceId();
doReturn(serviceInformation).when(networkTopologyOperationInput).getServiceInformation();
//mock networkRequestInformation
NetworkRequestInformation networkRequestInformation = mock(NetworkRequestInformation.class);
doReturn(networkRequestInformation).when(networkTopologyOperationInput).getNetworkRequestInformation();
doReturn("NetworkName").when(networkRequestInformation).getNetworkName();
//mock sdncRequestHeader
SdncRequestHeader sdncRequestHeader = mock(SdncRequestHeader.class);
doReturn(SdncRequestHeader.SvcAction.Assign).when(sdncRequestHeader).getSvcAction();
doReturn(sdncRequestHeader).when(networkTopologyOperationInput).getSdncRequestHeader();
doReturn(true).when(vnfsdnSvcLogicServiceClient).hasGraph(any(), any(), any(), any());
Future<RpcResult<NetworkTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.networkTopologyOperation(networkTopologyOperationInput);
Assert.assertEquals("200", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals(null, rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Error case:
* <p>
* <code>input.getVnfTopologyInformation() == null</code>
*
* @throws Exception
*/
@Test public void preloadVnfTopologyOperationErrorOne() throws Exception {
PreloadVnfTopologyOperationInput preloadVnfTopologyOperationInput =
mock(PreloadVnfTopologyOperationInput.class);
doReturn(null).when(preloadVnfTopologyOperationInput).getVnfTopologyInformation();
Future<RpcResult<PreloadVnfTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.preloadVnfTopologyOperation(preloadVnfTopologyOperationInput);
Assert.assertEquals("403", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals("invalid input, null or empty vnf-name or vnf-type",
rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Error case:
* <p>
* <code>preload_name.length() == 0</code>
* And
* <code>preload_type.length() == 0</code>
*
* @throws Exception
*/
@Test public void preloadVnfTopologyOperationErrorTwo() throws Exception {
// preload_name.length() == 0
vnfName = "";
vnfType = "vfModuleModelId";
PreloadVnfTopologyOperationInput preloadVnfTopologyOperationInput =
mock(PreloadVnfTopologyOperationInput.class);
doReturn(null).when(preloadVnfTopologyOperationInput).getVnfTopologyInformation();
VnfTopologyInformation vnfTopologyInformation = mock(VnfTopologyInformation.class);
doReturn(vnfTopologyInformation).when(preloadVnfTopologyOperationInput).getVnfTopologyInformation();
VnfTopologyIdentifier vnfTopologyIdentifier = mock(VnfTopologyIdentifier.class);
doReturn(vnfName).when(vnfTopologyIdentifier).getVnfName();
doReturn(vnfType).when(vnfTopologyIdentifier).getVnfType();
doReturn(vnfTopologyIdentifier).when(vnfTopologyInformation).getVnfTopologyIdentifier();
Future<RpcResult<PreloadVnfTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.preloadVnfTopologyOperation(preloadVnfTopologyOperationInput);
Assert.assertEquals("403", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals("invalid input, invalid preload-name",
rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
// preload_type.length() == 0
vnfName = "vnfName";
vnfType = "";
doReturn(vnfName).when(vnfTopologyIdentifier).getVnfName();
doReturn(vnfType).when(vnfTopologyIdentifier).getVnfType();
rpcResultFuture = vnfapiProvider.preloadVnfTopologyOperation(preloadVnfTopologyOperationInput);
Assert.assertEquals("403", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals("invalid input, invalid preload-type",
rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Error case:
* <code>svcLogicClient.hasGraph("VNF-API", SVC_OPERATION, null, "sync") = false</code>
*
* @throws Exception
*/
@Test public void preloadVnfTopologyOperationErrorThree() throws Exception {
// preload_name.length() == 0
vnfName = "vnfName";
vnfType = "vfModuleModelId";
PreloadVnfTopologyOperationInput preloadVnfTopologyOperationInput =
mock(PreloadVnfTopologyOperationInput.class);
doReturn(null).when(preloadVnfTopologyOperationInput).getVnfTopologyInformation();
VnfTopologyInformation vnfTopologyInformation = mock(VnfTopologyInformation.class);
doReturn(vnfTopologyInformation).when(preloadVnfTopologyOperationInput).getVnfTopologyInformation();
VnfTopologyIdentifier vnfTopologyIdentifier = mock(VnfTopologyIdentifier.class);
doReturn(vnfName).when(vnfTopologyIdentifier).getVnfName();
doReturn(vnfType).when(vnfTopologyIdentifier).getVnfType();
doReturn(vnfTopologyIdentifier).when(vnfTopologyInformation).getVnfTopologyIdentifier();
Future<RpcResult<PreloadVnfTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.preloadVnfTopologyOperation(preloadVnfTopologyOperationInput);
Assert.assertEquals("503", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertTrue(
rpcResultFuture.get().getResult().getResponseMessage().contains("No service logic active for VNF-API"));
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Success case
*
* @throws Exception
*/
@Test public void preloadVnfTopologyOperationSuccess() throws Exception {
// preload_name.length() == 0
vnfName = "vnfName";
vnfType = "vfModuleModelId";
PreloadVnfTopologyOperationInput preloadVnfTopologyOperationInput =
mock(PreloadVnfTopologyOperationInput.class);
doReturn(null).when(preloadVnfTopologyOperationInput).getVnfTopologyInformation();
VnfTopologyInformation vnfTopologyInformation = mock(VnfTopologyInformation.class);
doReturn(vnfTopologyInformation).when(preloadVnfTopologyOperationInput).getVnfTopologyInformation();
VnfTopologyIdentifier vnfTopologyIdentifier = mock(VnfTopologyIdentifier.class);
doReturn(vnfName).when(vnfTopologyIdentifier).getVnfName();
doReturn(vnfType).when(vnfTopologyIdentifier).getVnfType();
doReturn(vnfTopologyIdentifier).when(vnfTopologyInformation).getVnfTopologyIdentifier();
doReturn(true).when(vnfsdnSvcLogicServiceClient).hasGraph(any(), any(), any(), any());
Future<RpcResult<PreloadVnfTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.preloadVnfTopologyOperation(preloadVnfTopologyOperationInput);
Assert.assertEquals("200", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals(null, rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Error case:
* <p>
* <code>input.getVnfInstanceTopologyInformation() == null</code>
*
* @throws Exception
*/
@Test public void preloadVnfInstanceTopologyOperationErrorOne() throws Exception {
PreloadVnfInstanceTopologyOperationInput preloadVnfInstanceTopologyOperationInput =
mock(PreloadVnfInstanceTopologyOperationInput.class);
doReturn(null).when(preloadVnfInstanceTopologyOperationInput).getVnfInstanceTopologyInformation();
Future<RpcResult<PreloadVnfInstanceTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.preloadVnfInstanceTopologyOperation(preloadVnfInstanceTopologyOperationInput);
Assert.assertEquals("403", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals("invalid input, null or empty vnf-instance-name or vnf-model-id",
rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Error case:
* <p>
* <code>preload_name = ""</code>
* And
* <code>preload_type = ""</code>
*
* @throws Exception
*/
@Test public void preloadVnfInstanceTopologyOperationErrorTwo() throws Exception {
// preload_type = ""
vnfInstanceName = "vnfInstanceName";
vnfModelId = "";
PreloadVnfInstanceTopologyOperationInput preloadVnfInstanceTopologyOperationInput =
mock(PreloadVnfInstanceTopologyOperationInput.class);
VnfInstanceTopologyInformation vnfInstanceTopologyInformation = mock(VnfInstanceTopologyInformation.class);
doReturn(vnfInstanceTopologyInformation).when(preloadVnfInstanceTopologyOperationInput)
.getVnfInstanceTopologyInformation();
VnfInstanceIdentifiers vnfInstanceIdentifiers = mock(VnfInstanceIdentifiers.class);
doReturn(vnfInstanceName).when(vnfInstanceIdentifiers).getVnfInstanceName();
doReturn(vnfModelId).when(vnfInstanceIdentifiers).getVnfModelId();
doReturn(vnfInstanceIdentifiers).when(vnfInstanceTopologyInformation).getVnfInstanceIdentifiers();
Future<RpcResult<PreloadVnfInstanceTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.preloadVnfInstanceTopologyOperation(preloadVnfInstanceTopologyOperationInput);
Assert.assertEquals("403", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals("invalid input, invalid preload-type",
rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
//preload_name == ""
vnfInstanceName = "";
vnfModelId = "vnfModelId";
doReturn(vnfInstanceName).when(vnfInstanceIdentifiers).getVnfInstanceName();
doReturn(vnfModelId).when(vnfInstanceIdentifiers).getVnfModelId();
rpcResultFuture = vnfapiProvider.preloadVnfInstanceTopologyOperation(preloadVnfInstanceTopologyOperationInput);
Assert.assertEquals("403", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals("invalid input, invalid preload-name",
rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Error case:
* <p>
* <code>svcLogicClient.hasGraph("VNF-API", SVC_OPERATION, null, "sync") = false</code>
*
* @throws Exception
*/
@Test public void preloadVnfInstanceTopologyOperationErrorThree() throws Exception {
// preload_type = ""
vnfInstanceName = "vnfInstanceName";
vnfModelId = "vnfModelId";
PreloadVnfInstanceTopologyOperationInput preloadVnfInstanceTopologyOperationInput =
mock(PreloadVnfInstanceTopologyOperationInput.class);
VnfInstanceTopologyInformation vnfInstanceTopologyInformation = mock(VnfInstanceTopologyInformation.class);
doReturn(vnfInstanceTopologyInformation).when(preloadVnfInstanceTopologyOperationInput)
.getVnfInstanceTopologyInformation();
VnfInstanceIdentifiers vnfInstanceIdentifiers = mock(VnfInstanceIdentifiers.class);
doReturn(vnfInstanceName).when(vnfInstanceIdentifiers).getVnfInstanceName();
doReturn(vnfModelId).when(vnfInstanceIdentifiers).getVnfModelId();
doReturn(vnfInstanceIdentifiers).when(vnfInstanceTopologyInformation).getVnfInstanceIdentifiers();
SdncRequestHeader sdncRequestHeader = mock(SdncRequestHeader.class);
doReturn(sdncRequestHeader).when(preloadVnfInstanceTopologyOperationInput).getSdncRequestHeader();
doReturn(svcRequestId).when(sdncRequestHeader).getSvcRequestId();
Future<RpcResult<PreloadVnfInstanceTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.preloadVnfInstanceTopologyOperation(preloadVnfInstanceTopologyOperationInput);
Assert.assertEquals("503", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertTrue(
rpcResultFuture.get().getResult().getResponseMessage().contains("No service logic active for VNF-API"));
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Success case
*
* @throws Exception
*/
@Test public void preloadVnfInstanceTopologyOperationSuccess() throws Exception {
// preload_type = ""
vnfInstanceName = "vnfInstanceName";
vnfModelId = "vnfModelId";
PreloadVnfInstanceTopologyOperationInput preloadVnfInstanceTopologyOperationInput =
mock(PreloadVnfInstanceTopologyOperationInput.class);
VnfInstanceTopologyInformation vnfInstanceTopologyInformation = mock(VnfInstanceTopologyInformation.class);
doReturn(vnfInstanceTopologyInformation).when(preloadVnfInstanceTopologyOperationInput)
.getVnfInstanceTopologyInformation();
VnfInstanceIdentifiers vnfInstanceIdentifiers = mock(VnfInstanceIdentifiers.class);
doReturn(vnfInstanceName).when(vnfInstanceIdentifiers).getVnfInstanceName();
doReturn(vnfModelId).when(vnfInstanceIdentifiers).getVnfModelId();
doReturn(vnfInstanceIdentifiers).when(vnfInstanceTopologyInformation).getVnfInstanceIdentifiers();
SdncRequestHeader sdncRequestHeader = mock(SdncRequestHeader.class);
doReturn(sdncRequestHeader).when(preloadVnfInstanceTopologyOperationInput).getSdncRequestHeader();
doReturn(svcRequestId).when(sdncRequestHeader).getSvcRequestId();
doReturn(true).when(vnfsdnSvcLogicServiceClient).hasGraph(any(), any(), any(), any());
Future<RpcResult<PreloadVnfInstanceTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.preloadVnfInstanceTopologyOperation(preloadVnfInstanceTopologyOperationInput);
Assert.assertEquals("200", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals(null, rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Error case:
* <p>
* <code>input.getVfModuleTopologyInformation() == null</code>
*
* @throws Exception
*/
@Test public void preloadVfModuleTopologyOperationErrorOne() throws Exception {
PreloadVfModuleTopologyOperationInput preloadVnfTopologyOperationInput =
mock(PreloadVfModuleTopologyOperationInput.class);
doReturn(null).when(preloadVnfTopologyOperationInput).getVfModuleTopologyInformation();
Future<RpcResult<PreloadVfModuleTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.preloadVfModuleTopologyOperation(preloadVnfTopologyOperationInput);
Assert.assertEquals("403", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals("invalid input, null or empty vf-module-name or vf-module-model-id",
rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Error case:
* <p>
* <code>preload_name = ""</code>
* And
* <code>preload_type = ""</code>
*
* @throws Exception
*/
@Test public void preloadVfModuleTopologyOperationErrorTwo() throws Exception {
// preload_name = ""
vfModuleName = "";
vfModuleModelId = "vfModuleModelId";
PreloadVfModuleTopologyOperationInput preloadVnfTopologyOperationInput =
mock(PreloadVfModuleTopologyOperationInput.class);
VfModuleTopologyInformation vfModuleTopologyInformation = mock(VfModuleTopologyInformation.class);
doReturn(vfModuleTopologyInformation).when(preloadVnfTopologyOperationInput).getVfModuleTopologyInformation();
VfModuleIdentifiers vfModuleIdentifiers = mock(VfModuleIdentifiers.class);
doReturn(vfModuleName).when(vfModuleIdentifiers).getVfModuleName();
doReturn(vfModuleModelId).when(vfModuleIdentifiers).getVfModuleModelId();
doReturn(vfModuleIdentifiers).when(vfModuleTopologyInformation).getVfModuleIdentifiers();
Future<RpcResult<PreloadVfModuleTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.preloadVfModuleTopologyOperation(preloadVnfTopologyOperationInput);
Assert.assertEquals("403", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals("invalid input, invalid preload-name",
rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
// preload_type = ""
vfModuleName = "vfModuleName";
vfModuleModelId = "";
doReturn(vfModuleName).when(vfModuleIdentifiers).getVfModuleName();
doReturn(vfModuleModelId).when(vfModuleIdentifiers).getVfModuleModelId();
rpcResultFuture = vnfapiProvider.preloadVfModuleTopologyOperation(preloadVnfTopologyOperationInput);
Assert.assertEquals("403", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals("invalid input, invalid preload-type",
rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Error case:
* <p>
* <code>svcLogicClient.hasGraph("VNF-API", SVC_OPERATION, null, "sync") = false</code>
*
* @throws Exception
*/
@Test public void preloadVfModuleTopologyOperationErrorThree() throws Exception {
// preload_name = ""
vfModuleName = "vfModuleName";
vfModuleModelId = "vfModuleModelId";
PreloadVfModuleTopologyOperationInput preloadVnfTopologyOperationInput =
mock(PreloadVfModuleTopologyOperationInput.class);
VfModuleTopologyInformation vfModuleTopologyInformation = mock(VfModuleTopologyInformation.class);
doReturn(vfModuleTopologyInformation).when(preloadVnfTopologyOperationInput).getVfModuleTopologyInformation();
VfModuleIdentifiers vfModuleIdentifiers = mock(VfModuleIdentifiers.class);
doReturn(vfModuleName).when(vfModuleIdentifiers).getVfModuleName();
doReturn(vfModuleModelId).when(vfModuleIdentifiers).getVfModuleModelId();
doReturn(vfModuleIdentifiers).when(vfModuleTopologyInformation).getVfModuleIdentifiers();
SdncRequestHeader sdncRequestHeader = mock(SdncRequestHeader.class);
doReturn(sdncRequestHeader).when(preloadVnfTopologyOperationInput).getSdncRequestHeader();
doReturn(svcRequestId).when(sdncRequestHeader).getSvcRequestId();
Future<RpcResult<PreloadVfModuleTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.preloadVfModuleTopologyOperation(preloadVnfTopologyOperationInput);
Assert.assertEquals("503", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertTrue(
rpcResultFuture.get().getResult().getResponseMessage().contains("No service logic active for VNF-API"));
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Success case
*
* @throws Exception
*/
@Test public void preloadVfModuleTopologyOperationSuccess() throws Exception {
// preload_name = ""
vfModuleName = "vfModuleName";
vfModuleModelId = "vfModuleModelId";
PreloadVfModuleTopologyOperationInput preloadVnfTopologyOperationInput =
mock(PreloadVfModuleTopologyOperationInput.class);
VfModuleTopologyInformation vfModuleTopologyInformation = mock(VfModuleTopologyInformation.class);
doReturn(vfModuleTopologyInformation).when(preloadVnfTopologyOperationInput).getVfModuleTopologyInformation();
VfModuleIdentifiers vfModuleIdentifiers = mock(VfModuleIdentifiers.class);
doReturn(vfModuleName).when(vfModuleIdentifiers).getVfModuleName();
doReturn(vfModuleModelId).when(vfModuleIdentifiers).getVfModuleModelId();
doReturn(vfModuleIdentifiers).when(vfModuleTopologyInformation).getVfModuleIdentifiers();
SdncRequestHeader sdncRequestHeader = mock(SdncRequestHeader.class);
doReturn(sdncRequestHeader).when(preloadVnfTopologyOperationInput).getSdncRequestHeader();
doReturn(svcRequestId).when(sdncRequestHeader).getSvcRequestId();
doReturn(true).when(vnfsdnSvcLogicServiceClient).hasGraph(any(), any(), any(), any());
Future<RpcResult<PreloadVfModuleTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.preloadVfModuleTopologyOperation(preloadVnfTopologyOperationInput);
Assert.assertEquals("200", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals(null, rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Error case:
* <p>
* <code>input.getNetworkTopologyInformation() == null</code>
*
* @throws Exception
*/
@Test public void preloadNetworkTopologyOperationErrorOne() throws Exception {
PreloadNetworkTopologyOperationInput PreloadNetworkTopologyOperationInput =
mock(PreloadNetworkTopologyOperationInput.class);
doReturn(null).when(PreloadNetworkTopologyOperationInput).getNetworkTopologyInformation();
Future<RpcResult<PreloadNetworkTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.preloadNetworkTopologyOperation(PreloadNetworkTopologyOperationInput);
Assert.assertEquals("403", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals("input, null or empty network-name or network-type",
rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Error case:
* <p>
* <code>preload_name == ""</code>
* ANd
* <code>preload_type == ""ss</code>
*
* @throws Exception
*/
@Test public void preloadNetworkTopologyOperationErrorTwo() throws Exception {
String networkName = "";
String networkType = "NetworkType";
PreloadNetworkTopologyOperationInput PreloadNetworkTopologyOperationInput =
mock(PreloadNetworkTopologyOperationInput.class);
NetworkTopologyInformation networkTopologyInformation = mock(NetworkTopologyInformation.class);
doReturn(networkTopologyInformation).when(PreloadNetworkTopologyOperationInput).getNetworkTopologyInformation();
NetworkTopologyIdentifier networkTopologyIdentifier = mock(NetworkTopologyIdentifier.class);
doReturn(networkTopologyIdentifier).when(networkTopologyInformation).getNetworkTopologyIdentifier();
doReturn(networkName).when(networkTopologyIdentifier).getNetworkName();
doReturn(networkType).when(networkTopologyIdentifier).getNetworkType();
Future<RpcResult<PreloadNetworkTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.preloadNetworkTopologyOperation(PreloadNetworkTopologyOperationInput);
Assert.assertEquals("403", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals("input, invalid preload-name", rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
networkName = "NetworkName";
networkType = "";
doReturn(networkName).when(networkTopologyIdentifier).getNetworkName();
doReturn(networkType).when(networkTopologyIdentifier).getNetworkType();
rpcResultFuture = vnfapiProvider.preloadNetworkTopologyOperation(PreloadNetworkTopologyOperationInput);
Assert.assertEquals("403", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals("input, invalid preload-type", rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Error case:
* <p>
* <code>svcLogicClient.hasGraph("VNF-API",SVC_OPERATION,null,"sync" = false</code>
*
* @throws Exception
*/
@Test public void preloadNetworkTopologyOperationErrorThree() throws Exception {
String networkName = "NetworkName";
String networkType = "NetworkType";
PreloadNetworkTopologyOperationInput PreloadNetworkTopologyOperationInput =
mock(PreloadNetworkTopologyOperationInput.class);
NetworkTopologyInformation networkTopologyInformation = mock(NetworkTopologyInformation.class);
doReturn(networkTopologyInformation).when(PreloadNetworkTopologyOperationInput).getNetworkTopologyInformation();
NetworkTopologyIdentifier networkTopologyIdentifier = mock(NetworkTopologyIdentifier.class);
doReturn(networkTopologyIdentifier).when(networkTopologyInformation).getNetworkTopologyIdentifier();
doReturn(networkName).when(networkTopologyIdentifier).getNetworkName();
doReturn(networkType).when(networkTopologyIdentifier).getNetworkType();
SdncRequestHeader sdncRequestHeader = mock(SdncRequestHeader.class);
doReturn(sdncRequestHeader).when(PreloadNetworkTopologyOperationInput).getSdncRequestHeader();
doReturn(svcRequestId).when(sdncRequestHeader).getSvcRequestId();
Future<RpcResult<PreloadNetworkTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.preloadNetworkTopologyOperation(PreloadNetworkTopologyOperationInput);
Assert.assertEquals("503", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertTrue(
rpcResultFuture.get().getResult().getResponseMessage().contains("No service logic active for VNF-API"));
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Success case
*
* @throws Exception
*/
@Test public void preloadNetworkTopologyOperationErrorFour() throws Exception {
String networkName = "NetworkName";
String networkType = "NetworkType";
PreloadNetworkTopologyOperationInput PreloadNetworkTopologyOperationInput =
mock(PreloadNetworkTopologyOperationInput.class);
NetworkTopologyInformation networkTopologyInformation = mock(NetworkTopologyInformation.class);
doReturn(networkTopologyInformation).when(PreloadNetworkTopologyOperationInput).getNetworkTopologyInformation();
NetworkTopologyIdentifier networkTopologyIdentifier = mock(NetworkTopologyIdentifier.class);
doReturn(networkTopologyIdentifier).when(networkTopologyInformation).getNetworkTopologyIdentifier();
doReturn(networkName).when(networkTopologyIdentifier).getNetworkName();
doReturn(networkType).when(networkTopologyIdentifier).getNetworkType();
SdncRequestHeader sdncRequestHeader = mock(SdncRequestHeader.class);
doReturn(sdncRequestHeader).when(PreloadNetworkTopologyOperationInput).getSdncRequestHeader();
doReturn(svcRequestId).when(sdncRequestHeader).getSvcRequestId();
doReturn(true).when(vnfsdnSvcLogicServiceClient).hasGraph(any(), any(), any(), any());
doReturn(null).when(dataBroker).newWriteOnlyTransaction();
Future<RpcResult<PreloadNetworkTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.preloadNetworkTopologyOperation(PreloadNetworkTopologyOperationInput);
Assert.assertEquals("500", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals("java.lang.NullPointerException", rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
/**
* Test Success case
*
* @throws Exception
*/
@Test public void preloadNetworkTopologyOperationSuccess() throws Exception {
String networkName = "NetworkName";
String networkType = "NetworkType";
PreloadNetworkTopologyOperationInput PreloadNetworkTopologyOperationInput =
mock(PreloadNetworkTopologyOperationInput.class);
NetworkTopologyInformation networkTopologyInformation = mock(NetworkTopologyInformation.class);
doReturn(networkTopologyInformation).when(PreloadNetworkTopologyOperationInput).getNetworkTopologyInformation();
NetworkTopologyIdentifier networkTopologyIdentifier = mock(NetworkTopologyIdentifier.class);
doReturn(networkTopologyIdentifier).when(networkTopologyInformation).getNetworkTopologyIdentifier();
doReturn(networkName).when(networkTopologyIdentifier).getNetworkName();
doReturn(networkType).when(networkTopologyIdentifier).getNetworkType();
SdncRequestHeader sdncRequestHeader = mock(SdncRequestHeader.class);
doReturn(sdncRequestHeader).when(PreloadNetworkTopologyOperationInput).getSdncRequestHeader();
doReturn(svcRequestId).when(sdncRequestHeader).getSvcRequestId();
doReturn(true).when(vnfsdnSvcLogicServiceClient).hasGraph(any(), any(), any(), any());
Future<RpcResult<PreloadNetworkTopologyOperationOutput>> rpcResultFuture =
vnfapiProvider.preloadNetworkTopologyOperation(PreloadNetworkTopologyOperationInput);
Assert.assertEquals("200", rpcResultFuture.get().getResult().getResponseCode());
Assert.assertEquals(null, rpcResultFuture.get().getResult().getResponseMessage());
Assert.assertEquals("Y", rpcResultFuture.get().getResult().getAckFinalIndicator());
}
@Test public void getVfModuleServiceData() throws Exception {
// Three parameters: siid, vfModuleServiceDataBuilder, LogicalDatastoreType
String ssid = "ssid";
VfModuleServiceDataBuilder vfModuleServiceDataBuilder = spy(new VfModuleServiceDataBuilder());
Optional<VfModuleList> optional = mock(Optional.class);
doReturn(optional).when(checkedFuture).get();
doReturn(true).when(optional).isPresent();
VfModuleList vfModuleList = mock(VfModuleList.class);
doReturn(vfModuleList).when(optional).get();
VfModuleServiceData vfModuleServiceData = mock(VfModuleServiceData.class);
doReturn(vfModuleServiceData).when(vfModuleList).getVfModuleServiceData();
SdncRequestHeader sdncRequestHeader = mock(SdncRequestHeader.class);
doReturn(sdncRequestHeader).when(vfModuleServiceData).getSdncRequestHeader();
Whitebox.invokeMethod(vnfapiProvider, "getVfModuleServiceData", ssid, vfModuleServiceDataBuilder,
LogicalDatastoreType.CONFIGURATION);
Assert.assertEquals(sdncRequestHeader, vfModuleServiceDataBuilder.getSdncRequestHeader());
//With Two parameters: siid, vfModuleServiceDataBuilder
Whitebox.invokeMethod(vnfapiProvider, "getVfModuleServiceData", ssid, vfModuleServiceDataBuilder);
Assert.assertEquals(sdncRequestHeader, vfModuleServiceDataBuilder.getSdncRequestHeader());
}
@Test public void getPreloadData() throws Exception {
// Four parameters:
// String preload_name, String preload_type, PreloadDataBuilder preloadDataBuilder, LogicalDatastoreType type
PreloadDataBuilder preloadDataBuilder = spy(new PreloadDataBuilder());
// mock optional
Optional<VnfPreloadList> optional = mock(Optional.class);
doReturn(optional).when(checkedFuture).get();
doReturn(true).when(optional).isPresent();
VnfPreloadList vnfPreloadList = mock(VnfPreloadList.class);
doReturn(vnfPreloadList).when(optional).get();
PreloadData preloadData = mock(PreloadData.class);
doReturn(preloadData).when(vnfPreloadList).getPreloadData();
VnfTopologyInformation vnfTopologyInformation = mock(VnfTopologyInformation.class);
doReturn(vnfTopologyInformation).when(preloadData).getVnfTopologyInformation();
Whitebox.invokeMethod(vnfapiProvider, "getPreloadData", "preloadName", "preloadType", preloadDataBuilder,
LogicalDatastoreType.CONFIGURATION);
Assert.assertEquals(vnfTopologyInformation, preloadDataBuilder.getVnfTopologyInformation());
// Three parameters:
// String preload_name, String preload_type, PreloadDataBuilder preloadDataBuilder, LogicalDatastoreType type
Whitebox.invokeMethod(vnfapiProvider, "getPreloadData", "preloadName", "preloadType", preloadDataBuilder);
Assert.assertEquals(vnfTopologyInformation, preloadDataBuilder.getVnfTopologyInformation());
}
@Test public void getVnfInstancePreloadData() throws Exception {
// Four parameters:
// String preload_name, String preload_type, VnfInstancePreloadDataBuilder preloadDataBuilder,
// LogicalDatastoreType type
VnfInstancePreloadDataBuilder vnfInstancePreloadDataBuilder = spy(new VnfInstancePreloadDataBuilder());
// mock optional
Optional<VnfPreloadList> optional = mock(Optional.class);
doReturn(optional).when(checkedFuture).get();
doReturn(true).when(optional).isPresent();
VnfInstancePreloadList vnfInstancePreloadList = mock(VnfInstancePreloadList.class);
doReturn(vnfInstancePreloadList).when(optional).get();
VnfInstancePreloadData vnfInstancePreloadData = mock(VnfInstancePreloadData.class);
doReturn(vnfInstancePreloadData).when(vnfInstancePreloadList).getVnfInstancePreloadData();
VnfInstanceTopologyInformation vnfInstanceTopologyInformation = mock(VnfInstanceTopologyInformation.class);
doReturn(vnfInstanceTopologyInformation).when(vnfInstancePreloadData).getVnfInstanceTopologyInformation();
Whitebox.invokeMethod(vnfapiProvider, "getVnfInstancePreloadData", "preloadName", "preloadType",
vnfInstancePreloadDataBuilder, LogicalDatastoreType.CONFIGURATION);
Assert.assertEquals(vnfInstanceTopologyInformation,
vnfInstancePreloadDataBuilder.getVnfInstanceTopologyInformation());
// Three Parameters:
// String preload_name, String preload_type, VnfInstancePreloadDataBuilder preloadDataBuilder
Whitebox.invokeMethod(vnfapiProvider, "getVnfInstancePreloadData", "preloadName", "preloadType",
vnfInstancePreloadDataBuilder);
Assert.assertEquals(vnfInstanceTopologyInformation,
vnfInstancePreloadDataBuilder.getVnfInstanceTopologyInformation());
}
@Test public void getVfModulePreloadData() throws Exception {
// Four Parameters
// String preload_name, String preload_type, VfModulePreloadDataBuilder preloadDataBuilder,
// LogicalDatastoreType type
VfModulePreloadDataBuilder vfModulePreloadDataBuilder = spy(new VfModulePreloadDataBuilder());
// mock optional
Optional<VfModulePreloadList> optional = mock(Optional.class);
doReturn(optional).when(checkedFuture).get();
doReturn(true).when(optional).isPresent();
VfModulePreloadList vfModulePreloadList = mock(VfModulePreloadList.class);
doReturn(vfModulePreloadList).when(optional).get();
VfModulePreloadData vfModulePreloadData = mock(VfModulePreloadData.class);
doReturn(vfModulePreloadData).when(vfModulePreloadList).getVfModulePreloadData();
VfModuleTopologyInformation vfModuleTopologyInformation = mock(VfModuleTopologyInformation.class);
doReturn(vfModuleTopologyInformation).when(vfModulePreloadData).getVfModuleTopologyInformation();
Whitebox.invokeMethod(vnfapiProvider, "getVfModulePreloadData", "preloadName", "preloadType",
vfModulePreloadDataBuilder, LogicalDatastoreType.CONFIGURATION);
Assert.assertEquals(vfModuleTopologyInformation, vfModulePreloadDataBuilder.getVfModuleTopologyInformation());
// Three Parameters:
// String vnf_name, String vnf_type, VfModulePreloadDataBuilder preloadDataBuilder
Whitebox.invokeMethod(vnfapiProvider, "getVfModulePreloadData", "preloadName", "preloadType",
vfModulePreloadDataBuilder);
Assert.assertEquals(vfModuleTopologyInformation, vfModulePreloadDataBuilder.getVfModuleTopologyInformation());
}
/**
* With ServiceStatusBuilder, RequestInformation
*/
@Test public void setServiceStatusOne() throws Exception {
// VNFActivateRequest
RequestInformation requestInformation = mock(RequestInformation.class);
ServiceStatusBuilder serviceStatusBuilder = spy(new ServiceStatusBuilder());
doReturn(RequestInformation.RequestAction.VNFActivateRequest).when(requestInformation).getRequestAction();
doReturn(RequestInformation.RequestSubAction.SUPP).when(requestInformation).getRequestSubAction();
Whitebox.invokeMethod(vnfapiProvider, "setServiceStatus", serviceStatusBuilder, requestInformation);
Assert.assertEquals(ServiceStatus.VnfsdnAction.VNFActivateRequest, serviceStatusBuilder.getVnfsdnAction());
//ChangeVNFActivateRequest
doReturn(RequestInformation.RequestAction.ChangeVNFActivateRequest).when(requestInformation).getRequestAction();
doReturn(RequestInformation.RequestSubAction.CANCEL).when(requestInformation).getRequestSubAction();
Whitebox.invokeMethod(vnfapiProvider, "setServiceStatus", serviceStatusBuilder, requestInformation);
Assert
.assertEquals(ServiceStatus.VnfsdnAction.ChangeVNFActivateRequest, serviceStatusBuilder.getVnfsdnAction());
//DisconnectVNFRequest
doReturn(RequestInformation.RequestAction.DisconnectVNFRequest).when(requestInformation).getRequestAction();
Whitebox.invokeMethod(vnfapiProvider, "setServiceStatus", serviceStatusBuilder, requestInformation);
Assert.assertEquals(ServiceStatus.VnfsdnAction.DisconnectVNFRequest, serviceStatusBuilder.getVnfsdnAction());
//PreloadVNFRequest
doReturn(RequestInformation.RequestAction.PreloadVNFRequest).when(requestInformation).getRequestAction();
Whitebox.invokeMethod(vnfapiProvider, "setServiceStatus", serviceStatusBuilder, requestInformation);
Assert.assertEquals(ServiceStatus.VnfsdnAction.PreloadVNFRequest, serviceStatusBuilder.getVnfsdnAction());
//DeletePreloadVNFRequest
doReturn(RequestInformation.RequestAction.DeletePreloadVNFRequest).when(requestInformation).getRequestAction();
Whitebox.invokeMethod(vnfapiProvider, "setServiceStatus", serviceStatusBuilder, requestInformation);
Assert.assertEquals(ServiceStatus.VnfsdnAction.DeletePreloadVNFRequest, serviceStatusBuilder.getVnfsdnAction());
//VnfInstanceActivateRequest
doReturn(RequestInformation.RequestAction.VnfInstanceActivateRequest).when(requestInformation)
.getRequestAction();
Whitebox.invokeMethod(vnfapiProvider, "setServiceStatus", serviceStatusBuilder, requestInformation);
Assert.assertEquals(ServiceStatus.VnfsdnAction.VnfInstanceActivateRequest,
serviceStatusBuilder.getVnfsdnAction());
//ChangeVnfInstanceActivateRequest
doReturn(RequestInformation.RequestAction.ChangeVnfInstanceActivateRequest).when(requestInformation)
.getRequestAction();
Whitebox.invokeMethod(vnfapiProvider, "setServiceStatus", serviceStatusBuilder, requestInformation);
Assert.assertEquals(ServiceStatus.VnfsdnAction.ChangeVnfInstanceActivateRequest,
serviceStatusBuilder.getVnfsdnAction());
//DisconnectVnfInstanceRequest
doReturn(RequestInformation.RequestAction.DisconnectVnfInstanceRequest).when(requestInformation)
.getRequestAction();
Whitebox.invokeMethod(vnfapiProvider, "setServiceStatus", serviceStatusBuilder, requestInformation);
Assert.assertEquals(ServiceStatus.VnfsdnAction.DisconnectVnfInstanceRequest,
serviceStatusBuilder.getVnfsdnAction());
//PreloadVnfInstanceRequest
doReturn(RequestInformation.RequestAction.PreloadVnfInstanceRequest).when(requestInformation)
.getRequestAction();
Whitebox.invokeMethod(vnfapiProvider, "setServiceStatus", serviceStatusBuilder, requestInformation);
Assert
.assertEquals(ServiceStatus.VnfsdnAction.PreloadVnfInstanceRequest, serviceStatusBuilder.getVnfsdnAction());
//VfModuleActivateRequest
doReturn(RequestInformation.RequestAction.VfModuleActivateRequest).when(requestInformation).getRequestAction();
Whitebox.invokeMethod(vnfapiProvider, "setServiceStatus", serviceStatusBuilder, requestInformation);
Assert.assertEquals(ServiceStatus.VnfsdnAction.VfModuleActivateRequest, serviceStatusBuilder.getVnfsdnAction());
//ChangeVfModuleActivateRequest
doReturn(RequestInformation.RequestAction.ChangeVfModuleActivateRequest).when(requestInformation)
.getRequestAction();
Whitebox.invokeMethod(vnfapiProvider, "setServiceStatus", serviceStatusBuilder, requestInformation);
Assert.assertEquals(ServiceStatus.VnfsdnAction.ChangeVfModuleActivateRequest,
serviceStatusBuilder.getVnfsdnAction());
//DisconnectVfModuleRequest
doReturn(RequestInformation.RequestAction.DisconnectVfModuleRequest).when(requestInformation)
.getRequestAction();
Whitebox.invokeMethod(vnfapiProvider, "setServiceStatus", serviceStatusBuilder, requestInformation);
Assert
.assertEquals(ServiceStatus.VnfsdnAction.DisconnectVfModuleRequest, serviceStatusBuilder.getVnfsdnAction());
//PreloadVfModuleRequest
doReturn(RequestInformation.RequestAction.PreloadVfModuleRequest).when(requestInformation).getRequestAction();
Whitebox.invokeMethod(vnfapiProvider, "setServiceStatus", serviceStatusBuilder, requestInformation);
Assert.assertEquals(ServiceStatus.VnfsdnAction.PreloadVfModuleRequest, serviceStatusBuilder.getVnfsdnAction());
}
@Test public void getServiceData() throws Exception {
ServiceDataBuilder serviceDataBuilder = spy(new ServiceDataBuilder());
// mock optional
Optional<VnfList> optional = mock(Optional.class);
doReturn(optional).when(checkedFuture).get();
doReturn(true).when(optional).isPresent();
VnfList vnfList = mock(VnfList.class);
doReturn(vnfList).when(optional).get();
ServiceData serviceData = mock(ServiceData.class);
doReturn(serviceData).when(vnfList).getServiceData();
SdncRequestHeader sdncRequestHeader = mock(SdncRequestHeader.class);
doReturn(sdncRequestHeader).when(serviceData).getSdncRequestHeader();
Whitebox.invokeMethod(vnfapiProvider, "getServiceData", "siid", serviceDataBuilder,
LogicalDatastoreType.CONFIGURATION);
Assert.assertEquals(sdncRequestHeader, serviceDataBuilder.getSdncRequestHeader());
}
@Test public void getVnfInstanceServiceData() throws Exception {
VnfInstanceServiceDataBuilder vnfInstanceServiceDataBuilder = spy(new VnfInstanceServiceDataBuilder());
// mock optional
Optional<VnfList> optional = mock(Optional.class);
doReturn(optional).when(checkedFuture).get();
doReturn(true).when(optional).isPresent();
VnfInstanceList vnfInstanceList = mock(VnfInstanceList.class);
doReturn(vnfInstanceList).when(optional).get();
VnfInstanceServiceData vnfInstanceServiceData = mock(VnfInstanceServiceData.class);
doReturn(vnfInstanceServiceData).when(vnfInstanceList).getVnfInstanceServiceData();
SdncRequestHeader sdncRequestHeader = mock(SdncRequestHeader.class);
doReturn(sdncRequestHeader).when(vnfInstanceServiceData).getSdncRequestHeader();
Whitebox.invokeMethod(vnfapiProvider, "getVnfInstanceServiceData", "siid", vnfInstanceServiceDataBuilder,
LogicalDatastoreType.CONFIGURATION);
Assert.assertEquals(sdncRequestHeader, vnfInstanceServiceDataBuilder.getSdncRequestHeader());
}
@Test public void DeleteVnfList() throws Exception {
LogicalDatastoreType configuration = LogicalDatastoreType.CONFIGURATION;
VnfList vnfList = mock(VnfList.class);
VnfListKey vnfListKey = mock(VnfListKey.class);
doReturn(vnfListKey).when(vnfList).key();
InstanceIdentifier<VnfList> vnfListInstanceIdentifier = mock(InstanceIdentifier.class);
dataBroker.newWriteOnlyTransaction().put(configuration, vnfListInstanceIdentifier, vnfList);
Whitebox.invokeMethod(vnfapiProvider, "DeleteVnfList", vnfList, configuration);
verify(dataBroker, times(2)).newWriteOnlyTransaction();
}
}
|
9234619ead30d58932fd7654ea8664285c48e6bc | 2,981 | java | Java | src/main/java/ru/hollowhorizon/hc/common/story/dialogues/DialogueIterator.java | HollowHorizon/HollowCore | 6447f6009fa7e8332d98e34d4674b77e41f5b67f | [
"MIT"
] | 8 | 2022-01-22T19:56:54.000Z | 2022-03-25T18:10:39.000Z | src/main/java/ru/hollowhorizon/hc/common/story/dialogues/DialogueIterator.java | HollowHorizon/HollowCore | 6447f6009fa7e8332d98e34d4674b77e41f5b67f | [
"MIT"
] | 1 | 2022-01-26T13:59:21.000Z | 2022-01-27T06:28:38.000Z | src/main/java/ru/hollowhorizon/hc/common/story/dialogues/DialogueIterator.java | HollowHorizon/HollowCore | 6447f6009fa7e8332d98e34d4674b77e41f5b67f | [
"MIT"
] | 1 | 2022-01-28T12:06:26.000Z | 2022-01-28T12:06:26.000Z | 37.2625 | 136 | 0.67729 | 996,905 | package ru.hollowhorizon.hc.common.story.dialogues;
import ru.hollowhorizon.hc.common.network.NetworkHandler;
import ru.hollowhorizon.hc.common.network.messages.DialogueChoiceToServer;
import java.util.function.Consumer;
public class DialogueIterator {
private HollowDialogue dialogue;
public DialogueIterator(HollowDialogue dialogue) {
this.dialogue = dialogue.copy();
}
public boolean hasNext() {
return dialogue.getAllPhrases().size() > 0 || dialogue.getParent() != null;
}
public void prepareChoices(Consumer<DialogueComponent.DialogueChoiceComponent> onPrepare) {
Object component = nextNoUpdate();
if (component instanceof DialogueComponent.DialogueChoiceComponent) {
onPrepare.accept((DialogueComponent.DialogueChoiceComponent) component);
}
}
public boolean isChoiceNow() {
if (dialogue.getAllPhrases().size() == 0) return false;
Object object = dialogue.getAllPhrases().get(0);
return object instanceof DialogueComponent.DialogueChoiceComponent;
}
public void processDialogueComponent(
Consumer<DialogueComponent.DialogueTextComponent> ifText,
Consumer<DialogueComponent.DialogueChoiceComponent> ifChoice,
Consumer<DialogueComponent.DialogueEffectComponent> ifEffect
) {
Object component = next();
if (component instanceof DialogueComponent.DialogueTextComponent) {
ifText.accept((DialogueComponent.DialogueTextComponent) component);
} else if (component instanceof DialogueComponent.DialogueChoiceComponent) {
ifChoice.accept((DialogueComponent.DialogueChoiceComponent) component);
} else if (component instanceof DialogueComponent.DialogueEffectComponent) {
ifEffect.accept((DialogueComponent.DialogueEffectComponent) component);
}
removeCurrent();
}
private IDialoguePart next() {
if (dialogue.getAllPhrases().size() > 0) return dialogue.getAllPhrases().get(0);
else {
HollowDialogue parent = dialogue.getParent();
if (parent != null) {
this.dialogue = parent.copy();
removeCurrent();
return next();
} else {
return null;
}
}
}
private IDialoguePart nextNoUpdate() {
if (dialogue.getAllPhrases().size() > 0) return dialogue.getAllPhrases().get(0);
return null;
}
private void removeCurrent() {
dialogue.getAllPhrases().remove(0);
}
public void makeChoice(DialogueComponent.DialogueChoiceComponent component, ChoiceTextComponent buttonChoice, String dialogueName) {
if (buttonChoice != null) {
this.dialogue = component.getDialogueByChoice(buttonChoice).copy();
NetworkHandler.sendMessageToServer(new DialogueChoiceToServer(dialogueName + "_" + buttonChoice.getRegName()));
}
}
}
|
923463b9d5586887a6c2b5102abec1a076223dd1 | 8,196 | java | Java | src/main/java/com/intellij/gitlab/ui/panels/pipeline/GitLabPipeLineJobsPanel.java | Priytam/gitlab-intellij-plugin | a7a2a9f09cb990644957f9e05c8be3d447b3ef43 | [
"Apache-2.0"
] | 1 | 2021-05-02T19:26:46.000Z | 2021-05-02T19:26:46.000Z | src/main/java/com/intellij/gitlab/ui/panels/pipeline/GitLabPipeLineJobsPanel.java | Priytam/gitlab-intellij-plugin | a7a2a9f09cb990644957f9e05c8be3d447b3ef43 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/intellij/gitlab/ui/panels/pipeline/GitLabPipeLineJobsPanel.java | Priytam/gitlab-intellij-plugin | a7a2a9f09cb990644957f9e05c8be3d447b3ef43 | [
"Apache-2.0"
] | null | null | null | 39.980488 | 132 | 0.695949 | 996,906 | package com.intellij.gitlab.ui.panels.pipeline;
import com.google.common.collect.Lists;
import com.intellij.gitlab.actions.GitLabPipelineActionGroup;
import com.intellij.gitlab.server.GitLabServerManager;
import com.intellij.gitlab.tasks.JobRetryTask;
import com.intellij.gitlab.ui.panels.AbstractGitLabPanel;
import com.intellij.gitlab.util.GitLabLabelUtil;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.project.Project;
import com.intellij.ui.JBColor;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBPanel;
import com.intellij.util.ui.JBUI;
import org.apache.commons.collections.CollectionUtils;
import org.gitlab4j.api.GitLabApi;
import org.gitlab4j.api.models.Job;
import org.gitlab4j.api.models.JobStatus;
import org.gitlab4j.api.models.Pipeline;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static com.intellij.gitlab.util.GitLabLabelUtil.BOLD;
import static com.intellij.gitlab.util.GitLabLabelUtil.CANCELED_COLOR;
import static com.intellij.gitlab.util.GitLabLabelUtil.DONE_COLOR;
import static com.intellij.gitlab.util.GitLabLabelUtil.FAILED_COLOR;
import static com.intellij.gitlab.util.GitLabLabelUtil.HAND_CURSOR;
import static com.intellij.gitlab.util.GitLabLabelUtil.IN_PROGRESS_COLOR;
import static com.intellij.gitlab.util.GitLabLabelUtil.MANUAL_COLOR;
import static com.intellij.gitlab.util.GitLabLabelUtil.PENDING_COLOR;
import static com.intellij.gitlab.util.GitLabLabelUtil.SKIPPED_COLOR;
import static com.intellij.gitlab.util.GitLabLabelUtil.UNDEFINED_COLOR;
import static com.intellij.gitlab.util.GitLabLabelUtil.createEmptyLabel;
import static com.intellij.gitlab.util.GitLabLabelUtil.createEmptyStatusLabel;
import static com.intellij.gitlab.util.GitLabLabelUtil.createLabel;
import static com.intellij.gitlab.util.GitLabLabelUtil.createLinkLabel;
import static com.intellij.gitlab.util.GitLabPanelUtil.MARGIN_BOTTOM;
import static com.intellij.gitlab.util.GitLabPanelUtil.createWhitePanel;
import static com.intellij.openapi.util.text.StringUtil.toUpperCase;
import static java.awt.BorderLayout.CENTER;
import static java.awt.BorderLayout.LINE_START;
import static javax.swing.BoxLayout.Y_AXIS;
import static javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER;
import static javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
public class GitLabPipeLineJobsPanel extends AbstractGitLabPanel<Pipeline> {
private final org.gitlab4j.api.models.Project selectedProject;
private final Project project;
private final Pipeline pipeline;
public GitLabPipeLineJobsPanel(Project project, org.gitlab4j.api.models.Project selectedProject, Pipeline pipeline) {
super(true, true, pipeline);
this.project = project;
this.selectedProject = selectedProject;
this.pipeline = pipeline;
setBackground(JBColor.white);
initContent(getJobs());
}
@Override
public ActionGroup getActionGroup() {
GitLabPipelineActionGroup group = new GitLabPipelineActionGroup(this);
//group.add(new TransitIssueDialogAction(() -> null));
//group.add(new GitLabPipelineAssigneePopupAction(() -> null));
//group.add(new GitLabPipelinePrioritiesPopupAction(() -> null));
return group;
}
private void initContent(List<Job> jobs) {
JPanel jobDetails = new JBPanel().withBackground(JBColor.WHITE);
jobDetails.setLayout(new BoxLayout(jobDetails, Y_AXIS));
if (CollectionUtils.isNotEmpty(jobs)) {
Map<String, List<Job>> groupedJobs = getGroupedJobs(jobs);
groupedJobs.forEach((stage, jobList) -> {
JPanel stagePanel = getStagePanel(stage);
jobDetails.add(stagePanel);
jobList.forEach(job -> {
JPanel jobPanel = prepareJobPanel(job);
jobDetails.add(jobPanel);
});
});
}
JBPanel panel = new JBPanel(new BorderLayout())
.withBackground(JBColor.WHITE)
.withBorder(JBUI.Borders.empty(1, 0));
panel.add(ScrollPaneFactory.createScrollPane(jobDetails, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_NEVER), CENTER);
setContent(panel);
}
private JPanel prepareJobPanel(Job job) {
JPanel panel = createWhitePanel(new GridLayout(1, 4)).withBorder(MARGIN_BOTTOM);
panel.add(createLinkLabel(String.valueOf(job.getId()), job.getWebUrl()));
panel.add(createLabel(job.getName()));
panel.add(createLabel(getDuration(job.getDuration())));
panel.add(createStatusLabel(job));
panel.add(createActionButton(job));
return panel;
}
private Component createActionButton(Job job) {
if (job.getStatus().equals(JobStatus.SUCCESS) || job.getStatus().equals(JobStatus.FAILED)) {
return getButtonLabel("Retry", job, AllIcons.Actions.Restart);
}
if (job.getStatus().equals(JobStatus.MANUAL)) {
return getButtonLabel("Play", job, AllIcons.RunConfigurations.TestState.Run);
}
return createEmptyLabel();
}
@NotNull
private JBLabel getButtonLabel(String text, Job job, Icon icon) {
JBLabel watchLabel = createLabel(text);
watchLabel.setBackground(JBColor.WHITE);
watchLabel.setBorder(JBUI.Borders.empty(2, 20));
watchLabel.setCursor(HAND_CURSOR);
watchLabel.setIcon(icon);
watchLabel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
SwingUtilities.invokeLater(() -> new JobRetryTask(project, job.getId(), selectedProject).queue());
}
});
return watchLabel;
}
private Component createStatusLabel(Job job) {
JobStatus status = job.getStatus();
JBLabel statusLabel = createEmptyStatusLabel();
statusLabel.setText(toUpperCase(status.toValue()));
statusLabel.setBackground(getBackgroundColor(status));
statusLabel.setForeground(GitLabLabelUtil.WHITE);
return statusLabel;
}
private Color getBackgroundColor(JobStatus status) {
switch (status) {
case FAILED:
return FAILED_COLOR;
case MANUAL:
return MANUAL_COLOR;
case RUNNING:
return IN_PROGRESS_COLOR;
case PENDING:
return PENDING_COLOR;
case SUCCESS:
return DONE_COLOR;
case CANCELED:
return CANCELED_COLOR;
case SKIPPED:
return SKIPPED_COLOR;
default:
return UNDEFINED_COLOR;
}
}
private String getDuration(Float floatValue) {
int secs = floatValue == null ? 0 : floatValue.intValue();
return (secs / 3600) + ":" + ((secs % 3600) / 60) + ":" + (secs % 60);
}
@NotNull
private Map<String, List<Job>> getGroupedJobs(List<Job> jobs) {
return jobs.stream().collect(Collectors.toMap(Job::getStage, Lists::newArrayList, (j1, j2) -> {
j1.addAll(j2);
return j1;
}));
}
private JPanel getStagePanel(String name) {
JPanel typePanel = createWhitePanel(new BorderLayout())
.withBackground(JBColor.LIGHT_GRAY)
.withBorder(JBUI.Borders.empty(4, 30));
JBLabel typeLabel = createLabel(name).withFont(BOLD);
typePanel.add(typeLabel, LINE_START);
return typePanel;
}
private List<Job> getJobs() {
try {
GitLabApi gitLabApi = project.getComponent(GitLabServerManager.class).getGitLabApi();
return gitLabApi.getJobApi().getJobsForPipeline(selectedProject, pipeline.getId());
} catch (Exception e) {
return new ArrayList<>();
}
}
}
|
923465030608f3ccf63ad47013a98f9b5c8ffc97 | 3,411 | java | Java | protocol-kerberos/src/main/java/org/apache/directory/server/kerberos/sam/SamVerifier.java | mchoma/directory-server | 1399b77e0205b8b5dd8f67fe188f8fc99979ca8e | [
"Apache-2.0"
] | null | null | null | protocol-kerberos/src/main/java/org/apache/directory/server/kerberos/sam/SamVerifier.java | mchoma/directory-server | 1399b77e0205b8b5dd8f67fe188f8fc99979ca8e | [
"Apache-2.0"
] | null | null | null | protocol-kerberos/src/main/java/org/apache/directory/server/kerberos/sam/SamVerifier.java | mchoma/directory-server | 1399b77e0205b8b5dd8f67fe188f8fc99979ca8e | [
"Apache-2.0"
] | null | null | null | 33.184466 | 86 | 0.706554 | 996,907 | /*
* 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.directory.server.kerberos.sam;
import javax.naming.directory.DirContext;
import javax.security.auth.kerberos.KerberosKey;
import javax.security.auth.kerberos.KerberosPrincipal;
import org.apache.directory.shared.kerberos.codec.types.SamType;
/**
* Single-use Authentication Mechanism verifier (subsystem) interface.
* SamVerifiers are modules that can be configured and are dynamically
* loaded as needed. Implementations have a few requirements and things
* implementors should know:
*
* <ul>
* <li>A public default constructor is required,</li>
* <li>after instantitation environment properties are supplied,</li>
* <li>next the KeyIntegrityChecker is set for the verifier,</li>
* <li>finally the verifier is started up by calling startup(),
* incidentally this is where all initialization work should be
* done using the environment properties supplied.
* </li>
* </ul>
*
* @author <a href="mailto:dycjh@example.com">Apache Directory Project</a>
*/
public interface SamVerifier
{
/**
* Starts one of many pluggable SAM type subsystem.
*
* @throws SamException
*/
void startup() throws SamException;
/**
* Shuts down one of many pluggable SAM type subsystem.
*/
void shutdown();
/**
* SamVerifiers require a KeyIntegrityChecker to calculate the integrity of
* a generated KerberosKey. The Kerberos service exposes this interface
* and supplies it to the verifier to check generated keys to conduct the
* verification workflow.
*
* @param keyChecker The integrity checker that validates whether or not a
* key can decrypt-decode preauth data (an encryped-encoded generalized
* timestamp).
*/
void setIntegrityChecker( KeyIntegrityChecker keyChecker );
/**
* Verifies the single use password supplied.
*
* @param principal The kerberos principal to use.
* @param sad Single-use authentication data (encrypted generalized timestamp).
* @return The {@link KerberosKey}.
* @throws SamException
*/
KerberosKey verify( KerberosPrincipal principal, byte[] sad ) throws SamException;
/**
* Gets the registered SAM algorithm type implemented by this SamVerifier.
*
* @return The type value for the SAM algorithm used to verify the SUP.
*/
SamType getSamType();
/**
* Sets the user context where users are stored for the primary realm.
*
* @param userContext
*/
void setUserContext( DirContext userContext );
}
|
923467b99144b143b2e7cb9fb5efc3ac8df54bb3 | 1,660 | java | Java | javaweb-jiajiale-master/jiajiale-web/src/main/java/com/vip/dto/QueryResult.java | xionghaoxh/vip | 9446c68194c1265d9e1fc37f1a8810e92863868e | [
"Apache-2.0"
] | 16 | 2019-07-10T14:10:16.000Z | 2021-06-08T01:20:15.000Z | javaweb-jiajiale-master/jiajiale-web/src/main/java/com/vip/dto/QueryResult.java | xionghaoxh/vip | 9446c68194c1265d9e1fc37f1a8810e92863868e | [
"Apache-2.0"
] | null | null | null | javaweb-jiajiale-master/jiajiale-web/src/main/java/com/vip/dto/QueryResult.java | xionghaoxh/vip | 9446c68194c1265d9e1fc37f1a8810e92863868e | [
"Apache-2.0"
] | null | null | null | 18.651685 | 114 | 0.666265 | 996,908 | package com.vip.dto;
/**
* 公共查询结果DTO
* @author Administrator
*
*/
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
public class QueryResult<T> {
//总记录数
private int totalRows;
//当前页码
private int pageNo;
//每页大小
private int pageSize;
//总页数
private int totalPages=-1;
//当前页记录
private List<T> rows;
public QueryResult() {
}
public int getTotalRows() {
return totalRows;
}
public void setTotalRows(int totalRows) {
this.totalRows = totalRows;
}
public void setTotalRows(long totalRows) {
this.totalRows = (int)totalRows;
}
public int getPageNo() {
return pageNo;
}
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
public int getTotalPages() {
if(totalPages==-1) {
totalPages=totalRows/pageSize;
if(totalRows%pageSize!=0) {
totalPages++;
}
}
return totalPages;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public List<T> getRows() {
return rows;
}
public void setRows(List<T> rows) {
this.rows = rows;
}
public <X>QueryResult<X> rowsMap(Function<T, X> mapper){
QueryResult<X> qr=new QueryResult<>();
qr.setPageNo(this.getPageNo());
qr.setPageSize(this.getPageSize());
qr.setTotalRows(this.getTotalRows());
if(this.rows!=null) {
qr.setRows(this.rows.stream().map(mapper).collect(Collectors.toList()));
}
return qr;
}
@Override
public String toString() {
return "QueryResult [totalRows=" + totalRows + ", pageNo=" + pageNo + ", pageSize=" + pageSize + ", totalPages="
+ totalPages + ", rows=" + rows + "]";
}
}
|
923467d057448d114212577d8877709d17c735c0 | 916 | java | Java | src/graph/CapEdge.java | TenaciousTerrier/Java-Data-Structures | 8c09aa8565681d6a7a09ea9fa2e0481fdb1aade1 | [
"MIT"
] | null | null | null | src/graph/CapEdge.java | TenaciousTerrier/Java-Data-Structures | 8c09aa8565681d6a7a09ea9fa2e0481fdb1aade1 | [
"MIT"
] | null | null | null | src/graph/CapEdge.java | TenaciousTerrier/Java-Data-Structures | 8c09aa8565681d6a7a09ea9fa2e0481fdb1aade1 | [
"MIT"
] | null | null | null | 17.960784 | 68 | 0.677948 | 996,909 | package graph;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
/**
* A class which represents an edge between 2 nodes.
*/
public class CapEdge {
private int startNode;
private int endNode;
private double betweenness;
/**
* Create a new CapEdge between a starting node and an ending node.
*/
public CapEdge(int start, int end) {
startNode = start;
endNode = end;
betweenness = 0.0;
}
/**
* Get the starting node of the edge.
* @return The node where the edge starts.
*/
public int getStartNode() {
return startNode;
}
/**
* Get the ending node of the edge.
* @return The node where the edge ends.
*/
public int getEndNode() {
return endNode;
}
public double getBetweenness() {
return betweenness;
}
public void setBetweenness(double num) {
betweenness = num;
}
}
|
923468079fffeea766ac9eeb6803041456a3070b | 771 | java | Java | AndroidTestingBox/app/src/test/java/com/guddy/android_testing_box/zester/ZesterExampleTest.java | RoRoche/AndroidTestingBox | 814a9136a832ef90d5bbee0a350834b2ca9b4da1 | [
"Apache-2.0"
] | 67 | 2016-11-14T12:22:17.000Z | 2021-11-08T14:21:36.000Z | AndroidTestingBox/app/src/test/java/com/guddy/android_testing_box/zester/ZesterExampleTest.java | RoRoche/AndroidTestingBox | 814a9136a832ef90d5bbee0a350834b2ca9b4da1 | [
"Apache-2.0"
] | 1 | 2017-08-14T13:11:12.000Z | 2017-08-14T13:11:12.000Z | AndroidTestingBox/app/src/test/java/com/guddy/android_testing_box/zester/ZesterExampleTest.java | RoRoche/AndroidTestingBox | 814a9136a832ef90d5bbee0a350834b2ca9b4da1 | [
"Apache-2.0"
] | 5 | 2016-11-15T04:19:32.000Z | 2020-12-08T04:53:02.000Z | 25.7 | 81 | 0.648508 | 996,910 | package com.guddy.android_testing_box.zester;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ZesterExampleTest {
//region Fields
private NameParser mNameParser;
private String[] mNames;
//endregion
//region Lifecycle
@Before
public void setUp() {
mNameParser = new NameParser();
mNames = new String[]{"Mike Jones", "John Doe"};
}
//endregion
//region Test methods
@Test
public void shouldFindPersonByLastName() {
final Person person = mNameParser.findPersonWithLastName(mNames, "Doe");
final String firstName = person.getFirstName();
assertEquals("John", firstName);
}
//endregion
} |
92346b3a5ef46049fff682a1622d44941d1ad569 | 129 | java | Java | ProjectSourceCode/Apache Commons Math v3.5/src/main/java/org/apache/commons/math3/genetics/InvalidRepresentationException.java | yashgolwala/Software_Measurement_Team_M | 3d2aef4c0711b7a02155a42ca6b08bb6c2693d4c | [
"Unlicense"
] | null | null | null | ProjectSourceCode/Apache Commons Math v3.5/src/main/java/org/apache/commons/math3/genetics/InvalidRepresentationException.java | yashgolwala/Software_Measurement_Team_M | 3d2aef4c0711b7a02155a42ca6b08bb6c2693d4c | [
"Unlicense"
] | null | null | null | ProjectSourceCode/Apache Commons Math v3.5/src/main/java/org/apache/commons/math3/genetics/InvalidRepresentationException.java | yashgolwala/Software_Measurement_Team_M | 3d2aef4c0711b7a02155a42ca6b08bb6c2693d4c | [
"Unlicense"
] | 2 | 2019-06-24T22:57:32.000Z | 2019-06-26T16:58:52.000Z | 32.25 | 75 | 0.883721 | 996,911 | version https://git-lfs.github.com/spec/v1
oid sha256:059251b76e354a17a1e5f550a7260726b749791b4e7b7e3a7f901d38019d138f
size 1548
|
92346bf6ee59a4e499128ed216e672e3296c30f0 | 1,731 | java | Java | webapps/src/main/java/org/camunda/bpm/webapp/impl/security/filter/RequestAuthorizer.java | mrFranklin/camunda-bpm-platform | 7c5bf37307d3eeac3aee5724b6e4669a9992eaba | [
"Apache-2.0"
] | 2,577 | 2015-01-02T07:43:55.000Z | 2022-03-31T22:31:45.000Z | webapps/src/main/java/org/camunda/bpm/webapp/impl/security/filter/RequestAuthorizer.java | mrFranklin/camunda-bpm-platform | 7c5bf37307d3eeac3aee5724b6e4669a9992eaba | [
"Apache-2.0"
] | 839 | 2015-01-12T22:06:28.000Z | 2022-03-24T13:26:29.000Z | webapps/src/main/java/org/camunda/bpm/webapp/impl/security/filter/RequestAuthorizer.java | mrFranklin/camunda-bpm-platform | 7c5bf37307d3eeac3aee5724b6e4669a9992eaba | [
"Apache-2.0"
] | 1,270 | 2015-01-02T03:39:25.000Z | 2022-03-31T06:04:37.000Z | 34.62 | 97 | 0.751589 | 996,912 | /*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; 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.camunda.bpm.webapp.impl.security.filter;
import java.util.Map;
import org.camunda.bpm.webapp.impl.security.auth.Authentication;
/**
* The interface for request authorizers.
*
* @author nico.rehwaldt
*/
public interface RequestAuthorizer {
public static final RequestAuthorizer AUTHORIZE_ANNONYMOUS = new AnnonymousAuthorizer();
/**
* Authorize a request with the given parameters by returning a valid {@link Authentication}.
*
* @param parameters
*
* @return a valid {@link Authentication} or <code>null</code> if authorization to this request
* has not been granted
*/
public Authorization authorize(Map<String, String> parameters);
public static class AnnonymousAuthorizer implements RequestAuthorizer {
@Override
public Authorization authorize(Map<String, String> parameters) {
return Authorization.granted(Authentication.ANONYMOUS);
}
}
}
|
92346c3c10b5023e71206a50ae1953cac477d3a1 | 1,245 | java | Java | Mage.Sets/src/mage/cards/c/CoalitionHonorGuard.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 1,444 | 2015-01-02T00:25:38.000Z | 2022-03-31T13:57:18.000Z | Mage.Sets/src/mage/cards/c/CoalitionHonorGuard.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 6,180 | 2015-01-02T19:10:09.000Z | 2022-03-31T21:10:44.000Z | Mage.Sets/src/mage/cards/c/CoalitionHonorGuard.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 1,001 | 2015-01-01T01:15:20.000Z | 2022-03-30T20:23:04.000Z | 29.642857 | 165 | 0.734137 | 996,913 |
package mage.cards.c;
import mage.MageInt;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.effects.common.ruleModifying.TargetsHaveToTargetPermanentIfAbleEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import java.util.UUID;
/**
* Cardname: Coalition Honor Guard
*
* @author LevelX2
*/
public final class CoalitionHonorGuard extends CardImpl {
public CoalitionHonorGuard(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{W}");
this.subtype.add(SubType.HUMAN);
this.subtype.add(SubType.FLAGBEARER);
this.power = new MageInt(2);
this.toughness = new MageInt(4);
// While choosing targets as part of casting a spell or activating an ability, your opponents must choose at least one Flagbearer on the battlefield if able.
this.addAbility(new SimpleStaticAbility(new TargetsHaveToTargetPermanentIfAbleEffect()));
}
private CoalitionHonorGuard(final CoalitionHonorGuard card) {
super(card);
}
@Override
public CoalitionHonorGuard copy() {
return new CoalitionHonorGuard(this);
}
}
|
92346c5c5b97dc40fe9eb8b37ad1bb473eb33141 | 1,732 | java | Java | streams/functions/src/main/java/com/hortonworks/streamline/streams/udaf/Topn.java | hmcl/streamline-hortonworks | b458b5a36f961d6f21ad1b321ea14b81ffb1dfaa | [
"Apache-2.0"
] | 171 | 2017-02-24T21:24:03.000Z | 2022-03-11T12:47:54.000Z | streams/functions/src/main/java/com/hortonworks/streamline/streams/udaf/Topn.java | hmcl/streamline-hortonworks | b458b5a36f961d6f21ad1b321ea14b81ffb1dfaa | [
"Apache-2.0"
] | 762 | 2017-02-23T00:08:36.000Z | 2022-01-21T23:19:26.000Z | streams/functions/src/main/java/com/hortonworks/streamline/streams/udaf/Topn.java | hmcl/streamline-hortonworks | b458b5a36f961d6f21ad1b321ea14b81ffb1dfaa | [
"Apache-2.0"
] | 100 | 2017-02-22T22:06:20.000Z | 2022-01-25T14:12:08.000Z | 29.355932 | 100 | 0.650115 | 996,914 | /**
* Copyright 2017 Hortonworks.
*
* 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.hortonworks.streamline.streams.udaf;
import com.hortonworks.streamline.streams.rule.UDAF2;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
/**
* Computes streaming top n values of a group of values
*/
public class Topn<T extends Comparable<T>> implements UDAF2<PriorityQueue<T>, Integer, T, List<T>> {
@Override
public PriorityQueue<T> init() {
return new PriorityQueue<>();
}
@Override
public PriorityQueue<T> add(PriorityQueue<T> aggregate, Integer n, T val) {
if (n <= 0) {
return aggregate;
}
if (aggregate.size() >= n) {
if (val.compareTo(aggregate.peek()) > 0) {
aggregate.remove();
aggregate.add(val);
}
} else {
aggregate.add(val);
}
return aggregate;
}
@Override
public List<T> result(PriorityQueue<T> aggregate) {
List<T> res = new ArrayList<>(aggregate);
res.sort(Comparator.reverseOrder());
return res;
}
}
|
92346c9ac2bdef727440bdc1b2504a78e34449d6 | 8,067 | java | Java | app/src/main/java/com/demo/maat/hello_rxjava/Operators1Fragment.java | jingtalk/Hello-RxJava | 863c23bf23f5d777c4ba487480a3dfde2952462f | [
"Apache-2.0"
] | 610 | 2016-10-13T02:20:20.000Z | 2021-08-06T03:17:03.000Z | app/src/main/java/com/demo/maat/hello_rxjava/Operators1Fragment.java | jingtalk/Hello-RxJava | 863c23bf23f5d777c4ba487480a3dfde2952462f | [
"Apache-2.0"
] | 3 | 2016-11-18T02:35:01.000Z | 2017-01-18T09:21:39.000Z | app/src/main/java/com/demo/maat/hello_rxjava/Operators1Fragment.java | jingtalk/Hello-RxJava | 863c23bf23f5d777c4ba487480a3dfde2952462f | [
"Apache-2.0"
] | 121 | 2016-10-13T03:45:44.000Z | 2021-12-17T14:53:18.000Z | 27.253378 | 133 | 0.513574 | 996,915 | package com.demo.maat.hello_rxjava;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.demo.maat.hello_rxjava.common.logger.Log;
import java.util.concurrent.TimeUnit;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.functions.Func2;
import rx.subscriptions.CompositeSubscription;
import static rx.Observable.timer;
public class Operators1Fragment extends Fragment {
static final String TAG = "Operators1Fragment";
@BindView(R.id.btn_just)
Button mBtnJust;
@BindView(R.id.btn_from)
Button mBtnFrom;
@BindView(R.id.btn_repeat)
Button mBtnRepeat;
@BindView(R.id.btn_repeatwhen)
Button mBtnRepeatwhen;
@BindView(R.id.btn_interval)
Button mBtnInterval;
@BindView(R.id.btn_timer)
Button mBtnTimer;
@BindView(R.id.btn_range)
Button mBtnRange;
private CompositeSubscription mCompositeSubscription;
;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.operators1_fragment, container, false);
ButterKnife.bind(this, view);
mCompositeSubscription = new CompositeSubscription();
return view;
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
@OnClick({R.id.btn_just, R.id.btn_from, R.id.btn_repeat, R.id.btn_repeatwhen, R.id.btn_interval, R.id.btn_timer, R.id.btn_range})
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_just:
doJustOperation();
break;
case R.id.btn_from:
doFromOperation();
break;
case R.id.btn_repeat:
doRepeatOperation();
break;
case R.id.btn_repeatwhen:
doRepeatWhenOperation();
break;
case R.id.btn_interval:
doIntervalOperation();
break;
case R.id.btn_timer:
doTimerOperation();
break;
case R.id.btn_range:
doRangeOperation();
break;
}
}
/**
* 从3开始连续产生10个数字
*/
private void doRangeOperation() {
Subscription rangeSub =Observable.range(3,10).subscribe(new Subscriber<Integer>() {
@Override
public void onCompleted() {
printLog("Completed");
}
@Override
public void onError(Throwable e) {
printLog("Error");
}
@Override
public void onNext(Integer i) {
printLog("Next"+i);
}
});
mCompositeSubscription.add(rangeSub);
}
/**
* 每隔1秒输出一个数字
*/
private void doTimerOperation() {
Subscription timerSub=Observable.timer(1, 1, TimeUnit.SECONDS).subscribe(new Subscriber<Long>() {
@Override
public void onCompleted() {
printLog("Completed");
}
@Override
public void onError(Throwable e) {
printLog("Error");
}
@Override
public void onNext(Long aLong) {
printLog("Next" + aLong);
}
});
mCompositeSubscription.add(timerSub);
}
private void doIntervalOperation() {
Subscription intervalSub=Observable.interval(1, TimeUnit.SECONDS).subscribe(new Subscriber<Long>() {
@Override
public void onCompleted() {
printLog("Completed");
}
@Override
public void onError(Throwable e) {
printLog("Error");
}
@Override
public void onNext(Long aLong) {
printLog("Next" + aLong);
}
});
mCompositeSubscription.add(intervalSub);
}
/**
* 完成一次之后,再每隔1秒重复1次,共重复3次。
*/
private void doRepeatWhenOperation() {
Observable.just(1, 2, 3).repeatWhen(new Func1<Observable<? extends Void>, Observable<?>>() {
@Override
public Observable<?> call(Observable<? extends Void> observable) {
//重复3次
return observable.zipWith(Observable.range(1, 3), new Func2<Void, Integer, Integer>() {
@Override
public Integer call(Void aVoid, Integer integer) {
return integer;
}
}).flatMap(new Func1<Integer, Observable<?>>() {
@Override
public Observable<?> call(Integer integer) {
printLog("delay repeat" + integer);
//1秒钟重复一次
return timer(1, TimeUnit.SECONDS);
}
});
}
}).subscribe(new Subscriber<Integer>() {
@Override
public void onCompleted() {
printLog("Completed");
}
@Override
public void onError(Throwable e) {
printLog("Error");
}
@Override
public void onNext(Integer value) {
printLog("Next" + value);
}
});
}
// 从1开始输出3个数,重复2次
private void doRepeatOperation() {
Observable.range(1, 3).repeat(2).subscribe(new Subscriber<Integer>() {
@Override
public void onCompleted() {
printLog("Completed");
}
@Override
public void onError(Throwable e) {
printLog("Error");
}
@Override
public void onNext(Integer i) {
printLog("Nest" + i);
}
});
}
/**
* 接受一个数组,与just的区别就是接受的参数不同
*/
private void doFromOperation() {
Integer[] items = {0, 1, 2, 3, 4, 5};
Observable from = Observable.from(items);
from.subscribe(
new Action1<Integer>() {
@Override
public void call(Integer item) {
printLog("Next" + item);
}
},
new Action1<Throwable>() {
@Override
public void call(Throwable error) {
printLog("Error");
}
},
new Action0() {
@Override
public void call() {
printLog("Compeleted");
}
}
);
}
private void doJustOperation() {
Subscription subscription = Observable.just(1, 2, 3, 4, 5)
.subscribe(new Subscriber<Integer>() {
@Override
public void onNext(Integer item) {
printLog("Next" + item);
}
@Override
public void onError(Throwable error) {
printLog("Error");
}
@Override
public void onCompleted() {
printLog("Completed");
}
});
mCompositeSubscription.add(subscription);
}
private void printLog(String s) {
Log.i(TAG, s);
}
@Override
public void onDestroy() {
super.onDestroy();
mCompositeSubscription.unsubscribe();
}
}
|
92346cc3065dbb191c3b34a497dcfbf9bab9f38d | 2,525 | java | Java | src/main/java/com/sktutilities/panel/TrackingPanel.java | sanskrit-coders/sanskritnlpjava | b67cafa44427b35abc4e86632e0efda79a9b151f | [
"BSD-3-Clause"
] | 6 | 2016-04-30T20:16:35.000Z | 2020-05-20T08:53:36.000Z | src/main/java/com/sktutilities/panel/TrackingPanel.java | sanskrit-coders/sanskritnlpjava | b67cafa44427b35abc4e86632e0efda79a9b151f | [
"BSD-3-Clause"
] | 6 | 2016-04-08T06:34:09.000Z | 2017-03-31T15:02:03.000Z | src/main/java/com/sktutilities/panel/TrackingPanel.java | sanskrit-coders/sanskritnlpjava | b67cafa44427b35abc4e86632e0efda79a9b151f | [
"BSD-3-Clause"
] | 6 | 2015-02-04T13:45:57.000Z | 2020-05-22T07:47:05.000Z | 30.792683 | 106 | 0.616238 | 996,916 | package com.sktutilities.panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import com.sktutilities.sandhi.SandhiJFrame;
import com.sktutilities.util.Log;
public class TrackingPanel extends JPanel implements ActionListener
{
JButton previousItem, nextItem;
SandhiJFrame frame;
public TrackingPanel(SandhiJFrame frame)
{
super();
this.frame = frame;
previousItem = new JButton("<<<");
previousItem.setActionCommand("previous");
previousItem.setToolTipText("Go to Previous Entry.");
previousItem.setEnabled(false);
nextItem = new JButton(">>>");
nextItem.setActionCommand("next");
nextItem.setToolTipText("Go to Next Entry.");
nextItem.setEnabled(false);
// Adding ActionListener
previousItem.addActionListener(this);
nextItem.addActionListener(this);
this.add(previousItem);
this.add(nextItem);
}
@Override
public void actionPerformed(ActionEvent e)
{
if ((e.getActionCommand()).equals("previous"))
{
// if u r trying to scroll on the firsts added element
// and for some reason it is not disabled, then time to disable it
if (frame.getVectorTracker() <= 0) previousItem.setEnabled(false);
Log.logInfo("previous -> : vector_tracker " + frame.getVectorTracker());
nextItem.setEnabled(true);
frame.setText(frame.getBeanVector().elementAt(frame.preDeccrementVectorTracker()));
if (frame.getVectorTracker() <= 0) previousItem.setEnabled(false);
Log.logInfo("previous -> : vector_tracker" + frame.getVectorTracker());
}
else if ((e.getActionCommand()).equals("next"))
{
Log.logInfo("next -> : vector_tracker" + frame.getVectorTracker());
previousItem.setEnabled(true);
frame.setText(frame.getBeanVector().elementAt(frame.preIncrementVectorTracker()));
if (frame.getVectorTracker() >= frame.getBeanVector().size() - 1) nextItem.setEnabled(false);
Log.logInfo("next -> : vector_tracker" + frame.getVectorTracker());
}
}
public JButton getPreviousItem()
{
return previousItem;
}
public JButton getNextItem()
{
return nextItem;
}
}
|
92346dd4c5d47bf023a905394bae5af85886b41b | 1,521 | java | Java | src/main/java/org/vaadin/addons/javaee/container/service/ExampleFilterTranslator.java | thomasletsch/javaee-addon | 3060c8fa19c6d740e1a2c9e3d00d6eb2c0dc8480 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/vaadin/addons/javaee/container/service/ExampleFilterTranslator.java | thomasletsch/javaee-addon | 3060c8fa19c6d740e1a2c9e3d00d6eb2c0dc8480 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/vaadin/addons/javaee/container/service/ExampleFilterTranslator.java | thomasletsch/javaee-addon | 3060c8fa19c6d740e1a2c9e3d00d6eb2c0dc8480 | [
"Apache-2.0"
] | null | null | null | 38.2 | 85 | 0.635471 | 996,917 | /*******************************************************************************
* Copyright 2013 Thomas Letsch (upchh@example.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.vaadin.addons.javaee.container.service;
import java.util.Map;
import com.googlecode.javaeeutils.jpa.PersistentEntity;
import com.vaadin.data.Container.Filter;
public interface ExampleFilterTranslator<FILTER extends Filter> {
Class<FILTER> getAcceptedClass();
/**
*
* @param filter
* The actual filter to translate
* @param example
* The entity example for the query by example
* @param filters
* All configured builder for recursive call of sub filter translation
* @return
*/
<ENTITY extends PersistentEntity> ENTITY translate(FILTER filter, ENTITY example,
Map<Class<? extends Filter>, ExampleFilterTranslator<?>> filters);
}
|
92346df35fe6d3de0fb082ed56a10bcddfe9cf42 | 494 | java | Java | src/main/java/fr/flaurens/bankaccount/model/Client.java | simonxcz/coursTF | db081ae6848b3eb9fef22f3a2a33cb569fc52e0c | [
"MIT"
] | null | null | null | src/main/java/fr/flaurens/bankaccount/model/Client.java | simonxcz/coursTF | db081ae6848b3eb9fef22f3a2a33cb569fc52e0c | [
"MIT"
] | null | null | null | src/main/java/fr/flaurens/bankaccount/model/Client.java | simonxcz/coursTF | db081ae6848b3eb9fef22f3a2a33cb569fc52e0c | [
"MIT"
] | null | null | null | 19.76 | 68 | 0.659919 | 996,918 | package fr.flaurens.bankaccount.model;
public class Client {
private final long clientId;
private final String firstName;
private final String lastName;
public Client(long clientId, String firstName, String lastName){
this.clientId = clientId;
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName(){
return this.firstName;
}
public String getLastName() {
return this.lastName;
}
}
|
92346e44226041a88b3dbe8df8657cca0dcf74db | 62,104 | java | Java | cnd/cnd.debugger.common2/src/org/netbeans/modules/cnd/debugger/common2/debugger/NativeDebuggerImpl.java | leginee/netbeans | 814ad30e2d0a094f4aa3813bcbb5323a95a0b1d6 | [
"Apache-2.0"
] | null | null | null | cnd/cnd.debugger.common2/src/org/netbeans/modules/cnd/debugger/common2/debugger/NativeDebuggerImpl.java | leginee/netbeans | 814ad30e2d0a094f4aa3813bcbb5323a95a0b1d6 | [
"Apache-2.0"
] | null | null | null | cnd/cnd.debugger.common2/src/org/netbeans/modules/cnd/debugger/common2/debugger/NativeDebuggerImpl.java | leginee/netbeans | 814ad30e2d0a094f4aa3813bcbb5323a95a0b1d6 | [
"Apache-2.0"
] | null | null | null | 32.515183 | 156 | 0.601572 | 996,919 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
*
* Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.modules.cnd.debugger.common2.debugger;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.util.Iterator;
import org.netbeans.modules.cnd.debugger.common2.DbgActionHandler;
import org.netbeans.modules.cnd.debugger.common2.debugger.io.IOPack;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import javax.swing.SwingUtilities;
import org.netbeans.modules.cnd.spi.remote.RemoteSyncFactory;
import org.openide.text.Line;
import org.netbeans.api.debugger.DebuggerEngine;
import org.netbeans.api.project.Project;
import org.netbeans.spi.debugger.ContextProvider;
import org.netbeans.modules.cnd.api.remote.PathMap;
import org.netbeans.modules.cnd.api.toolchain.CompilerFlavor;
import org.netbeans.modules.cnd.api.toolchain.CompilerSet;
import org.netbeans.modules.cnd.api.toolchain.CompilerSetManager;
import org.netbeans.modules.cnd.api.toolchain.PredefinedToolKind;
import org.netbeans.modules.cnd.api.toolchain.Tool;
import org.netbeans.modules.cnd.api.toolchain.ui.BuildToolsAction;
import org.netbeans.modules.cnd.api.toolchain.ui.LocalToolsPanelModel;
import org.netbeans.modules.cnd.api.toolchain.ui.ToolsPanelModel;
import org.netbeans.modules.cnd.debugger.common2.DbgGuiModule;
import org.netbeans.modules.cnd.makeproject.api.configurations.Configuration;
import org.netbeans.modules.cnd.makeproject.api.configurations.MakeConfiguration;
import org.netbeans.modules.nativeexecution.api.ExecutionEnvironment;
import org.netbeans.modules.cnd.debugger.common2.utils.options.OptionLayers;
import org.netbeans.modules.cnd.debugger.common2.utils.options.OptionSet;
import org.netbeans.modules.cnd.debugger.common2.utils.ListMap;
import org.netbeans.modules.cnd.debugger.common2.utils.IpeUtils;
import org.netbeans.modules.cnd.debugger.common2.debugger.options.DebuggerOption;
import org.netbeans.modules.cnd.debugger.common2.debugger.breakpoints.NativeBreakpoint;
import org.netbeans.modules.cnd.debugger.common2.debugger.breakpoints.Handler;
import org.netbeans.modules.cnd.debugger.common2.debugger.breakpoints.Context;
import org.netbeans.modules.cnd.debugger.common2.debugger.breakpoints.Gen;
import org.netbeans.modules.cnd.debugger.common2.debugger.breakpoints.BreakpointManager;
import org.netbeans.modules.cnd.debugger.common2.debugger.breakpoints.BreakpointProvider;
import org.netbeans.modules.cnd.debugger.common2.debugger.assembly.DisFragModel;
import org.netbeans.modules.cnd.debugger.common2.debugger.assembly.Controller;
import org.netbeans.modules.cnd.debugger.common2.debugger.assembly.BreakpointModel;
import org.netbeans.modules.cnd.debugger.common2.debugger.assembly.StateModel;
import org.netbeans.modules.cnd.debugger.common2.debugger.remote.Host;
import org.netbeans.modules.cnd.debugger.common2.capture.ExternalStartManager;
import org.netbeans.modules.cnd.debugger.common2.capture.CaptureInfo;
import org.netbeans.modules.cnd.debugger.common2.capture.ExternalStart;
import org.netbeans.modules.cnd.debugger.common2.debugger.assembly.Disassembly;
import org.netbeans.modules.cnd.debugger.common2.debugger.assembly.DisassemblyUtils;
import org.netbeans.modules.cnd.debugger.common2.debugger.assembly.MemoryWindow;
import org.netbeans.modules.cnd.debugger.common2.debugger.assembly.RegistersWindow;
import org.netbeans.modules.cnd.debugger.common2.debugger.breakpoints.types.InstructionBreakpoint;
import org.netbeans.modules.cnd.debugger.common2.debugger.spi.DebuggerToolRecognizer;
import org.netbeans.modules.cnd.debugger.common2.utils.Executor;
import org.netbeans.modules.cnd.makeproject.api.configurations.CompilerSet2Configuration;
import org.netbeans.modules.cnd.makeproject.api.configurations.MakeConfigurationDescriptor;
import org.netbeans.modules.cnd.spi.toolchain.CompilerSetFactory;
import org.netbeans.modules.remote.spi.FileSystemProvider;
import org.netbeans.spi.viewmodel.ModelListener;
import org.openide.cookies.EditorCookie;
import org.openide.util.Lookup;
import org.openide.util.Pair;
import org.openide.util.RequestProcessor;
import org.openide.util.actions.SystemAction;
/**
* Stuff that is common to native DebuggerImpl's.
*/
public abstract class NativeDebuggerImpl implements NativeDebugger, BreakpointProvider {
private final BreakpointManager bm;
protected volatile boolean breakpointsActivated = true;
protected final ContextProvider ctxProvider; // for lookup
protected final DebuggerEngine debuggerEngine; // corresponding engine
protected final NativeSession session; // corresponding (our) session object
// turned on when postKill is called
protected volatile boolean postedKill = false;
// turned on when killEngine is issued
protected volatile boolean postedKillEngine = false;
protected volatile Location visitedLocation = null;
protected final DebuggerAnnotation visitMarker;
protected final DebuggerAnnotation visitDisMarker;
protected final DebuggerAnnotation currentPCMarker;
protected final DebuggerAnnotation currentDisPCMarker;
private boolean srcOOD;
private String srcOODMessage = null;
protected ListMap<WatchVariable> watches = new ListMap<WatchVariable>();
// local stuff
protected final ModelChangeDelegator localUpdater = new ModelChangeDelegator();
private boolean showAutos = false;
protected final List<Variable> autos = Collections.synchronizedList(new ArrayList<Variable>());
// stack stuff
protected Frame[] guiStackFrames = null;
protected Frame currentFrame;
protected final ModelChangeDelegator stackUpdater = new ModelChangeDelegator();
// thread stuff
protected final ModelChangeDelegator threadUpdater = new ModelChangeDelegator();
// debugging view stuff
protected final ModelChangeDelegator debuggingViewUpdater = new ModelChangeDelegator();
// assembly level stuff
private boolean disActive = false;
protected boolean disRequested = false;
private StateModelAdaptor disStateModel = new StateModelAdaptor();
private InstBreakpointModel breakpointModel = new InstBreakpointModel();
protected Executor executor;
protected NativeDebuggerImpl(ContextProvider ctxProvider) {
this.ctxProvider = ctxProvider;
this.bm = new BreakpointManager(this, this);
this.debuggerEngine = ctxProvider.lookupFirst(null, DebuggerEngine.class);
// Instantiate our session object
//
// This will find the
// org.netbeans.modules.cnd.debugger.common2.debugger.NativeSession
// registered in META-INF/debugger/netbeans-[Dbx|Gdb]Session
//
// We allocate it indirectly via lookup because then it has the
// side-effect of registering the session object in 'ctxProvider'
session = ctxProvider.lookupFirst(null, NativeSession.class);
assert session != null : "NativeDebuggerImpl created session";
session.setDebugger((NativeDebugger) this);
currentPCMarker =
new DebuggerAnnotation(null,
DebuggerAnnotation.TYPE_CURRENT_PC,
null,
true);
currentDisPCMarker =
new DebuggerAnnotation(null,
DebuggerAnnotation.TYPE_CURRENT_PC,
null,
true);
visitMarker =
new DebuggerAnnotation(null,
DebuggerAnnotation.TYPE_CALLSITE,
null,
true);
visitDisMarker =
new DebuggerAnnotation(null,
DebuggerAnnotation.TYPE_CALLSITE,
null,
true);
}
// interface NativeDebugger
@Override
public final NativeSession session() {
return session;
}
// interface NativeDebugger
@Override
public final NativeDebuggerManager manager() {
return NativeDebuggerManager.get();
}
// interface NativeDebugger
@Override
public final BreakpointManager bm() {
return bm;
}
/**
* Are we the current session?
*/
// interface NativeDebugger
@Override
public boolean isCurrent() {
return manager().currentNativeDebugger() == this;
}
@Override
public boolean areBreakpointsActivated() {
return breakpointsActivated;
}
// interface NativeDebugger
@Override
public abstract DebuggerSettingsBridge profileBridge();
@Override
public Context context() {
final String executable = session().getTarget();
final String hostname = session().getSessionHost();
return new Context(executable, hostname);
}
private IOPack ioPack;
protected void setIOPack(IOPack ioPack) {
this.ioPack = ioPack;
}
public IOPack getIOPack() {
return ioPack;
}
private Host host = null;
public ExecutionEnvironment getExecutionEnvironment() {
return executor.getExecutionEnvironment();
}
@Override
public Host getHost() {
if (host == null) {
host = Host.byName(getNDI().getHostName());
}
return host;
}
private PathMap cachedPathMap;
private boolean lookedPathMap;
private PathMap getPathMap() {
if (!lookedPathMap) {
lookedPathMap = true;
Configuration conf = getNDI().getConfiguration();
if (! (conf instanceof MakeConfiguration)) {
cachedPathMap = null;
} else {
cachedPathMap = getPathMapFromConfig(conf);
}
}
return cachedPathMap;
}
// It maps source roots to their canonical representations
private volatile LinkedList<Pair<String, String>> pathMap;
private final Object lock = new Object();
private String expandCanonicalPath(String potentiallyCanonicalPath) {
if (potentiallyCanonicalPath == null) {
return null;
}
String ret = potentiallyCanonicalPath;
Project project = getNDI().getProject();
if (project == null) {
return ret;
}
MakeConfigurationDescriptor makeConfigurationDescriptor = MakeConfigurationDescriptor.getMakeConfigurationDescriptor(project);
if (makeConfigurationDescriptor == null) {
return ret;
}
List<String> absoluteSourceRoots = makeConfigurationDescriptor.getAbsoluteSourceRoots();
synchronized (lock) {
if (pathMap == null) {
pathMap = new LinkedList<Pair<String, String>>();
for (String absoluteSourceRoot : absoluteSourceRoots) {
try {
String canonicalSourceRoot = FileSystemProvider.getCanonicalPath(getExecutionEnvironment(), absoluteSourceRoot);
if (!absoluteSourceRoot.equals(canonicalSourceRoot)) {
pathMap.add(Pair.of(absoluteSourceRoot, canonicalSourceRoot));
}
} catch (IOException ex) {
DbgGuiModule.logger.log(Level.INFO, ex.getMessage(), ex);
}
}
}
}
if (pathMap.size() > 0) {
for (Pair<String, String> paths : pathMap) {
ret = ret.replace(paths.second(), paths.first());
}
}
return ret;
}
public static PathMap getPathMapFromConfig(Configuration conf) {
MakeConfiguration mc = (MakeConfiguration) conf;
ExecutionEnvironment ee = mc.getDevelopmentHost().getExecutionEnvironment();
RemoteSyncFactory syncFactory = mc.getRemoteSyncFactory();
return (syncFactory == null) ? null : syncFactory.getPathMap(ee);
}
@Override
public final String localToRemote(String who, String path) {
String mapped;
if (path == null) {
mapped = path;
} else if (NativeDebuggerManager.isStandalone()) {
mapped = path;
} else {
PathMap pm = getPathMap();
if (pm == null) {
mapped = path;
} else {
mapped = pm.getRemotePath(path);
if (mapped == null) {
// no mapping was found
mapped = path;
}
}
}
if (Log.PathMap.debug) {
System.out.printf("localToRemote - %s\n", who); // NOI18N
System.out.printf(" from: %s\n", path); // NOI18N
System.out.printf(" to: %s\n", mapped); // NOI18N
}
return mapped;
}
@Override
public final String remoteToLocal(String who, String path) {
String mapped;
if (path == null) {
mapped = path;
} else if (NativeDebuggerManager.isStandalone()) {
mapped = path;
} else {
PathMap pm = getPathMap();
if (pm == null) {
mapped = path;
} else {
mapped = pm.getLocalPath(path);
if (mapped == null) {
// no mapping was found
mapped = path;
}
}
}
if (Log.PathMap.debug) {
System.out.printf("remoteToLocal - %s\n", who); // NOI18N
System.out.printf(" from: %s\n", path); // NOI18N
System.out.printf(" to: %s\n", mapped); // NOI18N
}
mapped = expandCanonicalPath(mapped);
return mapped;
}
/*
* Return true if we will be loading a program after a successful
* connection to the engine.
* If not, the progress dialog has to be brought down as soon as we have a
* connection.
*/
public final boolean willBeLoading() {
if (getNDI() == null) {
return false;
} else if (IpeUtils.isEmpty(getNDI().getTarget()) &&
IpeUtils.isEmpty(getNDI().getCorefile()) &&
getNDI().getPid() == -1) {
return false;
} else {
return true;
}
}
//
// Session stuff
//
/**
* Update session data for session associated with this engine
*/
// interface NativeDebugger
@Override
public void invalidateSessionData() {
if (session != null) // FIXUP: Ivan, check this....
{
session.update();
}
}
/**
* Trampoline to DebuggerManager.statusDisplayer.setStatusText()
*/
public void setStatusText(String text) {
manager().setStatusText(text);
}
/*
* Action sensitization and state stuff
*
* Compared to sierra/orion & rainier ...
* - we're banking that the actual cost of action enabling is low
* enough that we can afford redundant calls and forego the
* bitset delta detection that we used to do.
* - debuggercore now multiplexes action enabledness between sessions
* for us so all the accomodation and worries about that are gone.
*/
protected final List<StateListener> actions = new LinkedList<StateListener>();
protected final ReentrantReadWriteLock actionsLock = new ReentrantReadWriteLock();
protected javax.swing.Timer runTimer; // see stateSetRunning()
protected int runDelay = -1; // -1 == first time through
private final State state = new State(); // individual state values are mostly
// set by Dbx
private ActionEnabler actionEnabler() {
return NativeDebuggerManager.actionEnabler();
}
@Override
public State state() {
return state;
}
@Override
public void addStateListener(StateListener sl) {
actionsLock.writeLock().lock();
try {
actions.add(sl);
} finally {
actionsLock.writeLock().unlock();
}
}
@Override
public void removeStateListener(StateListener sl) {
actionsLock.writeLock().lock();
try {
actions.remove(sl);
} finally {
actionsLock.writeLock().unlock();
}
}
/**
* Declare that a bunch of state variables have changed
*/
public final void stateChanged() {
//System.out.println("STATE CHANGED @@@@@@@@@ " + state);
if (isCurrent()) {
updateActions();
invalidateSessionData(); // CR 6993279
} else {
// When user switches sessions by hand then we'll adjust
// the actions.
}
}
/**
* Declare that the pid of the process being debugged changed
*/
public final void pidChanged() {
// Cause bpt context info to get re-pulled
NativeBreakpoint[] bpts = bm().breakpointBag().getBreakpoints();
for (NativeBreakpoint b : bpts) {
b.updateFor(this);
}
}
/**
* Sensitive/desensitize all actions according to state.
* Each action decides on it's own what it needs to do.
*/
protected void updateActions() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// update explicitly registered actions
List<StateListener> actionsCopy;
actionsLock.readLock().lock();
try {
actionsCopy = new ArrayList<StateListener>(actions);
} finally {
actionsLock.readLock().unlock();
}
for (StateListener action : actionsCopy) {
action.update(state);
}
// update actions managed by ActionEnabler
actionEnabler().update(state);
}
});
}
/**
* Get the delay (in milliseconds) to use for GUI refreshes.
* Can be overriden by the property "spro.rundelay".
*/
private int getRunDelay() {
if (runDelay == -1) {
runDelay = 250; // 0.25 seconds
String delay = System.getProperty("spro.rundelay"); // NOI18N
if (delay != null) {
try {
runDelay = Integer.parseInt(delay);
} catch (java.lang.NumberFormatException e) {
}
}
}
return runDelay;
}
/*
* Clients don't modify State.isRunning directly, but rather through
* this method which uses a delay mechanism so as to not cause
* gui button flashing if resumption is of short duration.
*/
public final void stateSetRunning(boolean running) {
if (!running) {
// cancel timer
if (runTimer != null) {
runTimer.stop();
}
// really set the state and update
state.isRunning = false;
updateActions();
} else {
// start timer
if (runTimer == null) {
runTimer = new javax.swing.Timer(getRunDelay(),
new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
// set state and update when timer expires
state.isRunning = true;
updateActions();
}
});
runTimer.setRepeats(false);
runTimer.setCoalesce(true);
runTimer.start();
} else {
runTimer.restart();
}
}
}
protected final boolean stateFromProg() {
return !state.isCore && !state.isAttach;
}
// interface NativeDebugger as well.
@Override
public abstract String debuggerType();
protected static class WatchJob {
private Kind kind;
private int routingToken;
private WatchVariable target;
private NativeWatch template;
private boolean primaryChange;
public enum Kind {
NEW,
RESTORE,
REPLACE,
SPONTANEOUS,
DELETE
};
public WatchJob(Kind kind, WatchVariable target, NativeWatch template) {
this.kind = kind;
this.target = target;
this.template = template;
}
public void print() {
if (!Log.Watch.pathway) {
return;
}
System.out.printf("WatchJob %d %s: [%s]<[%s]\n" + // NOI18N
"spread %b\n", // NOI18N
routingToken, kind, target, template,
primaryChange);
}
public Kind kind() {
return kind;
}
public void setKind(Kind k) {
kind = k;
}
public WatchVariable target() {
return target;
}
public NativeWatch template() {
return template;
}
public void setPrimaryChange(boolean primaryChange) {
this.primaryChange = primaryChange;
}
public boolean isPrimaryChange() {
return primaryChange;
}
public void setRoutingToken(int routingToken) {
this.routingToken = routingToken;
}
public int getRoutingToken() {
return routingToken;
}
}
private static class WatchJobs extends HashMap<Integer, WatchJob> {
// @Override
public void put(int rt, WatchJob wj) {
wj.print();
super.put(rt, wj);
}
// @Override
public WatchJob get(int rt) {
WatchJob wj;
if (rt == 0) {
if (Log.Watch.pathway) {
System.out.printf("WatchJobs.get(): rt == 0\n"); // NOI18N
}
wj = new WatchJob(WatchJob.Kind.SPONTANEOUS, null, null);
return wj;
} else {
wj = super.get(rt);
assert wj != null :
"WatchJobs.get(): no watch for rt " + rt; // NOI18N
remove(rt);
return wj;
}
}
}
WatchJobs watchJobs = new WatchJobs();
protected WatchJob getWatchJob(int rt) {
return watchJobs.get(rt);
}
protected void noteNewWatch(NativeWatch template, int rt) {
if (Log.Watch.pathway) {
System.out.printf("noteNewWatch(%d)\n", rt); // NOI18N
}
WatchJob wj = new WatchJob(WatchJob.Kind.NEW, null, template);
wj.setRoutingToken(rt);
wj.setPrimaryChange(true);
watchJobs.put(rt, wj);
}
protected void noteDeletedWatch(WatchVariable target, boolean spread) {
int rt = target.getRoutingToken();
WatchJob wj = new WatchJob(WatchJob.Kind.DELETE, target, null);
wj.setPrimaryChange(spread);
wj.setRoutingToken(rt);
watchJobs.put(rt, wj);
}
protected void noteRestoredWatch(NativeWatch template, int rt) {
WatchJob wj = new WatchJob(WatchJob.Kind.RESTORE, null, template);
wj.setRoutingToken(rt);
watchJobs.put(rt, wj);
}
// interface NativeDebugger
@Override
public WatchVariable[] getWatches() {
return watches.toArray(new WatchVariable[watches.size()]);
}
protected WatchBag watchBag() {
return manager().watchBag();
}
protected ModelChangeDelegator watchUpdater() {
return manager().watchUpdater();
}
@Override
public void restoreWatches(WatchBag wb) {
NativeWatch[] watchesToRestore = wb.getWatches();
for (int i = 0; i < watchesToRestore.length; i++) {
NativeWatch template = watchesToRestore[i];
if (template != null && template.isEnabled()) {
restoreWatch(template);
}
}
}
protected void deleteWatch(WatchVariable w, boolean spreading) {
// LATER w.cleanup();
// take out of our list
watches.remove(w);
w.removeAllDescendantFromOpenList(false);
watchUpdater().treeChanged(); // causes a pull
final NativeWatch parent = w.getNativeWatch();
if (!postedKill) {
// if not finishing session
parent.removeSubWatch(w, (NativeDebugger) this);
if (parent.nChildren() == 0) {
parent.delete();
} else {
if (!spreading) {
parent.postDelete(true);
}
}
} else {
// finishing session. Just remove this sub-watch
parent.removeSubWatch(w, (NativeDebugger) this);
}
}
public final void deleteWatchById(int rt, int id) {
WatchVariable w = watches.byKey(id);
if (w != null) {
WatchJob wj = getWatchJob(rt);
deleteWatch(w, wj.isPrimaryChange());
}
}
@Override
public void spreadWatchCreation(NativeWatch w) {
// very similar to restoreWatches
restoreWatch(w);
}
@Override
public abstract void replaceWatch(NativeWatch template, String replacewith);
protected abstract void restoreWatch(NativeWatch template);
protected final void clearFiredEvents() {
for (Handler h : bm().getHandlers()) {
h.setFired(false);
}
}
private static class VarContinuations extends HashMap<Integer, VarContinuation> {
// @Override
public void put(int rt, VarContinuation vc) {
vc.print();
super.put(rt, vc);
}
// @Override
public VarContinuation get(int rt) {
VarContinuation vc = super.remove(rt);
return vc;
}
}
private VarContinuations varContinuations = new VarContinuations();
protected abstract void postVarContinuation(int rt, VarContinuation vc);
// interface NativeDebugger
@Override
public void postVarContinuation(VarContinuation vc) {
int rt = RoutingToken.VAR.getUniqueRoutingTokenInt();
varContinuations.put(rt, vc);
postVarContinuation(rt, vc);
}
public void handleVarContinuation(int rt, String result) {
VarContinuation vc = varContinuations.get(rt);
if (vc != null) {
vc.run(result);
}
}
@Override
public void setShowAutos(boolean showAutos) {
// System.out.printf("NativeDebuggerImpl.setShowAutos(%b)\n", showAutos);
this.showAutos = showAutos;
}
protected final boolean isShowAutos() {
return showAutos;
}
/**
* Clear out mark locations.
*
* Possibly relevant comment from the equivalent function in WorkShop:
* Clear out currentPCFile and visitedPCFile (don't have to mess with
* func and line since these are not consulted when I decide whether or
* not to reinstate marks on session switching). This is done as part
* of the fix for 4101911 to ensure that marks are not reinstated on
* session switching when they have been removed.
*/
protected final void deleteMarkLocations() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
setCurrentLine(null, false, false, ShowMode.NONE, false);
}
});
}
protected final void resetCurrentLine() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
setCurrentLine(null, false, false, ShowMode.NONE, false);
}
});
}
@Override
public Location getVisitedLocation() {
return visitedLocation;
}
public void annotateDis(boolean andShow) {
if (visitedLocation != null) {
DebuggerAnnotation marker;
if (visitedLocation.visited()) {
marker = visitDisMarker;
currentDisPCMarker.setLine(null, isCurrent());
} else {
marker = currentDisPCMarker;
visitDisMarker.setLine(null, isCurrent());
}
DisassemblyUtils.annotatePC(visitedLocation, marker, andShow);
} else {
currentDisPCMarker.setLine(null, isCurrent());
visitDisMarker.setLine(null, isCurrent());
}
}
protected static enum ShowMode {
SOURCE, // show source
DIS, // show disassembly
AUTO, // decide based on where we are now
NONE; // do not show at all
}
private boolean inDisMode() {
return Disassembly.isInDisasm() && disRequested;
}
protected void setCurrentLine(Line l, boolean visited, boolean srcOOD, ShowMode showMode, boolean focus) {
if (l != null) {
if (showMode == ShowMode.SOURCE || (showMode == ShowMode.AUTO && !inDisMode())) {
EditorBridge.showInEditor(l, focus);
}
if (visited) {
visitMarker.setLine(l, isCurrent());
currentPCMarker.setLine(null, isCurrent());
} else {
visitMarker.setLine(null, isCurrent());
// CR 7009746
if (!state.isRunning)
currentPCMarker.setLine(l, isCurrent());
}
// Annotate dis
annotateDis(showMode == ShowMode.DIS || (showMode == ShowMode.AUTO && inDisMode()));
} else {
visitMarker.setLine(null, isCurrent());
visitDisMarker.setLine(null, isCurrent());
currentPCMarker.setLine(null, isCurrent());
currentDisPCMarker.setLine(null, isCurrent());
}
// Arrange for DebuggerManager.error_sourceModified()
// to emit something.
this.srcOOD = srcOOD;
if (srcOOD) {
// Dbx emits "source-modified" errors once per "context", so
// while we might get OOD we might not have a good error message.
// So put a placeholder.
// error_sourceModified() might enhance it "shortly".
setSrcOODMessage(Catalog.get("SourceOODWarn")); // NOI18N
} else {
// error_sourceModified() doesn't get called when there's
// _no_ out of date src, so we need to clear
setSrcOODMessage(null);
}
}
// A kind of a HACK which allows registerDisassemblerWindow to know whether
// it was called by clicking tabs or via other switching actions.
protected volatile boolean viaShowLocation = false;
/**
* Show the current visiting location in the editor area.
* If user has requested source and it's available show source code in an
* editor pane.
* Else, if user has requested disassembly or no source information is
* available, bring up the disassembler.
*/
private static final RequestProcessor RP = new RequestProcessor("Debugger location updater", 1); // NOI18N
private void updateLocation(final boolean andShow, final ShowMode showModeOverride, final boolean focus) {
RP.post(new Runnable() {
@Override
public void run() {
final Location loc = getVisitedLocation();
final boolean haveSource = loc != null && loc.hasSource();
// Locations should already be in local path form.
final Line curentLine = !haveSource ? null : EditorBridge.getLine(fmap().engineToWorld(loc.src()), loc.line(),
NativeDebuggerImpl.this);
// To prevent locks on EDT when updateLocation is initiated by
// dbx using glue (which is binded to EDT) we need to prepare
// a document before entering the dispatch thread.
// See IZ#234276
if (curentLine != null) {
EditorCookie ec = curentLine.getLookup().lookup(EditorCookie.class);
if (ec != null) {
ec.prepareDocument().waitFinished();
}
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (haveSource && curentLine != null) {
ShowMode showMode = ShowMode.NONE;
if (andShow) {
showMode = showModeOverride;
NativeBreakpoint breakpoint = loc.getBreakpoint();
if (breakpoint != null && ShowMode.AUTO.equals(showModeOverride)) {
if (breakpoint instanceof InstructionBreakpoint) {
showMode = ShowMode.DIS;
} else {
showMode = ShowMode.SOURCE;
}
}
}
setCurrentLine(curentLine, loc.visited(), loc.srcOutOfdate(), showMode, focus);
} else {
if (loc != null && loc.pc() != 0) {
Disassembly.open();
annotateDis(andShow); // In order to update current line when source is unavailable
}
}
}
});
}
});
}
@Override
public void requestDisassembly() {
disRequested = true;
showCurrentDis();
}
public void showCurrentSource() {
Location loc = getVisitedLocation();
if (! (loc != null && loc.hasSource()) ) {
NativeDebuggerManager.warning(Catalog.get("Dis_MSG_NoSource"));
return;
}
disRequested = false;
updateLocation(true, ShowMode.SOURCE, false);
}
public void showCurrentDis() {
Disassembly.open();
updateLocation(true, ShowMode.DIS, false);
}
@Override
public final void setVisitedLocation(Location loc, boolean changeFocus) {
this.visitedLocation = loc;
requestAutos();
getDisassembly().stateUpdated();
//focus is the problem
//if we are in Debugger Console changing focus to editor
//it will really annoy our user
updateLocation(true, ShowMode.AUTO, changeFocus);
}
@Override
public final void setVisitedLocation(Location loc) {
setVisitedLocation(loc, false);
}
@Override
public void setSrcOODMessage(String msg) {
if (msg != null && !srcOOD) {
// If srcOOD is not set it's quite likley that this is a
// spurious setting, so ignore it.
return;
}
// remember for when we switch sessions (activate() and deactivate())
srcOODMessage = msg;
EditorBridge.setStatus(msg);
}
/**
* When not -1, the next resume should deliver the given signal
* number to the process.
*/
protected int deliverSignal = -1;
protected OptionLayers optionLayers = null;
@Override
public OptionLayers optionLayersInit() {
// we don't want to create one, if optionLayers is null
return optionLayers;
}
protected void addExtraOptions(OptionLayers optionLayers) {
}
@Override
public final OptionLayers optionLayers() {
// We want to create one, if optionLayers is null
if (optionLayers == null) {
OptionSet globalOptions = manager().globalOptions();
optionLayers = new OptionLayers(globalOptions);
// We may get a null profile on a botched engine startup
// See bug 6307423.
// Probably SHOULD do more work.
OptionSet profileOptions = null;
if (profileBridge().currentDbgProfile() != null) {
profileOptions = profileBridge().currentDbgProfile().getOptions();
assert profileOptions != null : "debug profile must have options";
optionLayers.push(profileOptions);
}
addExtraOptions(optionLayers);
}
return optionLayers;
}
// interface NativeDebugger
@Override
public void optionLayersReset() {
// arrange so we re-create optionLayers
optionLayers = null;
}
/**
* Called when this session has been switched to
* 'redundant' is true when we double-click on the same session.
*/
@Override
public void activate(boolean redundant) {
ioPack.switchTo();
//moved to dbx, gdb uses new disassembly
// disassemblerWindow().setDebugger(this);
// disassemblerWindow().getView().setModelController(disModel(),
// disController(),
// disStateModel(),
// breakpointModel());
// need to focus here, otherwise EditorContext does not see that the editor has updated
updateLocation(true, disActive ? ShowMode.DIS : ShowMode.SOURCE, true);
// CR 6986846
if (disActive) {
Disassembly.open();
}
visitMarker.attach(true);
visitDisMarker.attach(true);
currentPCMarker.attach(true);
currentDisPCMarker.attach(true);
EditorBridge.setStatus(srcOODMessage);
updateActions();
if (redundant) {
return;
}
bm().breakpointUpdater().treeChanged();
for (NativeBreakpoint bpt : bm().breakpointBag().getBreakpoints()) {
if (!bpt.isEnabled()) {
continue;//do nothing for disabled breakpoints
}
bpt.showAnnotationsFor(true, this);
}
registerRegistersWindow(RegistersWindow.getDefault().isShowing() ? RegistersWindow.getDefault() : null);
if (MemoryWindow.getDefault().isShowing()) {
registerMemoryWindow(MemoryWindow.getDefault());
MemoryWindow.getDefault().setDebugger(this);
} else {
registerMemoryWindow(null);
}
if (Disassembly.isOpened()) {
registerDisassembly(getDisassembly());
getDisassembly().stateUpdated();
} else {
registerDisassembly(null);
}
}
/**
* Called when this session has been switched away from
* 'redundant' is true when we double-click on the same session.
*/
@Override
public void deactivate(boolean redundant) {
if (redundant) {
return;
}
// The following was causing actions to be disabled as we
// switched between sessions. I can't recall or think now of
// why we needed to do this.
// TMP actionEnabler().update(null);
bm().breakpointUpdater().treeChanged();
for (NativeBreakpoint bpt : bm().breakpointBag().getBreakpoints()) {
bpt.showAnnotationsFor(false, this);
}
// remember src/dis state
disActive = Disassembly.isInDisasm();
getDisassembly().reset();
visitMarker.detach();
visitDisMarker.detach();
currentPCMarker.detach();
currentDisPCMarker.detach();
EditorBridge.setStatus(null);
}
@Override
public boolean getVerboseStack() {
if ("on".equals(DebuggerOption.STACK_VERBOSE.getCurrValue(optionLayers()))) { // NOI18N
return true;
} else {
return false;
}
// SHOULD cause the StackView actions provider to pull?
// or somehow tickle the action?
}
/**
* Common code to be called by subclass when engine goes away.
*/
protected final void preKill() {
// May be a bit redundant as it is usually set in postKill(),
// but we might get here just by the user typing 'quit' or
// the engine dying on us.
postedKill = true;
// DEBUG System.out.println("NativeDebuggerImpl.kill()");
// SHOULD disable all (most) actions so we don't end up sending
// stuff to engine.
if ( /* OLD ConsoleTopComponent.getDefault() != null && */getIOPack() != null
&& // getIOPack().console() != null &&
getIOPack().console().getTerm() != null) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
String warn = debuggerType() + " terminated\n"; // NOI18N
char[] warnArray = warn.toCharArray();
getIOPack().console().getTerm().putChars(warnArray,
0, warnArray.length);
}
});
}
// Close if no more sessions
NativeSession[] sessions = NativeDebuggerManager.get().getSessions();
if (sessions.length <= 1) {
Disassembly.close();
}
// Go through the array conversion otherwise we'll get
// ConcurrentModificatonExpcetions.
for (Handler h : bm().getHandlers()) {
bm().deleteHandler(h, Gen.secondary(null), true);
}
for (WatchVariable w : getWatches()) {
deleteWatch(w, false);
}
if (NativeDebuggerManager.isPerTargetBpts()) {
bm().breakpointBag().cleanupBpts();
}
DbgActionHandler dah = getNDI().getDah();
if (dah != null) {
dah.executionFinished(0);
}
}
/*
* Track if the disassembly window is "showing".
*/
private boolean asmVisible;
protected final boolean isAsmVisible() {
return asmVisible;
}
protected final void setAsmVisible(boolean asmVisible) {
this.asmVisible = asmVisible;
}
protected static enum CaptureState {
NONE, INITIAL, FINAL
}
private CaptureState captureState = CaptureState.NONE;
private CaptureInfo captureInfo;
abstract protected void stopUpdates();
abstract protected void startUpdates();
protected final void setCaptureState(CaptureState captureState) {
if (Log.Capture.state) {
System.out.printf("setCaptureState(): %s -> %s\n", // NOI18N
this.captureState, captureState);
}
this.captureState = captureState;
}
protected final CaptureState getCaptureState() {
return captureState;
}
protected final void setCaptureInfo(CaptureInfo captureInfo) {
if (Log.Capture.info) {
System.out.printf("setCaptureInfo(): %s\n", captureInfo); // NOI18N
}
this.captureInfo = captureInfo;
}
protected final CaptureInfo getCaptureInfo() {
return captureInfo;
}
protected final void captureFailed() {
ExternalStart xstart = ExternalStartManager.getXstart(getHost());
if (captureState != CaptureState.NONE) {
captureState = CaptureState.NONE;
startUpdates();
if (captureState == CaptureState.FINAL) {
NativeDebuggerManager.warning(String.format("ss_attach failed to exec %s",
captureInfo.executable));
} else {
if (xstart != null) {
xstart.fail();
}
NativeDebuggerManager.warning(String.format("%s failed during capture", debuggerType()));
}
} else {
// If we cancel the startup of an engine captureState
// will be NONE so we test isCaptured() here as well.
NativeDebuggerInfo ndi = getNDI();
if (xstart != null && ndi.isCaptured()) {
xstart.fail();
}
}
}
//
// Assembly level debugging support
//
protected abstract DisFragModel disModel();
public abstract Controller disController();
protected InstBreakpointModel breakpointModel() {
return breakpointModel;
}
protected final StateModelAdaptor disStateModel() {
return disStateModel;
}
protected class DisModelSupport implements DisFragModel {
private List<Line> current_addrs = new CopyOnWriteArrayList<Line>();
private List<Listener> listeners = new CopyOnWriteArrayList<Listener>();
// implement DisFragModel
@Override
public void clear() {
current_addrs.clear();
}
// implement DisFragModel
@Override
public Line getItem(int i) {
return current_addrs.get(i);
}
// implement DisFragModel
@Override
public int size() {
return current_addrs.size();
}
// interface DisFragModel
@Override
public void addListener(Listener listener) {
listeners.add(listener);
}
// interface DisFragModel
@Override
public void removeListener(Listener listener) {
listeners.remove(listener);
}
protected final void add(String memaddr, String memvalue) {
// careful!
// DisView.addrFromLine is sensitive to this number of spaces
current_addrs.add(new Line(memaddr, memvalue));
}
protected final void addAll(List<Line> lines) {
current_addrs.addAll(lines);
}
protected final void update() {
for (Listener listener : listeners) {
listener.fragUpdated();
}
}
@Override
public Iterator<Line> iterator() {
return current_addrs.iterator();
}
}
protected abstract class ControllerSupport implements Controller {
private StateListener runToCursorListener = null;
// interface Controller
@Override
abstract public void requestDis(boolean withSource);
// interface Controller
@Override
abstract public void requestDis(String start, int count, boolean withSource);
protected abstract void setBreakpointHelp(String address);
/*
* Add or Remove Instruction breakpoint by address
*/
// interface Controller
@Override
public void setBreakpoint(String address, boolean add) {
if (add) {
setBreakpointHelp(address);
} else {
long addr = Address.parseAddr(address);
InstBreakpointModel.Bpt foundBpt = breakpointModel().findBptByAddr(addr);
if (foundBpt != null && foundBpt.bpt != null) {
foundBpt.bpt.dispose();
}
}
}
/*
* Toggle Instruction breakpoint by address
*/
// interface Controller
@Override
public void toggleBreakpoint(String address) {
long addr = Address.parseAddr(address);
InstBreakpointModel.Bpt foundBpt = breakpointModel().findBptByAddr(addr);
if (foundBpt == null) {
setBreakpointHelp(address);
} else {
if (foundBpt.bpt != null) {
foundBpt.bpt.dispose();
}
}
}
/*
* Enable or disable Instruction Breakpoint Annotation
*/
// interface Controller
@Override
public final void enableBreakpoint(long address, NativeBreakpoint bpt,
boolean enable) {
if (enable) {
breakpointModel().enable(address, bpt);
} else {
InstBreakpointModel.Bpt foundBpt = breakpointModel().findBptByAddr(address);
breakpointModel().disable(foundBpt);
}
}
/*
* Add or Remove Instruction Breakpoint Annotation
* interface Controller
*/
// interface Controller
@Override
public final void updateBreakpoint(long address, NativeBreakpoint bpt,
boolean add) {
if (add) {
breakpointModel().add(address, bpt);
} else {
InstBreakpointModel.Bpt foundBpt = breakpointModel().findBptByAddr(address);
breakpointModel().remove(foundBpt);
}
}
// interface Controller
public final void runToCursor(String addr) {
runToCursorInst(addr);
}
// interface Controller
@Override
public final void addStateListenerInst(StateListener sl) {
if (runToCursorListener == null) {
runToCursorListener = sl;
addStateListener(sl);
}
}
// interface Controller
@Override
public final void removeStateListenerInst(StateListener sl) {
// 6567570
if (runToCursorListener != null) {
runToCursorListener = null;
removeStateListener(sl);
}
}
}
protected static final class InstBreakpointModel implements BreakpointModel {
public class Bpt {
public long addr;
public NativeBreakpoint bpt;
Bpt(long a, NativeBreakpoint b) {
addr = a;
bpt = b;
}
}
private List<Bpt> breakpoints_List = new CopyOnWriteArrayList<Bpt>();
private List<Listener> listeners = new CopyOnWriteArrayList<Listener>();
public InstBreakpointModel() {
}
// interface BreakpointModel
@Override
public void addListener(Listener listener) {
listeners.add(listener);
}
// interface BreakpointModel
@Override
public void removeListener(Listener listener) {
listeners.remove(listener);
}
/*
* Return bpt at this address.
*/
public Bpt findBptByAddr(long address) {
for (Bpt bpt : breakpoints_List) {
if (address == bpt.addr) {
return bpt;
}
}
return null;
}
/*
* Return number of disabled bpts at this address.
*/
// interface BreakpointModel
@Override
public int findDisabled(long address) {
int count = 0;
for (Bpt bpt : breakpoints_List) {
if (address == bpt.addr && !bpt.bpt.isEnabled()) {
count++;
}
}
return count;
}
/*
* Return number of bpts at this address.
*/
// interface BreakpointModel
@Override
public int find(long address) {
int count = 0;
for (Bpt bpt : breakpoints_List) {
if (address == bpt.addr) {
count++;
}
}
return count;
}
public void enable(long address, NativeBreakpoint bpt) {
for (Listener l : listeners) {
l.bptUpdated();
}
}
public void disable(Bpt bpt) {
for (Listener l : listeners) {
l.bptUpdated();
}
}
public void add(long address, NativeBreakpoint bpt) {
breakpoints_List.add(new Bpt(address, bpt));
for (Listener l : listeners) {
l.bptUpdated();
}
}
public void remove(Bpt bpt) {
breakpoints_List.remove(bpt);
for (Listener l : listeners) {
l.bptUpdated();
}
}
@Override
public NativeBreakpoint[] getBreakpoints() {
NativeBreakpoint[] res = new NativeBreakpoint[breakpoints_List.size()];
int idx = 0;
for (Bpt bpt : breakpoints_List) {
res[idx++] = bpt.bpt;
}
return res;
}
}
protected final class StateModelAdaptor implements StateModel {
private Location location = Location.EMPTY;
private HashMap<Long, Integer> addrHashMap;
private final List<Listener> listeners = new CopyOnWriteArrayList<Listener>();
public StateModelAdaptor() {
}
// interface StateModel
@Override
public void addListener(Listener listener) {
listeners.add(listener);
}
// interface StateModel
@Override
public void removeListener(Listener listener) {
listeners.remove(listener);
}
// interface StateModel
@Override
public void setAddrHashMap(HashMap<Long, Integer> hashmap) {
addrHashMap = hashmap;
}
// interface StateModel
@Override
public boolean isVisited() {
return location.visited();
}
// interface StateModel
@Override
public long getPC() {
return location.pc();
}
// interface StateModel
@Override
public String getFunction() {
return location.func();
}
// interface StateModel
@Override
public String getFile() {
return location.src();
}
// interface StateModel
@Override
public int getLine() {
return location.line();
}
private boolean inRange(long addr) {
if (addrHashMap == null)
return false;
Integer pos = addrHashMap.get(addr);
if (pos != null) {
return true;
}
return false;
}
public void updateStateModel(Location location, boolean retrieve) {
/*
System.out.printf("updateStateModel()\n");
System.out.printf("%s\n", location);
*/
this.location = location;
if (retrieve && !inRange(location.pc())) {
disController().requestDis(true);
} else {
for (Listener l : listeners) {
l.stateUpdated();
}
}
}
}
// interface NativeDebugger
@Override
public final void InstBptEnabled(long addr, NativeBreakpoint bpt) {
disController().enableBreakpoint(addr, bpt, true);
}
// interface NativeDebugger
@Override
public final void InstBptDisabled(long addr, NativeBreakpoint bpt) {
disController().enableBreakpoint(addr, bpt, false);
}
// interface NativeDebugger
@Override
public final void InstBptAdded(long addr, NativeBreakpoint bpt) {
disController().updateBreakpoint(addr, bpt, true);
}
// interface NativeDebugger
@Override
public final void InstBptRemoved(long addr, NativeBreakpoint bpt) {
disController().updateBreakpoint(addr, bpt, false);
}
public static String getDebuggerString(String debuggerID, MakeConfiguration conf) {
// Figure out dbx command
// Copied from GdbProfile
CompilerSet2Configuration csconf = conf.getCompilerSet();
/* OLD
if (csconf.isValid()) {
cs = CompilerSetManager.get(conf.getDevelopmentHost().getExecutionEnvironment()).getCompilerSet(csconf.getOption());
} else {
cs = CompilerSet.getCompilerSet(conf.getDevelopmentHost().getExecutionEnvironment(), csconf.getOldName(), conf.getPlatformInfo().getPlatform());
CompilerSetManager.get(conf.getDevelopmentHost().getExecutionEnvironment()).add(cs);
csconf.setValid();
}
Tool debuggerTool = cs.getTool(Tool.DebuggerTool);
if (debuggerTool != null) {
return debuggerTool.getPath();
}
*/
CompilerSet cs = csconf.getCompilerSet();
ExecutionEnvironment exEnv = conf.getDevelopmentHost().getExecutionEnvironment();
String csname = csconf.getOption();
if (cs == null) {
final int platform = conf.getPlatformInfo().getPlatform();
CompilerFlavor flavor = CompilerFlavor.toFlavor(csname, platform);
flavor = flavor == null ? CompilerFlavor.getUnknown(platform) : flavor;
cs = CompilerSetFactory.getCompilerSet(exEnv, flavor, csname);
}
Tool debuggerTool = cs.getTool(PredefinedToolKind.DebuggerTool);
if (debuggerTool != null) {
Collection<? extends DebuggerToolRecognizer> debuggerRecognizers = Lookup.getDefault().lookupAll(DebuggerToolRecognizer.class);
for (DebuggerToolRecognizer debuggerToolRecognizer : debuggerRecognizers) {
if (debuggerToolRecognizer.canHandle(debuggerID) && debuggerToolRecognizer.isTheSame(debuggerID, debuggerTool)) {
String path = debuggerTool.getPath();
if (path != null && !path.isEmpty()) {
return path;
}
}
}
//fallback
if (debuggerTool.getName().contains(debuggerID)) {
String path = debuggerTool.getPath();
if (path != null && !path.isEmpty()) {
return path;
}
}
}
// ask for debugger, IZ 192540
ToolsPanelModel model = new LocalToolsPanelModel();
model.setCRequired(false);
model.setCppRequired(false);
model.setFortranRequired(false);
model.setMakeRequired(false);
model.setDebuggerRequired(true);
model.setShowRequiredBuildTools(false);
model.setShowRequiredDebugTools(true);
model.setCompilerSetName(null); // means don't change
model.setSelectedCompilerSetName(csname);
model.setSelectedDevelopmentHost(exEnv);
model.setEnableDevelopmentHostChange(false);
BuildToolsAction bt = SystemAction.get(BuildToolsAction.class);
bt.setTitle(Catalog.get("LBL_ResolveMissingDebugger_Title")); // NOI18N
if (bt.initBuildTools(model, new ArrayList<String>(), cs)) {
conf.getCompilerSet().setValue(model.getSelectedCompilerSetName());
cs = CompilerSetManager.get(exEnv).getCompilerSet(model.getSelectedCompilerSetName());
if (cs != null) {
debuggerTool = cs.getTool(PredefinedToolKind.DebuggerTool);
if (debuggerTool != null) {
return debuggerTool.getPath();
}
}
}
return null;
}
@Override
public void registerMemoryWindow(MemoryWindow w) {
}
@Override
public Set<String> requestAutos() {
autos.clear();
if (!isShowAutos()) {
return Collections.emptySet();
}
Location location = getVisitedLocation();
if (location == null || ! location.hasSource()) {
localUpdater.batchOffForce(); // cause a pull to clear view
return Collections.emptySet();
}
return Autos.get(EditorBridge.documentFor(location.src(), this), location.line()-1);
}
@Override
public int getAutosCount() {
return autos.size();
}
@Override
public Variable[] getAutos() {
Variable array[] = autos.toArray(new Variable[autos.size()]);
return array;
}
@Override
public void copyStack() {
if (guiStackFrames == null)
return;
StringBuilder frameStr = new StringBuilder(guiStackFrames.length);
for (int fx = 0; fx < guiStackFrames.length; fx++) {
frameStr.append(guiStackFrames[fx].getLocationName()).append(" at ").append(//NOI18N
guiStackFrames[fx].getFullPath()).append(":").append(guiStackFrames[fx].getLineNo());//NOI18N
frameStr.append('\n');
}
Clipboard clipboard = org.openide.util.Lookup.getDefault().lookup(Clipboard.class);
if (clipboard == null) {
clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
}
Transferable transferableText =
new StringSelection(frameStr.toString());
clipboard.setContents(
transferableText,
null);
}
@Override
public void registerDebuggingViewModel(ModelListener model) {
debuggingViewUpdater.addListener(model);
}
}
|
92346eddef7aa4992f493c6381241b98011c3cef | 792 | java | Java | Swing_Programing/src/bp2_lab04/Lab4_Soru3.java | sametkaya/Java_Swing_Programming_2 | c50a138920419b32ba97d4d4daefd891bed5c3a3 | [
"MIT"
] | 5 | 2017-03-02T16:30:04.000Z | 2017-03-27T20:26:30.000Z | Swing_Programing/src/bp2_lab04/Lab4_Soru3.java | sametkaya/Java_Swing_Programming_2 | c50a138920419b32ba97d4d4daefd891bed5c3a3 | [
"MIT"
] | null | null | null | Swing_Programing/src/bp2_lab04/Lab4_Soru3.java | sametkaya/Java_Swing_Programming_2 | c50a138920419b32ba97d4d4daefd891bed5c3a3 | [
"MIT"
] | 1 | 2017-03-10T17:19:36.000Z | 2017-03-10T17:19:36.000Z | 24.75 | 79 | 0.556818 | 996,920 | /*
* 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 bp2_lab04;
/**
*
* @author samet
*/
public class Lab4_Soru3 {
public static void main(String[] args) {
String cumle = "Fatih SUltan Mehmet Vakif Üniversitesi";
// char [] karakterler = new char[cumle.length()];
// for (int i = 0; i < cumle.length(); i++) {
// karakterler[i]=cumle.charAt(i);
// }
//
// for (char c : karakterler) {
// System.out.println(c);
// }
//
char[] karakterler = cumle.toCharArray();
for (char c : karakterler) {
System.out.println(c);
}
}
}
|
92346fe69e5827a680bfb5ec7398758dbca42d5c | 2,513 | java | Java | src/test/java/com/github/git24j/core/GitObjectTest.java | git24j/git24j | 9ea76baaff965ff4bfde15b5cc9b8fbcf2ef1330 | [
"MIT"
] | 25 | 2020-01-04T18:07:45.000Z | 2022-02-20T19:16:06.000Z | src/test/java/com/github/git24j/core/GitObjectTest.java | git24j/git24j | 9ea76baaff965ff4bfde15b5cc9b8fbcf2ef1330 | [
"MIT"
] | 5 | 2020-06-18T02:34:32.000Z | 2022-01-25T03:48:47.000Z | src/test/java/com/github/git24j/core/GitObjectTest.java | git24j/git24j | 9ea76baaff965ff4bfde15b5cc9b8fbcf2ef1330 | [
"MIT"
] | 4 | 2019-11-06T02:26:51.000Z | 2022-02-20T19:16:07.000Z | 36.647059 | 95 | 0.642857 | 996,921 | package com.github.git24j.core;
import org.junit.Assert;
import org.junit.Test;
public class GitObjectTest extends TestBase {
@Test
public void search() {
Repository testRepo = TestRepo.SIMPLE1.tempRepo(folder);
GitObject obj = Revparse.single(testRepo, "HEAD");
Assert.assertEquals(GitObject.Type.COMMIT, obj.type());
GitObject searched = GitObject.lookup(testRepo, obj.id(), GitObject.Type.COMMIT);
Assert.assertEquals(GitObject.Type.COMMIT, searched.type());
Assert.assertEquals(searched.getRawPointer(), obj.getRawPointer());
try {
GitObject.lookupPrefix(testRepo, "ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6b", GitObject.Type.COMMIT);
Assert.fail("should have thrown ENOTFOUND error");
} catch (GitException e) {
Assert.assertEquals(GitException.ErrorCode.ENOTFOUND, e.getCode());
}
}
@Test
public void lookup() {
Repository testRepo = TestRepo.SIMPLE1.tempRepo(folder);
GitObject obj = Revparse.single(testRepo, "HEAD");
GitObject lookedUp =
GitObject.lookupPrefix(
testRepo, obj.id().toString().substring(0, 10), GitObject.Type.COMMIT);
Assert.assertEquals(GitObject.Type.COMMIT, lookedUp.type());
Assert.assertEquals(lookedUp.getRawPointer(), obj.getRawPointer());
}
@Test
public void shortId() {
Repository testRepo = TestRepo.SIMPLE1.tempRepo(folder);
GitObject obj = Revparse.single(testRepo, "master");
Buf buf = obj.shortId();
Assert.assertTrue(buf.getAsize() > 0);
}
@Test
public void owner() {
Repository testRepo = TestRepo.SIMPLE1.tempRepo(folder);
GitObject obj = Revparse.single(testRepo, "HEAD");
Repository owner = obj.owner();
Assert.assertEquals(testRepo.getPath(), owner.getPath());
}
@Test
public void peel() {
Repository testRepo = TestRepo.SIMPLE1.tempRepo(folder);
GitObject obj = Revparse.single(testRepo, "HEAD");
GitObject peel = obj.peel(GitObject.Type.COMMIT);
Assert.assertNotNull(peel);
}
@Test
public void dup() {
Repository testRepo = TestRepo.SIMPLE1.tempRepo(folder);
GitObject obj = Revparse.single(testRepo, "HEAD");
GitObject obj2 = new GitObject(true, obj.getRawPointer());
GitObject copy = obj2.dup();
Assert.assertEquals(copy.shortId().getPtr(), obj.shortId().getPtr());
}
}
|
9234717296d84bdb45e321c350dc4aee83fd9925 | 533 | java | Java | app/src/main/java/com/example/qpdjg/all_for/Item/CategoryItem.java | willtriti03/Allfor | 096ae3b7844cef3f266bcabfc1620f3e05234719 | [
"MIT"
] | null | null | null | app/src/main/java/com/example/qpdjg/all_for/Item/CategoryItem.java | willtriti03/Allfor | 096ae3b7844cef3f266bcabfc1620f3e05234719 | [
"MIT"
] | null | null | null | app/src/main/java/com/example/qpdjg/all_for/Item/CategoryItem.java | willtriti03/Allfor | 096ae3b7844cef3f266bcabfc1620f3e05234719 | [
"MIT"
] | null | null | null | 18.37931 | 67 | 0.622889 | 996,922 | package com.example.qpdjg.all_for.Item;
import android.content.Intent;
import android.graphics.drawable.Drawable;
public class CategoryItem {
Drawable icon;
String txt;
String toCall;
public CategoryItem(Drawable icon, String txt, String toCall) {
this.icon = icon;
this.txt = txt;
this.toCall = toCall;
}
public Drawable getIcon() {
return icon;
}
public String gettoCall() {
return toCall;
}
public String getTxt() {
return txt;
}
}
|
923471cc080cc6120f8ba350b2548178c89ba6ea | 1,517 | java | Java | src/main/java/io/gravitee/connector/http/AbstractHttpConnection.java | gravitee-io/gravitee-connector-http | 0c133ecc118d7464f8aa1a4bd8ee20d1d4e9a332 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/gravitee/connector/http/AbstractHttpConnection.java | gravitee-io/gravitee-connector-http | 0c133ecc118d7464f8aa1a4bd8ee20d1d4e9a332 | [
"Apache-2.0"
] | 1 | 2022-02-23T08:02:54.000Z | 2022-02-23T08:55:34.000Z | src/main/java/io/gravitee/connector/http/AbstractHttpConnection.java | AlexRogalskiy/gravitee-connector-http | 025b2a98db415f37df73e56262b12f37e47a8ddc | [
"Apache-2.0"
] | 2 | 2021-12-26T12:35:14.000Z | 2022-03-03T16:42:36.000Z | 31.604167 | 123 | 0.724456 | 996,923 | /**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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.gravitee.connector.http;
import io.gravitee.connector.api.Response;
import io.gravitee.connector.http.endpoint.HttpEndpoint;
import io.gravitee.gateway.api.handler.Handler;
import io.vertx.core.http.HttpClient;
/**
* @author David BRASSELY (david.brassely at graviteesource.com)
* @author GraviteeSource Team
*/
public abstract class AbstractHttpConnection<E extends HttpEndpoint> extends io.gravitee.connector.api.AbstractConnection {
protected final E endpoint;
public AbstractHttpConnection(E endpoint) {
this.endpoint = endpoint;
}
public abstract void connect(
HttpClient httpClient,
int port,
String host,
String uri,
Handler<Void> connectionHandler,
Handler<Void> tracker
);
protected void sendToClient(Response response) {
this.responseHandler.handle(response);
}
}
|
923473bffb4d1ea8f0071f52521bd576b21c4a2d | 9,244 | java | Java | src/pasketti/core/Regex.java | ewaldgrusk/pasketti | 6df9b74f4e85f471b21a4ec983cb9918ea79e8f4 | [
"MIT"
] | null | null | null | src/pasketti/core/Regex.java | ewaldgrusk/pasketti | 6df9b74f4e85f471b21a4ec983cb9918ea79e8f4 | [
"MIT"
] | null | null | null | src/pasketti/core/Regex.java | ewaldgrusk/pasketti | 6df9b74f4e85f471b21a4ec983cb9918ea79e8f4 | [
"MIT"
] | null | null | null | 29.069182 | 80 | 0.599308 | 996,924 | package pasketti.core;
import java.util.Objects;
import java.util.function.BinaryOperator;
import java.util.function.Predicate;
/**
* A regular expression.
*
* @author Nora Gruner
* @since 0.1.0
*/
public abstract class Regex<T> {
private final boolean active;
private final boolean empty;
private final boolean matched;
private Regex(boolean active, boolean empty, boolean matched) {
this.active = active;
this.empty = empty;
this.matched = matched;
}
public final boolean isActive() {
return active;
}
public final boolean isEmpty() {
return empty;
}
public final boolean hasMatched() {
return matched;
}
public final Regex<T> shift(boolean mark, T value) {
return (active || mark) ? step(mark, value) : this;
}
public abstract Regex<T> step(boolean mark, T value);
//----------------------------------------------------------------------------
// Smart constructors --------------------------------------------------------
//----------------------------------------------------------------------------
private static final Regex<?> EPSILON = new Epsilon();
/**
* Returns a regular expression that matches the empty sequence.
*
* @param <T> the type of the symbols
* @return a regex matching the empty sequence
*/
@SuppressWarnings("unchecked")
public static <T> Regex<T> epsilon() {
return (Regex<T>) EPSILON;
}
/**
* Returns a regular expression that matches any symbol satisfying the
* provided predicate.
*
* <p>For example, the regular expression {@code Regex.symbol(c -> c == 'A')}
* matches the capital letter <em>A</em>.
*
* @param <T> the type of the symbols
* @param predicate a predicate (may not be {@code null})
* @return a regex matching any symbol satisfying {@code predicate}
*/
public static <T> Regex<T> symbol(Predicate<T> predicate) {
Objects.requireNonNull(predicate, "predicate may not be null");
return new Symbol<T>(predicate);
}
/**
* Returns the result of reducing the specified array of elements with the
* provided binary operator.
*
* <p><em>Note:</em> This helper method does not validate its arguments.
*
* @param <U> the type of the array elements
* @param operator an associative function for combining two elements
* @param array a non-empty array of elements
* @return the result of reducing {@code array}
*/
private static <U> U reduce(BinaryOperator<U> operator, U[] array) {
U result = array[0];
for (int k = 1; k < array.length; k += 1) {
result = operator.apply(result, array[k]);
}
return result;
}
/**
* Checks that the specified array of elements does not contain any null
* elements.
*
* <p><em>Note:</em> This helper method does not check that the array itself
* is not {@code null}.
*
* @param <U> the type of the array elements
* @param array an array of elements
* @return the {@code array} if it does not contain any null elements
*/
private static <U> U[] requireNonNullElements(U[] array) {
for (int k = 0; k < array.length; k += 1) {
if (array[k] == null) {
throw new NullPointerException(
String.format("element at index %d may not be null", k)
);
}
}
return array;
}
/**
* Returns a regular expression that matches any sequence matched by either of
* the provided regular expressions.
*
* <p>The operation {@code choice} is also known as alternation. It is usually
* denoted by a vertical bar, i.e. {@code <regex1>|<regex2>|...}.
*
* <p>Invoking this method with no arguments returns the same result as
* calling {@link #epsilon()}.
*
* @param <T> the type of the symbols
* @param regexes regular expressions (may not be {@code null})
* @return the alternation of {@code regexes}
*/
@SafeVarargs public static <T> Regex<T> choice(Regex<T>... regexes) {
Objects.requireNonNull(regexes, "regexes may not be null");
if (regexes.length == 0) {
return epsilon(); // Early exit.
}
return reduce(Choice<T>::new, requireNonNullElements(regexes));
}
/**
* Returns the concatenation of the provided regular expressions.
*
* <p>The operation {@code concat} is usually expressed as simple
* juxtaposition, i.e. {@code <regex1><regex2>...}.
*
* <p>Invoking this method with no arguments returns the same result as
* calling {@link #epsilon()}.
*
* @param <T> the type of the symbols
* @param regexes regular expressions (may not be {@code null})
* @return the concatenation of {@code regexes}
*/
@SafeVarargs public static <T> Regex<T> concat(Regex<T>... regexes) {
Objects.requireNonNull(regexes, "regexes may not be null");
if (regexes.length == 0) {
return epsilon(); // Early exit.
}
return reduce(Concat<T>::new, requireNonNullElements(regexes));
}
/**
* Returns a regular expression that matches what zero or <em>one</em>
* consecutive occurrences of the provided regular expression would match.
*
* <p>The operation {@code optional} is usually denoted by a question mark,
* i.e. {@code <regex>?}.
*
* @param <T> the type of the symbols
* @param regex a regular expression (may not be {@code null})
* @return the regular expression {@code <regex>?}
*/
public static <T> Regex<T> optional(Regex<T> regex) {
Objects.requireNonNull(regex, "regex may not be null");
return new Choice<T>(regex, epsilon());
}
/**
* Returns a regular expression that matches what zero or <em>more</em>
* consecutive occurrences of the provided regular expression would match.
*
* <p>The operation {@code repetition} is also known as Kleene closure. It is
* usually denoted by an asterisk, i.e. {@code <regex>*}.
*
* @param <T> the type of the symbols
* @param regex a regular expression (may not be {@code null})
* @return the Kleene closure of {@code regex}
*/
public static <T> Regex<T> repetition(Regex<T> regex) {
Objects.requireNonNull(regex, "regex may not be null");
return new Repetition<T>(regex);
}
//----------------------------------------------------------------------------
// Static nested classes -----------------------------------------------------
//----------------------------------------------------------------------------
private static final class Epsilon<T> extends Regex<T> {
private Epsilon() {
super(false, true, false);
}
@Override public Regex<T> step(boolean mark, T value) {
return this; // My job here is done.
}
}
private static final class Symbol<T> extends Regex<T> {
private final Predicate<T> predicate;
private Symbol(Predicate<T> predicate, boolean active) {
super(active, false, active);
this.predicate = predicate;
}
private Symbol(Predicate<T> predicate) {
this(predicate, false);
}
@Override public Regex<T> step(boolean mark, T value) {
return new Symbol<T>(predicate, mark && predicate.test(value));
}
}
private static final class Choice<T> extends Regex<T> {
private final Regex<T> regex1;
private final Regex<T> regex2;
private Choice(Regex<T> regex1, Regex<T> regex2, boolean active) {
super(
active,
regex1.empty || regex2.empty,
active && (regex1.matched || regex2.matched)
);
this.regex1 = regex1;
this.regex2 = regex2;
}
private Choice(Regex<T> regex1, Regex<T> regex2) {
this(regex1, regex2, false);
}
@Override public Regex<T> step(boolean mark, T value) {
Regex<T>
r1 = regex1.shift(mark, value),
r2 = regex2.shift(mark, value);
return new Choice<T>(r1, r2, r1.active || r2.active);
}
}
private static final class Concat<T> extends Regex<T> {
private final Regex<T> regex1;
private final Regex<T> regex2;
private Concat(Regex<T> regex1, Regex<T> regex2, boolean active) {
super(
active,
regex1.empty && regex2.empty,
active && (regex2.matched || (regex1.matched && regex2.empty))
);
this.regex1 = regex1;
this.regex2 = regex2;
}
private Concat(Regex<T> regex1, Regex<T> regex2) {
this(regex1, regex2, false);
}
@Override public Regex<T> step(boolean mark, T value) {
Regex<T>
r1 = regex1.shift(mark, value),
r2 = regex2.shift(regex1.matched || (mark && regex1.empty), value);
return new Concat<T>(r1, r2, r1.active || r2.active);
}
}
private static final class Repetition<T> extends Regex<T> {
private final Regex<T> regex;
private Repetition(Regex<T> regex, boolean active) {
super(active, true, active && regex.matched);
this.regex = regex;
}
private Repetition(Regex<T> regex) {
this(regex, false);
}
@Override public Regex<T> step(boolean mark, T value) {
Regex<T> r = regex.shift(mark || regex.matched, value);
return new Repetition<T>(r, r.active);
}
}
}
|
923473ce0f021120bd9e868683b48b575467361b | 602 | java | Java | src/main/java/com/google/zxing/ReaderException.java | JackChan1999/boohee_v5.6 | 221f7ea237f491e2153039a42941a515493ba52c | [
"Apache-2.0"
] | 7 | 2017-05-30T12:01:38.000Z | 2021-04-22T12:22:39.000Z | src/main/java/com/google/zxing/ReaderException.java | JackChan1999/boohee_v5.6 | 221f7ea237f491e2153039a42941a515493ba52c | [
"Apache-2.0"
] | null | null | null | src/main/java/com/google/zxing/ReaderException.java | JackChan1999/boohee_v5.6 | 221f7ea237f491e2153039a42941a515493ba52c | [
"Apache-2.0"
] | 6 | 2017-07-28T03:47:08.000Z | 2019-06-28T17:57:50.000Z | 21.5 | 83 | 0.601329 | 996,925 | package com.google.zxing;
public abstract class ReaderException extends Exception {
protected static final StackTraceElement[] NO_TRACE = new StackTraceElement[0];
protected static final boolean isStackTrace;
static {
boolean z;
if (System.getProperty("surefire.test.class.path") != null) {
z = true;
} else {
z = false;
}
isStackTrace = z;
}
ReaderException() {
}
ReaderException(Throwable cause) {
super(cause);
}
public final Throwable fillInStackTrace() {
return null;
}
}
|
923474192f25d51e47944d5f0d559e8fd8033bf1 | 22,326 | java | Java | src/main/java/net/glowstone/GlowChunk.java | mikeprimm/Glowstone | c32b12778a5beac0f7e960ca8f412fc6a85b0c56 | [
"MIT"
] | 1 | 2019-08-29T19:28:25.000Z | 2019-08-29T19:28:25.000Z | src/main/java/net/glowstone/GlowChunk.java | mikeprimm/Glowstone | c32b12778a5beac0f7e960ca8f412fc6a85b0c56 | [
"MIT"
] | null | null | null | src/main/java/net/glowstone/GlowChunk.java | mikeprimm/Glowstone | c32b12778a5beac0f7e960ca8f412fc6a85b0c56 | [
"MIT"
] | null | null | null | 31.44507 | 188 | 0.553839 | 996,926 | package net.glowstone;
import net.glowstone.block.GlowBlock;
import net.glowstone.block.GlowBlockState;
import net.glowstone.block.ItemTable;
import net.glowstone.block.blocktype.BlockType;
import net.glowstone.block.entity.TileEntity;
import net.glowstone.entity.GlowEntity;
import net.glowstone.net.message.play.game.ChunkDataMessage;
import net.glowstone.util.NibbleArray;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import java.util.*;
import java.util.logging.Level;
/**
* Represents a chunk of the map.
* @author Graham Edgecombe
*/
public final class GlowChunk implements Chunk {
/**
* A chunk key represents the X and Z coordinates of a chunk and implements
* the {@link #hashCode()} and {@link #equals(Object)} methods making it
* suitable for use as a key in a hash table or set.
* @author Graham Edgecombe
*/
public static final class Key {
/**
* The coordinates.
*/
private final int x, z;
/**
* Creates a new chunk key with the specified X and Z coordinates.
* @param x The X coordinate.
* @param z The Z coordinate.
*/
public Key(int x, int z) {
this.x = x;
this.z = z;
}
/**
* Gets the X coordinate.
* @return The X coordinate.
*/
public int getX() {
return x;
}
/**
* Gets the Z coordinate.
* @return The Z coordinate.
*/
public int getZ() {
return z;
}
@Override
public int hashCode() {
return 31 * x + z;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Key other = (Key) obj;
return x == other.x && z == other.z;
}
@Override
public String toString() {
return "ChunkKey{" + x + ',' + z + '}';
}
}
/**
* The dimensions of a chunk (width: x, height: z, depth: y).
*/
public static final int WIDTH = 16, HEIGHT = 16, DEPTH = 256;
/**
* The Y depth of a single chunk section.
*/
private static final int SEC_DEPTH = 16;
/**
* A single cubic section of a chunk, with all data.
*/
public static final class ChunkSection {
private static final int ARRAY_SIZE = WIDTH * HEIGHT * SEC_DEPTH;
// these probably should be made non-public
public final byte[] types;
public final NibbleArray metaData;
public final NibbleArray skyLight;
public final NibbleArray blockLight;
/**
* Create a new, empty ChunkSection.
*/
public ChunkSection() {
types = new byte[ARRAY_SIZE];
metaData = new NibbleArray(ARRAY_SIZE);
skyLight = new NibbleArray(ARRAY_SIZE);
blockLight = new NibbleArray(ARRAY_SIZE);
skyLight.fill((byte) 0xf);
}
/**
* Create a ChunkSection with the specified chunk data. This
* ChunkSection assumes ownership of the arrays passed in, and they
* should not be further modified.
*/
public ChunkSection(byte[] types, NibbleArray metaData, NibbleArray skyLight, NibbleArray blockLight) {
if (types.length != ARRAY_SIZE || metaData.size() != ARRAY_SIZE || skyLight.size() != ARRAY_SIZE || blockLight.size() != ARRAY_SIZE) {
throw new IllegalArgumentException("An array length was not " + ARRAY_SIZE + ": " + types.length + " " + metaData.size() + " " + skyLight.size() + " " + blockLight.size());
}
this.types = types;
this.metaData = metaData;
this.skyLight = skyLight;
this.blockLight = blockLight;
}
/**
* Calculate the index into internal arrays for the given coordinates.
*/
public int index(int x, int y, int z) {
if (x < 0 || z < 0 || x >= WIDTH || z >= HEIGHT) {
throw new IndexOutOfBoundsException("Coords (x=" + x + ",z=" + z + ") out of section bounds");
}
return ((y & 0xf) << 8) | (z << 4) | x;
}
/**
* Check whether the section is empty (all blocks are air).
*/
public boolean isEmpty() {
for (byte type : types) {
if (type != 0) return false;
}
return true;
}
/**
* Take a snapshot of this section which will not reflect future changes.
*/
public ChunkSection snapshot() {
return new ChunkSection(types.clone(), metaData.snapshot(), skyLight.snapshot(), blockLight.snapshot());
}
}
/**
* The world of this chunk.
*/
private final GlowWorld world;
/**
* The coordinates of this chunk.
*/
private final int x, z;
/**
* The array of chunk sections this chunk contains, or null if it is unloaded.
*/
private ChunkSection[] sections;
/**
* The array of biomes this chunk contains, or null if it is unloaded.
*/
private byte[] biomes;
/**
* The tile entities that reside in this chunk.
*/
private final HashMap<Integer, TileEntity> tileEntities = new HashMap<>();
/**
* The entities that reside in this chunk.
*/
private final Set<GlowEntity> entities = new HashSet<>(4);
/**
* Whether the chunk has been populated by special features.
* Used in map generation.
*/
private boolean populated = false;
/**
* Creates a new chunk with a specified X and Z coordinate.
* @param x The X coordinate.
* @param z The Z coordinate.
*/
GlowChunk(GlowWorld world, int x, int z) {
this.world = world;
this.x = x;
this.z = z;
}
@Override
public String toString() {
return "GlowChunk{world=" + world.getName() + ",x=" + x + ",z=" + z + '}';
}
// ======== Basic stuff ========
public GlowWorld getWorld() {
return world;
}
public int getX() {
return x;
}
public int getZ() {
return z;
}
public GlowBlock getBlock(int x, int y, int z) {
return new GlowBlock(this, (this.x << 4) | (x & 0xf), y & 0xff, (this.z << 4) | (z & 0xf));
}
public Entity[] getEntities() {
return entities.toArray(new Entity[entities.size()]);
}
public Collection<GlowEntity> getRawEntities() {
return entities;
}
public GlowBlockState[] getTileEntities() {
List<GlowBlockState> states = new ArrayList<>(tileEntities.size());
for (TileEntity tileEntity : tileEntities.values()) {
GlowBlockState state = tileEntity.getState();
if (state != null) {
states.add(state);
}
}
return states.toArray(new GlowBlockState[states.size()]);
}
public Collection<TileEntity> getRawTileEntities() {
return Collections.unmodifiableCollection(tileEntities.values());
}
public GlowChunkSnapshot getChunkSnapshot() {
return getChunkSnapshot(true, false, false);
}
public GlowChunkSnapshot getChunkSnapshot(boolean includeMaxblocky, boolean includeBiome, boolean includeBiomeTempRain) {
return new GlowChunkSnapshot(x, z, world, sections, includeMaxblocky, includeBiome ? biomes.clone() : null, includeBiomeTempRain);
}
/**
* Gets whether this chunk has been populated by special features.
* @return Population status.
*/
public boolean isPopulated() {
return populated;
}
/**
* Sets the population status of this chunk.
* @param populated Population status.
*/
public void setPopulated(boolean populated) {
this.populated = populated;
}
// ======== Helper Functions ========
public boolean isLoaded() {
return sections != null;
}
public boolean load() {
return load(true);
}
public boolean load(boolean generate) {
return isLoaded() || world.getChunkManager().loadChunk(x, z, generate);
}
public boolean unload() {
return unload(true, true);
}
public boolean unload(boolean save) {
return unload(save, true);
}
public boolean unload(boolean save, boolean safe) {
if (!isLoaded()) {
return true;
}
if (safe && world.isChunkInUse(x, z)) {
return false;
}
if (save && !world.getChunkManager().performSave(this)) {
return false;
}
sections = null;
biomes = null;
tileEntities.clear();
return true;
}
/**
* Initialize this chunk from the given sections.
* @param initSections The ChunkSections to use.
*/
public void initializeSections(ChunkSection[] initSections) {
if (isLoaded()) {
GlowServer.logger.log(Level.SEVERE, "Tried to initialize already loaded chunk (" + x + "," + z + ")", new Throwable());
return;
}
//GlowServer.logger.log(Level.INFO, "Initializing chunk ({0},{1})", new Object[]{x, z});
sections = new ChunkSection[DEPTH / SEC_DEPTH];
System.arraycopy(initSections, 0, sections, 0, Math.min(sections.length, initSections.length));
biomes = new byte[WIDTH * HEIGHT];
// tile entity initialization
for (int i = 0; i < sections.length; ++i) {
if (sections[i] == null) continue;
int by = 16 * i;
for (int cx = 0; cx < WIDTH; ++cx) {
for (int cz = 0; cz < HEIGHT; ++cz) {
for (int cy = by; cy < by + 16; ++cy) {
createEntity(cx, cy, cz, getType(cx, cz, cy));
}
}
}
}
}
/**
* If needed, create a new tile entity at the given location.
*/
private void createEntity(int cx, int cy, int cz, int type) {
BlockType blockType = ItemTable.instance().getBlock(type);
if (blockType == null) return;
try {
TileEntity entity = blockType.createTileEntity(this, cx, cy, cz);
if (entity == null) return;
tileEntities.put(coordToIndex(cx, cz, cy), entity);
} catch (Exception ex) {
GlowServer.logger.log(Level.SEVERE, "Unable to initialize tile entity for " + type, ex);
}
}
// ======== Data access ========
/**
* Attempt to get the ChunkSection at the specified height.
* @param y the y value.
* @return The ChunkSection, or null if it is empty.
*/
private ChunkSection getSection(int y) {
int idx = y >> 4;
if (y < 0 || y >= DEPTH || !load() || idx >= sections.length) {
return null;
}
return sections[idx];
}
/**
* Attempt to get the tile entity located at the given coordinates.
* @param x The X coordinate.
* @param z The Z coordinate.
* @param y The Y coordinate.
* @return A GlowBlockState if the entity exists, or null otherwise.
*/
public TileEntity getEntity(int x, int y, int z) {
if (y >= DEPTH || y < 0) return null;
load();
return tileEntities.get(coordToIndex(x, z, y));
}
/**
* Gets the type of a block within this chunk.
* @param x The X coordinate.
* @param z The Z coordinate.
* @param y The Y coordinate.
* @return The type.
*/
public int getType(int x, int z, int y) {
ChunkSection section = getSection(y);
return section == null ? 0 : (section.types[section.index(x, y, z)] & 0xff);
}
/**
* Sets the type of a block within this chunk.
* @param x The X coordinate.
* @param z The Z coordinate.
* @param y The Y coordinate.
* @param type The type.
*/
public void setType(int x, int z, int y, int type) {
if (type < 0 || type >= 256)
throw new IllegalArgumentException("Block type out of range: " + type);
ChunkSection section = getSection(y);
if (section == null) {
if (type == 0) {
// don't need to create chunk for air
return;
} else {
// create new ChunkSection for this y coordinate
int idx = y >> 4;
if (y < 0 || y >= DEPTH || idx >= sections.length) {
// y is out of range somehow
return;
}
sections[idx] = section = new ChunkSection();
}
}
// destroy any tile entity there
int tileEntityIndex = coordToIndex(x, z, y);
if (tileEntities.containsKey(tileEntityIndex)) {
tileEntities.remove(tileEntityIndex).destroy();
}
// update the type
section.types[section.index(x, y, z)] = (byte) type;
if (type == 0 && section.isEmpty()) {
// destroy the empty section
sections[y / SEC_DEPTH] = null;
return;
}
// create a new tile entity if we need
createEntity(x, y, z, type);
}
/**
* Gets the metadata of a block within this chunk.
* @param x The X coordinate.
* @param z The Z coordinate.
* @param y The Y coordinate.
* @return The metadata.
*/
public int getMetaData(int x, int z, int y) {
ChunkSection section = getSection(y);
return section == null ? 0 : section.metaData.get(section.index(x, y, z));
}
/**
* Sets the metadata of a block within this chunk.
* @param x The X coordinate.
* @param z The Z coordinate.
* @param y The Y coordinate.
* @param metaData The metadata.
*/
public void setMetaData(int x, int z, int y, int metaData) {
if (metaData < 0 || metaData >= 16)
throw new IllegalArgumentException("Metadata out of range: " + metaData);
ChunkSection section = getSection(y);
if (section == null) return; // can't set metadata on an empty section
section.metaData.set(section.index(x, y, z), (byte) metaData);
}
/**
* Gets the sky light level of a block within this chunk.
* @param x The X coordinate.
* @param z The Z coordinate.
* @param y The Y coordinate.
* @return The sky light level.
*/
public byte getSkyLight(int x, int z, int y) {
ChunkSection section = getSection(y);
return section == null ? 0 : section.skyLight.get(section.index(x, y, z));
}
/**
* Sets the sky light level of a block within this chunk.
* @param x The X coordinate.
* @param z The Z coordinate.
* @param y The Y coordinate.
* @param skyLight The sky light level.
*/
public void setSkyLight(int x, int z, int y, int skyLight) {
ChunkSection section = getSection(y);
if (section == null) return; // can't set light on an empty section
section.skyLight.set(section.index(x, y, z), (byte) skyLight);
}
/**
* Gets the block light level of a block within this chunk.
* @param x The X coordinate.
* @param z The Z coordinate.
* @param y The Y coordinate.
* @return The block light level.
*/
public byte getBlockLight(int x, int z, int y) {
ChunkSection section = getSection(y);
return section == null ? 0 : section.blockLight.get(section.index(x, y, z));
}
/**
* Sets the block light level of a block within this chunk.
* @param x The X coordinate.
* @param z The Z coordinate.
* @param y The Y coordinate.
* @param blockLight The block light level.
*/
public void setBlockLight(int x, int z, int y, int blockLight) {
ChunkSection section = getSection(y);
if (section == null) return; // can't set light on an empty section
section.blockLight.set(section.index(x, y, z), (byte) blockLight);
}
/**
* Gets the biome of a column within this chunk.
* @param x The X coordinate.
* @param z The Z coordinate.
* @return The biome.
*/
public int getBiome(int x, int z) {
if (biomes == null) return -1;
return biomes[z * WIDTH + x] & 0xFF;
}
/**
* Sets the biome of a column within this chunk,
* @param x The X coordinate.
* @param z The Z coordinate.
* @param biome The biome.
*/
public void setBiome(int x, int z, int biome) {
if (biomes == null) return;
biomes[z * WIDTH + x] = (byte) biome;
}
/**
* Set the entire biome array of this chunk.
* @param newBiomes The biome array.
*/
public void setBiomes(byte[] newBiomes) {
if (biomes == null) {
throw new IllegalStateException("Must initialize chunk first");
}
if (newBiomes.length != biomes.length) {
throw new IllegalArgumentException("Biomes array not of length " + biomes.length);
}
System.arraycopy(newBiomes, 0, biomes, 0, biomes.length);
}
// ======== Helper functions ========
/**
* Converts a three-dimensional coordinate to an index within the
* one-dimensional arrays.
* @param x The X coordinate.
* @param z The Z coordinate.
* @param y The Y coordinate.
* @return The index within the arrays.
*/
private int coordToIndex(int x, int z, int y) {
if (x < 0 || z < 0 || y < 0 || x >= WIDTH || z >= HEIGHT || y >= DEPTH)
throw new IndexOutOfBoundsException("Coords (x=" + x + ",y=" + y + ",z=" + z + ") invalid");
return (y * HEIGHT + z) * WIDTH + x;
}
/**
* Creates a new {@link ChunkDataMessage} which can be sent to a client to stream
* this entire chunk to them.
* @return The {@link ChunkDataMessage}.
*/
public ChunkDataMessage toMessage() {
// this may need to be changed to "true" depending on resolution of
// some inconsistencies on the wiki
return toMessage(world.getEnvironment() == World.Environment.NORMAL);
}
/**
* Creates a new {@link ChunkDataMessage} which can be sent to a client to stream
* this entire chunk to them.
* @param skylight Whether to include skylight data.
* @return The {@link ChunkDataMessage}.
*/
public ChunkDataMessage toMessage(boolean skylight) {
return toMessage(skylight, true, 0);
}
/**
* Creates a new {@link ChunkDataMessage} which can be sent to a client to stream
* parts of this chunk to them.
* @return The {@link ChunkDataMessage}.
*/
public ChunkDataMessage toMessage(boolean skylight, boolean entireChunk, int sectionBitmask) {
load();
// filter sectionBitmask based on actual chunk contents
int sectionCount;
if (sections == null) {
sectionBitmask = 0;
sectionCount = 0;
} else {
final int maxBitmask = (1 << sections.length) - 1;
if (entireChunk) {
sectionBitmask = maxBitmask;
sectionCount = sections.length;
} else {
sectionBitmask &= maxBitmask;
sectionCount = countBits(sectionBitmask);
}
for (int i = 0; i < sections.length; ++i) {
if (sections[i] == null || sections[i].isEmpty()) {
// remove empty sections from bitmask
sectionBitmask &= ~(1 << i);
sectionCount--;
}
}
}
// break out early if there's nothing to send
if (sections == null || sectionBitmask == 0) {
return ChunkDataMessage.empty(x, z);
}
// calculate how big the data will need to be
final int numBlocks = WIDTH * HEIGHT * SEC_DEPTH;
int sectionSize = numBlocks * 5 / 2; // (data and metadata combo) * 2 + blockLight/2
if (skylight) {
sectionSize += numBlocks / 2; // + skyLight/2
}
int byteSize = sectionCount * sectionSize;
if (entireChunk) {
byteSize += 256; // + biomes
}
// get the list of sections
ChunkSection[] sendSections = new ChunkSection[sectionCount];
int pos = 0;
for (int i = 0, mask = 1; i < sections.length; ++i, mask <<= 1) {
if ((sectionBitmask & mask) != 0) {
sendSections[pos++] = sections[i];
}
}
// fill up the data
byte[] tileData = new byte[byteSize];
pos = 0;
// todo: this probably isn't very efficient
for (ChunkSection sec : sendSections) {
byte[] types = sec.types;
for (int i = 0; i < types.length; ++i) {
int t = types[i] & 0xff;
tileData[pos++] = (byte) ((t << 4) | sec.metaData.get(i));
tileData[pos++] = (byte) (t >> 4);
}
}
for (ChunkSection sec : sendSections) {
byte[] blockLight = sec.blockLight.getRawData();
System.arraycopy(blockLight, 0, tileData, pos, blockLight.length);
pos += blockLight.length;
}
if (skylight) {
for (ChunkSection sec : sendSections) {
byte[] skyLight = sec.skyLight.getRawData();
System.arraycopy(skyLight, 0, tileData, pos, skyLight.length);
pos += skyLight.length;
}
}
// biomes
if (entireChunk) {
for (int i = 0; i < 256; ++i) {
tileData[pos++] = 0;
}
}
if (pos != byteSize) {
throw new IllegalStateException("only wrote " + pos + " out of expected " + byteSize + " bytes");
}
return new ChunkDataMessage(x, z, entireChunk, sectionBitmask, tileData);
}
private int countBits(int v) {
// http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan
int c;
for (c = 0; v > 0; c++) {
v &= v - 1;
}
return c;
}
}
|
923474ce6808250b2f381624f453b8307d79733d | 821 | java | Java | cukes-rabbitmq/src/main/java/lv/ctco/cukes/rabbitmq/api/when/SendMessageSteps.java | medveduska/cukes | 31cf17e19650d4661491f9e25b5f020f230517b2 | [
"Apache-2.0"
] | 64 | 2017-08-01T10:45:18.000Z | 2022-02-20T22:22:07.000Z | cukes-rabbitmq/src/main/java/lv/ctco/cukes/rabbitmq/api/when/SendMessageSteps.java | medveduska/cukes | 31cf17e19650d4661491f9e25b5f020f230517b2 | [
"Apache-2.0"
] | 60 | 2017-07-20T08:38:22.000Z | 2022-01-21T23:18:41.000Z | cukes-rabbitmq/src/main/java/lv/ctco/cukes/rabbitmq/api/when/SendMessageSteps.java | medveduska/cukes | 31cf17e19650d4661491f9e25b5f020f230517b2 | [
"Apache-2.0"
] | 53 | 2017-07-18T09:35:03.000Z | 2022-03-26T13:43:51.000Z | 30.407407 | 116 | 0.730816 | 996,927 | package lv.ctco.cukes.rabbitmq.api.when;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.cucumber.java.en.When;
import lv.ctco.cukes.rabbitmq.api.NamePatterns;
import lv.ctco.cukes.rabbitmq.facade.RequestFacade;
import java.util.Optional;
@Singleton
public class SendMessageSteps {
@Inject
RequestFacade requestFacade;
@When("^the client sends message with routing key \"(.+)\"$")
public void sendMessage(String routingKey) {
requestFacade.sendMessage(Optional.empty(), routingKey);
}
@When("^the client sends message to exchange \"" + NamePatterns.EXCHANGE_NAME + "\" with routing key \"(.+)\"$")
public void sendMessageToExchange(String exchange, String routingKey) {
requestFacade.sendMessage(Optional.of(exchange), routingKey);
}
}
|
923474edcacec4b1538eb783ec5898cdbcbe077b | 1,650 | java | Java | Villages/src/com/domsplace/Villages/Commands/SubCommands/VillageSpawn.java | YourWishes/Villages | 23824aac29581f57f98871504711308302cb0c7f | [
"Apache-2.0"
] | null | null | null | Villages/src/com/domsplace/Villages/Commands/SubCommands/VillageSpawn.java | YourWishes/Villages | 23824aac29581f57f98871504711308302cb0c7f | [
"Apache-2.0"
] | null | null | null | Villages/src/com/domsplace/Villages/Commands/SubCommands/VillageSpawn.java | YourWishes/Villages | 23824aac29581f57f98871504711308302cb0c7f | [
"Apache-2.0"
] | null | null | null | 35.869565 | 109 | 0.717576 | 996,928 | /*
* Copyright 2013 Dominic Masters and Jordan Atkins
*
* 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.domsplace.Villages.Commands.SubCommands;
import com.domsplace.Villages.Bases.BukkitCommand;
import com.domsplace.Villages.Bases.SubCommand;
import com.domsplace.Villages.Objects.Region;
import com.domsplace.Villages.Objects.Resident;
import com.domsplace.Villages.Objects.Village;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
public class VillageSpawn extends SubCommand {
public VillageSpawn() {
super("village", "spawn");
this.setPermission("spawn");
}
@Override
public boolean cmd(BukkitCommand bkcmd, CommandSender sender, Command cmd, String label, String[] args) {
if(!isPlayer(sender)) {sk(sender, "playeronly");return true;}
Resident r = Resident.getResident(getPlayer(sender));
Village v = Village.getPlayersVillage(r);
if(v == null) {sk(sender, "notinvillage");return true;}
r.teleport(v.getSpawn().getSafeLocation());
sk(sender, "goingtovillage");
return true;
}
}
|
923474fb67ff40acf00fecc595eb3c23f0eadf4b | 828 | java | Java | app/src/main/java/com/app/missednotificationsreminder/ui/UiModule.java | SebFlippence/MissedNotificationsReminder | d64390855fe3020e03199d74a939d00c7d426cf2 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/app/missednotificationsreminder/ui/UiModule.java | SebFlippence/MissedNotificationsReminder | d64390855fe3020e03199d74a939d00c7d426cf2 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/app/missednotificationsreminder/ui/UiModule.java | SebFlippence/MissedNotificationsReminder | d64390855fe3020e03199d74a939d00c7d426cf2 | [
"Apache-2.0"
] | null | null | null | 23.657143 | 85 | 0.710145 | 996,929 | package com.app.missednotificationsreminder.ui;
import com.app.missednotificationsreminder.ui.activity.ApplicationsSelectionActivity;
import com.app.missednotificationsreminder.ui.activity.SettingsActivity;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
/**
* The Dagger dependency injection module for the UI layer
*/
@Module(
injects = {
SettingsActivity.class,
ApplicationsSelectionActivity.class,
},
complete = false,
library = true
)
public final class UiModule {
@Provides
@Singleton
AppContainer provideAppContainer() {
return AppContainer.DEFAULT;
}
@Provides
@Singleton
ActivityHierarchyServer provideActivityHierarchyServer() {
return ActivityHierarchyServer.NONE;
}
}
|
9234758b8a55b21e71e2e87661eea26a649aeb90 | 1,832 | java | Java | main/boofcv-ip/src/main/java/boofcv/factory/filter/binary/ConfigThresholdBlockMinMax.java | yuripourre-forks/BoofCV | 0a3091ef28c2bc9c632872ac5b6546e6973b59a0 | [
"Apache-2.0"
] | 782 | 2015-01-06T03:09:49.000Z | 2022-03-31T04:17:26.000Z | main/boofcv-ip/src/main/java/boofcv/factory/filter/binary/ConfigThresholdBlockMinMax.java | yuripourre-forks/BoofCV | 0a3091ef28c2bc9c632872ac5b6546e6973b59a0 | [
"Apache-2.0"
] | 205 | 2015-03-19T15:36:02.000Z | 2022-03-25T05:48:18.000Z | main/boofcv-ip/src/main/java/boofcv/factory/filter/binary/ConfigThresholdBlockMinMax.java | yuripourre-forks/BoofCV | 0a3091ef28c2bc9c632872ac5b6546e6973b59a0 | [
"Apache-2.0"
] | 241 | 2015-01-12T13:23:36.000Z | 2022-02-25T07:38:48.000Z | 27.757576 | 111 | 0.739629 | 996,930 | /*
* Copyright (c) 2021, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package boofcv.factory.filter.binary;
import boofcv.struct.ConfigLength;
import lombok.Getter;
import lombok.Setter;
/**
* Configuration for {@link boofcv.alg.filter.binary.ThresholdBlockMinMax}
*
* @author Peter Abeles
*/
@Getter @Setter
public class ConfigThresholdBlockMinMax extends ConfigThreshold {
/**
* If the lower and upper histogram values are different by less than or equal to this amount it is considered
* a textureless region. Set to a value <= -1 to disable.
*/
public double minimumSpread = 10;
{
scale = 0.85;
}
public ConfigThresholdBlockMinMax( int width, double minimumSpread, boolean down ) {
this(ConfigLength.fixed(width), minimumSpread, down);
}
public ConfigThresholdBlockMinMax( ConfigLength width, double minimumSpread, boolean down ) {
this.type = ThresholdType.BLOCK_MIN_MAX;
this.width = width;
this.minimumSpread = minimumSpread;
this.down = down;
}
public ConfigThresholdBlockMinMax() {
}
public void setTo( ConfigThresholdBlockMinMax src ) {
super.setTo(src);
this.minimumSpread = src.minimumSpread;
}
@Override
public void checkValidity() {
super.checkValidity();
}
}
|
9234764dc1f0c7b01c96cb71f06d3a8f4d986cdf | 1,577 | java | Java | src/main/java/com/fengjing/framework/spring/jdbc/dao/impl/CategoryDaoImpl.java | kuiwang/my-framework | 53c2686b4dffc63a0ec5cc5f5cac523f1a72c1b9 | [
"MIT"
] | null | null | null | src/main/java/com/fengjing/framework/spring/jdbc/dao/impl/CategoryDaoImpl.java | kuiwang/my-framework | 53c2686b4dffc63a0ec5cc5f5cac523f1a72c1b9 | [
"MIT"
] | null | null | null | src/main/java/com/fengjing/framework/spring/jdbc/dao/impl/CategoryDaoImpl.java | kuiwang/my-framework | 53c2686b4dffc63a0ec5cc5f5cac523f1a72c1b9 | [
"MIT"
] | null | null | null | 25.852459 | 97 | 0.717185 | 996,931 | package com.fengjing.framework.spring.jdbc.dao.impl;
import java.sql.Types;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.fengjing.framework.spring.jdbc.dao.CategoryDao;
import com.fengjing.framework.spring.jdbc.model.Category;
@Repository(value = "jdbcCategoryDaoImpl")
public class CategoryDaoImpl implements CategoryDao {
private JdbcTemplate jdbcTemplate;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
@Resource(name = "jdbcTemplate")
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public Category findById(long id) {
return getJdbcTemplate().queryForObject("select * from category where id = ? ",
new Long[] {id}, Category.class);
}
@Override
public void modify(Category t) {
getJdbcTemplate().update("update category set name =? where id =? ",
new Object[] {t.getName(), t.getId()}, new int[] {Types.VARCHAR, Types.INTEGER});
}
@Override
public void save(Category t) {
getJdbcTemplate().update("insert into category(name) values(?)", new Object[] {t.getName()});
}
@Override
public void deleteById(long id) {
getJdbcTemplate().update("delete from category where id= ? ", new Object[] {id});
}
@Override
public void delete(Category t) {
}
@Override
public List<Category> listAll() {
return getJdbcTemplate().queryForList("select * from category", Category.class);
}
}
|
923476a07f28c4bf69d023e3b20020a896f78fa1 | 2,725 | java | Java | app/src/main/java/br/com/mobiclub/quantoprima/database/table/UserTable.java | LuisMesquita/android-quantoprima | a6e6227696952999c08831b562ba1efc13da4143 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/br/com/mobiclub/quantoprima/database/table/UserTable.java | LuisMesquita/android-quantoprima | a6e6227696952999c08831b562ba1efc13da4143 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/br/com/mobiclub/quantoprima/database/table/UserTable.java | LuisMesquita/android-quantoprima | a6e6227696952999c08831b562ba1efc13da4143 | [
"Apache-2.0"
] | null | null | null | 44.672131 | 85 | 0.672661 | 996,932 | package br.com.mobiclub.quantoprima.database.table;
import br.com.mobiclub.quantoprima.database.common.DBColumn;
import br.com.mobiclub.quantoprima.database.common.DBTable;
public class UserTable extends DBTable {
private static final String TABLE_NAME = "User";
//Columns Index
public static final int ID_COL_INDEX = 0;
public static final int NAME_COL_INDEX = 1;
public static final int EMAIL_COL_INDEX = 2;
public static final int LAST_NAME_COL_INDEX = 3;
public static final int BIHTHDAY_COL_INDEX = 4;
public static final int GENDER_COL_INDEX = 5;
public static final int FACEBOOK_ID_COL_INDEX = 6;
public static final int FACEBOOK_ACCESS_EXPIRES_COL_INDEX = 7;
public static final int FACEBOOK_ACCESS_TOKEN_COL_INDEX = 8;
public static final int USER_ID_COL_INDEX = 9;
public static final int PHOTO_COL_INDEX = 10;
public static final int FACEBOOK_EMAIL_COL_INDEX = 11;
public static final int CPF_COL_INDEX = 12;
//Columns Names
public static final String ID_COL = "Id";
public static final String NAME_COL = "Name";
public static final String EMAIL_COL = "Email";
public static final String LAST_NAME_COL = "LastName";
public static final String BIHTHDAY_COL = "Birthday";
public static final String GENDER_COL = "Gender";
public static final String FACEBOOK_ID_COL = "FacebookId";
public static final String FACEBOOK_ACCESS_EXPIRES_COL = "FacebookAccessExpires";
public static final String FACEBOOK_ACCESS_TOKEN_COL = "FacebookAccessToken";
public static final String USER_ID_COL = "UserId";
public static final String PHOTO_COL = "Photo";
public static final String FACEBOOK_EMAIL_COL = "FacebookEmail";
public static final String CPF_COL = "cpf";
private static final DBColumn[] DB_COLUMNS = new DBColumn[]
{
new DBColumn(ID_COL, "INTEGER PRIMARY KEY AUTOINCREMENT"),
new DBColumn(NAME_COL, "TEXT"),
new DBColumn(EMAIL_COL, "TEXT"),
new DBColumn(LAST_NAME_COL, "TEXT"),
new DBColumn(BIHTHDAY_COL, "TEXT"),
new DBColumn(GENDER_COL, "TEXT"),
new DBColumn(FACEBOOK_ID_COL, "INTEGER"),
new DBColumn(FACEBOOK_ACCESS_EXPIRES_COL, "INTEGER"),
new DBColumn(FACEBOOK_ACCESS_TOKEN_COL, "TEXT"),
new DBColumn(USER_ID_COL, "INTEGER"),
new DBColumn(PHOTO_COL, "TEXT"),
new DBColumn(FACEBOOK_EMAIL_COL, "TEXT"),
new DBColumn(CPF_COL, "TEXT")
};
public UserTable() {
super(TABLE_NAME, DB_COLUMNS);
}
}
|
923476defa48d7266705008b62b0b24c2f7796bd | 1,191 | java | Java | springboot-kafka/src/main/java/com/javanorth/spring/springbootkafka/service/impl/ConsumerImpl.java | hirCodd/springboot-demo | 7bc8d371bfcf72575f8213b25d2190e6fa8cbdfa | [
"MIT"
] | 9 | 2019-10-21T08:29:29.000Z | 2021-07-12T04:17:15.000Z | springboot-kafka/src/main/java/com/javanorth/spring/springbootkafka/service/impl/ConsumerImpl.java | hirCodd/springboot-demo | 7bc8d371bfcf72575f8213b25d2190e6fa8cbdfa | [
"MIT"
] | null | null | null | springboot-kafka/src/main/java/com/javanorth/spring/springbootkafka/service/impl/ConsumerImpl.java | hirCodd/springboot-demo | 7bc8d371bfcf72575f8213b25d2190e6fa8cbdfa | [
"MIT"
] | null | null | null | 36.090909 | 107 | 0.697733 | 996,933 | package com.javanorth.spring.springbootkafka.service.impl;
import com.google.gson.Gson;
import com.javanorth.spring.springbootkafka.pojo.Message;
import com.javanorth.spring.springbootkafka.util.LogUtil;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
@Service
public class ConsumerImpl {
@KafkaListener(id = "client-1", topics = "${kafka.topic.name}", groupId = "${kafka.consumer.group-id}",
containerFactory = "kafkaListenerContainerFactory")
public void onMessage(String message) {
Gson gson = new Gson();
Message msg = gson.fromJson(message, Message.class);
LogUtil.info(ConsumerImpl.class, "receive message: {}", message);
LogUtil.info(ConsumerImpl.class, "receive msg: {}", msg.getMsg());
}
@KafkaListener(id = "client-2", topics = "${kafka.topic.name}")
public void onConsumerMessage(String message) {
Gson gson = new Gson();
Message msg = gson.fromJson(message, Message.class);
LogUtil.info(ConsumerImpl.class, "receive message2: {}", message);
LogUtil.info(ConsumerImpl.class, "receive msg2: {}", msg.getMsg());
}
}
|
9234770a97a6e969a5b124fdee924dc639ed1a04 | 4,693 | java | Java | client/rest-high-level/src/main/java/org/elasticsearch/client/ml/GetTrainedModelsRequest.java | jonasfh/elasticsearch | d8fb8d7ba9f741c8752d0fe9f26e4a579724cdbd | [
"Apache-2.0"
] | 2 | 2020-02-11T12:27:27.000Z | 2020-02-11T13:59:17.000Z | client/rest-high-level/src/main/java/org/elasticsearch/client/ml/GetTrainedModelsRequest.java | paulbaudrier/elasticsearch | 16bfdcacc0172264db9b32aa6edfa8b5c327f3b4 | [
"Apache-2.0"
] | 2 | 2019-12-05T10:21:58.000Z | 2020-01-10T09:17:26.000Z | client/rest-high-level/src/main/java/org/elasticsearch/client/ml/GetTrainedModelsRequest.java | paulbaudrier/elasticsearch | 16bfdcacc0172264db9b32aa6edfa8b5c327f3b4 | [
"Apache-2.0"
] | 2 | 2020-02-03T07:05:44.000Z | 2020-02-05T01:51:57.000Z | 33.521429 | 112 | 0.699339 | 996,934 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.ml;
import org.elasticsearch.client.Validatable;
import org.elasticsearch.client.ValidationException;
import org.elasticsearch.client.core.PageParams;
import org.elasticsearch.common.Nullable;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
public class GetTrainedModelsRequest implements Validatable {
public static final String ALLOW_NO_MATCH = "allow_no_match";
public static final String INCLUDE_MODEL_DEFINITION = "include_model_definition";
public static final String DECOMPRESS_DEFINITION = "decompress_definition";
private final List<String> ids;
private Boolean allowNoMatch;
private Boolean includeDefinition;
private Boolean decompressDefinition;
private PageParams pageParams;
/**
* Helper method to create a request that will get ALL TrainedModelConfigs
* @return new {@link GetTrainedModelsRequest} object for the id "_all"
*/
public static GetTrainedModelsRequest getAllTrainedModelConfigsRequest() {
return new GetTrainedModelsRequest("_all");
}
public GetTrainedModelsRequest(String... ids) {
this.ids = Arrays.asList(ids);
}
public List<String> getIds() {
return ids;
}
public Boolean getAllowNoMatch() {
return allowNoMatch;
}
/**
* Whether to ignore if a wildcard expression matches no trained models.
*
* @param allowNoMatch If this is {@code false}, then an error is returned when a wildcard (or {@code _all})
* does not match any trained models
*/
public GetTrainedModelsRequest setAllowNoMatch(boolean allowNoMatch) {
this.allowNoMatch = allowNoMatch;
return this;
}
public PageParams getPageParams() {
return pageParams;
}
public GetTrainedModelsRequest setPageParams(@Nullable PageParams pageParams) {
this.pageParams = pageParams;
return this;
}
public Boolean getIncludeDefinition() {
return includeDefinition;
}
/**
* Whether to include the full model definition.
*
* The full model definition can be very large.
*
* @param includeDefinition If {@code true}, the definition is included.
*/
public GetTrainedModelsRequest setIncludeDefinition(Boolean includeDefinition) {
this.includeDefinition = includeDefinition;
return this;
}
public Boolean getDecompressDefinition() {
return decompressDefinition;
}
/**
* Whether or not to decompress the trained model, or keep it in its compressed string form
*
* @param decompressDefinition If {@code true}, the definition is decompressed.
*/
public GetTrainedModelsRequest setDecompressDefinition(Boolean decompressDefinition) {
this.decompressDefinition = decompressDefinition;
return this;
}
@Override
public Optional<ValidationException> validate() {
if (ids == null || ids.isEmpty()) {
return Optional.of(ValidationException.withError("trained model id must not be null"));
}
return Optional.empty();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
GetTrainedModelsRequest other = (GetTrainedModelsRequest) o;
return Objects.equals(ids, other.ids)
&& Objects.equals(allowNoMatch, other.allowNoMatch)
&& Objects.equals(decompressDefinition, other.decompressDefinition)
&& Objects.equals(includeDefinition, other.includeDefinition)
&& Objects.equals(pageParams, other.pageParams);
}
@Override
public int hashCode() {
return Objects.hash(ids, allowNoMatch, pageParams, decompressDefinition, includeDefinition);
}
}
|
9234774b9f2e48879b52e6d72b15d466e0ddff35 | 2,629 | java | Java | app/src/main/java/com/oliinykov/yevgen/android/amconapp/presentation/view/ScrollAwareFABBehavior.java | zhekin/AmconApp | 68fd32845964911d9472445aab0ece8e3b7912aa | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/oliinykov/yevgen/android/amconapp/presentation/view/ScrollAwareFABBehavior.java | zhekin/AmconApp | 68fd32845964911d9472445aab0ece8e3b7912aa | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/oliinykov/yevgen/android/amconapp/presentation/view/ScrollAwareFABBehavior.java | zhekin/AmconApp | 68fd32845964911d9472445aab0ece8e3b7912aa | [
"Apache-2.0"
] | null | null | null | 41.730159 | 100 | 0.674021 | 996,935 | /*
* Copyright (c) 2016 Yevgen Oliinykov
*
* 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.oliinykov.yevgen.android.amconapp.presentation.view;
import android.content.Context;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.View;
/**
* Custom floating action button behavior. It hides fab on scroll down and shows on scroll up.
*/
public class ScrollAwareFABBehavior extends FloatingActionButton.Behavior {
public ScrollAwareFABBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onStartNestedScroll(final CoordinatorLayout coordinatorLayout,
final FloatingActionButton child,
final View directTargetChild, final View target,
final int nestedScrollAxes) {
// Ensure we react to vertical scrolling
return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL || super.onStartNestedScroll(
coordinatorLayout, child, directTargetChild, target, nestedScrollAxes);
}
@Override
public void onNestedScroll(final CoordinatorLayout coordinatorLayout,
final FloatingActionButton child,
final View target, final int dxConsumed, final int dyConsumed,
final int dxUnconsumed, final int dyUnconsumed) {
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed,
dyUnconsumed);
if (dyConsumed > 0 && child.getVisibility() == View.VISIBLE) {
// User scrolled down and the FAB is currently visible -> hide the FAB
child.hide();
} else if (dyConsumed < 0 && child.getVisibility() != View.VISIBLE) {
// User scrolled up and the FAB is currently not visible -> show the FAB
child.show();
}
}
} |
92347934eb95c08d325f3786860de10eb201175b | 4,179 | java | Java | src/main/java/venusians/data/board/AnchorChecker.java | goldenstein64/venusians | 414668fe32f6445ee58ecc152bcf8e91ba695ee6 | [
"MIT"
] | null | null | null | src/main/java/venusians/data/board/AnchorChecker.java | goldenstein64/venusians | 414668fe32f6445ee58ecc152bcf8e91ba695ee6 | [
"MIT"
] | null | null | null | src/main/java/venusians/data/board/AnchorChecker.java | goldenstein64/venusians | 414668fe32f6445ee58ecc152bcf8e91ba695ee6 | [
"MIT"
] | null | null | null | 27.86 | 88 | 0.705911 | 996,936 | package venusians.data.board;
import java.util.ArrayDeque;
import java.util.HashSet;
import venusians.data.board.buildable.Building;
import venusians.data.board.buildable.Road;
import venusians.data.board.buildable.SuggestedBuildable;
import venusians.data.players.Player;
import venusians.util.Matrix;
/**
* A class for checking whether suggested buildables affected by a removed road
* would be unanchored from any real buildables.
*/
public class AnchorChecker {
private Player owner;
private Matrix<SuggestedBuildable<? extends Building>> suggestedBuildingMap;
private Matrix<HashSet<SuggestedBuildable<Road>>> suggestedRoadMap;
/**
* Answers whether affected buildables would stay anchored without the passed in road.
*
* @param removingRoad The road that would be removed
* @return whether affected buildables would stay anchored
*/
public boolean buildablesStayAnchoredWithout(Road removingRoad) {
return (
buildingsStayAnchoredWithout(removingRoad) &&
roadsStayAnchoredWithout(removingRoad)
);
}
private boolean buildingsStayAnchoredWithout(Road removingRoad) {
return (
buildingsAtPositionStayAnchoredWithout(
removingRoad,
removingRoad.getPosition1()
) &&
buildingsAtPositionStayAnchoredWithout(
removingRoad,
removingRoad.getPosition2()
)
);
}
private boolean buildingsAtPositionStayAnchoredWithout(
Road removingRoad,
IntPoint position
) {
SuggestedBuildable<? extends Building> suggestedBuilding = suggestedBuildingMap.get(
position
);
if (suggestedBuilding == null) return true;
HashSet<Road> allRoads = new HashSet<>();
HashSet<Road> suggestedRoads = toRealRoads(suggestedRoadMap.get(position));
HashSet<Road> existingRoads = Board.getRoadsAt(position);
for (Road road : existingRoads) {
if (road.getOwner() != owner) {
existingRoads.remove(road);
}
}
allRoads.addAll(suggestedRoads);
allRoads.addAll(existingRoads);
allRoads.remove(removingRoad);
return !allRoads.isEmpty();
}
private boolean roadsStayAnchoredWithout(Road removingRoad) {
return (
roadsAtPositionStayAnchoredWithout(
removingRoad,
removingRoad.getPosition1()
) &&
roadsAtPositionStayAnchoredWithout(
removingRoad,
removingRoad.getPosition2()
)
);
}
private boolean roadsAtPositionStayAnchoredWithout(
Road removingRoad,
IntPoint position
) {
HashSet<Road> knownRoads = new HashSet<>();
knownRoads.add(removingRoad);
ArrayDeque<IntPoint> openPoints = new ArrayDeque<>();
openPoints.addLast(position);
boolean foundNewSuggestedRoads = false;
while (!openPoints.isEmpty()) {
IntPoint currentPosition = openPoints.removeLast();
if (Board.positionHasRoad(owner, currentPosition)) {
return true;
}
for (SuggestedBuildable<Road> suggestedRoad : suggestedRoadMap.get(
currentPosition
)) {
Road road = suggestedRoad.getBuildable();
if (knownRoads.contains(road)) continue;
IntPoint position1 = road.getPosition1();
IntPoint position2 = road.getPosition2();
IntPoint oppositePosition = currentPosition.equals(position1)
? position2
: position1;
foundNewSuggestedRoads = true;
openPoints.addLast(oppositePosition);
}
}
return !foundNewSuggestedRoads;
}
private HashSet<Road> toRealRoads(
HashSet<SuggestedBuildable<Road>> suggestedRoads
) {
HashSet<Road> result = new HashSet<>();
for (SuggestedBuildable<Road> suggestedRoad : suggestedRoads) {
result.add(suggestedRoad.getBuildable());
}
return result;
}
public void setSuggestedBuildingMap(
Matrix<SuggestedBuildable<? extends Building>> suggestedBuildingMap
) {
this.suggestedBuildingMap = suggestedBuildingMap;
}
public void setSuggestedRoadMap(
Matrix<HashSet<SuggestedBuildable<Road>>> suggestedRoadMap
) {
this.suggestedRoadMap = suggestedRoadMap;
}
public void setOwner(Player owner) {
this.owner = owner;
}
}
|
92347943fb6b6e778db55b1ae68d92edb1f574cb | 1,778 | java | Java | app/controllers/Authentication.java | michalzubkowicz/UniverseSiteMonitor | 4fadb922ec8090f3bf463d2aa97c0317173039fb | [
"Apache-2.0"
] | null | null | null | app/controllers/Authentication.java | michalzubkowicz/UniverseSiteMonitor | 4fadb922ec8090f3bf463d2aa97c0317173039fb | [
"Apache-2.0"
] | null | null | null | app/controllers/Authentication.java | michalzubkowicz/UniverseSiteMonitor | 4fadb922ec8090f3bf463d2aa97c0317173039fb | [
"Apache-2.0"
] | null | null | null | 24.694444 | 68 | 0.579303 | 996,937 | package controllers;
import models.User;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.adminlogin;
import static play.data.Form.form;
public class Authentication extends Controller {
public static Result authenticate() {
Form<Login> loginForm = form(Login.class).bindFromRequest();
if (loginForm.hasErrors()) {
return badRequest(adminlogin.render(loginForm));
} else {
session().clear();
session("username", loginForm.get().adminusername);
session("usergroup", User.USER_PANEL);
return redirect(
routes.Admin.index()
);
}
}
public static Result login() {
return ok(
adminlogin.render(form(Login.class))
);
}
public static Result logout() {
session().clear();
flash("success", "You've been logged out");
return redirect(
routes.Authentication.login()
);
}
public static class Login {
public String adminusername;
public String adminpassword;
public String getAdminusername() {
return adminusername;
}
public void setAdminusername(String adminusername) {
this.adminusername = adminusername;
}
public String getAdminpassword() {
return adminpassword;
}
public void setAdminpassword(String adminpassword) {
this.adminpassword = adminpassword;
}
public String validate() {
if (!User.authenticate(adminusername, adminpassword)) {
return "Invalid username or password";
}
return null;
}
}
}
|
923479fb7ed6962e64824d1aecac1b16ccc9f45a | 1,907 | java | Java | sandbox/runtime/container/wildfly/webapp/src/main/java/io/fabric8/portable/runtime/wildfly/FabricActivator.java | rcernich/fabric8io-fabric8 | 551d151c5d6d2d8c24d5d35877bfec79a5210153 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2016-04-30T14:17:14.000Z | 2016-04-30T14:17:14.000Z | sandbox/runtime/container/wildfly/webapp/src/main/java/io/fabric8/portable/runtime/wildfly/FabricActivator.java | rcernich/fabric8io-fabric8 | 551d151c5d6d2d8c24d5d35877bfec79a5210153 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | sandbox/runtime/container/wildfly/webapp/src/main/java/io/fabric8/portable/runtime/wildfly/FabricActivator.java | rcernich/fabric8io-fabric8 | 551d151c5d6d2d8c24d5d35877bfec79a5210153 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | 35.314815 | 82 | 0.75354 | 996,938 | /**
* Copyright 2005-2014 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package io.fabric8.portable.runtime.wildfly;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.jboss.gravia.runtime.Module;
import org.jboss.gravia.runtime.ModuleContext;
import org.jboss.gravia.runtime.Runtime;
import org.jboss.gravia.runtime.RuntimeLocator;
import org.jboss.gravia.runtime.embedded.spi.BundleContextAdaptor;
import org.osgi.framework.BundleContext;
/**
* Initialize the fabric webapp
*
* @since 20-Nov-2013
*/
public class FabricActivator implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
// Get the module for this webapp
Runtime runtime = RuntimeLocator.getRequiredRuntime();
ServletContext servletContext = event.getServletContext();
Module module = runtime.getModule(servletContext.getClassLoader());
// HttpService integration
ModuleContext moduleContext = module.getModuleContext();
BundleContext bundleContext = new BundleContextAdaptor(moduleContext);
servletContext.setAttribute(BundleContext.class.getName(), bundleContext);
}
@Override
public void contextDestroyed(ServletContextEvent event) {
}
}
|
92347b033c7b26448fb4ecd58921c1d33140e3a7 | 2,293 | java | Java | core/src/main/java/io/zero88/qwe/dto/JsonDataImpl.java | zero88/blueprint | ee30dc3bbda7f8cfd91b00d7e9003ee16bee044b | [
"Apache-2.0"
] | 3 | 2021-07-27T15:38:40.000Z | 2022-02-16T04:09:13.000Z | core/src/main/java/io/zero88/qwe/dto/JsonDataImpl.java | zero88/blueprint | ee30dc3bbda7f8cfd91b00d7e9003ee16bee044b | [
"Apache-2.0"
] | 34 | 2021-05-12T06:12:58.000Z | 2022-03-31T04:10:39.000Z | core/src/main/java/io/zero88/qwe/dto/JsonDataImpl.java | zero88/qwe | ee30dc3bbda7f8cfd91b00d7e9003ee16bee044b | [
"Apache-2.0"
] | null | null | null | 34.742424 | 113 | 0.615787 | 996,939 | package io.zero88.qwe.dto;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.DecodeException;
import io.vertx.core.json.JsonObject;
import io.zero88.qwe.exceptions.ErrorCode;
import io.zero88.qwe.exceptions.QWEException;
import lombok.NoArgsConstructor;
import lombok.NonNull;
@NoArgsConstructor
final class JsonDataImpl extends HashMap<String, Object> implements JsonData {
private static final Logger logger = LoggerFactory.getLogger(JsonDataImpl.class);
JsonDataImpl(@NonNull Map<String, Object> map) { this.putAll(map); }
JsonDataImpl(@NonNull JsonObject json) { this(json.getMap()); }
static JsonData tryParse(@NonNull Buffer buffer, boolean isJson, String backupKey, boolean isWrapper) {
if (buffer.length() == 0) {
return new JsonDataImpl();
}
try {
if (isWrapper) {
return new JsonDataImpl(new JsonObject().put(backupKey, buffer.toJson()));
}
return new JsonDataImpl(buffer.toJsonObject());
} catch (DecodeException e) {
logger.trace("Failed to parse json. Try json array", e);
JsonObject data = new JsonObject();
try {
data.put(backupKey, buffer.toJsonArray());
} catch (DecodeException ex) {
if (isJson) {
throw new QWEException(ErrorCode.INVALID_ARGUMENT,
"Cannot parse json data. Received data: " + buffer, ex);
}
logger.trace("Failed to parse json array. Use text", ex);
//TODO check length, check encode
data.put(backupKey, buffer.toString());
}
return new JsonDataImpl(data);
}
}
static JsonData tryParse(@NonNull Object obj) {
if (obj instanceof JsonData) {
return (JsonData) obj;
}
if (obj instanceof Buffer) {
return tryParse((Buffer) obj, true, SUCCESS_KEY, false);
}
return new JsonDataImpl(
JsonDataSerializer.builder().backupKey(SUCCESS_KEY).lenient(true).mapper(MAPPER).build().apply(obj));
}
}
|
92347b34836953f720b6711f640bcd59843e1682 | 1,969 | java | Java | app/src/main/java/me/robwei/silvester2017/MainActivity.java | RobWei/Silvester-2017 | 8f4f3360dec5e244f41c9d18e0184b116d03777c | [
"Apache-2.0"
] | null | null | null | app/src/main/java/me/robwei/silvester2017/MainActivity.java | RobWei/Silvester-2017 | 8f4f3360dec5e244f41c9d18e0184b116d03777c | [
"Apache-2.0"
] | null | null | null | app/src/main/java/me/robwei/silvester2017/MainActivity.java | RobWei/Silvester-2017 | 8f4f3360dec5e244f41c9d18e0184b116d03777c | [
"Apache-2.0"
] | null | null | null | 35.8 | 118 | 0.627222 | 996,940 | package me.robwei.silvester2017;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import pl.droidsonroids.gif.GifImageView;
public class MainActivity extends AppCompatActivity
{
private static final String FORMAT = "%02d:%02d:%02d";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView text1 = (TextView)findViewById(R.id.timeLeft);
final TextView text2 = (TextView)findViewById(R.id.textrz);
final GifImageView giv = (GifImageView) findViewById(R.id.gif);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
giv.setVisibility(View.INVISIBLE);
long between = (Long.valueOf("1514761200000")-System.currentTimeMillis());
new CountDownTimer(between, 1000)
{
public void onTick(long millisUntilFinished)
{
text1.setText(""+String.format(FORMAT,
TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(
TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
}
public void onFinish()
{
text1.setText("");
text2.setText("");
giv.setVisibility(View.VISIBLE);
}
}.start();
}
}
|
92347f68988c7643d58444c5d5d6713bf0d978a1 | 2,022 | java | Java | core/cas-server-core-services-api/src/test/java/org/apereo/cas/services/util/DefaultRegisteredServiceCipherExecutorTests.java | glennjin/cas | b50a668358a6b95b0eedcb8805e0e7f6237919e2 | [
"Apache-2.0"
] | 3 | 2018-10-10T09:05:29.000Z | 2021-02-23T02:29:49.000Z | core/cas-server-core-services-api/src/test/java/org/apereo/cas/services/util/DefaultRegisteredServiceCipherExecutorTests.java | glennjin/cas | b50a668358a6b95b0eedcb8805e0e7f6237919e2 | [
"Apache-2.0"
] | null | null | null | core/cas-server-core-services-api/src/test/java/org/apereo/cas/services/util/DefaultRegisteredServiceCipherExecutorTests.java | glennjin/cas | b50a668358a6b95b0eedcb8805e0e7f6237919e2 | [
"Apache-2.0"
] | null | null | null | 37.444444 | 136 | 0.763106 | 996,941 | package org.apereo.cas.services.util;
import org.apereo.cas.services.AbstractRegisteredService;
import org.apereo.cas.services.RegisteredServiceCipherExecutor;
import org.apereo.cas.services.RegisteredServicePublicKeyImpl;
import org.apereo.cas.services.RegisteredServiceTestUtils;
import org.apereo.cas.ticket.UniqueTicketIdGenerator;
import org.apereo.cas.util.DefaultUniqueTicketIdGenerator;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.junit.Assert.*;
/**
* This is {@link DefaultRegisteredServiceCipherExecutorTests}.
*
* @author Misagh Moayyed
* @since 5.2.0
*/
public class DefaultRegisteredServiceCipherExecutorTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void verifyCipherUnableToEncodeForStringIsTooLong() {
final AbstractRegisteredService svc = getService("classpath:keys/RSA1024Public.key");
final String ticketId = getStringToEncode();
final RegisteredServiceCipherExecutor e = new DefaultRegisteredServiceCipherExecutor();
assertNull(e.encode(ticketId, svc));
}
@Test
public void verifyCipherAbleToEncode() {
final AbstractRegisteredService svc = getService("classpath:keys/RSA4096Public.key");
final String ticketId = getStringToEncode();
final RegisteredServiceCipherExecutor e = new DefaultRegisteredServiceCipherExecutor();
assertNotNull(e.encode(ticketId, svc));
}
private AbstractRegisteredService getService(final String keyLocation) {
final AbstractRegisteredService svc = RegisteredServiceTestUtils.getRegisteredService("test");
svc.setPublicKey(new RegisteredServicePublicKeyImpl(keyLocation, "RSA"));
return svc;
}
private String getStringToEncode() {
final UniqueTicketIdGenerator gen = new DefaultUniqueTicketIdGenerator(100, "testing-gce-52ac2b2f-3d76-42e0-8d58-7ec8ff76a287");
return gen.getNewTicketId("TEST");
}
}
|
923480be9677455708cf2ea0bb1fad6f8b0b6a1b | 1,274 | java | Java | app/src/main/java/com/hmtri/foodsapp/view/home/HomeView.java | hmtri-it/FoodsApp | fa9839d56f7330210043262487f0b41dd7c4c4dd | [
"Apache-2.0"
] | 1 | 2019-07-30T07:34:03.000Z | 2019-07-30T07:34:03.000Z | app/src/main/java/com/hmtri/foodsapp/view/home/HomeView.java | hmtri-it/FoodsApp | fa9839d56f7330210043262487f0b41dd7c4c4dd | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/hmtri/foodsapp/view/home/HomeView.java | hmtri-it/FoodsApp | fa9839d56f7330210043262487f0b41dd7c4c4dd | [
"Apache-2.0"
] | 1 | 2019-07-26T04:44:18.000Z | 2019-07-26T04:44:18.000Z | 37.470588 | 92 | 0.55887 | 996,942 | /*-----------------------------------------------------------------------------
- Developed by hmtri-it -
- Copyright (c) 2019. All rights reserved -
-----------------------------------------------------------------------------*/
package com.hmtri.foodsapp.view.home;
import com.hmtri.foodsapp.model.Categories;
import com.hmtri.foodsapp.model.Meals;
import java.util.List;
public interface HomeView {
/*
* TODO Create void method
*
* The interface of this method will behave bridging between presenters to activities
* then activity Overriding the interface
*
* 1. behavior, when loading must appear || showLoading();
* 2. Loading must be removed || hideLoading()
* 3. Display Meal data (with List <Meal> meals) parameters || setMeals();
* 4. Displays Category data (with List parameters <Category> category) setCategories();
* 5. and, Behavior when an error occurs when requesting data to the API
*/
// TODO showLoading()
void showLoading();
void hideLoading();
void setMeals(List<Meals.Meal> meal);
void setCategory(List<Categories.Category> category);
void onErrorLoading(String message);
}
|
923480fa5b47949edfa15a7ca6cae72f502a23fb | 15,176 | java | Java | streams/src/main/java/org/apache/kafka/streams/processor/internals/GlobalStreamThread.java | lcyanxi/kafka | 9e81ec9a6ebe2913687f66cfb286177dd853ac13 | [
"Apache-2.0"
] | 126 | 2018-08-31T21:47:30.000Z | 2022-03-11T10:01:31.000Z | streams/src/main/java/org/apache/kafka/streams/processor/internals/GlobalStreamThread.java | lcyanxi/kafka | 9e81ec9a6ebe2913687f66cfb286177dd853ac13 | [
"Apache-2.0"
] | 75 | 2019-03-07T20:24:18.000Z | 2022-03-31T02:14:37.000Z | streams/src/main/java/org/apache/kafka/streams/processor/internals/GlobalStreamThread.java | lcyanxi/kafka | 9e81ec9a6ebe2913687f66cfb286177dd853ac13 | [
"Apache-2.0"
] | 46 | 2018-09-13T07:27:19.000Z | 2022-03-23T17:49:13.000Z | 39.832021 | 145 | 0.606154 | 996,943 | /*
* 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.kafka.streams.processor.internals;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.InvalidOffsetException;
import org.apache.kafka.common.Metric;
import org.apache.kafka.common.MetricName;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.utils.LogContext;
import org.apache.kafka.common.utils.Time;
import org.apache.kafka.common.utils.Utils;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.errors.LockException;
import org.apache.kafka.streams.errors.StreamsException;
import org.apache.kafka.streams.processor.StateRestoreListener;
import org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl;
import org.apache.kafka.streams.state.internals.ThreadCache;
import org.slf4j.Logger;
import java.io.IOException;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static org.apache.kafka.streams.processor.internals.GlobalStreamThread.State.DEAD;
import static org.apache.kafka.streams.processor.internals.GlobalStreamThread.State.PENDING_SHUTDOWN;
/**
* This is the thread responsible for keeping all Global State Stores updated.
* It delegates most of the responsibility to the internal class StateConsumer
*/
public class GlobalStreamThread extends Thread {
private final Logger log;
private final LogContext logContext;
private final StreamsConfig config;
private final Consumer<byte[], byte[]> globalConsumer;
private final StateDirectory stateDirectory;
private final Time time;
private final ThreadCache cache;
private final StreamsMetricsImpl streamsMetrics;
private final ProcessorTopology topology;
private volatile StreamsException startupException;
/**
* The states that the global stream thread can be in
*
* <pre>
* +-------------+
* +<--- | Created (0) |
* | +-----+-------+
* | |
* | v
* | +-----+-------+
* +<--- | Running (1) |
* | +-----+-------+
* | |
* | v
* | +-----+-------+
* +---> | Pending |
* | Shutdown (2)|
* +-----+-------+
* |
* v
* +-----+-------+
* | Dead (3) |
* +-------------+
* </pre>
*
* Note the following:
* <ul>
* <li>Any state can go to PENDING_SHUTDOWN. That is because streams can be closed at any time.</li>
* <li>State PENDING_SHUTDOWN may want to transit itself. In this case we will forbid the transition but will not treat as an error.</li>
* </ul>
*/
public enum State implements ThreadStateTransitionValidator {
CREATED(1, 2), RUNNING(2), PENDING_SHUTDOWN(3), DEAD;
private final Set<Integer> validTransitions = new HashSet<>();
State(final Integer... validTransitions) {
this.validTransitions.addAll(Arrays.asList(validTransitions));
}
public boolean isRunning() {
return equals(RUNNING);
}
@Override
public boolean isValidTransition(final ThreadStateTransitionValidator newState) {
final State tmpState = (State) newState;
return validTransitions.contains(tmpState.ordinal());
}
}
private volatile State state = State.CREATED;
private final Object stateLock = new Object();
private StreamThread.StateListener stateListener = null;
private final String logPrefix;
private final StateRestoreListener stateRestoreListener;
/**
* Set the {@link StreamThread.StateListener} to be notified when state changes. Note this API is internal to
* Kafka Streams and is not intended to be used by an external application.
*/
public void setStateListener(final StreamThread.StateListener listener) {
stateListener = listener;
}
/**
* @return The state this instance is in
*/
public State state() {
// we do not need to use the stat lock since the variable is volatile
return state;
}
/**
* Sets the state
*
* @param newState New state
*/
private void setState(final State newState) {
final State oldState = state;
synchronized (stateLock) {
if (state == State.PENDING_SHUTDOWN && newState == State.PENDING_SHUTDOWN) {
// when the state is already in PENDING_SHUTDOWN, its transition to itself
// will be refused but we do not throw exception here
return;
} else if (state == State.DEAD) {
// when the state is already in NOT_RUNNING, all its transitions
// will be refused but we do not throw exception here
return;
} else if (!state.isValidTransition(newState)) {
log.error("Unexpected state transition from {} to {}", oldState, newState);
throw new StreamsException(logPrefix + "Unexpected state transition from " + oldState + " to " + newState);
} else {
log.info("State transition from {} to {}", oldState, newState);
}
state = newState;
}
if (stateListener != null) {
stateListener.onChange(this, state, oldState);
}
}
public boolean stillRunning() {
synchronized (stateLock) {
return state.isRunning();
}
}
public GlobalStreamThread(final ProcessorTopology topology,
final StreamsConfig config,
final Consumer<byte[], byte[]> globalConsumer,
final StateDirectory stateDirectory,
final long cacheSizeBytes,
final StreamsMetricsImpl streamsMetrics,
final Time time,
final String threadClientId,
final StateRestoreListener stateRestoreListener) {
super(threadClientId);
this.time = time;
this.config = config;
this.topology = topology;
this.globalConsumer = globalConsumer;
this.stateDirectory = stateDirectory;
this.streamsMetrics = streamsMetrics;
this.logPrefix = String.format("global-stream-thread [%s] ", threadClientId);
this.logContext = new LogContext(logPrefix);
this.log = logContext.logger(getClass());
this.cache = new ThreadCache(logContext, cacheSizeBytes, this.streamsMetrics);
this.stateRestoreListener = stateRestoreListener;
}
static class StateConsumer {
private final Consumer<byte[], byte[]> globalConsumer;
private final GlobalStateMaintainer stateMaintainer;
private final Time time;
private final Duration pollTime;
private final long flushInterval;
private final Logger log;
private long lastFlush;
StateConsumer(final LogContext logContext,
final Consumer<byte[], byte[]> globalConsumer,
final GlobalStateMaintainer stateMaintainer,
final Time time,
final Duration pollTime,
final long flushInterval) {
this.log = logContext.logger(getClass());
this.globalConsumer = globalConsumer;
this.stateMaintainer = stateMaintainer;
this.time = time;
this.pollTime = pollTime;
this.flushInterval = flushInterval;
}
/**
* @throws IllegalStateException If store gets registered after initialized is already finished
* @throws StreamsException if the store's change log does not contain the partition
*/
void initialize() {
final Map<TopicPartition, Long> partitionOffsets = stateMaintainer.initialize();
globalConsumer.assign(partitionOffsets.keySet());
for (final Map.Entry<TopicPartition, Long> entry : partitionOffsets.entrySet()) {
globalConsumer.seek(entry.getKey(), entry.getValue());
}
lastFlush = time.milliseconds();
}
void pollAndUpdate() {
try {
final ConsumerRecords<byte[], byte[]> received = globalConsumer.poll(pollTime);
for (final ConsumerRecord<byte[], byte[]> record : received) {
stateMaintainer.update(record);
}
final long now = time.milliseconds();
if (now >= lastFlush + flushInterval) {
stateMaintainer.flushState();
lastFlush = now;
}
} catch (final InvalidOffsetException recoverableException) {
log.error("Updating global state failed. You can restart KafkaStreams to recover from this error.", recoverableException);
throw new StreamsException("Updating global state failed. " +
"You can restart KafkaStreams to recover from this error.", recoverableException);
}
}
public void close() throws IOException {
try {
globalConsumer.close();
} catch (final RuntimeException e) {
// just log an error if the consumer throws an exception during close
// so we can always attempt to close the state stores.
log.error("Failed to close global consumer due to the following error:", e);
}
stateMaintainer.close();
}
}
@Override
public void run() {
final StateConsumer stateConsumer = initialize();
if (stateConsumer == null) {
// during initialization, the caller thread would wait for the state consumer
// to restore the global state store before transiting to RUNNING state and return;
// if an error happens during the restoration process, the stateConsumer will be null
// and in this case we will transit the state to PENDING_SHUTDOWN and DEAD immediately.
// the exception will be thrown in the caller thread during start() function.
setState(State.PENDING_SHUTDOWN);
setState(State.DEAD);
log.warn("Error happened during initialization of the global state store; this thread has shutdown");
streamsMetrics.removeAllThreadLevelSensors(getName());
return;
}
setState(State.RUNNING);
try {
while (stillRunning()) {
stateConsumer.pollAndUpdate();
}
} finally {
// set the state to pending shutdown first as it may be called due to error;
// its state may already be PENDING_SHUTDOWN so it will return false but we
// intentionally do not check the returned flag
setState(State.PENDING_SHUTDOWN);
log.info("Shutting down");
try {
stateConsumer.close();
} catch (final IOException e) {
log.error("Failed to close state maintainer due to the following error:", e);
}
streamsMetrics.removeAllThreadLevelSensors(getName());
setState(DEAD);
log.info("Shutdown complete");
}
}
private StateConsumer initialize() {
try {
final GlobalStateManager stateMgr = new GlobalStateManagerImpl(
logContext,
topology,
globalConsumer,
stateDirectory,
stateRestoreListener,
config);
final GlobalProcessorContextImpl globalProcessorContext = new GlobalProcessorContextImpl(
config,
stateMgr,
streamsMetrics,
cache);
stateMgr.setGlobalProcessorContext(globalProcessorContext);
final StateConsumer stateConsumer = new StateConsumer(
logContext,
globalConsumer,
new GlobalStateUpdateTask(
topology,
globalProcessorContext,
stateMgr,
config.defaultDeserializationExceptionHandler(),
logContext
),
time,
Duration.ofMillis(config.getLong(StreamsConfig.POLL_MS_CONFIG)),
config.getLong(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG)
);
stateConsumer.initialize();
return stateConsumer;
} catch (final LockException fatalException) {
final String errorMsg = "Could not lock global state directory. This could happen if multiple KafkaStreams " +
"instances are running on the same host using the same state directory.";
log.error(errorMsg, fatalException);
startupException = new StreamsException(errorMsg, fatalException);
} catch (final StreamsException fatalException) {
startupException = fatalException;
} catch (final Exception fatalException) {
startupException = new StreamsException("Exception caught during initialization of GlobalStreamThread", fatalException);
}
return null;
}
@Override
public synchronized void start() {
super.start();
while (!stillRunning()) {
Utils.sleep(1);
if (startupException != null) {
throw startupException;
}
}
}
public void shutdown() {
// one could call shutdown() multiple times, so ignore subsequent calls
// if already shutting down or dead
setState(PENDING_SHUTDOWN);
}
public Map<MetricName, Metric> consumerMetrics() {
return Collections.unmodifiableMap(globalConsumer.metrics());
}
}
|
9234810f8fc71294589eab2c0207e5f5f2854855 | 1,012 | java | Java | src/cz/hartrik/common/DateTimeUtils.java | Hartrik/HS-Common-Library | ef18253fe47216ec01a01b89a104e4f1fd20e0ef | [
"MIT"
] | null | null | null | src/cz/hartrik/common/DateTimeUtils.java | Hartrik/HS-Common-Library | ef18253fe47216ec01a01b89a104e4f1fd20e0ef | [
"MIT"
] | null | null | null | src/cz/hartrik/common/DateTimeUtils.java | Hartrik/HS-Common-Library | ef18253fe47216ec01a01b89a104e4f1fd20e0ef | [
"MIT"
] | null | null | null | 28.914286 | 69 | 0.644269 | 996,944 | package cz.hartrik.common;
import cz.hartrik.common.reflect.LibraryClass;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
/**
* Poskytuje statické metody pro zjednodušení práce s datem a časem.
*
* @version 2015-04-04
* @author Patrik Harag
*/
@LibraryClass
public final class DateTimeUtils {
private DateTimeUtils() { }
/** Formát ve tvaru <code>yyyy-MM-dd HH-mm-ss</code> */
public static final DateTimeFormatter TIMESTAMP_FORMATTER =
new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral(" ")
.appendPattern("HH-mm-ss").toFormatter();
/**
* Vrátí aktuální čas ve tvaru <code>yyyy-MM-dd HH-mm-ss</code>
*
* @return formátovaný čas
*/
public static String timestamp() {
return TIMESTAMP_FORMATTER.format(ZonedDateTime.now());
}
} |
92348149af8abb522cff440e21ae94b1499e00ba | 1,584 | java | Java | model/src/main/java/io/jans/as/model/gluu/GluuErrorResponseType.java | qbert2k/jans-auth-server | 3a383e4c96b0f17ed8aa61d54ea82778047fe5b9 | [
"Apache-2.0"
] | 30 | 2020-10-08T07:42:25.000Z | 2022-01-14T08:28:54.000Z | model/src/main/java/io/jans/as/model/gluu/GluuErrorResponseType.java | qbert2k/jans-auth-server | 3a383e4c96b0f17ed8aa61d54ea82778047fe5b9 | [
"Apache-2.0"
] | 604 | 2022-01-13T12:32:50.000Z | 2022-03-31T20:27:36.000Z | model/src/main/java/io/jans/as/model/gluu/GluuErrorResponseType.java | qbert2k/jans-auth-server | 3a383e4c96b0f17ed8aa61d54ea82778047fe5b9 | [
"Apache-2.0"
] | 17 | 2020-10-07T17:23:59.000Z | 2022-01-14T09:28:21.000Z | 24 | 124 | 0.645833 | 996,945 | /*
* Janssen Project software is available under the Apache License (2004). See http://www.apache.org/licenses/ for full text.
*
* Copyright (c) 2020, Janssen Project
*/
package io.jans.as.model.gluu;
import io.jans.as.model.error.IErrorType;
import java.util.HashMap;
import java.util.Map;
public enum GluuErrorResponseType implements IErrorType {
/**
* The server encountered an unexpected condition which
* prevented it from fulfilling the request.
*/
SERVER_ERROR("server_error");
private static final Map<String, GluuErrorResponseType> lookup = new HashMap<>();
static {
for (GluuErrorResponseType enumType : values()) {
lookup.put(enumType.getParameter(), enumType);
}
}
private final String paramName;
GluuErrorResponseType(String paramName) {
this.paramName = paramName;
}
/**
* Return the corresponding enumeration from a string parameter.
*
* @param param The parameter to be match.
* @return The <code>enumeration</code> if found, otherwise
* <code>null</code>.
*/
public static GluuErrorResponseType fromString(String param) {
return lookup.get(param);
}
/**
* Returns a string representation of the object. In this case, the lower
* case code of the error.
*/
@Override
public String toString() {
return paramName;
}
/**
* Gets error parameter.
*
* @return error parameter
*/
@Override
public String getParameter() {
return paramName;
}
} |
923481c5c917e5e4dfc0b8d1a4463ed4bffce9e8 | 5,956 | java | Java | query/src/main/java/org/infinispan/query/clustered/ClusteredCacheQueryImpl.java | skymysky/infinispan | ace5cc23f345ed4e782fc863e83d5aa24e3a1ac9 | [
"Apache-2.0"
] | 1 | 2020-06-01T21:20:47.000Z | 2020-06-01T21:20:47.000Z | query/src/main/java/org/infinispan/query/clustered/ClusteredCacheQueryImpl.java | skymysky/infinispan | ace5cc23f345ed4e782fc863e83d5aa24e3a1ac9 | [
"Apache-2.0"
] | 1 | 2022-03-02T14:34:13.000Z | 2022-03-02T14:34:13.000Z | query/src/main/java/org/infinispan/query/clustered/ClusteredCacheQueryImpl.java | skymysky/infinispan | ace5cc23f345ed4e782fc863e83d5aa24e3a1ac9 | [
"Apache-2.0"
] | null | null | null | 39.184211 | 165 | 0.708697 | 996,946 | package org.infinispan.query.clustered;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.lucene.search.Query;
import org.hibernate.search.exception.SearchException;
import org.hibernate.search.spi.CustomTypeMetadata;
import org.hibernate.search.spi.IndexedTypeMap;
import org.hibernate.search.spi.SearchIntegrator;
import org.infinispan.AdvancedCache;
import org.infinispan.query.CacheQuery;
import org.infinispan.query.FetchOptions;
import org.infinispan.query.ResultIterator;
import org.infinispan.query.backend.KeyTransformationHandler;
import org.infinispan.query.impl.CacheQueryImpl;
import org.infinispan.query.impl.QueryDefinition;
import org.infinispan.remoting.transport.Address;
/**
* An extension of CacheQueryImpl used for distributed queries.
*
* @author Israel Lacerra <israeldl@gmail.com>
* @since 5.1
*/
public final class ClusteredCacheQueryImpl<E> extends CacheQueryImpl<E> {
private Integer resultSize;
private final ClusteredQueryInvoker invoker;
// like QueryHits.DEFAULT_TOP_DOC_RETRIEVAL_SIZE = 100;
// (just to have the same default size of not clustered queries)
private int maxResults = 100;
private int firstResult = 0;
public ClusteredCacheQueryImpl(Query luceneQuery, SearchIntegrator searchFactory,
ExecutorService asyncExecutor, AdvancedCache<?, ?> cache, KeyTransformationHandler keyTransformationHandler, Class<?>... classes) {
super(luceneQuery, searchFactory, cache, keyTransformationHandler, null, classes);
this.invoker = new ClusteredQueryInvoker(cache, asyncExecutor);
}
public ClusteredCacheQueryImpl(QueryDefinition queryDefinition, ExecutorService asyncExecutor, AdvancedCache<?, ?> cache,
KeyTransformationHandler keyTransformationHandler, IndexedTypeMap<CustomTypeMetadata> metadata) {
super(queryDefinition, cache, keyTransformationHandler);
if (metadata != null) {
this.queryDefinition.setIndexedType(metadata.keySet().iterator().next().getPojoType());
this.queryDefinition.setSortableField(metadata.values().iterator().next().getSortableFields());
}
this.invoker = new ClusteredQueryInvoker(cache, asyncExecutor);
}
@Override
public CacheQuery<E> maxResults(int maxResults) {
this.maxResults = maxResults;
return super.maxResults(maxResults);
}
@Override
public CacheQuery<E> firstResult(int firstResult) {
this.firstResult = firstResult;
return super.firstResult(firstResult);
}
@Override
public int getResultSize() {
partitionHandlingSupport.checkCacheAvailable();
if (resultSize == null) {
List<QueryResponse> responses = invoker.broadcast(ClusteredQueryCommand.getResultSize(queryDefinition, cache));
int accumulator = 0;
for (QueryResponse response : responses) {
accumulator += response.getResultSize();
}
resultSize = accumulator;
}
return resultSize;
}
@Override
public ResultIterator<E> iterator(FetchOptions fetchOptions) throws SearchException {
partitionHandlingSupport.checkCacheAvailable();
queryDefinition.setMaxResults(getNodeMaxResults());
switch (fetchOptions.getFetchMode()) {
case EAGER: {
ClusteredQueryCommand command = ClusteredQueryCommand.createEagerIterator(queryDefinition, cache);
Map<Address, NodeTopDocs> topDocsResponses = broadcastQuery(command);
return new DistributedIterator<>(queryDefinition.getSort(),
fetchOptions.getFetchSize(), resultSize, maxResults,
firstResult, topDocsResponses, cache);
}
case LAZY: {
UUID queryId = UUID.randomUUID();
ClusteredQueryCommand command = ClusteredQueryCommand.createLazyIterator(queryDefinition, cache, queryId);
Map<Address, NodeTopDocs> topDocsResponses = broadcastQuery(command);
// Make a sort copy to avoid reversed results
return new DistributedLazyIterator<>(queryDefinition.getSort(),
fetchOptions.getFetchSize(), resultSize, maxResults,
firstResult, queryId, topDocsResponses, invoker, cache);
}
default:
throw new IllegalArgumentException("Unknown FetchMode " + fetchOptions.getFetchMode());
}
}
// number of results of each node of cluster
private int getNodeMaxResults() {
return maxResults + firstResult;
}
private Map<Address, NodeTopDocs> broadcastQuery(ClusteredQueryCommand command) {
Map<Address, NodeTopDocs> topDocsResponses = new HashMap<>();
int resultSize = 0;
List<QueryResponse> responses = invoker.broadcast(command);
for (QueryResponse queryResponse : responses) {
if (queryResponse.getResultSize() > 0) {
topDocsResponses.put(queryResponse.getNodeTopDocs().address, queryResponse.getNodeTopDocs());
resultSize += queryResponse.getResultSize();
}
}
this.resultSize = resultSize;
return topDocsResponses;
}
@Override
public List<E> list() throws SearchException {
partitionHandlingSupport.checkCacheAvailable();
List<E> values = new ArrayList<>();
try (ResultIterator<E> iterator = iterator(new FetchOptions().fetchMode(FetchOptions.FetchMode.EAGER))) {
while (iterator.hasNext()) {
values.add(iterator.next());
}
}
return values;
}
@Override
public CacheQuery<E> timeout(long timeout, TimeUnit timeUnit) {
// TODO [anistor] see https://issues.jboss.org/browse/ISPN-9469
throw new UnsupportedOperationException("Clustered queries do not support timeouts yet.");
}
}
|
92348373c0ba018f8354514cfcb81b6168986fd3 | 8,582 | java | Java | backend/manager/modules/dal/src/test/java/org/ovirt/engine/core/dao/DiskDaoTest.java | leongold/ovirt-engine | 8b915dab8ad8157849b36b60eb0ca159b1923faf | [
"Apache-2.0"
] | null | null | null | backend/manager/modules/dal/src/test/java/org/ovirt/engine/core/dao/DiskDaoTest.java | leongold/ovirt-engine | 8b915dab8ad8157849b36b60eb0ca159b1923faf | [
"Apache-2.0"
] | null | null | null | backend/manager/modules/dal/src/test/java/org/ovirt/engine/core/dao/DiskDaoTest.java | leongold/ovirt-engine | 8b915dab8ad8157849b36b60eb0ca159b1923faf | [
"Apache-2.0"
] | null | null | null | 35.758333 | 118 | 0.695059 | 996,947 | package org.ovirt.engine.core.dao;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.junit.Test;
import org.ovirt.engine.core.common.businessentities.storage.BaseDisk;
import org.ovirt.engine.core.common.businessentities.storage.Disk;
import org.ovirt.engine.core.common.businessentities.storage.DiskStorageType;
import org.ovirt.engine.core.compat.Guid;
public class DiskDaoTest extends BaseReadDaoTestCase<Guid, Disk, DiskDao> {
private static final int TOTAL_DISK_IMAGES = 8;
@Override
protected Guid getExistingEntityId() {
return FixturesTool.DISK_ID;
}
@Override
protected DiskDao prepareDao() {
return dbFacade.getDiskDao();
}
@Override
protected Guid generateNonExistingId() {
return Guid.Empty;
}
@Override
protected int getEntitiesTotalCount() {
return TOTAL_DISK_IMAGES + DiskLunMapDaoTest.TOTAL_DISK_LUN_MAPS;
}
@Override
@Test
public void testGet() {
Disk result = dao.get(getExistingEntityId());
assertNotNull(result);
assertEquals(getExistingEntityId().toString(), result.getId().toString());
}
@Test
public void testGetFilteredWithPermissions() {
Disk result = dao.get(getExistingEntityId(), PRIVILEGED_USER_ID, true);
assertNotNull(result);
assertEquals(getExistingEntityId().toString(), result.getId().toString());
}
@Test
public void testGetFilteredWithoutPermissions() {
Disk result = dao.get(getExistingEntityId(), UNPRIVILEGED_USER_ID, true);
assertNull(result);
}
@Test
public void testGetFilteredWithoutPermissionsNoFilter() {
Disk result = dao.get(getExistingEntityId(), UNPRIVILEGED_USER_ID, false);
assertNotNull(result);
assertEquals(getExistingEntityId().toString(), result.getId().toString());
}
@Test
public void testGetFilteredWithPermissionsNoFilter() {
Disk result = dao.get(getExistingEntityId(), PRIVILEGED_USER_ID, false);
assertNotNull(result);
assertEquals(getExistingEntityId().toString(), result.getId().toString());
}
@Test
public void testGetAllForVMFilteredWithPermissions() {
// test user 3 - has permissions
List<Disk> disks = dao.getAllForVm(FixturesTool.VM_RHEL5_POOL_57, PRIVILEGED_USER_ID, true);
assertFullGetAllForVMResult(disks);
}
@Test
public void testGetAllForVMFilteredWithPermissionsNoPermissions() {
// test user 2 - hasn't got permissions
List<Disk> disks = dao.getAllForVm(FixturesTool.VM_RHEL5_POOL_57, UNPRIVILEGED_USER_ID, true);
assertTrue("VM should have no disks viewable to the user", disks.isEmpty());
}
@Test
public void testGetAllForVMFilteredWithPermissionsNoPermissionsAndNoFilter() {
// test user 2 - hasn't got permissions, but no filtering was requested
List<Disk> disks = dao.getAllForVm(FixturesTool.VM_RHEL5_POOL_57, UNPRIVILEGED_USER_ID, false);
assertFullGetAllForVMResult(disks);
}
@Test
public void testGetPluggedForVMFilteredWithPermissions() {
// test user 3 - has permissions
List<Disk> disks = dao.getAllForVm(FixturesTool.VM_RHEL5_POOL_57, true, PRIVILEGED_USER_ID, true);
assertPluggedGetAllForVMResult(disks);
}
@Test
public void testGetPluggedForVMFilteredWithPermissionsNoPermissions() {
// test user 2 - hasn't got permissions
List<Disk> disks = dao.getAllForVm(FixturesTool.VM_RHEL5_POOL_57, true, UNPRIVILEGED_USER_ID, true);
assertTrue("VM should have no disks viewable to the user", disks.isEmpty());
}
@Test
public void testGetPluggedForVMFilteredWithPermissionsNoPermissionsAndNoFilter() {
// test user 2 - hasn't got permissions, but no filtering was requested
List<Disk> disks = dao.getAllForVm(FixturesTool.VM_RHEL5_POOL_57, true, UNPRIVILEGED_USER_ID, false);
assertPluggedGetAllForVMResult(disks);
}
@Test
public void testGetAllForVM() {
List<Disk> disks = dao.getAllForVm(FixturesTool.VM_RHEL5_POOL_57);
assertFullGetAllForVMResult(disks);
}
@Test
public void testGetAllForVMs() {
Map<Guid, List<Disk>> vmDisksMap = dao.getAllForVms(Collections.singletonList(FixturesTool.VM_RHEL5_POOL_57));
// TODO - add other VM
assertTrue(vmDisksMap.containsKey(FixturesTool.VM_RHEL5_POOL_57));
assertFullGetAllForVMResult(vmDisksMap.get(FixturesTool.VM_RHEL5_POOL_57));
}
@Test
public void testGetAllAttachableDisksByPoolIdNoDisks() {
List<Disk> result =
dao.getAllAttachableDisksByPoolId(FixturesTool.STORAGE_POOL_NFS,
null,
null,
false);
assertTrue(result.isEmpty());
}
@Test
public void testGetAllAttachableDisksByPoolIdNull() {
List<Disk> result =
dao.getAllAttachableDisksByPoolId(null, null, null, false);
assertFullGetAllAttachableDisksByPoolId(result);
}
@Test
public void testGetAllAttachableDisksByPoolWithPermissions() {
List<Disk> result =
dao.getAllAttachableDisksByPoolId(null, null, PRIVILEGED_USER_ID, true);
assertFullGetAllAttachableDisksByPoolId(result);
}
@Test
public void testGetAllAttachableDisksByPoolWithNoPermissions() {
List<Disk> result =
dao.getAllAttachableDisksByPoolId(null, null, UNPRIVILEGED_USER_ID, true);
assertTrue(result.isEmpty());
}
@Test
public void testGetAllAttachableDisksByPoolWithNoPermissionsFilterDisabled() {
List<Disk> result =
dao.getAllAttachableDisksByPoolId(null, null, UNPRIVILEGED_USER_ID, false);
assertFullGetAllAttachableDisksByPoolId(result);
}
@Test
public void testGetVmBootActiveDisk() {
Disk bootDisk = dao.getVmBootActiveDisk(FixturesTool.VM_RHEL5_POOL_57);
assertNotNull("VM should have a boot disk attached", bootDisk);
assertEquals("Wrong boot disk for VM", FixturesTool.BOOTABLE_DISK_ID, bootDisk.getId());
}
@Test
public void testGetVmPartialData() {
List<Disk> disks = dao.getAllForVm(FixturesTool.VM_RHEL5_POOL_57, PRIVILEGED_USER_ID, true);
assertFullGetAllForVMResult(disks);
assertEquals("New Description", disks.get(0).getDiskDescription());
assertNotNull(disks.get(0).getDiskAlias());
}
@Test
public void testGetAllFromDisksByDiskStorageType() {
List<Disk> disks = dao.getAllFromDisksByDiskStorageType(DiskStorageType.CINDER, PRIVILEGED_USER_ID, true);
assertEquals("We should have one disk", 1, disks.size());
}
/**
* Asserts the result of {@link DiskDao#getAllForVm(Guid)} contains the correct disks.
* @param disks
* The result to check
*/
private static void assertFullGetAllForVMResult(List<Disk> disks) {
assertEquals("VM should have six disks", 6, disks.size());
}
/**
* Asserts the result of {@link DiskDao#getAllForVm(Guid)} contains the correct plugged disks.
* @param disks
* The result to check
*/
private static void assertPluggedGetAllForVMResult(List<Disk> disks) {
Integer numberOfDisks = 5;
assertEquals("VM should have " + numberOfDisks + " plugged disk", numberOfDisks.intValue(), disks.size());
}
/**
* Asserts the result of {@link DiskDao#getAllAttachableDisksByPoolId} contains the floating disk.
* @param disks
* The result to check
*/
private static void assertFullGetAllAttachableDisksByPoolId(List<Disk> disks) {
assertEquals("There should be only four attachable disks", 4, disks.size());
Set<Guid> expectedFloatingDiskIds =
new HashSet<>(Arrays.asList(FixturesTool.FLOATING_DISK_ID, FixturesTool.FLOATING_LUN_ID,
FixturesTool.FLOATING_CINDER_DISK_ID));
Set<Guid> actualFloatingDiskIds = disks.stream().map(BaseDisk::getId).collect(Collectors.toSet());
assertEquals("Wrong attachable disks", expectedFloatingDiskIds, actualFloatingDiskIds);
}
}
|
9234841bca1c6388b477d2acf2325604bbeb3a09 | 3,938 | java | Java | systems/src/gen/java/org/bytedeco/systems/macosx/rusage.java | oxisto/javacpp-presets | a70841e089cbe4269cd3e1b1e6de2005c3b4aa16 | [
"Apache-2.0"
] | 2,132 | 2015-01-14T10:02:38.000Z | 2022-03-31T07:51:08.000Z | systems/src/gen/java/org/bytedeco/systems/macosx/rusage.java | oxisto/javacpp-presets | a70841e089cbe4269cd3e1b1e6de2005c3b4aa16 | [
"Apache-2.0"
] | 1,024 | 2015-01-11T18:35:03.000Z | 2022-03-31T14:52:22.000Z | systems/src/gen/java/org/bytedeco/systems/macosx/rusage.java | oxisto/javacpp-presets | a70841e089cbe4269cd3e1b1e6de2005c3b4aa16 | [
"Apache-2.0"
] | 759 | 2015-01-15T08:41:48.000Z | 2022-03-29T17:05:57.000Z | 57.911765 | 131 | 0.685119 | 996,948 | // Targeted by JavaCPP version 1.5.6: DO NOT EDIT THIS FILE
package org.bytedeco.systems.macosx;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.javacpp.presets.javacpp.*;
import static org.bytedeco.systems.global.macosx.*;
/* Current process' children */
/*
* A structure representing an accounting of resource utilization. The
* address of an instance of this structure is the second parameter to
* getrusage().
*
* Note: All values other than ru_utime and ru_stime are implementaiton
* defined and subject to change in a future release. Their use
* is discouraged for standards compliant programs.
*/
@Properties(inherit = org.bytedeco.systems.presets.macosx.class)
public class rusage extends Pointer {
static { Loader.load(); }
/** Default native constructor. */
public rusage() { super((Pointer)null); allocate(); }
/** Native array allocator. Access with {@link Pointer#position(long)}. */
public rusage(long size) { super((Pointer)null); allocateArray(size); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public rusage(Pointer p) { super(p); }
private native void allocate();
private native void allocateArray(long size);
@Override public rusage position(long position) {
return (rusage)super.position(position);
}
@Override public rusage getPointer(long i) {
return new rusage((Pointer)this).offsetAddress(i);
}
public native @ByRef timeval ru_utime(); public native rusage ru_utime(timeval setter); /* user time used (PL) */
public native @ByRef timeval ru_stime(); public native rusage ru_stime(timeval setter); /* system time used (PL) */
// #if __DARWIN_C_LEVEL < __DARWIN_C_FULL
// #else
/*
* Informational aliases for source compatibility with programs
* that need more information than that provided by standards,
* and which do not mind being OS-dependent.
*/
public native long ru_maxrss(); public native rusage ru_maxrss(long setter); /* max resident set size (PL) */
// #define ru_first ru_ixrss /* internal: ruadd() range start */
public native long ru_ixrss(); public native rusage ru_ixrss(long setter); /* integral shared memory size (NU) */
public native long ru_idrss(); public native rusage ru_idrss(long setter); /* integral unshared data (NU) */
public native long ru_isrss(); public native rusage ru_isrss(long setter); /* integral unshared stack (NU) */
public native long ru_minflt(); public native rusage ru_minflt(long setter); /* page reclaims (NU) */
public native long ru_majflt(); public native rusage ru_majflt(long setter); /* page faults (NU) */
public native long ru_nswap(); public native rusage ru_nswap(long setter); /* swaps (NU) */
public native long ru_inblock(); public native rusage ru_inblock(long setter); /* block input operations (atomic) */
public native long ru_oublock(); public native rusage ru_oublock(long setter); /* block output operations (atomic) */
public native long ru_msgsnd(); public native rusage ru_msgsnd(long setter); /* messages sent (atomic) */
public native long ru_msgrcv(); public native rusage ru_msgrcv(long setter); /* messages received (atomic) */
public native long ru_nsignals(); public native rusage ru_nsignals(long setter); /* signals received (atomic) */
public native long ru_nvcsw(); public native rusage ru_nvcsw(long setter); /* voluntary context switches (atomic) */
public native long ru_nivcsw(); public native rusage ru_nivcsw(long setter); /* involuntary " */
// #define ru_last ru_nivcsw /* internal: ruadd() range end */
// #endif /* __DARWIN_C_LEVEL >= __DARWIN_C_FULL */
}
|
92348766746b87984bee2b60c41671e854e1dc82 | 301 | java | Java | engine/src/main/java/com/aegean/icsd/engine/core/annotations/Key.java | Binarios/Mci | 6db8aa5877a447e905d4317fa7c5b5afe64a0ed9 | [
"Apache-2.0"
] | null | null | null | engine/src/main/java/com/aegean/icsd/engine/core/annotations/Key.java | Binarios/Mci | 6db8aa5877a447e905d4317fa7c5b5afe64a0ed9 | [
"Apache-2.0"
] | null | null | null | engine/src/main/java/com/aegean/icsd/engine/core/annotations/Key.java | Binarios/Mci | 6db8aa5877a447e905d4317fa7c5b5afe64a0ed9 | [
"Apache-2.0"
] | null | null | null | 25.083333 | 48 | 0.827243 | 996,949 | package com.aegean.icsd.engine.core.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Key {
}
|
9234896e21f4f444e31a74e97ccbd98ded15fcd2 | 2,589 | java | Java | acceptance-tests/src/test/java/tech/pegasys/pantheon/tests/web3j/privacy/PrivacyGroupIdAcceptanceTest.java | alessandro-8/panth | fc6afda6230f9b42996b976fd051682e81e19792 | [
"Apache-2.0"
] | null | null | null | acceptance-tests/src/test/java/tech/pegasys/pantheon/tests/web3j/privacy/PrivacyGroupIdAcceptanceTest.java | alessandro-8/panth | fc6afda6230f9b42996b976fd051682e81e19792 | [
"Apache-2.0"
] | null | null | null | acceptance-tests/src/test/java/tech/pegasys/pantheon/tests/web3j/privacy/PrivacyGroupIdAcceptanceTest.java | alessandro-8/panth | fc6afda6230f9b42996b976fd051682e81e19792 | [
"Apache-2.0"
] | null | null | null | 35.958333 | 118 | 0.702202 | 996,950 | /*
* Copyright 2019 ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package tech.pegasys.pantheon.tests.web3j.privacy;
import tech.pegasys.pantheon.enclave.Enclave;
import tech.pegasys.pantheon.enclave.types.CreatePrivacyGroupRequest;
import tech.pegasys.pantheon.enclave.types.PrivacyGroup;
import tech.pegasys.pantheon.tests.acceptance.dsl.privacy.PrivacyAcceptanceTestBase;
import tech.pegasys.pantheon.tests.acceptance.dsl.privacy.PrivacyNet;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class PrivacyGroupIdAcceptanceTest extends PrivacyAcceptanceTestBase {
private static final String CONTRACT_NAME = "Event Emmiter";
private EventEmitterHarness eventEmitterHarness;
private PrivacyGroup privacyGroup;
@Before
public void setUp() throws Exception {
PrivacyNet privacyNet =
PrivacyNet.builder(privacy, privacyPantheon, cluster, false)
.addMinerNode("Alice")
.addMinerNode("Bob")
.addMinerNode("Charlie")
.build();
privacyNet.startPrivacyNet();
Enclave enclave =
new Enclave(privacyNet.getNode("Alice").getPrivacyParameters().getEnclaveUri());
String[] addresses =
privacyNet.getNodes().values().stream()
.map(privacyNode -> privacyNode.orion.getPublicKeys())
.flatMap(List::stream)
.toArray(String[]::new);
this.privacyGroup =
enclave.createPrivacyGroup(
new CreatePrivacyGroupRequest(
addresses,
privacyNet.getNode("Alice").orion.getPublicKeys().get(0),
"testName",
"testDesc"));
eventEmitterHarness =
new EventEmitterHarness(
privateTransactionBuilder,
privacyNet,
privateTransactions,
privateTransactionVerifier,
eea);
}
@Test
public void nodeCanDeployWithPrivacyGroupId() {
eventEmitterHarness.deployWithPrivacyGroup(
CONTRACT_NAME, "Alice", privacyGroup.getPrivacyGroupId(), "Alice", "Bob", "Charlie");
}
}
|
92348a59449b033e325792a9e5b4b85338dc4b0a | 10,145 | java | Java | app/src/main/java/com/anysoftkeyboard/keyboards/views/preview/KeyPreviewsManager.java | antonok-edm/AnySoftKeyboard | a6ad08502eb6823de592d77d09b8a5692c2c6361 | [
"Apache-2.0"
] | 3 | 2019-12-06T06:34:45.000Z | 2021-10-09T12:31:22.000Z | app/src/main/java/com/anysoftkeyboard/keyboards/views/preview/KeyPreviewsManager.java | antonok-edm/AnySoftKeyboard | a6ad08502eb6823de592d77d09b8a5692c2c6361 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/anysoftkeyboard/keyboards/views/preview/KeyPreviewsManager.java | antonok-edm/AnySoftKeyboard | a6ad08502eb6823de592d77d09b8a5692c2c6361 | [
"Apache-2.0"
] | null | null | null | 40.418327 | 180 | 0.651355 | 996,951 | package com.anysoftkeyboard.keyboards.views.preview;
import android.content.Context;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import com.anysoftkeyboard.api.KeyCodes;
import com.anysoftkeyboard.base.utils.Logger;
import com.anysoftkeyboard.keyboards.Keyboard;
import com.anysoftkeyboard.keyboards.views.AnyKeyboardViewBase;
import com.anysoftkeyboard.prefs.AnimationsLevel;
import com.menny.android.anysoftkeyboard.AnyApplication;
import com.menny.android.anysoftkeyboard.R;
import junit.framework.Assert;
import java.lang.ref.WeakReference;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import io.reactivex.disposables.CompositeDisposable;
public class KeyPreviewsManager implements KeyPreviewsController {
private static final String TAG = "ASK_PPM";
private static final KeyPreview NULL_KEY_PREVIEW = new KeyPreview() {
@Override
public void showPreviewForKey(Keyboard.Key key, CharSequence label, Point previewPosition) {
}
@Override
public void showPreviewForKey(Keyboard.Key key, Drawable icon, Point previewPosition) {
}
@Override
public void dismiss() {
}
};
private final CompositeDisposable mDisposables = new CompositeDisposable();
private int mMaxPopupInstances;
private final PreviewPopupTheme mPreviewPopupTheme;
private final Queue<KeyPreview> mFreeKeyPreviews = new ArrayDeque<>();
private final Queue<KeyPreview> mActiveKeyPreviews = new ArrayDeque<>();
private final Map<Keyboard.Key, KeyPreview> mActivePopupByKeyMap = new HashMap<>();
private final Context mContext;
private final AnyKeyboardViewBase mKeyboardView;
private final UIHandler mUiHandler;
private boolean mAnimationsEnabled;
private boolean mShowPreview;
private PositionCalculator mPositionCalculator;
public KeyPreviewsManager(@NonNull Context context, @NonNull AnyKeyboardViewBase keyboardView, @NonNull PreviewPopupTheme previewPopupTheme) {
mPreviewPopupTheme = previewPopupTheme;
mContext = context;
mKeyboardView = keyboardView;
mUiHandler = new UIHandler(this, context.getResources().getInteger(R.integer.preview_dismiss_delay));
mDisposables.add(AnyApplication.prefs(context).getString(R.string.settings_key_key_press_preview_popup_position, R.string.settings_default_key_press_preview_popup_position)
.asObservable().map("above_key"::equals).subscribe(value -> {
cancelAllPreviews();
mMaxPopupInstances = value ? context.getResources().getInteger(R.integer.maximum_instances_of_preview_popups) : 1;
mPositionCalculator = value ? new AboveKeyPositionCalculator() : new AboveKeyboardPositionCalculator();
}));
mDisposables.add(AnyApplication.prefs(context).getBoolean(R.string.settings_key_key_press_shows_preview_popup, R.bool.settings_default_key_press_shows_preview_popup)
.asObservable().subscribe(value -> {
cancelAllPreviews();
mShowPreview = value;
}));
mDisposables.add(AnimationsLevel.createPrefsObservable(context).subscribe(value -> {
cancelAllPreviews();
mAnimationsEnabled = AnimationsLevel.None != value;
}));
}
@Override
public void hidePreviewForKey(Keyboard.Key key) {
if (isEnabled()) mUiHandler.dismissPreview(key);
}
private boolean isEnabled() {
return mShowPreview && mAnimationsEnabled;
}
@Override
public void showPreviewForKey(Keyboard.Key key, Drawable icon) {
if (isEnabled()) {
KeyPreview popup = getPopupForKey(key);
Point previewPosition = mPositionCalculator.calculatePositionForPreview(key, mKeyboardView, mPreviewPopupTheme, mKeyboardView.getLocationInWindow());
popup.showPreviewForKey(key, icon, previewPosition);
}
}
@Override
public void showPreviewForKey(Keyboard.Key key, CharSequence label) {
if (isEnabled()) {
KeyPreview popup = getPopupForKey(key);
Point previewPosition = mPositionCalculator.calculatePositionForPreview(key, mKeyboardView, mPreviewPopupTheme, mKeyboardView.getLocationInWindow());
popup.showPreviewForKey(key, label, previewPosition);
}
}
@NonNull
private KeyPreview getPopupForKey(Keyboard.Key key) {
mUiHandler.cancelDismissForKey(key);
if (shouldNotShowPreview(key)) return NULL_KEY_PREVIEW;
if (!mActivePopupByKeyMap.containsKey(key)) {
//the key is not active.
//we have several options how to fetch a popup
//1) fetch the head from the free queue: if the queue size is not empty
if (!mFreeKeyPreviews.isEmpty()) {
//removing from the head
KeyPreview keyPreview = mFreeKeyPreviews.remove();
mActivePopupByKeyMap.put(key, keyPreview);
mActiveKeyPreviews.add(keyPreview);
} else {
//we do not have unused popups, we'll need to reuse one of the actives
//2) if queue size is not the maximum, then create a new one
if (mActiveKeyPreviews.size() < mMaxPopupInstances) {
KeyPreview keyPreview = new KeyPreviewPopupWindow(mContext, mKeyboardView, mPreviewPopupTheme);
mActivePopupByKeyMap.put(key, keyPreview);
mActiveKeyPreviews.add(keyPreview);
} else {
//3) we need to reused a currently active preview
KeyPreview keyPreview = mActiveKeyPreviews.remove();
//de-associating the old key with the popup
Keyboard.Key oldKey = null;
for (Map.Entry<Keyboard.Key, KeyPreview> pair : mActivePopupByKeyMap.entrySet()) {
if (pair.getValue() == keyPreview) {
oldKey = pair.getKey();
break;
}
}
Assert.assertNotNull(oldKey);
mActivePopupByKeyMap.remove(oldKey);
mActivePopupByKeyMap.put(key, keyPreview);
mActiveKeyPreviews.add(keyPreview);
}
}
}
return mActivePopupByKeyMap.get(key);
}
private boolean shouldNotShowPreview(Keyboard.Key key) {
return key == null ||//no key, no preview
key.modifier ||//modifiers should not preview (that's just weird)
(!key.showPreview) ||//maybe the layout author doesn't want us to preview
key.getCodesCount() == 0 ||//no key output, no preview
(key.getCodesCount() == 1 && isKeyCodeShouldNotBeShown(key.getPrimaryCode())) ||
mPreviewPopupTheme.getPreviewKeyTextSize() <= 0;
}
private boolean isKeyCodeShouldNotBeShown(int code) {
return code <= 0 || code == KeyCodes.ENTER || code == KeyCodes.SPACE;
}
@Override
public void cancelAllPreviews() {
mUiHandler.cancelAllMessages();
for (KeyPreview keyPreview : mActiveKeyPreviews) {
keyPreview.dismiss();
mFreeKeyPreviews.add(keyPreview);
}
mActiveKeyPreviews.clear();
mActivePopupByKeyMap.clear();
}
@Override
public void resetTheme() {
cancelAllPreviews();
mFreeKeyPreviews.clear();
}
@Override
public void destroy() {
mDisposables.dispose();
resetTheme();
mShowPreview = false;
}
@VisibleForTesting
PositionCalculator getPositionCalculator() {
return mPositionCalculator;
}
private static class UIHandler extends Handler {
private final WeakReference<KeyPreviewsManager> mPopupManagerWeakReference;
private static final int MSG_DISMISS_PREVIEW = R.id.popup_manager_dismiss_preview_message_id;
private final long mDelayBeforeDismiss;
UIHandler(KeyPreviewsManager popupManager, long delayBeforeDismiss) {
mDelayBeforeDismiss = delayBeforeDismiss;
mPopupManagerWeakReference = new WeakReference<>(popupManager);
}
@Override
public void handleMessage(Message msg) {
KeyPreviewsManager popupManager = mPopupManagerWeakReference.get();
if (popupManager != null && popupManager.isEnabled()) {
switch (msg.what) {
case MSG_DISMISS_PREVIEW:
popupManager.internalDismissPopupForKey((Keyboard.Key) msg.obj);
break;
default:
super.handleMessage(msg);
break;
}
}
}
void cancelAllMessages() {
removeMessages(MSG_DISMISS_PREVIEW);
}
void dismissPreview(Keyboard.Key key) {
cancelDismissForKey(key);
sendMessageDelayed(obtainMessage(MSG_DISMISS_PREVIEW, key), mDelayBeforeDismiss);
}
void cancelDismissForKey(Keyboard.Key key) {
removeMessages(MSG_DISMISS_PREVIEW, key);
}
}
private void internalDismissPopupForKey(Keyboard.Key key) {
if (shouldNotShowPreview(key) || !mActivePopupByKeyMap.containsKey(key)) return;
KeyPreview popup = mActivePopupByKeyMap.get(key);
try {
popup.dismiss();
} catch (IllegalArgumentException e) {
Logger.w(TAG, e, "Failed to dismiss popup, probably the view is gone already.");
} finally {
Assert.assertSame(popup, mActivePopupByKeyMap.remove(key));
Assert.assertTrue(mFreeKeyPreviews.add(popup));
Assert.assertTrue(mActiveKeyPreviews.remove(popup));
}
}
}
|
92348a8bceda13d040d0f33479c2739ff3f5b051 | 1,215 | java | Java | third_party/java/proguard/proguard6.2.2/src/proguard/io/Finisher.java | chadm-sq/bazel | 715c9faabba573501c9cb7604192759950633205 | [
"Apache-2.0"
] | 16,989 | 2015-09-01T19:57:15.000Z | 2022-03-31T23:54:00.000Z | third_party/java/proguard/proguard6.2.2/src/proguard/io/Finisher.java | chadm-sq/bazel | 715c9faabba573501c9cb7604192759950633205 | [
"Apache-2.0"
] | 12,562 | 2015-09-01T09:06:01.000Z | 2022-03-31T22:26:20.000Z | third_party/java/proguard/proguard6.2.2/src/proguard/io/Finisher.java | chadm-sq/bazel | 715c9faabba573501c9cb7604192759950633205 | [
"Apache-2.0"
] | 3,707 | 2015-09-02T19:20:01.000Z | 2022-03-31T17:06:14.000Z | 31.973684 | 80 | 0.72428 | 996,952 | /*
* ProGuard -- shrinking, optimization, obfuscation, and preverification
* of Java bytecode.
*
* Copyright (c) 2002-2019 Guardsquare NV
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package proguard.io;
import java.io.IOException;
/**
* This interface specifies a listener that is called to finish an output stream
* before it is closed.
*
* @author Eric Lafortune
*/
public interface Finisher
{
/**
* Finishes an output stream right before it is closed.
*/
public void finish() throws IOException;
}
|
92348b395b38b255ed5e722a6314c169778664b0 | 1,229 | java | Java | jeecg-boot/jeecg-boot-module-activiti/src/main/java/org/jeecg/modules/es/entity/Entry.java | cnetly/activiti-jeecg-boot | 4fc0a31cba3bf2a4fc65e9df3f4a2b8882d6f75a | [
"MIT"
] | 92 | 2021-11-08T16:00:45.000Z | 2022-03-25T06:59:07.000Z | jeecg-boot/jeecg-boot-module-activiti/src/main/java/org/jeecg/modules/es/entity/Entry.java | cnetly/activiti-jeecg-boot | 4fc0a31cba3bf2a4fc65e9df3f4a2b8882d6f75a | [
"MIT"
] | 5 | 2021-11-22T07:38:57.000Z | 2022-03-11T04:33:43.000Z | jeecg-boot/jeecg-boot-module-activiti/src/main/java/org/jeecg/modules/es/entity/Entry.java | cnetly/activiti-jeecg-boot | 4fc0a31cba3bf2a4fc65e9df3f4a2b8882d6f75a | [
"MIT"
] | 19 | 2021-11-23T10:52:26.000Z | 2022-03-25T07:32:00.000Z | 13.505495 | 71 | 0.561432 | 996,953 | package org.jeecg.modules.es.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.Date;
/**
* Entry
*
* @author dongjb
* @version v1.0
* @since 2021-09-04
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Entry implements Serializable {
private static final long serialVersionUID = -8076851446078143653L;
/**
* 主键
*/
private String entryId;
/**
* 词条标题
*/
private String entryTitle;
/**
* 词条简介
*/
private String entryDesc;
/**
* 图片。多个以逗号分隔
*/
private String imgIds;
/**
* 类型
*/
private String entryType;
/**
* 状态:在用1,失效0
*/
private String entryStatus;
/**
* 关键字。多个以逗号分隔
*/
private String keyword;
/**
* 权重(数字)
*/
private Integer weight;
/**
* 创建人
*/
private String createStaffId;
/**
* 创建时间
*/
private Date createTime;
/**
* 更新人
*/
private String updateStaffId;
/**
* 更新时间
*/
private Date updateTime;
/**
* 备注
*/
private String remark;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.