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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
922efa12f4386203782b1971ff61aef378047f18 | 393 | java | Java | src/main/java/dev/mylesmor/sudosigns/listeners/PlayerListener.java | lazerl0rd/SudoSigns | f639046274eb241c80efd811747c8a719a105267 | [
"MIT"
] | 1 | 2021-04-22T06:34:22.000Z | 2021-04-22T06:34:22.000Z | src/main/java/dev/mylesmor/sudosigns/listeners/PlayerListener.java | lazerl0rd/SudoSigns | f639046274eb241c80efd811747c8a719a105267 | [
"MIT"
] | 4 | 2020-08-31T03:09:41.000Z | 2022-02-27T22:21:33.000Z | src/main/java/dev/mylesmor/sudosigns/listeners/PlayerListener.java | lazerl0rd/SudoSigns | f639046274eb241c80efd811747c8a719a105267 | [
"MIT"
] | 1 | 2021-12-14T16:16:21.000Z | 2021-12-14T16:16:21.000Z | 26.2 | 60 | 0.778626 | 994,947 | package dev.mylesmor.sudosigns.listeners;
import dev.mylesmor.sudosigns.SudoSigns;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent;
public class PlayerListener implements Listener {
@EventHandler
public void onPlayerQuit(PlayerQuitEvent e) {
SudoSigns.users.remove(e.getPlayer().getUniqueId());
}
}
|
922efb352014686b5357ad4294cb59e62c070934 | 1,619 | java | Java | StackAgent/src/cq/core/orm/BaseDao.java | chenqing24/StackAgent | 6f582e885c040b704eb32d975b7ac7e95aba0acd | [
"Apache-2.0"
] | 1 | 2020-12-19T12:11:01.000Z | 2020-12-19T12:11:01.000Z | StackAgent/src/cq/core/orm/BaseDao.java | chenqing24/StackAgent | 6f582e885c040b704eb32d975b7ac7e95aba0acd | [
"Apache-2.0"
] | null | null | null | StackAgent/src/cq/core/orm/BaseDao.java | chenqing24/StackAgent | 6f582e885c040b704eb32d975b7ac7e95aba0acd | [
"Apache-2.0"
] | 1 | 2020-12-19T12:11:03.000Z | 2020-12-19T12:11:03.000Z | 21.315789 | 72 | 0.638889 | 994,948 | package cq.core.orm;
import java.sql.SQLException;
import java.util.List;
/**
*
* @author envkt@example.com
*/
public abstract class BaseDao implements Dao {
/* (non-Javadoc)
* @see cq.core.orm.Dao#save(java.lang.String)
*/
@Override
public Long save(String sql) throws SQLException {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see cq.core.orm.Dao#delete(java.lang.Long)
*/
@Override
public int delete(Long id) throws SQLException {
// TODO Auto-generated method stub
return 0;
}
/* (non-Javadoc)
* @see cq.core.orm.Dao#update(java.lang.Class)
*/
@Override
public int update(Class<?> clazz) throws SQLException {
// TODO Auto-generated method stub
return 0;
}
/* (non-Javadoc)
* @see cq.core.orm.Dao#get(java.lang.Long)
*/
@Override
public Object get(Long id) {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see cq.core.orm.Dao#find(java.lang.String, java.lang.Object[])
*/
@Override
public List<?> find(String sql, Object... params) {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see cq.core.orm.Dao#getTotal(java.lang.String, java.lang.Object[])
*/
@Override
public long getTotal(String sql, Object... params) {
// TODO Auto-generated method stub
return 0;
}
/* (non-Javadoc)
* @see cq.core.orm.Dao#selectByPage(int, int, java.lang.String)
*/
@Override
public List<?> selectByPage(int first, int size, String sql) {
// TODO Auto-generated method stub
return null;
}
}
|
922efb79ad5d0dacf2c0fe26b18a472dfb889dec | 781 | java | Java | test/src/test/java/no/nav/common/test/match/PredicateAsMatcher.java | navikt/common-java-modules | 67428a6422cc54723702b7f6df2d4a0d2eafb84d | [
"MIT"
] | 4 | 2019-08-15T19:14:10.000Z | 2021-08-05T09:21:41.000Z | test/src/test/java/no/nav/common/test/match/PredicateAsMatcher.java | navikt/common-java-modules | 67428a6422cc54723702b7f6df2d4a0d2eafb84d | [
"MIT"
] | 38 | 2019-06-19T07:56:15.000Z | 2022-03-28T08:19:33.000Z | test/src/test/java/no/nav/common/test/match/PredicateAsMatcher.java | navikt/common-java-modules | 67428a6422cc54723702b7f6df2d4a0d2eafb84d | [
"MIT"
] | null | null | null | 21.694444 | 75 | 0.704225 | 994,949 | package no.nav.common.test.match;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
import java.util.function.Predicate;
class PredicateAsMatcher<T> extends TypeSafeMatcher<T> {
private final String description;
private final Predicate<T> predicate;
PredicateAsMatcher(Predicate<T> predicate) {
this(predicate.getClass().getSimpleName(), predicate);
}
public PredicateAsMatcher(String description, Predicate<T> predicate) {
this.description = description;
this.predicate = predicate;
}
@Override
public void describeTo(Description desc) {
desc.appendText(this.description);
}
@Override
protected boolean matchesSafely(T item) {
return predicate.test(item);
}
} |
922efc334f3d6f6fd0aecd9dbf89995adb451899 | 525 | java | Java | application/use-cases/src/main/java/ro/ciprianradu/rentacar/usecases/registerrenter/RegisterRenterOutputPort.java | ciprian-radu/rent-a-car | 4bbe5f34e450f813e880bf8507c837d22648689c | [
"Apache-2.0"
] | 9 | 2019-09-08T13:50:10.000Z | 2020-10-06T15:09:15.000Z | application/use-cases/src/main/java/ro/ciprianradu/rentacar/usecases/registerrenter/RegisterRenterOutputPort.java | ciprian-radu/rent-a-car | 4bbe5f34e450f813e880bf8507c837d22648689c | [
"Apache-2.0"
] | 1 | 2021-01-15T15:22:02.000Z | 2021-01-15T15:57:28.000Z | application/use-cases/src/main/java/ro/ciprianradu/rentacar/usecases/registerrenter/RegisterRenterOutputPort.java | ciprian-radu/rent-a-car | 4bbe5f34e450f813e880bf8507c837d22648689c | [
"Apache-2.0"
] | 2 | 2020-05-10T03:09:08.000Z | 2020-10-10T09:03:56.000Z | 29.166667 | 99 | 0.733333 | 994,950 | package ro.ciprianradu.rentacar.usecases.registerrenter;
/**
* Defines the output interface exposed the {@link RegisterRenterUseCase}. It's the output boundary
* of mentioned use case.
*/
public interface RegisterRenterOutputPort {
/**
* Presents the result of the {@link RegisterRenterUseCase}
*
* @param registerRenterOutputData the output data of the {@link RegisterRenterUseCase} (cannot
* be <code>null</code>)
*/
void present(RegisterRenterOutputData registerRenterOutputData);
}
|
922efc62242ada2c65aa782ca567fdd2f8dd8933 | 1,327 | java | Java | ProjetoClinica_JavaFX/src/modelo/ModeloMedico.java | xaviergthiago/ProjetoClinica_JavaFX | d98b62d38a56a38f3d105e35fd0fceae8ae5ed03 | [
"MIT"
] | null | null | null | ProjetoClinica_JavaFX/src/modelo/ModeloMedico.java | xaviergthiago/ProjetoClinica_JavaFX | d98b62d38a56a38f3d105e35fd0fceae8ae5ed03 | [
"MIT"
] | null | null | null | ProjetoClinica_JavaFX/src/modelo/ModeloMedico.java | xaviergthiago/ProjetoClinica_JavaFX | d98b62d38a56a38f3d105e35fd0fceae8ae5ed03 | [
"MIT"
] | null | null | null | 17.693333 | 79 | 0.559156 | 994,951 | /*
* 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 modelo;
/**
*
* @author xavie
*/
public class ModeloMedico {
private int codigo;
private String nome;
private String especialidade;
private int crm;
/**
* @return the codigo
*/
public int getCodigo() {
return codigo;
}
/**
* @param codigo the codigo to set
*/
public void setCodigo(int codigo) {
this.codigo = codigo;
}
/**
* @return the nome
*/
public String getNome() {
return nome;
}
/**
* @param nome the nome to set
*/
public void setNome(String nome) {
this.nome = nome;
}
/**
* @return the especialidade
*/
public String getEspecialidade() {
return especialidade;
}
/**
* @param especialidade the especialidade to set
*/
public void setEspecialidade(String especialidade) {
this.especialidade = especialidade;
}
/**
* @return the crm
*/
public int getCrm() {
return crm;
}
/**
* @param crm the crm to set
*/
public void setCrm(int crm) {
this.crm = crm;
}
}
|
922efd37edbc1f62827e38a98f31ca53b7505748 | 326 | java | Java | src/main/java/yokohama/unit/ast_junit/BooleanLitExpr.java | tkob/yokohamaunit | 5e60b512153fbea81efdabc172afa2543a191224 | [
"MIT"
] | 1 | 2015-10-06T07:17:19.000Z | 2015-10-06T07:17:19.000Z | src/main/java/yokohama/unit/ast_junit/BooleanLitExpr.java | tkob/yokohamaunit | 5e60b512153fbea81efdabc172afa2543a191224 | [
"MIT"
] | null | null | null | src/main/java/yokohama/unit/ast_junit/BooleanLitExpr.java | tkob/yokohamaunit | 5e60b512153fbea81efdabc172afa2543a191224 | [
"MIT"
] | null | null | null | 18.111111 | 49 | 0.680982 | 994,952 | package yokohama.unit.ast_junit;
import lombok.Value;
@Value
public class BooleanLitExpr implements Expr {
private final boolean value;
public boolean getValue() {
return value;
}
@Override
public <T> T accept(ExprVisitor<T> visitor) {
return visitor.visitBooleanLitExpr(this);
}
}
|
922efd3983f74ffae220c73e47ea856a32d5dba8 | 241 | java | Java | src/main/java/br/com/baratella/aoplogexample/core/usecase/createperson/ICreatePerson.java | andersonbalves/AOPLogExample | 2abf95bf65843348d28324c2e837d4c1e042300c | [
"Apache-2.0"
] | null | null | null | src/main/java/br/com/baratella/aoplogexample/core/usecase/createperson/ICreatePerson.java | andersonbalves/AOPLogExample | 2abf95bf65843348d28324c2e837d4c1e042300c | [
"Apache-2.0"
] | null | null | null | src/main/java/br/com/baratella/aoplogexample/core/usecase/createperson/ICreatePerson.java | andersonbalves/AOPLogExample | 2abf95bf65843348d28324c2e837d4c1e042300c | [
"Apache-2.0"
] | null | null | null | 26.777778 | 91 | 0.842324 | 994,953 | package br.com.baratella.aoplogexample.core.usecase.createperson;
import br.com.baratella.aoplogexample.core.usecase.createperson.entity.CreatePersonRequest;
public interface ICreatePerson {
void execute(CreatePersonRequest request);
}
|
922efd9381e41f36115bddddda1e63e563ebfa77 | 5,556 | java | Java | src/test/java/io/zeebe/flakytestextractor/ExtendedTestSuiteXMLParserTest.java | M1chaCH/flaky-test-extractor-maven-plugin | eb5ff091db48c4fd1648f18e50cdec8a81653f75 | [
"Apache-2.0"
] | 5 | 2021-12-12T05:24:56.000Z | 2022-03-14T09:10:21.000Z | src/test/java/io/zeebe/flakytestextractor/ExtendedTestSuiteXMLParserTest.java | M1chaCH/flaky-test-extractor-maven-plugin | eb5ff091db48c4fd1648f18e50cdec8a81653f75 | [
"Apache-2.0"
] | 38 | 2020-08-14T10:05:35.000Z | 2022-03-14T09:15:13.000Z | src/test/java/io/zeebe/flakytestextractor/ExtendedTestSuiteXMLParserTest.java | M1chaCH/flaky-test-extractor-maven-plugin | eb5ff091db48c4fd1648f18e50cdec8a81653f75 | [
"Apache-2.0"
] | 1 | 2022-02-24T10:06:37.000Z | 2022-02-24T10:06:37.000Z | 42.412214 | 109 | 0.784737 | 994,954 | package io.zeebe.flakytestextractor;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import org.junit.Test;
import org.xml.sax.SAXException;
public class ExtendedTestSuiteXMLParserTest {
private static final ClassLoader CLASS_LOADER = Thread.currentThread().getContextClassLoader();
private final ExtendedTestSuiteXMLParser sut = new ExtendedTestSuiteXMLParser(new TestLogger());
@Test
public void testParseOutputOfPassingTest() throws ParserConfigurationException, SAXException, IOException {
try (InputStreamReader reader = getReaderForClassPathResource(
"surefire-reports/TEST-com.github.pihme.jenkinstestbed.module1.PassingTest.xml")) {
List<ExtendedReportTestSuite> testSuites = sut.parse(reader);
assertThat(testSuites).hasSize(1);
ExtendedReportTestSuite testSuite = testSuites.get(0);
assertThat(testSuite.getNumberOfTests()).isEqualTo(1);
assertThat(testSuite.getNumberOfFailures()).isEqualTo(0);
assertThat(testSuite.getNumberOfErrors()).isEqualTo(0);
}
}
@Test
public void testParseOutputOfFailingTest() throws ParserConfigurationException, SAXException, IOException {
try (InputStreamReader reader = getReaderForClassPathResource(
"surefire-reports/TEST-com.github.pihme.jenkinstestbed.module1.FailingTest.xml")) {
List<ExtendedReportTestSuite> testSuites = sut.parse(reader);
assertThat(testSuites).hasSize(1);
ExtendedReportTestSuite testSuite = testSuites.get(0);
assertThat(testSuite.getNumberOfTests()).isEqualTo(1);
assertThat(testSuite.getNumberOfFailures()).isEqualTo(1);
assertThat(testSuite.getNumberOfErrors()).isEqualTo(0);
assertThat(testSuite.getNumberOfFlakes()).isEqualTo(0);
ExtendedReportTestCase testCase = testSuite.getTestCases().get(0);
assertThat(testCase.isFlake()).isFalse();
assertThat(testCase.getSystemOut()).isEqualTo("Failing test\n");
}
}
@Test
public void testParseOutputOfErrorTest() throws ParserConfigurationException, SAXException, IOException {
try (InputStreamReader reader = getReaderForClassPathResource(
"surefire-reports/TEST-com.github.pihme.jenkinstestbed.module1.ErrorTest.xml")) {
List<ExtendedReportTestSuite> testSuites = sut.parse(reader);
assertThat(testSuites).hasSize(1);
ExtendedReportTestSuite testSuite = testSuites.get(0);
assertThat(testSuite.getNumberOfTests()).isEqualTo(1);
assertThat(testSuite.getNumberOfFailures()).isEqualTo(0);
assertThat(testSuite.getNumberOfErrors()).isEqualTo(1);
assertThat(testSuite.getNumberOfFlakes()).isEqualTo(0);
ExtendedReportTestCase testCase = testSuite.getTestCases().get(0);
assertThat(testCase.isFlake()).isFalse();
assertThat(testCase.getSystemOut()).isEqualTo("Error test\n");
}
}
@Test
public void testParseOutputOfFlakyTest() throws ParserConfigurationException, SAXException, IOException {
try (InputStreamReader reader = getReaderForClassPathResource(
"surefire-reports/TEST-com.github.pihme.jenkinstestbed.module1.FlakyTest.xml")) {
List<ExtendedReportTestSuite> testSuites = sut.parse(reader);
assertThat(testSuites).hasSize(1);
ExtendedReportTestSuite testSuite = testSuites.get(0);
assertThat(testSuite.getNumberOfTests()).isEqualTo(1);
assertThat(testSuite.getNumberOfFailures()).isEqualTo(0);
assertThat(testSuite.getNumberOfErrors()).isEqualTo(0);
assertThat(testSuite.getNumberOfFlakes()).isEqualTo(1);
ExtendedReportTestCase testCase = testSuite.getTestCases().get(0);
assertThat(testCase.isFlake()).isTrue();
assertThat(testCase.getClassName()).isEqualTo("FlakyTest");
assertThat(testCase.getFailureType()).isEqualTo("java.lang.AssertionError");
assertThat(testCase.getName()).isEqualTo("flakyTest");
assertThat(testCase.getFailureDetail()).isEqualTo("java.lang.AssertionError: failed\n"
+ "\tat com.github.pihme.jenkinstestbed.module1.FlakyTest.flakyTest(FlakyTest.java:16)\n");
assertThat(testCase.getSystemOut()).isEqualTo("Flaky test\n");
}
}
@Test
public void testParseOutputOfFlakyError() throws ParserConfigurationException, SAXException, IOException {
try (InputStreamReader reader = getReaderForClassPathResource(
"surefire-reports/TEST-com.github.pihme.jenkinstestbed.module1.FlakyErrorTest.xml")) {
List<ExtendedReportTestSuite> testSuites = sut.parse(reader);
assertThat(testSuites).hasSize(1);
ExtendedReportTestSuite testSuite = testSuites.get(0);
assertThat(testSuite.getNumberOfTests()).isEqualTo(1);
assertThat(testSuite.getNumberOfFailures()).isEqualTo(0);
assertThat(testSuite.getNumberOfErrors()).isEqualTo(0);
assertThat(testSuite.getNumberOfFlakes()).isEqualTo(1);
ExtendedReportTestCase testCase = testSuite.getTestCases().get(0);
assertThat(testCase.isFlake()).isTrue();
assertThat(testCase.getClassName()).isEqualTo("FlakyErrorTest");
assertThat(testCase.getFailureType()).isEqualTo("java.lang.RuntimeException");
assertThat(testCase.getName()).isEqualTo("failNever");
assertThat(testCase.getFailureDetail()).isEqualTo("java.lang.RuntimeException: Oops, something happeeed\n"
+ " at com.github.pihme.jenkinstestbed.module1.FlakyErrorTest.setUp(FlakyErrorTest.java:16)\n");
assertThat(testCase.getSystemOut()).isEqualTo("Flaky error\n");
}
}
private InputStreamReader getReaderForClassPathResource(String fileName) {
return new InputStreamReader(CLASS_LOADER.getResourceAsStream(fileName));
}
}
|
922efdad0fe28e173ae1ada4cad1bef29bdc8344 | 3,495 | java | Java | client-external/src/test/java/com/forcam/na/ffwebservices/client/api/config/TestForceAPIModule.java | dalbrx-forcam/java-sdk | c32a0f9b2c884fa0b2caa8c95577bd9cebd91fee | [
"MIT"
] | null | null | null | client-external/src/test/java/com/forcam/na/ffwebservices/client/api/config/TestForceAPIModule.java | dalbrx-forcam/java-sdk | c32a0f9b2c884fa0b2caa8c95577bd9cebd91fee | [
"MIT"
] | null | null | null | client-external/src/test/java/com/forcam/na/ffwebservices/client/api/config/TestForceAPIModule.java | dalbrx-forcam/java-sdk | c32a0f9b2c884fa0b2caa8c95577bd9cebd91fee | [
"MIT"
] | 2 | 2020-11-13T18:59:10.000Z | 2020-11-13T19:20:25.000Z | 34.60396 | 102 | 0.602861 | 994,955 | ////////////////////////////////////////////////////////////////////////////////
//
// Created by MJesser on 24.10.2017.
//
// Copyright (c) 2006 - 2017 FORCAM GmbH. All rights reserved.
////////////////////////////////////////////////////////////////////////////////
package com.forcam.na.ffwebservices.client.api.config;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.forcam.na.ffwebservices.client.BridgeAPI;
import dagger.Module;
import dagger.Provides;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import okhttp3.mockwebserver.MockWebServer;
import org.mockito.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
import javax.inject.Singleton;
import java.util.concurrent.TimeUnit;
/**
* The test Force API module.
*/
@Module
public class TestForceAPIModule {
// ------------------------------------------------------------------------
// constants
// ------------------------------------------------------------------------
/** Logger for class. */
private static final Logger LOGGER = LoggerFactory.getLogger(TestForceAPIModule.class);
private static final HttpLoggingInterceptor.Logger LOGGER_FUNCTION = msg -> {
if (BridgeAPI.LOGGER.isTraceEnabled()) {
LOGGER.trace(msg);
} else if (BridgeAPI.LOGGER.isDebugEnabled()) {
LOGGER.debug(msg);
} else if (BridgeAPI.LOGGER.isInfoEnabled()) {
LOGGER.info(msg);
} else {
LOGGER.warn(msg);
}
};
// ------------------------------------------------------------------------
// methods
// ------------------------------------------------------------------------
@Provides
@Singleton
public ObjectMapper objectMapper() {
final ObjectMapper mapper = new ObjectMapper();
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.registerModule(new JavaTimeModule());
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return mapper;
}
@Provides
@Singleton
public Retrofit retrofit(MockWebServer mockWebServer, ObjectMapper mapper) {
final HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(LOGGER_FUNCTION);
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(100, TimeUnit.MILLISECONDS)
.connectTimeout(100, TimeUnit.MILLISECONDS)
.addInterceptor(loggingInterceptor)
.build();
return new Retrofit.Builder()
.baseUrl(mockWebServer
.url("")
.toString())
.client(okHttpClient)
.addConverterFactory(JacksonConverterFactory.create(mapper))
.build();
}
@Provides
@Singleton
public MockWebServer mockWebServer() {
return new MockWebServer();
}
@Provides
OkHttpClient httpClient() {
return Mockito.mock(OkHttpClient.class);
}
} |
922efea138cd65824f55a4c54d59d1e39ab1ffd2 | 90 | java | Java | core-backend/src/main/java/com/exaz/hack2019/konsulta/constant/CaseRecordStatus.java | jenoosia/hack2019 | 5e355c7056cfd95dc1d37b454fbe6ba4ad8ccf21 | [
"MIT"
] | 1 | 2019-10-04T02:51:52.000Z | 2019-10-04T02:51:52.000Z | core-backend/src/main/java/com/exaz/hack2019/konsulta/constant/CaseRecordStatus.java | jenoosia/hack2019 | 5e355c7056cfd95dc1d37b454fbe6ba4ad8ccf21 | [
"MIT"
] | null | null | null | core-backend/src/main/java/com/exaz/hack2019/konsulta/constant/CaseRecordStatus.java | jenoosia/hack2019 | 5e355c7056cfd95dc1d37b454fbe6ba4ad8ccf21 | [
"MIT"
] | 1 | 2019-10-07T02:20:11.000Z | 2019-10-07T02:20:11.000Z | 15 | 44 | 0.777778 | 994,956 | package com.exaz.hack2019.konsulta.constant;
public enum CaseRecordStatus {
Active
}
|
922eff5c2dac86a497c7adf3c133d4fa4537bf61 | 1,119 | java | Java | orchextrasdk/src/main/java/com/gigigo/orchextra/sdk/features/GooglePlayServicesFeature.java | nuborisar/oxCustomNewReleaseNuboGit | e4b101a138e55e6894f453f75b5bfccc45710d08 | [
"Apache-2.0"
] | null | null | null | orchextrasdk/src/main/java/com/gigigo/orchextra/sdk/features/GooglePlayServicesFeature.java | nuborisar/oxCustomNewReleaseNuboGit | e4b101a138e55e6894f453f75b5bfccc45710d08 | [
"Apache-2.0"
] | null | null | null | orchextrasdk/src/main/java/com/gigigo/orchextra/sdk/features/GooglePlayServicesFeature.java | nuborisar/oxCustomNewReleaseNuboGit | e4b101a138e55e6894f453f75b5bfccc45710d08 | [
"Apache-2.0"
] | null | null | null | 31.971429 | 106 | 0.771224 | 994,957 | /*
* Created by Orchextra
*
* Copyright (C) 2016 Gigigo Mobile Services SL
*
* 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.gigigo.orchextra.sdk.features;
import com.gigigo.orchextra.domain.initalization.features.Feature;
import com.gigigo.orchextra.domain.abstractions.initialization.features.FeatureType;
public class GooglePlayServicesFeature extends Feature {
public GooglePlayServicesFeature(int status) {
super(FeatureType.GOOGLE_PLAY_SERVICES, GooglePlayServicesStatus.getGooglePlayServicesStatus(status));
}
@Override public boolean isSuccess() {
return false;
}
}
|
922f00d1e0c59dc729813602f9eaf03a2828e3a7 | 3,110 | java | Java | entity-view/impl/src/main/java/com/blazebit/persistence/view/impl/metamodel/EntityViewRootMappingImpl.java | sullrich84/blaze-persistence | f5a374fedf8cb1a24c769e37de56bd44e91afcf3 | [
"ECL-2.0",
"Apache-2.0"
] | 884 | 2015-02-17T16:29:05.000Z | 2022-03-31T05:01:09.000Z | entity-view/impl/src/main/java/com/blazebit/persistence/view/impl/metamodel/EntityViewRootMappingImpl.java | sullrich84/blaze-persistence | f5a374fedf8cb1a24c769e37de56bd44e91afcf3 | [
"ECL-2.0",
"Apache-2.0"
] | 1,105 | 2015-01-07T08:49:17.000Z | 2022-03-31T09:40:50.000Z | entity-view/impl/src/main/java/com/blazebit/persistence/view/impl/metamodel/EntityViewRootMappingImpl.java | sullrich84/blaze-persistence | f5a374fedf8cb1a24c769e37de56bd44e91afcf3 | [
"ECL-2.0",
"Apache-2.0"
] | 66 | 2015-03-12T16:43:39.000Z | 2022-03-22T06:55:15.000Z | 29.339623 | 300 | 0.712219 | 994,958 | /*
* Copyright 2014 - 2021 Blazebit.
*
* 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.blazebit.persistence.view.impl.metamodel;
import com.blazebit.persistence.JoinType;
import com.blazebit.persistence.view.CorrelationProvider;
import com.blazebit.persistence.view.spi.EntityViewRootMapping;
import java.util.List;
/**
*
* @author Christian Beikov
* @since 1.6.0
*/
public class EntityViewRootMappingImpl implements EntityViewRootMapping {
private final String name;
private final Class<?> managedTypeClass;
private final String joinExpression;
private final Class<? extends CorrelationProvider> correlationProvider;
private final String conditionExpression;
private final JoinType joinType;
private final String[] fetches;
private final List<String> orderByItems;
private final String limitExpression;
private final String offsetExpression;
public EntityViewRootMappingImpl(String name, Class<?> managedTypeClass, String joinExpression, Class<? extends CorrelationProvider> correlationProvider, String conditionExpression, JoinType joinType, String[] fetches, List<String> orderByItems, String limitExpression, String offsetExpression) {
this.name = name;
this.managedTypeClass = managedTypeClass;
this.joinExpression = joinExpression;
this.correlationProvider = correlationProvider;
this.conditionExpression = conditionExpression;
this.joinType = joinType;
this.fetches = fetches;
this.orderByItems = orderByItems;
this.limitExpression = limitExpression;
this.offsetExpression = offsetExpression;
}
@Override
public String getName() {
return name;
}
@Override
public Class<?> getManagedTypeClass() {
return managedTypeClass;
}
@Override
public String getJoinExpression() {
return joinExpression;
}
@Override
public Class<? extends CorrelationProvider> getCorrelationProvider() {
return correlationProvider;
}
@Override
public String getConditionExpression() {
return conditionExpression;
}
@Override
public JoinType getJoinType() {
return joinType;
}
@Override
public String[] getFetches() {
return fetches;
}
@Override
public List<String> getOrderByItems() {
return orderByItems;
}
@Override
public String getLimitExpression() {
return limitExpression;
}
@Override
public String getOffsetExpression() {
return offsetExpression;
}
}
|
922f013bb39f857b061ee7153f291e4627141389 | 2,301 | java | Java | matos-android/src/main/java/android/net/NetworkTemplate.java | Orange-OpenSource/matos-profiles | fb27c246911437070052197aa3ef91f9aaac6fc3 | [
"Apache-2.0"
] | 4 | 2015-05-31T02:12:56.000Z | 2016-01-27T11:53:06.000Z | matos-android/src/main/java/android/net/NetworkTemplate.java | Orange-OpenSource/matos-profiles | fb27c246911437070052197aa3ef91f9aaac6fc3 | [
"Apache-2.0"
] | null | null | null | matos-android/src/main/java/android/net/NetworkTemplate.java | Orange-OpenSource/matos-profiles | fb27c246911437070052197aa3ef91f9aaac6fc3 | [
"Apache-2.0"
] | 5 | 2015-05-31T00:15:20.000Z | 2021-06-22T10:21:38.000Z | 25.566667 | 84 | 0.719252 | 994,959 | package android.net;
/*
* #%L
* Matos
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2010 - 2014 Orange SA
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
public class NetworkTemplate
implements android.os.Parcelable
{
// Fields
public static final int MATCH_MOBILE_ALL = 1;
public static final int MATCH_MOBILE_3G_LOWER = 2;
public static final int MATCH_MOBILE_4G = 3;
public static final int MATCH_WIFI = 4;
public static final int MATCH_ETHERNET = 5;
public static final android.os.Parcelable.Creator<NetworkTemplate> CREATOR = null;
// Constructors
public NetworkTemplate(int arg1, java.lang.String arg2){
}
private NetworkTemplate(android.os.Parcel arg1){
}
// Methods
public boolean equals(java.lang.Object arg1){
return false;
}
public java.lang.String toString(){
return (java.lang.String) null;
}
public int hashCode(){
return 0;
}
public boolean matches(NetworkIdentity arg1){
return false;
}
public void writeToParcel(android.os.Parcel arg1, int arg2){
}
public int describeContents(){
return 0;
}
public java.lang.String getSubscriberId(){
return (java.lang.String) null;
}
public static NetworkTemplate buildTemplateMobileAll(java.lang.String arg1){
return (NetworkTemplate) null;
}
public static NetworkTemplate buildTemplateMobile3gLower(java.lang.String arg1){
return (NetworkTemplate) null;
}
public static NetworkTemplate buildTemplateMobile4g(java.lang.String arg1){
return (NetworkTemplate) null;
}
public static NetworkTemplate buildTemplateWifi(){
return (NetworkTemplate) null;
}
public static NetworkTemplate buildTemplateEthernet(){
return (NetworkTemplate) null;
}
public int getMatchRule(){
return 0;
}
}
|
922f0159b268fc5ade2fbbda5c8151886e040344 | 1,508 | java | Java | src/test/java/com/cschar/pmode3/SmokeJUnit4Test.java | cschar/power-mode-zeranthium | 4fa56a12e7f4cb729e62067b813ba871139a568e | [
"Apache-2.0"
] | 5 | 2020-07-16T18:26:58.000Z | 2021-07-23T12:33:00.000Z | src/test/java/com/cschar/pmode3/SmokeJUnit4Test.java | cschar/power-mode-zeranthium | 4fa56a12e7f4cb729e62067b813ba871139a568e | [
"Apache-2.0"
] | 2 | 2020-07-05T19:32:48.000Z | 2021-07-17T16:57:08.000Z | src/test/java/com/cschar/pmode3/SmokeJUnit4Test.java | cschar/power-mode-zeranthium | 4fa56a12e7f4cb729e62067b813ba871139a568e | [
"Apache-2.0"
] | 1 | 2020-07-16T18:26:59.000Z | 2020-07-16T18:26:59.000Z | 31.416667 | 90 | 0.68435 | 994,960 | package com.cschar.pmode3;
import static org.junit.Assert.assertEquals;
import com.intellij.configurationStore.XmlSerializer;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.List;
//Dummy test for pipeline
public class SmokeJUnit4Test {
@Test
public void testAdd() {
assertEquals(42, Integer.sum(19, 23));
}
@Test
public void deserializeXml() throws IOException, JDOMException {
SAXBuilder saxBuilder = new SAXBuilder();
String url = this.getClass().getClassLoader().getResource("").getPath();
File inputFile = new File("build/resources/test/save_config.xml");
Document document = saxBuilder.build(inputFile);
Element classElement = document.getRootElement();
List<Element> options = classElement.getChild("component").getChildren("option");
assertEquals(options.get(0).getAttribute("name").getValue(), "particleRGB");
assertEquals(options.get(0).getAttribute("value").getValue(), "-12566465");
// PowerMode3 pmode3Service = new PowerMode3();
// assertEquals(pmode3Service.getParticleRGB(), 0);
//
// XmlSerializer.deserializeAndLoadState(pmode3Service, classElement);
//
// assertEquals(-12566465, pmode3Service.getParticleRGB());
assertEquals(true,true);
}
} |
922f0173268ec83f83537d700b11f178e6ba3f30 | 2,919 | java | Java | components/extensions/appm-connector/org.wso2.carbon.appmgt.mdm.osgiconnector/src/main/java/org/wso2/carbon/appmgt/mdm/osgiconnector/mdmmgt/util/MDMServiceAPIUtils.java | hasuniea/carbon-device-mgt-plugins | a948a7d69a2e99d6dc1351ae18daf750145d0d32 | [
"Apache-2.0"
] | 9 | 2015-10-29T05:24:20.000Z | 2018-01-09T08:14:28.000Z | components/extensions/appm-connector/org.wso2.carbon.appmgt.mdm.osgiconnector/src/main/java/org/wso2/carbon/appmgt/mdm/osgiconnector/mdmmgt/util/MDMServiceAPIUtils.java | hasuniea/carbon-device-mgt-plugins | a948a7d69a2e99d6dc1351ae18daf750145d0d32 | [
"Apache-2.0"
] | 50 | 2015-08-04T06:06:51.000Z | 2022-01-10T16:17:16.000Z | components/extensions/appm-connector/org.wso2.carbon.appmgt.mdm.osgiconnector/src/main/java/org/wso2/carbon/appmgt/mdm/osgiconnector/mdmmgt/util/MDMServiceAPIUtils.java | hasuniea/carbon-device-mgt-plugins | a948a7d69a2e99d6dc1351ae18daf750145d0d32 | [
"Apache-2.0"
] | 170 | 2015-02-12T05:56:29.000Z | 2020-02-11T16:39:22.000Z | 38.92 | 93 | 0.749572 | 994,961 | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
/**
* MDMServiceAPIUtils class provides utility function.
*/
public class MDMServiceAPIUtils {
private static Log log = LogFactory.getLog(MDMServiceAPIUtils.class);
/**
* Returns the DeviceManagementProviderService osgi service.
*
* @param tenantId tenant id
* @return DeviceManagementProviderService
*/
public static DeviceManagementProviderService getDeviceManagementService(int tenantId) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ctx.setTenantId(tenantId, true);
DeviceManagementProviderService deviceManagementProviderService =
(DeviceManagementProviderService) ctx
.getOSGiService(DeviceManagementProviderService.class, null);
if (deviceManagementProviderService == null) {
String msg = "Device Management provider service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return deviceManagementProviderService;
}
/**
* Returns the ApplicationManagementProviderService osgi service.
*
* @param tenantId tenant id
* @return ApplicationManagementProviderService
*/
public static ApplicationManagementProviderService getAppManagementService(int tenantId) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ctx.setTenantId(tenantId, true);
ApplicationManagementProviderService applicationManagementProviderService =
(ApplicationManagementProviderService) ctx.
getOSGiService(
ApplicationManagementProviderService.class,
null);
if (applicationManagementProviderService == null) {
String msg = "Application management service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return applicationManagementProviderService;
}
}
|
922f0265dd3678d6f9e4da10b6df4059b92d225f | 1,932 | java | Java | src/main/java/org/openstreetmap/atlas/utilities/tuples/Either.java | Huyuntj/atlas | bb1545ed2da7a1d51f133a4bb686c064c63892eb | [
"BSD-3-Clause"
] | 188 | 2017-08-08T17:26:54.000Z | 2022-03-29T07:59:30.000Z | src/main/java/org/openstreetmap/atlas/utilities/tuples/Either.java | Huyuntj/atlas | bb1545ed2da7a1d51f133a4bb686c064c63892eb | [
"BSD-3-Clause"
] | 403 | 2017-08-09T16:15:25.000Z | 2022-02-16T19:33:42.000Z | src/main/java/org/openstreetmap/atlas/utilities/tuples/Either.java | Huyuntj/atlas | bb1545ed2da7a1d51f133a4bb686c064c63892eb | [
"BSD-3-Clause"
] | 79 | 2017-08-08T17:55:01.000Z | 2021-11-10T20:51:57.000Z | 23.851852 | 100 | 0.584369 | 994,962 | package org.openstreetmap.atlas.utilities.tuples;
import java.io.Serializable;
import java.util.function.Consumer;
/**
* Class that allows results to be one of two types. You can use the function like so: Either
* <String, Int>.left("Test").apply( left -> {System.out.println("String:" + left);}, right
* -> {System.out.println("Integer:" + right);} );
*
* @param <L>
* The type for the left value
* @param <R>
* The type for the right value
* @author cuthbertm
*/
public final class Either<L, R> implements Serializable
{
private static final long serialVersionUID = 158343315469036806L;
private final L left;
private final R right;
public static <L, R> Either<L, R> left(final L value)
{
return new Either<>(value, null);
}
public static <L, R> Either<L, R> right(final R value)
{
return new Either<>(null, value);
}
private Either(final L left, final R right)
{
this.left = left;
this.right = right;
}
/**
* Apply function that allows you to execute against the left or right values
*
* @param leftFunction
* The function to execute against the left value
* @param rightFunction
* The function to execute against the right value
*/
public void apply(final Consumer<? super L> leftFunction,
final Consumer<? super R> rightFunction)
{
if (this.left != null)
{
leftFunction.accept(this.left);
}
else if (this.right != null)
{
rightFunction.accept(this.right);
}
}
public L getLeft()
{
return this.left;
}
public R getRight()
{
return this.right;
}
public boolean isLeft()
{
return this.left != null;
}
public boolean isRight()
{
return this.right != null;
}
}
|
922f054b6448cc00a07530741afcf11066f79ad0 | 5,631 | java | Java | src/Controllers/EtudiantJpaController.java | nkaurelien/studentgrouper | a8b4e5eab961e819754657fe1582a2b977e1764f | [
"MIT"
] | null | null | null | src/Controllers/EtudiantJpaController.java | nkaurelien/studentgrouper | a8b4e5eab961e819754657fe1582a2b977e1764f | [
"MIT"
] | null | null | null | src/Controllers/EtudiantJpaController.java | nkaurelien/studentgrouper | a8b4e5eab961e819754657fe1582a2b977e1764f | [
"MIT"
] | null | null | null | 33.123529 | 112 | 0.559936 | 994,963 | /*
* 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 Controllers;
import Controllers.exceptions.NonexistentEntityException;
import entities.Etudiant;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entities.Groupe;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
/**
*
* @author Oracle
*/
public class EtudiantJpaController implements Serializable {
public EtudiantJpaController(EntityManagerFactory emf) {
this.emf = emf;
}
private EntityManagerFactory emf = null;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(Etudiant etudiant) {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Groupe groupe = etudiant.getGroupe();
if (groupe != null) {
groupe = em.getReference(groupe.getClass(), groupe.getId());
etudiant.setGroupe(groupe);
}
em.persist(etudiant);
if (groupe != null) {
groupe.getEtudiantList().add(etudiant);
groupe = em.merge(groupe);
}
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(Etudiant etudiant) throws NonexistentEntityException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Etudiant persistentEtudiant = em.find(Etudiant.class, etudiant.getId());
Groupe groupeOld = persistentEtudiant.getGroupe();
Groupe groupeNew = etudiant.getGroupe();
if (groupeNew != null) {
groupeNew = em.getReference(groupeNew.getClass(), groupeNew.getId());
etudiant.setGroupe(groupeNew);
}
etudiant = em.merge(etudiant);
if (groupeOld != null && !groupeOld.equals(groupeNew)) {
groupeOld.getEtudiantList().remove(etudiant);
groupeOld = em.merge(groupeOld);
}
if (groupeNew != null && !groupeNew.equals(groupeOld)) {
groupeNew.getEtudiantList().add(etudiant);
groupeNew = em.merge(groupeNew);
}
em.getTransaction().commit();
} catch (Exception ex) {
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Integer id = etudiant.getId();
if (findEtudiant(id) == null) {
throw new NonexistentEntityException("The etudiant with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void destroy(Integer id) throws NonexistentEntityException {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Etudiant etudiant;
try {
etudiant = em.getReference(Etudiant.class, id);
etudiant.getId();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The etudiant with id " + id + " no longer exists.", enfe);
}
Groupe groupe = etudiant.getGroupe();
if (groupe != null) {
groupe.getEtudiantList().remove(etudiant);
groupe = em.merge(groupe);
}
em.remove(etudiant);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
public List<Etudiant> findEtudiantEntities() {
return findEtudiantEntities(true, -1, -1);
}
public List<Etudiant> findEtudiantEntities(int maxResults, int firstResult) {
return findEtudiantEntities(false, maxResults, firstResult);
}
private List<Etudiant> findEtudiantEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Etudiant.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public Etudiant findEtudiant(Integer id) {
EntityManager em = getEntityManager();
try {
return em.find(Etudiant.class, id);
} finally {
em.close();
}
}
public int getEtudiantCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<Etudiant> rt = cq.from(Etudiant.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
}
|
922f0562ca7870f5c42cee46aa0092ea38f2f217 | 2,842 | java | Java | source/org/tigr/microarray/mev/script/scriptGUI/ScriptPropertiesChangeDialog.java | SamGG/mev | 72daf1eaf13d32cc6de45871bce09f943f856621 | [
"Artistic-2.0"
] | 1 | 2017-07-05T20:57:43.000Z | 2017-07-05T20:57:43.000Z | source/org/tigr/microarray/mev/script/scriptGUI/ScriptPropertiesChangeDialog.java | SamGG/mev-tm4 | 72daf1eaf13d32cc6de45871bce09f943f856621 | [
"Artistic-2.0"
] | null | null | null | source/org/tigr/microarray/mev/script/scriptGUI/ScriptPropertiesChangeDialog.java | SamGG/mev-tm4 | 72daf1eaf13d32cc6de45871bce09f943f856621 | [
"Artistic-2.0"
] | null | null | null | 31.577778 | 82 | 0.533427 | 994,964 | /*******************************************************************************
* Copyright (c) 1999-2005 The Institute for Genomic Research (TIGR).
* Copyright (c) 2005-2008, the Dana-Farber Cancer Institute (DFCI),
* J. Craig Venter Institute (JCVI) and the University of Washington.
* All rights reserved.
*******************************************************************************/
/*
* ScriptPropertiesChangeDialog.java
*
* Created on March 10, 2004, 5:18 PM
*/
package org.tigr.microarray.mev.script.scriptGUI;
import java.util.StringTokenizer;
import javax.swing.JFrame;
import javax.swing.JTable;
import org.tigr.microarray.mev.cluster.gui.impl.dialogs.AlgorithmDialog;
/**
*
* @author braisted
*/
public class ScriptPropertiesChangeDialog extends AlgorithmDialog {
JTable table;
boolean [] badData;
/** Creates a new instance of ScriptPropertiesChangeDialog */
public ScriptPropertiesChangeDialog(String [] lines) {
super(new JFrame(), "Value Editor", true);
String [][] data = new String[lines.length][2];
data = getKeyValuePairs(lines);
String [] header = new String[2];
header[0] = "Key";
header[1] = "Value";
table = new JTable(data, header);
// table = new ScriptAlgorithmPropertyViewer(header, data);
}
private String [][] getKeyValuePairs(String [] lines) {
String [][] data = new String[lines.length][2];
badData = new boolean[lines.length];
int cnt = 0;
for(int i = 0; i < lines.length; i++) {
data[cnt][0] = getKey(lines[i]);
data[cnt][1] = getValue(lines[i]);
}
return data;
}
private String getKey(String line) {
int pnt = line.indexOf("key");
StringTokenizer stok;
String str, val;
if(pnt > 0 && line.length() < pnt+4) {
str= line.substring(pnt);
stok = new StringTokenizer(str, "\"");
if(stok.countTokens() > 1){
stok.nextToken();
return stok.nextToken();
}
}
return null;
}
private String getValue(String line) {
int pnt = line.indexOf("value");
StringTokenizer stok;
String str, val;
if(pnt > 0 && line.length() < pnt+4) {
str= line.substring(pnt);
stok = new StringTokenizer(str, "\"");
if(stok.countTokens() > 1){
stok.nextToken();
return stok.nextToken();
}
}
return null;
}
/*
private class ScriptAlgorithmPropertyViewer extends TableViewer {
ScriptAlgorithmPropertyViewer(String [] header, String [][] data) {
super(header, data);
}
}
*/
}
|
922f0747c3aeb32b98ca79942b5bcad3fee30128 | 34,376 | java | Java | Frames/Fr_Cad_Paciente.java | GabiDeutner/LAZUL | 3a9d265ab8aa20f3cae25176c6c1916be54a7da0 | [
"MIT"
] | 3 | 2021-02-27T20:06:50.000Z | 2021-12-09T01:27:50.000Z | Frames/Fr_Cad_Paciente.java | GabiDeutner/LAZUL | 3a9d265ab8aa20f3cae25176c6c1916be54a7da0 | [
"MIT"
] | null | null | null | Frames/Fr_Cad_Paciente.java | GabiDeutner/LAZUL | 3a9d265ab8aa20f3cae25176c6c1916be54a7da0 | [
"MIT"
] | null | null | null | 45.712766 | 203 | 0.569176 | 994,965 | package Frames;
import Objeto.Objeto_Paciente;
import Objeto.Objeto_Sexo;
import Objeto.Objeto_EstadoCivil;
import BancoDado.BD_Paciente;
import BancoDado.BD_Sexo;
import BancoDado.BD_EstadoCivil;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
public class Fr_Cad_Paciente extends javax.swing.JFrame {
private BD_Paciente bd_paciente = new BD_Paciente ();
private ArrayList<Objeto_Paciente> ListaPaciente = new ArrayList();
private Objeto_Paciente RegistroPaciente = new Objeto_Paciente ();
private BD_Sexo bd_sexo = new BD_Sexo ();
private ArrayList<Objeto_Sexo> ListaSexo = new ArrayList();
private BD_EstadoCivil bd_estadocivil = new BD_EstadoCivil ();
private ArrayList<Objeto_EstadoCivil> ListaEstadoCivil = new ArrayList();
private String Operacao;
public Fr_Cad_Paciente() {
initComponents();
try {
CargaTabela ();
CargaListaSexo();
CargaListaEstadoCivil();
CargaComboBoxSexo ();
CargaComboBoxEstadoCivil ();
Desabilita ();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Erro Carga Grid/Combobox \n"+ex.getMessage(), "ERRO", JOptionPane.ERROR_MESSAGE);
}
Operacao="";
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
tb_paciente = new javax.swing.JTable();
lb_codigo = new javax.swing.JLabel();
lb_nome = new javax.swing.JLabel();
lb_ddd = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
lb_telefone = new javax.swing.JLabel();
lb_dtnasc = new javax.swing.JLabel();
lb_cpf = new javax.swing.JLabel();
lb_rg = new javax.swing.JLabel();
lb_sexo = new javax.swing.JLabel();
lb_estadocivil = new javax.swing.JLabel();
tf_codigo = new javax.swing.JTextField();
tf_nome = new javax.swing.JTextField();
tf_ddd = new javax.swing.JTextField();
tf_telefone = new javax.swing.JTextField();
tf_dtnasc = new javax.swing.JTextField();
tf_cpf = new javax.swing.JTextField();
tf_rg = new javax.swing.JTextField();
cb_sexo = new javax.swing.JComboBox();
cb_estadocivil = new javax.swing.JComboBox();
bt_limpar = new javax.swing.JButton();
bt_incluir = new javax.swing.JButton();
bt_excluir = new javax.swing.JButton();
bt_alterar = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
tb_paciente.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null}
},
new String [] {
"Código", "Nome", "DDD", "Telefone", "Data de Nasc", "CPF", "RG", "Sexo", "Estado Civil"
}
));
tb_paciente.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tb_pacienteMouseClicked(evt);
}
});
jScrollPane1.setViewportView(tb_paciente);
lb_codigo.setText("Código:");
lb_nome.setText("Nome:");
lb_ddd.setText("DDD:");
jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel4.setText("Cadastro de Pacientes");
lb_telefone.setText("Telefone:");
lb_dtnasc.setText("Data de Nascimento:");
lb_cpf.setText("CPF:");
lb_rg.setText("RG:");
lb_sexo.setText("Sexo:");
lb_estadocivil.setText("Estado Civil:");
bt_limpar.setText("Limpar");
bt_limpar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bt_limparActionPerformed(evt);
}
});
bt_incluir.setText("Incluir");
bt_incluir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bt_incluirActionPerformed(evt);
}
});
bt_excluir.setText("Excluir");
bt_excluir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bt_excluirActionPerformed(evt);
}
});
bt_alterar.setText("Alterar");
bt_alterar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bt_alterarActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jLabel4)
.addGap(323, 323, 323))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lb_dtnasc)
.addGap(277, 277, 277))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(128, 128, 128)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(64, 64, 64)
.addComponent(bt_limpar)
.addGap(48, 48, 48)
.addComponent(bt_incluir)
.addGap(54, 54, 54)
.addComponent(bt_excluir)
.addGap(51, 51, 51)
.addComponent(bt_alterar))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(lb_nome)
.addComponent(lb_codigo)
.addComponent(lb_ddd)
.addComponent(lb_telefone))
.addGap(34, 34, 34)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(tf_codigo, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 159, Short.MAX_VALUE)
.addComponent(tf_telefone)
.addComponent(tf_ddd)
.addComponent(tf_nome, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(73, 73, 73)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(lb_estadocivil)
.addComponent(lb_sexo)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lb_rg)
.addComponent(lb_cpf)))
.addGroup(layout.createSequentialGroup()
.addGap(110, 110, 110)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(cb_estadocivil, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cb_sexo, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(tf_rg, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(tf_cpf, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(tf_dtnasc, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)))))))
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 741, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(31, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel4)
.addGap(44, 44, 44)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lb_codigo)
.addComponent(tf_codigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lb_nome)
.addComponent(tf_nome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lb_ddd)
.addComponent(tf_ddd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lb_telefone)
.addComponent(tf_telefone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lb_cpf)
.addComponent(tf_cpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(tf_rg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lb_rg))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(tf_dtnasc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lb_dtnasc))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cb_sexo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lb_sexo))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lb_estadocivil)
.addComponent(cb_estadocivil, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(49, 49, 49)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(bt_limpar)
.addComponent(bt_incluir)
.addComponent(bt_excluir)
.addComponent(bt_alterar))
.addGap(39, 39, 39)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void tb_pacienteMouseClicked(java.awt.event.MouseEvent evt) {
CarregaTabela_TextFileld();
MontaTela();
// TODO add your handling code here:
}
private void bt_incluirActionPerformed(java.awt.event.ActionEvent evt) {
int cd_sexo=0;
int cd_estadocivil=0;
if(Operacao.equals("Incluir"))
{
if(isCamposPreenchidos ())
{
carregaRegPaciente_Inclusao ();
if(isCamposValidos()) {
try {
cd_sexo=bd_sexo.busca_abr_Sexo(RegistroPaciente.getAbr_Sexo());
RegistroPaciente.setCd_SexoPaciente(cd_sexo);
cd_estadocivil = bd_estadocivil.busca_abr_EstadoCivil(cb_estadocivil.getSelectedItem().toString());
RegistroPaciente.setCd_EstCivilPaciente(cd_estadocivil);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null,"Erro ao buscar Sexo\n"+ex.getMessage(),"ERRO BD",JOptionPane.ERROR_MESSAGE);
}
try {
if(bd_paciente.InserirPaciente(RegistroPaciente)) {
JOptionPane.showMessageDialog(null,"Paciente Incluído com Sucesso","MENSAGEM",JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null,"Erro ao incluir Paciente. Erro de Dados","ERRO BD",JOptionPane.ERROR_MESSAGE);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null,"Erro ao incluir Paciente\n"+ex.getMessage(),"ERRO BD",JOptionPane.ERROR_MESSAGE);
} finally {
try {
CargaTabela ();
CargaListaSexo();
CargaListaEstadoCivil();
CargaComboBoxSexo ();
CargaComboBoxEstadoCivil ();
Desabilita ();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Erro Carga Grid/Combobox \n"+ex.getMessage(), "ERRO", JOptionPane.ERROR_MESSAGE);
}
Operacao="";
} // finally
} else { // if(isCamposValidos()) {
JOptionPane.showMessageDialog(null, "Preencha Corretamente:\n Nome com até 30 Caracteres","ERRO",JOptionPane.ERROR_MESSAGE);
}
} else { // if(isCamposPreenchidos ()) {
JOptionPane.showMessageDialog(null, "Preencha todos os campo!","ERRO",JOptionPane.ERROR_MESSAGE);
}
}else { // if(Operacao.equals("Incluir")) {
Operacao="Incluir";
Limpar();
habilitaEdicao ();
}
// TODO add your handling code here:
}
private void bt_excluirActionPerformed(java.awt.event.ActionEvent evt) {
int resp = JOptionPane.showConfirmDialog(null,"Confirma Exclusão?","Mensagem Exclusão",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE);
if(resp==0) {
try {
RegistroPaciente.setCd_paciente(Integer.parseInt(tf_codigo.getText().trim()));
if(bd_paciente.ExcluirPaciente(RegistroPaciente) ) {
JOptionPane.showMessageDialog(null, "Paciente excluído com Sucesso","Mensagem",JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "Erro ao Excluir Paciente","ERRO BD",JOptionPane.ERROR_MESSAGE);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Erro ao Excluir Paciente"+ex.getMessage(),"ERRO BD",JOptionPane.ERROR_MESSAGE);
} finally {
Limpar();
habilitaConsulta();
try {
CargaTabela ();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Erro ao carregar GRID \n"+ex.getMessage(), "ERRO", JOptionPane.ERROR_MESSAGE);
}
}
} else {
Desabilita ();
}
// TODO add your handling code here:
}
private void bt_alterarActionPerformed(java.awt.event.ActionEvent evt) {
int cd_sexo=0;
int cd_estadocivil=0;
if(Operacao.equals("A"))
{
if(isCamposPreenchidos ())
{
carregaRegPaciente();
if(isCamposValidos()) {
try {
cd_sexo=bd_sexo.busca_abr_Sexo(RegistroPaciente.getAbr_Sexo());
RegistroPaciente.setCd_SexoPaciente(cd_sexo);
cd_estadocivil = bd_estadocivil.busca_abr_EstadoCivil(cb_estadocivil.getSelectedItem().toString());
RegistroPaciente.setCd_EstCivilPaciente(cd_estadocivil);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null,"Erro ao buscar Sexo\n"+ex.getMessage(),"ERRO BD",JOptionPane.ERROR_MESSAGE);
}
try {
if(bd_paciente.AlteraPaciente(RegistroPaciente)) {
JOptionPane.showMessageDialog(null,"Paciente Alterado com Sucesso","MENSAGEM",JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null,"Erro ao Alterar Paciente. Erro de Dados","ERRO BD",JOptionPane.ERROR_MESSAGE);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null,"Erro ao Alterar Paciente\n"+ex.getMessage(),"ERRO BD",JOptionPane.ERROR_MESSAGE);
} finally {
try {
CargaTabela ();
CargaListaSexo();
CargaListaEstadoCivil();
CargaComboBoxSexo ();
CargaComboBoxEstadoCivil ();
Desabilita ();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Erro Carga Grid/Combobox \n"+ex.getMessage(), "ERRO", JOptionPane.ERROR_MESSAGE);
}
Operacao="";
} // finally
} else { // if(isCamposValidos()) {
JOptionPane.showMessageDialog(null, "Preencha Corretamente:\n Nome com até 30 Caracteres","ERRO",JOptionPane.ERROR_MESSAGE);
}
} else { // if(isCamposPreenchidos ()) {
JOptionPane.showMessageDialog(null, "Preencha todos os campo!","ERRO",JOptionPane.ERROR_MESSAGE);
}
}else { // if(Operacao.equals("Incluir")) {
Operacao="A";
Limpar();
habilitaEdicao ();
}
// TODO add your handling code here:
}
private void bt_limparActionPerformed(java.awt.event.ActionEvent evt) {
tf_codigo.setText(null);
tf_nome.setText(null);
tf_cpf.setText(null);
tf_ddd.setText(null);
tf_rg.setText(null);
tf_telefone.setText(null);
tf_dtnasc.setText(null);
cb_sexo.setSelectedIndex(-1);
cb_estadocivil.setSelectedIndex(-1);
// TODO add your handling code here:
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Fr_Cad_Paciente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Fr_Cad_Paciente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Fr_Cad_Paciente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Fr_Cad_Paciente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Fr_Cad_Paciente().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton bt_alterar;
private javax.swing.JButton bt_excluir;
private javax.swing.JButton bt_incluir;
private javax.swing.JButton bt_limpar;
private javax.swing.JComboBox cb_estadocivil;
private javax.swing.JComboBox cb_sexo;
private javax.swing.JLabel jLabel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel lb_codigo;
private javax.swing.JLabel lb_cpf;
private javax.swing.JLabel lb_ddd;
private javax.swing.JLabel lb_dtnasc;
private javax.swing.JLabel lb_estadocivil;
private javax.swing.JLabel lb_nome;
private javax.swing.JLabel lb_rg;
private javax.swing.JLabel lb_sexo;
private javax.swing.JLabel lb_telefone;
private javax.swing.JTable tb_paciente;
private javax.swing.JTextField tf_codigo;
private javax.swing.JTextField tf_cpf;
private javax.swing.JTextField tf_ddd;
private javax.swing.JTextField tf_dtnasc;
private javax.swing.JTextField tf_nome;
private javax.swing.JTextField tf_rg;
private javax.swing.JTextField tf_telefone;
// End of variables declaration
private void Desabilita () {
Limpar();
tf_codigo.setEditable(false);
tf_nome.setEditable(false);
tf_cpf.setEditable(false);
tf_ddd.setEditable(false);
tf_rg.setEditable(false);
tf_telefone.setEditable(false);
tf_dtnasc.setEditable(false);
cb_sexo.setEditable(false);
cb_estadocivil.setEditable(false);
}
private void habilitaConsulta () {
Limpar();
tf_codigo.setEditable(true);
tf_nome.setEditable(false);
tf_cpf.setEditable(false);
tf_ddd.setEditable(false);
tf_rg.setEditable(false);
tf_telefone.setEditable(false);
tf_dtnasc.setEditable(false);
cb_sexo.setEditable(false);
cb_estadocivil.setEditable(false);
}
private void habilitaEdicao () {
Limpar();
tf_codigo.setEditable(false);
tf_nome.setEditable(true);
tf_cpf.setEditable(true);
tf_ddd.setEditable(true);
tf_rg.setEditable(true);
tf_telefone.setEditable(true);
tf_dtnasc.setEditable(true);
cb_sexo.setEditable(true);
cb_estadocivil.setEditable(true);
}
private void MontaTela() {
tf_nome.setText(RegistroPaciente.getNm_paciente());
tf_codigo.setText(String.valueOf(RegistroPaciente.getCd_paciente()));
tf_cpf.setText(String.valueOf(RegistroPaciente.getNr_CPFpaciente()));
tf_ddd.setText(String.valueOf(RegistroPaciente.getNr_DDDPaciente()));
tf_rg.setText(String.valueOf(RegistroPaciente.getNr_RGpaciente()));
tf_telefone.setText(String.valueOf(RegistroPaciente.getNr_TelefonePaciente()));
tf_dtnasc.setText(RegistroPaciente.getDt_nascimentoPaciente());
cb_sexo.setSelectedItem(RegistroPaciente.getAbr_Sexo());
cb_estadocivil.setSelectedItem(RegistroPaciente.getAbr_EstadoCivilPaciente());
}
private void Limpar() {
tf_codigo.setText(null);
tf_nome.setText(null);
tf_cpf.setText(null);
tf_ddd.setText(null);
tf_rg.setText(null);
tf_telefone.setText(null);
tf_dtnasc.setText(null);
cb_sexo.setSelectedIndex(-1);
cb_estadocivil.setSelectedIndex(-1);
}
private void carregaRegPaciente_Inclusao () {
RegistroPaciente.setNm_paciente(tf_nome.getText().trim());
RegistroPaciente.setNr_CPFpaciente(Integer.parseInt(tf_cpf.getText().trim()));
RegistroPaciente.setDt_nascimentoPaciente(tf_dtnasc.getText().trim());
RegistroPaciente.setNr_RGpaciente(Integer.parseInt(tf_rg.getText().trim()));
RegistroPaciente.setNr_DDDPaciente(Integer.parseInt(tf_ddd.getText().trim()));
RegistroPaciente.setNr_TelefonePaciente(Integer.parseInt(tf_telefone.getText().trim()));
RegistroPaciente.setAbr_Sexo(cb_sexo.getSelectedItem().toString());
RegistroPaciente.setAbr_EstadoCivilPaciente(cb_estadocivil.getSelectedItem().toString());
System.out.println(cb_sexo.getSelectedItem().toString());
System.out.println(cb_estadocivil.getSelectedItem().toString());
}
private void carregaRegPaciente () {
RegistroPaciente.setNm_paciente(tf_nome.getText().trim());
RegistroPaciente.setNr_CPFpaciente(Integer.parseInt(tf_cpf.getText().trim()));
RegistroPaciente.setDt_nascimentoPaciente(tf_dtnasc.getText().trim());
RegistroPaciente.setNr_RGpaciente(Integer.parseInt(tf_rg.getText().trim()));
RegistroPaciente.setNr_DDDPaciente(Integer.parseInt(tf_ddd.getText().trim()));
RegistroPaciente.setNr_TelefonePaciente(Integer.parseInt(tf_telefone.getText().trim()));
RegistroPaciente.setAbr_Sexo(cb_sexo.getSelectedItem().toString());
RegistroPaciente.setAbr_EstadoCivilPaciente(cb_estadocivil.getSelectedItem().toString());
}
private boolean isCamposPreenchidos () {
boolean saida=false;
if((!tf_nome.getText().trim().isEmpty())&&
(!tf_cpf.getText().trim().isEmpty())&&
(!tf_dtnasc.getText().trim().isEmpty())&&
(!tf_rg.getText().trim().isEmpty())&&
(!tf_ddd.getText().trim().isEmpty())&&
(!tf_telefone.getText().trim().isEmpty())&&
(cb_sexo.getSelectedIndex()!=-1) &&
(cb_estadocivil.getSelectedIndex()!=-1))
{
saida=true;
}
return saida;
}
public void CargaTabela () throws Exception {
try {
DefaultTableModel modelo = (DefaultTableModel) tb_paciente.getModel();
modelo.setNumRows(0);
modelo.setRowCount(0);
for(Objeto_Paciente registro: bd_paciente.CarregarListaPaciente()) {
modelo.addRow( new Object []
{
registro.getCd_paciente(),
registro.getNm_paciente(),
registro.getNr_DDDPaciente(),
registro.getNr_TelefonePaciente(),
registro.getDt_nascimentoPaciente(),
registro.getNr_CPFpaciente(),
registro.getNr_RGpaciente(),
registro.getAbr_Sexo(),
registro.getAbr_EstadoCivilPaciente()
}
);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Erro ao carregar GRID Paciente\n"+ex.getMessage(), "ERRO GRID", JOptionPane.ERROR_MESSAGE);
}
}
private void CarregaTabela_TextFileld() {
RegistroPaciente.setCd_paciente((int) tb_paciente.getValueAt(tb_paciente.getSelectedRow(),0));
RegistroPaciente.setNm_paciente((String) tb_paciente.getValueAt(tb_paciente.getSelectedRow(),1));
RegistroPaciente.setNr_DDDPaciente((int) tb_paciente.getValueAt(tb_paciente.getSelectedRow(),2));
RegistroPaciente.setNr_TelefonePaciente((int) tb_paciente.getValueAt(tb_paciente.getSelectedRow(),3));
RegistroPaciente.setDt_nascimentoPaciente((String) tb_paciente.getValueAt(tb_paciente.getSelectedRow(),4));
RegistroPaciente.setNr_CPFpaciente((int) tb_paciente.getValueAt(tb_paciente.getSelectedRow(),5));
RegistroPaciente.setNr_RGpaciente((int) tb_paciente.getValueAt(tb_paciente.getSelectedRow(),6));
RegistroPaciente.setAbr_Sexo(((String) tb_paciente.getValueAt(tb_paciente.getSelectedRow(),7)));
RegistroPaciente.setAbr_EstadoCivilPaciente(((String) tb_paciente.getValueAt(tb_paciente.getSelectedRow(),8)));
}
public boolean isCamposValidos(){
boolean saida=false;
if ((RegistroPaciente.isNm_Paciente_Valida())&& (RegistroPaciente.isDt_Paciente_Valida())) {
saida=true;
}
return saida;
}
private void CargaListaSexo() throws Exception {
ListaSexo = bd_sexo.CarregarListaSexo();
}
private void CargaListaEstadoCivil() throws Exception {
ListaEstadoCivil = bd_estadocivil.CarregarListaEstadoCivil();
}
private void CargaComboBoxSexo () {
Iterator<Objeto_Sexo> it = ListaSexo.iterator();
while(it.hasNext()) {
Objeto_Sexo reg = it.next();
String sexo = reg.getAbr_Sexo();
cb_sexo.addItem(sexo);
}
cb_sexo.setSelectedIndex(-1);
}
private void CargaComboBoxEstadoCivil () {
Iterator<Objeto_EstadoCivil> it = ListaEstadoCivil.iterator();
while(it.hasNext()) {
Objeto_EstadoCivil reg = it.next();
String estadocivil = reg.getAbr_EstadoCivilPaciente();
cb_estadocivil.addItem(estadocivil);
}
cb_estadocivil.setSelectedIndex(-1);
}
}
|
922f07497d33ca94193c93fa19c5242a7b4a764e | 1,479 | java | Java | product/src/main/java/io/onedev/server/product/ProductModule.java | OpenSrcRepoDataDigging/onedev | 1facaef51d35add5eb99740fb5d13a73b210a72e | [
"MIT"
] | null | null | null | product/src/main/java/io/onedev/server/product/ProductModule.java | OpenSrcRepoDataDigging/onedev | 1facaef51d35add5eb99740fb5d13a73b210a72e | [
"MIT"
] | null | null | null | product/src/main/java/io/onedev/server/product/ProductModule.java | OpenSrcRepoDataDigging/onedev | 1facaef51d35add5eb99740fb5d13a73b210a72e | [
"MIT"
] | 1 | 2019-01-13T05:02:37.000Z | 2019-01-13T05:02:37.000Z | 35.214286 | 95 | 0.805274 | 994,966 | package io.onedev.server.product;
import java.io.File;
import org.hibernate.cfg.Environment;
import io.onedev.launcher.loader.AbstractPluginModule;
import io.onedev.launcher.bootstrap.Bootstrap;
import io.onedev.utils.FileUtils;
import io.onedev.utils.StringUtils;
import io.onedev.server.persistence.HibernateProperties;
import io.onedev.server.util.jetty.ServerConfigurator;
import io.onedev.server.util.jetty.ServletConfigurator;
import io.onedev.server.util.serverconfig.ServerConfig;
public class ProductModule extends AbstractPluginModule {
@Override
protected void configure() {
super.configure();
File file = new File(Bootstrap.installDir, "conf/hibernate.properties");
HibernateProperties hibernateProps = new HibernateProperties(FileUtils.loadProperties(file));
String url = hibernateProps.getProperty(Environment.URL);
hibernateProps.setProperty(Environment.URL,
StringUtils.replace(url, "${installDir}", Bootstrap.installDir.getAbsolutePath()));
bind(HibernateProperties.class).toInstance(hibernateProps);
file = new File(Bootstrap.installDir, "conf/server.properties");
ServerProperties serverProps = new ServerProperties(FileUtils.loadProperties(file));
bind(ServerProperties.class).toInstance(serverProps);
bind(ServerConfig.class).to(DefaultServerConfig.class);
contribute(ServerConfigurator.class, ProductConfigurator.class);
contribute(ServletConfigurator.class, ProductServletConfigurator.class);
}
}
|
922f089ba129055f8b6740e79fc629bb12d11f32 | 2,903 | java | Java | src/main/java/bio/tech/catalog/utils/SummaryCaseCtl.java | h3abionet/catalogue-public | 008b74bfe6e1a1e53a476aec71194cb28c1089b0 | [
"MIT"
] | null | null | null | src/main/java/bio/tech/catalog/utils/SummaryCaseCtl.java | h3abionet/catalogue-public | 008b74bfe6e1a1e53a476aec71194cb28c1089b0 | [
"MIT"
] | null | null | null | src/main/java/bio/tech/catalog/utils/SummaryCaseCtl.java | h3abionet/catalogue-public | 008b74bfe6e1a1e53a476aec71194cb28c1089b0 | [
"MIT"
] | 3 | 2019-03-27T07:28:42.000Z | 2019-04-11T18:52:14.000Z | 21.827068 | 121 | 0.757148 | 994,967 | package bio.tech.catalog.utils;
public class SummaryCaseCtl {
private int countCases;
private int countCasesMale;
private int countCasesFemale;
private double casesVolume;
private int casesWithVolume;
private int countCtls;
private int countCtlsMale;
private int countCtlsFemale;
private double ctlsVolume;
private int ctlsWithVolume;
private String biobankName;
public SummaryCaseCtl() {
countCases = 0;
countCasesMale = 0;
countCasesFemale = 0;
casesVolume = 0;
casesWithVolume = 0;
countCtls = 0;
countCtlsMale = 0;
countCtlsFemale = 0;
biobankName = "";
}
public SummaryCaseCtl(int countCases, int countCasesMale, int countCasesFemale, double casesVolume, int casesWithVolume,
int countCtls, int countCtlsMale, int countCtlsFemale, double ctlsVolume, int ctlsWithVolume) {
this.countCases = countCases;
this.countCasesMale = countCasesMale;
this.countCasesFemale = countCasesFemale;
this.casesVolume = casesVolume;
this.casesWithVolume = casesWithVolume;
this.countCtls = countCtls;
this.countCtlsMale = countCtlsMale;
this.countCtlsFemale = countCtlsFemale;
this.ctlsVolume = ctlsVolume;
this.ctlsWithVolume = ctlsWithVolume;
}
public int getCountCases() {
return countCases;
}
public int getCountCasesMale() {
return countCasesMale;
}
public int getCountCasesFemale() {
return countCasesFemale;
}
public double getCasesVolume() {
return casesVolume;
}
public int getCasesWithVolume() {
return casesWithVolume;
}
public int getCountCtls() {
return countCtls;
}
public int getCountCtlsMale() {
return countCtlsMale;
}
public int getCountCtlsFemale() {
return countCtlsFemale;
}
public double getCtlsVolume() {
return ctlsVolume;
}
public int getCtlsWithVolume() {
return ctlsWithVolume;
}
public String getBiobankName() {
return biobankName;
}
// setters
public void setCountCases(int countCases) {
this.countCases = countCases;
}
public void setCountCasesMale(int countCasesMale) {
this.countCasesMale = countCasesMale;
}
public void setCountCasesFemale(int countCasesFemale) {
this.countCasesFemale = countCasesFemale;
}
public void setCasesVolume(double casesVolume) {
this.casesVolume = casesVolume;
}
public void setCasesWithVolume(int casesWithVolume) {
this.casesWithVolume = casesWithVolume;
}
public void setCountCtls(int countCtls) {
this.countCtls = countCtls;
}
public void setCountCtlsMale(int countCtlsMale) {
this.countCtlsMale = countCtlsMale;
}
public void setCountCtlsFemale(int countCtlsFemale) {
this.countCtlsFemale = countCtlsFemale;
}
public void setCtlsVolume(double ctlsVolume) {
this.ctlsVolume = ctlsVolume;
}
public void setCtlsWithVolume(int ctlsWithVolume) {
this.ctlsWithVolume = ctlsWithVolume;
}
public void setBiobankName(String biobankName) {
this.biobankName = biobankName;
}
}
|
922f092845d916691d2ae293822e21e3965bbf44 | 21,124 | java | Java | impl/src/main/java/org/apache/tuscany/sdo/helper/SDOHelperImpl.java | JLLeitschuh/tuscany-sdo | c27fb58d9490e4488b1b782f0d9b4798945d7285 | [
"Apache-2.0"
] | 5 | 2015-01-17T17:09:40.000Z | 2021-11-10T19:06:35.000Z | impl/src/main/java/org/apache/tuscany/sdo/helper/SDOHelperImpl.java | JLLeitschuh/tuscany-sdo | c27fb58d9490e4488b1b782f0d9b4798945d7285 | [
"Apache-2.0"
] | null | null | null | impl/src/main/java/org/apache/tuscany/sdo/helper/SDOHelperImpl.java | JLLeitschuh/tuscany-sdo | c27fb58d9490e4488b1b782f0d9b4798945d7285 | [
"Apache-2.0"
] | 14 | 2015-12-11T02:26:58.000Z | 2021-11-03T10:32:38.000Z | 39.781544 | 118 | 0.68576 | 994,968 | /**
*
* 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.tuscany.sdo.helper;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.tuscany.sdo.SDOExtendedMetaData;
import org.apache.tuscany.sdo.SDOFactory;
import org.apache.tuscany.sdo.SimpleAnyTypeDataObject;
import org.apache.tuscany.sdo.api.SDOHelper;
import org.apache.tuscany.sdo.api.XMLStreamHelper;
import org.apache.tuscany.sdo.api.EventListener;
import org.apache.tuscany.sdo.impl.ClassImpl;
import org.apache.tuscany.sdo.impl.DataGraphImpl;
import org.apache.tuscany.sdo.impl.DynamicDataObjectImpl;
import org.apache.tuscany.sdo.model.ModelFactory;
import org.apache.tuscany.sdo.model.impl.ModelFactoryImpl;
import org.apache.tuscany.sdo.spi.SDOHelperBase;
import org.apache.tuscany.sdo.util.DataObjectUtil;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.common.util.UniqueEList;
import org.eclipse.emf.ecore.EAnnotation;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.ecore.EModelElement;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.ETypedElement;
import org.eclipse.emf.ecore.EcoreFactory;
import org.eclipse.emf.ecore.EcorePackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.util.ExtendedMetaData;
import org.eclipse.emf.ecore.util.FeatureMap;
import org.eclipse.emf.ecore.util.FeatureMapUtil;
import org.eclipse.emf.ecore.xmi.XMLResource;
import commonj.sdo.DataGraph;
import commonj.sdo.DataObject;
import commonj.sdo.Property;
import commonj.sdo.Sequence;
import commonj.sdo.Type;
import commonj.sdo.helper.CopyHelper;
import commonj.sdo.helper.HelperContext;
import commonj.sdo.helper.TypeHelper;
import commonj.sdo.impl.HelperProvider;
public class SDOHelperImpl extends SDOHelperBase implements SDOHelper, SDOHelper.MetaDataBuilder {
public DataObject createDataTypeWrapper(Type dataType, Object value) {
SimpleAnyTypeDataObject simpleAnyType = SDOFactory.eINSTANCE.createSimpleAnyTypeDataObject();
simpleAnyType.setInstanceType((EDataType)dataType);
simpleAnyType.setValue(value);
return simpleAnyType;
}
public Object createFromString(Type dataType, String literal) {
return EcoreUtil.createFromString((EDataType)dataType, literal);
}
public String convertToString(Type dataType, Object value) {
return EcoreUtil.convertToString((EDataType)dataType, value);
}
public Type getXSDSDOType(String xsdType) {
Type type = null;
String name = (String)xsdToSdoMappings.get(xsdType);
if (name != null)
type = (Type)((ModelFactoryImpl)ModelFactory.INSTANCE).getEClassifier(name);
return type;
}
public Sequence getSubstitutionValues(DataObject dataObject, Property head) {
final EStructuralFeature group = ExtendedMetaData.INSTANCE.getGroup((EStructuralFeature)head);
return null == group ? null : (Sequence)((FeatureMap.Internal)((EObject)dataObject).eGet(group)).getWrapper();
}
public Type getJavaSDOType(Class javaClass) {
String name = (String)javaToSdoMappings.get(javaClass);
if (name != null) {
return (Type)((ModelFactoryImpl)ModelFactory.INSTANCE).getEClassifier(name);
}
return null;
}
public boolean isRequired(Property property) {
return ((EStructuralFeature)property).isRequired();
}
public int getUpperBound(Property property) {
return ((EStructuralFeature)property).getUpperBound();
}
public int getLowerBound(Property property) {
return ((EStructuralFeature)property).getLowerBound();
}
public List getEnumerationFacet(Type type) {
List instProps = type.getInstanceProperties();
String propertyName = "enumeration";
Property enumProperty = null;
for (int i = 0; i < instProps.size(); i++)
{
Property prop = (Property)instProps.get(i);
if (propertyName.equals(prop.getName()))
enumProperty = prop;
}
return (List)DataObjectUtil.getMetaObjectInstanceProperty((EModelElement)type, enumProperty);
}
public List getPatternFacet(Type type) {
List instProps = type.getInstanceProperties();
String propertyName = "pattern";
Property patternProperty = null;
for (int i = 0; i < instProps.size(); i++)
{
Property prop = (Property)instProps.get(i);
if (propertyName.equals(prop.getName()))
patternProperty = prop;
}
return (List)DataObjectUtil.getMetaObjectInstanceProperty((EModelElement)type, patternProperty);
}
public boolean isMany(Property property, DataObject context) {
return FeatureMapUtil.isMany((EObject)context, (EStructuralFeature)property);
}
public DataGraph createDataGraph() {
return SDOFactory.eINSTANCE.createDataGraph();
}
public void setRootObject(DataGraph dataGraph, DataObject rootObject) {
((DataGraphImpl)dataGraph).setERootObject((EObject)rootObject);
}
public static DataGraph loadDataGraph(InputStream inputStream, Map options) throws IOException {
ResourceSet resourceSet = DataObjectUtil.createResourceSet();
Resource resource = resourceSet.createResource(URI.createURI("all.datagraph"));
resource.load(inputStream, options);
return (DataGraph)resource.getContents().get(0);
}
static final Object LOADING_SCOPE = XMLResource.OPTION_EXTENDED_META_DATA;
protected void registerLoadingScope(Map options, TypeHelper scope) {
Object extendedMetaData = ((TypeHelperImpl)scope).getExtendedMetaData();
options.put(LOADING_SCOPE, extendedMetaData);
}
public DataGraph loadDataGraph(InputStream inputStream, Map options, HelperContext scope) throws IOException {
if (scope == null) {
scope = HelperProvider.getDefaultContext();
}
TypeHelper th = scope.getTypeHelper();
DataGraph result = null;
if (th == null || th == TypeHelper.INSTANCE) {
result = loadDataGraph(inputStream, options);
} else if (options == null) {
options = new HashMap();
registerLoadingScope(options, th);
result = loadDataGraph(inputStream, options);
} else if (options.containsKey(LOADING_SCOPE)) {
Object restore = options.get(LOADING_SCOPE);
registerLoadingScope(options, th);
try {
result = loadDataGraph(inputStream, options);
} finally {
options.put(LOADING_SCOPE, restore);
}
} else {
registerLoadingScope(options, th);
try {
result = loadDataGraph(inputStream, options);
} finally {
options.remove(LOADING_SCOPE);
}
}
return result;
}
public void saveDataGraph(DataGraph dataGraph, OutputStream outputStream, Map options) throws IOException {
((DataGraphImpl)dataGraph).getDataGraphResource().save(outputStream, options);
}
public void registerDataGraphTypes(DataGraph dataGraph, List/* Type */types) {
// if (types == null)
// types = SDOUtil.getDataGraphTypes(dataGraph);
Set/* EPackage */packages = new HashSet();
for (final Iterator iterator = types.iterator(); iterator.hasNext();) {
EClassifier type = (EClassifier)iterator.next();
packages.add(type.getEPackage());
}
ResourceSet resourceSet = ((DataGraphImpl)dataGraph).getResourceSet();
for (Iterator iterator = packages.iterator(); iterator.hasNext();) {
EPackage typePackage = (EPackage)iterator.next();
Resource resource = typePackage.eResource();
if (resource == null) {
resource = resourceSet.createResource(URI.createURI(".ecore"));
resource.setURI(URI.createURI(typePackage.getNsURI()));
resource.getContents().add(typePackage);
} else if (resource.getResourceSet() != resourceSet)
resourceSet.getResources().add(resource);
}
}
public HelperContext createHelperContext() {
return new HelperContextImpl(false, null);
}
public HelperContext createHelperContext(boolean extensibleNamespaces) {
return new HelperContextImpl(extensibleNamespaces);
}
public HelperContext createHelperContext(Map options) {
return new HelperContextImpl(false, options);
}
public HelperContext createHelperContext(boolean extensibleNamespaces, Map options) {
return new HelperContextImpl(extensibleNamespaces, options);
}
public CopyHelper createCrossScopeCopyHelper(HelperContext hc) {
return new CrossScopeCopyHelperImpl(hc.getTypeHelper());
}
public XMLStreamHelper createXMLStreamHelper(HelperContext hc) {
return ((HelperContextImpl)hc).getXMLStreamHelper();
}
public List getTypes(HelperContext hc, String uri) {
EPackage ePackage = ((HelperContextImpl)hc).getExtendedMetaData().getPackage(uri);
if (ePackage != null) {
return new ArrayList(ePackage.getEClassifiers());
}
return null;
}
public List getOpenContentProperties(DataObject dataObject) {
List result = new UniqueEList();
((ClassImpl)dataObject.getType()).addOpenProperties((EObject)dataObject, result);
return result;
}
public boolean isDocumentRoot(Type type) {
return "".equals(SDOExtendedMetaData.INSTANCE.getName((EClassifier)type));
}
public Type createType(HelperContext hc, String uri, String name, boolean isDataType) {
ExtendedMetaData extendedMetaData = ((HelperContextImpl)hc).getExtendedMetaData();
if ("".equals(uri))
uri = null; // FB
EPackage ePackage = extendedMetaData.getPackage(uri);
if (ePackage == null) {
ePackage = EcoreFactory.eINSTANCE.createEPackage();
ePackage.setEFactoryInstance(new DynamicDataObjectImpl.FactoryImpl());
ePackage.setNsURI(uri);
String packagePrefix = uri != null ? URI.createURI(uri).trimFileExtension().lastSegment() : ""; // FB
ePackage.setName(packagePrefix);
ePackage.setNsPrefix(packagePrefix);
extendedMetaData.putPackage(uri, ePackage);
}
EClassifier eClassifier = ePackage.getEClassifier(name);
if (eClassifier != null) // already defined?
{
// throw new IllegalArgumentException();
return null;
}
if (name != null) {
eClassifier =
isDataType ? (EClassifier)SDOFactory.eINSTANCE.createDataType() : (EClassifier)SDOFactory.eINSTANCE
.createClass();
eClassifier.setName(name);
} else {
eClassifier = DataObjectUtil.createDocumentRoot();
}
ePackage.getEClassifiers().add(eClassifier);
return (Type)eClassifier;
}
public void addBaseType(Type type, Type baseType) {
((EClass)type).getESuperTypes().add(baseType);
}
public void addAliasName(Type type, String aliasName) {
throw new UnsupportedOperationException(); // TODO: implement this
// method properly
// type.getAliasNames().add(aliasName);
}
public void setOpen(Type type, boolean isOpen) {
if (isOpen == type.isOpen())
return;
if (isOpen) {
EAttribute eAttribute = (EAttribute)SDOFactory.eINSTANCE.createAttribute();
((EClass)type).getEStructuralFeatures().add(eAttribute);
eAttribute.setName("any");
eAttribute.setUnique(false);
eAttribute.setUpperBound(ETypedElement.UNBOUNDED_MULTIPLICITY);
eAttribute.setEType(EcorePackage.eINSTANCE.getEFeatureMapEntry());
ExtendedMetaData.INSTANCE.setFeatureKind(eAttribute, ExtendedMetaData.ELEMENT_WILDCARD_FEATURE);
ExtendedMetaData.INSTANCE.setProcessingKind(eAttribute, ExtendedMetaData.LAX_PROCESSING);
ExtendedMetaData.INSTANCE.setWildcards(eAttribute, Collections.singletonList("##any"));
// FB TBD Add an "anyAttribute" EAttribute as well.
if (ExtendedMetaData.INSTANCE.getMixedFeature((EClass)type) != null) {
eAttribute.setDerived(true);
eAttribute.setTransient(true);
eAttribute.setVolatile(true);
}
} else {
EClass eClass = (EClass)type;
EAttribute any = (EAttribute)eClass.getEStructuralFeature("any");
eClass.getEStructuralFeatures().remove(any);
}
}
public void setSequenced(Type type, boolean isSequenced) {
// currently, we require setSequenced to be called first, before
// anything else is added to the type.
if (type.isDataType() || !type.getProperties().isEmpty()) {
if (type.getName() != "DocumentRoot") // document root is a
// special case
throw new IllegalArgumentException();
}
if (isSequenced) {
EClass eClass = (EClass)type;
ExtendedMetaData.INSTANCE.setContentKind(eClass, ExtendedMetaData.MIXED_CONTENT);
EAttribute mixedFeature = (EAttribute)SDOFactory.eINSTANCE.createAttribute();
mixedFeature.setName("mixed");
mixedFeature.setUnique(false);
mixedFeature.setEType(EcorePackage.eINSTANCE.getEFeatureMapEntry());
mixedFeature.setLowerBound(0);
mixedFeature.setUpperBound(-1);
// eClass.getEStructuralFeatures().add(mixedFeature);
((ClassImpl)eClass).setSequenceFeature(mixedFeature);
ExtendedMetaData.INSTANCE.setFeatureKind(mixedFeature, ExtendedMetaData.ELEMENT_WILDCARD_FEATURE);
ExtendedMetaData.INSTANCE.setName(mixedFeature, ":mixed");
} else {
// nothing to do, because of current restriction that setSequence
// must be called first.
}
}
public void setAbstract(Type type, boolean isAbstract) {
((EClass)type).setAbstract(isAbstract);
}
public void setJavaClassName(Type type, String javaClassName) {
((EClassifier)type).setInstanceClassName(javaClassName);
}
public Property createProperty(Type containingType, String name, Type propertyType) {
EStructuralFeature eStructuralFeature =
propertyType.isDataType() ? (EStructuralFeature)SDOFactory.eINSTANCE.createAttribute()
: (EStructuralFeature)SDOFactory.eINSTANCE.createReference();
eStructuralFeature.setName(name);
eStructuralFeature.setEType((EClassifier)propertyType);
((EClass)containingType).getEStructuralFeatures().add(eStructuralFeature);
if ("".equals(ExtendedMetaData.INSTANCE.getName((EClass)containingType))) // DocumentRoot
// containingType?
{
ExtendedMetaData.INSTANCE.setNamespace(eStructuralFeature, containingType.getURI());
//FB???eStructuralFeature.setUnique(false);
//FB???eStructuralFeature.setUpperBound(ETypedElement.UNSPECIFIED_MULTIPLICITY);
}
if (ExtendedMetaData.INSTANCE.getMixedFeature((EClass)containingType) != null) {
eStructuralFeature.setDerived(true);
eStructuralFeature.setTransient(true);
eStructuralFeature.setVolatile(true);
ExtendedMetaData.INSTANCE.setFeatureKind(eStructuralFeature, ExtendedMetaData.ELEMENT_FEATURE);
} else {
// By default, a SDO property is an XSD element
ExtendedMetaData.INSTANCE.setFeatureKind(eStructuralFeature, ExtendedMetaData.ELEMENT_FEATURE);
}
return (Property)eStructuralFeature;
}
public void setPropertyXMLKind(Property property, boolean isXmlElement) {
if (isXmlElement) {
ExtendedMetaData.INSTANCE.setFeatureKind((EStructuralFeature)property, ExtendedMetaData.ELEMENT_FEATURE);
}
else {
ExtendedMetaData.INSTANCE.setFeatureKind((EStructuralFeature)property, ExtendedMetaData.ATTRIBUTE_FEATURE);
}
}
public Property createOpenContentProperty(HelperContext hc, String uri, String name, Type type)
{
ExtendedMetaData extendedMetaData = ((HelperContextImpl)hc).getExtendedMetaData();
// get/create document root
EPackage ePackage = extendedMetaData.getPackage(uri);
Type documentRoot = ePackage != null ? (Type)extendedMetaData.getType(ePackage, "") : null;
if (documentRoot == null) {
documentRoot = createType(hc, uri, null, false);
}
// Determine if property already exists
Property newProperty = documentRoot.getProperty(name);
if (newProperty == null) {
// Create the new property 'under' the document root.....
newProperty = createProperty(documentRoot, name, type);
} else {
// if property already exists, validate the expected type
if (!newProperty.getType().equals(type))
throw new IllegalArgumentException();
}
return newProperty;
}
public void addAliasName(Property property, String aliasName) {
throw new UnsupportedOperationException(); // TODO: implement this
// method properly
// property.getAliasNames().add(aliasName);
}
public void setMany(Property property, boolean isMany) {
((EStructuralFeature)property).setUpperBound(isMany ? EStructuralFeature.UNBOUNDED_MULTIPLICITY : 1);
}
public void setContainment(Property property, boolean isContainment) {
((EReference)property).setContainment(isContainment);
}
public void setDefault(Property property, String defaultValue) {
((EStructuralFeature)property).setDefaultValueLiteral(defaultValue);
}
public void setReadOnly(Property property, boolean isReadOnly) {
((EStructuralFeature)property).setChangeable(!isReadOnly);
}
public void setOpposite(Property property, Property opposite) {
((EReference)property).setEOpposite((EReference)opposite);
}
public void addTypeInstanceProperty(Type definedType, Property instanceProperty, Object value) {
addInstanceProperty((EModelElement)definedType, instanceProperty, value);
}
public void addPropertyInstanceProperty(Property definedProperty, Property instanceProperty, Object value) {
addInstanceProperty((EModelElement)definedProperty, instanceProperty, value);
}
protected void addInstanceProperty(EModelElement metaObject, Property property, Object value) {
String uri = property.getContainingType().getURI();
EAnnotation eAnnotation = metaObject.getEAnnotation(uri);
if (eAnnotation == null) {
eAnnotation = EcoreFactory.eINSTANCE.createEAnnotation();
eAnnotation.setSource(uri);
metaObject.getEAnnotations().add(eAnnotation);
}
// TODO if (property.isMany()) ... // convert list of values
String stringValue = convertToString(property.getType(), value);
eAnnotation.getDetails().put(property.getName(), stringValue);
}
public void addChangeListener(DataObject dob, EventListener listener) {
// Adapter l = (Adapter)listener;
((Notifier)dob).eAdapters().add(listener);
}
public void removeChangeListener(DataObject dob, EventListener listener) {
((Notifier)dob).eAdapters().remove(listener);
}
}
|
922f095c2eb384fe3d51ee9a55fd2d3335ca20f3 | 1,438 | java | Java | src/main/java/example/GreeterHtmlRenderer.java | StefanLiebenberg/presentation-guice-injection | 4282ee88280123bc6490fdf59e04d00e20c6c904 | [
"MIT"
] | null | null | null | src/main/java/example/GreeterHtmlRenderer.java | StefanLiebenberg/presentation-guice-injection | 4282ee88280123bc6490fdf59e04d00e20c6c904 | [
"MIT"
] | null | null | null | src/main/java/example/GreeterHtmlRenderer.java | StefanLiebenberg/presentation-guice-injection | 4282ee88280123bc6490fdf59e04d00e20c6c904 | [
"MIT"
] | null | null | null | 34.238095 | 136 | 0.673853 | 994,969 | package example;
import com.google.inject.Inject;
import example.plugins.Plugin;
import javax.annotation.Nullable;
import java.util.Set;
public class GreeterHtmlRenderer {
private final ModelFormatter modelFormatter;
private final ClockHtmlRenderer clockHtmlRenderer;
private final Set<Plugin> pluginList;
@Inject
public GreeterHtmlRenderer(ModelFormatter modelFormatter, ClockHtmlRenderer clockHtmlRenderer, @Nullable Set<Plugin> pluginList) {
this.modelFormatter = modelFormatter;
this.clockHtmlRenderer = clockHtmlRenderer;
this.pluginList = pluginList;
}
public String render(GreeterModel greeterModel) {
StringBuilder htmlBuilder = new StringBuilder();
htmlBuilder.append("<div class='greeting' id='").append(greeterModel.getId()).append("'>");
htmlBuilder.append("<small><b>[").append(clockHtmlRenderer.render(greeterModel.getClockModel())).append("]</b></small>: ");
htmlBuilder.append("<span>").append(modelFormatter.formatGreeter(greeterModel)).append("</span>");
if (!pluginList.isEmpty()) {
htmlBuilder.append("<ul>");
for (Plugin plugin : pluginList) {
htmlBuilder.append("<li>").append(plugin.getHtmlContent()).append("</li>");
}
htmlBuilder.append("</ul>");
}
htmlBuilder.append("</div>");
return htmlBuilder.toString();
}
}
|
922f0a0037068835c0b351e4a91695b64f09a11d | 3,642 | java | Java | straightline/src/test/java/org/poormanscastle/studies/compilers/grammar/grammar_oh/ast/domain/TypeTest.java | georgfedermann/compilers | 20bef63e5749e9472886d0d8e4dfc3158c15703b | [
"Apache-2.0"
] | 1 | 2016-03-01T17:42:54.000Z | 2016-03-01T17:42:54.000Z | straightline/src/test/java/org/poormanscastle/studies/compilers/grammar/grammar_oh/ast/domain/TypeTest.java | georgfedermann/compilers | 20bef63e5749e9472886d0d8e4dfc3158c15703b | [
"Apache-2.0"
] | 2 | 2016-02-12T18:02:58.000Z | 2016-02-18T08:49:05.000Z | straightline/src/test/java/org/poormanscastle/studies/compilers/grammar/grammar_oh/ast/domain/TypeTest.java | georgfedermann/compilers | 20bef63e5749e9472886d0d8e4dfc3158c15703b | [
"Apache-2.0"
] | null | null | null | 44.414634 | 86 | 0.725151 | 994,970 | package org.poormanscastle.studies.compilers.grammar.grammar_oh.ast.domain;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Created by 02eex612 on 22.02.2016.
*/
public class TypeTest {
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void testAreTypesCompatible() throws Exception {
assertTrue(Type.areTypesCompatible(Type.BOOLEAN, Type.BOOLEAN));
assertTrue(Type.areTypesCompatible(Type.INT, Type.INT));
assertTrue(Type.areTypesCompatible(Type.INT, Type.DOUBLE));
assertTrue(Type.areTypesCompatible(Type.DOUBLE, Type.DOUBLE));
assertTrue(Type.areTypesCompatible(Type.DOUBLE, Type.INT));
assertTrue(Type.areTypesCompatible(Type.TEXT, Type.BOOLEAN));
assertTrue(Type.areTypesCompatible(Type.TEXT, Type.INT));
assertTrue(Type.areTypesCompatible(Type.TEXT, Type.DOUBLE));
assertTrue(Type.areTypesCompatible(Type.TEXT, Type.TEXT));
assertFalse(Type.areTypesCompatible(Type.BOOLEAN, Type.INT));
assertFalse(Type.areTypesCompatible(Type.BOOLEAN, Type.DOUBLE));
}
@Test
public void testGetInferredType() throws Exception {
assertEquals(Type.DOUBLE, Type.getInferredType(Type.INT, Type.DOUBLE));
assertEquals(Type.INT, Type.getInferredType(Type.INT, Type.INT));
assertEquals(Type.BOOLEAN, Type.getInferredType(Type.BOOLEAN, Type.BOOLEAN));
assertEquals(Type.TEXT, Type.getInferredType(Type.TEXT, Type.BOOLEAN));
assertEquals(Type.TEXT, Type.getInferredType(Type.TEXT, Type.INT));
assertEquals(Type.TEXT, Type.getInferredType(Type.TEXT, Type.DOUBLE));
assertEquals(Type.TEXT, Type.getInferredType(Type.TEXT, Type.TEXT));
}
@Test
public void testBooleanWithInteger() {
exception.expect(RuntimeException.class);
exception.expectMessage("The two types BOOLEAN and INT are incompatible.");
Type.getInferredType(Type.BOOLEAN, Type.INT);
}
@Test
public void testBooleanWithDouble() {
exception.expect(RuntimeException.class);
exception.expectMessage("The two types BOOLEAN and DOUBLE are incompatible.");
Type.getInferredType(Type.BOOLEAN, Type.DOUBLE);
}
@Test
public void testIsRhsAssignableToLhs() throws Exception {
assertTrue(Type.isRhsAssignableToLhs(Type.BOOLEAN, Type.BOOLEAN));
assertFalse(Type.isRhsAssignableToLhs(Type.BOOLEAN, Type.INT));
assertFalse(Type.isRhsAssignableToLhs(Type.BOOLEAN, Type.DOUBLE));
assertFalse(Type.isRhsAssignableToLhs(Type.BOOLEAN, Type.TEXT));
assertFalse(Type.isRhsAssignableToLhs(Type.INT, Type.BOOLEAN));
assertTrue(Type.isRhsAssignableToLhs(Type.INT, Type.INT));
assertFalse(Type.isRhsAssignableToLhs(Type.INT, Type.DOUBLE));
assertFalse(Type.isRhsAssignableToLhs(Type.INT, Type.TEXT));
assertFalse(Type.isRhsAssignableToLhs(Type.DOUBLE, Type.BOOLEAN));
assertTrue(Type.isRhsAssignableToLhs(Type.DOUBLE, Type.INT));
assertTrue(Type.isRhsAssignableToLhs(Type.DOUBLE, Type.DOUBLE));
assertFalse(Type.isRhsAssignableToLhs(Type.DOUBLE, Type.TEXT));
assertFalse(Type.isRhsAssignableToLhs(Type.TEXT, Type.BOOLEAN));
assertFalse(Type.isRhsAssignableToLhs(Type.TEXT, Type.INT));
assertFalse(Type.isRhsAssignableToLhs(Type.TEXT, Type.DOUBLE));
assertTrue(Type.isRhsAssignableToLhs(Type.TEXT, Type.TEXT));
}
} |
922f0b3f354cfc49ae3818d8194fde7a490c54ce | 48 | java | Java | testprojects/java/visibillity/application/ClassDefault.java | senkz/HUSACCT | 4888062b1a933c5e8458a6d087a3c6f3781207e7 | [
"MIT"
] | null | null | null | testprojects/java/visibillity/application/ClassDefault.java | senkz/HUSACCT | 4888062b1a933c5e8458a6d087a3c6f3781207e7 | [
"MIT"
] | null | null | null | testprojects/java/visibillity/application/ClassDefault.java | senkz/HUSACCT | 4888062b1a933c5e8458a6d087a3c6f3781207e7 | [
"MIT"
] | 1 | 2021-02-02T12:58:55.000Z | 2021-02-02T12:58:55.000Z | 8 | 20 | 0.729167 | 994,971 | package application;
class ClassDefault {
}
|
922f0c3ac47b83aa1e9a1ee835332dbe3ad770a0 | 649 | java | Java | LearningJava/src/main/java/org/pengfei/Lesson00_Java_Basics/A01_Microbenchmarking/source/JMHTest01.java | pengfei99/JavaBasic | c8190a429d6bab5b39d90450dae1a45e894e0060 | [
"MIT"
] | null | null | null | LearningJava/src/main/java/org/pengfei/Lesson00_Java_Basics/A01_Microbenchmarking/source/JMHTest01.java | pengfei99/JavaBasic | c8190a429d6bab5b39d90450dae1a45e894e0060 | [
"MIT"
] | 4 | 2021-02-19T08:40:21.000Z | 2021-04-28T15:46:13.000Z | LearningJava/src/main/java/org/pengfei/Lesson00_Java_Basics/A01_Microbenchmarking/source/JMHTest01.java | pengfei99/JavaBasic | c8190a429d6bab5b39d90450dae1a45e894e0060 | [
"MIT"
] | 1 | 2020-05-15T15:42:53.000Z | 2020-05-15T15:42:53.000Z | 21.633333 | 70 | 0.70416 | 994,972 | package org.pengfei.Lesson00_Java_Basics.A01_Microbenchmarking.source;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import java.util.concurrent.TimeUnit;
public class JMHTest01 {
@Benchmark
public void doNothing(){
System.out.println("Doing nothing");
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.SECONDS)
public void exp1(){
int a=1;
int b=2;
int sum=a+b;
System.out.println("Sum value: "+sum);
}
}
|
922f0c821835983f05278573a6b267b6cc193e8c | 470 | java | Java | extra/mybatis1217_2/src/cn/itcast/mybatis/mapper/UserMapper.java | q1770750695/JavaEE | 1934d9b4e629cd5ca7ef6b7eb7184fdaf853efe1 | [
"MIT"
] | null | null | null | extra/mybatis1217_2/src/cn/itcast/mybatis/mapper/UserMapper.java | q1770750695/JavaEE | 1934d9b4e629cd5ca7ef6b7eb7184fdaf853efe1 | [
"MIT"
] | null | null | null | extra/mybatis1217_2/src/cn/itcast/mybatis/mapper/UserMapper.java | q1770750695/JavaEE | 1934d9b4e629cd5ca7ef6b7eb7184fdaf853efe1 | [
"MIT"
] | null | null | null | 18.076923 | 66 | 0.659574 | 994,973 | package cn.itcast.mybatis.mapper;
import java.util.List;
import cn.itcast.mybatis.po.User;
/**
*
* <p>Title: UserMapper</p>
* <p>Description:mapper接口 </p>
* <p>Company: www.itcast.com</p>
* @author 传智.燕青
* @date 2014-12-17下午3:12:26
* @version 1.0
*/
public interface UserMapper {
//根据用户id查询用户信息
public User findUserById(int id) throws Exception;
//查询用户列表
public List<User> findUserList(String username)throws Exception;
}
|
922f0da8e963390ec4eab2ec8b78f6a1cc06fde8 | 546 | java | Java | Deck.java | Kaustubh-Wadagavi/Java_BlackJackGame | dfaac683d4c2919d07cd712984034138aaddfccc | [
"Apache-2.0"
] | null | null | null | Deck.java | Kaustubh-Wadagavi/Java_BlackJackGame | dfaac683d4c2919d07cd712984034138aaddfccc | [
"Apache-2.0"
] | null | null | null | Deck.java | Kaustubh-Wadagavi/Java_BlackJackGame | dfaac683d4c2919d07cd712984034138aaddfccc | [
"Apache-2.0"
] | 1 | 2020-05-17T08:16:53.000Z | 2020-05-17T08:16:53.000Z | 21.84 | 54 | 0.661172 | 994,974 | import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Deck {
private static int min = 2;
private static int max = 11;
private static Random rand = new Random();
// This will draw a random card with values from 2-11
public static int drawCard() {
return rand.nextInt((max - min) + 1) + min;
}
public static List<Integer> drawCards(int n) {
List<Integer> cards = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
cards.add(rand.nextInt((max - min) + 1) + min);
}
return cards;
}
}
|
922f0f9b203ed7862b68fd51ddd9b6a1896de47d | 4,428 | java | Java | src/jokrey/utilities/encoder/tag_based/tests/serialization/full/ObjectEncoderFullTest.java | jokrey/utility-algorithms-java | efc66376bac33ff3ac1ee25c5d3afeeda42d7e0f | [
"MIT"
] | null | null | null | src/jokrey/utilities/encoder/tag_based/tests/serialization/full/ObjectEncoderFullTest.java | jokrey/utility-algorithms-java | efc66376bac33ff3ac1ee25c5d3afeeda42d7e0f | [
"MIT"
] | null | null | null | src/jokrey/utilities/encoder/tag_based/tests/serialization/full/ObjectEncoderFullTest.java | jokrey/utility-algorithms-java | efc66376bac33ff3ac1ee25c5d3afeeda42d7e0f | [
"MIT"
] | null | null | null | 50.896552 | 176 | 0.748645 | 994,975 | package jokrey.utilities.encoder.tag_based.tests.serialization.full;
import jokrey.utilities.encoder.EncodableAsBytes;
import jokrey.utilities.encoder.EncodableAsString;
import jokrey.utilities.encoder.tag_based.TagBasedEncoder;
import jokrey.utilities.encoder.tag_based.implementation.paired.length_indicator.bytes.LITagBytesEncoder;
import jokrey.utilities.encoder.tag_based.implementation.paired.length_indicator.serialization.LIObjectEncoderFull;
import jokrey.utilities.encoder.tag_based.implementation.paired.length_indicator.string.LITagStringEncoder;
import jokrey.utilities.encoder.tag_based.serialization.field.full.ObjectEncoderFull;
import jokrey.utilities.encoder.tag_based.tests.serialization.beanish.TestBeanObject;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
/**
* @author jokrey
*/
public class ObjectEncoderFullTest {
private TestFullObject o = new TestFullObject(-1233, 945783945789866557L, TestBeanObject.getRandomizedExample(), true);
@Test
public void full_serialize_test_en_use__de_use() throws InstantiationException, IllegalAccessException {
full_serializer_test_helper(LITagStringEncoder.class, true);
full_serializer_test_helper(LITagStringEncoder.class, o);
full_serializer_test_helper(LITagStringEncoder.class, "string test");
full_serializer_test_helper(LITagStringEncoder.class, 17357);
full_serializer_test_helper(LITagStringEncoder.class, new String[][] {{""}, {}, {"test", "hello"}});
String e = LIObjectEncoderFull.serialize_as_str(o);
TestFullObject r = LIObjectEncoderFull.deserialize(e, TestFullObject.class);
assertEquals(o, r);
}
@Test
public void full_serialize_test_en_litbe__de_use() throws InstantiationException, IllegalAccessException {
full_serializer_test_helper(LITagBytesEncoder.class, true);
}
@Test
public void full_serialize_test_en_use__de_litbe() throws InstantiationException, IllegalAccessException {
full_serializer_test_helper(LITagStringEncoder.class, false);
}
@Test
public void full_serialize_test_en_litbe__de_litbe() throws InstantiationException, IllegalAccessException {
full_serializer_test_helper(LITagBytesEncoder.class, false);
full_serializer_test_helper(LITagBytesEncoder.class, o);
full_serializer_test_helper(LITagStringEncoder.class, o);
full_serializer_test_helper(LITagStringEncoder.class, "string test");
full_serializer_test_helper(LITagStringEncoder.class, 17357);
full_serializer_test_helper(LITagStringEncoder.class, new String[][] {{""}, {}, {"test", "hello"}});
byte[] e = LIObjectEncoderFull.serialize(o);
TestFullObject r = LIObjectEncoderFull.deserialize(e, TestFullObject.class);
assertEquals(o, r);
}
private void full_serializer_test_helper(Class<? extends TagBasedEncoder> encoder_class_used, boolean decode_string) throws IllegalAccessException, InstantiationException {
TagBasedEncoder encoder = ObjectEncoderFull.serialize(encoder_class_used.newInstance(), o);
if(decode_string) {
TagBasedEncoder decoder = EncodableAsString.createFromEncodedString(encoder.getEncodedString(), encoder_class_used);
TestFullObject r = ObjectEncoderFull.deserialize(decoder, TestFullObject.class);
assertEquals(o, r);
} else {
TagBasedEncoder decoder = EncodableAsBytes.createFromEncodedBytes(encoder.getEncodedBytes(), encoder_class_used);
TestFullObject r = ObjectEncoderFull.deserialize(decoder, TestFullObject.class);
assertEquals(o, r);
}
}
@SuppressWarnings("unchecked")
private<SF> void full_serializer_test_helper(Class<? extends TagBasedEncoder<SF>> encoder_class_used, Object orig) throws IllegalAccessException, InstantiationException {
SF encoded = (SF) ObjectEncoderFull.serialize(encoder_class_used, orig).getEncoded();
Object r = ObjectEncoderFull.deserialize(encoded, encoder_class_used, orig.getClass());
try {
assertEquals(orig, r);
} catch(AssertionError e) {
try {
assertArrayEquals((Object[]) orig, (Object[]) r);
} catch(AssertionError e2) {
e.printStackTrace();
throw e2;
}
}
}
}
|
922f10241e7b1f76036d130a582d870d2aa9fc82 | 5,119 | java | Java | src/main/java/igentuman/ncsteamadditions/machine/block/BlockNCSteamAdditionsProcessor.java | igentuman/nc-steam-additions | d105b90aeaadb1db21839dd3c9b9dcc35a064954 | [
"MIT"
] | 2 | 2022-01-18T00:52:04.000Z | 2022-01-20T23:47:35.000Z | src/main/java/igentuman/ncsteamadditions/machine/block/BlockNCSteamAdditionsProcessor.java | igentuman/nc-steam-additions | d105b90aeaadb1db21839dd3c9b9dcc35a064954 | [
"MIT"
] | 11 | 2021-12-11T16:13:41.000Z | 2022-02-11T18:44:11.000Z | src/main/java/igentuman/ncsteamadditions/machine/block/BlockNCSteamAdditionsProcessor.java | igentuman/nc-steam-additions | d105b90aeaadb1db21839dd3c9b9dcc35a064954 | [
"MIT"
] | null | null | null | 30.289941 | 174 | 0.756593 | 994,976 | package igentuman.ncsteamadditions.machine.block;
import static nc.block.property.BlockProperties.ACTIVE;
import static nc.block.property.BlockProperties.FACING_HORIZONTAL;
import java.util.Random;
import igentuman.ncsteamadditions.NCSteamAdditions;
import igentuman.ncsteamadditions.processors.ProcessorType;
import igentuman.ncsteamadditions.processors.AbstractProcessor;
import nc.block.property.BlockProperties;
import nc.block.tile.BlockSidedTile;
import nc.block.tile.IActivatable;
import nc.block.tile.ITileType;
import nc.init.NCItems;
import nc.tile.ITileGui;
import nc.tile.fluid.ITileFluid;
import nc.tile.processor.IProcessor;
import nc.tile.processor.IUpgradable;
import nc.util.BlockHelper;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fluids.FluidUtil;
import net.minecraftforge.fml.common.network.internal.FMLNetworkHandler;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class BlockNCSteamAdditionsProcessor extends BlockSidedTile implements IActivatable, ITileType
{
protected ProcessorType type;
public <T extends AbstractProcessor> BlockNCSteamAdditionsProcessor(T processor)
{
super(Material.IRON);
if (processor.getCreativeTab() != null)
setCreativeTab(processor.getCreativeTab());
this.type = processor.getType();
}
@Override
public String getTileName()
{
return type.getName();
}
@Override
public TileEntity createNewTileEntity(World world, int meta)
{
return type.getTile();
}
@Override
public IBlockState getStateFromMeta(int meta)
{
EnumFacing enumfacing = EnumFacing.values()[meta & 7];
if (enumfacing.getAxis() == EnumFacing.Axis.Y)
{
enumfacing = EnumFacing.NORTH;
}
return getDefaultState().withProperty(FACING_HORIZONTAL, enumfacing).withProperty(ACTIVE,
Boolean.valueOf((meta & 8) > 0));
}
@Override
public int getMetaFromState(IBlockState state)
{
int i = state.getValue(FACING_HORIZONTAL).getIndex();
if (state.getValue(ACTIVE).booleanValue())
i |= 8;
return i;
}
@Override
protected BlockStateContainer createBlockState()
{
return new BlockStateContainer(this, new IProperty[] { FACING_HORIZONTAL, ACTIVE});
}
public IBlockState getStateForPlacement(World world, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer, EnumHand hand) {
return this.getDefaultState().withProperty(BlockProperties.FACING_HORIZONTAL, placer.getHorizontalFacing().getOpposite()).withProperty(BlockProperties.ACTIVE, false);
}
@Override
public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand,
EnumFacing facing, float hitX, float hitY, float hitZ)
{
if (player == null || hand != EnumHand.MAIN_HAND)
return false;
TileEntity tile = world.getTileEntity(pos);
if (tile instanceof IUpgradable)
{
if (installUpgrade(tile, ((IUpgradable) tile).getSpeedUpgradeSlot(), player, hand, facing,
new ItemStack(NCItems.upgrade, 1, 0)))
return true;
}
if (player.isSneaking())
return false;
if (!(tile instanceof ITileFluid) && !(tile instanceof ITileGui))
return false;
if (tile instanceof ITileFluid && !(tile instanceof ITileGui)
&& FluidUtil.getFluidHandler(player.getHeldItem(hand)) == null)
return false;
if (tile instanceof ITileFluid)
{
if (world.isRemote)
return true;
ITileFluid tileFluid = (ITileFluid) tile;
boolean accessedTanks = BlockHelper.accessTanks(player, hand, facing, tileFluid);
if (accessedTanks)
{
if (tile instanceof IProcessor)
{
((IProcessor) tile).refreshRecipe();
((IProcessor) tile).refreshActivity();
}
return true;
}
}
if (tile instanceof ITileGui)
{
if (world.isRemote)
{
onGuiOpened(world, pos);
return true;
}
else
{
onGuiOpened(world, pos);
if (tile instanceof IProcessor)
{
((IProcessor) tile).refreshRecipe();
((IProcessor) tile).refreshActivity();
}
FMLNetworkHandler.openGui(player, NCSteamAdditions.instance, ((ITileGui) tile).getGuiID(), world, pos.getX(),
pos.getY(), pos.getZ());
}
}
else
return false;
return true;
}
@Override
@SideOnly(Side.CLIENT)
public void randomDisplayTick(IBlockState state, World world, BlockPos pos, Random rand)
{
if (!state.getValue(ACTIVE))
return;
BlockHelper.spawnParticleOnProcessor(state, world, pos, rand, state.getValue(FACING_HORIZONTAL),
type.getParticle1());
BlockHelper.spawnParticleOnProcessor(state, world, pos, rand, state.getValue(FACING_HORIZONTAL),
type.getParticle2());
}
} |
922f12c6e11c6dc46671ccce4d036a6b9412d238 | 15,646 | java | Java | src/main/java/ru/mecotrade/kidtracker/device/DeviceManager.java | mecotrade/kidtracker | f927eb53a0f923d536e87a084fb1dfb4563b1558 | [
"Apache-2.0"
] | 9 | 2021-01-22T22:00:13.000Z | 2021-12-22T07:58:36.000Z | src/main/java/ru/mecotrade/kidtracker/device/DeviceManager.java | mecotrade/kidtracker | f927eb53a0f923d536e87a084fb1dfb4563b1558 | [
"Apache-2.0"
] | 4 | 2020-10-21T06:57:30.000Z | 2021-11-30T21:25:37.000Z | src/main/java/ru/mecotrade/kidtracker/device/DeviceManager.java | mecotrade/kidtracker | f927eb53a0f923d536e87a084fb1dfb4563b1558 | [
"Apache-2.0"
] | 5 | 2021-04-16T09:37:17.000Z | 2022-02-14T17:44:20.000Z | 41.194737 | 164 | 0.626166 | 994,977 | /*
* Copyright 2020 Sergey Shadchin (ychag@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 ru.mecotrade.kidtracker.device;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;
import ru.mecotrade.kidtracker.dao.model.DeviceInfo;
import ru.mecotrade.kidtracker.dao.model.KidInfo;
import ru.mecotrade.kidtracker.dao.model.Media;
import ru.mecotrade.kidtracker.dao.service.DeviceService;
import ru.mecotrade.kidtracker.dao.service.MessageService;
import ru.mecotrade.kidtracker.dao.model.Message;
import ru.mecotrade.kidtracker.dao.model.UserInfo;
import ru.mecotrade.kidtracker.exception.KidTrackerConfirmationException;
import ru.mecotrade.kidtracker.exception.KidTrackerConnectionException;
import ru.mecotrade.kidtracker.exception.KidTrackerException;
import ru.mecotrade.kidtracker.exception.KidTrackerParseException;
import ru.mecotrade.kidtracker.exception.KidTrackerUnknownDeviceException;
import ru.mecotrade.kidtracker.model.ChatMessage;
import ru.mecotrade.kidtracker.model.Command;
import ru.mecotrade.kidtracker.model.Report;
import ru.mecotrade.kidtracker.model.Status;
import ru.mecotrade.kidtracker.model.Temporal;
import ru.mecotrade.kidtracker.processor.MediaProcessor;
import ru.mecotrade.kidtracker.task.Cleanable;
import ru.mecotrade.kidtracker.task.Job;
import ru.mecotrade.kidtracker.task.UserToken;
import ru.mecotrade.kidtracker.util.MessageUtils;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
@Component
@Slf4j
public class DeviceManager implements MessageListener, Cleanable {
@Autowired
private MessageService messageService;
@Autowired
private DeviceService deviceService;
@Autowired
private MediaProcessor mediaProcessor;
@Autowired
private SimpMessagingTemplate simpMessagingTemplate;
@Value("${kidtracker.token.length}")
private int tokenLength;
@Value("${kidtracker.token.ttl.millis}")
private long tokenTtlMillis;
@Value("${kidtracker.device.job.ttl.millis}")
private long deviceJobTtlMillis;
@Value("${kidtracker.user.queue.report}")
private String userQueueReport;
@Value("${kidtracker.user.queue.chat}")
private String userQueueChat;
@Value("${kidtracker.user.queue.status}")
private String userQueueStatus;
private final Map<String, Device> devices = new ConcurrentHashMap<>();
private final Map<String, Temporal<DeviceJob>> deviceJobs = new ConcurrentHashMap<>();
private final Map<UserToken, Temporal<Job>> jobs = new ConcurrentHashMap<>();
private final Map<String, Set<String>> deviceUsers = new ConcurrentHashMap<>();
public void send(String deviceId, Command command) throws KidTrackerConnectionException {
Device device = devices.get(deviceId);
if (device != null) {
device.send(command);
} else {
throw new KidTrackerConnectionException(String.format("Device %s is not connected", deviceId));
}
}
public Message send(String deviceId, Command command, long timeout) throws KidTrackerConnectionException {
Device device = devices.get(deviceId);
if (device != null) {
return device.send(command, timeout);
} else {
throw new KidTrackerConnectionException(String.format("Device %s is not connected", deviceId));
}
}
@Override
public void onMessage(Message message, MessageConnector messageConnector) throws KidTrackerException {
String deviceId = message.getDeviceId();
Device device = devices.get(deviceId);
if (device == null) {
if (deviceService.exists(deviceId) || deviceJobs.containsKey(deviceId)) {
device = new Device(deviceId, message.getManufacturer(), messageConnector);
devices.put(deviceId, device);
log.info("[{}] New device by {} connected to [{}]", deviceId, message.getManufacturer(), messageConnector.getId());
onDevice(device);
} else {
log.warn("[{}] Unknown device by {} tries to connect to [{}] with message {}",
deviceId,
message.getManufacturer(),
messageConnector.getId(),
message);
return;
}
} else {
device.check(messageConnector);
}
message = messageService.save(message);
log.debug("[{}] >>> {}", messageConnector.getId(), message);
device.process(message);
process(message, device);
}
public Collection<Device> select(Collection<String> deviceIds) {
return devices.entrySet().stream()
.filter(e -> deviceIds.contains(e.getKey()))
.map(Map.Entry::getValue)
.collect(Collectors.toList());
}
public Date last(String deviceId) {
Device device = devices.get(deviceId);
return device != null ? device.getLast() : null;
}
public boolean isConnected(String deviceId) {
return devices.containsKey(deviceId);
}
public void executeOrApply(String deviceId, DeviceJob deviceJob) throws KidTrackerException {
Device device = devices.get(deviceId);
if (device != null) {
deviceJob.execute(device);
} else {
deviceJobs.put(deviceId, Temporal.of(deviceJob));
log.info("Device {} is offline, created welcome job", deviceId);
}
}
public void sendOrApply(String deviceId, Command command) throws KidTrackerException {
executeOrApply(deviceId, d -> d.send(command));
}
public void apply(UserInfo userInfo, String deviceId, Command command) throws KidTrackerException {
Device device = devices.get(deviceId);
if (device != null) {
UserToken userToken = UserToken.of(userInfo.getId(), RandomStringUtils.randomNumeric(tokenLength));
device.apply(userToken, command);
device.send(Command.of("SMS", userInfo.getPhone(), userToken.getToken()));
log.info("[{}] {} for {} is sent to user {}", deviceId, userToken, command, userInfo);
} else {
throw new KidTrackerUnknownDeviceException(deviceId);
}
}
public Message apply(UserInfo userInfo, String deviceId, Command command, long timeout) throws KidTrackerException {
Device device = devices.get(deviceId);
if (device != null) {
UserToken userToken = UserToken.of(userInfo.getId(), RandomStringUtils.randomNumeric(tokenLength));
device.apply(userToken, command, timeout);
Command smsCommand = Command.of("SMS", userInfo.getPhone(), userToken.getToken());
Message confirmation = device.send(smsCommand, timeout);
if (confirmation != null) {
log.info("[{}] {} for {} is sent to user {}", deviceId, userToken, command, userInfo);
return confirmation;
} else {
throw new KidTrackerConfirmationException(String.format("%s on device %s was not confirmed within %d milliseconds", smsCommand, deviceId, timeout));
}
} else {
throw new KidTrackerUnknownDeviceException(deviceId);
}
}
public void execute(UserToken userToken, String deviceId) throws KidTrackerException {
Device device = devices.get(deviceId);
if (device != null) {
device.execute(userToken, tokenTtlMillis);
} else {
throw new KidTrackerUnknownDeviceException(deviceId);
}
}
public void onDevice(Device device) throws KidTrackerException {
Temporal<DeviceJob> deviceJob = deviceJobs.get(device.getId());
if (deviceJob != null && System.currentTimeMillis() - deviceJob.getTimestamp().getTime() < deviceJobTtlMillis) {
deviceJob.getValue().execute(device);
deviceJobs.remove(device.getId());
}
}
public void remove(String deviceId) {
devices.remove(deviceId);
log.info("[{}] Device is removed from connected devices list", deviceId);
}
@Override
public void clean() {
devices.forEach((key, value) -> value.clean(tokenTtlMillis)
.forEach(u -> log.info("[{}] Obsolete job for {} has been removed", key, u)));
// remove obsolete welcome jobs
long millis = System.currentTimeMillis();
Collection<String> obsoleteWelcome = deviceJobs.entrySet().stream()
.filter(w -> millis - w.getValue().getTimestamp().getTime() > deviceJobTtlMillis)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
obsoleteWelcome.forEach(id -> {
deviceJobs.remove(id);
log.info("[{}] Obsolete welcome job has been removed", id);
});
// remove all not connected devices
Collection<String> closed = devices.values().stream().filter(Device::isClosed).map(Device::getId).collect(Collectors.toList());
closed.forEach(id -> {
devices.remove(id);
log.info("[{}] Device is offline and removed from connected device list", id);
});
}
public void alarmOff(String deviceId) {
Device device = devices.get(deviceId);
if (device != null) {
device.alarmOff();
}
}
public void notificationOff(String deviceId) {
Device device = devices.get(deviceId);
if (device != null) {
device.notificationOff();
}
}
public void subscribe(UserInfo userInfo) {
String username = userInfo.getUsername();
userInfo.getKids().forEach(k -> {
String deviceId = k.getDevice().getId();
Set<String> users = deviceUsers.computeIfAbsent(deviceId, id -> new HashSet<>());
if (users.contains(username)) {
log.warn("User {} tries to subscribe to device {} he or she already subscribed", username, deviceId);
} else {
users.add(username);
log.info("User {} successfully subscribed to device {}", username, deviceId);
}
});
}
public void unsubscribe(UserInfo userInfo) {
String username = userInfo.getUsername();
userInfo.getKids().forEach(k -> {
String deviceId = k.getDevice().getId();
if (deviceUsers.containsKey(deviceId)) {
Set<String> users = deviceUsers.get(deviceId);
if (users.remove(username)) {
log.info("User {} successfully unsubscribed from device {}", username, deviceId);
} else {
log.warn("User {} tried to unsubscribe from device {}, but he or she was not subscribed", username, deviceId);
}
if (users.isEmpty()) {
deviceUsers.remove(deviceId);
log.info("Device {} has no more subscribed users", deviceId);
}
} else {
log.warn("User {} tried to unsubscribe from device {}, but device has no subscribed users", username, deviceId);
}
});
}
public Report report(Device device) {
if (device.getLink() == null) {
synchronized (device) {
if (device.getLink() == null) {
Message message = messageService.last(device.getId(), Collections.singleton(MessageUtils.LINK_TYPE), Message.Source.DEVICE);
log.debug("[{}] Link not found, use historical message {}", device.getId(), message);
try {
device.setLink(MessageUtils.toLink(message));
} catch (KidTrackerParseException ex) {
log.warn("[{}] Unable to parse historical link message {}", device.getId(), message);
}
}
}
}
if (device.getLocation() == null) {
synchronized (device) {
if (device.getLocation() == null) {
Message message = messageService.last(device.getId(), MessageUtils.LOCATION_TYPES, Message.Source.DEVICE);
if (message != null) {
log.debug("[{}] Location not found, use historical message {}", device.getId(), message);
try {
device.setLocation(MessageUtils.toLocation(message));
} catch (KidTrackerParseException ex) {
log.warn("[{}] Unable to parse historical location message {}", device.getId(), message);
}
} else {
log.warn("[{}] Location not found, no historical data found, device location is undefined", device.getId());
}
}
}
}
return Report.builder()
.deviceId(device.getId())
.position(device.position())
.snapshot(device.snapshot())
.alarm(device.getAlarm().getValue())
.notification(device.getNotification().getValue())
.last(device.getLast())
.build();
}
public Collection<Report> reports(UserInfo userInfo) {
return select(userInfo.getKids().stream()
.map(KidInfo::getDevice)
.map(DeviceInfo::getId)
.collect(Collectors.toList())).stream()
.map(this::report)
.collect(Collectors.toList());
}
private void process(Message message, Device device) throws KidTrackerException {
Media media = mediaProcessor.process(message);
if (media != null) {
sendToUsers(message.getDeviceId(), userQueueChat, ChatMessage.of(media));
}
if (MessageUtils.REPORT_TYPES.contains(message.getType()) || MessageUtils.MEDIA_TYPES.contains(message.getType())) {
sendToUsers(device.getId(), userQueueReport, report(device));
}
sendToUsers(device.getId(), userQueueStatus, new Status(device.getId(), true, message.getTimestamp()));
}
private void sendToUsers(String deviceId, String queue, Object payload) {
deviceUsers.getOrDefault(deviceId, Collections.emptySet()).forEach(user -> {
try {
simpMessagingTemplate.convertAndSendToUser(user, queue, payload);
} catch (MessagingException ex) {
log.warn("[{}] Unable to send {} to {} for user {}", deviceId, payload, queue, user, ex);
}
});
}
}
|
922f12da56703f8b0037a87e3723890027ee9145 | 5,884 | java | Java | LimitedLibraryManagementSystem/test/limitedlibrarymanagementsystem/DBControllerTest.java | gbouzon/prog-patterns-finalproject | fcb9c4a3e9f283d05431f3b62bfd1e7beb7375fc | [
"MIT"
] | null | null | null | LimitedLibraryManagementSystem/test/limitedlibrarymanagementsystem/DBControllerTest.java | gbouzon/prog-patterns-finalproject | fcb9c4a3e9f283d05431f3b62bfd1e7beb7375fc | [
"MIT"
] | null | null | null | LimitedLibraryManagementSystem/test/limitedlibrarymanagementsystem/DBControllerTest.java | gbouzon/prog-patterns-finalproject | fcb9c4a3e9f283d05431f3b62bfd1e7beb7375fc | [
"MIT"
] | null | null | null | 38.710526 | 162 | 0.673861 | 994,978 | /*
* The MIT License
*
* Copyright 2021 Chilka Castro, Giuliana Bouzon.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package limitedlibrarymanagementsystem;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.time.LocalDate;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Test class to test controller methods (JUnit as required)
* Final Project for Programming Patterns course - Fall 2021.
* @author Chilka Castro, Giuliana Bouzon
*/
public class DBControllerTest {
private final Connection connection;
/**
* Constructor of the DBControllerTest
* @throws Exception exception thrown
*/
public DBControllerTest() throws Exception {
this.connection = DBConnection.getSingleInstance();
}
/**
* Test of addBook method, of class DBController.
*/
@Test
public void testAddBook() throws Exception {
//generating a random SN to avoid primary key errors
Book book = new Book("3223423432", new BookData("A Test Book", "Test Author", "Penguin", 8, 18.29, 0, LocalDate.now()));
DBController controller = new DBController(new View());
controller.addBook(book);
String query = "SELECT COUNT(*) AS total FROM BOOK";
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(query);
int result = rs.getInt("total");
//error when run this a second time since SN will be duplicated -> delete entry from book table
assertEquals(result, 33);
}
/**
* Test of issueBook method, of class DBController.
*/
@Test
public void testIssueBook() throws Exception {
Book book = new Book("3453535343", new BookData());
Student student = new Student("1940108", new StudentData());
DBController controller = new DBController(student, new View());
boolean expResult = false;
boolean result = controller.issueBook(book, student);
assertEquals(expResult, result);
}
/**
* Test of returnBook method, of class DBController.
*/
@Test (expected = Exception.class)
public void testReturnBook() throws Exception {
Book book = new Book("219831928319", new BookData());
Student student = new Student("1940108", new StudentData());
DBController controller = new DBController(student, new View());
controller.returnBook(book, student); //throws exception because book has not been borrowed therefore cannot be returned
}
/**
* Test of searchBookByTitle method, of class DBController.
*/
@Test(expected = Exception.class)
public void testSearchBookByTitle() throws Exception {
String title = "hello";
Student student = new Student("1940108", new StudentData());
DBController controller = new DBController(student, new View());
controller.searchBookByTitle(title);
}
/**
* Test of searchBookByAuthorName method, of class DBController.
*/
@Test(expected = Exception.class)
public void testSearchBookByAuthorName() throws Exception {
String name = "hello";
Student student = new Student("1940108", new StudentData());
DBController controller = new DBController(student, new View());
controller.searchBookByAuthorName(name);
}
/**
* Test of searchBookByPublisher method, of class DBController.
* @throws Exception
*/
@Test(expected = Exception.class)
public void testSearchBookByPublisher() throws Exception {
String publisher = "hello";
Student student = new Student("1940108", new StudentData());
DBController controller = new DBController(student, new View());
controller.searchBookByPublisher(publisher);
}
/**
* Test of borrow method, of class DBController.
*/
@Test()
public void testBorrow() throws Exception {
Book book = new Book("3453535343", new BookData());
Student student = new Student("1940108", new StudentData());
DBController controller = new DBController(student, new View());
boolean expResult = false;
boolean result = controller.borrow(book);
assertEquals(expResult, result);
}
/**
* Test of toReturn method, of class DBController.
*/
@Test
public void testToReturn() throws Exception {
Book book = new Book("219831928319", new BookData());
Student student = new Student("1940108", new StudentData());
DBController controller = new DBController(student, new View());
controller.borrow(book);
boolean expResult = true;
boolean result = controller.toReturn(book);
assertEquals(expResult, result);
}
} |
922f131d8a4d50ea51d9f29fd87f85c87dec74c6 | 2,366 | java | Java | src/main/java/org/olat/course/editor/importnodes/ImportCourseFile.java | oueya1479/OpenOLAT | eda7ea3a60cc833af2f41e70b439226d58bb04e5 | [
"Apache-2.0"
] | 1 | 2019-03-05T01:53:06.000Z | 2019-03-05T01:53:06.000Z | src/main/java/org/olat/course/editor/importnodes/ImportCourseFile.java | oueya1479/OpenOLAT | eda7ea3a60cc833af2f41e70b439226d58bb04e5 | [
"Apache-2.0"
] | 11 | 2020-04-23T18:02:12.000Z | 2020-07-13T19:05:18.000Z | src/main/java/org/olat/course/editor/importnodes/ImportCourseFile.java | oueya1479/OpenOLAT | eda7ea3a60cc833af2f41e70b439226d58bb04e5 | [
"Apache-2.0"
] | null | null | null | 24.484536 | 82 | 0.738526 | 994,979 | /**
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
package org.olat.course.editor.importnodes;
import java.util.ArrayList;
import java.util.List;
import org.olat.core.util.vfs.VFSItem;
/**
*
* Initial date: 8 oct. 2021<br>
* @author srosse, dycjh@example.com, http://www.frentix.com
*
*/
public class ImportCourseFile {
private boolean renamed;
private String renamedFilename;
private VFSItem targetItem;
private VFSItem originalItem;
private String courseFolderSubPath;
private ImportCourseFile parent;
private final List<ImportCourseFile> children = new ArrayList<>();
public ImportCourseFile(VFSItem originalItem) {
this.originalItem = originalItem;
}
public VFSItem getOriginalItem() {
return originalItem;
}
public VFSItem getTargetItem() {
return targetItem;
}
public void setTargetItem(VFSItem targetItem) {
this.targetItem = targetItem;
}
public boolean isRenamed() {
return renamed;
}
public void setRenamed(boolean renamed) {
this.renamed = renamed;
}
public String getRenamedFilename() {
return renamedFilename;
}
public void setRenamedFilename(String renamedFilename) {
this.renamedFilename = renamedFilename;
}
public String getCourseFolderSubPath() {
return courseFolderSubPath;
}
public void setCourseFolderSubPath(String courseFolderSubPath) {
this.courseFolderSubPath = courseFolderSubPath;
}
public ImportCourseFile getParent() {
return parent;
}
public void setParent(ImportCourseFile parent) {
this.parent = parent;
}
public List<ImportCourseFile> getChildren() {
return children;
}
}
|
922f139da49459f516a52dfb44892d446b0c9f29 | 1,121 | java | Java | rapidoid-integration-tests/src/test/java/org/rapidoid/docs/revproxy/Main.java | xwt-benchmarks/rapidoid | 26a41baee15bfba77dff84834b4db0f1affe85ed | [
"Apache-2.0"
] | null | null | null | rapidoid-integration-tests/src/test/java/org/rapidoid/docs/revproxy/Main.java | xwt-benchmarks/rapidoid | 26a41baee15bfba77dff84834b4db0f1affe85ed | [
"Apache-2.0"
] | null | null | null | rapidoid-integration-tests/src/test/java/org/rapidoid/docs/revproxy/Main.java | xwt-benchmarks/rapidoid | 26a41baee15bfba77dff84834b4db0f1affe85ed | [
"Apache-2.0"
] | null | null | null | 26.069767 | 75 | 0.706512 | 994,980 | /*-
* #%L
* rapidoid-integration-tests
* %%
* Copyright (C) 2014 - 2018 Nikolche Mihajlovski and contributors
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.rapidoid.docs.revproxy;
import org.rapidoid.http.Req;
import org.rapidoid.reverseproxy.Reverse;
import org.rapidoid.setup.App;
import org.rapidoid.setup.On;
public class Main {
public static void main(String[] args) {
App.bootstrap(args);
On.get("/a*").json(Req::uri);
Reverse.proxy("/g")
.roles("administrator")
.cacheTTL(1000)
.to("http://upstream1:8080", "http://upstream2:8080")
.add();
}
}
|
922f14526e0e59777c4399f9700b0e7c04566203 | 1,741 | java | Java | InversionOfControl/src/main/java/Everest/Framework/InversionOfControl/DI/ComponentProvider.java | chendjouCaleb/EverestFramework | 851c4d308938a48be485b91f29ec4313af028370 | [
"MIT"
] | null | null | null | InversionOfControl/src/main/java/Everest/Framework/InversionOfControl/DI/ComponentProvider.java | chendjouCaleb/EverestFramework | 851c4d308938a48be485b91f29ec4313af028370 | [
"MIT"
] | null | null | null | InversionOfControl/src/main/java/Everest/Framework/InversionOfControl/DI/ComponentProvider.java | chendjouCaleb/EverestFramework | 851c4d308938a48be485b91f29ec4313af028370 | [
"MIT"
] | null | null | null | 29.508475 | 110 | 0.731763 | 994,981 | package Everest.Framework.InversionOfControl.DI;
import Everest.Framework.Core.IComponentProvider;
import Everest.Framework.Core.IComponentScope;
import Everest.Framework.InversionOfControl.DI.Lookup.LookupEngine;
import Everest.Framework.InversionOfControl.DI.Lookup.RootComponentCache;
import Everest.Framework.InversionOfControl.DI.Lookup.ScopeComponentCache;
import java.util.List;
/**
* The default implementation of {@link IComponentProvider}.
* @see IComponentProvider
*
* @author Chendjou
* @version 1
* @since 01-05-2019
*/
public class ComponentProvider implements IComponentProvider {
private LookupEngine lookupEngine;
private RootComponentCache rootComponentCache;
private ComponentCollection components;
public ComponentProvider(ComponentCollection components) {
this.components = components;
rootComponentCache = new RootComponentCache();
this.lookupEngine = new LookupEngine(components, this, rootComponentCache, new ScopeComponentCache());
this.lookupEngine.addSingletonComponents();
}
@Override
public <T> T getComponent(Class<? extends T> type) {
return (T) lookupEngine.look(type);
}
public <T> T getComponent(String name, Class<? extends T> type) {
return (T) lookupEngine.look(name);
}
public Object getComponent(String name) {
return lookupEngine.look(name);
}
public <T> List<T> getComponents(Class<? extends T> type) {
return (List<T>) lookupEngine.lookComponents(type);
}
public IComponentScope createScope() {
return new ComponentScope(this, components, rootComponentCache);
}
public LookupEngine getLookupEngine() {
return lookupEngine;
}
}
|
922f156140eb77b286e2d9e4de3a5b7fc95afd75 | 2,490 | java | Java | addressbook/src/main/java/vasugiaddressbook/AddressBook.java | Vasugi14/4806_Lab6 | 1645a3b02641bfc9e0b626d99ff9d291f50ecb34 | [
"MIT"
] | null | null | null | addressbook/src/main/java/vasugiaddressbook/AddressBook.java | Vasugi14/4806_Lab6 | 1645a3b02641bfc9e0b626d99ff9d291f50ecb34 | [
"MIT"
] | null | null | null | addressbook/src/main/java/vasugiaddressbook/AddressBook.java | Vasugi14/4806_Lab6 | 1645a3b02641bfc9e0b626d99ff9d291f50ecb34 | [
"MIT"
] | null | null | null | 25.670103 | 92 | 0.626908 | 994,982 | package vasugiaddressbook;
import javax.persistence.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ArrayList;
import java.util.List;
@Entity
public class AddressBook implements PropertyChangeListener {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
PropertyChangeSupport pcs = new PropertyChangeSupport(this);
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "addressBook")
private List<BuddyInfo> buddies;
public AddressBook(int id) {
this.id = id;
this.buddies = new ArrayList<BuddyInfo>();
}
public AddressBook(){
}
public void setBuddies(List<BuddyInfo> buddies) {
this.buddies = buddies;
}
/**
* Add a buddy to the list
* @param buddy Buddy to be added to the list of buddies
*/
public void addBuddy(BuddyInfo buddy) {
this.buddies.add(buddy);
}
/**
*
* @return buddies. List of all the buddies in the address book
*/
public List<BuddyInfo> getBuddies(){
return buddies;
}
/**
*
* @param buddy Name of the buddy to be removed from the list of buddies
* @return true if the buddy is removed and flase if the buddy isn't in the list
*/
public Boolean removeBuddy(BuddyInfo buddy) {
return this.buddies.remove(buddy);
}
/**
*
* @param name Name of the buddy you would like to access
* @return The buddy matching the provided name
*/
public BuddyInfo getBuddy(String name) {
for (BuddyInfo buddy: buddies) {
if (buddy.getName().equals(name)) return buddy;
}
return null;
}
@Override
public String toString() {
String returnValue = "";
for (BuddyInfo buddy: buddies) {
returnValue += buddy.toString() + "\n";
}
return returnValue;
}
public int getId() {
return id;
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
System.out.println("Variation of " + evt.getPropertyName());
System.out.println("\t(" + evt.getOldValue() +
" -> " + evt.getNewValue() + ")");
System.out.println("Property in object " + evt.getSource());
}
public void addObserver(PropertyChangeListener l) {
pcs.addPropertyChangeListener("theProperty", l);
}
} |
922f1657f64387e9d8a40f2393219a0db24cc7da | 5,050 | java | Java | site/src/main/java/com/onehippo/gogreen/jaxrs/model/ProductRepresentation.java | gridi/GoGreen | 0e1d2dc8c04ba4e7bb24cb542d8b9ee94b393767 | [
"Apache-2.0"
] | null | null | null | site/src/main/java/com/onehippo/gogreen/jaxrs/model/ProductRepresentation.java | gridi/GoGreen | 0e1d2dc8c04ba4e7bb24cb542d8b9ee94b393767 | [
"Apache-2.0"
] | null | null | null | site/src/main/java/com/onehippo/gogreen/jaxrs/model/ProductRepresentation.java | gridi/GoGreen | 0e1d2dc8c04ba4e7bb24cb542d8b9ee94b393767 | [
"Apache-2.0"
] | null | null | null | 30.239521 | 106 | 0.673465 | 994,983 | /*
* Copyright 2010-2013 Hippo B.V. (http://www.onehippo.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 com.onehippo.gogreen.jaxrs.model;
import java.util.List;
import javax.jcr.RepositoryException;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import org.apache.commons.lang.ArrayUtils;
import org.hippoecm.hst.content.beans.standard.HippoResource;
import org.hippoecm.hst.content.rewriter.ContentRewriter;
import org.hippoecm.hst.core.container.ContainerConstants;
import org.hippoecm.hst.core.request.HstRequestContext;
import com.onehippo.gogreen.beans.Product;
import com.onehippo.gogreen.beans.compound.ImageSet;
@XmlRootElement(name = "product")
public class ProductRepresentation extends DocumentRepresentation {
private String productLink;
private double price;
private double rating;
private double votes;
private String[] categories;
private String image;
private String[] images;
private String smallThumbnail;
public ProductRepresentation(){}
public ProductRepresentation(HstRequestContext requestContext, ContentRewriter<String> contentRewriter){
super(requestContext, contentRewriter);
}
public ProductRepresentation represent(Product bean) throws RepositoryException {
super.represent(bean);
this.productLink = this.requestContext
.getHstLinkCreator()
.create(bean.getNode(), this.requestContext, ContainerConstants.MOUNT_ALIAS_SITE)
.toUrlForm(this.requestContext, true);
this.price = bean.getPrice();
this.rating = bean.getRating();
this.votes = bean.getVotes();
this.categories = (String []) ArrayUtils.clone(bean.getCategories());
this.image = buildImageLinkUrl(bean);
this.images = buildImageGalleryLinks(bean);
this.smallThumbnail = buildImageLinkUrl(bean, "hippogogreengallery:smallthumbnail");
return this;
}
@XmlElement(name="productLink")
public String getProductLink(){
return productLink;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public double getRating() {
return rating;
}
public void setRating(double rating) {
this.rating = rating;
}
public double getVotes() {
return votes;
}
public void setVotes(double votes) {
this.votes = votes;
}
@XmlElementWrapper(name="categories")
@XmlElements(@XmlElement(name="category"))
public String[] getCategories() {
return categories;
}
public String getImage(){
return image;
}
public String getSmallThumbnail() {
return smallThumbnail;
}
@XmlElementWrapper(name="images")
@XmlElements(@XmlElement(name="image"))
public String[] getImages() {
return images;
}
private String buildImageLinkUrl(Product product){
if (product.getMainImage() == null) {
return null;
}
return requestContext
.getHstLinkCreator()
.create(product.getMainImage().getNode(), this.requestContext, ContainerConstants.MOUNT_ALIAS_SITE)
.toUrlForm(this.requestContext, true);
}
private String buildImageLinkUrl(Product product, String relPath){
ImageSet imageSet = product.getMainImage();
if (imageSet == null) {
return null;
}
HippoResource imageResource = imageSet.getBean(relPath);
if (imageResource == null) {
return null;
}
return requestContext
.getHstLinkCreator()
.create(imageResource.getNode(), this.requestContext, ContainerConstants.MOUNT_ALIAS_SITE)
.toUrlForm(this.requestContext, true);
}
private String[] buildImageGalleryLinks(Product product){
List<ImageSet> images = product.getImages();
if (images == null) {
return null;
}
String[] imageUrls = new String[images.size()];
for(int i=0; i<images.size(); i++)
imageUrls[i] = requestContext
.getHstLinkCreator()
.create(images.get(i).getNode(), this.requestContext, ContainerConstants.MOUNT_ALIAS_SITE)
.toUrlForm(this.requestContext, true);
return imageUrls;
}
}
|
922f16701f302f4c2dd88ac24158161f8c1fae67 | 179 | java | Java | Let's Build a Game/src/com/tutorial/main/PauseState.java | braden-foxcroft/Braden-Manjot-Michael-Sean-Game | b4395425c45a5164a4b9ec6607006bab7a00d5d7 | [
"MIT"
] | null | null | null | Let's Build a Game/src/com/tutorial/main/PauseState.java | braden-foxcroft/Braden-Manjot-Michael-Sean-Game | b4395425c45a5164a4b9ec6607006bab7a00d5d7 | [
"MIT"
] | 2 | 2020-02-04T19:51:24.000Z | 2020-02-24T06:06:17.000Z | Let's Build a Game/src/com/tutorial/main/PauseState.java | braden-foxcroft/Braden-Manjot-Michael-Sean-Game | b4395425c45a5164a4b9ec6607006bab7a00d5d7 | [
"MIT"
] | 1 | 2021-05-11T22:19:33.000Z | 2021-05-11T22:19:33.000Z | 13.769231 | 66 | 0.681564 | 994,984 | package com.tutorial.main;
/**
* enum that is used to control what is displayed on the PauseMenu
* @author mdbuc
*
*/
public enum PauseState {
save(),
mainPause(),
quit();
}
|
922f1826d5ca50036cc5067ee301e9b6d0eb4872 | 5,015 | java | Java | bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/mobileanalytics/batchclient/internal/MobileAnalyticsBatchClientImpl.java | ort55555/ort | b3996ff4225b722cb3496a596af26a9e44a6ff89 | [
"Apache-2.0"
] | null | null | null | bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/mobileanalytics/batchclient/internal/MobileAnalyticsBatchClientImpl.java | ort55555/ort | b3996ff4225b722cb3496a596af26a9e44a6ff89 | [
"Apache-2.0"
] | null | null | null | bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/mobileanalytics/batchclient/internal/MobileAnalyticsBatchClientImpl.java | ort55555/ort | b3996ff4225b722cb3496a596af26a9e44a6ff89 | [
"Apache-2.0"
] | 1 | 2019-05-31T16:30:55.000Z | 2019-05-31T16:30:55.000Z | 34.115646 | 89 | 0.662213 | 994,985 | /*
* Copyright 2015 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.core.mobileanalytics.batchclient.internal;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.eclipse.core.mobileanalytics.batchclient.MobileAnalyticsBatchClient;
import com.amazonaws.handlers.AsyncHandler;
import com.amazonaws.services.mobileanalytics.AmazonMobileAnalyticsAsync;
import com.amazonaws.services.mobileanalytics.AmazonMobileAnalyticsAsyncClient;
import com.amazonaws.services.mobileanalytics.model.Event;
import com.amazonaws.services.mobileanalytics.model.PutEventsRequest;
import com.amazonaws.services.mobileanalytics.model.PutEventsResult;
/**
* An implementation of MobileAnalyticsBatchClient which uses a bounded queue
* for caching incoming events and a single-threaded service client for sending
* out event batches. It also guarantees that the events are sent in the same
* order as they are accepted by the client.
*/
public class MobileAnalyticsBatchClientImpl implements MobileAnalyticsBatchClient {
private static final int MIN_EVENT_BATCH_SIZE = 20;
private static final int MAX_QUEUE_SIZE = 500;
/**
* Mobile Analytics async client with a single background thread
*/
private final AmazonMobileAnalyticsAsync mobileAnalytics;
/**
* The x-amz-client-context header string to be included in every PutEvents
* request
*/
private final String clientContextString;
/**
* For caching incoming events for batching
*/
private final EventQueue eventQueue = new EventQueue();
/**
* To keep track of the on-going putEvents request and make sure only one
* request can be made at a time.
*/
private final AtomicBoolean isSendingPutEventsRequest = new AtomicBoolean(false);
public MobileAnalyticsBatchClientImpl(
AWSCredentialsProvider credentialsProvider,
String clientContextString) {
this.mobileAnalytics = new AmazonMobileAnalyticsAsyncClient(
credentialsProvider, Executors.newFixedThreadPool(1));
this.clientContextString = clientContextString;
}
@Override
public void putEvent(Event event) {
// we don't lock the queue when accepting incoming event, and the
// queue size is only a rough estimate.
int queueSize = eventQueue.size();
// keep the queue bounded
if (queueSize >= MAX_QUEUE_SIZE) {
tryDispatchAllEventsAsync();
return;
}
eventQueue.addToTail(event);
if (queueSize >= MIN_EVENT_BATCH_SIZE) {
tryDispatchAllEventsAsync();
}
}
@Override
public void flush() {
tryDispatchAllEventsAsync();
}
/**
* To make sure the order of the analytic events is preserved, this method
* call will immediately return if there is an ongoing PutEvents call.
*/
private void tryDispatchAllEventsAsync() {
boolean contentionDetected = this.isSendingPutEventsRequest
.getAndSet(true);
if (!contentionDetected) {
dispatchAllEventsAsync();
}
}
/**
* Only one thread can call this method at a time
*/
private void dispatchAllEventsAsync() {
final List<Event> eventsBatch = this.eventQueue.pollAllQueuedEvents();
mobileAnalytics.putEventsAsync(
new PutEventsRequest().withClientContext(clientContextString)
.withEvents(eventsBatch),
new AsyncHandler<PutEventsRequest, PutEventsResult>() {
@Override
public void onSuccess(PutEventsRequest arg0, PutEventsResult arg1) {
markRequestDone();
}
@Override
public void onError(Exception arg0) {
restoreEventsQueue(eventsBatch);
markRequestDone();
}
private void restoreEventsQueue(List<Event> failedBatch) {
MobileAnalyticsBatchClientImpl.this.eventQueue
.addToHead(failedBatch);
}
private void markRequestDone() {
MobileAnalyticsBatchClientImpl.this.isSendingPutEventsRequest
.set(false);
}
});
}
}
|
922f18d80524dfc24bd4719e6deea120972878e2 | 2,449 | java | Java | src/main/java/com/danifoldi/microbase/waterfall/WaterfallBasePlayer.java | DaniFoldi/microbase | 06d386a2bf39990a304c2d3e78fedd6db1560a2a | [
"MIT"
] | null | null | null | src/main/java/com/danifoldi/microbase/waterfall/WaterfallBasePlayer.java | DaniFoldi/microbase | 06d386a2bf39990a304c2d3e78fedd6db1560a2a | [
"MIT"
] | 6 | 2022-02-10T16:21:32.000Z | 2022-03-01T22:45:35.000Z | src/main/java/com/danifoldi/microbase/waterfall/WaterfallBasePlayer.java | DaniFoldi/microbase | 06d386a2bf39990a304c2d3e78fedd6db1560a2a | [
"MIT"
] | null | null | null | 31 | 146 | 0.719069 | 994,986 | package com.danifoldi.microbase.waterfall;
import com.danifoldi.microbase.BasePlayer;
import com.danifoldi.microbase.BaseServer;
import com.danifoldi.microbase.depend.PremiumVanishDepend;
import net.kyori.adventure.platform.bukkit.BukkitAudiences;
import net.kyori.adventure.platform.bungeecord.BungeeAudiences;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.connection.ProxiedPlayer;
@SuppressWarnings("ClassCanBeRecord")
public class WaterfallBasePlayer extends WaterfallBaseSender implements BasePlayer {
private final ProxiedPlayer player;
private final BungeeAudiences audience;
WaterfallBasePlayer(ProxiedPlayer player, BungeeAudiences audience) {
super(player, audience);
this.player = player;
this.audience = audience;
}
@Override
public boolean vanished() {
return PremiumVanishDepend.vanished(player.getUniqueId());
}
@Override
public int protocol() {
return player.getPendingConnection().getVersion();
}
@Override
public int ping() {
return player.getPing();
}
@Override
public String locale() {
return player.getLocale().getDisplayName();
}
@Override
public void run(String command) {
ProxyServer.getInstance().getPluginManager().dispatchCommand(player, command);
}
@Override
public void actionbar(String message) {
player.sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(message));
}
@Override
public void chat(String message) {
player.chat(message);
}
@Override
public void connect(BaseServer server) {
player.connect(ProxyServer.getInstance().getServerInfo(server.name()));
}
@Override
public BaseServer connectedTo() {
return new WaterfallBaseServer(player.getServer().getInfo(), audience);
}
@Override
public void title(String message, int fadeIn, int stay, int fadeOut) {
player.sendTitle(ProxyServer.getInstance().createTitle().title(new TextComponent(message)).fadeIn(fadeIn).stay(stay).fadeOut(fadeOut));
}
@Override
public void subtitle(String message, int fadeIn, int stay, int fadeOut) {
player.sendTitle(ProxyServer.getInstance().createTitle().subTitle(new TextComponent(message)).fadeIn(fadeIn).stay(stay).fadeOut(fadeOut));
}
}
|
922f1a7ce17d06108f844d68b52126ed98ef4d89 | 7,446 | java | Java | jdk11/java.base/sun/text/UCompactIntArray.java | 1446554749/jdk_11_src_read | b9c070d7232ee3cf5f2f6270e748ada74cbabb3f | [
"Apache-2.0"
] | 543 | 2017-06-14T14:53:33.000Z | 2022-03-23T14:18:09.000Z | jdk/src/main/java/sun/text/UCompactIntArray.java | dibt/spring-framework | ce2dfa68e2331a07d36bdcf7aa92597c91a391ee | [
"Apache-2.0"
] | 381 | 2017-10-31T14:29:54.000Z | 2022-03-25T15:27:27.000Z | jdk/src/main/java/sun/text/UCompactIntArray.java | dibt/spring-framework | ce2dfa68e2331a07d36bdcf7aa92597c91a391ee | [
"Apache-2.0"
] | 50 | 2018-01-06T12:35:14.000Z | 2022-03-13T14:54:33.000Z | 36.145631 | 88 | 0.547139 | 994,987 | /*
* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.text;
public final class UCompactIntArray implements Cloneable {
/**
* Default constructor for UCompactIntArray, the default value of the
* compact array is 0.
*/
public UCompactIntArray() {
values = new int[16][];
indices = new short[16][];
blockTouched = new boolean[16][];
planeTouched = new boolean[16];
}
public UCompactIntArray(int defaultValue) {
this();
this.defaultValue = defaultValue;
}
/**
* Get the mapped value of a Unicode character.
* @param index the character to get the mapped value with
* @return the mapped value of the given character
*/
public int elementAt(int index) {
int plane = (index & PLANEMASK) >> PLANESHIFT;
if (!planeTouched[plane]) {
return defaultValue;
}
index &= CODEPOINTMASK;
return values[plane][(indices[plane][index >> BLOCKSHIFT] & 0xFFFF)
+ (index & BLOCKMASK)];
}
/**
* Set a new value for a Unicode character.
* Set automatically expands the array if it is compacted.
* @param index the character to set the mapped value with
* @param value the new mapped value
*/
public void setElementAt(int index, int value) {
if (isCompact) {
expand();
}
int plane = (index & PLANEMASK) >> PLANESHIFT;
if (!planeTouched[plane]) {
initPlane(plane);
}
index &= CODEPOINTMASK;
values[plane][index] = value;
blockTouched[plane][index >> BLOCKSHIFT] = true;
}
/**
* Compact the array.
*/
public void compact() {
if (isCompact) {
return;
}
for (int plane = 0; plane < PLANECOUNT; plane++) {
if (!planeTouched[plane]) {
continue;
}
int limitCompacted = 0;
int iBlockStart = 0;
short iUntouched = -1;
for (int i = 0; i < indices[plane].length; ++i, iBlockStart += BLOCKCOUNT) {
indices[plane][i] = -1;
if (!blockTouched[plane][i] && iUntouched != -1) {
// If no values in this block were set, we can just set its
// index to be the same as some other block with no values
// set, assuming we've seen one yet.
indices[plane][i] = iUntouched;
} else {
int jBlockStart = limitCompacted * BLOCKCOUNT;
if (i > limitCompacted) {
System.arraycopy(values[plane], iBlockStart,
values[plane], jBlockStart, BLOCKCOUNT);
}
if (!blockTouched[plane][i]) {
// If this is the first untouched block we've seen, remember it.
iUntouched = (short)jBlockStart;
}
indices[plane][i] = (short)jBlockStart;
limitCompacted++;
}
}
// we are done compacting, so now make the array shorter
int newSize = limitCompacted * BLOCKCOUNT;
int[] result = new int[newSize];
System.arraycopy(values[plane], 0, result, 0, newSize);
values[plane] = result;
blockTouched[plane] = null;
}
isCompact = true;
}
// --------------------------------------------------------------
// private
// --------------------------------------------------------------
/**
* Expanded takes the array back to a 0x10ffff element array
*/
private void expand() {
int i;
if (isCompact) {
int[] tempArray;
for (int plane = 0; plane < PLANECOUNT; plane++) {
if (!planeTouched[plane]) {
continue;
}
blockTouched[plane] = new boolean[INDEXCOUNT];
tempArray = new int[UNICODECOUNT];
for (i = 0; i < UNICODECOUNT; ++i) {
tempArray[i] = values[plane][indices[plane][i >> BLOCKSHIFT]
& 0xffff + (i & BLOCKMASK)];
blockTouched[plane][i >> BLOCKSHIFT] = true;
}
for (i = 0; i < INDEXCOUNT; ++i) {
indices[plane][i] = (short)(i<<BLOCKSHIFT);
}
values[plane] = tempArray;
}
isCompact = false;
}
}
private void initPlane(int plane) {
values[plane] = new int[UNICODECOUNT];
indices[plane] = new short[INDEXCOUNT];
blockTouched[plane] = new boolean[INDEXCOUNT];
planeTouched[plane] = true;
if (planeTouched[0] && plane != 0) {
System.arraycopy(indices[0], 0, indices[plane], 0, INDEXCOUNT);
} else {
for (int i = 0; i < INDEXCOUNT; ++i) {
indices[plane][i] = (short)(i<<BLOCKSHIFT);
}
}
for (int i = 0; i < UNICODECOUNT; ++i) {
values[plane][i] = defaultValue;
}
}
public int getKSize() {
int size = 0;
for (int plane = 0; plane < PLANECOUNT; plane++) {
if (planeTouched[plane]) {
size += (values[plane].length * 4 + indices[plane].length * 2);
}
}
return size / 1024;
}
private static final int PLANEMASK = 0x30000;
private static final int PLANESHIFT = 16;
private static final int PLANECOUNT = 0x10;
private static final int CODEPOINTMASK = 0xffff;
private static final int UNICODECOUNT = 0x10000;
private static final int BLOCKSHIFT = 7;
private static final int BLOCKCOUNT = (1<<BLOCKSHIFT);
private static final int INDEXSHIFT = (16-BLOCKSHIFT);
private static final int INDEXCOUNT = (1<<INDEXSHIFT);
private static final int BLOCKMASK = BLOCKCOUNT - 1;
private int defaultValue;
private int values[][];
private short indices[][];
private boolean isCompact;
private boolean[][] blockTouched;
private boolean[] planeTouched;
};
|
922f1a842154496de815ccc606b39e7c8928e7c5 | 2,397 | java | Java | src/main/java/net/ripe/rpki/ui/ca/CreateProductionCaPage.java | RIPE-NCC/rpki-core | cf6293bd0481e7f926c11a1237ee92e3dc3c1ea5 | [
"BSD-3-Clause"
] | 6 | 2022-02-09T09:59:08.000Z | 2022-02-16T19:17:39.000Z | src/main/java/net/ripe/rpki/ui/ca/CreateProductionCaPage.java | RIPE-NCC/rpki-core | cf6293bd0481e7f926c11a1237ee92e3dc3c1ea5 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/net/ripe/rpki/ui/ca/CreateProductionCaPage.java | RIPE-NCC/rpki-core | cf6293bd0481e7f926c11a1237ee92e3dc3c1ea5 | [
"BSD-3-Clause"
] | 1 | 2022-02-09T16:03:28.000Z | 2022-02-09T16:03:28.000Z | 39.295082 | 92 | 0.736754 | 994,988 | package net.ripe.rpki.ui.ca;
import net.ripe.rpki.commons.util.VersionedId;
import net.ripe.rpki.server.api.commands.CreateRootCertificateAuthorityCommand;
import net.ripe.rpki.server.api.services.command.CertificateAuthorityNameNotUniqueException;
import net.ripe.rpki.server.api.services.command.CommandService;
import net.ripe.rpki.server.api.services.system.ActiveNodeService;
import net.ripe.rpki.ui.admin.UpstreamCaManagementPage;
import net.ripe.rpki.ui.commons.AdminCertificationBasePage;
import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
public class CreateProductionCaPage extends AdminCertificationBasePage {
@SpringBean
private CommandService commandService;
@SpringBean
private ActiveNodeService activeNodeService;
public CreateProductionCaPage(PageParameters parameters) {
super("Create Production Certification Authority", parameters, false);
add(new FeedbackPanel("feedbackPanel"));
add(getCertificateAuthorityCreationForm());
}
private Form<CreateProductionCaPage> getCertificateAuthorityCreationForm() {
return new CreateCertificateAuthorityForm("createCertificateAuthorityForm");
}
@Override
protected String getPageTitle() {
return "Create Production Certification Authority";
}
private class CreateCertificateAuthorityForm extends Form<CreateProductionCaPage> {
private static final long serialVersionUID = 1L;
public CreateCertificateAuthorityForm(String id) {
super(id, new CompoundPropertyModel<>(CreateProductionCaPage.this));
}
@Override
protected void onSubmit() {
try {
VersionedId caId = commandService.getNextId();
commandService.execute(new CreateRootCertificateAuthorityCommand(caId));
activeNodeService.activateCurrentNode();
setResponsePage(UpstreamCaManagementPage.class);
} catch (CertificateAuthorityNameNotUniqueException ex) {
error(getString("certificateAuthority.name.notUnique"));
} catch (Exception ex) {
error(ex.getMessage());
}
}
}
}
|
922f1a8ef2c58704b90525baefe9705f350c8e2c | 229 | java | Java | src/cmdbproxy-manager/src/main/java/cn/gyyx/elves/cmdbproxy/service/ManagerService.java | elves-project/cmdbproxy | fd1de7d359c784550845162d27cc598092429774 | [
"Apache-2.0"
] | 2 | 2017-09-23T06:22:48.000Z | 2017-09-23T14:44:05.000Z | src/cmdbproxy-manager/src/main/java/cn/gyyx/elves/cmdbproxy/service/ManagerService.java | elves-project/cmdbproxy | fd1de7d359c784550845162d27cc598092429774 | [
"Apache-2.0"
] | null | null | null | src/cmdbproxy-manager/src/main/java/cn/gyyx/elves/cmdbproxy/service/ManagerService.java | elves-project/cmdbproxy | fd1de7d359c784550845162d27cc598092429774 | [
"Apache-2.0"
] | null | null | null | 16.357143 | 40 | 0.676856 | 994,989 | package cn.gyyx.elves.cmdbproxy.service;
import java.util.Map;
/**
* @Author : east.Fu
* @Description :
* @Date : Created in 2017/10/3 21:21
*/
public interface ManagerService {
public Map<String,Object> process();
}
|
922f1bcf28bcc37b013e5c4021203d4c35b33b6e | 1,358 | java | Java | vahub-model/src/main/java/com/acuity/visualisations/rawdatamodel/service/plots/vo/BarChartCalculationObject.java | digital-ECMT/acuity-vahub | 244eb7ec0f56cdac81ac6a8245ba2959b012b246 | [
"Apache-2.0"
] | 7 | 2022-01-25T18:12:19.000Z | 2022-03-22T18:31:08.000Z | vahub-model/src/main/java/com/acuity/visualisations/rawdatamodel/service/plots/vo/BarChartCalculationObject.java | digital-ECMT/acuity-vahub | 244eb7ec0f56cdac81ac6a8245ba2959b012b246 | [
"Apache-2.0"
] | null | null | null | vahub-model/src/main/java/com/acuity/visualisations/rawdatamodel/service/plots/vo/BarChartCalculationObject.java | digital-ECMT/acuity-vahub | 244eb7ec0f56cdac81ac6a8245ba2959b012b246 | [
"Apache-2.0"
] | 1 | 2022-03-28T15:20:09.000Z | 2022-03-28T15:20:09.000Z | 30.863636 | 76 | 0.776141 | 994,990 | /*
* Copyright 2021 The University of Manchester
*
* 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.acuity.visualisations.rawdatamodel.service.plots.vo;
import com.acuity.visualisations.rawdatamodel.vo.HasStringId;
import com.acuity.visualisations.rawdatamodel.vo.HasSubject;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.Collection;
import java.util.Set;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class BarChartCalculationObject<T extends HasStringId & HasSubject> {
@JsonIgnore
private Set<String> subjects;
@JsonIgnore
private Collection<T> eventSet;
@JsonIgnore
private Integer events;
private Double value;
private Integer totalSubject;
}
|
922f1cdc640f1e6f0fb7a737d4cf18c37546f1a1 | 38,330 | java | Java | src/com.mentor.nucleus.bp.core/src/com/mentor/nucleus/bp/core/CantHappen_c.java | hjjohny/editor | c85d3329f00327f2fd9010ab617c70e031ed5e00 | [
"Apache-2.0"
] | null | null | null | src/com.mentor.nucleus.bp.core/src/com/mentor/nucleus/bp/core/CantHappen_c.java | hjjohny/editor | c85d3329f00327f2fd9010ab617c70e031ed5e00 | [
"Apache-2.0"
] | 1 | 2015-09-11T07:14:45.000Z | 2015-09-11T07:14:45.000Z | src/com.mentor.nucleus.bp.core/src/com/mentor/nucleus/bp/core/CantHappen_c.java | hjjohny/editor | c85d3329f00327f2fd9010ab617c70e031ed5e00 | [
"Apache-2.0"
] | null | null | null | 33.622807 | 162 | 0.688782 | 994,991 | package com.mentor.nucleus.bp.core;
//====================================================================
//
// File: com.mentor.nucleus.bp.core.CantHappen_c.java
//
// WARNING: Do not edit this generated file
// Generated by ../MC-Java/java.arc, $Revision: 1.111 $
//
// (c) Copyright 2005-2014 by Mentor Graphics Corp. All rights reserved.
//
//====================================================================
// No special imports
import java.util.*;
import java.lang.reflect.*;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import com.mentor.nucleus.bp.core.util.PersistenceUtil;
import org.eclipse.core.runtime.NullProgressMonitor;
import com.mentor.nucleus.bp.core.ui.marker.UmlProblem;
import com.mentor.nucleus.bp.core.common.*;
abstract class EV_CANT_HAPPEN extends genericEvent_c {
public abstract int getEvtcode();
}
public class CantHappen_c extends NonRootModelElement
implements
IAdaptable,
Cloneable {
// Public Constructors
public CantHappen_c(ModelRoot modelRoot, java.util.UUID p_m_smstt_id,
java.util.UUID p_m_smevt_id, java.util.UUID p_m_sm_id,
java.util.UUID p_m_smspd_id, String p_m_descrip) {
super(modelRoot);
//pre-process the uuid so that we re-use null uuid instance rather then creating a new one.
m_smstt_id = IdAssigner.preprocessUUID(p_m_smstt_id);
//pre-process the uuid so that we re-use null uuid instance rather then creating a new one.
m_smevt_id = IdAssigner.preprocessUUID(p_m_smevt_id);
//pre-process the uuid so that we re-use null uuid instance rather then creating a new one.
m_sm_id = IdAssigner.preprocessUUID(p_m_sm_id);
//pre-process the uuid so that we re-use null uuid instance rather then creating a new one.
m_smspd_id = IdAssigner.preprocessUUID(p_m_smspd_id);
m_descrip = p_m_descrip;
Object[] key = {m_smspd_id, m_smevt_id, m_sm_id, m_smstt_id};
addInstanceToMap(key);
}
static public CantHappen_c createProxy(ModelRoot modelRoot,
java.util.UUID p_m_smstt_id, java.util.UUID p_m_smevt_id,
java.util.UUID p_m_sm_id, java.util.UUID p_m_smspd_id,
String p_m_descrip, String p_contentPath, IPath p_localPath) {
ModelRoot resolvedModelRoot = ModelRoot.findModelRoot(modelRoot,
p_contentPath, p_localPath);
// if a model root was not resolved it is most likely
// due to a missing file of the proxy, defualt back to
// the original model root
if (resolvedModelRoot != null)
modelRoot = resolvedModelRoot;
InstanceList instances = modelRoot.getInstanceList(CantHappen_c.class);
CantHappen_c new_inst = null;
synchronized (instances) {
Object[] key = {p_m_smspd_id, p_m_smevt_id, p_m_sm_id, p_m_smstt_id};
new_inst = (CantHappen_c) instances.get(key);
}
String contentPath = PersistenceUtil.resolveRelativePath(p_localPath,
new Path(p_contentPath));
if (modelRoot.isNewCompareRoot()) {
// for comparisons we do not want to change
// the content path
contentPath = p_contentPath;
}
if (new_inst != null && !modelRoot.isCompareRoot()) {
PersistableModelComponent pmc = new_inst.getPersistableComponent();
if (pmc == null) {
// dangling reference, redo this instance
new_inst.batchUnrelate();
//pre-process the uuid so that we re-use null uuid instance rather then creating a new one.
new_inst.m_smstt_id = IdAssigner.preprocessUUID(p_m_smstt_id);
//pre-process the uuid so that we re-use null uuid instance rather then creating a new one.
new_inst.m_smevt_id = IdAssigner.preprocessUUID(p_m_smevt_id);
//pre-process the uuid so that we re-use null uuid instance rather then creating a new one.
new_inst.m_sm_id = IdAssigner.preprocessUUID(p_m_sm_id);
//pre-process the uuid so that we re-use null uuid instance rather then creating a new one.
new_inst.m_smspd_id = IdAssigner.preprocessUUID(p_m_smspd_id);
new_inst.m_descrip = p_m_descrip;
}
}
if (new_inst == null) {
// there is no instance matching the id, create a proxy
// if the resource doesn't exist then this will be a dangling reference
new_inst = new CantHappen_c(modelRoot, p_m_smstt_id, p_m_smevt_id,
p_m_sm_id, p_m_smspd_id, p_m_descrip);
new_inst.m_contentPath = contentPath;
}
return new_inst;
}
static public CantHappen_c resolveInstance(ModelRoot modelRoot,
java.util.UUID p_m_smstt_id, java.util.UUID p_m_smevt_id,
java.util.UUID p_m_sm_id, java.util.UUID p_m_smspd_id,
String p_m_descrip) {
InstanceList instances = modelRoot.getInstanceList(CantHappen_c.class);
CantHappen_c source = null;
synchronized (instances) {
Object[] key = {p_m_smspd_id, p_m_smevt_id, p_m_sm_id, p_m_smstt_id};
source = (CantHappen_c) instances.get(key);
if (source != null && !modelRoot.isCompareRoot()) {
source.convertFromProxy();
source.batchUnrelate();
//pre-process the uuid so that we re-use null uuid instance rather then creating a new one.
source.m_smstt_id = IdAssigner.preprocessUUID(p_m_smstt_id);
//pre-process the uuid so that we re-use null uuid instance rather then creating a new one.
source.m_smevt_id = IdAssigner.preprocessUUID(p_m_smevt_id);
//pre-process the uuid so that we re-use null uuid instance rather then creating a new one.
source.m_sm_id = IdAssigner.preprocessUUID(p_m_sm_id);
//pre-process the uuid so that we re-use null uuid instance rather then creating a new one.
source.m_smspd_id = IdAssigner.preprocessUUID(p_m_smspd_id);
source.m_descrip = p_m_descrip;
return source;
}
}
// there is no instance matching the id
CantHappen_c new_inst = new CantHappen_c(modelRoot, p_m_smstt_id,
p_m_smevt_id, p_m_sm_id, p_m_smspd_id, p_m_descrip);
return new_inst;
}
public CantHappen_c(ModelRoot modelRoot) {
super(modelRoot);
m_smstt_id = IdAssigner.NULL_UUID;
m_smevt_id = IdAssigner.NULL_UUID;
m_sm_id = IdAssigner.NULL_UUID;
m_smspd_id = IdAssigner.NULL_UUID;
m_descrip = "";
Object[] key = {m_smspd_id, m_smevt_id, m_sm_id, m_smstt_id};
addInstanceToMap(key);
}
public Object getInstanceKey() {
Object[] key = {m_smspd_id, m_smevt_id, m_sm_id, m_smstt_id};
return key;
}
public boolean setInstanceKey(UUID p_newKey) {
boolean changed = false;
// round p1
// round p2
// round p3
// round p4
// round p5
if (m_smspd_id != p_newKey) {
m_smspd_id = p_newKey;
changed = true;
}
return changed;
}
public boolean equals(Object elem) {
if (!(elem instanceof CantHappen_c)) {
return false;
}
// check that the model-roots are the same
if (((NonRootModelElement) elem).getModelRoot() != getModelRoot()) {
return false;
}
return identityEquals(elem);
}
public boolean identityEquals(Object elem) {
if (!(elem instanceof CantHappen_c)) {
return false;
}
CantHappen_c me = (CantHappen_c) elem;
// don't allow an empty id-value to produce a false positive result;
// in this case, use whether the two instances are actually the same
// one in memory, instead
if ((IdAssigner.NULL_UUID.equals(getSmspd_id()) || IdAssigner.NULL_UUID
.equals(((CantHappen_c) elem).getSmspd_id())) && this != elem) {
return false;
}
if (!getSmspd_id().equals(((CantHappen_c) elem).getSmspd_id()))
return false;
// don't allow an empty id-value to produce a false positive result;
// in this case, use whether the two instances are actually the same
// one in memory, instead
if ((IdAssigner.NULL_UUID.equals(getSmevt_id()) || IdAssigner.NULL_UUID
.equals(((CantHappen_c) elem).getSmevt_id())) && this != elem) {
return false;
}
if (!getSmevt_id().equals(((CantHappen_c) elem).getSmevt_id()))
return false;
// don't allow an empty id-value to produce a false positive result;
// in this case, use whether the two instances are actually the same
// one in memory, instead
if ((IdAssigner.NULL_UUID.equals(getSm_id()) || IdAssigner.NULL_UUID
.equals(((CantHappen_c) elem).getSm_id())) && this != elem) {
return false;
}
if (!getSm_id().equals(((CantHappen_c) elem).getSm_id()))
return false;
// don't allow an empty id-value to produce a false positive result;
// in this case, use whether the two instances are actually the same
// one in memory, instead
if ((IdAssigner.NULL_UUID.equals(getSmstt_id()) || IdAssigner.NULL_UUID
.equals(((CantHappen_c) elem).getSmstt_id())) && this != elem) {
return false;
}
if (!getSmstt_id().equals(((CantHappen_c) elem).getSmstt_id()))
return false;
return true;
}
public boolean cachedIdentityEquals(Object elem) {
if (!(elem instanceof CantHappen_c)) {
return false;
}
CantHappen_c me = (CantHappen_c) elem;
if (!getSmspd_idCachedValue().equals(
((CantHappen_c) elem).getSmspd_idCachedValue()))
return false;
if (!getSmevt_idCachedValue().equals(
((CantHappen_c) elem).getSmevt_idCachedValue()))
return false;
if (!getSm_idCachedValue().equals(
((CantHappen_c) elem).getSm_idCachedValue()))
return false;
if (!getSmstt_idCachedValue().equals(
((CantHappen_c) elem).getSmstt_idCachedValue()))
return false;
return true;
}
// Attributes
private java.util.UUID m_smstt_id;
private java.util.UUID m_smevt_id;
private java.util.UUID m_sm_id;
private java.util.UUID m_smspd_id;
private String m_descrip;
// declare association references from this class
// referring navigation
StateEventMatrixEntry_c IsSupertypeStateEventMatrixEntry;
public void relateAcrossR504To(StateEventMatrixEntry_c target) {
relateAcrossR504To(target, true);
}
public void relateAcrossR504To(StateEventMatrixEntry_c target,
boolean notifyChanges) {
if (target == null)
return;
if (target == IsSupertypeStateEventMatrixEntry)
return; // already related
if (IsSupertypeStateEventMatrixEntry != target) {
Object oldKey = getInstanceKey();
if (IsSupertypeStateEventMatrixEntry != null) {
IsSupertypeStateEventMatrixEntry.clearBackPointerR504To(this);
if (Boolean.valueOf(System.getenv("PTC_MCC_ENABLED")) == true) { //$NON-NLS-1$
Ooaofooa.log
.println(
ILogger.CONSISTENCY,
"CantHappen_c.relateAcrossR504To(StateEventMatrixEntry_c target)",
"Relate performed across R504 from Cant Happen to State Event Matrix Entry without unrelate of prior instance.");
}
}
IsSupertypeStateEventMatrixEntry = target;
if (IdAssigner.NULL_UUID.equals(target.getSmstt_id())) {
// do not update cached value
} else {
// update cached value
m_smstt_id = target.getSmstt_idCachedValue();
}
if (IdAssigner.NULL_UUID.equals(target.getSmevt_id())) {
// do not update cached value
} else {
// update cached value
m_smevt_id = target.getSmevt_idCachedValue();
}
if (IdAssigner.NULL_UUID.equals(target.getSm_id())) {
// do not update cached value
} else {
// update cached value
m_sm_id = target.getSm_idCachedValue();
}
if (IdAssigner.NULL_UUID.equals(target.getSmspd_id())) {
// do not update cached value
} else {
// update cached value
m_smspd_id = target.getSmspd_idCachedValue();
}
updateInstanceKey(oldKey, getInstanceKey());
target.setBackPointerR504To(this);
target.addRef();
if (notifyChanges) {
RelationshipChangeModelDelta change = new RelationshipChangeModelDelta(
Modeleventnotification_c.DELTA_ELEMENT_RELATED, this,
target, "504", "");
Ooaofooa.getDefaultInstance().fireModelElementRelationChanged(
change);
}
}
}
public void unrelateAcrossR504From(StateEventMatrixEntry_c target) {
unrelateAcrossR504From(target, true);
}
public void unrelateAcrossR504From(StateEventMatrixEntry_c target,
boolean notifyChanges) {
if (target == null)
return;
if (IsSupertypeStateEventMatrixEntry == null)
return; // already unrelated
if (target != IsSupertypeStateEventMatrixEntry) {
Exception e = new Exception();
e.fillInStackTrace();
CorePlugin.logError(
"Tried to unrelate from non-related instance across R504",
e);
return;
}
if (target != null) {
target.clearBackPointerR504To(this);
}
if (IsSupertypeStateEventMatrixEntry != null) {
m_smstt_id = IsSupertypeStateEventMatrixEntry.getSmstt_id();
if (IdAssigner.NULL_UUID.equals(m_smstt_id)) {
m_smstt_id = IsSupertypeStateEventMatrixEntry
.getSmstt_idCachedValue();
}
m_smevt_id = IsSupertypeStateEventMatrixEntry.getSmevt_id();
if (IdAssigner.NULL_UUID.equals(m_smevt_id)) {
m_smevt_id = IsSupertypeStateEventMatrixEntry
.getSmevt_idCachedValue();
}
m_sm_id = IsSupertypeStateEventMatrixEntry.getSm_id();
if (IdAssigner.NULL_UUID.equals(m_sm_id)) {
m_sm_id = IsSupertypeStateEventMatrixEntry
.getSm_idCachedValue();
}
m_smspd_id = IsSupertypeStateEventMatrixEntry.getSmspd_id();
if (IdAssigner.NULL_UUID.equals(m_smspd_id)) {
m_smspd_id = IsSupertypeStateEventMatrixEntry
.getSmspd_idCachedValue();
}
IsSupertypeStateEventMatrixEntry = null;
target.removeRef();
if (notifyChanges) {
RelationshipChangeModelDelta change = new RelationshipChangeModelDelta(
Modeleventnotification_c.DELTA_ELEMENT_UNRELATED, this,
target, "504", "");
Ooaofooa.getDefaultInstance().fireModelElementRelationChanged(
change);
}
}
}
public static CantHappen_c getOneSM_CHOnR504(
StateEventMatrixEntry_c[] targets) {
return getOneSM_CHOnR504(targets, null);
}
public static CantHappen_c getOneSM_CHOnR504(
StateEventMatrixEntry_c[] targets, ClassQueryInterface_c test) {
CantHappen_c ret_val = null;
if (targets != null) {
for (int i = 0; i < targets.length && ret_val == null; ++i) {
ret_val = getOneSM_CHOnR504(targets[i], test);
}
}
return ret_val;
}
public static CantHappen_c getOneSM_CHOnR504(StateEventMatrixEntry_c target) {
return getOneSM_CHOnR504(target, null);
}
public static CantHappen_c getOneSM_CHOnR504(
StateEventMatrixEntry_c target, boolean loadComponent) {
return getOneSM_CHOnR504(target.getModelRoot(), target, null,
loadComponent);
}
public static CantHappen_c getOneSM_CHOnR504(
StateEventMatrixEntry_c target, ClassQueryInterface_c test) {
if (target != null) {
return getOneSM_CHOnR504(target.getModelRoot(), target, test);
}
return null;
}
public static CantHappen_c getOneSM_CHOnR504(ModelRoot modelRoot,
StateEventMatrixEntry_c target, ClassQueryInterface_c test) {
return getOneSM_CHOnR504(modelRoot, target, test, true);
}
public static CantHappen_c getOneSM_CHOnR504(ModelRoot modelRoot,
StateEventMatrixEntry_c target, ClassQueryInterface_c test,
boolean loadComponent) {
return find_getOneSM_CHOnR504(modelRoot, target, test);
}
private static CantHappen_c find_getOneSM_CHOnR504(ModelRoot modelRoot,
StateEventMatrixEntry_c target, ClassQueryInterface_c test) {
if (target != null) {
CantHappen_c source = (CantHappen_c) target.backPointer_IsSubtypeCantHappenIsSubtype_R504;
if (source != null && (test == null || test.evaluate(source))) {
return source;
}
}
// not found
return null;
}
public static CantHappen_c[] getManySM_CHsOnR504(
StateEventMatrixEntry_c[] targets) {
return getManySM_CHsOnR504(targets, null);
}
public static CantHappen_c[] getManySM_CHsOnR504(
StateEventMatrixEntry_c[] targets, boolean loadComponent) {
return getManySM_CHsOnR504(targets, null, loadComponent);
}
public static CantHappen_c[] getManySM_CHsOnR504(
StateEventMatrixEntry_c[] targets, ClassQueryInterface_c test) {
return getManySM_CHsOnR504(targets, test, true);
}
public static CantHappen_c[] getManySM_CHsOnR504(
StateEventMatrixEntry_c[] targets, ClassQueryInterface_c test,
boolean loadComponent) {
if (targets == null || targets.length == 0 || targets[0] == null)
return new CantHappen_c[0];
ModelRoot modelRoot = targets[0].getModelRoot();
InstanceList instances = modelRoot.getInstanceList(CantHappen_c.class);
Vector matches = new Vector();
for (int i = 0; i < targets.length; i++) {
CantHappen_c source = (CantHappen_c) targets[i].backPointer_IsSubtypeCantHappenIsSubtype_R504;
if (source != null && (test == null || test.evaluate(source))) {
matches.add(source);
}
}
if (matches.size() > 0) {
CantHappen_c[] ret_set = new CantHappen_c[matches.size()];
matches.copyInto(ret_set);
return ret_set;
} else {
return new CantHappen_c[0];
}
}
public static CantHappen_c[] getManySM_CHsOnR504(
StateEventMatrixEntry_c target) {
if (target != null) {
StateEventMatrixEntry_c[] targetArray = new StateEventMatrixEntry_c[1];
targetArray[0] = target;
return getManySM_CHsOnR504(targetArray);
} else {
CantHappen_c[] result = new CantHappen_c[0];
return result;
}
}
public static CantHappen_c[] getManySM_CHsOnR504(
StateEventMatrixEntry_c target, boolean loadComponent) {
if (target != null) {
StateEventMatrixEntry_c[] targetArray = new StateEventMatrixEntry_c[1];
targetArray[0] = target;
return getManySM_CHsOnR504(targetArray, loadComponent);
} else {
CantHappen_c[] result = new CantHappen_c[0];
return result;
}
}
public void batchRelate(ModelRoot modelRoot, boolean notifyChanges,
boolean searchAllRoots) {
batchRelate(modelRoot, false, notifyChanges, searchAllRoots);
}
public void batchRelate(ModelRoot modelRoot, boolean relateProxies,
boolean notifyChanges, boolean searchAllRoots) {
InstanceList instances = null;
ModelRoot baseRoot = modelRoot;
// R504
StateEventMatrixEntry_c relInst38694 = (StateEventMatrixEntry_c) baseRoot
.getInstanceList(StateEventMatrixEntry_c.class).get(
new Object[]{m_smspd_id, m_smevt_id, m_sm_id,
m_smstt_id});
// if there was no local element, check for any global elements
// failing that proceed to check other model roots
if (relInst38694 == null) {
relInst38694 = (StateEventMatrixEntry_c) Ooaofooa
.getDefaultInstance()
.getInstanceList(StateEventMatrixEntry_c.class)
.get(new Object[]{m_smspd_id, m_smevt_id, m_sm_id,
m_smstt_id});
}
if (relInst38694 == null && searchAllRoots && !baseRoot.isCompareRoot()) {
Ooaofooa[] roots = Ooaofooa.getInstances();
for (int i = 0; i < roots.length; i++) {
if (roots[i].isCompareRoot()) {
// never use elements from any compare root
continue;
}
relInst38694 = (StateEventMatrixEntry_c) roots[i]
.getInstanceList(StateEventMatrixEntry_c.class).get(
new Object[]{m_smspd_id, m_smevt_id, m_sm_id,
m_smstt_id});
if (relInst38694 != null)
break;
}
}
//synchronized
if (relInst38694 != null) {
if (relateProxies || !isProxy()
|| (inSameComponent(this, relInst38694) && !isProxy())) {
relInst38694.relateAcrossR504To(this, notifyChanges);
}
}
}
public void batchUnrelate(boolean notifyChanges) {
NonRootModelElement inst = null;
// R504
// SM_SEME
inst = IsSupertypeStateEventMatrixEntry;
unrelateAcrossR504From(IsSupertypeStateEventMatrixEntry, notifyChanges);
if (inst != null) {
inst.removeRef();
}
}
public static void batchRelateAll(ModelRoot modelRoot,
boolean notifyChanges, boolean searchAllRoots) {
batchRelateAll(modelRoot, notifyChanges, searchAllRoots, false);
}
public static void batchRelateAll(ModelRoot modelRoot, boolean notifyChanges, boolean searchAllRoots, boolean relateProxies)
{
InstanceList instances = modelRoot.getInstanceList(CantHappen_c.class);
synchronized(instances) {
Iterator<NonRootModelElement> cursor = instances.iterator() ;
while (cursor.hasNext())
{
final CantHappen_c inst = (CantHappen_c)cursor.next() ;
inst.batchRelate(modelRoot, relateProxies, notifyChanges, searchAllRoots );
}
}
}
public static void clearInstances(ModelRoot modelRoot) {
InstanceList instances = modelRoot.getInstanceList(CantHappen_c.class);
synchronized (instances) {
for (int i = instances.size() - 1; i >= 0; i--) {
((NonRootModelElement) instances.get(i)).delete_unchecked();
}
}
}
public static CantHappen_c CantHappenInstance(ModelRoot modelRoot,
ClassQueryInterface_c test, boolean loadComponent) {
CantHappen_c result = findCantHappenInstance(modelRoot, test,
loadComponent);
if (result == null && loadComponent) {
List pmcs = PersistenceManager.findAllComponents(modelRoot,
CantHappen_c.class);
for (int i = 0; i < pmcs.size(); i++) {
PersistableModelComponent component = (PersistableModelComponent) pmcs
.get(i);
if (!component.isLoaded()) {
try {
component.load(new NullProgressMonitor());
result = findCantHappenInstance(modelRoot, test,
loadComponent);
if (result != null)
return result;
} catch (Exception e) {
CorePlugin.logError("Error Loading component", e);
}
}
}
}
if (result != null && loadComponent) {
result.loadProxy();
}
return result;
}
private static CantHappen_c findCantHappenInstance(ModelRoot modelRoot,
ClassQueryInterface_c test, boolean loadComponent) {
InstanceList instances = modelRoot.getInstanceList(CantHappen_c.class);
synchronized (instances) {
for (int i = 0; i < instances.size(); ++i) {
CantHappen_c x = (CantHappen_c) instances.get(i);
if (test == null || test.evaluate(x)) {
if (x.ensureLoaded(loadComponent))
return x;
}
}
}
return null;
}
public static CantHappen_c CantHappenInstance(ModelRoot modelRoot,
ClassQueryInterface_c test) {
return CantHappenInstance(modelRoot, test, true);
}
public static CantHappen_c CantHappenInstance(ModelRoot modelRoot) {
return CantHappenInstance(modelRoot, null, true);
}
public static CantHappen_c[] CantHappenInstances(ModelRoot modelRoot,
ClassQueryInterface_c test, boolean loadComponent) {
if (loadComponent) {
PersistenceManager.ensureAllInstancesLoaded(modelRoot,
CantHappen_c.class);
}
InstanceList instances = modelRoot.getInstanceList(CantHappen_c.class);
Vector matches = new Vector();
synchronized (instances) {
for (int i = 0; i < instances.size(); ++i) {
CantHappen_c x = (CantHappen_c) instances.get(i);
if (test == null || test.evaluate(x)) {
if (x.ensureLoaded(loadComponent))
matches.add(x);
}
}
if (matches.size() > 0) {
CantHappen_c[] ret_set = new CantHappen_c[matches.size()];
matches.copyInto(ret_set);
return ret_set;
} else {
return new CantHappen_c[0];
}
}
}
public static CantHappen_c[] CantHappenInstances(ModelRoot modelRoot,
ClassQueryInterface_c test) {
return CantHappenInstances(modelRoot, test, true);
}
public static CantHappen_c[] CantHappenInstances(ModelRoot modelRoot) {
return CantHappenInstances(modelRoot, null, true);
}
public boolean delete() {
boolean result = super.delete();
boolean delete_error = false;
String errorMsg = "The following relationships were not torn down by the Cant Happen.dispose call: ";
StateEventMatrixEntry_c testR504Inst2 = StateEventMatrixEntry_c
.getOneSM_SEMEOnR504(this, false);
if (testR504Inst2 != null) {
delete_error = true;
errorMsg = errorMsg + "504 ";
}
if (delete_error == true) {
if (CorePlugin.getDefault().isDebugging()) {
Ooaofooa.log.println(ILogger.DELETE, "Cant Happen", errorMsg);
} else {
Exception e = new Exception();
e.fillInStackTrace();
CorePlugin.logError(errorMsg, e);
}
}
return result;
}
// end declare instance pool
// declare attribute accessors
public boolean isUUID(String attributeName) {
if (attributeName.equals("smstt_id")) {
return true;
}
if (attributeName.equals("smevt_id")) {
return true;
}
if (attributeName.equals("sm_id")) {
return true;
}
if (attributeName.equals("smspd_id")) {
return true;
}
return false;
}
public String getCompUniqueID() {
UUID tempID = null;
long longID = 0L;
StringBuffer result = new StringBuffer();
tempID = getSmspd_id();
if (IdAssigner.NULL_UUID.equals(tempID))
tempID = getSmspd_idCachedValue();
result.append(Long.toHexString(tempID.getMostSignificantBits()));
result.append(Long.toHexString(tempID.getLeastSignificantBits()));
tempID = getSmevt_id();
if (IdAssigner.NULL_UUID.equals(tempID))
tempID = getSmevt_idCachedValue();
result.append(Long.toHexString(tempID.getMostSignificantBits()));
result.append(Long.toHexString(tempID.getLeastSignificantBits()));
tempID = getSm_id();
if (IdAssigner.NULL_UUID.equals(tempID))
tempID = getSm_idCachedValue();
result.append(Long.toHexString(tempID.getMostSignificantBits()));
result.append(Long.toHexString(tempID.getLeastSignificantBits()));
tempID = getSmstt_id();
if (IdAssigner.NULL_UUID.equals(tempID))
tempID = getSmstt_idCachedValue();
result.append(Long.toHexString(tempID.getMostSignificantBits()));
result.append(Long.toHexString(tempID.getLeastSignificantBits()));
return result.toString();
}
// declare attribute accessors
public long getSmstt_idLongBased() {
if (IsSupertypeStateEventMatrixEntry != null) {
return IsSupertypeStateEventMatrixEntry.getSmstt_idLongBased();
}
return 0;
}
public java.util.UUID getSmstt_id() {
if (IsSupertypeStateEventMatrixEntry != null) {
return IsSupertypeStateEventMatrixEntry.getSmstt_id();
}
return IdAssigner.NULL_UUID;
}
public boolean hasSuperType() {
return (IsSupertypeStateEventMatrixEntry != null);
}
public java.util.UUID getSmstt_idCachedValue() {
if (!IdAssigner.NULL_UUID.equals(m_smstt_id))
return m_smstt_id;
else
return getSmstt_id();
}
public void setSmstt_id(java.util.UUID newValue) {
if (newValue != null) {
if (newValue.equals(m_smstt_id)) {
return;
}
} else if (m_smstt_id != null) {
if (m_smstt_id.equals(newValue)) {
return;
}
} else {
return;
}
AttributeChangeModelDelta change = new AttributeChangeModelDelta(
Modeleventnotification_c.DELTA_ATTRIBUTE_CHANGE, this,
"Smstt_id", m_smstt_id, newValue, true);
m_smstt_id = IdAssigner.preprocessUUID(newValue);
Ooaofooa.getDefaultInstance().fireModelElementAttributeChanged(change);
}
public long getSmevt_idLongBased() {
if (IsSupertypeStateEventMatrixEntry != null) {
return IsSupertypeStateEventMatrixEntry.getSmevt_idLongBased();
}
return 0;
}
public java.util.UUID getSmevt_id() {
if (IsSupertypeStateEventMatrixEntry != null) {
return IsSupertypeStateEventMatrixEntry.getSmevt_id();
}
return IdAssigner.NULL_UUID;
}
public java.util.UUID getSmevt_idCachedValue() {
if (!IdAssigner.NULL_UUID.equals(m_smevt_id))
return m_smevt_id;
else
return getSmevt_id();
}
public void setSmevt_id(java.util.UUID newValue) {
if (newValue != null) {
if (newValue.equals(m_smevt_id)) {
return;
}
} else if (m_smevt_id != null) {
if (m_smevt_id.equals(newValue)) {
return;
}
} else {
return;
}
AttributeChangeModelDelta change = new AttributeChangeModelDelta(
Modeleventnotification_c.DELTA_ATTRIBUTE_CHANGE, this,
"Smevt_id", m_smevt_id, newValue, true);
m_smevt_id = IdAssigner.preprocessUUID(newValue);
Ooaofooa.getDefaultInstance().fireModelElementAttributeChanged(change);
}
public long getSm_idLongBased() {
if (IsSupertypeStateEventMatrixEntry != null) {
return IsSupertypeStateEventMatrixEntry.getSm_idLongBased();
}
return 0;
}
public java.util.UUID getSm_id() {
if (IsSupertypeStateEventMatrixEntry != null) {
return IsSupertypeStateEventMatrixEntry.getSm_id();
}
return IdAssigner.NULL_UUID;
}
public java.util.UUID getSm_idCachedValue() {
if (!IdAssigner.NULL_UUID.equals(m_sm_id))
return m_sm_id;
else
return getSm_id();
}
public void setSm_id(java.util.UUID newValue) {
if (newValue != null) {
if (newValue.equals(m_sm_id)) {
return;
}
} else if (m_sm_id != null) {
if (m_sm_id.equals(newValue)) {
return;
}
} else {
return;
}
AttributeChangeModelDelta change = new AttributeChangeModelDelta(
Modeleventnotification_c.DELTA_ATTRIBUTE_CHANGE, this, "Sm_id",
m_sm_id, newValue, true);
m_sm_id = IdAssigner.preprocessUUID(newValue);
Ooaofooa.getDefaultInstance().fireModelElementAttributeChanged(change);
}
public long getSmspd_idLongBased() {
if (IsSupertypeStateEventMatrixEntry != null) {
return IsSupertypeStateEventMatrixEntry.getSmspd_idLongBased();
}
return 0;
}
public java.util.UUID getSmspd_id() {
if (IsSupertypeStateEventMatrixEntry != null) {
return IsSupertypeStateEventMatrixEntry.getSmspd_id();
}
return IdAssigner.NULL_UUID;
}
public java.util.UUID getSmspd_idCachedValue() {
if (!IdAssigner.NULL_UUID.equals(m_smspd_id))
return m_smspd_id;
else
return getSmspd_id();
}
public void setSmspd_id(java.util.UUID newValue) {
if (newValue != null) {
if (newValue.equals(m_smspd_id)) {
return;
}
} else if (m_smspd_id != null) {
if (m_smspd_id.equals(newValue)) {
return;
}
} else {
return;
}
AttributeChangeModelDelta change = new AttributeChangeModelDelta(
Modeleventnotification_c.DELTA_ATTRIBUTE_CHANGE, this,
"Smspd_id", m_smspd_id, newValue, true);
m_smspd_id = IdAssigner.preprocessUUID(newValue);
Ooaofooa.getDefaultInstance().fireModelElementAttributeChanged(change);
}
public String getDescrip() {
return m_descrip;
}
public void setDescrip(String newValue) {
if (newValue != null) {
if (newValue.equals(m_descrip)) {
return;
}
} else if (m_descrip != null) {
if (m_descrip.equals(newValue)) {
return;
}
} else {
return;
}
AttributeChangeModelDelta change = new AttributeChangeModelDelta(
Modeleventnotification_c.DELTA_ATTRIBUTE_CHANGE, this,
"Descrip", m_descrip, newValue, true);
m_descrip = newValue;
Ooaofooa.getDefaultInstance().fireModelElementAttributeChanged(change);
}
// end declare accessors
public static void checkClassConsistency(ModelRoot modelRoot) {
Ooaofooa.log.println(ILogger.OPERATION, "Cant Happen", //$NON-NLS-1$
" Operation entered: Cant Happen::checkClassConsistency"); //$NON-NLS-1$
if (Boolean.valueOf(System.getenv("PTC_MCC_ENABLED")) == false) { //$NON-NLS-1$
return;
}
CantHappen_c[] objs = CantHappen_c.CantHappenInstances(modelRoot, null,
false);
for (int i = 0; i < objs.length; i++) {
objs[i].checkConsistency();
}
}
public boolean checkConsistency() {
Ooaofooa.log.println(ILogger.OPERATION, "Cant Happen", //$NON-NLS-1$
" Operation entered: Cant Happen::checkConsistency"); //$NON-NLS-1$
if (Boolean.valueOf(System.getenv("PTC_MCC_ENABLED")) == false) { //$NON-NLS-1$
return true;
}
ModelRoot modelRoot = getModelRoot();
boolean retval = true;
class CantHappen_c_test38696_c implements ClassQueryInterface_c {
CantHappen_c_test38696_c(java.util.UUID p38697,
java.util.UUID p38698, java.util.UUID p38699,
java.util.UUID p38700) {
m_p38697 = p38697;
m_p38698 = p38698;
m_p38699 = p38699;
m_p38700 = p38700;
}
private java.util.UUID m_p38697;
private java.util.UUID m_p38698;
private java.util.UUID m_p38699;
private java.util.UUID m_p38700;
public boolean evaluate(Object candidate) {
CantHappen_c selected = (CantHappen_c) candidate;
boolean retval = false;
retval = (selected.getSmspd_id().equals(m_p38697))
& (selected.getSmevt_id().equals(m_p38698))
& (selected.getSm_id().equals(m_p38699))
& (selected.getSmstt_id().equals(m_p38700));
return retval;
}
}
CantHappen_c[] objs38695 = CantHappen_c.CantHappenInstances(modelRoot,
new CantHappen_c_test38696_c(getSmspd_id(), getSmevt_id(),
getSm_id(), getSmstt_id()));
if (((objs38695.length) == 0)) {
if (CorePlugin.getDefault().isDebugging()) {
Ooaofooa.log
.println(ILogger.CONSISTENCY,
"Cant Happen", //$NON-NLS-1$
"Consistency: Object: Cant Happen: Cardinality of an identifier is zero. " //$NON-NLS-1$
+ "Actual Value: " + Integer.toString(objs38695.length)); //$NON-NLS-1$
} else {
Exception e = new Exception();
CorePlugin.logError(
"Consistency: Object: Cant Happen: Cardinality of an identifier is zero. " //$NON-NLS-1$
+ "Actual Value: " //$NON-NLS-1$
+ Integer.toString(objs38695.length), e);
}
retval = false;
}
if (((objs38695.length) > 1)) {
if (CorePlugin.getDefault().isDebugging()) {
Ooaofooa.log
.println(ILogger.CONSISTENCY,
"Cant Happen", //$NON-NLS-1$
"Consistency: Object: Cant Happen: Cardinality of an identifier is greater than 1. " //$NON-NLS-1$
+ "Actual Value: " //$NON-NLS-1$
+ Integer.toString(objs38695.length)
+ " SMspd_ID: " + "Not Printable" + " SMevt_ID: " + "Not Printable" + " SM_ID: " + "Not Printable" + " SMstt_ID: " + "Not Printable"); //$NON-NLS-1$
} else {
Exception e = new Exception();
CorePlugin
.logError(
"Consistency: Object: Cant Happen: Cardinality of an identifier is greater than 1. " //$NON-NLS-1$
+ "Actual Value: " //$NON-NLS-1$
+ Integer.toString(objs38695.length)
+ " SMspd_ID: " + "Not Printable" + " SMevt_ID: " + "Not Printable" + " SM_ID: " + "Not Printable" + " SMstt_ID: " + "Not Printable", e); //$NON-NLS-1$
}
retval = false;
}
// Cant Happen is a subtype in association: rel.Numb = 504
// The supertype class is: State Event Matrix Entry
class StateEventMatrixEntry_c_test38704_c
implements
ClassQueryInterface_c {
StateEventMatrixEntry_c_test38704_c(java.util.UUID p38705,
java.util.UUID p38706, java.util.UUID p38707,
java.util.UUID p38708) {
m_p38705 = p38705;
m_p38706 = p38706;
m_p38707 = p38707;
m_p38708 = p38708;
}
private java.util.UUID m_p38705;
private java.util.UUID m_p38706;
private java.util.UUID m_p38707;
private java.util.UUID m_p38708;
public boolean evaluate(Object candidate) {
StateEventMatrixEntry_c selected = (StateEventMatrixEntry_c) candidate;
boolean retval = false;
retval = (selected.getSmstt_id().equals(m_p38705))
& (selected.getSmevt_id().equals(m_p38706))
& (selected.getSm_id().equals(m_p38707))
& (selected.getSmspd_id().equals(m_p38708));
return retval;
}
}
StateEventMatrixEntry_c[] objs38703 = StateEventMatrixEntry_c
.StateEventMatrixEntryInstances(modelRoot,
new StateEventMatrixEntry_c_test38704_c(getSmstt_id(),
getSmevt_id(), getSm_id(), getSmspd_id()));
if (((objs38703.length) != 1)) {
if (CorePlugin.getDefault().isDebugging()) {
Ooaofooa.log
.println(ILogger.CONSISTENCY,
"Cant Happen", //$NON-NLS-1$
"Consistency: Object: Cant Happen: Association: 504: Cardinality of a supertype is not equal to 1. " //$NON-NLS-1$
+ "Actual Value: " + Integer.toString(objs38703.length)); //$NON-NLS-1$
} else {
Exception e = new Exception();
CorePlugin
.logError(
"Consistency: Object: Cant Happen: Association: 504: Cardinality of a supertype is not equal to 1. " //$NON-NLS-1$
+ "Actual Value: " //$NON-NLS-1$
+ Integer.toString(objs38703.length), e);
}
retval = false;
}
return retval;
}
// declare transform functions
public String Get_name() {
Ooaofooa.log.println(ILogger.OPERATION, "Cant Happen",
" Operation entered: CantHappen::Get_name");
return "Can't Happen";
} // End get_name
public void Dispose() {
Ooaofooa.log.println(ILogger.OPERATION, "Cant Happen",
" Operation entered: CantHappen::Dispose");
final ModelRoot modelRoot = getModelRoot();
StateEventMatrixEntry_c v_seme = StateEventMatrixEntry_c
.getOneSM_SEMEOnR504(this);
if (((v_seme != null))) {
this.unrelateAcrossR504From(v_seme);
}
if (delete()) {
Ooaofooa.getDefaultInstance().fireModelElementDeleted(
new BaseModelDelta(Modeleventnotification_c.DELTA_DELETE,
this));
}
} // End dispose
public String Get_label() {
Ooaofooa.log.println(ILogger.OPERATION, "Cant Happen",
" Operation entered: CantHappen::Get_label");
final ModelRoot modelRoot = getModelRoot();
StateEventMatrixEntry_c v_seme = StateEventMatrixEntry_c
.getOneSM_SEMEOnR504(this);
if ((v_seme != null)) {
StateMachineEvent_c v_event = StateMachineEvent_c
.getOneSM_EVTOnR525(SemEvent_c.getOneSM_SEVTOnR503(v_seme));
StateMachineState_c v_state = StateMachineState_c
.getOneSM_STATEOnR503(v_seme);
if (((v_state != null) && (v_event != null))) {
return v_event.getDrv_lbl() + "/" + v_state.getName();
}
else {
return "";
}
}
else {
return "";
}
} // End get_label
// end transform functions
public Object getAdapter(Class adapter) {
Object superAdapter = super.getAdapter(adapter);
if (superAdapter != null) {
return superAdapter;
}
return null;
}
} // end Cant Happen
|
922f1d536f50422d4376d567e92a8423ff8f07dd | 1,363 | java | Java | app/src/main/java/com/recek/huewakeup/app/TimePickerFragment.java | Receks/HueSleepAndWake | 84b5e409dd1929150a2192be471882fb51c3ed7f | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | app/src/main/java/com/recek/huewakeup/app/TimePickerFragment.java | Receks/HueSleepAndWake | 84b5e409dd1929150a2192be471882fb51c3ed7f | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | app/src/main/java/com/recek/huewakeup/app/TimePickerFragment.java | Receks/HueSleepAndWake | 84b5e409dd1929150a2192be471882fb51c3ed7f | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | 29 | 90 | 0.682318 | 994,992 | package com.recek.huewakeup.app;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.os.Bundle;
import com.recek.huewakeup.util.AbsoluteTime;
import java.util.Calendar;
public class TimePickerFragment extends DialogFragment {
private TimePickerDialog.OnTimeSetListener onTimeSetListener;
private String timeString;
public void setTimeSetListener(TimePickerDialog.OnTimeSetListener onTimeSetListener) {
this.onTimeSetListener = onTimeSetListener;
}
public void setCurrentTime(String timeString) {
this.timeString = timeString;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AbsoluteTime absoluteTime = new AbsoluteTime(timeString);
int hour;
int minute;
if (absoluteTime.isValid) {
hour = absoluteTime.hours;
minute = absoluteTime.minutes;
} else {
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
}
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), onTimeSetListener, hour, minute,
// DateFormat.is24HourFormat(getActivity())
true
);
}
}
|
922f1d5a02e14e5422bcd736787ae263746f4ab3 | 1,000 | java | Java | subprojects/language-java/src/main/java/org/gradle/api/internal/tasks/compile/incremental/recomp/IncrementalCompilationResult.java | ALD110/gradle | d9adf33a57925582988fc512002dcc0e8ce4db95 | [
"Apache-2.0"
] | 2 | 2015-12-10T21:06:45.000Z | 2016-08-04T19:35:30.000Z | subprojects/language-java/src/main/java/org/gradle/api/internal/tasks/compile/incremental/recomp/IncrementalCompilationResult.java | ALD110/gradle | d9adf33a57925582988fc512002dcc0e8ce4db95 | [
"Apache-2.0"
] | null | null | null | subprojects/language-java/src/main/java/org/gradle/api/internal/tasks/compile/incremental/recomp/IncrementalCompilationResult.java | ALD110/gradle | d9adf33a57925582988fc512002dcc0e8ce4db95 | [
"Apache-2.0"
] | 1 | 2019-06-26T20:28:16.000Z | 2019-06-26T20:28:16.000Z | 34.482759 | 75 | 0.764 | 994,993 | /*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.internal.tasks.compile.incremental.recomp;
import org.gradle.api.tasks.WorkResult;
/**
* A marker interface for incremental compilation result.
*/
public interface IncrementalCompilationResult extends WorkResult {
WorkResult getCompilerResult();
PreviousCompilationData getPreviousCompilationData();
RecompilationSpec getRecompilationSpec();
}
|
922f1d9031f60d22eae9eb59970d125034242526 | 2,559 | java | Java | components/data-modeling-service/shared/api/src/main/java/de/buw/tmdt/plasma/services/dms/shared/dto/syntaxmodel/CompositeDTO.java | tmdt-buw/plasma | ce977d051bd1e8aa0d9de1f3280ba487fbabbae9 | [
"Apache-2.0"
] | 2 | 2020-12-17T19:07:37.000Z | 2022-03-16T09:21:40.000Z | components/data-modeling-service/shared/api/src/main/java/de/buw/tmdt/plasma/services/dms/shared/dto/syntaxmodel/CompositeDTO.java | tmdt-buw/plasma | ce977d051bd1e8aa0d9de1f3280ba487fbabbae9 | [
"Apache-2.0"
] | null | null | null | components/data-modeling-service/shared/api/src/main/java/de/buw/tmdt/plasma/services/dms/shared/dto/syntaxmodel/CompositeDTO.java | tmdt-buw/plasma | ce977d051bd1e8aa0d9de1f3280ba487fbabbae9 | [
"Apache-2.0"
] | 1 | 2020-12-27T20:52:32.000Z | 2020-12-27T20:52:32.000Z | 31.207317 | 94 | 0.762407 | 994,994 | package de.buw.tmdt.plasma.services.dms.shared.dto.syntaxmodel;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import de.buw.tmdt.plasma.services.dms.shared.dto.syntaxmodel.operation.SyntacticOperationDTO;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
@JsonTypeName("CompositeDTO")
public class CompositeDTO extends SchemaNodeDTO {
private static final long serialVersionUID = 5858068735685107958L;
private static final String SPLITTER_PROPERTY = "splitter";
private static final String CLEANSING_PATTERN_PROPERTY = "cleansingPattern";
private final List<SplitterDTO> splitter;
private final String cleansingPattern;
@JsonCreator
public CompositeDTO(
@Nullable @JsonProperty(X_COORDINATE_PROPERTY) Double xCoordinate,
@Nullable @JsonProperty(Y_COORDINATE_PROPERTY) Double yCoordinate,
@NotNull @JsonProperty(UUID_PROPERTY) UUID uuid,
@JsonProperty(LABEL_PROPERTY) @NotNull String label,
@NotNull @JsonProperty(OPERATIONS_PROPERTY) List<SyntacticOperationDTO> operations,
@JsonProperty(IS_VALID__PROPERTY) boolean isValid,
@NotNull @JsonProperty(CLEANSING_PATTERN_PROPERTY) String cleansingPattern,
@NotNull @JsonProperty(SPLITTER_PROPERTY) List<SplitterDTO> splitter
) {
super(xCoordinate, yCoordinate, uuid, label, operations, isValid);
this.cleansingPattern = cleansingPattern;
this.splitter = Collections.unmodifiableList(splitter);
}
@JsonProperty(CLEANSING_PATTERN_PROPERTY)
@NotNull
public String getCleansingPattern() {
return cleansingPattern;
}
@NotNull
@JsonProperty(SPLITTER_PROPERTY)
public List<SplitterDTO> getSplitter() {
return Collections.unmodifiableList(splitter);
}
@Override
@SuppressWarnings("MagicCharacter")
public String toString() {
return "{\"@class\":\"CompositeDTO\""
+ ", \"@super\":" + super.toString()
+ ", \"cleansingPattern\":\"" + cleansingPattern + '"'
+ '}';
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
CompositeDTO that = (CompositeDTO) o;
return Objects.equals(cleansingPattern, that.cleansingPattern);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), cleansingPattern);
}
}
|
922f1e734fd28eb3a69076206b02b866b10a8007 | 2,848 | java | Java | jenkins-scm-koji-plugin/src/main/java/hudson/plugins/scm/koji/KojiBuildProvider.java | RadoslavCap/jenkins-scm-koji-plugin | 79b3f72e7b2f031c9b5dce08b671da130ed9f7cb | [
"MIT"
] | null | null | null | jenkins-scm-koji-plugin/src/main/java/hudson/plugins/scm/koji/KojiBuildProvider.java | RadoslavCap/jenkins-scm-koji-plugin | 79b3f72e7b2f031c9b5dce08b671da130ed9f7cb | [
"MIT"
] | 6 | 2021-05-09T10:42:23.000Z | 2022-02-27T10:47:24.000Z | jenkins-scm-koji-plugin/src/main/java/hudson/plugins/scm/koji/KojiBuildProvider.java | RadoslavCap/jenkins-scm-koji-plugin | 79b3f72e7b2f031c9b5dce08b671da130ed9f7cb | [
"MIT"
] | null | null | null | 33.116279 | 117 | 0.666784 | 994,995 | package hudson.plugins.scm.koji;
import hudson.Extension;
import hudson.model.Describable;
import hudson.model.Descriptor;
import hudson.plugins.scm.koji.model.BuildProvider;
import hudson.util.FormValidation;
import jenkins.model.Jenkins;
import org.fakekoji.xmlrpc.server.JavaServerConstants;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import javax.annotation.Nonnull;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URL;
public class KojiBuildProvider implements Describable<KojiBuildProvider>, Serializable {
private final BuildProvider buildProvider;
@DataBoundConstructor
public KojiBuildProvider(String topUrl, String downloadUrl) {
buildProvider = new BuildProvider(replaceXPort(topUrl), replaceDPORT(downloadUrl));
}
@SuppressWarnings("unchecked")
@Override
public Descriptor<KojiBuildProvider> getDescriptor() {
return Jenkins.getActiveInstance().getDescriptorOrDie(getClass());
}
public BuildProvider getBuildProvider() {
return buildProvider;
}
private static String replaceDPORT(String url) {
return url.replace(
":" + JavaServerConstants.dPortAxiom,
":" + JavaServerConstants.DFAULT_DWNLD_PORT
);
}
private static String replaceXPort(String url) {
return url.replace(
":" + JavaServerConstants.xPortAxiom,
":" + JavaServerConstants.DFAULT_RP2C_PORT
);
}
@Extension
public static final class KojiBuildProviderDescriptor extends Descriptor<KojiBuildProvider> {
private static final String SUPPORTED_PROTOCOL = "HTTP";
private static final String URL_INVALID = "The URL is invalid";
private static final String PROTOCOL_NOT_SUPPORTED = "Only " + SUPPORTED_PROTOCOL + " protocol is supported";
@Nonnull
@Override
public String getDisplayName() {
return "Koji build provider";
}
FormValidation doCheckTopUrl(@QueryParameter String value) {
try {
new URL(replaceXPort(value));
} catch (MalformedURLException e) {
return FormValidation.error(URL_INVALID);
}
return FormValidation.ok();
}
FormValidation doCheckDownloadUrl(@QueryParameter String value) {
try {
final URL url = new URL(replaceDPORT(value));
if (!url.getProtocol().equals(SUPPORTED_PROTOCOL.toLowerCase())) {
return FormValidation.error(PROTOCOL_NOT_SUPPORTED);
}
} catch (MalformedURLException e) {
return FormValidation.error(URL_INVALID);
}
return FormValidation.ok();
}
}
}
|
922f1f4c328935e523f9f980aaf6a37ab307394d | 2,477 | java | Java | hapi-fhir-validation/src/main/java/org/hl7/fhir/common/hapi/validation/validator/HapiToHl7OrgDstu2ValidatingSupportWrapper.java | ShahimEssaid/hapi-fhir | 06030094c803deac725be5bf63e4d1ce7bb26b6d | [
"Apache-2.0"
] | 1,194 | 2015-01-01T23:22:15.000Z | 2020-12-12T19:27:42.000Z | hapi-fhir-validation/src/main/java/org/hl7/fhir/common/hapi/validation/validator/HapiToHl7OrgDstu2ValidatingSupportWrapper.java | ShahimEssaid/hapi-fhir | 06030094c803deac725be5bf63e4d1ce7bb26b6d | [
"Apache-2.0"
] | 1,994 | 2015-01-04T10:06:26.000Z | 2020-12-13T22:19:41.000Z | hapi-fhir-validation/src/main/java/org/hl7/fhir/common/hapi/validation/validator/HapiToHl7OrgDstu2ValidatingSupportWrapper.java | ShahimEssaid/hapi-fhir | 06030094c803deac725be5bf63e4d1ce7bb26b6d | [
"Apache-2.0"
] | 1,088 | 2015-01-04T19:31:43.000Z | 2020-12-12T20:56:04.000Z | 31.35443 | 123 | 0.788857 | 994,996 | package org.hl7.fhir.common.hapi.validation.validator;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.context.FhirVersionEnum;
import ca.uhn.fhir.context.support.IValidationSupport;
import org.apache.commons.lang3.Validate;
import org.hl7.fhir.common.hapi.validation.support.BaseValidationSupportWrapper;
import org.hl7.fhir.instance.model.api.IBaseResource;
import java.util.List;
import java.util.stream.Collectors;
public class HapiToHl7OrgDstu2ValidatingSupportWrapper extends BaseValidationSupportWrapper implements IValidationSupport {
private final FhirContext myHapiCtx;
/**
* Constructor
*/
public HapiToHl7OrgDstu2ValidatingSupportWrapper(IValidationSupport theWrap) {
super(FhirContext.forDstu2Hl7Org(), theWrap);
Validate.isTrue(theWrap.getFhirContext().getVersion().getVersion() == FhirVersionEnum.DSTU2);
myHapiCtx = theWrap.getFhirContext();
}
@Override
public List<IBaseResource> fetchAllConformanceResources() {
return super.fetchAllConformanceResources();
}
@Override
public List<IBaseResource> fetchAllStructureDefinitions() {
return super
.fetchAllStructureDefinitions()
.stream()
.map(t -> translate(t))
.collect(Collectors.toList());
}
@Override
public <T extends IBaseResource> T fetchResource(Class<T> theClass, String theUri) {
Class<? extends IBaseResource> type = translateTypeToHapi(theClass);
IBaseResource output = super.fetchResource(type, theUri);
return theClass.cast(translate(output));
}
@Override
public IBaseResource fetchCodeSystem(String theSystem) {
IBaseResource output = super.fetchCodeSystem(theSystem);
return translate(output);
}
@Override
public IBaseResource fetchValueSet(String theUri) {
return translate(super.fetchValueSet(theUri));
}
@Override
public IBaseResource fetchStructureDefinition(String theUrl) {
return translate(super.fetchStructureDefinition(theUrl));
}
private Class<? extends IBaseResource> translateTypeToHapi(Class<? extends IBaseResource> theCodeSystemType) {
if (theCodeSystemType == null) {
return null;
}
String resName = getFhirContext().getResourceType(theCodeSystemType);
return myHapiCtx.getResourceDefinition(resName).getImplementingClass();
}
private IBaseResource translate(IBaseResource theInput) {
if (theInput == null) {
return null;
}
String encoded = myHapiCtx.newJsonParser().encodeResourceToString(theInput);
return getFhirContext().newJsonParser().parseResource(encoded);
}
}
|
922f20c2e6e2f0ea1846111dcd78d9c1f2d26cc1 | 786 | java | Java | src/test/java/test/service/TestAttendance.java | yan123zi/PersonManager | a2bd8a70978ce0bf2bca410594d8e14a8caf49d6 | [
"Apache-2.0"
] | null | null | null | src/test/java/test/service/TestAttendance.java | yan123zi/PersonManager | a2bd8a70978ce0bf2bca410594d8e14a8caf49d6 | [
"Apache-2.0"
] | 4 | 2020-03-05T00:20:06.000Z | 2021-12-09T22:00:43.000Z | src/test/java/test/service/TestAttendance.java | yan123zi/PersonManager | a2bd8a70978ce0bf2bca410594d8e14a8caf49d6 | [
"Apache-2.0"
] | 1 | 2022-03-22T14:38:23.000Z | 2022-03-22T14:38:23.000Z | 31.44 | 75 | 0.834606 | 994,997 | package test.service;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.pxxy.personManagement.domain.Attendance;
import com.pxxy.personManagement.service.AdminAttendanceService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:config/spring-context.xml"})
public class TestAttendance {
@Autowired
private AdminAttendanceService adminAttendanceService;
@Test
public void testAttenByEmp() {
List<Attendance> attenForEmp = adminAttendanceService.getAttenForEmp(17);
System.out.println(attenForEmp);
}
}
|
922f21e04521aee4e6f89b591f6ee99ab114ab84 | 5,818 | java | Java | iconbadge-sample/src/main/java/com/frandioniz/iconbadge_sample/MainActivity.java | Dioniz/iconbadge | 158bf3a85de4fe327c6ff4c24265c40e27f86b62 | [
"Apache-2.0"
] | null | null | null | iconbadge-sample/src/main/java/com/frandioniz/iconbadge_sample/MainActivity.java | Dioniz/iconbadge | 158bf3a85de4fe327c6ff4c24265c40e27f86b62 | [
"Apache-2.0"
] | null | null | null | iconbadge-sample/src/main/java/com/frandioniz/iconbadge_sample/MainActivity.java | Dioniz/iconbadge | 158bf3a85de4fe327c6ff4c24265c40e27f86b62 | [
"Apache-2.0"
] | null | null | null | 41.856115 | 127 | 0.606738 | 994,998 | package com.frandioniz.iconbadge_sample;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import com.frandioniz.iconbadge.IconBadge;
import com.joanzapata.iconify.widget.IconTextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private IconTextView[] btn = new IconTextView[4];
private IconTextView btn_unfocus;
private int[] btn_id = {R.id.btn0, R.id.btn1, R.id.btn2, R.id.btn3};
private int unfocusColor;
private IconBadge iconBadge, iconBadge2;
private Button mSwitchBTN;
private String[] icons = {"{fa-heart}", "{ion-alert-circled}", "{md-email}", "{wi_day_sunny}"};
private int[] colors = {R.color.colorBlue, R.color.colorRed, R.color.colorGreen, R.color.colorOrange, R.color.colorYellow};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iconBadge = findViewById(R.id.iconbadge);
iconBadge2 = findViewById(R.id.iconbadge2);
iconBadge2.setIcon("{fa-heart}");
//iconBadge2.setIcon(R.drawable.ic_launcher_background);
iconBadge2.setIconColor(R.color.colorBlue);
iconBadge2.setBadgePosition(IconBadge.POS_TOP_LEFT);
iconBadge2.setBadgeNumber(1);
iconBadge2.setDimens(20, IconBadge.DIM_REGULAR);
iconBadge2.setBadgeTextColor(android.R.color.white);
iconBadge2.setBadgeBorderColor(android.R.color.white);
iconBadge2.setBadgeBorderWidth(2);
iconBadge2.setBadgeBackgroundColor(R.color.colorOrange);
iconBadge2.setBadgeCornersRadius(200);
iconBadge2.setBadgeCornersRadius(5, 5, 200, 200);
// Seekbar
SeekBar seekBar = findViewById(R.id.seekbar);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
iconBadge.setDimens(i, iconBadge.getBadgeDimen());
iconBadge2.setDimens(i, iconBadge2.getBadgeDimen());
((TextView) findViewById(R.id.tv_seekbar_progress)).setText("Dimens: " + i);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
// Buttons
for(int i = 0; i < btn.length; i++){
btn[i] = (IconTextView) findViewById(btn_id[i]);
unfocusColor = btn[i].getCurrentTextColor();
btn[i].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn0 :
setFocus(btn_unfocus, btn[0]);
iconBadge.setBadgePosition(IconBadge.POS_TOP_LEFT);
iconBadge2.setBadgePosition(IconBadge.POS_TOP_LEFT);
break;
case R.id.btn1 :
setFocus(btn_unfocus, btn[1]);
iconBadge.setBadgePosition(IconBadge.POS_TOP_RIGHT);
iconBadge2.setBadgePosition(IconBadge.POS_TOP_RIGHT);
break;
case R.id.btn2 :
setFocus(btn_unfocus, btn[2]);
iconBadge.setBadgePosition(IconBadge.POS_BOTTOM_LEFT);
iconBadge2.setBadgePosition(IconBadge.POS_BOTTOM_LEFT);
break;
case R.id.btn3 :
setFocus(btn_unfocus, btn[3]);
iconBadge.setBadgePosition(IconBadge.POS_BOTTOM_RIGHT);
iconBadge2.setBadgePosition(IconBadge.POS_BOTTOM_RIGHT);
break;
}
}
});
}
btn_unfocus = btn[0];
setFocus(btn_unfocus, btn[iconBadge.getBadgePosition()]);
mSwitchBTN = findViewById(R.id.btn_switch);
final Random random = new Random(SystemClock.currentThreadTimeMillis());
mSwitchBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int iconPos = random.nextInt(icons.length);
int colorPos = random.nextInt(colors.length);
iconBadge2.setIcon(icons[iconPos]);
//iconBadge2.setIcon(R.drawable.ic_launcher_background);
iconBadge2.setIconColor(colors[colorPos]);
iconBadge2.setBadgePosition(iconBadge2.getBadgePosition());
iconBadge2.setBadgeNumber(1);
iconBadge2.setDimens(iconBadge2.getIconDimen(), IconBadge.DIM_SMALL);
iconBadge2.setBadgeTextColor(android.R.color.white);
iconBadge2.setBadgeBorderColor(android.R.color.white);
iconBadge2.setBadgeBorderWidth(2);
colorPos = random.nextInt(colors.length);
iconBadge2.setBadgeBackgroundColor(colors[colorPos]);
iconBadge2.setBadgeCornersRadius(200);
iconBadge2.setBadgeCornersRadius(5, 5, 200, 200);
}
});
}
private void setFocus(IconTextView btn_unfocus, IconTextView btn_focus){
btn_unfocus.setTextColor(unfocusColor);
btn_focus.setTextColor(getResources().getColor(R.color.colorAccent));
this.btn_unfocus = btn_focus;
}
}
|
922f2247ddd97e13e53cbea0be7d32667e59c1c6 | 390 | java | Java | platform-db-sql/src/main/java/com/softicar/platform/db/sql/expressions/numeric/SqlLongExpression0.java | softicar/platform | d4cf99f3e3537272af23bf60f6b088891bd271ff | [
"MIT"
] | 1 | 2021-11-25T09:58:31.000Z | 2021-11-25T09:58:31.000Z | platform-db-sql/src/main/java/com/softicar/platform/db/sql/expressions/numeric/SqlLongExpression0.java | softicar/platform | d4cf99f3e3537272af23bf60f6b088891bd271ff | [
"MIT"
] | 22 | 2021-11-10T13:59:22.000Z | 2022-03-04T16:38:33.000Z | platform-db-sql/src/main/java/com/softicar/platform/db/sql/expressions/numeric/SqlLongExpression0.java | softicar/platform | d4cf99f3e3537272af23bf60f6b088891bd271ff | [
"MIT"
] | null | null | null | 32.5 | 99 | 0.838462 | 994,999 | package com.softicar.platform.db.sql.expressions.numeric;
import com.softicar.platform.db.sql.expressions.ISqlExpression;
import com.softicar.platform.db.sql.expressions.helper.SqlExpressionWrapper;
public class SqlLongExpression0 extends SqlExpressionWrapper<Long> implements ISqlLongExpression0 {
public SqlLongExpression0(ISqlExpression<Long> expression) {
super(expression);
}
}
|
922f22d835788c006bad6ac78cc741bf1f4cf374 | 2,445 | java | Java | app/src/main/java/db/juhaku/juhakudb/core/android/EntityCriteria.java | juhaku/juhakudb | 56365a46f1c875dac5c72d09414bcb9e432f94d9 | [
"MIT"
] | 1 | 2018-10-01T11:07:29.000Z | 2018-10-01T11:07:29.000Z | app/src/main/java/db/juhaku/juhakudb/core/android/EntityCriteria.java | juhaku/juhakudb | 56365a46f1c875dac5c72d09414bcb9e432f94d9 | [
"MIT"
] | 2 | 2017-11-12T09:34:43.000Z | 2018-03-16T21:29:57.000Z | app/src/main/java/db/juhaku/juhakudb/core/android/EntityCriteria.java | juhaku/juhakudb | 56365a46f1c875dac5c72d09414bcb9e432f94d9 | [
"MIT"
] | 1 | 2018-03-09T16:28:48.000Z | 2018-03-09T16:28:48.000Z | 31.346154 | 105 | 0.669121 | 995,000 | /**
MIT License
Copyright (c) 2018 juhaku
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package db.juhaku.juhakudb.core.android;
import android.util.Log;
import javax.persistence.Entity;
import db.juhaku.juhakudb.core.Criteria;
/**
* Created by juha on 16/04/16.
*<p>This criteria is used to resolve entities for database schema creation.</p>
* @author juha
*
* @since 1.0.2
*/
public class EntityCriteria implements Criteria<String> {
private String[] packages;
public EntityCriteria(String[] packages) {
this.packages = packages;
}
@Override
public boolean meetCriteria(String type) {
for (String path : packages) {
if (type.startsWith(path)) {
// If class is not an enum and it has Entity annotation it should be entity.
Class<?> clazz;
if ((clazz = initializeClass(type)) != null) {
if (!Enum.class.isAssignableFrom(clazz) && clazz.isAnnotationPresent(Entity.class)) {
return true;
}
}
}
}
return false;
}
private static Class<?> initializeClass(String name) {
try {
return Class.forName(name);
} catch (Exception e) {
Log.e(EntityCriteria.class.getName(), "Could not initialize class by name: " +
name + ", null returned!", e);
}
return null;
}
}
|
922f23833d0d9542be94b57eced94783362dcb2b | 1,083 | java | Java | MyNetty/src/main/java/com/juno/framework/netty/core/client/ClientIdleStateTrigger.java | junochan/framework | e9cfcab0ce3e50a3f814d940fa5703e6b371e2e1 | [
"Apache-2.0"
] | null | null | null | MyNetty/src/main/java/com/juno/framework/netty/core/client/ClientIdleStateTrigger.java | junochan/framework | e9cfcab0ce3e50a3f814d940fa5703e6b371e2e1 | [
"Apache-2.0"
] | null | null | null | MyNetty/src/main/java/com/juno/framework/netty/core/client/ClientIdleStateTrigger.java | junochan/framework | e9cfcab0ce3e50a3f814d940fa5703e6b371e2e1 | [
"Apache-2.0"
] | null | null | null | 33.84375 | 92 | 0.712835 | 995,001 | package com.juno.framework.netty.core.client;
import com.juno.framework.netty.beans.NettyMessage;
import com.juno.framework.netty.utils.NettyMessageGenerator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
/**
* 用于捕获 @link{IdleState#WRITER_IDLE} 事件(未在指定时间内向服务器发送数据),
* 然后向<code>Server</code>端发送一个心跳包。
* @Author: Juno
* @Date: 2020/4/9 13:59
*/
public class ClientIdleStateTrigger extends ChannelInboundHandlerAdapter {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
IdleState state = ((IdleStateEvent) evt).state();
if (IdleState.WRITER_IDLE == state) {
NettyMessage nettyMessage = NettyMessageGenerator.genHeartBeatMessage();
ctx.writeAndFlush(nettyMessage.toString());
}
} else {
super.userEventTriggered(ctx, evt);
}
}
}
|
922f258cf3056d9126fbbb42fb561dc3cafa6fa4 | 1,070 | java | Java | src/gwt/client/stuff/ItemEntry.java | VirtueDev/synced_repo | adc1b61ad68402492386fa011e4c628d6588c800 | [
"BSD-3-Clause"
] | 21 | 2015-04-30T10:28:47.000Z | 2021-06-23T23:00:45.000Z | src/gwt/client/stuff/ItemEntry.java | VirtueDev/synced_repo | adc1b61ad68402492386fa011e4c628d6588c800 | [
"BSD-3-Clause"
] | 36 | 2015-07-29T20:50:57.000Z | 2021-09-18T22:37:25.000Z | src/gwt/client/stuff/ItemEntry.java | VirtueDev/synced_repo | adc1b61ad68402492386fa011e4c628d6588c800 | [
"BSD-3-Clause"
] | 35 | 2015-04-30T10:29:41.000Z | 2022-02-15T21:17:01.000Z | 28.918919 | 92 | 0.645794 | 995,002 | //
// $Id$
package client.stuff;
import com.threerings.msoy.item.data.all.Item;
import com.threerings.msoy.web.gwt.Pages;
import client.item.ItemActivator;
import client.item.ItemBox;
import client.item.ItemUtil;
/**
* Displays a thumbnail version of an item.
*/
public class ItemEntry extends ItemBox
{
public ItemEntry (Item item, boolean activator)
{
super(item.getThumbnailMedia(), ItemUtil.getName(item, true),
item.getPrimaryMedia().isRemixable(),
item.isAttrSet(Item.ATTR_THEME_STAMPED) ? Pages.STUFF : null,
"d", item.getType(), item.itemId);
if (item.itemId > 0) { // if this item is an original, style it slightly differently
getFlexCellFormatter().addStyleName(1, 0, "Original");
}
if (!item.isAttrSet(Item.ATTR_THEME_STAMPED)) {
this.addStyleName("Shaded");
} else if (activator) {
// only allow activation if the item is stamped
addWidget(new ItemActivator(item, false), getColumns(), "Activator");
}
}
}
|
922f26a70d01d9a17fc6049fe0f4779cf14bfc1c | 17,100 | java | Java | geode-core/src/integrationTest/java/org/apache/geode/cache/query/transaction/QueryAndJtaJUnitTest.java | nikochiko/geode | 19f55add07d6a652911dc5a5e2116fcf7bf7b2f7 | [
"Apache-2.0"
] | 1,475 | 2016-12-06T06:10:53.000Z | 2022-03-30T09:55:23.000Z | geode-core/src/integrationTest/java/org/apache/geode/cache/query/transaction/QueryAndJtaJUnitTest.java | nikochiko/geode | 19f55add07d6a652911dc5a5e2116fcf7bf7b2f7 | [
"Apache-2.0"
] | 2,809 | 2016-12-06T19:24:26.000Z | 2022-03-31T22:02:20.000Z | geode-core/src/integrationTest/java/org/apache/geode/cache/query/transaction/QueryAndJtaJUnitTest.java | Krishnan-Raghavan/geode | 708588659751c1213c467f5b200b2c36952af563 | [
"Apache-2.0",
"BSD-3-Clause"
] | 531 | 2016-12-06T05:48:47.000Z | 2022-03-31T23:06:37.000Z | 37.831858 | 100 | 0.646316 | 995,003 | /*
* 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.
*/
/*
* QueryAndJtaJUnitTest.java
*
* Created on June 15, 2005, 12:49 PM
*/
package org.apache.geode.cache.query.transaction;
import static org.apache.geode.cache.Region.SEPARATOR;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.Collection;
import javax.naming.Context;
import javax.transaction.RollbackException;
import javax.transaction.UserTransaction;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.apache.geode.CopyHelper;
import org.apache.geode.cache.AttributesFactory;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.DataPolicy;
import org.apache.geode.cache.EntryEvent;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionAttributes;
import org.apache.geode.cache.query.Index;
import org.apache.geode.cache.query.IndexType;
import org.apache.geode.cache.query.Query;
import org.apache.geode.cache.query.QueryService;
import org.apache.geode.cache.query.SelectResults;
import org.apache.geode.cache.query.data.Portfolio;
import org.apache.geode.cache.query.internal.QueryObserverAdapter;
import org.apache.geode.cache.query.internal.QueryObserverHolder;
import org.apache.geode.cache.util.CacheListenerAdapter;
import org.apache.geode.internal.jta.CacheUtils;
import org.apache.geode.test.junit.categories.OQLQueryTest;
@Category({OQLQueryTest.class})
public class QueryAndJtaJUnitTest {
private Region currRegion;
private Cache cache;
private QueryService qs;
private Query q;
private int tblIDFld;
private String tblNameFld;
private String tblName;
@Before
public void setUp() throws Exception {
tblName = CacheUtils.init("CacheTest");
cache = CacheUtils.getCache();
AttributesFactory attributesFactory = new AttributesFactory();
attributesFactory.setValueConstraint(Portfolio.class);
RegionAttributes regionAttributes = attributesFactory.create();
currRegion = cache.createRegion("portfolios", regionAttributes);
qs = CacheUtils.getQueryService();
}
@After
public void tearDown() throws Exception {
CacheUtils.destroyTable(tblName);
cache.close();
}
@Test
public void testScenario1() throws Exception {
Context ctx = cache.getJNDIContext();
UserTransaction ta = null;
// Connection conn = null;
try {
qs.createIndex("iIndex", IndexType.FUNCTIONAL, "ID", SEPARATOR + "portfolios");
// PUT 4 objects in region, QUERY, CREATEINDEX
for (int i = 0; i < 4; i++) {
currRegion.put("key" + i, new Portfolio(i));
}
QueryObserverImpl observer2 = new QueryObserverImpl();
QueryObserverHolder.setInstance(observer2);
q = qs.newQuery("select distinct * from " + SEPARATOR + "portfolios where ID != 53");
Object r = q.execute();
if (!observer2.isIndexesUsed) {
fail("NO INDEX WAS USED, IT WAS EXPECTED TO BE USED");
}
if (((Collection) r).size() != 4) {
fail("Query result not of expected size");
}
// print("Size of query result :"+ ((Collection)r).size());
// print("Result of query =" + Utils.printResult(r));
// print("Index IS: " + ((RangeIndex)i2).dump());
// BEGIN TX PUT new 4 objects in region, QUERY,CREATEINDEX, ROLLBACK
ta = (UserTransaction) ctx.lookup("java:/UserTransaction");
ta.begin();
for (int i = 9; i < 13; i++) {
currRegion.put("key" + i, new Portfolio(i));
}
observer2 = new QueryObserverImpl();
QueryObserverHolder.setInstance(observer2);
q = qs.newQuery("select distinct * from " + SEPARATOR + "portfolios where ID != 53");
r = q.execute();
if (!observer2.isIndexesUsed) {
fail("NO INDEX WAS USED, IT WAS EXPECTED TO BE USED");
}
if (((Collection) r).size() != 4) {
fail("Query result not of expected size");
}
// print("Size of query result :"+ ((Collection)r).size());
// print("Result of query =" + Utils.printResult(r));
Index i1 = qs.createIndex("tIndex", IndexType.FUNCTIONAL, "status", SEPARATOR + "portfolios");
// print("Index IS: " + ((RangeIndex)i1).dump());
observer2 = new QueryObserverImpl();
QueryObserverHolder.setInstance(observer2);
q = qs.newQuery("select distinct * from " + SEPARATOR + "portfolios where status = 'active'");
r = q.execute();
if (!observer2.isIndexesUsed) {
fail("NO INDEX WAS USED, IT WAS EXPECTED TO BE USED");
}
if (((Collection) r).size() != 2) {
fail("Query result not of expected size");
}
observer2 = new QueryObserverImpl();
QueryObserverHolder.setInstance(observer2);
q = qs
.newQuery("select distinct * from " + SEPARATOR + "portfolios where status = 'inactive'");
r = q.execute();
if (!observer2.isIndexesUsed) {
fail("NO INDEX WAS USED, IT WAS EXPECTED TO BE USED");
}
if (((Collection) r).size() != 2) {
fail("Query result not of expected size");
}
ta.rollback();
// PRINT INDEX AFTER ROLLBACK, REMOVEINDEX.
observer2 = new QueryObserverImpl();
QueryObserverHolder.setInstance(observer2);
q = qs.newQuery("select distinct * from " + SEPARATOR + "portfolios where status = 'active'");
r = q.execute();
if (!observer2.isIndexesUsed) {
fail("NO INDEX WAS USED, IT WAS EXPECTED TO BE USED");
}
if (((Collection) r).size() != 2) {
fail("Query result not of expected size");
}
// print("AfterRollback \n"+currRegion.values());
// print("Index IS: " + ((RangeIndex)i1).dump());
qs.removeIndex(i1);
// BEGIN TX PUT new 4 objects in region,CREATEINDEX, QUERY ,COMMIT
ta.begin();
for (int i = 9; i < 13; i++) {
currRegion.put("key" + i, new Portfolio(i));
}
i1 = qs.createIndex("tIndex", IndexType.FUNCTIONAL, "status", SEPARATOR + "portfolios");
// print("Index IS: " + ((RangeIndex)i1).dump());
observer2 = new QueryObserverImpl();
QueryObserverHolder.setInstance(observer2);
q = qs.newQuery("select distinct * from " + SEPARATOR + "portfolios where status = 'active'");
r = q.execute();
if (!observer2.isIndexesUsed) {
fail("NO INDEX WAS USED, IT WAS EXPECTED TO BE USED");
}
if (((Collection) r).size() != 2) {
fail("Query result not of expected size");
}
for (int i = 9; i < 13; i++) {
currRegion.put("key" + i, new Portfolio(i));
}
observer2 = new QueryObserverImpl();
QueryObserverHolder.setInstance(observer2);
q = qs.newQuery("select distinct * from " + SEPARATOR + "portfolios where status = 'active'");
r = q.execute();
if (!observer2.isIndexesUsed) {
fail("NO INDEX WAS USED, IT WAS EXPECTED TO BE USED");
}
if (((Collection) r).size() != 2) {
fail("Query result not of expected size");
}
// print("Size of query result :"+ ((Collection)r).size());
// print("Result of query =" + Utils.printResult(r));
// print("Index on status IS: " + ((RangeIndex)i1).dump());
// print("Index On ID IS: " + ((RangeIndex)i2).dump());
ta.commit();
// WAIT FOR 2 secs DISPLAYINDEX, QUERY
Thread.sleep(2000);
// print("Aftercommit \n"+currRegion.values());
// print("Index IS: " + ((RangeIndex)i1).dump());
observer2 = new QueryObserverImpl();
QueryObserverHolder.setInstance(observer2);
q = qs.newQuery("select distinct * from " + SEPARATOR + "portfolios where status = 'active'");
r = q.execute();
if (!observer2.isIndexesUsed) {
fail("NO INDEX WAS USED, IT WAS EXPECTED TO BE USED");
}
if (((Collection) r).size() != 4) {
fail("Query result not of expected size");
}
observer2 = new QueryObserverImpl();
QueryObserverHolder.setInstance(observer2);
q = qs
.newQuery("select distinct * from " + SEPARATOR + "portfolios where status = 'inactive'");
r = q.execute();
if (!observer2.isIndexesUsed) {
fail("NO INDEX WAS USED, IT WAS EXPECTED TO BE USED");
}
if (((Collection) r).size() != 4) {
fail("Query result not of expected size");
}
observer2 = new QueryObserverImpl();
QueryObserverHolder.setInstance(observer2);
q = qs.newQuery("select distinct * from " + SEPARATOR + "portfolios where ID != 53");
r = q.execute();
if (!observer2.isIndexesUsed) {
fail("NO INDEX WAS USED, IT WAS EXPECTED TO BE USED");
}
if (((Collection) r).size() != 8) {
fail("Query result not of expected size");
}
// print("Size of query result :"+ ((Collection)r).size());
// print("Result of query =" + Utils.printResult(r));
// print("Index On ID IS: " + ((RangeIndex)i2).dump());
} catch (RollbackException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
ta.rollback();
}
}
private static void print(String str) {
CacheUtils.log("\n" + str + "\n");
}
private static class QueryObserverImpl extends QueryObserverAdapter {
boolean isIndexesUsed = false;
ArrayList indexesUsed = new ArrayList();
@Override
public void beforeIndexLookup(Index index, int oper, Object key) {
indexesUsed.add(index.getName());
}
@Override
public void afterIndexLookup(Collection results) {
if (results != null) {
isIndexesUsed = true;
}
}
}
/**
* verify that queries on indexes work with transaction
*
*/
@Test
public void testIndexOnCommitForPut() throws Exception {
AttributesFactory af = new AttributesFactory();
af.setDataPolicy(DataPolicy.REPLICATE);
Region region = cache.createRegion("sample", af.create());
qs.createIndex("foo", IndexType.FUNCTIONAL, "age", SEPARATOR + "sample");
Context ctx = cache.getJNDIContext();
UserTransaction utx = (UserTransaction) ctx.lookup("java:/UserTransaction");
Integer x = new Integer(0);
utx.begin();
region.create(x, new Person("xyz", 45));
utx.commit();
Query q = qs.newQuery("select * from " + SEPARATOR + "sample where age < 50");
assertEquals(1, ((SelectResults) q.execute()).size());
Person dsample = (Person) CopyHelper.copy(region.get(x));
dsample.setAge(55);
utx.begin();
region.put(x, dsample);
utx.commit();
CacheUtils.log(((Person) region.get(x)));
assertEquals(0, ((SelectResults) q.execute()).size());
}
@Test
public void testIndexOnCommitForInvalidate() throws Exception {
AttributesFactory af = new AttributesFactory();
af.setDataPolicy(DataPolicy.REPLICATE);
Region region = cache.createRegion("sample", af.create());
qs.createIndex("foo", IndexType.FUNCTIONAL, "age", SEPARATOR + "sample");
Context ctx = cache.getJNDIContext();
UserTransaction utx = (UserTransaction) ctx.lookup("java:/UserTransaction");
Integer x = new Integer(0);
utx.begin();
region.create(x, new Person("xyz", 45));
utx.commit();
Query q = qs.newQuery("select * from " + SEPARATOR + "sample where age < 50");
assertEquals(1, ((SelectResults) q.execute()).size());
Person dsample = (Person) CopyHelper.copy(region.get(x));
dsample.setAge(55);
utx.begin();
region.invalidate(x);
utx.commit();
CacheUtils.log(((Person) region.get(x)));
assertEquals(0, ((SelectResults) q.execute()).size());
}
@Test
public void testAllIndexesOnCommitForPut() throws Exception {
// create region
AttributesFactory af = new AttributesFactory();
af.setDataPolicy(DataPolicy.REPLICATE);
Region region = cache.createRegion("sample", af.create());
// put data
for (int i = 0; i < 10; i++) {
region.put(i, new Portfolio(i));
}
String[] queries = {"select * from " + SEPARATOR + "sample where ID = 5",
"select ID from " + SEPARATOR + "sample where ID < 5",
"select ID from " + SEPARATOR + "sample where ID > 5",
"select ID from " + SEPARATOR + "sample where ID != 5",
"select status from " + SEPARATOR + "sample where status = 'active'",
"select status from " + SEPARATOR + "sample where status > 'active'",
"select status from " + SEPARATOR + "sample where status < 'active'",
"select status from " + SEPARATOR + "sample where status != 'active'",
"select pos.secId from " + SEPARATOR
+ "sample p, p.positions.values pos where pos.secId = 'IBM'",
"select pos.secId from " + SEPARATOR
+ "sample p, p.positions.values pos where pos.secId < 'VMW'",
"select pos.secId from " + SEPARATOR
+ "sample p, p.positions.values pos where pos.secId > 'IBM'",
"select pos.secId from " + SEPARATOR
+ "sample p, p.positions.values pos where pos.secId != 'IBM'"};
SelectResults[][] sr = new SelectResults[queries.length][2];
// execute queries without indexes
for (int i = 0; i < queries.length; i++) {
sr[i][0] = (SelectResults) qs.newQuery(queries[i]).execute();
}
// create indexes
qs.createKeyIndex("IDIndex", "ID", SEPARATOR + "sample");
qs.createIndex("statusIndex", "status", SEPARATOR + "sample");
qs.createIndex("secIdIndex", "pos.secId", SEPARATOR + "sample p, p.positions.values pos");
// begin transaction
Context ctx = cache.getJNDIContext();
UserTransaction utx = (UserTransaction) ctx.lookup("java:/UserTransaction");
utx.begin();
// update data
for (int i = 0; i < 10; i++) {
region.put(i, new Portfolio(i));
}
// execute queries with indexes during transaction
for (int i = 0; i < queries.length; i++) {
sr[i][1] = (SelectResults) qs.newQuery(queries[i]).execute();
}
// complete transaction
utx.commit();
// verify results
org.apache.geode.cache.query.CacheUtils.compareResultsOfWithAndWithoutIndex(sr);
}
@Test
public void testIndexOnCommitForDestroy() throws Exception {
AttributesFactory af = new AttributesFactory();
af.setDataPolicy(DataPolicy.REPLICATE);
Region region = cache.createRegion("sample", af.create());
qs.createIndex("foo", IndexType.FUNCTIONAL, "age", SEPARATOR + "sample");
Context ctx = cache.getJNDIContext();
UserTransaction utx = (UserTransaction) ctx.lookup("java:/UserTransaction");
Integer x = new Integer(0);
utx.begin();
region.create(x, new Person("xyz", 45));
utx.commit();
Query q = qs.newQuery("select * from " + SEPARATOR + "sample where age < 50");
assertEquals(1, ((SelectResults) q.execute()).size());
Person dsample = (Person) CopyHelper.copy(region.get(x));
dsample.setAge(55);
utx.begin();
region.destroy(x);
utx.commit();
CacheUtils.log(((Person) region.get(x)));
assertEquals(0, ((SelectResults) q.execute()).size());
}
/*
* Enable this test when indexes are made transactional.
*/
@Ignore
@Test
public void testFailedIndexUpdateOnJTACommitForPut() throws Exception {
Person.THROW_ON_INDEX = true;
AttributesFactory af = new AttributesFactory();
af.setDataPolicy(DataPolicy.REPLICATE);
Region region = cache.createRegion("sample", af.create());
qs.createIndex("foo", IndexType.FUNCTIONAL, "index", SEPARATOR + "sample");
Context ctx = cache.getJNDIContext();
UserTransaction utx = (UserTransaction) ctx.lookup("java:/UserTransaction");
Integer x = new Integer(0);
utx.begin();
region.create(x, new Person("xyz", 45));
try {
utx.commit();
fail("Commit should have thrown an exception because the index update threw");
} catch (Exception e) {
// this is desired
}
}
private static class SimpleListener extends CacheListenerAdapter {
public int creates = 0;
public int updates = 0;
@Override
public void afterCreate(EntryEvent event) {
// TODO Auto-generated method stub
CacheUtils.log("SimpleListener.create!:" + event);
creates++;
}
@Override
public void afterUpdate(EntryEvent event) {
// TODO Auto-generated method stub
updates++;
}
}
}
|
922f26c89b172a4523d48d73847cbc87c3fa3e67 | 4,168 | java | Java | sell/src/main/java/net/honarnama/sell/activity/ForgotPasswordActivity.java | Honarnama/AndroidApps | 43f1f0155a983b98b7e78c52fe923f6c9624731c | [
"Apache-2.0"
] | 3 | 2019-03-18T12:52:33.000Z | 2020-11-11T16:45:27.000Z | sell/src/main/java/net/honarnama/sell/activity/ForgotPasswordActivity.java | Honarnama/AndroidApps | 43f1f0155a983b98b7e78c52fe923f6c9624731c | [
"Apache-2.0"
] | null | null | null | sell/src/main/java/net/honarnama/sell/activity/ForgotPasswordActivity.java | Honarnama/AndroidApps | 43f1f0155a983b98b7e78c52fe923f6c9624731c | [
"Apache-2.0"
] | 1 | 2020-11-11T16:46:05.000Z | 2020-11-11T16:46:05.000Z | 46.831461 | 210 | 0.6238 | 995,004 | package net.honarnama.sell.activity;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import net.honarnama.base.utils.GravityTextWatcher;
import net.honarnama.base.utils.NetworkManager;
import net.honarnama.sell.HonarnamaSellApp;
import net.honarnama.sell.R;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class ForgotPasswordActivity extends HonarnamaSellActivity {
private Button mForgotPasswordButton;
private EditText mForgotPasswordEmailEditEext;
private ProgressDialog mWaitingProgressDialog;
private Tracker mTracker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTracker = HonarnamaSellApp.getInstance().getDefaultTracker();
mTracker.setScreenName("ForgotPasswordActivity");
mTracker.send(new HitBuilders.ScreenViewBuilder().build());
setContentView(R.layout.activity_forgot_password);
mForgotPasswordEmailEditEext = (EditText) findViewById(R.id.forgot_password_email_edit_text);
mForgotPasswordEmailEditEext.addTextChangedListener(new GravityTextWatcher(mForgotPasswordEmailEditEext));
mForgotPasswordEmailEditEext.requestFocus();
mForgotPasswordButton = (Button) findViewById(R.id.forgot_password_button);
mForgotPasswordButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!NetworkManager.getInstance().isNetworkEnabled(true)) {
return;
}
String email = mForgotPasswordEmailEditEext.getText().toString().trim();
if (email.length() == 0) {
mForgotPasswordEmailEditEext.requestFocus();
mForgotPasswordEmailEditEext.setError(getString(R.string.error_email_not_set));
return;
} else {
boolean isOK = android.util.Patterns.EMAIL_ADDRESS.matcher(mForgotPasswordEmailEditEext.getText().toString()).matches();
if (!isOK) {
mForgotPasswordEmailEditEext.requestFocus();
mForgotPasswordEmailEditEext.setError(getString(net.honarnama.base.R.string.error_email_address_is_not_valid));
return;
}
}
mWaitingProgressDialog = new ProgressDialog(ForgotPasswordActivity.this);
mWaitingProgressDialog.setMessage(getString(R.string.please_wait));
mWaitingProgressDialog.setCancelable(false);
mWaitingProgressDialog.show();
// ParseUser.requestPasswordResetInBackground(cEmail, new RequestPasswordResetCallback() {
// @Override
// public void done(ParseException e) {
// mWaitingProgressDialog.dismiss();
// if (e == null) {
// Toast.makeText(ForgotPasswordActivity.this, getString(R.string.password_reset_link_sent), Toast.LENGTH_LONG).show();
// kill_activity();
// } else {
// if (e.getCode() == ParseException.EMAIL_NOT_FOUND) {
// Toast.makeText(ForgotPasswordActivity.this, getString(R.string.no_user_found_matching_email), Toast.LENGTH_LONG).show();
// } else {
// Toast.makeText(ForgotPasswordActivity.this, getString(R.string.error_sending_reset_pass_link) + getString(R.string.please_check_internet_connection), Toast.LENGTH_LONG).show();
// logE("Error sending request for forgot password link" + " // Error Code: " + e.getCode() + "// Error Message: " + e.getMessage(), "", e);
// }
// }
// }
// });
}
});
}
void kill_activity() {
finish();
}
}
|
922f26c8cf153ebe2193a43894d4949c737f7568 | 15,363 | java | Java | jgnash-fx/src/main/java/jgnash/uifx/report/IncomeExpensePayeePieChartDialogController.java | weedySeaDragon/jgnash | 29e30368b8fa8728cc23952625522bf314998cee | [
"MIT"
] | null | null | null | jgnash-fx/src/main/java/jgnash/uifx/report/IncomeExpensePayeePieChartDialogController.java | weedySeaDragon/jgnash | 29e30368b8fa8728cc23952625522bf314998cee | [
"MIT"
] | null | null | null | jgnash-fx/src/main/java/jgnash/uifx/report/IncomeExpensePayeePieChartDialogController.java | weedySeaDragon/jgnash | 29e30368b8fa8728cc23952625522bf314998cee | [
"MIT"
] | null | null | null | 34.995444 | 120 | 0.650589 | 995,005 | /*
* jGnash, a personal finance application
* Copyright (C) 2001-2018 Craig Cavanaugh
*
* 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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package jgnash.uifx.report;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.UUID;
import java.util.function.Predicate;
import java.util.prefs.Preferences;
import java.util.stream.Collectors;
import javafx.application.Platform;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ChangeListener;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.geometry.Side;
import javafx.scene.Scene;
import javafx.scene.chart.PieChart;
import javafx.scene.control.TextField;
import javafx.scene.control.TextInputControl;
import javafx.scene.control.TitledPane;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import jgnash.engine.Account;
import jgnash.engine.Comparators;
import jgnash.engine.CurrencyNode;
import jgnash.engine.Engine;
import jgnash.engine.EngineFactory;
import jgnash.engine.Transaction;
import jgnash.text.CommodityFormat;
import jgnash.uifx.Options;
import jgnash.uifx.control.AccountComboBox;
import jgnash.uifx.control.DatePickerEx;
import jgnash.uifx.control.DoughnutChart;
import jgnash.uifx.util.InjectFXML;
import jgnash.util.CollectionUtils;
import jgnash.util.EncodeDecode;
import jgnash.util.NotNull;
import jgnash.util.function.PayeePredicate;
/**
* Income and Expense Payee Pie Chart.
*
* @author Craig Cavanaugh
* @author Pranay Kumar
*/
public class IncomeExpensePayeePieChartDialogController {
private static final String LAST_ACCOUNT = "lastAccount";
private static final String FILTERS = "filters";
private static final char DELIMITER = 0x25FC;
private static final int CREDIT = 0;
private static final int DEBIT = 1;
private static final int MAX_NAME_LENGTH = 12;
private static final String ELLIPSIS = "…";
private static final String CHART_CSS = "jgnash/skin/incomeExpensePieChart.css";
private final Preferences preferences
= Preferences.userNodeForPackage(IncomeExpensePayeePieChartDialogController.class)
.node("IncomeExpensePayeePieChart");
@InjectFXML
private final ObjectProperty<Scene> parent = new SimpleObjectProperty<>();
@FXML
private TitledPane titledPane;
@FXML
private VBox filtersPane;
@FXML
private GridPane chartPane;
@FXML
private DoughnutChart debitPieChart;
@FXML
private DoughnutChart creditPieChart;
@FXML
private DatePickerEx startDatePicker;
@FXML
private DatePickerEx endDatePicker;
@FXML
private AccountComboBox accountComboBox;
@FXML
private ResourceBundle resources;
private final ChangeListener<String> payeeChangeListener = (observable, oldValue, newValue) -> {
if (newValue != null) {
if (newValue.isEmpty()) {
Platform.runLater(this::trimAuxPayeeTextFields);
} else {
if (!isEmptyPayeeFieldAvailable()) {
Platform.runLater(this::insertAuxPayeeTextField);
}
}
}
Platform.runLater(this::updateCharts);
final List<String> filters = getPayeeTextFields().stream()
.filter(textField -> !textField.getText().isEmpty())
.map(TextInputControl::getText).collect(Collectors.toList());
if (filters.isEmpty()) {
preferences.remove(FILTERS);
} else {
preferences.put(FILTERS, EncodeDecode.encodeStringCollection(filters, DELIMITER));
}
};
@FXML
public void initialize() {
// Respect animation preference
debitPieChart.animatedProperty().set(Options.animationsEnabledProperty().get());
creditPieChart.animatedProperty().set(Options.animationsEnabledProperty().get());
creditPieChart.getStylesheets().addAll(CHART_CSS);
debitPieChart.getStylesheets().addAll(CHART_CSS);
creditPieChart.centerTitleProperty().set(resources.getString("Column.Credit"));
debitPieChart.centerTitleProperty().set(resources.getString("Column.Debit"));
accountComboBox.setPredicate(AccountComboBox.getShowAllPredicate());
if (preferences.get(LAST_ACCOUNT, null) != null) {
final String uuid = preferences.get(LAST_ACCOUNT, "");
if (!uuid.isEmpty()) {
final Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);
Objects.requireNonNull(engine);
final Account account = engine.getAccountByUuid(UUID.fromString(uuid));
if (account != null) {
accountComboBox.setValue(account);
}
}
}
startDatePicker.setValue(endDatePicker.getValue().minusYears(1));
final ChangeListener<Object> listener = (observable, oldValue, newValue) -> {
if (newValue != null) {
updateCharts();
preferences.put(LAST_ACCOUNT, accountComboBox.getValue().getUuid().toString());
}
};
accountComboBox.valueProperty().addListener(listener);
startDatePicker.valueProperty().addListener(listener);
endDatePicker.valueProperty().addListener(listener);
creditPieChart.setLegendSide(Side.BOTTOM);
debitPieChart.setLegendSide(Side.BOTTOM);
// Load in the first aux payee text field
insertAuxPayeeTextField();
restoreFilters();
// Expand the titled pane if filters are being used
Platform.runLater(() -> {
if (getPayeeTextFields().size() > 1) {
titledPane.setExpanded(true);
}
});
// Push the initial load to the end of the platform thread for better startup and nicer visual effect
Platform.runLater(this::updateCharts);
}
private void restoreFilters() {
final List<String> filters
= new ArrayList<>(EncodeDecode.decodeStringCollection(preferences.get(FILTERS, ""), DELIMITER));
// Need to reverse the order since we are inserting at the top
Collections.reverse(filters);
filters.forEach(this::insertAuxPayeeTextField);
}
private void insertAuxPayeeTextField() {
final TextField payeeField = new TextField();
payeeField.textProperty().addListener(payeeChangeListener);
filtersPane.getChildren().add(payeeField);
}
private void insertAuxPayeeTextField(final String filter) {
final TextField payeeField = new TextField(filter);
payeeField.textProperty().addListener(payeeChangeListener);
filtersPane.getChildren().add(0, payeeField);
}
private void trimAuxPayeeTextFields() {
final List<TextField> empty = filtersPane.getChildren().stream().filter(node -> node instanceof TextField)
.filter(node -> ((TextField) node).getText().isEmpty())
.map(node -> (TextField) node).collect(Collectors.toList());
// Reverse order so we leave the last empty at the bottom
Collections.reverse(empty);
for (int i = empty.size() - 1; i > 0; i--) {
final TextField textField = empty.get(i);
textField.textProperty().removeListener(payeeChangeListener);
filtersPane.getChildren().remove(textField);
}
}
private boolean isEmptyPayeeFieldAvailable() {
boolean result = false;
for (TextField textField : getPayeeTextFields()) {
if (textField.getText().isEmpty()) {
result = true;
break;
}
}
return result;
}
private List<TextField> getPayeeTextFields() {
return filtersPane.getChildren().stream()
.filter(node -> node instanceof TextField).map(node -> (TextField) node).collect(Collectors.toList());
}
private void updateCharts() {
final Account account = accountComboBox.getValue();
if (account != null) {
final ObservableList<PieChart.Data>[] chartData = createPieDataSet(account);
creditPieChart.setData(chartData[CREDIT]);
debitPieChart.setData(chartData[DEBIT]);
final NumberFormat numberFormat = CommodityFormat.getFullNumberFormat(account.getCurrencyNode());
// Calculate the totals for percentage value
final double creditTotal = chartData[CREDIT].parallelStream().mapToDouble(PieChart.Data::getPieValue).sum();
final double debitTotal = chartData[DEBIT].parallelStream().mapToDouble(PieChart.Data::getPieValue).sum();
final NumberFormat percentFormat = NumberFormat.getPercentInstance();
percentFormat.setMaximumFractionDigits(1);
percentFormat.setMinimumFractionDigits(1);
// Install tooltips on the data after it has been added to the chart
creditPieChart.getData().forEach(data ->
Tooltip.install(data.getNode(), new Tooltip((data.getNode().getUserData()
+ "\n" + numberFormat.format(data.getPieValue()) + "(" +
percentFormat.format(data.getPieValue() / creditTotal)) + ")")));
// Install tooltips on the data after it has been added to the chart
debitPieChart.getData().forEach(data ->
Tooltip.install(data.getNode(), new Tooltip(((data.getNode().getUserData())
+ "\n" + numberFormat.format(data.getPieValue()) + "(" +
percentFormat.format(data.getPieValue() / debitTotal)) + ")")));
creditPieChart.centerSubTitleProperty().set(numberFormat.format(creditTotal));
debitPieChart.centerSubTitleProperty().set(numberFormat.format(debitTotal));
} else {
creditPieChart.setData(FXCollections.emptyObservableList());
creditPieChart.setTitle("No Data");
debitPieChart.setData(FXCollections.emptyObservableList());
debitPieChart.setTitle("No Data");
}
}
private ObservableList<PieChart.Data>[] createPieDataSet(@NotNull final Account account) {
@SuppressWarnings("unchecked")
final ObservableList<PieChart.Data>[] chartData = new ObservableList[2];
chartData[CREDIT] = FXCollections.observableArrayList();
chartData[DEBIT] = FXCollections.observableArrayList();
final Map<String, BigDecimal> names = new HashMap<>();
final List<TranTuple> list = getTransactions(account, new ArrayList<>(), startDatePicker.getValue(),
endDatePicker.getValue());
final CurrencyNode currency = account.getCurrencyNode();
// Create a list of predicates
final List<Predicate<Transaction>> predicates = getPayeeTextFields().stream()
.filter(textField -> !textField.getText().isEmpty())
.map(textField -> new PayeePredicate(textField.getText(), Options.regexForFiltersProperty().get()))
.collect(Collectors.toList());
// Iterate through the list and add up filtered payees
for (final TranTuple tranTuple : list) {
final String payee = tranTuple.transaction.getPayee();
BigDecimal sum = tranTuple.transaction.getAmount(tranTuple.account);
sum = sum.multiply(tranTuple.account.getCurrencyNode().getExchangeRate(currency));
boolean keep = false;
if (predicates.isEmpty()) {
keep = true;
} else {
for (final Predicate<Transaction> predicate : predicates) {
if (predicate.test(tranTuple.transaction)) {
keep = true;
break;
}
}
}
if (keep) {
if (names.containsKey(payee)) {
sum = sum.add(names.get(payee));
}
names.put(payee, sum);
}
}
final Map<String, BigDecimal> sortedNames = CollectionUtils.sortMapByValue(names);
for (final Map.Entry<String, BigDecimal> entry : sortedNames.entrySet()) {
final PieChart.Data data = new PieChart.Data(truncateString(entry.getKey()),
entry.getValue().abs().doubleValue());
// nodes are created lazily. Set the user data (Account) after the node is created
data.nodeProperty().addListener((observable, oldValue, newValue) -> newValue.setUserData(entry.getKey()));
if (entry.getValue().signum() == -1) {
chartData[DEBIT].add(data);
} else {
chartData[CREDIT].add(data);
}
}
return chartData;
}
private static String truncateString(final String string) {
if (string.length() <= MAX_NAME_LENGTH) {
return string;
}
return string.substring(0, MAX_NAME_LENGTH - 1) + ELLIPSIS;
}
private static class TranTuple {
final Account account;
final Transaction transaction;
TranTuple(Account account, Transaction transaction) {
this.account = account;
this.transaction = transaction;
}
}
private List<TranTuple> getTransactions(final Account account, final List<TranTuple> transactions,
final LocalDate startDate, final LocalDate endDate) {
for (final Transaction transaction : account.getTransactions(startDate, endDate)) {
TranTuple tuple = new TranTuple(account, transaction);
transactions.add(tuple);
}
for (final Account child : account.getChildren(Comparators.getAccountByCode())) {
getTransactions(child, transactions, startDate, endDate);
}
return transactions;
}
@FXML
private void handleSaveAction() {
ChartUtilities.saveChart(chartPane);
}
@FXML
private void handleCopyToClipboard() {
ChartUtilities.copyToClipboard(chartPane);
}
@FXML
private void handlePrintAction() {
ChartUtilities.printChart(chartPane);
}
@FXML
private void handleCloseAction() {
((Stage) parent.get().getWindow()).close();
}
}
|
922f27ed53cdaad0440a6cf4a2405eaf75c30501 | 1,503 | java | Java | google/cloud/dataqna/v1alpha/google-cloud-dataqna-v1alpha-java/gapic-google-cloud-dataqna-v1alpha-java/src/main/java/com/google/cloud/dataqna/v1alpha/stub/AutoSuggestionServiceStub.java | googleapis/googleapis-gen | d84824c78563d59b0e58d5664bfaa430e9ad7e7a | [
"Apache-2.0"
] | 7 | 2021-02-21T10:39:41.000Z | 2021-12-07T07:31:28.000Z | google/cloud/dataqna/v1alpha/google-cloud-dataqna-v1alpha-java/gapic-google-cloud-dataqna-v1alpha-java/src/main/java/com/google/cloud/dataqna/v1alpha/stub/AutoSuggestionServiceStub.java | googleapis/googleapis-gen | d84824c78563d59b0e58d5664bfaa430e9ad7e7a | [
"Apache-2.0"
] | 6 | 2021-02-02T23:46:11.000Z | 2021-11-15T01:46:02.000Z | google/cloud/dataqna/v1alpha/google-cloud-dataqna-v1alpha-java/gapic-google-cloud-dataqna-v1alpha-java/src/main/java/com/google/cloud/dataqna/v1alpha/stub/AutoSuggestionServiceStub.java | googleapis/googleapis-gen | d84824c78563d59b0e58d5664bfaa430e9ad7e7a | [
"Apache-2.0"
] | 4 | 2021-01-28T23:25:45.000Z | 2021-08-30T01:55:16.000Z | 34.953488 | 96 | 0.779108 | 995,006 | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.dataqna.v1alpha.stub;
import com.google.api.core.BetaApi;
import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.dataqna.v1alpha.SuggestQueriesRequest;
import com.google.cloud.dataqna.v1alpha.SuggestQueriesResponse;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* Base stub class for the AutoSuggestionService service API.
*
* <p>This class is for advanced usage and reflects the underlying API directly.
*/
@BetaApi
@Generated("by gapic-generator-java")
public abstract class AutoSuggestionServiceStub implements BackgroundResource {
public UnaryCallable<SuggestQueriesRequest, SuggestQueriesResponse> suggestQueriesCallable() {
throw new UnsupportedOperationException("Not implemented: suggestQueriesCallable()");
}
@Override
public abstract void close();
}
|
922f27f45ca047c9672e958e614fdfba1fd086a7 | 1,164 | java | Java | Semana01.Material02.exerc01.RamdomizacaoDado_10-03-2020/src/entities/Dice.java | enzoappi/ProjetoDeSistemasI.Java.FEMASS | 81569615933083ebfbcf99f1f948cbecc6f2cc19 | [
"MIT"
] | null | null | null | Semana01.Material02.exerc01.RamdomizacaoDado_10-03-2020/src/entities/Dice.java | enzoappi/ProjetoDeSistemasI.Java.FEMASS | 81569615933083ebfbcf99f1f948cbecc6f2cc19 | [
"MIT"
] | null | null | null | Semana01.Material02.exerc01.RamdomizacaoDado_10-03-2020/src/entities/Dice.java | enzoappi/ProjetoDeSistemasI.Java.FEMASS | 81569615933083ebfbcf99f1f948cbecc6f2cc19 | [
"MIT"
] | null | null | null | 19.728814 | 79 | 0.564433 | 995,007 | /*
* 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 entities;
/**
*
* @author enzoappi
*/
public class Dice {
protected Integer play1;
protected Integer play2;
protected Integer play3;
public Dice() {
}
public Dice(Integer play1, Integer play2, Integer play3) {
this.play1 = play1;
this.play2 = play2;
this.play3 = play3;
}
public Integer getPlay1() {
return play1;
}
public void setPlay1() {
int temp = (int) ((Math.random() * 6) + 1);
this.play1 = temp;
}
public Integer getPlay2() {
return play2;
}
public void setPlay2() {
int temp = (int) ((Math.random() * 6) + 1);
this.play2 = temp;
}
public Integer getPlay3() {
return play3;
}
public void setPlay3() {
int temp = (int) ((Math.random() * 6) + 1);
this.play3 = temp;
}
public Integer sumValuesPlays(){
return this.play1 + this.play2 + this.play3;
}
}
|
922f29cd177ba998241eed48eed6b6e360533c49 | 5,896 | java | Java | to0scheduler/to0client/src/main/java/org/sdo/iotplatformsdk/to0scheduler/to0client/To0ClientConfiguration.java | bprashan/iot-platform-sdk | 839fba8004a6d575a1e55fb91d6a720d70de07fa | [
"Apache-2.0"
] | null | null | null | to0scheduler/to0client/src/main/java/org/sdo/iotplatformsdk/to0scheduler/to0client/To0ClientConfiguration.java | bprashan/iot-platform-sdk | 839fba8004a6d575a1e55fb91d6a720d70de07fa | [
"Apache-2.0"
] | null | null | null | to0scheduler/to0client/src/main/java/org/sdo/iotplatformsdk/to0scheduler/to0client/To0ClientConfiguration.java | bprashan/iot-platform-sdk | 839fba8004a6d575a1e55fb91d6a720d70de07fa | [
"Apache-2.0"
] | null | null | null | 37.081761 | 97 | 0.763569 | 995,008 | /*******************************************************************************
* Copyright 2020 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package org.sdo.iotplatformsdk.to0scheduler.to0client;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.cert.Certificate;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import javax.net.ssl.SSLContext;
import org.sdo.iotplatformsdk.common.protocol.config.CertificateFactoryBean;
import org.sdo.iotplatformsdk.common.protocol.config.ClientHttpRequestFactoryCreatingFactoryBean;
import org.sdo.iotplatformsdk.common.protocol.config.PrivateKeyFactoryBean;
import org.sdo.iotplatformsdk.common.protocol.config.SdoProperties;
import org.sdo.iotplatformsdk.common.protocol.config.SecureRandomFactoryBean;
import org.sdo.iotplatformsdk.common.protocol.config.SimpleWaitSecondsBuilderFactoryBean;
import org.sdo.iotplatformsdk.common.protocol.config.SslContextFactoryBean;
import org.sdo.iotplatformsdk.common.protocol.config.WaitSecondsBuilder;
import org.sdo.iotplatformsdk.common.protocol.security.CryptoLevel;
import org.sdo.iotplatformsdk.common.protocol.security.CryptoLevel11;
import org.sdo.iotplatformsdk.common.protocol.security.SignatureService;
import org.sdo.iotplatformsdk.common.protocol.security.SignatureServiceFactory;
import org.sdo.iotplatformsdk.common.protocol.security.Signatures;
import org.sdo.iotplatformsdk.common.protocol.types.SignatureBlock;
import org.sdo.iotplatformsdk.common.protocol.types.To1SdoRedirect;
import org.sdo.iotplatformsdk.common.protocol.util.Destroyer;
import org.sdo.iotplatformsdk.to0scheduler.to0library.To0Client;
import org.sdo.iotplatformsdk.to0scheduler.to0library.To0ClientSession;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.http.client.ClientHttpRequestFactory;
@Configuration
@EnableAutoConfiguration
@EnableConfigurationProperties(SdoProperties.class)
public class To0ClientConfiguration {
private final SdoProperties properties;
public To0ClientConfiguration(SdoProperties properties) {
this.properties = properties;
}
@Bean
protected FactoryBean<Certificate> certificateFactoryBean() {
CertificateFactoryBean factory = new CertificateFactoryBean();
factory.setUri(getProperties().getOwner().getCert());
return factory;
}
@Bean
protected FactoryBean<ClientHttpRequestFactory> clientHttpRequestFactoryCreatingFactoryBean() {
return new ClientHttpRequestFactoryCreatingFactoryBean();
}
@Bean
@SuppressWarnings("unused")
protected CryptoLevel cryptoLevel() {
return new CryptoLevel11();
}
protected SdoProperties getProperties() {
return properties;
}
@Bean
protected FactoryBean<PrivateKey> privateKeyFactoryBean() {
PrivateKeyFactoryBean factory = new PrivateKeyFactoryBean();
factory.setUri(getProperties().getOwner().getKey());
return factory;
}
@Bean
protected FactoryBean<SecureRandom> secureRandomFactoryBean() {
return new SecureRandomFactoryBean();
}
@Bean
@SuppressWarnings("unused")
protected SignatureService signatureService() {
return data -> CompletableFuture.supplyAsync(() -> {
try (Destroyer<PrivateKey> hkey = new Destroyer<>(privateKeyFactoryBean().getObject())) {
final Signature s = Signatures.getInstance(hkey.get());
s.initSign(hkey.get());
s.update(StandardCharsets.US_ASCII.encode(CharBuffer.wrap(data)));
return new SignatureBlock(CharBuffer.wrap(data),
Objects.requireNonNull(certificateFactoryBean().getObject()).getPublicKey(),
ByteBuffer.wrap(s.sign()));
} catch (Exception e) {
throw new RuntimeException(e);
}
});
}
@Bean
@SuppressWarnings("unused")
protected SignatureServiceFactory signatureServiceFactory() {
return (uuids) -> signatureService();
}
@Bean
protected FactoryBean<SSLContext> sslContextFactoryBean() {
return new SslContextFactoryBean();
}
@Bean
@Scope("prototype")
protected To0Client to0Client() {
return new To0Client();
}
@Bean
@Scope("prototype")
protected To0ClientSession to0Session() {
return new To0ClientSession(signatureServiceFactory());
}
@Bean
protected To1SdoRedirect to1SdoRedirect() {
SdoProperties.To0.OwnerSign ownerSign = getProperties().getTo0().getOwnerSign();
SdoProperties.To0.OwnerSign.To1d.Bo to1d = ownerSign.getTo1d().getBo();
return new To1SdoRedirect(to1d.getI1(), to1d.getDns1(), to1d.getPort1(), null);
}
@Bean
protected FactoryBean<WaitSecondsBuilder> waitSecondsBuilderFactoryBean() {
SimpleWaitSecondsBuilderFactoryBean bean = new SimpleWaitSecondsBuilderFactoryBean();
bean.setWaitSeconds(getProperties().getTo0().getOwnerSign().getTo0d().getWs());
return bean;
}
}
|
922f2c8a9c3ca4a454c0958261045b34c3eb796c | 1,958 | java | Java | Variant Programs/4/4-7/Workspace/Trilled/DinersTimer.java | hjc851/SourceCodePlagiarismDetectionDataset | f67bc79576a8df85e8a7b4f5d012346e3a76db37 | [
"MIT"
] | null | null | null | Variant Programs/4/4-7/Workspace/Trilled/DinersTimer.java | hjc851/SourceCodePlagiarismDetectionDataset | f67bc79576a8df85e8a7b4f5d012346e3a76db37 | [
"MIT"
] | null | null | null | Variant Programs/4/4-7/Workspace/Trilled/DinersTimer.java | hjc851/SourceCodePlagiarismDetectionDataset | f67bc79576a8df85e8a7b4f5d012346e3a76db37 | [
"MIT"
] | null | null | null | 27.577465 | 100 | 0.673647 | 995,009 | package Workspace.Trilled;
import Retailer.Trainmaster;
import Programmer.Database;
import Programmer.Work;
import java.util.ArrayDeque;
public class DinersTimer extends Programmer.Database {
public synchronized String initializationPseudonym() {
return "RR:";
}
public DinersTimer() {
this.happyStopper = (new java.util.ArrayDeque<>());
sentenceUnexpended = (NowLevel);
}
public synchronized void treatInfluent(Work procedures) {
happyStopper.addLast(procedures);
}
public java.util.ArrayDeque<Work> happyStopper;
public synchronized void optiBeat() {
if (typicalProceedings != null) {
typicalProceedings.orderedFunctionalChance(typicalProceedings.fixFunctionalChance() + 1);
sentenceUnexpended--;
if (typicalProceedings.fixFunctionalChance() == typicalProceedings.takeExecutionsDiameter()) {
typicalProceedings.layPassingMoment(this.findActualRetick());
this.realizedWork.addLast(typicalProceedings);
typicalProceedings = (null);
this.variWaving = (true);
}
if (sentenceUnexpended == 0 && typicalProceedings != null) {
if (happyStopper.isEmpty()) {
sentenceUnexpended = (NowLevel);
} else {
happyStopper.addLast(typicalProceedings);
typicalProceedings = (null);
this.variWaving = (true);
}
}
}
if (this.variWaving && typicalProceedings == null) {
this.anotherBurberryYears--;
if (anotherBurberryYears == 0) {
this.variWaving = (false);
this.anotherBurberryYears = (Trainmaster.SlayMoment);
}
} else {
if (typicalProceedings == null && !happyStopper.isEmpty()) {
typicalProceedings = (happyStopper.removeFirst());
cargoAct(typicalProceedings);
typicalProceedings.putBeginClock(this.findActualRetick());
sentenceUnexpended = (NowLevel);
}
}
}
public int sentenceUnexpended;
}
|
922f2dcc175d5124011830a25c41acfe60d92e2f | 693 | java | Java | src/main/java/local/tobbstr/demos/cleanarch/todo_in_spring/usecase/add_task_to_todo/infrastructure/AddTaskToTodoPresenterFactory.java | tobbstr/clean_arch-demo-todo_in_spring | 3dbffa19ec45726a7b2633f52878ca2484b9ece0 | [
"MIT"
] | 1 | 2021-08-02T00:29:15.000Z | 2021-08-02T00:29:15.000Z | src/main/java/local/tobbstr/demos/cleanarch/todo_in_spring/usecase/add_task_to_todo/infrastructure/AddTaskToTodoPresenterFactory.java | tobbstr/clean_arch-demo-todo_in_spring | 3dbffa19ec45726a7b2633f52878ca2484b9ece0 | [
"MIT"
] | null | null | null | src/main/java/local/tobbstr/demos/cleanarch/todo_in_spring/usecase/add_task_to_todo/infrastructure/AddTaskToTodoPresenterFactory.java | tobbstr/clean_arch-demo-todo_in_spring | 3dbffa19ec45726a7b2633f52878ca2484b9ece0 | [
"MIT"
] | null | null | null | 33 | 111 | 0.847042 | 995,010 | package local.tobbstr.demos.cleanarch.todo_in_spring.usecase.add_task_to_todo.infrastructure;
import org.springframework.stereotype.Component;
import local.tobbstr.demos.cleanarch.todo_in_spring.usecase.add_task_to_todo.adapter.AddTaskToTodoPresenter;
import local.tobbstr.demos.cleanarch.todo_in_spring.usecase.add_task_to_todo.adapter.AddTaskToTodoPresentation;
/**
* AddTaskToTodoPresenterFactory is an implementation of {@link AddTaskToTodoPresenterMaker}.
* @author tobias
*
*/
@Component
public class AddTaskToTodoPresenterFactory implements AddTaskToTodoPresenterMaker {
@Override
public AddTaskToTodoPresenter makePresenter() {
return new AddTaskToTodoPresentation();
}
}
|
922f2e102e2286b2753c68ee3ef1e7e6ab57faee | 5,777 | java | Java | ccn/org/ccnx/ccn/impl/repo/RepositoryDataHandler.java | buptn/CCNxTomcat | f029a531af1eb462553cb56b495ed0721d777eac | [
"Apache-2.0"
] | null | null | null | ccn/org/ccnx/ccn/impl/repo/RepositoryDataHandler.java | buptn/CCNxTomcat | f029a531af1eb462553cb56b495ed0721d777eac | [
"Apache-2.0"
] | null | null | null | ccn/org/ccnx/ccn/impl/repo/RepositoryDataHandler.java | buptn/CCNxTomcat | f029a531af1eb462553cb56b495ed0721d777eac | [
"Apache-2.0"
] | 4 | 2015-12-12T14:16:08.000Z | 2020-10-13T14:17:19.000Z | 33.587209 | 109 | 0.710403 | 995,011 | /*
* Part of the CCNx Java Library.
*
* Copyright (C) 2008, 2009, 2011, 2012 Palo Alto Research Center, Inc.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
* This library 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
* Lesser General Public License for more details. You should have received
* a copy of the GNU Lesser General Public License along with this library;
* if not, write to the Free Software Foundation, Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.ccnx.ccn.impl.repo;
import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Level;
import org.ccnx.ccn.config.SystemConfiguration;
import org.ccnx.ccn.impl.InterestTable;
import org.ccnx.ccn.impl.InterestTable.Entry;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.profiles.nameenum.NameEnumerationResponse;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.ContentObject;
import org.ccnx.ccn.protocol.Interest;
/**
* So the main listener can output interests sooner, we do the data store work
* in a separate thread.
*/
public class RepositoryDataHandler implements Runnable {
public static final int THROTTLE_TOP = 2000;
public static final int THROTTLE_BOTTOM = 1800;
private final RepositoryServer _server;
private final Queue<ContentObject> _queue = new ConcurrentLinkedQueue<ContentObject>();
private final InterestTable<ContentName> _pendingKeyChecks = new InterestTable<ContentName>();
private boolean _shutdown = false;
private boolean _shutdownComplete = false;
protected int _currentQueueSize;
protected boolean _throttled = false;
public RepositoryDataHandler(RepositoryServer server) {
_server = server;
}
public void add(ContentObject co) {
_currentQueueSize++;
if (!_throttled && _currentQueueSize > THROTTLE_TOP) {
_throttled = true;
_server.setThrottle(true);
}
_queue.add(co);
_queue.notify();
}
public void addKeyCheck(ContentName target) {
_pendingKeyChecks.add(new Interest(target), target);
}
/**
* The content listener runs this thread to store data using the content store.
* The thread also checks for policy updates which may reset the repository's
* namespace and sends "early" nameEnumerationResponses when requested by the
* store.
*
* @see RepositoryStore
*/
public void run() {
while (!_shutdownComplete) {
ContentObject co = null;
do {
co = _queue.poll();
if (null == co) {
if (_shutdown) {
synchronized (this) {
_shutdownComplete = true;
notifyAll();
}
return;
}
try {
_queue.wait(SystemConfiguration.MEDIUM_TIMEOUT);
} catch (InterruptedException e) {}
}
} while (null == co);
_currentQueueSize--;
if (_throttled && _currentQueueSize < THROTTLE_BOTTOM) {
_throttled = false;
_server.setThrottle(false);
}
try {
if (Log.isLoggable(Log.FAC_REPO, Level.FINER)) {
Log.finer(Log.FAC_REPO, "Saving content in: " + co.toString());
}
NameEnumerationResponse ner = _server.getRepository().saveContent(co);
if (!_shutdown) {
if (ner!=null && ner.hasNames()) {
_server.sendEnumerationResponse(ner);
}
}
// When a write or some syncs are first requested we don't know what key data
// was being used because this is in the ContentObject which of course we didn't
// have yet. Bbut we need this data to make sure the key is saved along with the file.
// Now we can find the key data and check if we have it already or need to get it
// too. Also the key locator that we dont have yet could have been a link. We
// didn't know that either. If it was we have to get the data it points to.
//
// Also we have to check for more locators associated with our new object
// and the objects pointed to by the links.
Entry<ContentName> entry = _pendingKeyChecks.removeMatch(co);
if (null != entry) {
ContentName nameToCheck = entry.value();
if (Log.isLoggable(Log.FAC_REPO, Level.FINER)) {
Log.finer(Log.FAC_REPO, "Processing key check entry: {0}", nameToCheck);
}
ContentName linkCheck = _server.getLinkedKeyTarget(co);
if (null != linkCheck) {
if (Log.isLoggable(Log.FAC_REPO, Level.FINER)) {
Log.finer(Log.FAC_REPO, "Processing key check entry for link: {0}", linkCheck);
}
Interest linkInterest = new Interest(linkCheck);
_server.doSync(linkInterest, linkInterest);
syncKeysForObject(co, linkCheck);
}
syncKeysForObject(co, nameToCheck);
}
} catch (Exception e) {
e.printStackTrace();
Log.logStackTrace(Level.WARNING, e);
}
}
}
private void syncKeysForObject(ContentObject co, ContentName name) throws RepositoryException, IOException {
ContentName target = _server.getKeyTargetFromObject(co, name);
if (null != target) {
if (Log.isLoggable(Log.FAC_REPO, Level.FINER)) {
Log.finer(Log.FAC_REPO, "Fetching key from dataHandler: " + target);
}
Interest interest = Interest.constructInterest(target, _server.getExcludes(), 1, 3, null, null);
addKeyCheck(target);
_server.doSync(interest, interest);
}
}
public void shutdown() {
_shutdown = true;
synchronized (this) {
while (!_shutdownComplete) {
try {
wait(SystemConfiguration.LONG_TIMEOUT);
} catch (InterruptedException e) {}
}
}
}
public int getCurrentQueueSize() {
return _currentQueueSize;
}
}
|
922f2e8a6c941812dac7ef845cd571992b57b1a9 | 1,287 | java | Java | HRM-ejb/src/java/cn/hanbell/hrm/ejb/DepartmentBean.java | hanbellgp/Hanbell-EAP | 6d2d85a6ca1306349bb1e6ad1e21d3b662ba29fb | [
"Apache-2.0"
] | null | null | null | HRM-ejb/src/java/cn/hanbell/hrm/ejb/DepartmentBean.java | hanbellgp/Hanbell-EAP | 6d2d85a6ca1306349bb1e6ad1e21d3b662ba29fb | [
"Apache-2.0"
] | 3 | 2019-08-11T23:42:24.000Z | 2020-02-19T07:40:00.000Z | HRM-ejb/src/java/cn/hanbell/hrm/ejb/DepartmentBean.java | hanbellgp/Hanbell-EAP | 6d2d85a6ca1306349bb1e6ad1e21d3b662ba29fb | [
"Apache-2.0"
] | 1 | 2018-01-11T01:08:23.000Z | 2018-01-11T01:08:23.000Z | 26.265306 | 91 | 0.651904 | 995,012 | /*
* 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 cn.hanbell.hrm.ejb;
import cn.hanbell.hrm.comm.SuperEJBForHRM;
import cn.hanbell.hrm.entity.Department;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.Query;
/**
*
* @author C0160
*/
@Stateless
@LocalBean
public class DepartmentBean extends SuperEJBForHRM<Department> {
public DepartmentBean() {
super(Department.class);
}
public Department findByDepartmentId(String id) {
Query query = getEntityManager().createNamedQuery("Department.findByDepartmentId");
query.setParameter("departmentId", id);
try {
Object o = query.getSingleResult();
return (Department) o;
} catch (Exception ex) {
return null;
}
}
public Department findByCode(String code) {
Query query = getEntityManager().createNamedQuery("Department.findByCode");
query.setParameter("code", code);
try {
Object o = query.getSingleResult();
return (Department) o;
} catch (Exception ex) {
return null;
}
}
}
|
922f305403a3bf6e92176edb0505e5c960a1f2b6 | 5,045 | java | Java | app/src/main/java/com/threepeople/dazzlecolourweather/view/ColorChangeableIconView.java | ThreePeopleTogether/Dazzle-colour-weather | c72f8a5b31bfd964c79b95bcb498631df8947cb8 | [
"Apache-2.0"
] | 1 | 2021-06-11T00:54:34.000Z | 2021-06-11T00:54:34.000Z | app/src/main/java/com/threepeople/dazzlecolourweather/view/ColorChangeableIconView.java | ThreePeopleTogether/Dazzle-colour-weather | c72f8a5b31bfd964c79b95bcb498631df8947cb8 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/threepeople/dazzlecolourweather/view/ColorChangeableIconView.java | ThreePeopleTogether/Dazzle-colour-weather | c72f8a5b31bfd964c79b95bcb498631df8947cb8 | [
"Apache-2.0"
] | 1 | 2021-06-06T03:02:41.000Z | 2021-06-06T03:02:41.000Z | 31.335404 | 119 | 0.597423 | 995,013 | package com.threepeople.dazzlecolourweather.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;
import com.threepeople.dazzlecolourweather.R;
/**
* 可变色的图标展示View.<br>
* 间接继承于{@link android.widget.ImageView},图标设置方法与其相同.<br><br>
*
* <p><b>可设置的属性:</b></p>
* <p><b>属性名</b></p> <b>值类型</b> <b>说明</b> <b>默认值</b> <br><br>
* <p>baseColor</p> 颜色值 图标原来的颜色 #FFFFFFFF <br><br>
* <p>goalColor</p> 颜色值 图标的新颜色 #FFFFFFFF <br><br>
*
* <p><b><font color="#FF0000">注意:</font></b></p>
* 1. 请确保baseColor与原来的图标颜色相同,否则可能失去预想的效果<br>
* 2. 原始图标请勿为透明,否则亦可能失去预想的效果<br>
*
* @see #setBaseColor(int)
* @see #setGoalColor(int)
* @see #setBaseAndGoalColor(int, int)
*/
public class ColorChangeableIconView extends AppCompatImageView {
private final ColorMatrix colorMatrix;
private ColorMatrixColorFilter colorFilter;
private ColorInfo baseColor;
private ColorInfo goalColor;
public ColorChangeableIconView(@NonNull Context context) {
this(context, null);
}
public ColorChangeableIconView(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public ColorChangeableIconView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
colorMatrix = new ColorMatrix();
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ColorChangeableIconView);
try {
baseColor = new ColorInfo(typedArray.getColor(R.styleable.ColorChangeableIconView_baseColor, Color.WHITE));
goalColor = new ColorInfo(typedArray.getColor(R.styleable.ColorChangeableIconView_goalColor, Color.WHITE));
} finally {
typedArray.recycle();
}
initColorFilter();
}
/**
* 设置图标原始的颜色.<br>
* 设置后将重新绘制.
*
* @param baseColor 图标的原始颜色
* @see #setGoalColor(int)
* @see #setBaseAndGoalColor(int, int)
*/
public void setBaseColor(int baseColor) {
this.baseColor = new ColorInfo(baseColor);
initColorFilter();
refresh();
}
/**
* 设置图标的新颜色.<br>
* 设置后将重绘.
*
* @param goalColor 图标的新颜色
* @see #setBaseColor(int)
* @see #setBaseAndGoalColor(int, int)
*/
public void setGoalColor(int goalColor) {
this.goalColor = new ColorInfo(goalColor);
initColorFilter();
refresh();
}
/**
* 同时设置图标的原始颜色和新颜色.<br>
* 设置后将重绘.
*
* @param baseColor 图标的原始颜色
* @param goalColor 图标的新颜色
* @see #setBaseColor(int)
* @see #setGoalColor(int)
*/
public void setBaseAndGoalColor(int baseColor, int goalColor) {
this.baseColor = new ColorInfo(baseColor);
this.goalColor = new ColorInfo(goalColor);
initColorFilter();
refresh();
}
private void initColorFilter() {
colorMatrix.set(new float[] {
1.0f, 0.0f, 0.0f, 0.0f, goalColor.r - baseColor.r,
0.0f, 1.0f, 0.0f, 0.0f, goalColor.g - baseColor.g,
0.0f, 0.0f, 1.0f, 0.0f, goalColor.b - baseColor.b,
0.0f, 0.0f, 0.0f, 1.0f, goalColor.a - baseColor.a
});
colorFilter = new ColorMatrixColorFilter(colorMatrix);
}
private void refresh() {
invalidate();
requestLayout();
}
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if (drawable == null && (drawable = getBackground()) == null) {
super.onDraw(canvas);
return;
}
drawable.setColorFilter(colorFilter);
setImageDrawable(drawable);
setBackground(null);
super.onDraw(canvas);
}
private static class ColorInfo {
private final int a;
private final int r;
private final int g;
private final int b;
private ColorInfo(int color) {
a = color >> 24 & 0xFF;
r = (color & 0x00FF0000) >> 16;
g = (color & 0x0000FF00) >> 8;
b = color & 0x000000FF;
}
@NonNull
@Override
public String toString() {
String aHex = Integer.toHexString(a);
String rHex = Integer.toHexString(r);
String gHex = Integer.toHexString(g);
String bHex = Integer.toHexString(b);
return '#' + (a < 16 ? '0' + aHex : aHex) + (r < 16 ? '0' + rHex : rHex)
+ (g < 16 ? '0' + gHex : gHex) + (b < 16 ? '0' + bHex : bHex)
+ '(' + a + ", " + r + ", " + g + ", " + b + ')';
}
}
}
|
922f30d87923c259e0b4c685c6da52d09be0014b | 2,332 | java | Java | src/main/java/com/automaton/zwave/AbstractZSwitch.java | Vijay2win/automaton | 3df52a548383fe8d00011d2d332a7903320f95d1 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/automaton/zwave/AbstractZSwitch.java | Vijay2win/automaton | 3df52a548383fe8d00011d2d332a7903320f95d1 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/automaton/zwave/AbstractZSwitch.java | Vijay2win/automaton | 3df52a548383fe8d00011d2d332a7903320f95d1 | [
"Apache-2.0"
] | null | null | null | 27.761905 | 97 | 0.682247 | 995,014 | package com.automaton.zwave;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.automaton.accessories.Light;
import com.automaton.characteristics.CharacteristicCallback;
public abstract class AbstractZSwitch {
protected static final Logger logger = LoggerFactory.getLogger(AbstractZSwitch.class);
private static final String DEFAULT_MODEL = "on-off-switch";
private static final String DEFAULT_MANUFACTURER = "VJ, Inc.";
private final int id;
private final String serial;
private final String label;
protected Set<CharacteristicCallback> subscribeCallback = new HashSet<>();
public volatile boolean powerState = false;
public AbstractZSwitch(int id, String name) {
this.id = id;
this.serial = "VJ123456." + id;
this.label = name;
}
public int getId() {
return this.id;
}
public String getLabel() {
return this.label;
}
public String getSerialNumber() {
return this.serial;
}
public String getModel() {
return DEFAULT_MODEL;
}
public String getManufacturer() {
return DEFAULT_MANUFACTURER;
}
public void identify() {
logger.info("Identifying {}", this.label);
}
public CompletableFuture<Boolean> getPowerState() {
return CompletableFuture.completedFuture(Boolean.valueOf(this.powerState));
}
public CompletableFuture<Void> setPowerState(boolean powerState) throws Exception {
this.powerState = powerState;
for (CharacteristicCallback callback : this.subscribeCallback)
callback.changed();
return CompletableFuture.completedFuture(null);
}
public void subscribe(CharacteristicCallback callback) {
if (callback != null)
this.subscribeCallback.add(callback);
}
public void unsubscribe() {
this.subscribeCallback = subscribeCallback.stream().filter(input -> !input.isRemovable())
.collect(Collectors.toSet());
}
public static class ZOnOffSwitch extends AbstractZSwitch implements Light {
public ZOnOffSwitch(int id, String name) {
super(id, name);
}
}
}
|
922f31468d27bcb89fc395b07a5634d8ab71bd2f | 1,091 | java | Java | annotationprocessingtesting/src/main/java/com/tickaroo/tikxml/annotationprocessing/element/autovalue/ServerConfig.java | mariopce/tikxml | 5c4219ac33395eaff089062b5cc796ff51425a63 | [
"Apache-2.0"
] | 436 | 2015-11-26T11:43:02.000Z | 2022-03-26T02:46:50.000Z | annotationprocessingtesting/src/main/java/com/tickaroo/tikxml/annotationprocessing/element/autovalue/ServerConfig.java | mariopce/tikxml | 5c4219ac33395eaff089062b5cc796ff51425a63 | [
"Apache-2.0"
] | 152 | 2015-12-12T14:01:01.000Z | 2021-12-05T08:37:15.000Z | annotationprocessingtesting/src/main/java/com/tickaroo/tikxml/annotationprocessing/element/autovalue/ServerConfig.java | mariopce/tikxml | 5c4219ac33395eaff089062b5cc796ff51425a63 | [
"Apache-2.0"
] | 76 | 2016-02-02T02:38:56.000Z | 2022-03-15T07:49:55.000Z | 31.171429 | 75 | 0.756187 | 995,015 | /*
* Copyright (C) 2015 Hannes Dorfmann
* Copyright (C) 2015 Tickaroo, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.tickaroo.tikxml.annotationprocessing.element.autovalue;
import com.google.auto.value.AutoValue;
import com.tickaroo.tikxml.annotation.Attribute;
import com.tickaroo.tikxml.annotation.PropertyElement;
import com.tickaroo.tikxml.annotation.Xml;
/**
* @author Hannes Dorfmann
*/
@Xml
@AutoValue
public abstract class ServerConfig {
@Attribute public abstract boolean enabled();
@PropertyElement public abstract String ip();
}
|
922f32c55ec6a093a0498492b6dd145e4b12c4fe | 1,326 | java | Java | backend/src/main/java/com/mcoding/modular/auth/config/AuthInterceptor.java | gnanquanmama/java_web_staging | 93e90ce597ab21a7dcf093e931bfe2952e57df83 | [
"MIT"
] | 125 | 2020-08-01T14:20:45.000Z | 2022-03-09T07:22:52.000Z | backend/src/main/java/com/mcoding/modular/auth/config/AuthInterceptor.java | gnanquanmama/fast_develp_java_web | 93e90ce597ab21a7dcf093e931bfe2952e57df83 | [
"MIT"
] | 12 | 2020-03-17T15:41:40.000Z | 2020-07-27T15:47:08.000Z | backend/src/main/java/com/mcoding/modular/auth/config/AuthInterceptor.java | gnanquanmama/fast_develp_java_web | 93e90ce597ab21a7dcf093e931bfe2952e57df83 | [
"MIT"
] | 17 | 2020-08-06T03:15:18.000Z | 2021-09-24T10:04:25.000Z | 30.136364 | 121 | 0.731523 | 995,016 | package com.mcoding.modular.auth.config;
import com.alibaba.fastjson.JSON;
import com.mcoding.base.core.rest.ResponseCode;
import com.mcoding.base.core.rest.ResponseResult;
import com.mcoding.modular.system.user.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
/**
* @author wzt on 2019/11/13.
* @version 1.0
*/
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
SysUser loginUser = (SysUser) request.getSession().getAttribute("currentUser");
if (loginUser == null) {
this.write(response, ResponseResult.fail(ResponseCode.UNAUTHORIZED, "请先登录"));
return false;
}
return true;
}
private void write(HttpServletResponse response, ResponseResult<String> responseResult) throws Exception {
response.setContentType("application/json;charset=UTF-8");
PrintWriter writer = response.getWriter();
writer.write(JSON.toJSONString(responseResult));
writer.flush();
writer.close();
}
}
|
922f3439816c66575316da40ca950a9f0f76c743 | 488 | java | Java | src/test/java/com/liyongquan/dp/LargestDivisibleSubsetTest.java | liyongquan/leetcode-project | 9c84215780b7cd07309dc72488f58bc8e24cb1ef | [
"Apache-2.0"
] | 5 | 2021-03-27T02:41:22.000Z | 2022-01-18T02:54:30.000Z | src/test/java/com/liyongquan/dp/LargestDivisibleSubsetTest.java | liyongquan/leetcode-project | 9c84215780b7cd07309dc72488f58bc8e24cb1ef | [
"Apache-2.0"
] | null | null | null | src/test/java/com/liyongquan/dp/LargestDivisibleSubsetTest.java | liyongquan/leetcode-project | 9c84215780b7cd07309dc72488f58bc8e24cb1ef | [
"Apache-2.0"
] | null | null | null | 23.238095 | 86 | 0.67623 | 995,017 | package com.liyongquan.dp;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.*;
@Slf4j
public class LargestDivisibleSubsetTest {
private LargestDivisibleSubset lds = new LargestDivisibleSubset();
@Test
public void largestDivisibleSubset() {
List<Integer> res = lds.largestDivisibleSubset(new int[]{2, 10000, 10000001});
for (Integer re : res) {
log.info("{}", re);
}
}
} |
922f348ba5bcc9acead7d075f4c20820fd770815 | 2,413 | java | Java | ScanQr.java | WooJunHo/SmartPowerManagementSystem | 55b6b8ac88073d9bc40c0394b69d6df7a168332c | [
"Unlicense"
] | null | null | null | ScanQr.java | WooJunHo/SmartPowerManagementSystem | 55b6b8ac88073d9bc40c0394b69d6df7a168332c | [
"Unlicense"
] | null | null | null | ScanQr.java | WooJunHo/SmartPowerManagementSystem | 55b6b8ac88073d9bc40c0394b69d6df7a168332c | [
"Unlicense"
] | null | null | null | 32.608108 | 105 | 0.617903 | 995,018 | package com.example.smartpowerclient;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import org.json.JSONException;
import org.json.JSONObject;
import static java.security.AccessController.getContext;
public class ScanQr extends AppCompatActivity {
//view Objects
//qr code scanner object
private IntentIntegrator qrScan;
public static final int sub = 1001;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_qr);
//View Objects
//intializing scan object
qrScan = new IntentIntegrator(this);
//scan option
qrScan.setPrompt("Scanning...");
//qrScan.setOrientationLocked(false);
qrScan.initiateScan();
}
//Getting the scan results
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
//qrcode 가 없으면
if (result.getContents() == null) {
Toast.makeText(ScanQr.this, "취소!", Toast.LENGTH_SHORT).show();
} else {
//qrcode 결과가 있으면
Toast.makeText(ScanQr.this, "스캔완료!", Toast.LENGTH_SHORT).show();
try {
//data를 json으로 변환
JSONObject obj = new JSONObject(result.getContents());
Intent intent = new Intent(getApplicationContext(), User.class);
intent.putExtra("POT",obj.getString("name"));
startActivityForResult(intent,sub);
} catch (JSONException e) {
e.printStackTrace();
//Toast.makeText(MainActivity.this, result.getContents(), Toast.LENGTH_LONG).show();
}
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
} |
922f34c6348c5c1d4be6b3befbffa7d04480b924 | 2,153 | java | Java | src/main/java/com/github/fluxw42/smappee/api/impl/ApplianceImpl.java | fluxw42/smappee-api | 7877ff250ab66ba72421999580f0202c077902a2 | [
"MIT"
] | 1 | 2021-11-20T13:47:15.000Z | 2021-11-20T13:47:15.000Z | src/main/java/com/github/fluxw42/smappee/api/impl/ApplianceImpl.java | fluxw42/smappee-api | 7877ff250ab66ba72421999580f0202c077902a2 | [
"MIT"
] | null | null | null | src/main/java/com/github/fluxw42/smappee/api/impl/ApplianceImpl.java | fluxw42/smappee-api | 7877ff250ab66ba72421999580f0202c077902a2 | [
"MIT"
] | null | null | null | 19.572727 | 140 | 0.659545 | 995,019 | package com.github.fluxw42.smappee.api.impl;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.fluxw42.smappee.api.Appliance;
import java.util.Objects;
/**
* Date: 6/17/17 - 7:43 PM
*
* @author Jeroen Meulemeester
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class ApplianceImpl implements Appliance {
/**
* The appliance identifier
*/
private final long id;
/**
* The name of the appliance
*/
private final String name;
/**
* The appliance type
*/
private final String type;
/**
* Create a new appliance instance
*
* @param id The unique appliance id
* @param name The name of the appliance
* @param type The type of appliance
*/
@JsonCreator
public ApplianceImpl(@JsonProperty("id") final long id, @JsonProperty("name") final String name, @JsonProperty("type") final String type) {
this.id = id;
this.name = name;
this.type = type;
}
/**
* {@inheritDoc}
*/
@Override
public final long getId() {
return this.id;
}
/**
* {@inheritDoc}
*/
@Override
public final String getName() {
return this.name;
}
/**
* {@inheritDoc}
*/
@Override
public final String getType() {
return this.type;
}
/**
* {@inheritDoc}
*/
@Override
public final boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ApplianceImpl)) {
return false;
}
final ApplianceImpl appliance = (ApplianceImpl) o;
return getId() == appliance.getId() &&
Objects.equals(getType(), appliance.getType()) &&
Objects.equals(getName(), appliance.getName());
}
/**
* {@inheritDoc}
*/
@Override
public final int hashCode() {
return Objects.hash(getId(), getType(), getName());
}
/**
* {@inheritDoc}
*/
@Override
public final String toString() {
final StringBuilder sb = new StringBuilder("ApplianceImpl{");
sb.append("id=").append(id);
sb.append(", type='").append(type).append('\'');
sb.append(", name='").append(name).append('\'');
sb.append('}');
return sb.toString();
}
}
|
922f35da188753bfe8117169f7c12d32a0cb56b7 | 1,143 | java | Java | src/test/java/org/cucumber/utils/TestLogger.java | soloshah/TelesalesATCucumber | eb70b28519af2a3460dd28874c0d6cbe1ae5a641 | [
"MIT",
"Unlicense"
] | null | null | null | src/test/java/org/cucumber/utils/TestLogger.java | soloshah/TelesalesATCucumber | eb70b28519af2a3460dd28874c0d6cbe1ae5a641 | [
"MIT",
"Unlicense"
] | null | null | null | src/test/java/org/cucumber/utils/TestLogger.java | soloshah/TelesalesATCucumber | eb70b28519af2a3460dd28874c0d6cbe1ae5a641 | [
"MIT",
"Unlicense"
] | null | null | null | 25.4 | 78 | 0.537183 | 995,020 | package org.cucumber.utils;
import org.apache.log4j.Logger;
public final class TestLogger {
final static Logger logger = Logger.getLogger(TestLogger.class);
public enum Entry {
Step, Check, Info, Error
}
public static void LogTestHasStarted(String test) {
Info("================================================================ ::");
Info("================================================================ ::");
Info("Starting Test: " + test);
Info("================================================================ ::");
Info("================================================================ ::");
}
public static void Step(String message) {
LogMessage(message, Entry.Step);
}
public static void Check(String message) {
LogMessage(message, Entry.Check);
}
public static void Info(String message) {
LogMessage(message, Entry.Info);
}
public static void Error(String message, Exception ex) {
LogMessage(message, ex);
}
private static void LogMessage(String message, Entry entryType) {
logger.info(entryType + ": " + message);
}
private static void LogMessage(String message, Exception ex) {
}
}
|
922f35f07413ccc6f8e9690c5e6d1440253ff59f | 3,740 | java | Java | src/main/java/svenhjol/charm/tweaks/module/CauldronWaterSource.java | Nanamiya738/Charm | 0acf74319b530f0abda8558e9e790e349313df86 | [
"MIT"
] | null | null | null | src/main/java/svenhjol/charm/tweaks/module/CauldronWaterSource.java | Nanamiya738/Charm | 0acf74319b530f0abda8558e9e790e349313df86 | [
"MIT"
] | null | null | null | src/main/java/svenhjol/charm/tweaks/module/CauldronWaterSource.java | Nanamiya738/Charm | 0acf74319b530f0abda8558e9e790e349313df86 | [
"MIT"
] | null | null | null | 42.022472 | 120 | 0.635561 | 995,021 | package svenhjol.charm.tweaks.module;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.potion.PotionUtils;
import net.minecraft.potion.Potions;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.SoundEvent;
import net.minecraft.util.SoundEvents;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.event.entity.player.FillBucketEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import svenhjol.charm.Charm;
import svenhjol.charm.base.CharmCategories;
import svenhjol.meson.MesonModule;
import svenhjol.meson.helper.CauldronHelper;
import svenhjol.meson.helper.PlayerHelper;
import svenhjol.meson.helper.PotionHelper;
import svenhjol.meson.iface.Module;
@Module(mod = Charm.MOD_ID, category = CharmCategories.TWEAKS, hasSubscriptions = true,
description = "Cauldrons can be used as a permanent water source when sneaking.")
public class CauldronWaterSource extends MesonModule {
@SubscribeEvent
public void onBucketUse(FillBucketEvent event) {
if (event.getEntityLiving() != null
&& event.getEntityLiving() instanceof PlayerEntity
&& PlayerHelper.isCrouching((PlayerEntity) event.getEntityLiving())
) {
PlayerEntity player = (PlayerEntity) event.getEntityLiving();
if (event.getTarget() != null) {
BlockState state = player.getEntityWorld().getBlockState(new BlockPos(event.getTarget().getHitVec()));
if (CauldronHelper.isFull(state)) {
event.setCanceled(true);
}
}
}
}
@SubscribeEvent
public void onCauldronUse(PlayerInteractEvent.RightClickBlock event) {
if (event.getWorld().getBlockState(event.getPos()).getBlock() == Blocks.CAULDRON && event.getPlayer() != null) {
PlayerEntity player = event.getPlayer();
World world = player.world;
ItemStack held = player.getHeldItem(event.getHand());
BlockState state = event.getWorld().getBlockState(event.getPos());
if (PlayerHelper.isCrouching(player)) {
ItemStack item = null;
SoundEvent sound = null;
if (CauldronHelper.hasWater(state) && held.getItem() == Items.GLASS_BOTTLE) {
item = PotionHelper.getFilledWaterBottle();
sound = SoundEvents.ITEM_BOTTLE_FILL;
} else if (CauldronHelper.isFull(state) && held.getItem() == Items.BUCKET) {
item = new ItemStack(Items.WATER_BUCKET);
sound = SoundEvents.ITEM_BUCKET_FILL;
}
if (item != null) {
event.setResult(Event.Result.DENY);
PlayerHelper.setHeldItem(player, event.getHand(), item);
if (sound != null) {
world.playSound(null, player.getPosition(), sound, SoundCategory.BLOCKS, 1.0F, 1.0F);
}
}
} else {
// don't activate cauldron if stack contains multiple water bottles
if (held.getItem() == Items.POTION
&& PotionUtils.getPotionFromItem(held) == Potions.WATER
&& held.getCount() > 1
) {
event.setResult(Event.Result.DENY);
event.setCanceled(true);
}
}
}
}
}
|
922f374770fe4f3c46e39f557f2351444a7eda71 | 1,766 | java | Java | modules/citrus-admin/src/main/java/com/consol/citrus/admin/model/TestResult.java | greyowlone/citrus | d4c913eec13132282e209284b32fd2cecd82743e | [
"Apache-2.0"
] | null | null | null | modules/citrus-admin/src/main/java/com/consol/citrus/admin/model/TestResult.java | greyowlone/citrus | d4c913eec13132282e209284b32fd2cecd82743e | [
"Apache-2.0"
] | null | null | null | modules/citrus-admin/src/main/java/com/consol/citrus/admin/model/TestResult.java | greyowlone/citrus | d4c913eec13132282e209284b32fd2cecd82743e | [
"Apache-2.0"
] | 1 | 2021-03-25T17:39:49.000Z | 2021-03-25T17:39:49.000Z | 20.298851 | 75 | 0.611552 | 995,022 | /*
* Copyright 2006-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 com.consol.citrus.admin.model;
/**
* @author Christoph Deppisch
* @since 1.3.1
*/
public class TestResult {
private TestCaseData testCase;
private boolean success;
private String stackTrace;
private String failureStack;
/**
* @return
*/
public TestCaseData getTestCase() {
return testCase;
}
/**
* @param value
*/
public void setTestCase(TestCaseData value) {
this.testCase = value;
}
/**
* @return
*/
public boolean isSuccess() {
return success;
}
/**
* @param value
*/
public void setSuccess(boolean value) {
this.success = value;
}
/**
* @return
*/
public String getStackTrace() {
return stackTrace;
}
/**
* @param value
*/
public void setStackTrace(String value) {
this.stackTrace = value;
}
/**
* @return
*/
public String getFailureStack() {
return failureStack;
}
/**
* @param value
*/
public void setFailureStack(String value) {
this.failureStack = value;
}
}
|
922f3764edc9bc446fbc376cec500a16b93fc9c3 | 4,029 | java | Java | jetty-websocket/websocket-jetty-api/src/main/java/org/eclipse/jetty/websocket/api/UpgradeResponse.java | simple569/jetty.project | d681f108536442f29b6bde54042e56220ad2bc82 | [
"Apache-2.0"
] | 4 | 2017-07-19T23:27:10.000Z | 2021-01-02T11:12:53.000Z | jetty-websocket/websocket-jetty-api/src/main/java/org/eclipse/jetty/websocket/api/UpgradeResponse.java | simple569/jetty.project | d681f108536442f29b6bde54042e56220ad2bc82 | [
"Apache-2.0"
] | 6 | 2021-12-19T02:33:51.000Z | 2022-01-26T08:48:34.000Z | jetty-websocket/websocket-jetty-api/src/main/java/org/eclipse/jetty/websocket/api/UpgradeResponse.java | simple569/jetty.project | d681f108536442f29b6bde54042e56220ad2bc82 | [
"Apache-2.0"
] | null | null | null | 27.786207 | 118 | 0.621494 | 995,023 | //
// ========================================================================
// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under
// the terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0
//
// This Source Code may also be made available under the following
// Secondary Licenses when the conditions for such availability set
// forth in the Eclipse Public License, v. 2.0 are satisfied:
// the Apache License v2.0 which is available at
// https://www.apache.org/licenses/LICENSE-2.0
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.websocket.api;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.jetty.websocket.api.extensions.ExtensionConfig;
/**
* The HTTP Upgrade to WebSocket Response
*/
public interface UpgradeResponse
{
/**
* Add a header value to the response.
*
* @param name the header name
* @param value the header value
*/
void addHeader(String name, String value);
/**
* Get the accepted WebSocket protocol.
*
* @return the accepted WebSocket protocol.
*/
String getAcceptedSubProtocol();
/**
* Get the list of extensions that should be used for the websocket.
*
* @return the list of negotiated extensions to use.
*/
List<ExtensionConfig> getExtensions();
/**
* Get a header value
*
* @param name the header name
* @return the value (null if header doesn't exist)
*/
String getHeader(String name);
/**
* Get the header names
*
* @return the set of header names
*/
Set<String> getHeaderNames();
/**
* Get the headers map
*
* @return the map of headers
*/
Map<String, List<String>> getHeaders();
/**
* Get the multi-value header value
*
* @param name the header name
* @return the list of values (null if header doesn't exist)
*/
List<String> getHeaders(String name);
/**
* Get the HTTP Response Status Code
*
* @return the status code
*/
int getStatusCode();
/**
* Issue a forbidden upgrade response.
* <p>
* This means that the websocket endpoint was valid, but the conditions to use a WebSocket resulted in a forbidden
* access.
* <p>
* Use this when the origin or authentication is invalid.
*
* @param message the short 1 line detail message about the forbidden response
* @throws IOException if unable to send the forbidden
*/
void sendForbidden(String message) throws IOException;
/**
* Set the accepted WebSocket Protocol.
*
* @param protocol the protocol to list as accepted
*/
void setAcceptedSubProtocol(String protocol);
/**
* Set the list of extensions that are approved for use with this websocket.
* <p>
* Notes:
* <ul>
* <li>Per the spec you cannot add extensions that have not been seen in the {@link UpgradeRequest}, just remove
* entries you don't want to use</li>
* <li>If this is unused, or a null is passed, then the list negotiation will follow default behavior and use the
* complete list of extensions that are
* available in this WebSocket server implementation.</li>
* </ul>
*
* @param extensions the list of extensions to use.
*/
void setExtensions(List<ExtensionConfig> extensions);
/**
* Set a header
* <p>
* Overrides previous value of header (if set)
*
* @param name the header name
* @param value the header value
*/
void setHeader(String name, String value);
/**
* Set the HTTP Response status code
*
* @param statusCode the status code
*/
void setStatusCode(int statusCode);
}
|
922f37662f2ad03a54eb258250ffcb8ce2453d07 | 806 | java | Java | xmall/generatorSqlmapCustom/src/cn/exrick/manager/pojo/TbItemDesc.java | YouGuangAnYue/MyShop | 30a04ac99f0b60e3c22f17b8443762e5e7fdbd58 | [
"Apache-2.0"
] | 1 | 2020-09-19T16:01:09.000Z | 2020-09-19T16:01:09.000Z | xmall/generatorSqlmapCustom/src/cn/exrick/manager/pojo/TbItemDesc.java | YouGuangAnYue/MyShop | 30a04ac99f0b60e3c22f17b8443762e5e7fdbd58 | [
"Apache-2.0"
] | 15 | 2019-11-01T08:05:01.000Z | 2022-03-31T20:29:35.000Z | xmall/generatorSqlmapCustom/src/cn/exrick/manager/pojo/TbItemDesc.java | YouGuangAnYue/MyShop | 30a04ac99f0b60e3c22f17b8443762e5e7fdbd58 | [
"Apache-2.0"
] | 1 | 2020-09-19T16:00:30.000Z | 2020-09-19T16:00:30.000Z | 17.911111 | 66 | 0.609181 | 995,024 | package cn.exrick.manager.pojo;
import java.util.Date;
public class TbItemDesc {
private Long itemId;
private Date created;
private Date updated;
private String itemDesc;
public Long getItemId() {
return itemId;
}
public void setItemId(Long itemId) {
this.itemId = itemId;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
public String getItemDesc() {
return itemDesc;
}
public void setItemDesc(String itemDesc) {
this.itemDesc = itemDesc == null ? null : itemDesc.trim();
}
} |
922f38d64c63256605db66c67e2fac93ac7ae2eb | 1,061 | java | Java | src/br/lojaroupa/bd/model/Cliente.java | vinimussio1/LojaGames | 214d540e613a15e2ddceee32493cf34e12dda0e0 | [
"MIT"
] | null | null | null | src/br/lojaroupa/bd/model/Cliente.java | vinimussio1/LojaGames | 214d540e613a15e2ddceee32493cf34e12dda0e0 | [
"MIT"
] | null | null | null | src/br/lojaroupa/bd/model/Cliente.java | vinimussio1/LojaGames | 214d540e613a15e2ddceee32493cf34e12dda0e0 | [
"MIT"
] | null | null | null | 17.683333 | 79 | 0.590952 | 995,025 | /*
* 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 br.lojaroupa.bd.model;
/**
*
* @author JoaoPaulo
*/
public class Cliente {
private String nome;
private String rg;
private String cpf;
private String sexo;
private String telefone;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getRg() {
return rg;
}
public void setRg(String rg) {
this.rg = rg;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getSexo() {
return sexo;
}
public void setSexo(String sexo) {
this.sexo = sexo;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
}
|
922f391d5e5130a47a0fe422dd31449ddd85f7c4 | 1,522 | java | Java | src/main/java/com/azwebdesign/service/ListPageService.java | PankajNalawade/selenium-testng | 2084d9849445d0efa23fb7ab6ec89d7ce8ee80b8 | [
"MIT"
] | null | null | null | src/main/java/com/azwebdesign/service/ListPageService.java | PankajNalawade/selenium-testng | 2084d9849445d0efa23fb7ab6ec89d7ce8ee80b8 | [
"MIT"
] | null | null | null | src/main/java/com/azwebdesign/service/ListPageService.java | PankajNalawade/selenium-testng | 2084d9849445d0efa23fb7ab6ec89d7ce8ee80b8 | [
"MIT"
] | 3 | 2018-08-30T10:35:37.000Z | 2020-04-11T11:11:50.000Z | 28.716981 | 84 | 0.687911 | 995,026 | package com.azwebdesign.service;
import com.azwebdesign.MyDriver;
import com.azwebdesign.page.ListPage;
import com.azwebdesign.page.SubmitPage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class ListPageService {
private WebDriver driver;
@Autowired
public void setDriver(MyDriver myDriver) {
this.driver = myDriver.getDriver();
}
public List<WebElement> getAllThings() {
ListPage listPage = new ListPage(driver);
return listPage.getThings();
}
public boolean findItemWithTitle(String titleContains) {
boolean found = false;
for(WebElement thing : getAllThings()) {
WebElement title = thing.findElement(By.className("title"));
if (title.getText().contains(titleContains)) {
found = true;
break;
}
}
return found;
}
public void clickSubmitLink() {
ListPage listPage = new ListPage(driver);
listPage.getSubmitLink().click();
// wait for page to load
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.urlContains(new SubmitPage(driver).getUrl()));
}
}
|
922f39e0ec2db9e2fbb03799c02070f34e0dc218 | 1,385 | java | Java | src/test/java/io/schinzel/basicutils/thrower/ThrowerMessageTest.java | Schinzel/basic-utils | 4153d60981775aec43b400208eeec4e09a1d71a8 | [
"Apache-2.0"
] | 4 | 2017-05-04T08:05:43.000Z | 2018-06-27T22:30:51.000Z | src/test/java/io/schinzel/basicutils/thrower/ThrowerMessageTest.java | Schinzel/basic-utils | 4153d60981775aec43b400208eeec4e09a1d71a8 | [
"Apache-2.0"
] | 10 | 2017-02-15T19:22:27.000Z | 2017-04-02T18:34:26.000Z | src/test/java/io/schinzel/basicutils/thrower/ThrowerMessageTest.java | Schinzel/basic-utils | 4153d60981775aec43b400208eeec4e09a1d71a8 | [
"Apache-2.0"
] | 1 | 2017-01-03T06:17:44.000Z | 2017-01-03T06:17:44.000Z | 32.209302 | 123 | 0.67509 | 995,027 | package io.schinzel.basicutils.thrower;
import io.schinzel.basicutils.thrower.ThrowerMessage;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
public class ThrowerMessageTest {
@Test
public void message_ConstructorTrue_ThrowsException() {
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> ThrowerMessage.create(true).message("My message"))
.withMessageStartingWith("My message");
}
@Test
public void message_ConstructorFalse_NoException() {
assertThatCode(() ->
new ThrowerMessage(false).message("My message")).doesNotThrowAnyException();
}
@Test
public void message_CreateFalse_NoException() {
assertThatCode(() ->
ThrowerMessage.create(false).message("Any message")).doesNotThrowAnyException();
}
@Test
public void message_Format_CorrectString() {
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> ThrowerMessage.create(true)
.message("The value %1$d in variable '%2$s' is too small. Min value is %3$d.", 123, "my_var", 100))
.withMessageStartingWith("The value 123 in variable 'my_var' is too small. Min value is 100.");
}
} |
922f3a6430641d39f380eedbc4611ad7258bf75d | 1,143 | java | Java | mat-fhir-services/src/main/java/gov/cms/mat/fhir/services/summary/FhirLibraryResourceValidationResult.java | laxmanvijay/QDM-QICore-Conversion | c13fb6bddbac435181701b2fcdc15a483838093e | [
"CC0-1.0"
] | 5 | 2019-12-05T20:52:16.000Z | 2021-04-13T20:00:40.000Z | mat-fhir-services/src/main/java/gov/cms/mat/fhir/services/summary/FhirLibraryResourceValidationResult.java | laxmanvijay/QDM-QICore-Conversion | c13fb6bddbac435181701b2fcdc15a483838093e | [
"CC0-1.0"
] | 45 | 2020-06-02T15:18:15.000Z | 2021-09-21T12:21:46.000Z | mat-fhir-services/src/main/java/gov/cms/mat/fhir/services/summary/FhirLibraryResourceValidationResult.java | laxmanvijay/QDM-QICore-Conversion | c13fb6bddbac435181701b2fcdc15a483838093e | [
"CC0-1.0"
] | 3 | 2021-04-13T20:00:43.000Z | 2021-06-21T17:37:14.000Z | 30.078947 | 102 | 0.783027 | 995,028 | package gov.cms.mat.fhir.services.summary;
import gov.cms.mat.fhir.commons.objects.FhirResourceValidationResult;
import gov.cms.mat.fhir.rest.dto.ConversionType;
import gov.cms.mat.fhir.rest.dto.LibraryConversionResults;
import java.util.ArrayList;
import java.util.List;
public class FhirLibraryResourceValidationResult extends FhirResourceValidationResult {
List<LibraryConversionResults> libraryConversionResults = new ArrayList<>();
private ConversionType libraryConversionType;
public FhirLibraryResourceValidationResult(String id) {
super(id, "Library");
}
public List<LibraryConversionResults> getLibraryConversionResults() {
return libraryConversionResults;
}
public void setLibraryConversionResults(List<LibraryConversionResults> libraryConversionResults) {
this.libraryConversionResults = libraryConversionResults;
}
public ConversionType getLibraryConversionType() {
return libraryConversionType;
}
public void setLibraryConversionType(ConversionType libraryConversionType) {
this.libraryConversionType = libraryConversionType;
}
}
|
922f3dd932e05cd203b28822d3590a5ceadcbe9b | 470 | java | Java | schedoscope-export/src/test/java/org/schedoscope/export/ftp/upload/UploaderTest.java | juliankeppel/schedoscope | bdd41e428132223dfdcd82921d745168bed6fc89 | [
"Apache-2.0"
] | 112 | 2015-05-12T19:30:58.000Z | 2022-01-13T09:26:56.000Z | schedoscope-export/src/test/java/org/schedoscope/export/ftp/upload/UploaderTest.java | juliankeppel/schedoscope | bdd41e428132223dfdcd82921d745168bed6fc89 | [
"Apache-2.0"
] | 44 | 2015-06-24T13:53:05.000Z | 2018-03-27T08:25:32.000Z | schedoscope-export/src/test/java/org/schedoscope/export/ftp/upload/UploaderTest.java | juliankeppel/schedoscope | bdd41e428132223dfdcd82921d745168bed6fc89 | [
"Apache-2.0"
] | 33 | 2015-07-27T12:51:58.000Z | 2021-12-15T17:27:10.000Z | 26.111111 | 81 | 0.723404 | 995,029 | package org.schedoscope.export.ftp.upload;
import org.junit.Test;
public class UploaderTest {
@Test
public void testEncrypetedKey() throws Exception {
Uploader.checkPrivateKey("src/test/resources/keys/id_rsa_encrypted");
assert (true);
}
@Test(expected = IllegalArgumentException.class)
public void testNotEncryptedKey() throws Exception {
Uploader.checkPrivateKey("src/test/resources/keys/id_rsa_not_encrypted");
}
}
|
922f3e1382b4fef0466cd8552508844062b69166 | 4,323 | java | Java | src/test/java/Domain/EntityManagerTest.java | galrosenthal/Football-Workshop | 2fdf866393361a757cbd7c4a22c7124c5a0782d6 | [
"Unlicense"
] | 1 | 2020-07-22T14:40:23.000Z | 2020-07-22T14:40:23.000Z | src/test/java/Domain/EntityManagerTest.java | galrosenthal/Football-Workshop | 2fdf866393361a757cbd7c4a22c7124c5a0782d6 | [
"Unlicense"
] | 10 | 2020-04-04T13:30:15.000Z | 2022-02-13T14:27:50.000Z | src/test/java/Domain/EntityManagerTest.java | galrosenthal/Football-Workshop | 2fdf866393361a757cbd7c4a22c7124c5a0782d6 | [
"Unlicense"
] | null | null | null | 39.66055 | 102 | 0.712931 | 995,030 | package Domain;
import DB.DBManager;
import DB.DBManagerForTest;
import Domain.Game.League;
import Domain.Game.PointsPolicy;
import Domain.Game.SchedulingPolicy;
import Domain.SystemLogger.SystemLoggerManager;
import Domain.Users.*;
import Generic.GenericTestAbstract;
import org.junit.*;
import java.util.List;
import static org.junit.Assert.*;
public class EntityManagerTest extends GenericTestAbstract {
@Test
public void doesLeagueExistsUTest() {
EntityManager.getInstance().removeLeagueByName("League Name");
assertFalse(EntityManager.getInstance().doesLeagueExists("League Name"));
}
@Test
public void addLeagueUTestUTest() {
assertFalse(EntityManager.getInstance().doesLeagueExists("League Name"));
EntityManager.getInstance().addLeague(new League("League Name", true));
assertTrue(EntityManager.getInstance().doesLeagueExists("League Name"));
EntityManager.getInstance().removeLeagueByName("League Name");
}
// @Test
// public void removeLeagueByNameUTest() {
// EntityManager.getInstance().addLeague(new League("League Name1", true));
// EntityManager.getInstance().addLeague(new League("League Name2", true));
// assertTrue(EntityManager.getInstance().removeLeagueByName("League Name2"));
// assertFalse(EntityManager.getInstance().doesLeagueExists("League Name2"));
// assertFalse(EntityManager.getInstance().removeLeagueByName("League Name2"));
// assertFalse(EntityManager.getInstance().removeLeagueByName("League Name2"));
// }
@Test
public void getRefereesUTest() {
assertTrue(EntityManager.getInstance().getReferees().isEmpty());
EntityManager.getInstance().addUser(new SystemUserStub("stubUsername","name",93121, true));
assertFalse(EntityManager.getInstance().getReferees().isEmpty());
}
@Test
public void getRefereesITest() {
assertTrue(EntityManager.getInstance().getReferees().isEmpty());
SystemUser systemUser = new SystemUser("stubUsername","name", true);
new Referee(systemUser, RefereeQualification.VAR_REFEREE, true);
List<SystemUser> referees = EntityManager.getInstance().getReferees();
assertFalse(referees.isEmpty());
assertTrue(referees.size()==1);
assertTrue(referees.get(0).isType(RoleTypes.REFEREE));
}
@Test
public void doesPointsPolicyExistsITest() {
assertFalse(EntityManager.getInstance().doesPointsPolicyExists(1,-1,0));
}
@Test
public void addPointsPolicyITest() {
assertFalse(EntityManager.getInstance().doesPointsPolicyExists(1,-1,0));
EntityManager.getInstance().addPointsPolicy(new PointsPolicy(1,-1,0));
assertTrue(EntityManager.getInstance().doesPointsPolicyExists(1,-1,0));
}
@Test
public void addPointsPolicy2ITest() {
assertFalse(EntityManager.getInstance().doesPointsPolicyExists(1,-1,0));
PointsPolicy pointsPolicy = new PointsPolicy(1,-1,0);
EntityManager.getInstance().addPointsPolicy(pointsPolicy);
assertTrue(EntityManager.getInstance().getPointsPolicy(1,-1,0).equals(pointsPolicy));
assertNull(EntityManager.getInstance().getPointsPolicy(1,-1,1));
}
@Test
public void doesSchedulingPolicyExistsITest() {
assertFalse(EntityManager.getInstance().doesSchedulingPolicyExists(2,2,2));
}
@Test
public void addSchedulingPolicyITest() {
assertFalse(EntityManager.getInstance().doesSchedulingPolicyExists(2,2,2));
EntityManager.getInstance().addSchedulingPolicy(new SchedulingPolicy(2,2,2));
assertTrue(EntityManager.getInstance().doesSchedulingPolicyExists(2,2,2));
}
// @Test
// public void addSchedulingPolicy2ITest() {
// assertFalse(EntityManager.getInstance().doesSchedulingPolicyExists(2,2,2));
// SchedulingPolicy schedulingPolicy= new SchedulingPolicy(2,2,2);
// EntityManager.getInstance().addSchedulingPolicy(schedulingPolicy);
// assertTrue(EntityManager.getInstance().getSchedulingPolicy(2,2,2).equals(schedulingPolicy));
// assertNull(EntityManager.getInstance().getSchedulingPolicy(3,2,2));
// }
@After
public void tearDown() throws Exception {
EntityManager.getInstance().clearAll();
}
} |
922f3e47ea43b3d43d301633319098d2f289c763 | 1,837 | java | Java | com.io7m.jade.tests/src/test/java/com/io7m/jade/tests/ApplicationNamesTest.java | io7m/jade | 25fe05921a9f567f40a1896918d82df5d1a1a513 | [
"0BSD"
] | null | null | null | com.io7m.jade.tests/src/test/java/com/io7m/jade/tests/ApplicationNamesTest.java | io7m/jade | 25fe05921a9f567f40a1896918d82df5d1a1a513 | [
"0BSD"
] | null | null | null | com.io7m.jade.tests/src/test/java/com/io7m/jade/tests/ApplicationNamesTest.java | io7m/jade | 25fe05921a9f567f40a1896918d82df5d1a1a513 | [
"0BSD"
] | null | null | null | 28.2 | 78 | 0.66503 | 995,031 | /*
* Copyright © 2020 Mark Raynsford <envkt@example.com> http://io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.io7m.jade.tests;
import com.io7m.jade.api.ApplicationNames;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import java.util.stream.Stream;
public final class ApplicationNamesTest
{
@TestFactory
public Stream<DynamicTest> testValidNames()
{
return Stream.of(
"Window.23_",
"παράθυρο.23_",
"窗口.23_",
"окно.23_",
"_23.شباك",
"ອ.23_"
).map(name -> {
return DynamicTest.dynamicTest(
"testValid" + name,
() -> {
ApplicationNames.checkValid(name);
});
});
}
@TestFactory
public Stream<DynamicTest> testInvalidNames()
{
return Stream.of(
"-",
"",
","
).map(name -> {
return DynamicTest.dynamicTest(
"testInvalid" + name,
() -> {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
ApplicationNames.checkValid(name);
});
});
});
}
}
|
922f3ecc60b08a77aecaca2093d47ac8f100459e | 1,553 | java | Java | raptor-codegen/raptor-codegen-core/src/test/java/com/ppdai/raptor/codegen/test/java/PomGeneratorTest.java | zy475459736/raptor | 06e12a3bfcb43a8dcaf1130b550aa201ca7d1d6e | [
"Apache-2.0"
] | null | null | null | raptor-codegen/raptor-codegen-core/src/test/java/com/ppdai/raptor/codegen/test/java/PomGeneratorTest.java | zy475459736/raptor | 06e12a3bfcb43a8dcaf1130b550aa201ca7d1d6e | [
"Apache-2.0"
] | null | null | null | raptor-codegen/raptor-codegen-core/src/test/java/com/ppdai/raptor/codegen/test/java/PomGeneratorTest.java | zy475459736/raptor | 06e12a3bfcb43a8dcaf1130b550aa201ca7d1d6e | [
"Apache-2.0"
] | 1 | 2021-05-26T08:47:40.000Z | 2021-05-26T08:47:40.000Z | 29.865385 | 112 | 0.710238 | 995,032 | package com.ppdai.raptor.codegen.test.java;
import com.ppdai.raptor.codegen.java.PomGenerator;
import com.ppdai.raptor.codegen.java.maven.PomModel;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.junit.Assert;
import org.junit.Test;
import java.io.*;
/**
* @author zhangchengxi
* Date 2018/5/17
*/
public class PomGeneratorTest {
@Test
public void testReadPom() {
PomGenerator pomGenerator = new PomGenerator();
Model model = pomGenerator.readExamplePom();
Assert.assertNotNull(model);
}
@Test
public void testWriteTo() throws IOException, XmlPullParserException {
String artifactId = "artifactId";
String version = "version";
String groupId = "groupId";
PomModel pomModel = PomModel.builder().artifactId(artifactId).groupId(groupId).version(version).build();
PomGenerator pomGenerator = new PomGenerator(pomModel);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
pomGenerator.writeTo(baos);
String s = baos.toString();
MavenXpp3Reader mavenXpp3Reader = new MavenXpp3Reader();
InputStream is = new ByteArrayInputStream(s.getBytes());
Model generated = mavenXpp3Reader.read(is);
Assert.assertEquals(artifactId,generated.getArtifactId());
Assert.assertEquals(version,generated.getVersion());
Assert.assertEquals(groupId,generated.getGroupId());
}
}
|
922f3f2fe6405f279e54dabe2fa62b4b229b88b0 | 1,885 | java | Java | src/helper/one/profiler/JfrCombiner.java | Jongy/async-profiler | ec8a40431a435648982bad852796bdf621ab7aeb | [
"Apache-2.0"
] | null | null | null | src/helper/one/profiler/JfrCombiner.java | Jongy/async-profiler | ec8a40431a435648982bad852796bdf621ab7aeb | [
"Apache-2.0"
] | null | null | null | src/helper/one/profiler/JfrCombiner.java | Jongy/async-profiler | ec8a40431a435648982bad852796bdf621ab7aeb | [
"Apache-2.0"
] | null | null | null | 29.920635 | 92 | 0.681698 | 995,033 | /*
* Copyright 2021 Andrei Pangin
*
* 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 one.profiler;
import jdk.jfr.FlightRecorder;
import jdk.jfr.FlightRecorderListener;
import jdk.jfr.Recording;
import jdk.jfr.RecordingState;
import java.nio.file.Path;
/**
* Appends async-profiler recording to an existing JFR recording.
*/
class JfrCombiner implements FlightRecorderListener {
private JfrCombiner() {
}
@Override
public void recordingStateChanged(Recording recording) {
if (recording.getState() == RecordingState.STOPPED) {
Path path = recording.getDestination();
if (path != null) {
appendRecording(path.toString());
}
} else if (recording.getState() != RecordingState.CLOSED) {
disableBuiltinEvents(recording);
}
}
private static void disableBuiltinEvents(Recording recording) {
recording.disable("jdk.ExecutionSample");
recording.disable("jdk.NativeMethodSample");
}
private static native void appendRecording(String path);
static {
if (FlightRecorder.isInitialized()) {
for (Recording recording : FlightRecorder.getFlightRecorder().getRecordings()) {
disableBuiltinEvents(recording);
}
}
FlightRecorder.addListener(new JfrCombiner());
}
}
|
922f4012f7a393c6bab0e6493ccf1f99a944b659 | 5,213 | java | Java | backend/manager/modules/restapi/interface/definition/src/main/java/org/ovirt/engine/api/xml/JAXBMessageBodyReader.java | phoenixsbk/kvmmgr | 1ed6230dc4246fe511eeb5fc9d0532d3e651b459 | [
"Apache-2.0"
] | 1 | 2019-01-12T06:46:55.000Z | 2019-01-12T06:46:55.000Z | backend/manager/modules/restapi/interface/definition/src/main/java/org/ovirt/engine/api/xml/JAXBMessageBodyReader.java | phoenixsbk/kvmmgr | 1ed6230dc4246fe511eeb5fc9d0532d3e651b459 | [
"Apache-2.0"
] | null | null | null | backend/manager/modules/restapi/interface/definition/src/main/java/org/ovirt/engine/api/xml/JAXBMessageBodyReader.java | phoenixsbk/kvmmgr | 1ed6230dc4246fe511eeb5fc9d0532d3e651b459 | [
"Apache-2.0"
] | 2 | 2016-03-09T16:37:23.000Z | 2022-01-19T13:12:27.000Z | 35.222973 | 119 | 0.666219 | 995,034 | /*
* Copyright (c) 2014 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ovirt.engine.api.xml;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.Consumes;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.ovirt.engine.api.model.API;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class is responsible for converting XML documents into model objects. Note that it can't be a generic class
* because if it is then the JAX-RS framework will select other builtin classes that are more specific.
*/
@Provider
@Consumes(MediaType.APPLICATION_XML)
public class JAXBMessageBodyReader implements MessageBodyReader<Object> {
/**
* The logger used by this class.
*/
private Logger log = LoggerFactory.getLogger(JAXBMessageBodyReader.class);
/**
* The factory used to create XML document readers.
*/
private XMLInputFactory parserFactory;
/**
* The JAXB jaxbContext used to convert XML documents into the corresponding model objects.
*/
private JAXBContext jaxbContext;
/**
* Default event handler recognizes XML parsing as error and not as warning.
*/
private ValidationEventHandler jaxbHandler = new JAXBValidationEventHandler();
public JAXBMessageBodyReader() {
// Create a factory that will produce XML parsers that ignore entity references and DTDs:
parserFactory = XMLInputFactory.newFactory();
parserFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);
parserFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
parserFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
// Create a JAXB context for the model package:
String modelPackage = API.class.getPackage().getName();
try {
jaxbContext = JAXBContext.newInstance(modelPackage);
}
catch (JAXBException exception) {
log.error("Can't create JAXB context for package \"{}\".", modelPackage, exception);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean isReadable(Class<?> type, Type genericType, Annotation annotations[], MediaType mediaType) {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public Object readFrom(Class<Object> type, Type genericType, Annotation annotations[], MediaType mediaType,
MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
throws IOException, WebApplicationException {
XMLStreamReader reader = null;
try {
reader = parserFactory.createXMLStreamReader(entityStream, "UTF-8");
return readFrom(reader);
}
catch (XMLStreamException exception) {
throw new IOException(exception);
}
finally {
if (reader != null) {
try {
reader.close();
}
catch (XMLStreamException exception) {
log.warn("Can't close XML stream reader.", exception);
}
}
}
}
/**
* Read the XML document using the given reader and convert it to an object. The given reader will be closed by the
* caller.
*/
private Object readFrom(XMLStreamReader reader) throws IOException {
try {
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
unmarshaller.setEventHandler(jaxbHandler);
Object result = unmarshaller.unmarshal(reader);
if (result instanceof JAXBElement) {
result = ((JAXBElement) result).getValue();
}
return result;
}
catch (JAXBException exception) {
Throwable linked = exception.getLinkedException();
if (linked != null) {
Throwable cause = linked;
while (cause.getCause() != null) {
cause = cause.getCause();
}
throw new IOException(cause);
}
throw new IOException(exception);
}
}
}
|
922f40169dd34d8308e30c273d8557f90c8699df | 2,859 | java | Java | src/test/java/spark/embeddedserver/EmbeddedServersTest.java | AutoscanForJava/com.sparkjava-spark-core | 54079b0f95f0076dd3c440e1255a7d449d9489f1 | [
"Apache-2.0"
] | 8,906 | 2015-01-02T12:29:01.000Z | 2022-03-30T19:27:50.000Z | src/test/java/spark/embeddedserver/EmbeddedServersTest.java | AutoscanForJava/com.sparkjava-spark-core | 54079b0f95f0076dd3c440e1255a7d449d9489f1 | [
"Apache-2.0"
] | 945 | 2015-01-12T13:50:47.000Z | 2022-03-31T12:14:03.000Z | src/test/java/spark/embeddedserver/EmbeddedServersTest.java | AutoscanForJava/com.sparkjava-spark-core | 54079b0f95f0076dd3c440e1255a7d449d9489f1 | [
"Apache-2.0"
] | 1,840 | 2015-01-01T10:55:31.000Z | 2022-03-24T22:56:54.000Z | 34.035714 | 114 | 0.694998 | 995,035 | package spark.embeddedserver;
import java.io.File;
import org.eclipse.jetty.server.NCSARequestLog;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.thread.ThreadPool;
import org.junit.AfterClass;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import spark.Spark;
import spark.embeddedserver.jetty.EmbeddedJettyFactory;
import spark.embeddedserver.jetty.JettyServerFactory;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class EmbeddedServersTest {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Test
public void testAddAndCreate_whenCreate_createsCustomServer() throws Exception {
// Create custom Server
Server server = new Server();
File requestLogDir = temporaryFolder.newFolder();
File requestLogFile = new File(requestLogDir, "request.log");
server.setRequestLog(new NCSARequestLog(requestLogFile.getAbsolutePath()));
JettyServerFactory serverFactory = mock(JettyServerFactory.class);
when(serverFactory.create(0, 0, 0)).thenReturn(server);
String id = "custom";
// Register custom server
EmbeddedServers.add(id, new EmbeddedJettyFactory(serverFactory));
EmbeddedServer embeddedServer = EmbeddedServers.create(id, null, null, null, false);
assertNotNull(embeddedServer);
embeddedServer.trustForwardHeaders(true);
embeddedServer.ignite("localhost", 0, null, 0, 0, 0);
assertTrue(requestLogFile.exists());
embeddedServer.extinguish();
verify(serverFactory).create(0, 0, 0);
}
@Test
public void testAdd_whenConfigureRoutes_createsCustomServer() throws Exception {
File requestLogDir = temporaryFolder.newFolder();
File requestLogFile = new File(requestLogDir, "request.log");
// Register custom server
EmbeddedServers.add(EmbeddedServers.Identifiers.JETTY, new EmbeddedJettyFactory(new JettyServerFactory() {
@Override
public Server create(int maxThreads, int minThreads, int threadTimeoutMillis) {
Server server = new Server();
server.setRequestLog(new NCSARequestLog(requestLogFile.getAbsolutePath()));
return server;
}
@Override
public Server create(ThreadPool threadPool) {
return null;
}
}));
Spark.get("/", (request, response) -> "OK");
Spark.awaitInitialization();
assertTrue(requestLogFile.exists());
}
@AfterClass
public static void tearDown() {
Spark.stop();
}
}
|
922f40d0b90d20fe23d4dc1934993555b3448e3d | 71,240 | java | Java | herddb-utils/src/main/java/herddb/proto/PduCodec.java | lorenzobalzani/herddb | e434d7ae1abceaa6c3443074ace122b709f5e481 | [
"Apache-2.0"
] | 261 | 2016-05-17T10:06:14.000Z | 2022-03-21T04:45:18.000Z | herddb-utils/src/main/java/herddb/proto/PduCodec.java | lorenzobalzani/herddb | e434d7ae1abceaa6c3443074ace122b709f5e481 | [
"Apache-2.0"
] | 588 | 2016-04-13T12:46:29.000Z | 2022-03-22T11:31:58.000Z | herddb-utils/src/main/java/herddb/proto/PduCodec.java | lorenzobalzani/herddb | e434d7ae1abceaa6c3443074ace122b709f5e481 | [
"Apache-2.0"
] | 53 | 2016-03-31T15:08:30.000Z | 2022-02-24T06:40:16.000Z | 36.236012 | 162 | 0.497108 | 995,036 | /*
Licensed to Diennea S.r.l. under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. Diennea S.r.l. 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 herddb.proto;
import herddb.utils.ByteBufUtils;
import herddb.utils.DataAccessor;
import herddb.utils.IntHolder;
import herddb.utils.KeyValue;
import herddb.utils.RawString;
import herddb.utils.RecordsBatch;
import herddb.utils.SystemProperties;
import herddb.utils.TuplesList;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
/**
* Codec for PDUs
*
* @author enrico.olivelli
*/
public abstract class PduCodec {
private static final boolean SEND_FULL_STACKTRACES = SystemProperties.getBooleanSystemProperty("herddb.network.sendstacktraces", true);
public static final byte VERSION_3 = 3;
public static Pdu decodePdu(ByteBuf in) throws IOException {
byte version = in.getByte(0);
if (version == VERSION_3) {
byte flags = in.getByte(1);
byte type = in.getByte(2);
long messageId = in.getLong(3);
return Pdu.newPdu(in, type, flags, messageId);
}
throw new IOException("Cannot decode version " + version);
}
private static final int ONE_BYTE = 1;
private static final int ONE_INT = 4;
private static final int ONE_LONG = 8;
private static final int MSGID_SIZE = 8;
private static final int TYPE_SIZE = 1;
private static final int FLAGS_SIZE = 1;
private static final int VERSION_SIZE = 1;
private static final int NULLABLE_FIELD_PRESENT = 1;
private static final int NULLABLE_FIELD_ABSENT = 0;
public static final byte TYPE_STRING = 0;
public static final byte TYPE_LONG = 1;
public static final byte TYPE_INTEGER = 2;
public static final byte TYPE_BYTEARRAY = 3;
public static final byte TYPE_TIMESTAMP = 4;
public static final byte TYPE_NULL = 5;
public static final byte TYPE_DOUBLE = 6;
public static final byte TYPE_BOOLEAN = 7;
public static final byte TYPE_SHORT = 8;
public static final byte TYPE_BYTE = 9;
public abstract static class ExecuteStatementsResult {
public static ByteBuf write(long replyId, List<Long> updateCounts, List<Map<String, Object>> otherdata, long tx) {
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
.directBuffer(
VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG
+ ONE_LONG);
byteBuf.writeByte(VERSION_3);
byteBuf.writeByte(Pdu.FLAGS_ISRESPONSE);
byteBuf.writeByte(Pdu.TYPE_EXECUTE_STATEMENTS_RESULT);
byteBuf.writeLong(replyId);
byteBuf.writeLong(tx);
byteBuf.writeInt(updateCounts.size());
for (Long updateCount : updateCounts) {
byteBuf.writeLong(updateCount);
}
byteBuf.writeInt(otherdata.size());
for (Map<String, Object> record : otherdata) {
// the Map is serialized as a list of objects (k1,v1,k2,v2...)
int size = record != null ? record.size() : 0;
ByteBufUtils.writeVInt(byteBuf, size * 2);
if (record != null) {
for (Map.Entry<String, Object> entry : record.entrySet()) {
writeObject(byteBuf, entry.getKey());
writeObject(byteBuf, entry.getValue());
}
}
}
return byteBuf;
}
public static long readTx(Pdu pdu) {
return pdu.buffer.getLong(
VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE);
}
public static List<Long> readUpdateCounts(Pdu pdu) {
pdu.buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG);
int numStatements = pdu.buffer.readInt();
List<Long> res = new ArrayList<>(numStatements);
for (int i = 0; i < numStatements; i++) {
res.add(pdu.buffer.readLong());
}
return res;
}
public static ListOfListsReader startResultRecords(Pdu pdu) {
final ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG);
int numStatements = buffer.readInt();
for (int i = 0; i < numStatements; i++) {
buffer.skipBytes(ONE_LONG);
}
int numLists = ByteBufUtils.readVInt(buffer);
return new ListOfListsReader(pdu, numLists);
}
}
public abstract static class ExecuteStatementResult {
public static ByteBuf write(
long messageId, long updateCount, long tx, Map<String, Object> record
) {
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
.directBuffer(
VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG
+ ONE_LONG);
byteBuf.writeByte(VERSION_3);
byteBuf.writeByte(Pdu.FLAGS_ISRESPONSE);
byteBuf.writeByte(Pdu.TYPE_EXECUTE_STATEMENT_RESULT);
byteBuf.writeLong(messageId);
byteBuf.writeLong(updateCount);
byteBuf.writeLong(tx);
// the Map is serialized as a list of objects (k1,v1,k2,v2...)
int size = record != null ? record.size() : 0;
ByteBufUtils.writeVInt(byteBuf, size * 2);
if (record != null) {
for (Map.Entry<String, Object> entry : record.entrySet()) {
writeObject(byteBuf, entry.getKey());
writeObject(byteBuf, entry.getValue());
}
}
return byteBuf;
}
public static boolean hasRecord(Pdu pdu) {
return pdu.buffer.writerIndex() > VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG
+ ONE_LONG;
}
public static ObjectListReader readRecord(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG
+ ONE_LONG
);
int numParams = ByteBufUtils.readVInt(buffer);
return new ObjectListReader(pdu, numParams);
}
public static long readUpdateCount(Pdu pdu) {
return pdu.buffer.getLong(
VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE);
}
public static long readTx(Pdu pdu) {
return pdu.buffer.getLong(
VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG /* update count */);
}
}
public abstract static class PrepareStatementResult {
public static ByteBuf write(
long messageId, long statementId
) {
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
.directBuffer(
VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG);
byteBuf.writeByte(VERSION_3);
byteBuf.writeByte(Pdu.FLAGS_ISRESPONSE);
byteBuf.writeByte(Pdu.TYPE_PREPARE_STATEMENT_RESULT);
byteBuf.writeLong(messageId);
byteBuf.writeLong(statementId);
return byteBuf;
}
public static long readStatementId(Pdu pdu) {
return pdu.buffer.getLong(
VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE);
}
}
public abstract static class SaslTokenMessageRequest {
public static ByteBuf write(long messageId, String saslMech, byte[] firstToken) {
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
.directBuffer(
VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ 64);
byteBuf.writeByte(VERSION_3);
byteBuf.writeByte(Pdu.FLAGS_ISREQUEST);
byteBuf.writeByte(Pdu.TYPE_SASL_TOKEN_MESSAGE_REQUEST);
byteBuf.writeLong(messageId);
ByteBufUtils.writeString(byteBuf, saslMech);
ByteBufUtils.writeArray(byteBuf, firstToken);
return byteBuf;
}
public static String readMech(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(0);
buffer.skipBytes(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE);
return new String(ByteBufUtils.readArray(buffer), StandardCharsets.UTF_8);
}
public static byte[] readToken(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(0);
buffer.skipBytes(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE);
ByteBufUtils.skipArray(buffer);
return ByteBufUtils.readArray(buffer);
}
}
public abstract static class SaslTokenMessageToken {
public static ByteBuf write(long messageId, byte[] token) {
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
.directBuffer(
VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ 1 + (token != null ? token.length : 0));
byteBuf.writeByte(VERSION_3);
byteBuf.writeByte(Pdu.FLAGS_ISREQUEST);
byteBuf.writeByte(Pdu.TYPE_SASL_TOKEN_MESSAGE_TOKEN);
byteBuf.writeLong(messageId);
if (token == null) {
byteBuf.writeByte(NULLABLE_FIELD_ABSENT);
} else {
byteBuf.writeByte(NULLABLE_FIELD_PRESENT);
ByteBufUtils.writeArray(byteBuf, token);
}
return byteBuf;
}
public static byte[] readToken(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(0);
buffer.skipBytes(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE);
byte tokenPresent = buffer.readByte();
if (tokenPresent == NULLABLE_FIELD_PRESENT) {
return ByteBufUtils.readArray(buffer);
} else {
return null;
}
}
}
public static class SaslTokenServerResponse {
public static ByteBuf write(long messageId, byte[] token) {
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
.directBuffer(
VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ 64);
byteBuf.writeByte(VERSION_3);
byteBuf.writeByte(Pdu.FLAGS_ISRESPONSE);
byteBuf.writeByte(Pdu.TYPE_SASL_TOKEN_SERVER_RESPONSE);
byteBuf.writeLong(messageId);
if (token != null) {
ByteBufUtils.writeArray(byteBuf, token);
}
return byteBuf;
}
public static byte[] readToken(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
if (buffer.writerIndex() > VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE) {
buffer.readerIndex(0);
buffer.skipBytes(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE);
return ByteBufUtils.readArray(buffer);
} else {
return null;
}
}
}
public static class AckResponse {
public static ByteBuf write(long messageId) {
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
.directBuffer(
VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE);
byteBuf.writeByte(VERSION_3);
byteBuf.writeByte(Pdu.FLAGS_ISRESPONSE);
byteBuf.writeByte(Pdu.TYPE_ACK);
byteBuf.writeLong(messageId);
return byteBuf;
}
}
public static class ErrorResponse {
public static final byte FLAG_NONE = 0;
public static final byte FLAG_NOT_LEADER = 1;
public static final byte FLAG_MISSING_PREPARED_STATEMENT = 2;
public static final byte FLAG_DUPLICATEPRIMARY_KEY_ERROR = 4;
public static ByteBuf write(long messageId, String error) {
return write(messageId, error, false, false, false);
}
public static ByteBuf writeNotLeaderError(long messageId, String message) {
return write(messageId, message, true, false, false);
}
public static ByteBuf writeMissingPreparedStatementError(long messageId, String message) {
return write(messageId, message, false, true, false);
}
public static ByteBuf writeNotLeaderError(long messageId, Throwable message) {
return write(messageId, message.toString(), true, false, false);
}
public static ByteBuf writeSqlIntegrityConstraintsViolation(long messageId, Throwable message) {
return write(messageId, message.toString(), false, false, true);
}
private static ByteBuf write(long messageId, String error, boolean notLeader, boolean missingPreparedStatement, boolean sqlIntegrityConstraintViolation) {
if (error == null) {
error = "";
}
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
.directBuffer(
VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_BYTE
+ error.length());
byteBuf.writeByte(VERSION_3);
byteBuf.writeByte(Pdu.FLAGS_ISRESPONSE);
byteBuf.writeByte(Pdu.TYPE_ERROR);
byteBuf.writeLong(messageId);
byte flags = FLAG_NONE;
if (notLeader) {
flags = (byte) (flags | FLAG_NOT_LEADER);
}
if (missingPreparedStatement) {
flags = (byte) (flags | FLAG_MISSING_PREPARED_STATEMENT);
}
if (sqlIntegrityConstraintViolation) {
flags = (byte) (flags | FLAG_DUPLICATEPRIMARY_KEY_ERROR);
}
byteBuf.writeByte(flags);
ByteBufUtils.writeString(byteBuf, error);
return byteBuf;
}
public static ByteBuf write(long messageId, Throwable error, boolean notLeader, boolean missingPreparedStatementError) {
String errorMessageForClient;
if (SEND_FULL_STACKTRACES) {
StringWriter writer = new StringWriter();
error.printStackTrace(new PrintWriter(writer));
errorMessageForClient = writer.toString();
} else {
// no stacktrace
errorMessageForClient = error + "";
}
return write(messageId, errorMessageForClient, notLeader, missingPreparedStatementError, false);
}
public static ByteBuf write(long messageId, Throwable error) {
return write(messageId, error, false, false);
}
public static String readError(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(0);
buffer.skipBytes(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_BYTE);
return ByteBufUtils.readString(buffer);
}
public static boolean readIsNotLeader(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
byte read = buffer.getByte(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE);
return (read & FLAG_NOT_LEADER) == FLAG_NOT_LEADER;
}
public static boolean readIsMissingPreparedStatementError(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
byte read = buffer.getByte(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE);
return (read & FLAG_MISSING_PREPARED_STATEMENT) == FLAG_MISSING_PREPARED_STATEMENT;
}
public static boolean readIsSqlIntegrityViolationError(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
byte read = buffer.getByte(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE);
return (read & FLAG_DUPLICATEPRIMARY_KEY_ERROR) == FLAG_DUPLICATEPRIMARY_KEY_ERROR;
}
}
public abstract static class TxCommand {
public static final byte TX_COMMAND_ROLLBACK_TRANSACTION = 1;
public static final byte TX_COMMAND_COMMIT_TRANSACTION = 2;
public static final byte TX_COMMAND_BEGIN_TRANSACTION = 3;
public static ByteBuf write(long messageId, byte command, long tx, String tableSpace) {
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
.directBuffer(
VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_BYTE
+ ONE_LONG
+ tableSpace.length());
byteBuf.writeByte(VERSION_3);
byteBuf.writeByte(Pdu.FLAGS_ISREQUEST);
byteBuf.writeByte(Pdu.TYPE_TX_COMMAND);
byteBuf.writeLong(messageId);
byteBuf.writeByte(command);
byteBuf.writeLong(tx);
ByteBufUtils.writeString(byteBuf, tableSpace);
return byteBuf;
}
public static byte readCommand(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
return buffer.getByte(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE);
}
public static long readTx(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
return buffer.getLong(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_BYTE);
}
public static String readTablespace(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_BYTE
+ ONE_LONG);
return ByteBufUtils.readString(buffer);
}
}
public abstract static class TxCommandResult {
public static ByteBuf write(long messageId, long tx) {
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
.directBuffer(
VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE);
byteBuf.writeByte(VERSION_3);
byteBuf.writeByte(Pdu.FLAGS_ISRESPONSE);
byteBuf.writeByte(Pdu.TYPE_TX_COMMAND_RESULT);
byteBuf.writeLong(messageId);
byteBuf.writeLong(tx);
return byteBuf;
}
public static long readTx(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
return buffer.getLong(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE);
}
}
public static class OpenScanner {
public static ByteBuf write(
long messageId, String tableSpace, String query,
long scannerId, long tx, List<Object> params, long statementId, int fetchSize, int maxRows,
boolean keepReadLocks
) {
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
.directBuffer(
VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG
+ ONE_INT
+ ONE_INT
+ ONE_LONG
+ ONE_LONG
+ 1 + tableSpace.length()
+ 2 + query.length()
+ 1 + params.size() * 8);
byteBuf.writeByte(VERSION_3);
byteBuf.writeByte(Pdu.FLAGS_ISREQUEST);
byteBuf.writeByte(Pdu.TYPE_OPENSCANNER);
byteBuf.writeLong(messageId);
byteBuf.writeLong(tx);
byteBuf.writeLong(statementId);
byteBuf.writeInt(fetchSize);
byteBuf.writeInt(maxRows);
byteBuf.writeLong(scannerId);
ByteBufUtils.writeString(byteBuf, tableSpace);
ByteBufUtils.writeString(byteBuf, query);
ByteBufUtils.writeVInt(byteBuf, params.size());
for (Object p : params) {
writeObject(byteBuf, p);
}
// trailer
if (!keepReadLocks) {
byteBuf.writeByte(Pdu.FLAGS_OPENSCANNER_DONTKEEP_READ_LOCKS);
}
return byteBuf;
}
public static long readTx(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
return buffer.getLong(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE);
}
public static long readStatementId(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
return buffer.getLong(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG);
}
public static int readFetchSize(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
return buffer.getInt(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG
+ ONE_LONG);
}
public static int readMaxRows(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
return buffer.getInt(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG
+ ONE_LONG
+ ONE_INT);
}
public static long readScannerId(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
return buffer.getLong(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG
+ ONE_LONG
+ ONE_INT
+ ONE_INT
);
}
public static String readTablespace(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG
+ ONE_LONG
+ ONE_INT
+ ONE_INT
+ ONE_LONG);
return ByteBufUtils.readString(buffer);
}
public static String readQuery(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG
+ ONE_LONG
+ ONE_INT
+ ONE_INT
+ ONE_LONG);
ByteBufUtils.skipArray(buffer); // tablespace
return ByteBufUtils.readString(buffer);
}
public static ObjectListReader startReadParameters(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG
+ ONE_LONG
+ ONE_INT
+ ONE_INT
+ ONE_LONG
);
ByteBufUtils.skipArray(buffer); // tablespace
ByteBufUtils.skipArray(buffer); // query
int numParams = ByteBufUtils.readVInt(buffer);
return new ObjectListReader(pdu, numParams);
}
}
public static class ResultSetChunk {
private static int estimateTupleListSize(TuplesList data) {
return data.tuples.size() * 1024 + data.columnNames.length * 64;
}
public static ByteBuf write(long messageId, TuplesList tuplesList, boolean last, long tx) {
int dataSize = estimateTupleListSize(tuplesList);
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
.directBuffer(
VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG
+ ONE_BYTE
+ dataSize);
byteBuf.writeByte(VERSION_3);
byteBuf.writeByte(Pdu.FLAGS_ISRESPONSE);
byteBuf.writeByte(Pdu.TYPE_RESULTSET_CHUNK);
byteBuf.writeLong(messageId);
byteBuf.writeLong(tx);
byteBuf.writeByte(last ? 1 : 0);
int numColumns = tuplesList.columnNames.length;
byteBuf.writeInt(numColumns);
for (String columnName : tuplesList.columnNames) {
ByteBufUtils.writeString(byteBuf, columnName);
}
// num records
byteBuf.writeInt(tuplesList.tuples.size());
for (DataAccessor da : tuplesList.tuples) {
IntHolder currentColumn = new IntHolder();
da.forEach((String key, Object value) -> {
String expectedColumnName = tuplesList.columnNames[currentColumn.value];
while (!key.equals(expectedColumnName)) {
// nulls are not returned for some special accessors, like DataAccessorForFullRecord
writeObject(byteBuf, null);
currentColumn.value++;
expectedColumnName = tuplesList.columnNames[currentColumn.value];
}
writeObject(byteBuf, value);
currentColumn.value++;
});
// fill with nulls
while (currentColumn.value < numColumns) {
writeObject(byteBuf, null);
currentColumn.value++;
}
if (currentColumn.value > numColumns) {
throw new RuntimeException("unexpected number of columns " + currentColumn.value + " > " + numColumns);
}
}
return byteBuf;
}
public static long readTx(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
return buffer.getLong(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE);
}
public static boolean readIsLast(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
return buffer.getByte(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG
) == 1;
}
public static RecordsBatch startReadingData(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG
+ ONE_BYTE);
return new RecordsBatch(pdu);
}
}
public static class FetchScannerData {
public static ByteBuf write(long messageId, long scannerId, int fetchSize) {
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
.directBuffer(
VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG
+ ONE_INT);
byteBuf.writeByte(VERSION_3);
byteBuf.writeByte(Pdu.FLAGS_ISREQUEST);
byteBuf.writeByte(Pdu.TYPE_FETCHSCANNERDATA);
byteBuf.writeLong(messageId);
byteBuf.writeLong(scannerId);
byteBuf.writeInt(fetchSize);
return byteBuf;
}
public static long readScannerId(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
return buffer.getLong(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE);
}
public static int readFetchSize(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
return buffer.getInt(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG);
}
}
public static class CloseScanner {
public static ByteBuf write(long messageId, long scannerId) {
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
.directBuffer(
VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG);
byteBuf.writeByte(VERSION_3);
byteBuf.writeByte(Pdu.FLAGS_ISREQUEST);
byteBuf.writeByte(Pdu.TYPE_CLOSESCANNER);
byteBuf.writeLong(messageId);
byteBuf.writeLong(scannerId);
return byteBuf;
}
public static long readScannerId(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
return buffer.getLong(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE);
}
}
public static class ExecuteStatements {
public static ByteBuf write(
long messageId, String tableSpace, String query,
long tx, boolean returnValues, long statementId, List<List<Object>> statements
) {
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
.directBuffer(
VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG
+ ONE_BYTE
+ ONE_LONG
+ 1 + statements.size() * 64);
byteBuf.writeByte(VERSION_3);
byteBuf.writeByte(Pdu.FLAGS_ISREQUEST);
byteBuf.writeByte(Pdu.TYPE_EXECUTE_STATEMENTS);
byteBuf.writeLong(messageId);
byteBuf.writeByte(returnValues ? 1 : 0);
byteBuf.writeLong(tx);
byteBuf.writeLong(statementId);
ByteBufUtils.writeString(byteBuf, tableSpace);
ByteBufUtils.writeString(byteBuf, query);
// number of statements
ByteBufUtils.writeVInt(byteBuf, statements.size());
for (List<Object> list : statements) {
// number of params
ByteBufUtils.writeVInt(byteBuf, list.size());
for (Object param : list) {
writeObject(byteBuf, param);
}
}
return byteBuf;
}
public static boolean readReturnValues(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
return buffer.getByte(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE) == 1;
}
public static long readTx(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
return buffer.getLong(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_BYTE);
}
public static long readStatementId(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
return buffer.getLong(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_BYTE
+ ONE_LONG);
}
public static String readTablespace(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_BYTE
+ ONE_LONG
+ ONE_LONG
);
return ByteBufUtils.readString(buffer);
}
public static String readQuery(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_BYTE
+ ONE_LONG
+ ONE_LONG
);
ByteBufUtils.skipArray(buffer); // tablespace
return ByteBufUtils.readString(buffer);
}
public static ListOfListsReader startReadStatementsParameters(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_BYTE
+ ONE_LONG
+ ONE_LONG
);
ByteBufUtils.skipArray(buffer); // tablespace
ByteBufUtils.skipArray(buffer); // query
int numLists = ByteBufUtils.readVInt(buffer);
return new ListOfListsReader(pdu, numLists);
}
}
public static class ExecuteStatement {
public static ByteBuf write(
long messageId, String tableSpace, String query, long tx,
boolean returnValues, long statementId,
List<Object> params
) {
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
.directBuffer(
VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_BYTE
+ ONE_LONG
+ tableSpace.length()
+ query.length()
+ ONE_BYTE
+ params.size() * 8);
byteBuf.writeByte(VERSION_3);
byteBuf.writeByte(Pdu.FLAGS_ISREQUEST);
byteBuf.writeByte(Pdu.TYPE_EXECUTE_STATEMENT);
byteBuf.writeLong(messageId);
byteBuf.writeByte(returnValues ? 1 : 0);
byteBuf.writeLong(tx);
byteBuf.writeLong(statementId);
ByteBufUtils.writeString(byteBuf, tableSpace);
ByteBufUtils.writeString(byteBuf, query);
ByteBufUtils.writeVInt(byteBuf, params.size());
for (Object p : params) {
writeObject(byteBuf, p);
}
return byteBuf;
}
public static boolean readReturnValues(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
return buffer.getByte(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE) == 1;
}
public static long readTx(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
return buffer.getLong(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_BYTE);
}
public static long readStatementId(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
return buffer.getLong(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_BYTE
+ ONE_LONG);
}
public static String readTablespace(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_BYTE
+ ONE_LONG
+ ONE_LONG
);
return ByteBufUtils.readString(buffer);
}
public static String readQuery(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_BYTE
+ ONE_LONG
+ ONE_LONG
);
ByteBufUtils.skipArray(buffer); // tablespace
return ByteBufUtils.readString(buffer);
}
public static ObjectListReader startReadParameters(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_BYTE
+ ONE_LONG
+ ONE_LONG
);
ByteBufUtils.skipArray(buffer); // tablespace
ByteBufUtils.skipArray(buffer); // query
int numParams = ByteBufUtils.readVInt(buffer);
return new ObjectListReader(pdu, numParams);
}
}
public static class PrepareStatement {
public static ByteBuf write(long messageId, String tableSpace, String query) {
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
.directBuffer(
VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE);
byteBuf.writeByte(VERSION_3);
byteBuf.writeByte(Pdu.FLAGS_ISREQUEST);
byteBuf.writeByte(Pdu.TYPE_PREPARE_STATEMENT);
byteBuf.writeLong(messageId);
ByteBufUtils.writeString(byteBuf, tableSpace);
ByteBufUtils.writeString(byteBuf, query);
return byteBuf;
}
public static String readTablespace(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
);
return ByteBufUtils.readString(buffer);
}
public static String readQuery(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
);
ByteBufUtils.skipArray(buffer); // tablespace
return ByteBufUtils.readString(buffer);
}
}
public static class RequestTablespaceDump {
public static ByteBuf write(long messageId, String tableSpace, String dumpId, int fetchSize, boolean includeTransactionLog) {
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
.directBuffer(
VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_BYTE
+ ONE_INT
+ tableSpace.length()
+ dumpId.length());
byteBuf.writeByte(VERSION_3);
byteBuf.writeByte(Pdu.FLAGS_ISREQUEST);
byteBuf.writeByte(Pdu.TYPE_REQUEST_TABLESPACE_DUMP);
byteBuf.writeLong(messageId);
byteBuf.writeByte(includeTransactionLog ? 1 : 0);
byteBuf.writeInt(fetchSize);
ByteBufUtils.writeString(byteBuf, tableSpace);
ByteBufUtils.writeString(byteBuf, dumpId);
return byteBuf;
}
public static boolean readInludeTransactionLog(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
return buffer.getByte(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE) == 1;
}
public static int readFetchSize(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
return buffer.getInt(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_BYTE);
}
public static String readTablespace(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_BYTE
+ ONE_INT
);
return ByteBufUtils.readString(buffer);
}
public static String readDumpId(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_BYTE
+ ONE_INT
);
ByteBufUtils.skipArray(buffer); // tablespace
return ByteBufUtils.readString(buffer);
}
}
public static class TablespaceDumpData {
public static ByteBuf write(
long messageId, String tableSpace, String dumpId,
String command, byte[] tableDefinition, long estimatedSize,
long dumpLedgerid, long dumpOffset, List<byte[]> indexesDefinition,
List<KeyValue> records
) {
if (tableDefinition == null) {
tableDefinition = new byte[0];
}
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
.directBuffer(
VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_BYTE
+ ONE_INT
+ tableDefinition.length
+ tableSpace.length()
+ dumpId.length());
byteBuf.writeByte(VERSION_3);
byteBuf.writeByte(Pdu.FLAGS_ISREQUEST);
byteBuf.writeByte(Pdu.TYPE_TABLESPACE_DUMP_DATA);
byteBuf.writeLong(messageId);
byteBuf.writeLong(dumpLedgerid);
byteBuf.writeLong(dumpOffset);
byteBuf.writeLong(estimatedSize);
ByteBufUtils.writeString(byteBuf, tableSpace);
ByteBufUtils.writeString(byteBuf, dumpId);
ByteBufUtils.writeString(byteBuf, command);
ByteBufUtils.writeArray(byteBuf, tableDefinition);
if (indexesDefinition == null) {
byteBuf.writeInt(0);
} else {
byteBuf.writeInt(indexesDefinition.size());
for (int i = 0; i < indexesDefinition.size(); i++) {
ByteBufUtils.writeArray(byteBuf, indexesDefinition.get(i));
}
}
if (records == null) {
byteBuf.writeInt(0);
} else {
byteBuf.writeInt(records.size());
for (KeyValue kv : records) {
ByteBufUtils.writeArray(byteBuf, kv.key);
ByteBufUtils.writeArray(byteBuf, kv.value);
}
}
return byteBuf;
}
public static long readLedgerId(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
return buffer.getLong(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE);
}
public static long readOffset(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
return buffer.getLong(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG
);
}
public static long readEstimatedSize(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
return buffer.getLong(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG
+ ONE_LONG
);
}
public static String readTablespace(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG
+ ONE_LONG
+ ONE_LONG
);
return ByteBufUtils.readString(buffer);
}
public static String readDumpId(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG
+ ONE_LONG
+ ONE_LONG
);
ByteBufUtils.skipArray(buffer); // tablespace
return ByteBufUtils.readString(buffer);
}
public static String readCommand(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG
+ ONE_LONG
+ ONE_LONG
);
ByteBufUtils.skipArray(buffer); // tablespace
ByteBufUtils.skipArray(buffer); // dumpId
return ByteBufUtils.readString(buffer);
}
public static byte[] readTableDefinition(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG
+ ONE_LONG
+ ONE_LONG
);
ByteBufUtils.skipArray(buffer); // tablespace
ByteBufUtils.skipArray(buffer); // dumpId
ByteBufUtils.skipArray(buffer); // command
return ByteBufUtils.readArray(buffer);
}
public static List<byte[]> readIndexesDefinition(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG
+ ONE_LONG
+ ONE_LONG
);
ByteBufUtils.skipArray(buffer); // tablespace
ByteBufUtils.skipArray(buffer); // dumpId
ByteBufUtils.skipArray(buffer); // command
ByteBufUtils.skipArray(buffer); // tableDefinition
int num = buffer.readInt();
List<byte[]> res = new ArrayList<>();
for (int i = 0; i < num; i++) {
res.add(ByteBufUtils.readArray(buffer));
}
return res;
}
public static void readRecords(Pdu pdu, BiConsumer<byte[], byte[]> consumer) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG
+ ONE_LONG
+ ONE_LONG
);
ByteBufUtils.skipArray(buffer); // tablespace
ByteBufUtils.skipArray(buffer); // dumpId
ByteBufUtils.skipArray(buffer); // command
ByteBufUtils.skipArray(buffer); // tableDefinition
int num = buffer.readInt();
for (int i = 0; i < num; i++) {
ByteBufUtils.skipArray(buffer);
}
int numRecords = buffer.readInt();
for (int i = 0; i < numRecords; i++) {
byte[] key = ByteBufUtils.readArray(buffer);
byte[] value = ByteBufUtils.readArray(buffer);
consumer.accept(key, value);
}
}
}
public static class RequestTableRestore {
public static ByteBuf write(
long messageId, String tableSpace, byte[] tableDefinition,
long dumpLedgerId, long dumpOffset
) {
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
.directBuffer(
VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG
+ ONE_LONG
+ tableSpace.length()
+ tableDefinition.length
);
byteBuf.writeByte(VERSION_3);
byteBuf.writeByte(Pdu.FLAGS_ISREQUEST);
byteBuf.writeByte(Pdu.TYPE_REQUEST_TABLE_RESTORE);
byteBuf.writeLong(messageId);
byteBuf.writeLong(dumpLedgerId);
byteBuf.writeLong(dumpOffset);
ByteBufUtils.writeString(byteBuf, tableSpace);
ByteBufUtils.writeArray(byteBuf, tableDefinition);
return byteBuf;
}
public static long readLedgerId(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
return buffer.getLong(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE);
}
public static long readOffset(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
return buffer.getLong(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG
);
}
public static String readTablespace(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG
+ ONE_LONG
);
return ByteBufUtils.readString(buffer);
}
public static byte[] readTableDefinition(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ ONE_LONG
+ ONE_LONG
);
ByteBufUtils.skipArray(buffer); // tablespace
return ByteBufUtils.readArray(buffer);
}
}
public static class TableRestoreFinished {
public static ByteBuf write(
long messageId, String tableSpace, String tableName,
List<byte[]> indexesDefinition
) {
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
.directBuffer(
VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ tableSpace.length()
+ tableName.length()
+ (indexesDefinition == null ? 0 : (indexesDefinition.size() * 64)));
byteBuf.writeByte(VERSION_3);
byteBuf.writeByte(Pdu.FLAGS_ISREQUEST);
byteBuf.writeByte(Pdu.TYPE_TABLE_RESTORE_FINISHED);
byteBuf.writeLong(messageId);
ByteBufUtils.writeString(byteBuf, tableSpace);
ByteBufUtils.writeString(byteBuf, tableName);
if (indexesDefinition == null) {
byteBuf.writeInt(0);
} else {
byteBuf.writeInt(indexesDefinition.size());
for (int i = 0; i < indexesDefinition.size(); i++) {
ByteBufUtils.writeArray(byteBuf, indexesDefinition.get(i));
}
}
return byteBuf;
}
public static String readTablespace(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
);
return ByteBufUtils.readString(buffer);
}
public static String readTableName(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
);
ByteBufUtils.skipArray(buffer); // tablespace
return ByteBufUtils.readString(buffer);
}
public static List<byte[]> readIndexesDefinition(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
);
ByteBufUtils.skipArray(buffer); // tablespace
ByteBufUtils.skipArray(buffer); // tableName
int num = buffer.readInt();
List<byte[]> res = new ArrayList<>();
for (int i = 0; i < num; i++) {
res.add(ByteBufUtils.readArray(buffer));
}
return res;
}
}
public static class RestoreFinished {
public static ByteBuf write(long messageId, String tableSpace) {
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
.directBuffer(
VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ tableSpace.length());
byteBuf.writeByte(VERSION_3);
byteBuf.writeByte(Pdu.FLAGS_ISREQUEST);
byteBuf.writeByte(Pdu.TYPE_RESTORE_FINISHED);
byteBuf.writeLong(messageId);
ByteBufUtils.writeString(byteBuf, tableSpace);
return byteBuf;
}
public static String readTablespace(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
);
return ByteBufUtils.readString(buffer);
}
}
public static class PushTableData {
public static ByteBuf write(long messageId, String tableSpace, String tableName, List<KeyValue> records) {
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
.directBuffer(
VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ tableSpace.length()
+ tableName.length()
+ records.size() * 512);
byteBuf.writeByte(VERSION_3);
byteBuf.writeByte(Pdu.FLAGS_ISREQUEST);
byteBuf.writeByte(Pdu.TYPE_PUSH_TABLE_DATA);
byteBuf.writeLong(messageId);
ByteBufUtils.writeString(byteBuf, tableSpace);
ByteBufUtils.writeString(byteBuf, tableName);
byteBuf.writeInt(records.size());
for (KeyValue kv : records) {
ByteBufUtils.writeArray(byteBuf, kv.key);
ByteBufUtils.writeArray(byteBuf, kv.value);
}
return byteBuf;
}
public static String readTablespace(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
);
return ByteBufUtils.readString(buffer);
}
public static String readTablename(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
);
ByteBufUtils.skipArray(buffer); // tablespace
return ByteBufUtils.readString(buffer);
}
public static void readRecords(Pdu pdu, BiConsumer<byte[], byte[]> consumer) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
);
ByteBufUtils.skipArray(buffer); // tablespace
ByteBufUtils.skipArray(buffer); // tablename
int numRecords = buffer.readInt();
for (int i = 0; i < numRecords; i++) {
byte[] key = ByteBufUtils.readArray(buffer);
byte[] value = ByteBufUtils.readArray(buffer);
consumer.accept(key, value);
}
}
}
public static class PushTxLogChunk {
public static ByteBuf write(long messageId, String tableSpace, List<KeyValue> records) {
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
.directBuffer(
VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ tableSpace.length()
+ records.size() * 512);
byteBuf.writeByte(VERSION_3);
byteBuf.writeByte(Pdu.FLAGS_ISREQUEST);
byteBuf.writeByte(Pdu.TYPE_PUSH_TXLOGCHUNK);
byteBuf.writeLong(messageId);
ByteBufUtils.writeString(byteBuf, tableSpace);
byteBuf.writeInt(records.size());
for (KeyValue kv : records) {
ByteBufUtils.writeArray(byteBuf, kv.key);
ByteBufUtils.writeArray(byteBuf, kv.value);
}
return byteBuf;
}
public static String readTablespace(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
);
return ByteBufUtils.readString(buffer);
}
public static void readRecords(Pdu pdu, BiConsumer<byte[], byte[]> consumer) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
);
ByteBufUtils.skipArray(buffer); // tablespace
int numRecords = buffer.readInt();
for (int i = 0; i < numRecords; i++) {
byte[] key = ByteBufUtils.readArray(buffer);
byte[] value = ByteBufUtils.readArray(buffer);
consumer.accept(key, value);
}
}
}
public static class PushTransactionsBlock {
public static ByteBuf write(long messageId, String tableSpace, List<byte[]> records) {
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
.directBuffer(
VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
+ tableSpace.length()
+ records.size() * 512);
byteBuf.writeByte(VERSION_3);
byteBuf.writeByte(Pdu.FLAGS_ISREQUEST);
byteBuf.writeByte(Pdu.TYPE_PUSH_TRANSACTIONSBLOCK);
byteBuf.writeLong(messageId);
ByteBufUtils.writeString(byteBuf, tableSpace);
byteBuf.writeInt(records.size());
for (byte[] tx : records) {
ByteBufUtils.writeArray(byteBuf, tx);
}
return byteBuf;
}
public static String readTablespace(Pdu pdu) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
);
return ByteBufUtils.readString(buffer);
}
public static void readTransactions(Pdu pdu, Consumer<byte[]> consumer) {
ByteBuf buffer = pdu.buffer;
buffer.readerIndex(VERSION_SIZE
+ FLAGS_SIZE
+ TYPE_SIZE
+ MSGID_SIZE
);
ByteBufUtils.skipArray(buffer); // tablespace
int numRecords = buffer.readInt();
for (int i = 0; i < numRecords; i++) {
byte[] key = ByteBufUtils.readArray(buffer);
consumer.accept(key);
}
}
}
public static class ListOfListsReader {
private final Pdu pdu;
private final int numLists;
public ListOfListsReader(Pdu pdu, int numLists) {
this.pdu = pdu;
this.numLists = numLists;
}
public int getNumLists() {
return numLists;
}
public ObjectListReader nextList() {
// assuming that the readerIndex is not altered but other direct accesses to the ByteBuf
int numValues = ByteBufUtils.readVInt(pdu.buffer);
return new ObjectListReader(pdu, numValues);
}
}
public static class ObjectListReader {
private final Pdu pdu;
private final int numParams;
public ObjectListReader(Pdu pdu, int numParams) {
this.pdu = pdu;
this.numParams = numParams;
}
public int getNumParams() {
return numParams;
}
public Object nextObject() {
// assuming that the readerIndex is not altered but other direct accesses to the ByteBuf
return readObject(pdu.buffer);
}
public byte readTrailer() {
// assuming that the readerIndex is not altered but other direct accesses to the ByteBuf
if (pdu.buffer.isReadable()) {
return pdu.buffer.readByte();
} else {
return 0;
}
}
public static boolean isDontKeepReadLocks(byte trailer) {
return ((trailer & Pdu.FLAGS_OPENSCANNER_DONTKEEP_READ_LOCKS) == Pdu.FLAGS_OPENSCANNER_DONTKEEP_READ_LOCKS);
}
}
static void writeObject(ByteBuf byteBuf, Object v) {
if (v == null) {
byteBuf.writeByte(TYPE_NULL);
} else if (v instanceof RawString) {
byteBuf.writeByte(TYPE_STRING);
ByteBufUtils.writeRawString(byteBuf, (RawString) v);
} else if (v instanceof String) {
byteBuf.writeByte(TYPE_STRING);
ByteBufUtils.writeString(byteBuf, (String) v);
} else if (v instanceof Long) {
byteBuf.writeByte(TYPE_LONG);
byteBuf.writeLong((Long) v);
} else if (v instanceof Integer) {
byteBuf.writeByte(TYPE_INTEGER);
byteBuf.writeInt((Integer) v);
} else if (v instanceof Boolean) {
byteBuf.writeByte(TYPE_BOOLEAN);
byteBuf.writeBoolean((Boolean) v);
} else if (v instanceof java.util.Date) {
byteBuf.writeByte(TYPE_TIMESTAMP);
byteBuf.writeLong(((java.util.Date) v).getTime());
} else if (v instanceof Double) {
byteBuf.writeByte(TYPE_DOUBLE);
byteBuf.writeDouble((Double) v);
} else if (v instanceof Float) {
byteBuf.writeByte(TYPE_DOUBLE);
byteBuf.writeDouble((Float) v);
} else if (v instanceof Short) {
byteBuf.writeByte(TYPE_SHORT);
byteBuf.writeShort((Short) v);
} else if (v instanceof byte[]) {
byteBuf.writeByte(TYPE_BYTEARRAY);
ByteBufUtils.writeArray(byteBuf, (byte[]) v);
} else if (v instanceof Byte) {
byteBuf.writeByte(TYPE_BYTE);
byteBuf.writeByte((Byte) v);
} else {
throw new IllegalArgumentException("bad data type " + v.getClass());
}
}
public static Object readObject(ByteBuf dii) {
int type = ByteBufUtils.readVInt(dii);
switch (type) {
case TYPE_BYTEARRAY:
return ByteBufUtils.readArray(dii);
case TYPE_LONG:
return dii.readLong();
case TYPE_INTEGER:
return dii.readInt();
case TYPE_SHORT:
return dii.readShort();
case TYPE_BYTE:
return dii.readByte();
case TYPE_STRING:
return ByteBufUtils.readUnpooledRawString(dii);
case TYPE_TIMESTAMP:
return new java.sql.Timestamp(dii.readLong());
case TYPE_NULL:
return null;
case TYPE_BOOLEAN:
return dii.readBoolean();
case TYPE_DOUBLE:
return dii.readDouble();
default:
throw new IllegalArgumentException("bad column type " + type);
}
}
/**
* Ensure that every parameter matches the same type as when we are marshalling/unmarshalling
* it. This is useful for "local" mode: we do not want a different behaviour in local mode vs network mode
* and also we do not want unexpected JDBC parameter types on server-side processing.
* @param parameters the JDBC parameters
* @return a new list with converted JDBC parameters
* @see #writeObject(io.netty.buffer.ByteBuf, java.lang.Object)
* @see #readObject(io.netty.buffer.ByteBuf)
*/
public static List<Object> normalizeParametersList(List<Object> parameters) {
if (parameters == null || parameters.isEmpty()) {
return parameters;
}
List<Object> result = new ArrayList<>(parameters.size());
for (Object v : parameters) {
if (v == null) {
result.add(null);
} else if (v instanceof String) {
result.add(RawString.of((String) v));
} else if (v instanceof RawString) {
result.add(v);
} else if (v instanceof Long) {
result.add(v);
} else if (v instanceof Integer) {
result.add(v);
} else if (v instanceof Boolean) {
result.add(v);
} else if (v instanceof java.sql.Timestamp) {
result.add(v);
} else if (v instanceof java.util.Date) {
result.add(new java.sql.Timestamp(((java.util.Date) v).getTime()));
} else if (v instanceof Double) {
result.add(v);
} else if (v instanceof Float) {
result.add(((Float) v).doubleValue());
} else if (v instanceof Short) {
result.add(v);
} else if (v instanceof byte[]) {
result.add(v);
} else if (v instanceof Byte) {
result.add(v);
} else {
throw new IllegalArgumentException("bad data type " + v.getClass());
}
}
return result;
}
}
|
922f40d249c99076c729785df785a3d14ed7c5aa | 560 | java | Java | src/main/java/yamahari/ilikewood/block/WoodenLadderBlock.java | meckintosh/ILikeWood-1.15 | 508efa50cdbc1c23d1fccb93beac83bc78d45627 | [
"MIT"
] | null | null | null | src/main/java/yamahari/ilikewood/block/WoodenLadderBlock.java | meckintosh/ILikeWood-1.15 | 508efa50cdbc1c23d1fccb93beac83bc78d45627 | [
"MIT"
] | null | null | null | src/main/java/yamahari/ilikewood/block/WoodenLadderBlock.java | meckintosh/ILikeWood-1.15 | 508efa50cdbc1c23d1fccb93beac83bc78d45627 | [
"MIT"
] | null | null | null | 25.454545 | 77 | 0.742857 | 995,037 | package yamahari.ilikewood.block;
import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraft.block.LadderBlock;
import yamahari.ilikewood.util.IWooden;
import yamahari.ilikewood.util.WoodType;
public final class WoodenLadderBlock extends LadderBlock implements IWooden {
private final WoodType type;
public WoodenLadderBlock(final WoodType type) {
super(Block.Properties.from(Blocks.LADDER));
this.type = type;
}
@Override
public WoodType getWoodType() {
return this.type;
}
}
|
922f40e2d5839b5167a7d9dbe0b47cf549d93b6a | 3,089 | java | Java | src/main/java/org/ednovo/gooru/client/mvp/shelf/collection/tab/info/IsCollectionInfoTabView.java | sravanthi1/Gooru-Web | 1c3f36069996be43b47d88fec981f2a644c9200a | [
"MIT"
] | null | null | null | src/main/java/org/ednovo/gooru/client/mvp/shelf/collection/tab/info/IsCollectionInfoTabView.java | sravanthi1/Gooru-Web | 1c3f36069996be43b47d88fec981f2a644c9200a | [
"MIT"
] | null | null | null | src/main/java/org/ednovo/gooru/client/mvp/shelf/collection/tab/info/IsCollectionInfoTabView.java | sravanthi1/Gooru-Web | 1c3f36069996be43b47d88fec981f2a644c9200a | [
"MIT"
] | null | null | null | 34.322222 | 98 | 0.721593 | 995,038 | /*******************************************************************************
* Copyright 2013 Ednovo d/b/a Gooru. All rights reserved.
*
* http://www.goorulearning.org/
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
******************************************************************************/
package org.ednovo.gooru.client.mvp.shelf.collection.tab.info;
import java.util.List;
import org.ednovo.gooru.client.gin.IsViewWithHandlers;
import org.ednovo.gooru.shared.model.code.CodeDo;
import org.ednovo.gooru.shared.model.code.LibraryCodeDo;
import org.ednovo.gooru.shared.model.content.CollectionDo;
import org.ednovo.gooru.shared.model.search.SearchDo;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
/**
* @author Search Team
*
*/
public interface IsCollectionInfoTabView extends IsViewWithHandlers<CollectionInfoTabUiHandlers> {
/**
* Set collection meta data info
* @param collectionDo instance of {@link CollectionDo}
*/
void setData(CollectionDo collectionDo);
/**
* Set suggest standards
* @param mapSearchDo instance of {@link SearchDo} type of {@link CodeDo}
*/
void setStandardSuggestions(SearchDo<CodeDo> mapSearchDo);
/**
* Set collection default course
* @param libraryCode instance {@link LibraryCodeDo} as List
*/
void setCourseList(List<LibraryCodeDo> libraryCode);
/**
* Update collection course
* @param collectionDo instance of {@link CollectionDo}
*/
void onPostCourseUpdate(CollectionDo collectionDo);
/**
* Update collection standards
* @param collectionDo instance of {@link CollectionDo}
*/
void onPostStandardUpdate(CollectionDo collectionDo);
void closeAllOpenedPopUp();
FlowPanel getStandardContainer();
void getUserStandardPrefCodeId(List<String> list);
void OnStandardsClickEvent(Button addBtn);
void setUpdatedStandards(String standardsCode, Integer codeId,String description);
/* void displayErrorMsgTeacherTip();
void setExistingTeacherTip(CollectionDo collectionDo);*/
}
|
922f41de0ae7a9ec8bc020d62490cac6868ba4b4 | 1,759 | java | Java | src/main/java/com/llf/springboot/poi/MyExcelExportUtil.java | 1537898081/spring-boot-demo | ca19396f8bc8f6ce08ddf10ddad7ab2e9fd35604 | [
"MIT"
] | null | null | null | src/main/java/com/llf/springboot/poi/MyExcelExportUtil.java | 1537898081/spring-boot-demo | ca19396f8bc8f6ce08ddf10ddad7ab2e9fd35604 | [
"MIT"
] | 1 | 2021-02-03T19:31:05.000Z | 2021-02-03T19:31:05.000Z | src/main/java/com/llf/springboot/poi/MyExcelExportUtil.java | 1537898081/spring-boot-demo | ca19396f8bc8f6ce08ddf10ddad7ab2e9fd35604 | [
"MIT"
] | null | null | null | 35.897959 | 145 | 0.688459 | 995,039 | package com.llf.springboot.poi;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import org.apache.poi.ss.usermodel.Workbook;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
/**
* @ClassName: ExcelExportUtil
* @Description: Exceld导出工具类
* @Author: sunt
* @Date: 2019/8/30 14:49
* @Version 1.0
**/
public class MyExcelExportUtil {
/**
* Excel文件导出,导出的文件名默认为:headTitle+当前系统时间
* @param listData 要导出的list数据
* @param pojoClass 定义excel属性信息
* @param headTitle Excel文件头信息
* @param sheetName Excel文件sheet名称
* @param response
*/
public static void exportExcel(Collection<?> listData,Class<?> pojoClass, String headTitle, String sheetName, HttpServletResponse response) {
ExportParams params = new ExportParams(headTitle, sheetName);
params.setHeight((short) 8);
params.setStyle(ExcelExportMyStylerImpl.class);
try {
Workbook workbook = ExcelExportUtil.exportExcel(params, pojoClass, listData);
String fileName = headTitle + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
fileName = URLEncoder.encode(fileName, "UTF8");
response.setContentType("application/vnd.ms-excel;chartset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename="+fileName + ".xls");
ServletOutputStream out=response.getOutputStream();
workbook.write(out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} |
922f430ac22982454d19204974496c501284a477 | 1,032 | java | Java | app/src/main/java/com/hzh/myweather/adapter/MainFragmentAdapter.java | yan-mingwei/MyWeather | d9a7186b3d02b3b9d26aa7a4046c20c0a554ca86 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/hzh/myweather/adapter/MainFragmentAdapter.java | yan-mingwei/MyWeather | d9a7186b3d02b3b9d26aa7a4046c20c0a554ca86 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/hzh/myweather/adapter/MainFragmentAdapter.java | yan-mingwei/MyWeather | d9a7186b3d02b3b9d26aa7a4046c20c0a554ca86 | [
"Apache-2.0"
] | null | null | null | 24.571429 | 138 | 0.724806 | 995,040 | package com.hzh.myweather.adapter;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Lifecycle;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import java.util.ArrayList;
import java.util.List;
public class MainFragmentAdapter extends FragmentStateAdapter {
ArrayList<Fragment> fragmentList;
public MainFragmentAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle,ArrayList<Fragment> fragmentList) {
super(fragmentManager, lifecycle);
this.fragmentList=fragmentList;
}
@NonNull
@Override
public Fragment createFragment(int position) {
return fragmentList.get(position);
}
@Override
public int getItemCount() {
return fragmentList.size();
}
/**
* 更新数据源
* @param cities
*/
public void refreshData(ArrayList<Fragment> cities){
fragmentList=cities;
notifyDataSetChanged();
}
}
|
922f440422cac05f1d27c4df5769a8a5ccdcdbf0 | 3,095 | java | Java | src/main/java/net/xmeter/ethereum/sampler/DeployContract.java | Nero1930/ethereum-jmeter | 074fe690add7e2015de631ae9f62dfef901482e9 | [
"Apache-2.0"
] | 4 | 2018-01-29T02:12:37.000Z | 2018-11-27T09:48:42.000Z | src/main/java/net/xmeter/ethereum/sampler/DeployContract.java | XMeterSaaSService/ethereum-jmeter | 074fe690add7e2015de631ae9f62dfef901482e9 | [
"Apache-2.0"
] | null | null | null | src/main/java/net/xmeter/ethereum/sampler/DeployContract.java | XMeterSaaSService/ethereum-jmeter | 074fe690add7e2015de631ae9f62dfef901482e9 | [
"Apache-2.0"
] | 4 | 2018-03-19T04:55:32.000Z | 2018-11-27T09:48:43.000Z | 31.907216 | 110 | 0.685622 | 995,041 | package net.xmeter.ethereum.sampler;
import org.apache.jmeter.samplers.AbstractSampler;
import org.apache.jmeter.samplers.Entry;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
import net.xmeter.ethereum.common.Constants;
import net.xmeter.ethereum.common.EthTestUtil;
@SuppressWarnings("deprecation")
public class DeployContract extends AbstractSampler implements Constants {
private static final long serialVersionUID = 1L;
public boolean isUseCorrelatedData() {
return getPropertyAsBoolean("useCorrelatedData");
}
public void setUseCorrelatedData(boolean useCorrelatedData) {
setProperty("useCorrelatedData", useCorrelatedData);
}
public String getBinStr() {
return getPropertyAsString(BINCODE, "");
}
public void setBinStr(String binStr) {
setProperty(BINCODE, binStr);
}
public String getGas() {
return getPropertyAsString("gas", "");
}
public void setGas(String gas) {
setProperty("gas", gas);
}
public String getFromUser() {
return getPropertyAsString("fromUser", "");
}
public void setFromUser(String fromUser) {
setProperty("fromUser", fromUser);
}
@Override
public SampleResult sample(Entry arg0) {
SampleResult result = new SampleResult();
result.setSampleLabel(getName());
try {
String binStr, gas;
if (isUseCorrelatedData()) {
JMeterVariables vars = JMeterContextService.getContext().getVariables();
binStr = (vars.get("binStr") == null) ? "null" : vars.get("binStr");
gas = (vars.get("gas") == null) ? "null" : vars.get("gas");
} else {
binStr = getBinStr();
gas= getGas();
}
String fromUser = getFromUser();
result.sampleStart();
String postData = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_sendTransaction\",\"params\":[{\"from\":\""
+ fromUser + "\",\"gas\":\"" + gas + "\",\"data\":\"" + binStr + "\"}],\"id\":1003}";
result.setRequestHeaders(postData);
String responseMsg = EthTestUtil.invokeAPI(null, postData);
result.sampleEnd();
Object document = Configuration.defaultConfiguration().jsonProvider().parse(responseMsg);
try {
JsonPath.read(document, "$.error").toString(); // detect possible error first
result.setResponseCode("400");
result.setResponseData(responseMsg);
} catch (com.jayway.jsonpath.PathNotFoundException e) {
String txHash = JsonPath.read(document, "$.result").toString();
result.setResponseCode("200");
result.setSuccessful(true);
result.setResponseData(responseMsg);
JMeterVariables vars = JMeterContextService.getContext().getVariables();
vars.put("txHash", txHash);
}
} catch(Exception ex) {
if (result.getEndTime() == 0) result.sampleEnd(); // avoid twice call sampleEnd()
result.setResponseCode("500");
result.setResponseData(ex.getMessage().getBytes());
}
return result;
}
}
|
922f443c6fc3e39e28f5be96518f22876f24c5d9 | 198 | java | Java | code-rule/src/main/java/com/keehoo/rule/converter/Converter.java | wuzhihao7/java-samples | fef51504e5ff7bcddbc708f98d2cabce94ae12db | [
"Apache-2.0"
] | null | null | null | code-rule/src/main/java/com/keehoo/rule/converter/Converter.java | wuzhihao7/java-samples | fef51504e5ff7bcddbc708f98d2cabce94ae12db | [
"Apache-2.0"
] | null | null | null | code-rule/src/main/java/com/keehoo/rule/converter/Converter.java | wuzhihao7/java-samples | fef51504e5ff7bcddbc708f98d2cabce94ae12db | [
"Apache-2.0"
] | null | null | null | 15.230769 | 41 | 0.641414 | 995,042 | package com.technologysia.rule.converter;
/**
* 对象转换
* @author wuzhihao
* @version V1.0
* @since 2019/3/20
*/
public interface Converter<S, T> {
T doForward(S s);
S doBackward(T t);
}
|
922f4441c9922cab1912622186700affc363be75 | 378 | java | Java | mobile_app1/module1183/src/main/java/module1183packageJava0/Foo1875.java | HiWong/android-build-eval | d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6 | [
"Apache-2.0"
] | 70 | 2021-01-22T16:48:06.000Z | 2022-02-16T10:37:33.000Z | mobile_app1/module1183/src/main/java/module1183packageJava0/Foo1875.java | HiWong/android-build-eval | d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6 | [
"Apache-2.0"
] | 16 | 2021-01-22T20:52:52.000Z | 2021-08-09T17:51:24.000Z | mobile_app1/module1183/src/main/java/module1183packageJava0/Foo1875.java | HiWong/android-build-eval | d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6 | [
"Apache-2.0"
] | 5 | 2021-01-26T13:53:49.000Z | 2021-08-11T20:10:57.000Z | 11.8125 | 48 | 0.579365 | 995,043 | package module1183packageJava0;
import java.lang.Integer;
public class Foo1875 {
Integer int0;
public void foo0() {
new module1183packageJava0.Foo1874().foo5();
}
public void foo1() {
foo0();
}
public void foo2() {
foo1();
}
public void foo3() {
foo2();
}
public void foo4() {
foo3();
}
public void foo5() {
foo4();
}
}
|
922f455ec2466f6be99c2f41008f8229d21f8192 | 3,518 | java | Java | odata_parser/src/test/java/com/sdl/odata/parser/ParserArithmeticTest.java | leviramsey/odata | 500cdb6dfa69197fb135867a7425cd3c85682bf9 | [
"Apache-2.0"
] | 140 | 2015-09-14T10:52:19.000Z | 2021-06-05T03:30:06.000Z | odata_parser/src/test/java/com/sdl/odata/parser/ParserArithmeticTest.java | adilakhter/odata | 96754a6df36e2849a0498f1111640bce515dfaaf | [
"Apache-2.0"
] | 139 | 2015-08-17T14:20:49.000Z | 2021-02-03T19:27:25.000Z | odata_parser/src/test/java/com/sdl/odata/parser/ParserArithmeticTest.java | adilakhter/odata | 96754a6df36e2849a0498f1111640bce515dfaaf | [
"Apache-2.0"
] | 56 | 2015-09-14T10:52:23.000Z | 2020-12-18T09:42:00.000Z | 40.436782 | 117 | 0.729676 | 995,044 | /*
* Copyright (c) 2014-2021 All Rights Reserved by the RWS Group for and on behalf of its affiliates and subsidiaries.
*
* 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.sdl.odata.parser;
import com.sdl.odata.api.ODataException;
import com.sdl.odata.api.parser.AddExpr;
import com.sdl.odata.api.parser.ArithmeticExpr;
import com.sdl.odata.api.parser.DivExpr;
import com.sdl.odata.api.parser.EntityPathExpr;
import com.sdl.odata.api.parser.FilterOption;
import com.sdl.odata.api.parser.GtExpr;
import com.sdl.odata.api.parser.LiteralExpr;
import com.sdl.odata.api.parser.ModExpr;
import com.sdl.odata.api.parser.MulExpr;
import com.sdl.odata.api.parser.NumberLiteral;
import com.sdl.odata.api.parser.ODataUri;
import com.sdl.odata.api.parser.PropertyPathExpr;
import com.sdl.odata.api.parser.SubExpr;
import org.junit.Test;
import scala.math.BigDecimal;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
/**
* Parser Arithmetic Test.
*
*/
public class ParserArithmeticTest extends ParserTestSuite {
@Test
public void testArithmeticOperators() throws ODataException {
GtExpr addGtExpr = getExprFromOperator("add");
AddExpr addExpr = (AddExpr) addGtExpr.left();
processArithmeticTree(addExpr, addGtExpr);
GtExpr subGtExpr = getExprFromOperator("sub");
SubExpr subExpr = (SubExpr) subGtExpr.left();
processArithmeticTree(subExpr, subGtExpr);
GtExpr mulGtExpr = getExprFromOperator("mul");
MulExpr mulExpr = (MulExpr) mulGtExpr.left();
processArithmeticTree(mulExpr, mulGtExpr);
GtExpr divGtExpr = getExprFromOperator("div");
DivExpr divExpr = (DivExpr) divGtExpr.left();
processArithmeticTree(divExpr, divGtExpr);
GtExpr modGtExpr = getExprFromOperator("mod");
ModExpr modExpr = (ModExpr) modGtExpr.left();
processArithmeticTree(modExpr, modGtExpr);
}
private void processArithmeticTree(ArithmeticExpr addExpr, GtExpr expression) {
EntityPathExpr entityPathExpr = (EntityPathExpr) addExpr.left();
PropertyPathExpr propertyPathExpr = (PropertyPathExpr) entityPathExpr.subPath().get();
assertThat(propertyPathExpr.propertyName(), is("id"));
LiteralExpr literalExpr = (LiteralExpr) addExpr.right();
NumberLiteral nubmerLiteral = (NumberLiteral) literalExpr.value();
assertThat(nubmerLiteral.value(), is(new BigDecimal(new java.math.BigDecimal(5))));
LiteralExpr literal = (LiteralExpr) expression.right();
NumberLiteral number = (NumberLiteral) literal.value();
assertThat(number.value(), is(new BigDecimal(new java.math.BigDecimal(10))));
}
public GtExpr getExprFromOperator(String operator) throws ODataException {
ODataUri uri = parser.parseUri(SERVICE_ROOT + "Products?$filter=id " + operator + " 5 gt 10", model);
FilterOption option = getSingleOption(uri);
return (GtExpr) option.expression();
}
}
|
922f465af176f95985f91dc14d81230fdb85ab90 | 4,314 | java | Java | app/src/test/java/com/sap/cloud/sfsf/timeoff/entity/SFSFEmployeeTimeTest.java | sunilake/cloud-sfsf-timeoff-ext | 9a300911f59ecfbd41e9e288a12b85ac2bfc6fbb | [
"Apache-2.0"
] | 5 | 2017-05-29T11:41:02.000Z | 2020-08-18T12:21:17.000Z | app/src/test/java/com/sap/cloud/sfsf/timeoff/entity/SFSFEmployeeTimeTest.java | SAP/cloud-sfsf-timeoff-ext | 3fe4a95544034beda408fcecfbd7c7a364985660 | [
"Apache-2.0"
] | null | null | null | app/src/test/java/com/sap/cloud/sfsf/timeoff/entity/SFSFEmployeeTimeTest.java | SAP/cloud-sfsf-timeoff-ext | 3fe4a95544034beda408fcecfbd7c7a364985660 | [
"Apache-2.0"
] | 2 | 2017-11-08T10:45:09.000Z | 2018-10-22T23:28:01.000Z | 38.176991 | 117 | 0.751275 | 995,045 | /**
* Copyright 2016 SAP SE
*
* 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.sap.cloud.sfsf.timeoff.entity;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.net.URL;
import java.text.ParseException;
import java.time.OffsetDateTime;
import java.time.ZonedDateTime;
import com.fasterxml.jackson.annotation.JsonCreator.Mode;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import com.sap.cloud.sfsf.timeoff.entity.EmpJob;
import com.sap.cloud.sfsf.timeoff.entity.SFSFEmployeeTime;
import com.sap.cloud.sfsf.timeoff.entity.UserIdNav;
import org.junit.Before;
import org.junit.Test;
public class SFSFEmployeeTimeTest {
private SFSFEmployeeTime empTime;
private EmpJob empJob;
private UserIdNav userIdNav;
@Before
public void before() {
empJob = new EmpJob();
userIdNav = new UserIdNav().setJob(empJob);
}
@Test
public void oneDayIsAddedToEndTime() {
// given
final OffsetDateTime endDT = OffsetDateTime.parse("2016-05-30T00:00:00Z");
// when
empTime = new SFSFEmployeeTime(OffsetDateTime.parse("2016-05-20T00:00:00Z"), endDT, userIdNav, endDT, endDT);
// then
assertThat(empTime.getEndDate()).describedAs("One day needs to be added to endDate to compensate for SFSF issue")
.isEqualTo(ZonedDateTime.parse("2016-05-31T00:00:00Z[UTC]"));
}
@Test
public void zonedStartDateIsNotChanged() throws ParseException {
// given
final OffsetDateTime startDate = OffsetDateTime.parse("2016-05-30T00:00:00Z");
empJob.setTimezone("PST");
// when
empTime = new SFSFEmployeeTime(startDate, startDate, userIdNav, startDate, startDate);
// then
final ZonedDateTime result = empTime.getStartDate();
assertThat(result).describedAs("Only the zone should be added. The time should not be changed")
.isEqualTo(ZonedDateTime.parse("2016-05-30T00:00-07:00[America/Los_Angeles]"));
}
@Test
public void zonedEndDateOneDayAdded() throws ParseException {
// given
final OffsetDateTime endDate = OffsetDateTime.parse("2016-05-30T00:00:00Z");
empJob.setTimezone("PST");
// when
empTime = new SFSFEmployeeTime(endDate, endDate, userIdNav, endDate, endDate);
// then
final ZonedDateTime result = empTime.getEndDate();
assertThat(result).describedAs("Only the zone should be added. The time should not be changed")
.isEqualTo(ZonedDateTime.parse("2016-05-31T00:00-07:00[America/Los_Angeles]"));
}
@Test
public void testSerlialization() throws JsonParseException, JsonMappingException, IOException {
// given
final ObjectMapper mapper =
new ObjectMapper().registerModules(new ParameterNamesModule(Mode.PROPERTIES), new JavaTimeModule())
.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
final URL jsonFile = Thread.currentThread().getContextClassLoader().getResource("employee_time_data.json");
// when
final SFSFEmployeeTime result = mapper.readValue(jsonFile, SFSFEmployeeTime.class);
// then
assertThat(result.getStartDate()).isEqualTo(ZonedDateTime.parse("2016-05-30T00:00:00-04:00[US/Eastern]"));
assertThat(result.getEndDate()).isEqualTo(ZonedDateTime.parse("2016-06-01T00:00:00-04:00[US/Eastern]"));
assertThat(result.getCreatedDateTime()).isEqualTo(ZonedDateTime.parse("2016-05-11T09:40:14Z[US/Eastern]"));
assertThat(result.getLastModifiedDateTime()).isEqualTo(ZonedDateTime.parse("2016-05-11T09:40:14Z[US/Eastern]"));
}
}
|
922f4729d0070c6754abbfccae28fc67e5f9cb6c | 4,898 | java | Java | src/test/java/org/robolectric/util/TestUtil.java | daisy1754/robolectric | fe5d80212e0cd6c717eb33a3e2154bd4bc3c4968 | [
"MIT"
] | null | null | null | src/test/java/org/robolectric/util/TestUtil.java | daisy1754/robolectric | fe5d80212e0cd6c717eb33a3e2154bd4bc3c4968 | [
"MIT"
] | null | null | null | src/test/java/org/robolectric/util/TestUtil.java | daisy1754/robolectric | fe5d80212e0cd6c717eb33a3e2154bd4bc3c4968 | [
"MIT"
] | null | null | null | 39.184 | 166 | 0.664965 | 995,046 | package org.robolectric.util;
import org.robolectric.AndroidManifest;
import org.robolectric.R;
import org.robolectric.res.AndroidSdkFinder;
import org.robolectric.res.ResourcePath;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Collection;
import static org.junit.Assert.assertTrue;
import static org.robolectric.Robolectric.DEFAULT_SDK_VERSION;
public abstract class TestUtil {
public static final ResourcePath TEST_RESOURCE_PATH = new ResourcePath(R.class, resourceFile("res"), resourceFile("assets"));
public static final String TEST_PACKAGE = R.class.getPackage().getName();
public static final ResourcePath SYSTEM_RESOURCE_PATH = new AndroidSdkFinder().findSystemResourcePath(DEFAULT_SDK_VERSION);
public static final String SYSTEM_PACKAGE = android.R.class.getPackage().getName();
public static File testDirLocation;
public static void assertEquals(Collection<?> expected, Collection<?> actual) {
org.junit.Assert.assertEquals(stringify(expected), stringify(actual));
}
public static String stringify(Collection<?> collection) {
StringBuilder buf = new StringBuilder();
for (Object o : collection) {
if (buf.length() > 0) buf.append("\n");
buf.append(o);
}
return buf.toString();
}
public static <T> void assertInstanceOf(Class<? extends T> expectedClass, T object) {
Class actualClass = object.getClass();
assertTrue(expectedClass + " should be assignable from " + actualClass,
expectedClass.isAssignableFrom(actualClass));
}
public static File resourcesBaseDir() {
if (testDirLocation == null) {
File testDir = Util.file("src", "test", "resources");
if (hasTestManifest(testDir)) return testDirLocation = testDir;
File roboTestDir = Util.file("robolectric", "src", "test", "resources");
if (hasTestManifest(roboTestDir)) return testDirLocation = roboTestDir;
File submoduleDir = Util.file("submodules", "robolectric", "src", "test", "resources");
if (hasTestManifest(submoduleDir)) return testDirLocation = submoduleDir;
//required for robolectric-sqlite to find resources to test against
File roboSiblingTestDir = Util.file(new File(new File(".").getAbsolutePath()).getParentFile().getParentFile(), "robolectric", "src", "test", "resources");
if (hasTestManifest(roboSiblingTestDir)) return testDirLocation = roboSiblingTestDir;
throw new RuntimeException("can't find your TestAndroidManifest.xml in "
+ testDir.getAbsolutePath() + " or " + roboTestDir.getAbsolutePath() + "\n or " + roboSiblingTestDir.getAbsolutePath());
} else {
return testDirLocation;
}
}
private static boolean hasTestManifest(File testDir) {
return new File(testDir, "TestAndroidManifest.xml").isFile();
}
public static File resourceFile(String... pathParts) {
return Util.file(resourcesBaseDir(), pathParts);
}
public static ResourcePath testResources() {
return TEST_RESOURCE_PATH;
}
public static ResourcePath lib1Resources() {
return new ResourcePath(org.robolectric.lib1.R.class, resourceFile("lib1/res"), resourceFile("lib1/assets"));
}
public static ResourcePath lib2Resources() {
return new ResourcePath(org.robolectric.lib2.R.class, resourceFile("lib2/res"), resourceFile("lib2/assets"));
}
public static ResourcePath lib3Resources() {
return new ResourcePath(org.robolectric.lib3.R.class, resourceFile("lib3/res"), resourceFile("lib3/assets"));
}
public static ResourcePath systemResources() {
return SYSTEM_RESOURCE_PATH;
}
public static AndroidManifest newConfig(String androidManifestFile) {
return new AndroidManifest(resourceFile(androidManifestFile), null, null);
}
public static String readString(InputStream is) throws IOException {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
return writer.toString();
}
public static String joinPath(String... parts) {
File file = new File(parts[0]);
for (int i = 1; i < parts.length; i++) {
String part = parts[i];
file = new File(file, part);
}
return file.getPath();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.