text
stringlengths 7
1.01M
|
|---|
/*
* Copyright 2018 Red Hat, Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.reactiverse.es4x.impl;
import io.reactiverse.es4x.ESVerticleFactory;
import io.reactiverse.es4x.Runtime;
import io.vertx.core.*;
import io.vertx.core.buffer.Buffer;
import java.nio.file.InvalidPathException;
public final class MJSVerticleFactory extends ESVerticleFactory {
@Override
public String prefix() {
return "mjs";
}
@Override
protected Verticle createVerticle(Runtime runtime, String fsVerticleName) {
return new Verticle() {
private Vertx vertx;
private Context context;
@Override
public Vertx getVertx() {
return vertx;
}
@Override
public void init(Vertx vertx, Context context) {
this.vertx = vertx;
this.context = context;
}
@Override
public void start(Promise<Void> startFuture) {
final String address;
final boolean worker;
if (context != null) {
address = context.deploymentID();
worker = context.isWorkerContext();
// expose config
if (context.config() != null) {
runtime.config(context.config());
}
} else {
worker = false;
address = null;
}
try {
if (worker) {
setupVerticleMessaging(runtime, vertx, address);
}
// wrap the deployment in a execute blocking as blocking net/io can happen during deploy
vertx
.<Void>executeBlocking(deploy -> {
try {
// the main script buffer
final Buffer buffer = vertx.fileSystem().readFileBlocking(fsVerticleName);
runtime.eval(
// strip the shebang if present
ESModuleIO.stripShebang(buffer.toString()),
fsVerticleName,
"application/javascript+module",
false);
deploy.complete();
} catch (InvalidPathException e) {
deploy.fail("File Not Found: " + fsVerticleName);
} catch (RuntimeException e) {
deploy.fail(e);
}
}, true)
.onFailure(startFuture::fail)
.onSuccess(v ->
waitFor(runtime, "deploy").onComplete(startFuture));
} catch (RuntimeException e) {
startFuture.fail(e);
}
}
@Override
public void stop(Promise<Void> stopFuture) {
// call the undeploy if available
waitFor(runtime, "undeploy")
.onComplete(undeploy -> {
stopFuture.handle(undeploy);
runtime.close();
});
}
};
}
@Override
protected String[] defaultExtensions() {
return new String[] {
".mjs",
".js"
};
}
}
|
/**
*
*/
package org.junit.experimental.theories.internal;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Assume.AssumptionViolatedException;
import org.junit.experimental.theories.ParameterSignature;
import org.junit.experimental.theories.PotentialParameterValue;
import org.junit.experimental.theories.Theory;
import org.junit.experimental.theories.PotentialParameterValue.CouldNotGenerateValueException;
import org.junit.internal.runners.TestClass;
import org.junit.internal.runners.TestMethod;
public class TheoryMethod extends TestMethod {
public static class PotentialMethodValues {
public final List<PotentialParameterValue> fSources;
public PotentialMethodValues() {
this(new ArrayList<PotentialParameterValue>());
}
public PotentialMethodValues(List<PotentialParameterValue> concat) {
fSources= concat;
}
Object[] getValues(boolean nullsOk) throws CouldNotGenerateValueException {
Object[] values= new Object[fSources.size()];
for (int i= 0; i < values.length; i++) {
values[i]= fSources.get(i).getValue();
if (values[i] == null && !nullsOk)
throw new CouldNotGenerateValueException();
}
return values;
}
PotentialMethodValues concat(PotentialParameterValue source) {
List<PotentialParameterValue> list= new ArrayList<PotentialParameterValue>();
list.addAll(fSources);
list.add(source);
return new PotentialMethodValues(list);
}
}
private final Method fMethod;
private List<AssumptionViolatedException> fInvalidParameters= new ArrayList<AssumptionViolatedException>();
public TheoryMethod(Method method, TestClass testClass) {
super(method, testClass);
fMethod= method;
}
@Override
public void invoke(Object test) throws IllegalArgumentException,
IllegalAccessException, InvocationTargetException {
int runCount= 0;
try {
runCount+= runWithDiscoveredParameterValues(test,
new PotentialMethodValues(), ParameterSignature
.signatures(fMethod));
} catch (Throwable e) {
throw new InvocationTargetException(e);
}
if (runCount == 0)
Assert
.fail("Never found parameters that satisfied method. Violated assumptions: "
+ fInvalidParameters);
}
public boolean nullsOk() {
Theory annotation= fMethod.getAnnotation(Theory.class);
if (annotation == null)
return false;
return annotation.nullsAccepted();
}
int invokeWithActualParameters(Object target, Object[] params)
throws Throwable {
try {
try {
fMethod.invoke(target, params);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
} catch (AssumptionViolatedException e) {
fInvalidParameters.add(e);
return 0;
} catch (Throwable e) {
if (params.length == 0)
throw e;
throw new ParameterizedAssertionError(e, fMethod.getName(), params);
}
return 1;
}
int runWithDiscoveredParameterValues(Object target,
PotentialMethodValues valueSources, List<ParameterSignature> sigs)
throws Throwable {
if (sigs.size() == 0) {
try {
return invokeWithActualParameters(target, valueSources
.getValues(nullsOk()));
} catch (CouldNotGenerateValueException e) {
return 0;
}
}
int count= 0;
for (PotentialParameterValue source : sigs.get(0).getPotentialValues(
target)) {
count+= runWithDiscoveredParameterValues(target, valueSources
.concat(source), sigs.subList(1, sigs.size()));
}
return count;
}
}
|
/*
* ApplicationInsights-Java
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the ""Software""), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package com.microsoft.applicationinsights.agent.internal.config;
import com.microsoft.applicationinsights.agent.internal.agent.ClassInstrumentationData;
import java.util.List;
/**
* Created by gupele on 6/5/2015.
*/
public class AgentBuiltInConfiguration {
private final boolean enabled;
private final boolean httpEnabled;
private final boolean jdbcEnabled;
private final boolean hibernateEnabled;
private final boolean jedisEnabled;
private final boolean jmxEnabled;
private final long maxSqlQueryLimitInMS;
private final long redisThresholdInMS;
private final DataOfConfigurationForException dataOfConfigurationForException;
private final List<ClassInstrumentationData> simpleBuiltInClasses;
public AgentBuiltInConfiguration(boolean enabled,
List<ClassInstrumentationData> simpleBuiltInClasses,
boolean httpEnabled,
boolean jdbcEnabled,
boolean hibernateEnabled,
boolean jedisEnabled,
boolean jmxEnabled,
Long maxSqlQueryLimitInMS,
long redisThresholdInMS,
DataOfConfigurationForException dataOfConfigurationForException) {
this.simpleBuiltInClasses = simpleBuiltInClasses;
this.enabled = enabled;
this.httpEnabled = httpEnabled;
this.jdbcEnabled = jdbcEnabled;
this.hibernateEnabled = hibernateEnabled;
this.jmxEnabled = jmxEnabled;
if (maxSqlQueryLimitInMS == null) {
throw new IllegalArgumentException("maxSqlQueryLimit cannot be null");
}
this.redisThresholdInMS = redisThresholdInMS;
this.jedisEnabled = jedisEnabled;
this.maxSqlQueryLimitInMS = maxSqlQueryLimitInMS;
this.dataOfConfigurationForException = dataOfConfigurationForException;
}
public boolean isEnabled() {
return enabled;
}
public boolean isHttpEnabled() {
return httpEnabled;
}
public boolean isJdbcEnabled() {
return jdbcEnabled;
}
public boolean isHibernateEnabled() {
return hibernateEnabled;
}
public long getSqlMaxQueryLimitInMS() {
return maxSqlQueryLimitInMS;
}
public boolean isRedisEnabled() {
return jedisEnabled;
}
public long getRedisThresholdInMS() {
return redisThresholdInMS;
}
public boolean isJmxEnabled() {
return jmxEnabled;
}
public DataOfConfigurationForException getDataOfConfigurationForException() {
return dataOfConfigurationForException;
}
public List<ClassInstrumentationData> getSimpleBuiltInClasses() {
return simpleBuiltInClasses;
}
}
|
package com.quorum.tessera.test.rest;
import static org.assertj.core.api.Assertions.assertThat;
import com.quorum.tessera.test.Party;
import com.quorum.tessera.test.PartyHelper;
import jakarta.json.Json;
import jakarta.json.JsonArrayBuilder;
import jakarta.json.JsonObject;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.util.Arrays;
import java.util.stream.Stream;
public class PrivacyGroupTestUtil {
private PartyHelper partyHelper = PartyHelper.create();
public String create(String... aliases) {
JsonArrayBuilder members = Json.createArrayBuilder();
Stream.of(aliases).map(partyHelper::findByAlias).map(Party::getPublicKey).forEach(members::add);
Party sender = partyHelper.findByAlias(aliases[0]);
JsonObject json =
Json.createObjectBuilder()
.add("addresses", members)
.add("from", sender.getPublicKey())
.add("name", "Organisation " + Arrays.toString(aliases))
.add("description", "Contains members of Organisation " + Arrays.toString(aliases))
.build();
final Response response =
sender
.getRestClient()
.target(sender.getQ2TUri())
.path("/createPrivacyGroup")
.request()
.post(Entity.entity(json, MediaType.APPLICATION_JSON));
assertThat(response.getStatus()).isEqualTo(200);
return response.readEntity(String.class);
}
public String retrieve(String targetNode, String groupId) {
JsonObject reqJson = Json.createObjectBuilder().add("privacyGroupId", groupId).build();
Party node = partyHelper.findByAlias(targetNode);
final Response response =
node.getRestClient()
.target(node.getQ2TUri())
.path("/retrievePrivacyGroup")
.request()
.post(Entity.entity(reqJson, MediaType.APPLICATION_JSON));
assertThat(response.getStatus()).isEqualTo(200);
return response.readEntity(String.class);
}
public String find(String targetNode, String... aliases) {
JsonArrayBuilder members = Json.createArrayBuilder();
Stream.of(aliases).map(partyHelper::findByAlias).map(Party::getPublicKey).forEach(members::add);
JsonObject json = Json.createObjectBuilder().add("addresses", members).build();
Party node = partyHelper.findByAlias(targetNode);
final Response response =
node.getRestClient()
.target(node.getQ2TUri())
.path("/findPrivacyGroup")
.request()
.post(Entity.entity(json, MediaType.APPLICATION_JSON));
assertThat(response.getStatus()).isEqualTo(200);
return response.readEntity(String.class);
}
}
|
/**
* The MIT License
* Copyright (c) 2010 Tad Glines
*
* Contributors: Ovea.com, Mycila.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.glines.socketio.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.ServiceConfigurationError;
/**
* @author Mathieu Carbou <mathieu.carbou@gmail.com>
* @param <S> The type of the service to be loaded by this loader
*/
public final class ServiceClassLoader<S> implements Iterable<Class<S>> {
private static final String PREFIX = "META-INF/services/";
private final Class<S> service;
private final Loader loader;
private LinkedHashMap<String, Class<S>> providers = new LinkedHashMap<String, Class<S>>();
private LazyIterator lookupIterator;
public void reload() {
providers.clear();
lookupIterator = new LazyIterator(service, loader);
}
private ServiceClassLoader(Class<S> svc, Loader loader) {
this.service = svc;
this.loader = loader;
reload();
}
private static void fail(Class service, String msg, Throwable cause) throws ServiceConfigurationError {
throw new ServiceConfigurationError(service.getName() + ": " + msg, cause);
}
private static void fail(Class service, String msg) throws ServiceConfigurationError {
throw new ServiceConfigurationError(service.getName() + ": " + msg);
}
private static void fail(Class service, URL u, int line, String msg) throws ServiceConfigurationError {
fail(service, u + ":" + line + ": " + msg);
}
private int parseLine(Class service, URL u, BufferedReader r, int lc, List<String> names) throws IOException, ServiceConfigurationError {
String ln = r.readLine();
if (ln == null) return -1;
int ci = ln.indexOf('#');
if (ci >= 0) ln = ln.substring(0, ci);
ln = ln.trim();
int n = ln.length();
if (n != 0) {
if ((ln.indexOf(' ') >= 0) || (ln.indexOf('\t') >= 0))
fail(service, u, lc, "Illegal configuration-file syntax");
int cp = ln.codePointAt(0);
if (!Character.isJavaIdentifierStart(cp))
fail(service, u, lc, "Illegal provider-class name: " + ln);
for (int i = Character.charCount(cp); i < n; i += Character.charCount(cp)) {
cp = ln.codePointAt(i);
if (!Character.isJavaIdentifierPart(cp) && (cp != '.'))
fail(service, u, lc, "Illegal provider-class name: " + ln);
}
if (!providers.containsKey(ln) && !names.contains(ln))
names.add(ln);
}
return lc + 1;
}
private Iterator<String> parse(Class service, URL u) throws ServiceConfigurationError {
InputStream in = null;
BufferedReader r = null;
ArrayList<String> names = new ArrayList<String>();
try {
in = u.openStream();
r = new BufferedReader(new InputStreamReader(in, "utf-8"));
int lc = 1;
while ((lc = parseLine(service, u, r, lc, names)) >= 0) ;
} catch (IOException x) {
fail(service, "Error reading configuration file", x);
} finally {
try {
if (r != null) r.close();
if (in != null) in.close();
} catch (IOException y) {
fail(service, "Error closing configuration file", y);
}
}
return names.iterator();
}
private class LazyIterator implements Iterator<Class<S>> {
final Class<? super S> service;
final Loader loader;
Iterator<URL> configs = null;
Iterator<String> pending = null;
String nextName = null;
private LazyIterator(Class<? super S> service, Loader loader) {
this.service = service;
this.loader = loader;
}
public boolean hasNext() {
if (nextName != null) {
return true;
}
if (configs == null) {
String fullName = PREFIX + service.getName();
configs = loader.getResources(fullName).iterator();
}
while ((pending == null) || !pending.hasNext()) {
if (!configs.hasNext()) {
return false;
}
pending = parse(service, configs.next());
}
nextName = pending.next();
return true;
}
@SuppressWarnings({"unchecked"})
public Class<S> next() {
if (!hasNext())
throw new NoSuchElementException();
String cn = nextName;
nextName = null;
try {
Class<S> p = (Class<S>) loader.loadClass(cn);
providers.put(cn, p);
return p;
} catch (RuntimeException x) {
fail(service,
"Provider " + cn + " could not be instantiated: " + x,
x);
}
throw new Error(); // This cannot happen
}
public void remove() {
throw new UnsupportedOperationException();
}
}
public Iterator<Class<S>> iterator() {
return new Iterator<Class<S>>() {
Iterator<Map.Entry<String, Class<S>>> knownProviders = providers.entrySet().iterator();
public boolean hasNext() {
return knownProviders.hasNext() || lookupIterator.hasNext();
}
public Class<S> next() {
if (knownProviders.hasNext())
return knownProviders.next().getValue();
return lookupIterator.next();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public static <S> ServiceClassLoader<S> load(Class<S> service, Loader loader) {
return new ServiceClassLoader<S>(service, loader);
}
public static <S> ServiceClassLoader<S> load(Class<S> service) {
return new ServiceClassLoader<S>(service, new DefaultLoader());
}
public String toString() {
return "ServiceClassLoader[" + service.getName() + "]";
}
}
|
// RobotBuilder Version: 2.0
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc3853.CompetitionRobot20160120.commands;
import edu.wpi.first.wpilibj.command.Command;
/**
*
*/
public class AutonomousCommand extends Command {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_DECLARATIONS
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_DECLARATIONS
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR
public AutonomousCommand() {
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_SETTING
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_SETTING
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
}
// Called just before this Command runs the first time
@Override
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
@Override
protected void execute() {
}
// Make this return true when this Command no longer needs to run execute()
@Override
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
@Override
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
@Override
protected void interrupted() {
}
}
|
package io.microvibe.booster.core.base.mybatis.annotation;
import io.microvibe.booster.core.base.mybatis.statement.BuilderType;
import java.lang.annotation.*;
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface AutoStatement {
BuilderType value() default BuilderType.NOOP;
}
|
package de.metanome.validation;
import de.metanome.algorithm_integration.algorithm_types.ListBoxParameterAlgorithm;
public interface InclusionDependencyValidationAlgorithm extends ListBoxParameterAlgorithm {
}
|
/**
* Copyright (C) 2015 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 io.fabric8.kubernetes.client.dsl;
import io.fabric8.kubernetes.api.model.v1.Scale;
public interface Scaleable<T> {
int POLL_INTERVAL_MS = 100;
T scale(int count);
T scale(int count, boolean wait);
Scale scale();
Scale scale(Scale scale);
}
|
package com.app.api.product;
import io.swagger.annotations.*;
//import springfox.documentation.annotations.*;
import javax.servlet.http.*;
import org.springframework.http.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.data.domain.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
//import static org.springframework.http.MediaType.*;
import org.springframework.dao.DataIntegrityViolationException;
import java.util.*;
import java.util.stream.Collectors;
import java.lang.*;
import com.app.api.*;
import com.app.model.product.*;
import com.app.repo.*;
import com.app.services.StorageService;
import com.app.model.response.*;
import static com.app.model.response.OperationResponse.*;
@RestController
@RequestMapping(value = "/api", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(tags = {"Products"})
public class ProductController {
@Autowired private JdbcTemplate jdbcTemplate;
@Autowired private ProductRepo productRepo;
@Autowired
StorageService storageService;
List<String> files = new ArrayList<String>();
@ApiOperation(value = "List of products", response = ProductResponse.class)
@RequestMapping(value = "/products", method = RequestMethod.GET)
public ProductResponse getProductsByPage(
@ApiParam(value = "" ) @RequestParam(value = "page" , defaultValue="0" , required = false) Integer page,
@ApiParam(value = "between 1 to 1000" ) @RequestParam(value = "size" , defaultValue="20" , required = false) Integer size,
@RequestParam(value = "productid" , required = false) Integer productId,
@RequestParam(value = "category" , required = false) String category,
Pageable pageable
) {
ProductResponse resp = new ProductResponse();
Product qry = new Product();
if (productId != null) { qry.setId(productId); }
if (category != null) { qry.setCategory(category); }
Page<Product> productPage = productRepo.findAll(org.springframework.data.domain.Example.of(qry), pageable);
resp.setPageStats(productPage, true);
resp.setItems(productPage.getContent());
return resp;
}
@ApiOperation(value = "Add new product", response = OperationResponse.class)
@RequestMapping(value = "/products", method = RequestMethod.POST, produces = {"application/json"})
public OperationResponse addNewProduct(@RequestBody Product product, HttpServletRequest req) {
OperationResponse resp = new OperationResponse();
if (this.productRepo.exists(product.getId()) ){
resp.setOperationStatus(ResponseStatusEnum.ERROR);
resp.setOperationMessage("Unable to add Product - Product allready exist ");
}
else{
//Product addedProduct = this.productRepo.save(product);
this.productRepo.save(product);
resp.setOperationStatus(ResponseStatusEnum.SUCCESS);
resp.setOperationMessage("Product Added");
}
return resp;
}
@ApiOperation(value = "Delete a product", response = OperationResponse.class)
@RequestMapping(value = "/products/{productId}", method = RequestMethod.DELETE, produces = {"application/json"})
public OperationResponse deleteProduct(@PathVariable("productId") Integer productId, HttpServletRequest req) {
OperationResponse resp = new OperationResponse();
if (this.productRepo.exists(productId) ){
this.productRepo.delete(productId);
resp.setOperationStatus(ResponseStatusEnum.SUCCESS);
resp.setOperationMessage("Product Deleted");
}
else{
resp.setOperationStatus(ResponseStatusEnum.ERROR);
resp.setOperationMessage("No Product Exist");
}
return resp;
}
@PostMapping("/product/uploadFile")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
String message = "";
try {
storageService.store(file);
files.add(file.getOriginalFilename());
message = "You successfully uploaded " + file.getOriginalFilename() + "!";
return ResponseEntity.status(HttpStatus.OK).body(message);
} catch (Exception e) {
message = "FAIL to upload " + file.getOriginalFilename() + "!" + e;
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(message);
}
}
@GetMapping("/product/getallfiles")
public ResponseEntity<List<String>> getListFiles(Model model) {
return ResponseEntity.ok().body(files);
}
@ApiOperation(value = "File", response = ResponseEntity.class)
@RequestMapping(value = "/product/files", method = RequestMethod.GET)
public ResponseEntity<Resource> getFile(
@RequestParam(value = "filename" , required = true) String filename
)
{
System.out.println(filename);
Resource file = storageService.loadFile(filename);
System.out.println(file);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
.body(file);
}
}
|
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2;
import static com.google.common.truth.Truth.assertThat;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.google.android.exoplayer2.DefaultLoadControl.Builder;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.upstream.DefaultAllocator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/** Unit tests for {@link DefaultLoadControl}. */
@RunWith(AndroidJUnit4.class)
public class DefaultLoadControlTest {
private static final float SPEED = 1f;
private static final long MAX_BUFFER_US = C.msToUs(DefaultLoadControl.DEFAULT_MAX_BUFFER_MS);
private static final long MIN_BUFFER_US = MAX_BUFFER_US / 2;
private static final int TARGET_BUFFER_BYTES = C.DEFAULT_BUFFER_SEGMENT_SIZE * 2;
private Builder builder;
private DefaultAllocator allocator;
private DefaultLoadControl loadControl;
@Before
public void setUp() throws Exception {
builder = new Builder();
allocator = new DefaultAllocator(true, C.DEFAULT_BUFFER_SEGMENT_SIZE);
}
@Test
public void shouldContinueLoading_untilMaxBufferExceeded() {
createDefaultLoadControl();
assertThat(
loadControl.shouldContinueLoading(
/* playbackPositionUs= */ 0, /* bufferedDurationUs= */ 0, SPEED))
.isTrue();
assertThat(
loadControl.shouldContinueLoading(
/* playbackPositionUs= */ 0, MAX_BUFFER_US - 1, SPEED))
.isTrue();
assertThat(loadControl.shouldContinueLoading(/* playbackPositionUs= */ 0, MAX_BUFFER_US, SPEED))
.isFalse();
}
@Test
public void shouldNotContinueLoadingOnceBufferingStopped_untilBelowMinBuffer() {
builder.setBufferDurationsMs(
/* minBufferMs= */ (int) C.usToMs(MIN_BUFFER_US),
/* maxBufferMs= */ (int) C.usToMs(MAX_BUFFER_US),
/* bufferForPlaybackMs= */ 0,
/* bufferForPlaybackAfterRebufferMs= */ 0);
createDefaultLoadControl();
assertThat(loadControl.shouldContinueLoading(/* playbackPositionUs= */ 0, MAX_BUFFER_US, SPEED))
.isFalse();
assertThat(
loadControl.shouldContinueLoading(
/* playbackPositionUs= */ 0, MAX_BUFFER_US - 1, SPEED))
.isFalse();
assertThat(loadControl.shouldContinueLoading(/* playbackPositionUs= */ 0, MIN_BUFFER_US, SPEED))
.isFalse();
assertThat(
loadControl.shouldContinueLoading(
/* playbackPositionUs= */ 0, MIN_BUFFER_US - 1, SPEED))
.isTrue();
}
@Test
public void continueLoadingOnceBufferingStopped_andBufferAlmostEmpty_evenIfMinBufferNotReached() {
builder.setBufferDurationsMs(
/* minBufferMs= */ 0,
/* maxBufferMs= */ (int) C.usToMs(MAX_BUFFER_US),
/* bufferForPlaybackMs= */ 0,
/* bufferForPlaybackAfterRebufferMs= */ 0);
createDefaultLoadControl();
assertThat(loadControl.shouldContinueLoading(/* playbackPositionUs= */ 0, MAX_BUFFER_US, SPEED))
.isFalse();
assertThat(
loadControl.shouldContinueLoading(
/* playbackPositionUs= */ 0, 5 * C.MICROS_PER_SECOND, SPEED))
.isFalse();
assertThat(loadControl.shouldContinueLoading(/* playbackPositionUs= */ 0, 500L, SPEED))
.isTrue();
}
@Test
public void shouldContinueLoadingWithTargetBufferBytesReached_untilMinBufferReached() {
builder.setPrioritizeTimeOverSizeThresholds(true);
builder.setBufferDurationsMs(
/* minBufferMs= */ (int) C.usToMs(MIN_BUFFER_US),
/* maxBufferMs= */ (int) C.usToMs(MAX_BUFFER_US),
/* bufferForPlaybackMs= */ 0,
/* bufferForPlaybackAfterRebufferMs= */ 0);
createDefaultLoadControl();
makeSureTargetBufferBytesReached();
assertThat(
loadControl.shouldContinueLoading(
/* playbackPositionUs= */ 0, /* bufferedDurationUs= */ 0, SPEED))
.isTrue();
assertThat(
loadControl.shouldContinueLoading(
/* playbackPositionUs= */ 0, MIN_BUFFER_US - 1, SPEED))
.isTrue();
assertThat(loadControl.shouldContinueLoading(/* playbackPositionUs= */ 0, MIN_BUFFER_US, SPEED))
.isFalse();
assertThat(loadControl.shouldContinueLoading(/* playbackPositionUs= */ 0, MAX_BUFFER_US, SPEED))
.isFalse();
}
@Test
public void
shouldContinueLoading_withTargetBufferBytesReachedAndNotPrioritizeTimeOverSize_returnsTrueAsSoonAsTargetBufferReached() {
builder.setPrioritizeTimeOverSizeThresholds(false);
createDefaultLoadControl();
// Put loadControl in buffering state.
assertThat(
loadControl.shouldContinueLoading(
/* playbackPositionUs= */ 0, /* bufferedDurationUs= */ 0, SPEED))
.isTrue();
makeSureTargetBufferBytesReached();
assertThat(
loadControl.shouldContinueLoading(
/* playbackPositionUs= */ 0, /* bufferedDurationUs= */ 0, SPEED))
.isFalse();
assertThat(
loadControl.shouldContinueLoading(
/* playbackPositionUs= */ 0, MIN_BUFFER_US - 1, SPEED))
.isFalse();
assertThat(loadControl.shouldContinueLoading(/* playbackPositionUs= */ 0, MIN_BUFFER_US, SPEED))
.isFalse();
assertThat(loadControl.shouldContinueLoading(/* playbackPositionUs= */ 0, MAX_BUFFER_US, SPEED))
.isFalse();
}
@Test
public void shouldContinueLoadingWithMinBufferReached_inFastPlayback() {
builder.setBufferDurationsMs(
/* minBufferMs= */ (int) C.usToMs(MIN_BUFFER_US),
/* maxBufferMs= */ (int) C.usToMs(MAX_BUFFER_US),
/* bufferForPlaybackMs= */ 0,
/* bufferForPlaybackAfterRebufferMs= */ 0);
createDefaultLoadControl();
// At normal playback speed, we stop buffering when the buffer reaches the minimum.
assertThat(loadControl.shouldContinueLoading(/* playbackPositionUs= */ 0, MIN_BUFFER_US, SPEED))
.isFalse();
// At double playback speed, we continue loading.
assertThat(
loadControl.shouldContinueLoading(
/* playbackPositionUs= */ 0, MIN_BUFFER_US, /* playbackSpeed= */ 2f))
.isTrue();
}
@Test
public void shouldNotContinueLoadingWithMaxBufferReached_inFastPlayback() {
createDefaultLoadControl();
assertThat(
loadControl.shouldContinueLoading(
/* playbackPositionUs= */ 0, MAX_BUFFER_US, /* playbackSpeed= */ 100f))
.isFalse();
}
@Test
public void startsPlayback_whenMinBufferSizeReached() {
createDefaultLoadControl();
assertThat(loadControl.shouldStartPlayback(MIN_BUFFER_US, SPEED, /* rebuffering= */ false))
.isTrue();
}
@Test
public void shouldContinueLoading_withNoSelectedTracks_returnsTrue() {
loadControl = builder.createDefaultLoadControl();
loadControl.onTracksSelected(new Renderer[0], TrackGroupArray.EMPTY, new TrackSelectionArray());
assertThat(
loadControl.shouldContinueLoading(
/* playbackPositionUs= */ 0, /* bufferedDurationUs= */ 0, /* playbackSpeed= */ 1f))
.isTrue();
}
private void createDefaultLoadControl() {
builder.setAllocator(allocator).setTargetBufferBytes(TARGET_BUFFER_BYTES);
loadControl = builder.createDefaultLoadControl();
loadControl.onTracksSelected(new Renderer[0], null, null);
}
private void makeSureTargetBufferBytesReached() {
while (allocator.getTotalBytesAllocated() < TARGET_BUFFER_BYTES) {
allocator.allocate();
}
}
}
|
package p3d4amb.sat.lib.session;
public abstract class DepthCertBase {
/**
* The enum Solution
*/
public enum Solution {
/** The right */
RIGHT,
/** The wrong */
WRONG,
/** The null */
NULL
}
/** The certifier status */
protected CertifierStatus certifierStatus;
/**
* The class CertifierStatus
*/
static public class CertifierStatus {
/** The current depth */
public int currentDepth;
/** The current result */
public TestSession.Result currentResult;
@Override
public String toString() {
switch (currentResult) {
case FINISH_CERTIFIED:
return "CERTIFICATE at level: " + currentDepth;
case FINISH_NOT_CERTIFIED:
return "FINISHED but NOT CERTIFIED until level: " + currentDepth;
case CONTINUE:
return "NOT COMPLETED (Testing " + currentDepth + ")";
}
return "";
}
}
/**
* Get current depth
*
* @return the current depth
*/
public int getCurrentDepth() {
return certifierStatus.currentDepth;
}
abstract void computeNextDepth(Solution sol);
/**
* Get current status
*
* @return
*/
abstract public CertifierStatus getCurrentStatus();
}
|
/*
* Copyright 1999-2019 Seata.io Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.seata.sqlparser.druid.mysql;
import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlOutputVisitor;
import io.seata.common.util.StringUtils;
import io.seata.sqlparser.ParametersHolder;
import io.seata.sqlparser.druid.BaseRecognizer;
import io.seata.sqlparser.struct.Null;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* @author will
*/
public abstract class BaseMySQLRecognizer extends BaseRecognizer {
/**
* Instantiates a new mysql base recognizer
*
* @param originalSql the original sql
*/
public BaseMySQLRecognizer(String originalSql) {
super(originalSql);
}
public MySqlOutputVisitor createOutputVisitor(final ParametersHolder parametersHolder,
final ArrayList<List<Object>> paramAppenderList,
final StringBuilder sb) {
return new MySqlOutputVisitor(sb) {
@Override
public boolean visit(SQLVariantRefExpr x) {
if ("?".equals(x.getName())) {
ArrayList<Object> oneParamValues = parametersHolder.getParameters()[x.getIndex()];
if (paramAppenderList.isEmpty()) {
oneParamValues.forEach(t -> paramAppenderList.add(new ArrayList<>()));
}
for (int i = 0; i < oneParamValues.size(); i++) {
Object o = oneParamValues.get(i);
paramAppenderList.get(i).add(o instanceof Null ? null : o);
}
}
return super.visit(x);
}
};
}
public String getWhereCondition(SQLExpr where, final ParametersHolder parametersHolder,
final ArrayList<List<Object>> paramAppenderList) {
if (Objects.isNull(where)) {
return StringUtils.EMPTY;
}
StringBuilder sb = new StringBuilder();
executeVisit(where, createOutputVisitor(parametersHolder, paramAppenderList, sb));
return sb.toString();
}
public String getWhereCondition(SQLExpr where) {
if (Objects.isNull(where)) {
return StringUtils.EMPTY;
}
StringBuilder sb = new StringBuilder();
executeVisit(where, new MySqlOutputVisitor(sb));
return sb.toString();
}
}
|
package org.tron.core.db.common.iterator;
import java.io.Closeable;
import java.util.Iterator;
import java.util.Map.Entry;
public interface DBIterator extends Iterator<Entry<byte[], byte[]>>, Closeable {
}
|
/*
* 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.
*/
/**
* @author Vera Y. Petrashkova
* @version $Revision$
*/
package org.apache.harmony.security.tests.java.security;
import java.math.BigInteger;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidParameterException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import org.apache.harmony.security.tests.support.MyKeyPairGenerator1;
import org.apache.harmony.security.tests.support.MyKeyPairGenerator2;
import org.apache.harmony.security.tests.support.SpiEngUtils;
import junit.framework.TestCase;
/**
* Tests for <code>KeyPairGenerator</code> class constructors and methods.
*
*/
public class KeyPairGenerator1Test extends TestCase {
private static String[] invalidValues = SpiEngUtils.invalidValues;
public static final String srvKeyPairGenerator = "KeyPairGenerator";
public static String[] algs = {
"DSA", "dsa", "Dsa", "DsA", "dsA" };
public static String validAlgName = "DSA";
private static String validProviderName = null;
public static Provider validProvider = null;
private static boolean DSASupported = false;
public static String NotSupportMsg = "";
static {
validProvider = SpiEngUtils.isSupport(
validAlgName,
srvKeyPairGenerator);
DSASupported = (validProvider != null);
if (!DSASupported) {
NotSupportMsg = validAlgName + " algorithm is not supported" ;
}
validProviderName = (DSASupported ? validProvider.getName() : null);
}
protected KeyPairGenerator [] createKPGen() {
if (!DSASupported) {
fail(NotSupportMsg);
return null;
}
KeyPairGenerator[] kpg = new KeyPairGenerator[3];
try {
kpg[0] = KeyPairGenerator.getInstance(validAlgName);
kpg[1] = KeyPairGenerator.getInstance(validAlgName, validProvider);
kpg[2] = KeyPairGenerator.getInstance(validAlgName, validProviderName);
return kpg;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Test for <code>getInstance(String algorithm)</code> method
* Assertion:
* throws NullPointerException when algorithm is null
* throws NoSuchAlgorithmException when algorithm is incorrect;
*/
public void testKeyPairGenerator01() throws NoSuchAlgorithmException {
try {
KeyPairGenerator.getInstance(null);
fail("NullPointerException or NoSuchAlgorithmException must be thrown when algorithm is null");
} catch (NoSuchAlgorithmException e) {
} catch (NullPointerException e) {
}
for (int i = 0; i < invalidValues.length; i++) {
try {
KeyPairGenerator.getInstance(invalidValues[i]);
fail("NoSuchAlgorithmException must be thrown when algorithm is not available: "
.concat(invalidValues[i]));
} catch (NoSuchAlgorithmException e) {
}
}
}
/**
* Test for <code>getInstance(String algorithm)</code> method
* Assertion: returns KeyPairGenerator object
*/
public void testKeyPairGenerator02() throws NoSuchAlgorithmException {
if (!DSASupported) {
fail(NotSupportMsg);
return;
}
KeyPairGenerator kpg;
for (int i = 0; i < algs.length; i++) {
kpg = KeyPairGenerator.getInstance(algs[i]);
assertEquals("Incorrect algorithm ", kpg.getAlgorithm().toUpperCase(),
algs[i].toUpperCase());
}
}
/**
* Test for <code>getInstance(String algorithm, String provider)</code>
* method
* Assertion: throws IllegalArgumentException when provider is null or empty
*/
public void testKeyPairGenerator03() throws NoSuchAlgorithmException,
NoSuchProviderException {
if (!DSASupported) {
fail(NotSupportMsg);
return;
}
String provider = null;
for (int i = 0; i < algs.length; i++) {
try {
KeyPairGenerator.getInstance(algs[i], provider);
fail("IllegalArgumentException must be thrown when provider is null");
} catch (IllegalArgumentException e) {
}
try {
KeyPairGenerator.getInstance(algs[i], "");
fail("IllegalArgumentException must be thrown when provider is empty");
} catch (IllegalArgumentException e) {
}
}
}
/**
* Test for <code>getInstance(String algorithm, String provider)</code>
* method
* Assertion:
* throws NoSuchProviderException when provider is not available
*/
public void testKeyPairGenerator04() throws NoSuchAlgorithmException,
IllegalArgumentException {
if (!DSASupported) {
fail(NotSupportMsg);
return;
}
for (int i = 0; i < algs.length; i++) {
for (int j = 1; j < invalidValues.length; j++) {
try {
KeyPairGenerator.getInstance(algs[i], invalidValues[j]);
fail("NoSuchProviderException must be thrown (algorithm: "
.concat(algs[i]).concat(" provider: ").concat(
invalidValues[j]).concat(")"));
} catch (NoSuchProviderException e) {
}
}
}
}
/**
* Test for <code>getInstance(String algorithm, String provider)</code>
* method
* Assertion: throws NoSuchAlgorithmException when algorithm is not
* available
* throws NullPointerException when algorithm is null
* throws NoSuchAlgorithmException when algorithm is incorrect;
*/
public void testKeyPairGenerator05() throws NoSuchProviderException,
IllegalArgumentException {
if (!DSASupported) {
fail(NotSupportMsg);
return;
}
try {
KeyPairGenerator.getInstance(null, validProviderName);
fail("NullPointerException or NoSuchAlgorithmException must be thrown when algorithm is null");
} catch (NoSuchAlgorithmException e) {
} catch (NullPointerException e) {
}
for (int i = 0; i < invalidValues.length; i++) {
try {
KeyPairGenerator.getInstance(invalidValues[i],
validProviderName);
fail("NoSuchAlgorithmException must be thrown (algorithm: "
.concat(algs[i]).concat(" provider: ").concat(
validProviderName).concat(")"));
} catch (NoSuchAlgorithmException e) {
}
}
}
/**
* Test for <code>getInstance(String algorithm, String provider)</code>
* method
* Assertion: returns KeyPairGenerator object
*/
public void testKeyPairGenerator06() throws NoSuchProviderException,
NoSuchAlgorithmException, IllegalArgumentException {
if (!DSASupported) {
fail(NotSupportMsg);
return;
}
KeyPairGenerator kpg;
for (int i = 0; i < algs.length; i++) {
kpg = KeyPairGenerator.getInstance(algs[i], validProviderName);
assertEquals("Incorrect algorithm", kpg.getAlgorithm().toUpperCase(),
algs[i].toUpperCase());
assertEquals("Incorrect provider", kpg.getProvider().getName(),
validProviderName);
}
}
/**
* Test for <code>getInstance(String algorithm, Provider provider)</code>
* method
* Assertion: throws IllegalArgumentException when provider is null
*/
public void testKeyPairGenerator07() throws NoSuchAlgorithmException {
if (!DSASupported) {
fail(NotSupportMsg);
return;
}
Provider provider = null;
for (int i = 0; i < algs.length; i++) {
try {
KeyPairGenerator.getInstance(algs[i], provider);
fail("IllegalArgumentException must be thrown when provider is null");
} catch (IllegalArgumentException e) {
}
}
}
/**
* Test for <code>getInstance(String algorithm, Provider provider)</code>
* method
* Assertion:
* throws NullPointerException when algorithm is null
* throws NoSuchAlgorithmException when algorithm is incorrect;
*/
public void testKeyPairGenerator08() throws IllegalArgumentException {
if (!DSASupported) {
fail(NotSupportMsg);
return;
}
try {
KeyPairGenerator.getInstance(null, validProvider);
fail("NullPointerException or NoSuchAlgorithmException must be thrown when algorithm is null");
} catch (NoSuchAlgorithmException e) {
} catch (NullPointerException e) {
}
for (int i = 0; i < invalidValues.length; i++) {
try {
KeyPairGenerator.getInstance(invalidValues[i], validProvider);
fail("NoSuchAlgorithmException must be thrown (algorithm: "
.concat(algs[i]).concat(" provider: ").concat(
validProviderName).concat(")"));
} catch (NoSuchAlgorithmException e) {
}
}
}
/**
* Test for <code>getInstance(String algorithm, Provider provider)</code>
* method
* Assertion: returns KeyPairGenerator object
*/
public void testKeyPairGenerator09() throws NoSuchAlgorithmException,
IllegalArgumentException {
if (!DSASupported) {
fail(NotSupportMsg);
return;
}
KeyPairGenerator kpg;
for (int i = 0; i < algs.length; i++) {
kpg = KeyPairGenerator.getInstance(algs[i], validProvider);
assertEquals("Incorrect algorithm", kpg.getAlgorithm().toUpperCase(),
algs[i].toUpperCase());
assertEquals("Incorrect provider", kpg.getProvider(), validProvider);
}
}
/**
* Test for <code>generateKeyPair()</code> and <code>genKeyPair()</code>
* methods
* Assertion: KeyPairGenerator was initialized before the invocation
* of these methods
*/
public void testKeyPairGenerator10() throws NoSuchAlgorithmException,
NoSuchProviderException, IllegalArgumentException {
if (!DSASupported) {
fail(NotSupportMsg);
return;
}
KeyPairGenerator[] kpg = createKPGen();
assertNotNull("KeyPairGenerator objects were not created", kpg);
KeyPair kp, kp1;
for (int i = 0; i < kpg.length; i++) {
kpg[i].initialize(512);
kp = kpg[i].generateKeyPair();
kp1 = kpg[i].genKeyPair();
assertFalse("Incorrect private key", kp.getPrivate().equals(
kp1.getPrivate()));
assertFalse("Incorrect public key", kp.getPublic().equals(
kp1.getPublic()));
}
}
/**
* Test for methods:
* <code>initialize(int keysize)</code>
* <code>initialize(int keysize, SecureRandom random)</code>
* <code>initialize(AlgorithmParameterSpec param)</code>
* <code>initialize(AlgorithmParameterSpec param, SecureRandom random)</code>
* Assertion: throws InvalidParameterException or
* InvalidAlgorithmParameterException when parameters keysize or param are
* incorrect
*/
public void testKeyPairGenerator11() throws NoSuchAlgorithmException,
NoSuchProviderException {
if (!DSASupported) {
fail(NotSupportMsg);
return;
}
int[] keys = { -10000, -1024, -1, 0, 10000 };
KeyPairGenerator[] kpg = createKPGen();
assertNotNull("KeyPairGenerator objects were not created", kpg);
SecureRandom random = new SecureRandom();
AlgorithmParameterSpec aps = null;
for (int i = 0; i < kpg.length; i++) {
for (int j = 0; j < keys.length; j++) {
try {
kpg[i].initialize(keys[j]);
kpg[i].initialize(keys[j], random);
} catch (InvalidParameterException e) {
}
}
try {
kpg[i].initialize(aps);
kpg[i].initialize(aps, random);
} catch (InvalidAlgorithmParameterException e) {
}
}
}
/**
* Test for methods: <code>initialize(int keysize)</code>
* <code>initialize(int keysize, SecureRandom random)</code>
* <code>initialize(AlgorithmParameterSpec param)</code>
* <code>initialize(AlgorithmParameterSpec param, SecureRandom random)</code>
* <code>generateKeyPair()</code>
* <code>genKeyPair()</code>
* Assertion: throws InvalidParameterException or
* InvalidAlgorithmParameterException when parameters keysize or param are
* incorrect Assertion: generateKeyPair() and genKeyPair() return null
* KeyPair Additional class MyKeyPairGenerator1 is used
*/
public void testKeyPairGenerator12() {
int[] keys = { -1, -250, 1, 64, 512, 1024 };
SecureRandom random = new SecureRandom();
AlgorithmParameterSpec aps;
KeyPairGenerator mKPG = new MyKeyPairGenerator1("");
assertEquals("Incorrect algorithm", mKPG.getAlgorithm(),
MyKeyPairGenerator1.getResAlgorithm());
mKPG.generateKeyPair();
mKPG.genKeyPair();
for (int i = 0; i < keys.length; i++) {
try {
mKPG.initialize(keys[i]);
fail("InvalidParameterException must be thrown (key: "
+ Integer.toString(keys[i]) + ")");
} catch (InvalidParameterException e) {
}
try {
mKPG.initialize(keys[i], random);
fail("InvalidParameterException must be thrown (key: "
+ Integer.toString(keys[i]) + ")");
} catch (InvalidParameterException e) {
}
}
try {
mKPG.initialize(100, null);
fail("InvalidParameterException must be thrown when random is null");
} catch (InvalidParameterException e) {
}
mKPG.initialize(100, random);
assertEquals("Incorrect random", random,
((MyKeyPairGenerator1) mKPG).secureRandom);
assertEquals("Incorrect keysize", 100,
((MyKeyPairGenerator1) mKPG).keySize);
try {
mKPG.initialize(null, random);
fail("InvalidAlgorithmParameterException must be thrown when param is null");
} catch (InvalidAlgorithmParameterException e) {
}
if (DSASupported) {
BigInteger bInt = new BigInteger("1");
aps = new java.security.spec.DSAParameterSpec(bInt, bInt, bInt);
try {
mKPG.initialize(aps, null);
fail("InvalidParameterException must be thrown when random is null");
} catch (InvalidParameterException e) {
} catch (InvalidAlgorithmParameterException e) {
fail("Unexpected InvalidAlgorithmParameterException was thrown");
}
try {
mKPG.initialize(aps, random);
assertEquals("Incorrect random", random,
((MyKeyPairGenerator1) mKPG).secureRandom);
assertEquals("Incorrect params", aps,
((MyKeyPairGenerator1) mKPG).paramSpec);
} catch (InvalidAlgorithmParameterException e) {
fail("Unexpected InvalidAlgorithmParameterException was thrown");
}
}
}
/**
* Test for methods: <code>initialize(int keysize)</code>
* <code>initialize(int keysize, SecureRandom random)</code>
* <code>initialize(AlgorithmParameterSpec param)</code>
* <code>initialize(AlgorithmParameterSpec param, SecureRandom random)</code>
* <code>generateKeyPair()</code>
* <code>genKeyPair()</code>
* Assertion: initialize(int ...) throws InvalidParameterException when
* keysize in incorrect Assertion: initialize(AlgorithmParameterSpec
* ...)throws UnsupportedOperationException Assertion: generateKeyPair() and
* genKeyPair() return not null KeyPair Additional class MyKeyPairGenerator2
* is used
*/
public void testKeyPairGenerator13() {
int[] keys = { -1, -250, 1, 63, -512, -1024 };
SecureRandom random = new SecureRandom();
KeyPairGenerator mKPG = new MyKeyPairGenerator2(null);
assertEquals("Algorithm must be null", mKPG.getAlgorithm(),
MyKeyPairGenerator2.getResAlgorithm());
assertNull("genKeyPair() must return null", mKPG.genKeyPair());
assertNull("generateKeyPair() mut return null", mKPG.generateKeyPair());
for (int i = 0; i < keys.length; i++) {
try {
mKPG.initialize(keys[i]);
fail("InvalidParameterException must be thrown (key: "
+ Integer.toString(keys[i]) + ")");
} catch (InvalidParameterException e) {
}
try {
mKPG.initialize(keys[i], random);
fail("InvalidParameterException must be thrown (key: "
+ Integer.toString(keys[i]) + ")");
} catch (InvalidParameterException e) {
}
}
try {
mKPG.initialize(64);
} catch (InvalidParameterException e) {
fail("Unexpected InvalidParameterException was thrown");
}
try {
mKPG.initialize(64, null);
} catch (InvalidParameterException e) {
fail("Unexpected InvalidParameterException was thrown");
}
try {
mKPG.initialize(null, random);
} catch (UnsupportedOperationException e) {
// on j2se1.4 this exception is not thrown
} catch (InvalidAlgorithmParameterException e) {
fail("Unexpected InvalidAlgorithmParameterException was thrown");
}
}
}
|
package com.atguigu.gulimall.product;
import com.atguigu.gulimall.product.entity.BrandEntity;
import com.atguigu.gulimall.product.service.BrandService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class GulimallProductApplicationTests {
@Autowired
BrandService brandService;
@Test
void contextLoads() {
BrandEntity brandEntity = new BrandEntity();
brandEntity.setName("华为");
brandService.save(brandEntity);
System.out.println("保存成功");
}
}
|
/*
* This file is generated by jOOQ.
*/
package ru.inovus.messaging.impl.jooq.tables.records;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record2;
import org.jooq.Row2;
import org.jooq.impl.UpdatableRecordImpl;
import ru.inovus.messaging.impl.jooq.tables.Tenant;
/**
* Тенанты
*/
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class TenantRecord extends UpdatableRecordImpl<TenantRecord> implements Record2<String, String> {
private static final long serialVersionUID = 1778893056;
/**
* Setter for <code>messaging.tenant.code</code>. Уникальный код тенанта
*/
public void setCode(String value) {
set(0, value);
}
/**
* Getter for <code>messaging.tenant.code</code>. Уникальный код тенанта
*/
public String getCode() {
return (String) get(0);
}
/**
* Setter for <code>messaging.tenant.name</code>. Наименование тенанта
*/
public void setName(String value) {
set(1, value);
}
/**
* Getter for <code>messaging.tenant.name</code>. Наименование тенанта
*/
public String getName() {
return (String) get(1);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
@Override
public Record1<String> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record2 type implementation
// -------------------------------------------------------------------------
@Override
public Row2<String, String> fieldsRow() {
return (Row2) super.fieldsRow();
}
@Override
public Row2<String, String> valuesRow() {
return (Row2) super.valuesRow();
}
@Override
public Field<String> field1() {
return Tenant.TENANT.CODE;
}
@Override
public Field<String> field2() {
return Tenant.TENANT.NAME;
}
@Override
public String component1() {
return getCode();
}
@Override
public String component2() {
return getName();
}
@Override
public String value1() {
return getCode();
}
@Override
public String value2() {
return getName();
}
@Override
public TenantRecord value1(String value) {
setCode(value);
return this;
}
@Override
public TenantRecord value2(String value) {
setName(value);
return this;
}
@Override
public TenantRecord values(String value1, String value2) {
value1(value1);
value2(value2);
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached TenantRecord
*/
public TenantRecord() {
super(Tenant.TENANT);
}
/**
* Create a detached, initialised TenantRecord
*/
public TenantRecord(String code, String name) {
super(Tenant.TENANT);
set(0, code);
set(1, name);
}
}
|
/*
* 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.solr.handler;
import java.io.Closeable;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.request.AbstractUpdateRequest;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.cloud.ZkController;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.cloud.ClusterState;
import org.apache.solr.common.cloud.Slice;
import org.apache.solr.common.cloud.ZkCoreNodeProps;
import org.apache.solr.common.cloud.ZkNodeProps;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.params.UpdateParams;
import org.apache.solr.common.util.ExecutorUtil;
import org.apache.solr.common.util.IOUtils;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.core.CloseHook;
import org.apache.solr.core.PluginBag;
import org.apache.solr.core.SolrCore;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrRequestHandler;
import org.apache.solr.request.SolrRequestInfo;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.update.CdcrUpdateLog;
import org.apache.solr.update.UpdateLog;
import org.apache.solr.update.VersionInfo;
import org.apache.solr.update.processor.DistributedUpdateProcessor;
import org.apache.solr.util.DefaultSolrThreadFactory;
import org.apache.solr.util.plugin.SolrCoreAware;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.solr.handler.admin.CoreAdminHandler.COMPLETED;
import static org.apache.solr.handler.admin.CoreAdminHandler.FAILED;
import static org.apache.solr.handler.admin.CoreAdminHandler.RESPONSE;
import static org.apache.solr.handler.admin.CoreAdminHandler.RESPONSE_MESSAGE;
import static org.apache.solr.handler.admin.CoreAdminHandler.RESPONSE_STATUS;
import static org.apache.solr.handler.admin.CoreAdminHandler.RUNNING;
/**
* <p>
* This request handler implements the CDCR API and is responsible of the execution of the
* {@link CdcrReplicator} threads.
* </p>
* <p>
* It relies on three classes, {@link org.apache.solr.handler.CdcrLeaderStateManager},
* {@link org.apache.solr.handler.CdcrBufferStateManager} and {@link org.apache.solr.handler.CdcrProcessStateManager}
* to synchronise the state of the CDCR across all the nodes.
* </p>
* <p>
* The CDCR process can be either {@link org.apache.solr.handler.CdcrParams.ProcessState#STOPPED} or {@link org.apache.solr.handler.CdcrParams.ProcessState#STARTED} by using the
* actions {@link org.apache.solr.handler.CdcrParams.CdcrAction#STOP} and {@link org.apache.solr.handler.CdcrParams.CdcrAction#START} respectively. If a node is leader and the process
* state is {@link org.apache.solr.handler.CdcrParams.ProcessState#STARTED}, the {@link CdcrReplicatorManager} will
* start the {@link CdcrReplicator} threads. If a node becomes non-leader or if the process state becomes
* {@link org.apache.solr.handler.CdcrParams.ProcessState#STOPPED}, the {@link CdcrReplicator} threads are stopped.
* </p>
* <p>
* The CDCR can be switched to a "buffering" mode, in which the update log will never delete old transaction log
* files. Such a mode can be enabled or disabled using the action {@link org.apache.solr.handler.CdcrParams.CdcrAction#ENABLEBUFFER} and
* {@link org.apache.solr.handler.CdcrParams.CdcrAction#DISABLEBUFFER} respectively.
* </p>
* <p>
* Known limitations: The source and target clusters must have the same topology. Replication between clusters
* with a different number of shards will likely results in an inconsistent index.
* </p>
*/
public class CdcrRequestHandler extends RequestHandlerBase implements SolrCoreAware {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private SolrCore core;
private String collection;
private String path;
private SolrParams updateLogSynchronizerConfiguration;
private SolrParams replicatorConfiguration;
private SolrParams bufferConfiguration;
private Map<String, List<SolrParams>> replicasConfiguration;
private CdcrProcessStateManager processStateManager;
private CdcrBufferStateManager bufferStateManager;
private CdcrReplicatorManager replicatorManager;
private CdcrLeaderStateManager leaderStateManager;
private CdcrUpdateLogSynchronizer updateLogSynchronizer;
private CdcrBufferManager bufferManager;
@Override
public void init(NamedList args) {
super.init(args);
if (args != null) {
// Configuration of the Update Log Synchronizer
Object updateLogSynchonizerParam = args.get(CdcrParams.UPDATE_LOG_SYNCHRONIZER_PARAM);
if (updateLogSynchonizerParam != null && updateLogSynchonizerParam instanceof NamedList) {
updateLogSynchronizerConfiguration = SolrParams.toSolrParams((NamedList) updateLogSynchonizerParam);
}
// Configuration of the Replicator
Object replicatorParam = args.get(CdcrParams.REPLICATOR_PARAM);
if (replicatorParam != null && replicatorParam instanceof NamedList) {
replicatorConfiguration = SolrParams.toSolrParams((NamedList) replicatorParam);
}
// Configuration of the Buffer
Object bufferParam = args.get(CdcrParams.BUFFER_PARAM);
if (bufferParam != null && bufferParam instanceof NamedList) {
bufferConfiguration = SolrParams.toSolrParams((NamedList) bufferParam);
}
// Configuration of the Replicas
replicasConfiguration = new HashMap<>();
List replicas = args.getAll(CdcrParams.REPLICA_PARAM);
for (Object replica : replicas) {
if (replica != null && replica instanceof NamedList) {
SolrParams params = SolrParams.toSolrParams((NamedList) replica);
if (!replicasConfiguration.containsKey(params.get(CdcrParams.SOURCE_COLLECTION_PARAM))) {
replicasConfiguration.put(params.get(CdcrParams.SOURCE_COLLECTION_PARAM), new ArrayList<>());
}
replicasConfiguration.get(params.get(CdcrParams.SOURCE_COLLECTION_PARAM)).add(params);
}
}
}
}
@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
// Pick the action
SolrParams params = req.getParams();
CdcrParams.CdcrAction action = null;
String a = params.get(CommonParams.ACTION);
if (a != null) {
action = CdcrParams.CdcrAction.get(a);
}
if (action == null) {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Unknown action: " + a);
}
switch (action) {
case START: {
this.handleStartAction(req, rsp);
break;
}
case STOP: {
this.handleStopAction(req, rsp);
break;
}
case STATUS: {
this.handleStatusAction(req, rsp);
break;
}
case COLLECTIONCHECKPOINT: {
this.handleCollectionCheckpointAction(req, rsp);
break;
}
case SHARDCHECKPOINT: {
this.handleShardCheckpointAction(req, rsp);
break;
}
case ENABLEBUFFER: {
this.handleEnableBufferAction(req, rsp);
break;
}
case DISABLEBUFFER: {
this.handleDisableBufferAction(req, rsp);
break;
}
case LASTPROCESSEDVERSION: {
this.handleLastProcessedVersionAction(req, rsp);
break;
}
case QUEUES: {
this.handleQueuesAction(req, rsp);
break;
}
case OPS: {
this.handleOpsAction(req, rsp);
break;
}
case ERRORS: {
this.handleErrorsAction(req, rsp);
break;
}
case BOOTSTRAP: {
this.handleBootstrapAction(req, rsp);
break;
}
case BOOTSTRAP_STATUS: {
this.handleBootstrapStatus(req, rsp);
break;
}
case CANCEL_BOOTSTRAP: {
this.handleCancelBootstrap(req, rsp);
break;
}
default: {
throw new RuntimeException("Unknown action: " + action);
}
}
rsp.setHttpCaching(false);
}
@Override
public void inform(SolrCore core) {
this.core = core;
collection = core.getCoreDescriptor().getCloudDescriptor().getCollectionName();
// Make sure that the core is ZKAware
if (!core.getCoreDescriptor().getCoreContainer().isZooKeeperAware()) {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
"Solr instance is not running in SolrCloud mode.");
}
// Make sure that the core is using the CdcrUpdateLog implementation
if (!(core.getUpdateHandler().getUpdateLog() instanceof CdcrUpdateLog)) {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
"Solr instance is not configured with the cdcr update log.");
}
// Find the registered path of the handler
path = null;
for (Map.Entry<String, PluginBag.PluginHolder<SolrRequestHandler>> entry : core.getRequestHandlers().getRegistry().entrySet()) {
if (core.getRequestHandlers().isLoaded(entry.getKey()) && entry.getValue().get() == this) {
path = entry.getKey();
break;
}
}
if (path == null) {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
"The CdcrRequestHandler is not registered with the current core.");
}
if (!path.startsWith("/")) {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
"The CdcrRequestHandler needs to be registered to a path. Typically this is '/cdcr'");
}
// Initialisation phase
// If the Solr cloud is being initialised, each CDCR node will start up in its default state, i.e., STOPPED
// and non-leader. The leader state will be updated later, when all the Solr cores have been loaded.
// If the Solr cloud has already been initialised, and the core is reloaded (i.e., because a node died or a new node
// is added to the cluster), the CDCR node will synchronise its state with the global CDCR state that is stored
// in zookeeper.
// Initialise the buffer state manager
bufferStateManager = new CdcrBufferStateManager(core, bufferConfiguration);
// Initialise the process state manager
processStateManager = new CdcrProcessStateManager(core);
// Initialise the leader state manager
leaderStateManager = new CdcrLeaderStateManager(core);
// Initialise the replicator states manager
replicatorManager = new CdcrReplicatorManager(core, path, replicatorConfiguration, replicasConfiguration);
replicatorManager.setProcessStateManager(processStateManager);
replicatorManager.setLeaderStateManager(leaderStateManager);
// we need to inform it of a state event since the process and leader state
// may have been synchronised during the initialisation
replicatorManager.stateUpdate();
// Initialise the update log synchronizer
updateLogSynchronizer = new CdcrUpdateLogSynchronizer(core, path, updateLogSynchronizerConfiguration);
updateLogSynchronizer.setLeaderStateManager(leaderStateManager);
// we need to inform it of a state event since the leader state
// may have been synchronised during the initialisation
updateLogSynchronizer.stateUpdate();
// Initialise the buffer manager
bufferManager = new CdcrBufferManager(core);
bufferManager.setLeaderStateManager(leaderStateManager);
bufferManager.setBufferStateManager(bufferStateManager);
// we need to inform it of a state event since the leader state
// may have been synchronised during the initialisation
bufferManager.stateUpdate();
// register the close hook
this.registerCloseHook(core);
}
/**
* register a close hook to properly shutdown the state manager and scheduler
*/
private void registerCloseHook(SolrCore core) {
core.addCloseHook(new CloseHook() {
@Override
public void preClose(SolrCore core) {
String collectionName = core.getCoreDescriptor().getCloudDescriptor().getCollectionName();
String shard = core.getCoreDescriptor().getCloudDescriptor().getShardId();
log.info("Solr core is being closed - shutting down CDCR handler @ {}:{}", collectionName, shard);
updateLogSynchronizer.shutdown();
replicatorManager.shutdown();
bufferStateManager.shutdown();
processStateManager.shutdown();
leaderStateManager.shutdown();
}
@Override
public void postClose(SolrCore core) {
}
});
}
/**
* <p>
* Update and synchronize the process state.
* </p>
* <p>
* The process state manager must notify the replicator states manager of the change of state.
* </p>
*/
private void handleStartAction(SolrQueryRequest req, SolrQueryResponse rsp) {
if (processStateManager.getState() == CdcrParams.ProcessState.STOPPED) {
processStateManager.setState(CdcrParams.ProcessState.STARTED);
processStateManager.synchronize();
}
rsp.add(CdcrParams.CdcrAction.STATUS.toLower(), this.getStatus());
}
private void handleStopAction(SolrQueryRequest req, SolrQueryResponse rsp) {
if (processStateManager.getState() == CdcrParams.ProcessState.STARTED) {
processStateManager.setState(CdcrParams.ProcessState.STOPPED);
processStateManager.synchronize();
}
rsp.add(CdcrParams.CdcrAction.STATUS.toLower(), this.getStatus());
}
private void handleStatusAction(SolrQueryRequest req, SolrQueryResponse rsp) {
rsp.add(CdcrParams.CdcrAction.STATUS.toLower(), this.getStatus());
}
private NamedList getStatus() {
NamedList status = new NamedList();
status.add(CdcrParams.ProcessState.getParam(), processStateManager.getState().toLower());
status.add(CdcrParams.BufferState.getParam(), bufferStateManager.getState().toLower());
return status;
}
/**
* This action is generally executed on the target cluster in order to retrieve the latest update checkpoint.
* This checkpoint is used on the source cluster to setup the
* {@link org.apache.solr.update.CdcrUpdateLog.CdcrLogReader} of a shard leader. <br/>
* This method will execute in parallel one
* {@link org.apache.solr.handler.CdcrParams.CdcrAction#SHARDCHECKPOINT} request per shard leader. It will
* then pick the lowest version number as checkpoint. Picking the lowest amongst all shards will ensure that we do not
* pick a checkpoint that is ahead of the source cluster. This can occur when other shard leaders are sending new
* updates to the target cluster while we are currently instantiating the
* {@link org.apache.solr.update.CdcrUpdateLog.CdcrLogReader}.
* This solution only works in scenarios where the topology of the source and target clusters are identical.
*/
private void handleCollectionCheckpointAction(SolrQueryRequest req, SolrQueryResponse rsp)
throws IOException, SolrServerException {
ZkController zkController = core.getCoreDescriptor().getCoreContainer().getZkController();
try {
zkController.getZkStateReader().forceUpdateCollection(collection);
} catch (Exception e) {
log.warn("Error when updating cluster state", e);
}
ClusterState cstate = zkController.getClusterState();
Collection<Slice> shards = cstate.getActiveSlices(collection);
ExecutorService parallelExecutor = ExecutorUtil.newMDCAwareCachedThreadPool(new DefaultSolrThreadFactory("parallelCdcrExecutor"));
long checkpoint = Long.MAX_VALUE;
try {
List<Callable<Long>> callables = new ArrayList<>();
for (Slice shard : shards) {
ZkNodeProps leaderProps = zkController.getZkStateReader().getLeaderRetry(collection, shard.getName());
ZkCoreNodeProps nodeProps = new ZkCoreNodeProps(leaderProps);
callables.add(new SliceCheckpointCallable(nodeProps.getCoreUrl(), path));
}
for (final Future<Long> future : parallelExecutor.invokeAll(callables)) {
long version = future.get();
if (version < checkpoint) { // we must take the lowest checkpoint from all the shards
checkpoint = version;
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
"Error while requesting shard's checkpoints", e);
} catch (ExecutionException e) {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
"Error while requesting shard's checkpoints", e);
} finally {
parallelExecutor.shutdown();
}
rsp.add(CdcrParams.CHECKPOINT, checkpoint);
}
/**
* Retrieve the version number of the latest entry of the {@link org.apache.solr.update.UpdateLog}.
*/
private void handleShardCheckpointAction(SolrQueryRequest req, SolrQueryResponse rsp) {
if (!leaderStateManager.amILeader()) {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Action '" + CdcrParams.CdcrAction.SHARDCHECKPOINT +
"' sent to non-leader replica");
}
UpdateLog ulog = core.getUpdateHandler().getUpdateLog();
VersionInfo versionInfo = ulog.getVersionInfo();
try (UpdateLog.RecentUpdates recentUpdates = ulog.getRecentUpdates()) {
long maxVersionFromRecent = recentUpdates.getMaxRecentVersion();
long maxVersionFromIndex = versionInfo.getMaxVersionFromIndex(req.getSearcher());
log.info("Found maxVersionFromRecent {} maxVersionFromIndex {}", maxVersionFromRecent, maxVersionFromIndex);
// there is no race with ongoing bootstrap because we don't expect any updates to come from the source
long maxVersion = Math.max(maxVersionFromIndex, maxVersionFromRecent);
if (maxVersion == 0L) {
maxVersion = -1;
}
rsp.add(CdcrParams.CHECKPOINT, maxVersion);
} catch (IOException e) {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Action '" + CdcrParams.CdcrAction.SHARDCHECKPOINT +
"' could not read max version");
}
}
private void handleEnableBufferAction(SolrQueryRequest req, SolrQueryResponse rsp) {
if (bufferStateManager.getState() == CdcrParams.BufferState.DISABLED) {
bufferStateManager.setState(CdcrParams.BufferState.ENABLED);
bufferStateManager.synchronize();
}
rsp.add(CdcrParams.CdcrAction.STATUS.toLower(), this.getStatus());
}
private void handleDisableBufferAction(SolrQueryRequest req, SolrQueryResponse rsp) {
if (bufferStateManager.getState() == CdcrParams.BufferState.ENABLED) {
bufferStateManager.setState(CdcrParams.BufferState.DISABLED);
bufferStateManager.synchronize();
}
rsp.add(CdcrParams.CdcrAction.STATUS.toLower(), this.getStatus());
}
/**
* <p>
* We have to take care of four cases:
* <ul>
* <li>Replication & Buffering</li>
* <li>Replication & No Buffering</li>
* <li>No Replication & Buffering</li>
* <li>No Replication & No Buffering</li>
* </ul>
* In the first three cases, at least one log reader should have been initialised. We should take the lowest
* last processed version across all the initialised readers. In the last case, there isn't a log reader
* initialised. We should instantiate one and get the version of the first entries.
* </p>
*/
private void handleLastProcessedVersionAction(SolrQueryRequest req, SolrQueryResponse rsp) {
String collectionName = core.getCoreDescriptor().getCloudDescriptor().getCollectionName();
String shard = core.getCoreDescriptor().getCloudDescriptor().getShardId();
if (!leaderStateManager.amILeader()) {
log.warn("Action {} sent to non-leader replica @ {}:{}", CdcrParams.CdcrAction.LASTPROCESSEDVERSION, collectionName, shard);
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Action " + CdcrParams.CdcrAction.LASTPROCESSEDVERSION +
" sent to non-leader replica");
}
// take care of the first three cases
// first check the log readers from the replicator states
long lastProcessedVersion = Long.MAX_VALUE;
for (CdcrReplicatorState state : replicatorManager.getReplicatorStates()) {
long version = Long.MAX_VALUE;
if (state.getLogReader() != null) {
version = state.getLogReader().getLastVersion();
}
lastProcessedVersion = Math.min(lastProcessedVersion, version);
}
// next check the log reader of the buffer
CdcrUpdateLog.CdcrLogReader bufferLogReader = ((CdcrUpdateLog) core.getUpdateHandler().getUpdateLog()).getBufferToggle();
if (bufferLogReader != null) {
lastProcessedVersion = Math.min(lastProcessedVersion, bufferLogReader.getLastVersion());
}
// the fourth case: no cdc replication, no buffering: all readers were null
if (processStateManager.getState().equals(CdcrParams.ProcessState.STOPPED) &&
bufferStateManager.getState().equals(CdcrParams.BufferState.DISABLED)) {
CdcrUpdateLog.CdcrLogReader logReader = ((CdcrUpdateLog) core.getUpdateHandler().getUpdateLog()).newLogReader();
try {
// let the reader initialize lastVersion
logReader.next();
lastProcessedVersion = Math.min(lastProcessedVersion, logReader.getLastVersion());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
"Error while fetching the last processed version", e);
} catch (IOException e) {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
"Error while fetching the last processed version", e);
} finally {
logReader.close();
}
}
log.debug("Returning the lowest last processed version {} @ {}:{}", lastProcessedVersion, collectionName, shard);
rsp.add(CdcrParams.LAST_PROCESSED_VERSION, lastProcessedVersion);
}
private void handleQueuesAction(SolrQueryRequest req, SolrQueryResponse rsp) {
NamedList hosts = new NamedList();
for (CdcrReplicatorState state : replicatorManager.getReplicatorStates()) {
NamedList queueStats = new NamedList();
CdcrUpdateLog.CdcrLogReader logReader = state.getLogReader();
if (logReader == null) {
String collectionName = req.getCore().getCoreDescriptor().getCloudDescriptor().getCollectionName();
String shard = req.getCore().getCoreDescriptor().getCloudDescriptor().getShardId();
log.warn("The log reader for target collection {} is not initialised @ {}:{}",
state.getTargetCollection(), collectionName, shard);
queueStats.add(CdcrParams.QUEUE_SIZE, -1l);
} else {
queueStats.add(CdcrParams.QUEUE_SIZE, logReader.getNumberOfRemainingRecords());
}
queueStats.add(CdcrParams.LAST_TIMESTAMP, state.getTimestampOfLastProcessedOperation());
if (hosts.get(state.getZkHost()) == null) {
hosts.add(state.getZkHost(), new NamedList());
}
((NamedList) hosts.get(state.getZkHost())).add(state.getTargetCollection(), queueStats);
}
rsp.add(CdcrParams.QUEUES, hosts);
UpdateLog updateLog = core.getUpdateHandler().getUpdateLog();
rsp.add(CdcrParams.TLOG_TOTAL_SIZE, updateLog.getTotalLogsSize());
rsp.add(CdcrParams.TLOG_TOTAL_COUNT, updateLog.getTotalLogsNumber());
rsp.add(CdcrParams.UPDATE_LOG_SYNCHRONIZER,
updateLogSynchronizer.isStarted() ? CdcrParams.ProcessState.STARTED.toLower() : CdcrParams.ProcessState.STOPPED.toLower());
}
private void handleOpsAction(SolrQueryRequest req, SolrQueryResponse rsp) {
NamedList hosts = new NamedList();
for (CdcrReplicatorState state : replicatorManager.getReplicatorStates()) {
NamedList ops = new NamedList();
ops.add(CdcrParams.COUNTER_ALL, state.getBenchmarkTimer().getOperationsPerSecond());
ops.add(CdcrParams.COUNTER_ADDS, state.getBenchmarkTimer().getAddsPerSecond());
ops.add(CdcrParams.COUNTER_DELETES, state.getBenchmarkTimer().getDeletesPerSecond());
if (hosts.get(state.getZkHost()) == null) {
hosts.add(state.getZkHost(), new NamedList());
}
((NamedList) hosts.get(state.getZkHost())).add(state.getTargetCollection(), ops);
}
rsp.add(CdcrParams.OPERATIONS_PER_SECOND, hosts);
}
private void handleErrorsAction(SolrQueryRequest req, SolrQueryResponse rsp) {
NamedList hosts = new NamedList();
for (CdcrReplicatorState state : replicatorManager.getReplicatorStates()) {
NamedList errors = new NamedList();
errors.add(CdcrParams.CONSECUTIVE_ERRORS, state.getConsecutiveErrors());
errors.add(CdcrReplicatorState.ErrorType.BAD_REQUEST.toLower(), state.getErrorCount(CdcrReplicatorState.ErrorType.BAD_REQUEST));
errors.add(CdcrReplicatorState.ErrorType.INTERNAL.toLower(), state.getErrorCount(CdcrReplicatorState.ErrorType.INTERNAL));
NamedList lastErrors = new NamedList();
for (String[] lastError : state.getLastErrors()) {
lastErrors.add(lastError[0], lastError[1]);
}
errors.add(CdcrParams.LAST, lastErrors);
if (hosts.get(state.getZkHost()) == null) {
hosts.add(state.getZkHost(), new NamedList());
}
((NamedList) hosts.get(state.getZkHost())).add(state.getTargetCollection(), errors);
}
rsp.add(CdcrParams.ERRORS, hosts);
}
private AtomicBoolean running = new AtomicBoolean();
private volatile Future<Boolean> bootstrapFuture;
private volatile BootstrapCallable bootstrapCallable;
private void handleBootstrapAction(SolrQueryRequest req, SolrQueryResponse rsp) throws IOException, SolrServerException {
String collectionName = core.getCoreDescriptor().getCloudDescriptor().getCollectionName();
String shard = core.getCoreDescriptor().getCloudDescriptor().getShardId();
if (!leaderStateManager.amILeader()) {
log.warn("Action {} sent to non-leader replica @ {}:{}", CdcrParams.CdcrAction.BOOTSTRAP, collectionName, shard);
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Action " + CdcrParams.CdcrAction.BOOTSTRAP +
" sent to non-leader replica");
}
Runnable runnable = () -> {
Lock recoveryLock = req.getCore().getSolrCoreState().getRecoveryLock();
boolean locked = recoveryLock.tryLock();
try {
if (!locked) {
handleCancelBootstrap(req, rsp);
} else if (leaderStateManager.amILeader()) {
running.set(true);
String masterUrl = req.getParams().get(ReplicationHandler.MASTER_URL);
bootstrapCallable = new BootstrapCallable(masterUrl, core);
bootstrapFuture = core.getCoreDescriptor().getCoreContainer().getUpdateShardHandler().getRecoveryExecutor().submit(bootstrapCallable);
try {
bootstrapFuture.get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Bootstrap was interrupted", e);
} catch (ExecutionException e) {
log.error("Bootstrap operation failed", e);
}
} else {
log.error("Action {} sent to non-leader replica @ {}:{}. Aborting bootstrap.", CdcrParams.CdcrAction.BOOTSTRAP, collectionName, shard);
}
} finally {
if (locked) {
running.set(false);
recoveryLock.unlock();
}
}
};
try {
core.getCoreDescriptor().getCoreContainer().getUpdateShardHandler().getUpdateExecutor().submit(runnable);
rsp.add(RESPONSE_STATUS, "submitted");
} catch (RejectedExecutionException ree) {
// no problem, we're probably shutting down
rsp.add(RESPONSE_STATUS, "failed");
}
}
private void handleCancelBootstrap(SolrQueryRequest req, SolrQueryResponse rsp) {
BootstrapCallable callable = this.bootstrapCallable;
IOUtils.closeQuietly(callable);
rsp.add(RESPONSE_STATUS, "cancelled");
}
private void handleBootstrapStatus(SolrQueryRequest req, SolrQueryResponse rsp) throws IOException, SolrServerException {
if (running.get()) {
rsp.add(RESPONSE_STATUS, RUNNING);
return;
}
Future<Boolean> future = bootstrapFuture;
BootstrapCallable callable = this.bootstrapCallable;
if (future == null) {
rsp.add(RESPONSE_STATUS, "notfound");
rsp.add(RESPONSE_MESSAGE, "No bootstrap found in running, completed or failed states");
} else if (future.isCancelled() || callable.isClosed()) {
rsp.add(RESPONSE_STATUS, "cancelled");
} else if (future.isDone()) {
// could be a normal termination or an exception
try {
Boolean result = future.get();
if (result) {
rsp.add(RESPONSE_STATUS, COMPLETED);
} else {
rsp.add(RESPONSE_STATUS, FAILED);
}
} catch (InterruptedException e) {
// should not happen?
} catch (ExecutionException e) {
rsp.add(RESPONSE_STATUS, FAILED);
rsp.add(RESPONSE, e);
} catch (CancellationException ce) {
rsp.add(RESPONSE_STATUS, FAILED);
rsp.add(RESPONSE_MESSAGE, "Bootstrap was cancelled");
}
} else {
rsp.add(RESPONSE_STATUS, RUNNING);
}
}
private static class BootstrapCallable implements Callable<Boolean>, Closeable {
private final String masterUrl;
private final SolrCore core;
private volatile boolean closed = false;
BootstrapCallable(String masterUrl, SolrCore core) {
this.masterUrl = masterUrl;
this.core = core;
}
@Override
public void close() throws IOException {
closed = true;
SolrRequestHandler handler = core.getRequestHandler(ReplicationHandler.PATH);
ReplicationHandler replicationHandler = (ReplicationHandler) handler;
replicationHandler.abortFetch();
}
public boolean isClosed() {
return closed;
}
@Override
public Boolean call() throws Exception {
boolean success = false;
UpdateLog ulog = core.getUpdateHandler().getUpdateLog();
// we start buffering updates as a safeguard however we do not expect
// to receive any updates from the source during bootstrap
ulog.bufferUpdates();
try {
commitOnLeader(masterUrl);
// use rep handler directly, so we can do this sync rather than async
SolrRequestHandler handler = core.getRequestHandler(ReplicationHandler.PATH);
ReplicationHandler replicationHandler = (ReplicationHandler) handler;
if (replicationHandler == null) {
throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE,
"Skipping recovery, no " + ReplicationHandler.PATH + " handler found");
}
ModifiableSolrParams solrParams = new ModifiableSolrParams();
solrParams.set(ReplicationHandler.MASTER_URL, masterUrl);
// we do not want the raw tlog files from the source
solrParams.set(ReplicationHandler.TLOG_FILES, false);
success = replicationHandler.doFetch(solrParams, false);
// this is required because this callable can race with HttpSolrCall#destroy
// which clears the request info.
// Applying buffered updates fails without the following line because LogReplayer
// also tries to set request info and fails with AssertionError
SolrRequestInfo.clearRequestInfo();
Future<UpdateLog.RecoveryInfo> future = ulog.applyBufferedUpdates();
if (future == null) {
// no replay needed
log.info("No replay needed.");
} else {
log.info("Replaying buffered documents.");
// wait for replay
UpdateLog.RecoveryInfo report = future.get();
if (report.failed) {
SolrException.log(log, "Replay failed");
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Replay failed");
}
}
return success;
} finally {
if (closed || !success) {
// we cannot apply the buffer in this case because it will introduce newer versions in the
// update log and then the source cluster will get those versions via collectioncheckpoint
// causing the versions in between to be completely missed
boolean dropped = ulog.dropBufferedUpdates();
assert dropped;
}
}
}
private void commitOnLeader(String leaderUrl) throws SolrServerException,
IOException {
try (HttpSolrClient client = new HttpSolrClient.Builder(leaderUrl).build()) {
client.setConnectionTimeout(30000);
UpdateRequest ureq = new UpdateRequest();
ureq.setParams(new ModifiableSolrParams());
ureq.getParams().set(DistributedUpdateProcessor.COMMIT_END_POINT, true);
ureq.getParams().set(UpdateParams.OPEN_SEARCHER, false);
ureq.setAction(AbstractUpdateRequest.ACTION.COMMIT, false, true).process(
client);
}
}
}
@Override
public String getDescription() {
return "Manage Cross Data Center Replication";
}
/**
* A thread subclass for executing a single
* {@link org.apache.solr.handler.CdcrParams.CdcrAction#SHARDCHECKPOINT} action.
*/
private static final class SliceCheckpointCallable implements Callable<Long> {
final String baseUrl;
final String cdcrPath;
SliceCheckpointCallable(final String baseUrl, final String cdcrPath) {
this.baseUrl = baseUrl;
this.cdcrPath = cdcrPath;
}
@Override
public Long call() throws Exception {
try (HttpSolrClient server = new HttpSolrClient.Builder(baseUrl).build()) {
server.setConnectionTimeout(15000);
server.setSoTimeout(60000);
ModifiableSolrParams params = new ModifiableSolrParams();
params.set(CommonParams.ACTION, CdcrParams.CdcrAction.SHARDCHECKPOINT.toString());
SolrRequest request = new QueryRequest(params);
request.setPath(cdcrPath);
NamedList response = server.request(request);
return (Long) response.get(CdcrParams.CHECKPOINT);
}
}
}
}
|
package com.hari;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
@SpringBootApplication
@EnableConfigServer
public class InsurenceConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(InsurenceConfigServerApplication.class, args);
}
}
|
package ch.unisg.tapasexecutorpool.pool.application.port.out;
import ch.unisg.tapascommon.common.SelfValidating;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Value;
import javax.validation.constraints.NotNull;
@EqualsAndHashCode(callSuper = false)
@Value
public class TaskAssignedEvent extends SelfValidating<TaskAssignedEvent> {
@Getter
@NotNull
String serviceProvider;
@Getter
@NotNull
String taskUri;
public TaskAssignedEvent(String serviceProvider, String taskUri) {
this.serviceProvider = serviceProvider;
this.taskUri = taskUri;
this.validateSelf();
}
}
|
package com.udacity.gamedev.gigagal.util;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetDescriptor;
import com.badlogic.gdx.assets.AssetErrorListener;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.Animation.PlayMode;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasRegion;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;
public class Assets implements Disposable, AssetErrorListener {
public static final String TAG = Assets.class.getName();
public static final Assets instance = new Assets();
public GigaGalAssets gigaGalAssets;
// TODO: Add a PlatformAssets member
private AssetManager assetManager;
private Assets() {
}
public void init(AssetManager assetManager) {
this.assetManager = assetManager;
assetManager.setErrorListener(this);
assetManager.load(Constants.TEXTURE_ATLAS, TextureAtlas.class);
assetManager.finishLoading();
TextureAtlas atlas = assetManager.get(Constants.TEXTURE_ATLAS);
gigaGalAssets = new GigaGalAssets(atlas);
// TODO: Initialize platformAssets, passing in the atlas
}
@Override
public void error(AssetDescriptor asset, Throwable throwable) {
Gdx.app.error(TAG, "Couldn't load asset: " + asset.fileName, throwable);
}
@Override
public void dispose() {
assetManager.dispose();
}
public class GigaGalAssets {
public final AtlasRegion standingLeft;
public final AtlasRegion standingRight;
public final AtlasRegion walkingLeft;
public final AtlasRegion walkingRight;
public final AtlasRegion jumpingLeft;
public final AtlasRegion jumpingRight;
public final Animation walkingLeftAnimation;
public final Animation walkingRightAnimation;
public GigaGalAssets(TextureAtlas atlas) {
standingLeft = atlas.findRegion(Constants.STANDING_LEFT);
standingRight = atlas.findRegion(Constants.STANDING_RIGHT);
walkingLeft = atlas.findRegion(Constants.WALKING_LEFT_2);
walkingRight = atlas.findRegion(Constants.WALKING_RIGHT_2);
jumpingLeft = atlas.findRegion(Constants.JUMPING_LEFT);
jumpingRight = atlas.findRegion(Constants.JUMPING_RIGHT);
Array<AtlasRegion> walkingLeftFrames = new Array<AtlasRegion>();
walkingLeftFrames.add(atlas.findRegion(Constants.WALKING_LEFT_2));
walkingLeftFrames.add(atlas.findRegion(Constants.WALKING_LEFT_1));
walkingLeftFrames.add(atlas.findRegion(Constants.WALKING_LEFT_2));
walkingLeftFrames.add(atlas.findRegion(Constants.WALKING_LEFT_3));
walkingLeftAnimation = new Animation(Constants.WALK_LOOP_DURATION, walkingLeftFrames, PlayMode.LOOP);
Array<AtlasRegion> walkingRightFrames = new Array<AtlasRegion>();
walkingRightFrames.add(atlas.findRegion(Constants.WALKING_RIGHT_2));
walkingRightFrames.add(atlas.findRegion(Constants.WALKING_RIGHT_1));
walkingRightFrames.add(atlas.findRegion(Constants.WALKING_RIGHT_2));
walkingRightFrames.add(atlas.findRegion(Constants.WALKING_RIGHT_3));
walkingRightAnimation = new Animation(Constants.WALK_LOOP_DURATION, walkingRightFrames, PlayMode.LOOP);
}
}
public class PlatformAssets {
// TODO: Add a NinePatch member
public PlatformAssets(TextureAtlas atlas) {
// TODO: Find the AtlasRegion holding the platform
// TODO: Turn that AtlasRegion into a NinePatch using the edge constant you defined
}
}
}
|
/*
* Copyright (C) 2011 0xlab - http://0xlab.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Authored by Kan-Ru Chen <kanru@0xlab.org>
*/
package org.zeroxlab.aster.cmds;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.script.SimpleBindings;
import org.python.core.PyException;
import org.zeroxlab.aster.operations.AsterOperation;
import org.zeroxlab.wookieerunner.ScriptRunner;
public abstract class AsterCommand {
protected static ScriptRunner mRunner;
protected static int mSeqNext = 0;
protected int mSerial = 0;
protected boolean mLandscape = false;
protected BufferedImage mImage = null;
protected AsterOperation[] mOps;
protected boolean mExecuting = false;
protected boolean mFilled = false;
public static class ExecutionResult {
public boolean mSuccess;
public String mMessage;
public ExecutionResult() {
}
public ExecutionResult(boolean success, String message) {
mSuccess = success;
mMessage = message;
}
}
public boolean isFilled() {
return mFilled;
}
protected void setFilled(boolean status) {
mFilled = status;
}
static public void setScriptRunner(ScriptRunner runner) {
mRunner = runner;
}
synchronized public void setExecuting(boolean status) {
mExecuting = status;
}
synchronized public boolean isExecuting() {
return mExecuting;
}
synchronized public boolean isLandscape() {
return mLandscape;
}
protected String[] splitArgs(String argline) {
String[] args = argline.split(",");
for (int i = 0; i < args.length; ++i) {
args[i] = args[i].replaceAll("^[() ]+","").replaceAll("[() ]$","");
}
return args;
}
protected String stripQuote(String src) {
return src.replaceAll("'", "").replaceAll("\"", "");
}
public BufferedImage getImage() {
return mImage;
}
public void saveImage(String prefix) throws IOException {
if (mImage != null) {
File pngfile = new File(prefix, String.format("%d.png", mSerial));
pngfile.delete();
ImageIO.write(mImage, "png", pngfile);
}
}
/* Return operations that stored in this Command */
public AsterOperation[] getOperations() {
return mOps;
}
public final void fillSettings(SimpleBindings settings) throws IOException {
setFilled(true);
onFillSettings(settings);
}
/* Get name of command */
public abstract String getName();
/* Get settings of a command */
public abstract SimpleBindings getSettings();
/* Set settings of a command */
protected abstract void onFillSettings(SimpleBindings settings) throws IOException;
/* Dump command to script text */
public abstract String toScript();
/* Execute command */
public ExecutionResult execute() {
try {
mRunner.runStringLocal(toScript());
} catch (PyException e) {
return new ExecutionResult(false, e.toString());
}
return new ExecutionResult(true, "");
}
public interface CommandListener {
public void commandFinished(AsterCommand whichOne);
}
public interface CommandExecutionListener {
public void processResult(ExecutionResult result);
}
}
|
// Targeted by JavaCPP version 1.5.1: DO NOT EDIT THIS FILE
package org.bytedeco.onnx;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.onnx.global.onnx.*;
@Namespace("onnx") @Opaque @Properties(inherit = org.bytedeco.onnx.presets.onnx.class)
public class Min_Onnx_ver1 extends Pointer {
/** Empty constructor. Calls {@code super((Pointer)null)}. */
public Min_Onnx_ver1() { super((Pointer)null); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public Min_Onnx_ver1(Pointer p) { super(p); }
}
|
package org.logs;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableFeignClients
public class LogsApplication {
public static void main(String[] args) {
SpringApplication.run(LogsApplication.class, args);
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.hadoop.utils.db.cache;
import java.util.concurrent.CompletableFuture;
import com.google.common.base.Optional;
import org.apache.hadoop.test.GenericTestUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.fail;
/**
* Class tests partial table cache.
*/
public class TestPartialTableCache {
private TableCache<CacheKey<String>, CacheValue<String>> tableCache;
@Before
public void create() {
tableCache = new PartialTableCache<>();
}
@Test
public void testPartialTableCache() {
for (int i = 0; i< 10; i++) {
tableCache.put(new CacheKey<>(Integer.toString(i)),
new CacheValue<>(Optional.of(Integer.toString(i)), i));
}
for (int i=0; i < 10; i++) {
Assert.assertEquals(Integer.toString(i),
tableCache.get(new CacheKey<>(Integer.toString(i))).getValue());
}
// On a full table cache if some one calls cleanup it is a no-op.
tableCache.cleanup(4);
for (int i=5; i < 10; i++) {
Assert.assertEquals(Integer.toString(i),
tableCache.get(new CacheKey<>(Integer.toString(i))).getValue());
}
}
@Test
public void testPartialTableCacheParallel() throws Exception {
int totalCount = 0;
CompletableFuture<Integer> future =
CompletableFuture.supplyAsync(() -> {
try {
return writeToCache(10, 1, 0);
} catch (InterruptedException ex) {
fail("writeToCache got interrupt exception");
}
return 0;
});
int value = future.get();
Assert.assertEquals(10, value);
totalCount += value;
future =
CompletableFuture.supplyAsync(() -> {
try {
return writeToCache(10, 11, 100);
} catch (InterruptedException ex) {
fail("writeToCache got interrupt exception");
}
return 0;
});
// Check we have first 10 entries in cache.
for (int i=1; i <= 10; i++) {
Assert.assertEquals(Integer.toString(i),
tableCache.get(new CacheKey<>(Integer.toString(i))).getValue());
}
int deleted = 5;
// cleanup first 5 entires
tableCache.cleanup(deleted);
value = future.get();
Assert.assertEquals(10, value);
totalCount += value;
// We should totalCount - deleted entries in cache.
final int tc = totalCount;
GenericTestUtils.waitFor(() -> (tc - deleted == tableCache.size()), 100,
5000);
// Check if we have remaining entries.
for (int i=6; i <= totalCount; i++) {
Assert.assertEquals(Integer.toString(i),
tableCache.get(new CacheKey<>(Integer.toString(i))).getValue());
}
tableCache.cleanup(10);
tableCache.cleanup(totalCount);
// Cleaned up all entries, so cache size should be zero.
GenericTestUtils.waitFor(() -> (0 == tableCache.size()), 100,
5000);
}
private int writeToCache(int count, int startVal, long sleep)
throws InterruptedException {
int counter = 1;
while (counter <= count){
tableCache.put(new CacheKey<>(Integer.toString(startVal)),
new CacheValue<>(Optional.of(Integer.toString(startVal)), startVal));
startVal++;
counter++;
Thread.sleep(sleep);
}
return count;
}
}
|
package com.jc.gulimall.thirdparty;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@EnableDiscoveryClient
@SpringBootApplication
public class GulimallThirdPartyApplication {
public static void main(String[] args) {
SpringApplication.run(GulimallThirdPartyApplication.class, args);
}
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:04bd6018f85734a27cfd30b1ec90e331a7f3dc82510ebb806acb5d466d5a51ae
size 2024
|
/*
* Copyright 2011 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.rhine.unicorn.core.imported.cglib.proxy;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.rhine.unicorn.core.imported.cglib.core.Constants;
import org.rhine.unicorn.core.imported.cglib.core.Signature;
import org.rhine.unicorn.core.imported.asm.ClassReader;
import org.rhine.unicorn.core.imported.asm.ClassVisitor;
import org.rhine.unicorn.core.imported.asm.MethodVisitor;
import org.rhine.unicorn.core.imported.asm.Opcodes;
/**
* Uses bytecode reflection to figure out the targets of all bridge methods that use invokespecial
* and invokeinterface, so that we can later rewrite them to use invokevirtual.
*
* <p>For interface bridges, using invokesuper will fail since the method being bridged to is in a
* superinterface, not a superclass. Starting in Java 8, javac emits default bridge methods in
* interfaces, which use invokeinterface to bridge to the target method.
*
* @author sberlin@gmail.com (Sam Berlin)
*/
class BridgeMethodResolver {
private final Map/* <Class, Set<Signature> */declToBridge;
private final ClassLoader classLoader;
public BridgeMethodResolver(Map declToBridge, ClassLoader classLoader) {
this.declToBridge = declToBridge;
this.classLoader = classLoader;
}
/**
* Finds all bridge methods that are being called with invokespecial &
* returns them.
*/
public Map/*<Signature, Signature>*/resolveAll() {
Map resolved = new HashMap();
for (Iterator entryIter = declToBridge.entrySet().iterator(); entryIter.hasNext(); ) {
Map.Entry entry = (Map.Entry) entryIter.next();
Class owner = (Class) entry.getKey();
Set bridges = (Set) entry.getValue();
try {
InputStream is = classLoader.getResourceAsStream(owner.getName().replace('.', '/') + ".class");
if (is == null) {
return resolved;
}
try {
new ClassReader(is)
.accept(new BridgedFinder(bridges, resolved),
ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG);
} finally {
is.close();
}
} catch (IOException ignored) {}
}
return resolved;
}
private static class BridgedFinder extends ClassVisitor {
private Map/*<Signature, Signature>*/ resolved;
private Set/*<Signature>*/ eligibleMethods;
private Signature currentMethod = null;
BridgedFinder(Set eligibleMethods, Map resolved) {
super(Constants.ASM_API);
this.resolved = resolved;
this.eligibleMethods = eligibleMethods;
}
public void visit(int version, int access, String name,
String signature, String superName, String[] interfaces) {
}
public MethodVisitor visitMethod(int access, String name, String desc,
String signature, String[] exceptions) {
Signature sig = new Signature(name, desc);
if (eligibleMethods.remove(sig)) {
currentMethod = sig;
return new MethodVisitor(Constants.ASM_API) {
public void visitMethodInsn(
int opcode, String owner, String name, String desc, boolean itf) {
if ((opcode == Opcodes.INVOKESPECIAL
|| (itf && opcode == Opcodes.INVOKEINTERFACE))
&& currentMethod != null) {
Signature target = new Signature(name, desc);
// If the target signature is the same as the current,
// we shouldn't change our bridge becaues invokespecial
// is the only way to make progress (otherwise we'll
// get infinite recursion). This would typically
// only happen when a bridge method is created to widen
// the visibility of a superclass' method.
if (!target.equals(currentMethod)) {
resolved.put(currentMethod, target);
}
currentMethod = null;
}
}
};
} else {
return null;
}
}
}
}
|
/*
* 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.rocketmq.example.filter;
import java.io.IOException;
import java.util.List;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
public class TagFilterConsumer {
public static void main(String[] args) throws InterruptedException, MQClientException, IOException {
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("TagFilterComsumer");
consumer.subscribe("TOPIC", "TAGA || TAGB || TAGC");
consumer.registerMessageListener(new MessageListenerConcurrently() {
@Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
ConsumeConcurrentlyContext context) {
System.out.printf("%s Receive New Messages: %s %n", Thread.currentThread().getName(), msgs);
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
});
consumer.start();
System.out.printf("Consumer Started.%n");
}
}
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|store
operator|.
name|jdbc
package|;
end_package
begin_import
import|import
name|java
operator|.
name|sql
operator|.
name|PreparedStatement
import|;
end_import
begin_import
import|import
name|java
operator|.
name|sql
operator|.
name|ResultSet
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|jms
operator|.
name|DeliveryMode
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|jms
operator|.
name|Destination
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|jms
operator|.
name|Message
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|jms
operator|.
name|MessageConsumer
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|jms
operator|.
name|MessageProducer
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|jms
operator|.
name|Session
import|;
end_import
begin_import
import|import
name|junit
operator|.
name|framework
operator|.
name|TestCase
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|ActiveMQConnectionFactory
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|broker
operator|.
name|BrokerService
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|openwire
operator|.
name|OpenWireFormat
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|util
operator|.
name|ByteSequence
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|wireformat
operator|.
name|WireFormat
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|derby
operator|.
name|jdbc
operator|.
name|EmbeddedDataSource
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|Logger
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|LoggerFactory
import|;
end_import
begin_comment
comment|// https://issues.apache.org/activemq/browse/AMQ-2880
end_comment
begin_class
specifier|public
class|class
name|JDBCCommitExceptionTest
extends|extends
name|TestCase
block|{
specifier|private
specifier|static
specifier|final
name|Logger
name|LOG
init|=
name|LoggerFactory
operator|.
name|getLogger
argument_list|(
name|JDBCCommitExceptionTest
operator|.
name|class
argument_list|)
decl_stmt|;
specifier|protected
specifier|static
specifier|final
name|int
name|messagesExpected
init|=
literal|10
decl_stmt|;
specifier|protected
name|ActiveMQConnectionFactory
name|factory
decl_stmt|;
specifier|protected
name|BrokerService
name|broker
decl_stmt|;
specifier|protected
name|String
name|connectionUri
decl_stmt|;
specifier|protected
name|BrokenPersistenceAdapter
name|jdbc
decl_stmt|;
annotation|@
name|Override
specifier|public
name|void
name|setUp
parameter_list|()
throws|throws
name|Exception
block|{
name|broker
operator|=
name|createBroker
argument_list|()
expr_stmt|;
name|broker
operator|.
name|start
argument_list|()
expr_stmt|;
name|factory
operator|=
operator|new
name|ActiveMQConnectionFactory
argument_list|(
name|connectionUri
operator|+
literal|"?jms.prefetchPolicy.all=0&jms.redeliveryPolicy.maximumRedeliveries="
operator|+
name|messagesExpected
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Override
specifier|public
name|void
name|tearDown
parameter_list|()
throws|throws
name|Exception
block|{
name|broker
operator|.
name|stop
argument_list|()
expr_stmt|;
block|}
specifier|public
name|void
name|testSqlException
parameter_list|()
throws|throws
name|Exception
block|{
name|doTestSqlException
argument_list|()
expr_stmt|;
block|}
specifier|public
name|void
name|doTestSqlException
parameter_list|()
throws|throws
name|Exception
block|{
name|sendMessages
argument_list|(
name|messagesExpected
argument_list|)
expr_stmt|;
name|int
name|messagesReceived
init|=
name|receiveMessages
argument_list|(
name|messagesExpected
argument_list|)
decl_stmt|;
name|dumpMessages
argument_list|()
expr_stmt|;
name|assertEquals
argument_list|(
literal|"Messages expected doesn't equal messages received"
argument_list|,
name|messagesExpected
argument_list|,
name|messagesReceived
argument_list|)
expr_stmt|;
name|broker
operator|.
name|stop
argument_list|()
expr_stmt|;
block|}
specifier|protected
name|int
name|dumpMessages
parameter_list|()
throws|throws
name|Exception
block|{
name|int
name|count
init|=
literal|0
decl_stmt|;
name|WireFormat
name|wireFormat
init|=
operator|new
name|OpenWireFormat
argument_list|()
decl_stmt|;
name|java
operator|.
name|sql
operator|.
name|Connection
name|conn
init|=
operator|(
operator|(
name|JDBCPersistenceAdapter
operator|)
name|broker
operator|.
name|getPersistenceAdapter
argument_list|()
operator|)
operator|.
name|getDataSource
argument_list|()
operator|.
name|getConnection
argument_list|()
decl_stmt|;
name|PreparedStatement
name|statement
init|=
name|conn
operator|.
name|prepareStatement
argument_list|(
literal|"SELECT ID, XID, MSG FROM ACTIVEMQ_MSGS"
argument_list|)
decl_stmt|;
name|ResultSet
name|result
init|=
name|statement
operator|.
name|executeQuery
argument_list|()
decl_stmt|;
name|LOG
operator|.
name|info
argument_list|(
literal|"Messages left in broker after test"
argument_list|)
expr_stmt|;
while|while
condition|(
name|result
operator|.
name|next
argument_list|()
condition|)
block|{
name|long
name|id
init|=
name|result
operator|.
name|getLong
argument_list|(
literal|1
argument_list|)
decl_stmt|;
name|String
name|xid
init|=
name|result
operator|.
name|getString
argument_list|(
literal|2
argument_list|)
decl_stmt|;
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|command
operator|.
name|Message
name|message
init|=
operator|(
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|command
operator|.
name|Message
operator|)
name|wireFormat
operator|.
name|unmarshal
argument_list|(
operator|new
name|ByteSequence
argument_list|(
name|result
operator|.
name|getBytes
argument_list|(
literal|3
argument_list|)
argument_list|)
argument_list|)
decl_stmt|;
name|LOG
operator|.
name|info
argument_list|(
literal|"id: "
operator|+
name|id
operator|+
literal|", xid: "
operator|+
name|xid
operator|+
literal|", message SeqId: "
operator|+
name|message
operator|.
name|getMessageId
argument_list|()
operator|.
name|getBrokerSequenceId
argument_list|()
operator|+
literal|", MSG: "
operator|+
name|message
argument_list|)
expr_stmt|;
name|count
operator|++
expr_stmt|;
block|}
name|statement
operator|.
name|close
argument_list|()
expr_stmt|;
name|conn
operator|.
name|close
argument_list|()
expr_stmt|;
return|return
name|count
return|;
block|}
specifier|protected
name|int
name|receiveMessages
parameter_list|(
name|int
name|messagesExpected
parameter_list|)
throws|throws
name|Exception
block|{
name|javax
operator|.
name|jms
operator|.
name|Connection
name|connection
init|=
name|factory
operator|.
name|createConnection
argument_list|()
decl_stmt|;
name|connection
operator|.
name|start
argument_list|()
expr_stmt|;
name|Session
name|session
init|=
name|connection
operator|.
name|createSession
argument_list|(
literal|true
argument_list|,
name|Session
operator|.
name|SESSION_TRANSACTED
argument_list|)
decl_stmt|;
name|jdbc
operator|.
name|setShouldBreak
argument_list|(
literal|true
argument_list|)
expr_stmt|;
comment|// first try and receive these messages, they'll continually fail
name|receiveMessages
argument_list|(
name|messagesExpected
argument_list|,
name|session
argument_list|)
expr_stmt|;
name|jdbc
operator|.
name|setShouldBreak
argument_list|(
literal|false
argument_list|)
expr_stmt|;
comment|// now that the store is sane, try and get all the messages sent
return|return
name|receiveMessages
argument_list|(
name|messagesExpected
argument_list|,
name|session
argument_list|)
return|;
block|}
specifier|protected
name|int
name|receiveMessages
parameter_list|(
name|int
name|messagesExpected
parameter_list|,
name|Session
name|session
parameter_list|)
throws|throws
name|Exception
block|{
name|int
name|messagesReceived
init|=
literal|0
decl_stmt|;
for|for
control|(
name|int
name|i
init|=
literal|0
init|;
name|i
operator|<
name|messagesExpected
condition|;
name|i
operator|++
control|)
block|{
name|Destination
name|destination
init|=
name|session
operator|.
name|createQueue
argument_list|(
literal|"TEST"
argument_list|)
decl_stmt|;
name|MessageConsumer
name|consumer
init|=
name|session
operator|.
name|createConsumer
argument_list|(
name|destination
argument_list|)
decl_stmt|;
name|Message
name|message
init|=
literal|null
decl_stmt|;
try|try
block|{
name|LOG
operator|.
name|debug
argument_list|(
literal|"Receiving message "
operator|+
operator|(
name|messagesReceived
operator|+
literal|1
operator|)
operator|+
literal|" of "
operator|+
name|messagesExpected
argument_list|)
expr_stmt|;
name|message
operator|=
name|consumer
operator|.
name|receive
argument_list|(
literal|2000
argument_list|)
expr_stmt|;
name|LOG
operator|.
name|info
argument_list|(
literal|"Received : "
operator|+
name|message
argument_list|)
expr_stmt|;
if|if
condition|(
name|message
operator|!=
literal|null
condition|)
block|{
name|session
operator|.
name|commit
argument_list|()
expr_stmt|;
name|messagesReceived
operator|++
expr_stmt|;
block|}
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
name|LOG
operator|.
name|debug
argument_list|(
literal|"Caught exception "
operator|+
name|e
argument_list|)
expr_stmt|;
name|session
operator|.
name|rollback
argument_list|()
expr_stmt|;
block|}
finally|finally
block|{
if|if
condition|(
name|consumer
operator|!=
literal|null
condition|)
block|{
name|consumer
operator|.
name|close
argument_list|()
expr_stmt|;
block|}
block|}
block|}
return|return
name|messagesReceived
return|;
block|}
specifier|protected
name|void
name|sendMessages
parameter_list|(
name|int
name|messagesExpected
parameter_list|)
throws|throws
name|Exception
block|{
name|javax
operator|.
name|jms
operator|.
name|Connection
name|connection
init|=
name|factory
operator|.
name|createConnection
argument_list|()
decl_stmt|;
name|connection
operator|.
name|start
argument_list|()
expr_stmt|;
name|Session
name|session
init|=
name|connection
operator|.
name|createSession
argument_list|(
literal|false
argument_list|,
name|Session
operator|.
name|AUTO_ACKNOWLEDGE
argument_list|)
decl_stmt|;
name|Destination
name|destination
init|=
name|session
operator|.
name|createQueue
argument_list|(
literal|"TEST"
argument_list|)
decl_stmt|;
name|MessageProducer
name|producer
init|=
name|session
operator|.
name|createProducer
argument_list|(
name|destination
argument_list|)
decl_stmt|;
name|producer
operator|.
name|setDeliveryMode
argument_list|(
name|DeliveryMode
operator|.
name|PERSISTENT
argument_list|)
expr_stmt|;
for|for
control|(
name|int
name|i
init|=
literal|0
init|;
name|i
operator|<
name|messagesExpected
condition|;
name|i
operator|++
control|)
block|{
name|LOG
operator|.
name|debug
argument_list|(
literal|"Sending message "
operator|+
operator|(
name|i
operator|+
literal|1
operator|)
operator|+
literal|" of "
operator|+
name|messagesExpected
argument_list|)
expr_stmt|;
name|producer
operator|.
name|send
argument_list|(
name|session
operator|.
name|createTextMessage
argument_list|(
literal|"test message "
operator|+
operator|(
name|i
operator|+
literal|1
operator|)
argument_list|)
argument_list|)
expr_stmt|;
block|}
block|}
specifier|protected
name|BrokerService
name|createBroker
parameter_list|()
throws|throws
name|Exception
block|{
name|BrokerService
name|broker
init|=
operator|new
name|BrokerService
argument_list|()
decl_stmt|;
name|broker
operator|.
name|setAdvisorySupport
argument_list|(
literal|false
argument_list|)
expr_stmt|;
name|jdbc
operator|=
operator|new
name|BrokenPersistenceAdapter
argument_list|()
expr_stmt|;
name|jdbc
operator|.
name|setUseLock
argument_list|(
literal|false
argument_list|)
expr_stmt|;
name|jdbc
operator|.
name|deleteAllMessages
argument_list|()
expr_stmt|;
name|broker
operator|.
name|setPersistenceAdapter
argument_list|(
name|jdbc
argument_list|)
expr_stmt|;
name|broker
operator|.
name|setPersistent
argument_list|(
literal|true
argument_list|)
expr_stmt|;
name|connectionUri
operator|=
name|broker
operator|.
name|addConnector
argument_list|(
literal|"tcp://localhost:0"
argument_list|)
operator|.
name|getPublishableConnectString
argument_list|()
expr_stmt|;
return|return
name|broker
return|;
block|}
block|}
end_class
end_unit
|
package org.gradle.test.performance.mediummonolithicjavaproject.p2;
public class Production55 {
private String property0;
public String getProperty0() {
return property0;
}
public void setProperty0(String value) {
property0 = value;
}
private String property1;
public String getProperty1() {
return property1;
}
public void setProperty1(String value) {
property1 = value;
}
private String property2;
public String getProperty2() {
return property2;
}
public void setProperty2(String value) {
property2 = value;
}
private String property3;
public String getProperty3() {
return property3;
}
public void setProperty3(String value) {
property3 = value;
}
private String property4;
public String getProperty4() {
return property4;
}
public void setProperty4(String value) {
property4 = value;
}
private String property5;
public String getProperty5() {
return property5;
}
public void setProperty5(String value) {
property5 = value;
}
private String property6;
public String getProperty6() {
return property6;
}
public void setProperty6(String value) {
property6 = value;
}
private String property7;
public String getProperty7() {
return property7;
}
public void setProperty7(String value) {
property7 = value;
}
private String property8;
public String getProperty8() {
return property8;
}
public void setProperty8(String value) {
property8 = value;
}
private String property9;
public String getProperty9() {
return property9;
}
public void setProperty9(String value) {
property9 = value;
}
}
|
package _09Animals;/**
* Created by IntelliJ IDEA.
* User: LAPD
* Date: 18.3.2018 г.
* Time: 15:30 ч.
*/
public class Kittens extends Cat {
public Kittens(String type, String name,
int age, String gender) {
super(type, name, age, gender);
}
@Override
public String produceSound() {
return "Miau";
}
}
|
package com.iot.security.common.web;
import org.apache.commons.io.IOUtils;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.util.Enumeration;
import java.util.Map;
import java.util.Vector;
public class ParameterRequestWrapper extends HttpServletRequestWrapper {
private Map params;
public ParameterRequestWrapper(HttpServletRequest request, Map newParams) {
super(request);
this.params = newParams;
}
@Override
public Map getParameterMap() {
return params;
}
@Override
public Enumeration getParameterNames() {
Vector l = new Vector(params.keySet());
return l.elements();
}
@Override
public String[] getParameterValues(String name) {
Object v = params.get(name);
if (v == null) {
return null;
} else if (v instanceof String[]) {
return (String[]) v;
} else if (v instanceof String) {
return new String[] { (String) v };
} else {
return new String[] { v.toString() };
}
}
@Override
public String getParameter(String name) {
Object v = params.get(name);
if (v == null) {
return null;
} else if (v instanceof String[]) {
String[] strArr = (String[]) v;
if (strArr.length > 0) {
return strArr[0];
} else {
return null;
}
} else if (v instanceof String) {
return (String) v;
} else {
return v.toString();
}
}
}
|
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.pinpoint.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.pinpoint.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* DeleteAdmChannelRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DeleteAdmChannelRequestProtocolMarshaller implements Marshaller<Request<DeleteAdmChannelRequest>, DeleteAdmChannelRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON)
.requestUri("/v1/apps/{application-id}/channels/adm").httpMethodName(HttpMethodName.DELETE).hasExplicitPayloadMember(false)
.hasPayloadMembers(false).serviceName("AmazonPinpoint").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public DeleteAdmChannelRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<DeleteAdmChannelRequest> marshall(DeleteAdmChannelRequest deleteAdmChannelRequest) {
if (deleteAdmChannelRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<DeleteAdmChannelRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
deleteAdmChannelRequest);
protocolMarshaller.startMarshalling();
DeleteAdmChannelRequestMarshaller.getInstance().marshall(deleteAdmChannelRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
package com.bustiblelemons.cthulhator.character.persistance;
import android.content.Context;
import com.bustiblelemons.async.AbsSimpleAsync;
import com.bustiblelemons.cthulhator.character.characterslist.logic.SavedCharacterTransformer;
import com.bustiblelemons.cthulhator.system.Grouping;
import com.bustiblelemons.cthulhator.view.charactercard.CharacterInfo;
import java.util.ArrayList;
import java.util.List;
/**
* Created by bhm on 13.08.14.
*/
public class SavedCharactersLoadAsyn extends AbsSimpleAsync<Grouping, List<CharacterInfo>> {
private final SavedCharactersProvider.OnCharactersInfoLoaded callBack;
public SavedCharactersLoadAsyn(Context context, SavedCharactersProvider.OnCharactersInfoLoaded callBack) {
super(context);
this.callBack = callBack;
}
@Override
protected List<CharacterInfo> call(Grouping... groupings) throws Exception {
for (Grouping g : groupings) {
SavedCharactersSet set = SavedCharactersProvider.getCharacterSet(context);
if (set != null) {
List<CharacterInfo> infos = new ArrayList<CharacterInfo>();
for (SavedCharacter savedCharacter : set.getCharacters()) {
CharacterInfo characterInfo =
SavedCharacterTransformer.getInstance()
.withContext(getContext())
.transform(new CharacterWrapper(savedCharacter));
infos.add(characterInfo);
}
publishProgress(g, infos);
}
}
return null;
}
@Override
protected boolean onException(Exception e) {
return false;
}
@Override
protected boolean onSuccess(List<CharacterInfo> result) {
return false;
}
@Override
public void onProgressUpdate(Grouping param, List<CharacterInfo> result) {
if (callBack != null) {
callBack.onCharactersInfoLoaded(param, result);
}
}
}
|
package control.commodity;
import actuator.ActuatorOpenCloseLaneGroup;
import common.AbstractLaneGroup;
import common.FlowAccumulatorState;
import common.LaneGroupSet;
import common.Scenario;
import control.AbstractController;
import control.command.CommandRestrictionMap;
import dispatch.Dispatcher;
import dispatch.EventPoke;
import error.OTMException;
import jaxb.Controller;
import lanechange.AbstractLaneSelector;
import lanechange.LogitLaneSelector;
import models.fluid.AbstractFluidModel;
import models.fluid.FluidLaneGroup;
import utils.OTMUtils;
import utils.LookupTable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class ControllerTollLaneGroup extends AbstractController {
public boolean firsttime;
public final float def_keep = 0.7f;
public final float def_rho_vpkmplane = 0.007147f;
public Set<Long> free_comms = new HashSet<>();
public Set<Long> banned_comms = new HashSet<>();
public Set<Long> tolled_comms = new HashSet<>();
public float toll_coef;
public float speed_threshold_meterpdt;
public LookupTable vplpdt_to_cents_table;
public Set<LGInfo> lginfos;
public ControllerTollLaneGroup(Scenario scenario, Controller jcnt) throws OTMException {
super(scenario, jcnt);
if(jcnt.getParameters()!=null)
for(jaxb.Parameter p : jcnt.getParameters().getParameter()){
switch(p.getName()){
case "free_comms":
free_comms.addAll(OTMUtils.csv2longlist(p.getValue()));
break;
case "disallowed_comms":
banned_comms.addAll(OTMUtils.csv2longlist(p.getValue()));
break;
case "tolled_comms":
tolled_comms.addAll(OTMUtils.csv2longlist(p.getValue()));
break;
case "vplph_to_cents_table":
vplpdt_to_cents_table = new LookupTable(p.getValue());
vplpdt_to_cents_table.scaleX(dt/3600f);
break;
case "toll_coef":
toll_coef = Float.parseFloat(p.getValue());
break;
case "qos_speed_threshold_kph":
speed_threshold_meterpdt = Float.parseFloat(p.getValue()); // fix units in initialize
speed_threshold_meterpdt *= 1000.0*dt/3600.0;
break;
}
}
}
@Override
public void initialize(Scenario scenario) throws OTMException {
super.initialize(scenario);
this.firsttime=true;
ActuatorOpenCloseLaneGroup act = (ActuatorOpenCloseLaneGroup)actuators.values().iterator().next();
this.lginfos = new HashSet<>();
for (AbstractLaneGroup hotlg : ((LaneGroupSet) act.target).lgs)
lginfos.add(new LGInfo(hotlg));
}
@Override
public void update_command(Dispatcher dispatcher) throws OTMException {
float timestamp = dispatcher.current_time;
long act_id = this.actuators.keySet().iterator().next();
if(firsttime){
// open/close the lanegroup
Map<Long, ControllerRestrictLaneGroup.Restriction> X = new HashMap<>();
for (Long commid : free_comms)
X.put(commid, ControllerRestrictLaneGroup.Restriction.Open);
for (Long commid : tolled_comms)
X.put(commid, ControllerRestrictLaneGroup.Restriction.Open);
for (Long commid : banned_comms)
X.put(commid, ControllerRestrictLaneGroup.Restriction.Closed);
command.put(act_id,new CommandRestrictionMap(X));
// save the existing lane selector and replace it with a new one
lginfos.forEach(l->l.initialize(dispatcher));
firsttime=false;
}
else if(timestamp<end_time)
lginfos.forEach(l->l.update());
// final time, return to previous state
else {
// release restrictions
Map<Long, ControllerRestrictLaneGroup.Restriction> X = new HashMap<>();
for(Long commid : this.scenario.commodities.keySet())
X.put(commid, ControllerRestrictLaneGroup.Restriction.Open);
command.put(act_id,new CommandRestrictionMap(X));
// put lane selector backs
lginfos.forEach(l->l.restore(scenario));
}
// register next poke
// if (timestamp<end_time)
// dispatcher.register_event(new EventPoke(dispatcher,19,this.end_time,this));
}
class LGInfo {
AbstractLaneGroup gplg;
AbstractLaneGroup hotlg;
FlowAccumulatorState fa;
double ffspeed_meterperdt;
Map<Long,AbstractLaneSelector> nom_ls;
Map<Long,LogitLaneSelector> toll_ls;
double prev_count;
public LGInfo(AbstractLaneGroup hotlg){
this.hotlg = hotlg;
this.gplg = hotlg.neighbor_out;
this.fa = hotlg.request_flow_accumulator(null);
prev_count = fa.get_total_count();
}
public void initialize(Dispatcher dispatcher){
nom_ls = new HashMap<>();
toll_ls = new HashMap<>();
int numcells = ((FluidLaneGroup)hotlg).cells.size();
double celllength_meter = hotlg.length / numcells;
ffspeed_meterperdt = ((FluidLaneGroup)hotlg).ffspeed_cell_per_dt * celllength_meter;
ffspeed_meterperdt *= dt/((AbstractFluidModel)hotlg.link.model).dt_sec;
for(Long commid : tolled_comms){
LogitLaneSelector newls;
if(gplg.lane_selector.containsKey(commid)) {
AbstractLaneSelector oldls = gplg.lane_selector.get(commid);
// remove future pokes
dispatcher.remove_events_for_recipient(EventPoke.class,oldls);
nom_ls.put(commid,oldls);
if(oldls instanceof LogitLaneSelector) {
LogitLaneSelector oldlogit = (LogitLaneSelector) oldls;
newls = new LogitLaneSelector(gplg,0,(float)oldlogit.getKeep(),(float)oldlogit.getRho_vehperlane(), commid);
}
else
newls = new LogitLaneSelector(gplg,0,def_keep,def_rho_vpkmplane, commid);
}
else
newls = new LogitLaneSelector(gplg,0,def_keep,def_rho_vpkmplane, commid);
try {
newls.initialize(scenario,start_time);
} catch (OTMException e) {
e.printStackTrace();
}
toll_ls.put(commid,newls);
gplg.lane_selector.put(commid,newls);
}
}
public void restore(Scenario scenario){
try {
for(Long commid : tolled_comms) {
if (nom_ls.containsKey(commid)) {
AbstractLaneSelector old_ls = nom_ls.get(commid);
old_ls.initialize(scenario,scenario.dispatcher.current_time);
gplg.lane_selector.put(commid, old_ls);
}
// remove future pokes for generated lane selectors
scenario.dispatcher.remove_events_for_recipient(EventPoke.class,toll_ls.get(commid));
}
} catch (OTMException e) {
e.printStackTrace();
}
}
public void update(){
double count = fa.get_total_count();
double flow_vpdt = count-prev_count;
prev_count = count;
double veh = hotlg.get_total_vehicles();
double speed_meterperdt = veh<1 ? ffspeed_meterperdt : hotlg.length*flow_vpdt/veh;
if(speed_meterperdt>ffspeed_meterperdt)
speed_meterperdt = ffspeed_meterperdt;
double add_term;
if(speed_meterperdt > speed_threshold_meterpdt)
add_term = Double.POSITIVE_INFINITY;
else {
double toll = vplpdt_to_cents_table.get_value_for((float)flow_vpdt/hotlg.num_lanes);
add_term = toll_coef*toll;
}
for(Long commid : tolled_comms)
toll_ls.get(commid).setAdd_in(add_term);
}
}
}
|
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.security.net.config;
import android.content.Context;
import android.test.AndroidTestCase;
import android.test.MoreAsserts;
import android.util.ArraySet;
import android.util.Pair;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
import java.security.KeyStore;
import java.security.Provider;
import java.security.Security;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Set;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
public class XmlConfigTests extends AndroidTestCase {
private final static String DEBUG_CA_SUBJ = "O=AOSP, CN=Test debug CA";
public void testEmptyConfigFile() throws Exception {
XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.empty_config);
ApplicationConfig appConfig = new ApplicationConfig(source);
assertFalse(appConfig.hasPerDomainConfigs());
NetworkSecurityConfig config = appConfig.getConfigForHostname("");
assertNotNull(config);
// Check defaults.
assertTrue(config.isCleartextTrafficPermitted());
assertFalse(config.isHstsEnforced());
assertFalse(config.getTrustAnchors().isEmpty());
PinSet pinSet = config.getPins();
assertTrue(pinSet.pins.isEmpty());
// Try some connections.
SSLContext context = TestUtils.getSSLContext(source);
TestUtils.assertConnectionSucceeds(context, "android.com", 443);
TestUtils.assertConnectionSucceeds(context, "developer.android.com", 443);
TestUtils.assertUrlConnectionSucceeds(context, "google.com", 443);
}
public void testEmptyAnchors() throws Exception {
XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.empty_trust);
ApplicationConfig appConfig = new ApplicationConfig(source);
assertFalse(appConfig.hasPerDomainConfigs());
NetworkSecurityConfig config = appConfig.getConfigForHostname("");
assertNotNull(config);
// Check defaults.
assertTrue(config.isCleartextTrafficPermitted());
assertFalse(config.isHstsEnforced());
assertTrue(config.getTrustAnchors().isEmpty());
PinSet pinSet = config.getPins();
assertTrue(pinSet.pins.isEmpty());
SSLContext context = TestUtils.getSSLContext(source);
TestUtils.assertConnectionFails(context, "android.com", 443);
TestUtils.assertConnectionFails(context, "developer.android.com", 443);
TestUtils.assertUrlConnectionFails(context, "google.com", 443);
}
public void testBasicDomainConfig() throws Exception {
XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.domain1);
ApplicationConfig appConfig = new ApplicationConfig(source);
assertTrue(appConfig.hasPerDomainConfigs());
NetworkSecurityConfig config = appConfig.getConfigForHostname("");
assertNotNull(config);
// Check defaults.
assertTrue(config.isCleartextTrafficPermitted());
assertFalse(config.isHstsEnforced());
assertTrue(config.getTrustAnchors().isEmpty());
PinSet pinSet = config.getPins();
assertTrue(pinSet.pins.isEmpty());
// Check android.com.
config = appConfig.getConfigForHostname("android.com");
assertTrue(config.isCleartextTrafficPermitted());
assertFalse(config.isHstsEnforced());
assertFalse(config.getTrustAnchors().isEmpty());
pinSet = config.getPins();
assertTrue(pinSet.pins.isEmpty());
// Try connections.
SSLContext context = TestUtils.getSSLContext(source);
TestUtils.assertConnectionSucceeds(context, "android.com", 443);
TestUtils.assertConnectionFails(context, "developer.android.com", 443);
TestUtils.assertUrlConnectionFails(context, "google.com", 443);
TestUtils.assertUrlConnectionSucceeds(context, "android.com", 443);
// Check that sockets created without the hostname fail with per-domain configs
SSLSocket socket = (SSLSocket) context.getSocketFactory()
.createSocket(InetAddress.getByName("android.com"), 443);
try {
socket.startHandshake();
socket.getInputStream();
fail();
} catch (IOException expected) {
}
}
public void testBasicPinning() throws Exception {
XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.pins1);
ApplicationConfig appConfig = new ApplicationConfig(source);
assertTrue(appConfig.hasPerDomainConfigs());
// Check android.com.
NetworkSecurityConfig config = appConfig.getConfigForHostname("android.com");
PinSet pinSet = config.getPins();
assertFalse(pinSet.pins.isEmpty());
// Try connections.
SSLContext context = TestUtils.getSSLContext(source);
TestUtils.assertConnectionSucceeds(context, "android.com", 443);
TestUtils.assertUrlConnectionSucceeds(context, "android.com", 443);
TestUtils.assertConnectionSucceeds(context, "google.com", 443);
}
public void testExpiredPin() throws Exception {
XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.expired_pin);
ApplicationConfig appConfig = new ApplicationConfig(source);
assertTrue(appConfig.hasPerDomainConfigs());
// Check android.com.
NetworkSecurityConfig config = appConfig.getConfigForHostname("android.com");
PinSet pinSet = config.getPins();
assertFalse(pinSet.pins.isEmpty());
// Try connections.
SSLContext context = TestUtils.getSSLContext(source);
TestUtils.assertConnectionSucceeds(context, "android.com", 443);
TestUtils.assertUrlConnectionSucceeds(context, "android.com", 443);
}
public void testOverridesPins() throws Exception {
XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.override_pins);
ApplicationConfig appConfig = new ApplicationConfig(source);
assertTrue(appConfig.hasPerDomainConfigs());
// Check android.com.
NetworkSecurityConfig config = appConfig.getConfigForHostname("android.com");
PinSet pinSet = config.getPins();
assertFalse(pinSet.pins.isEmpty());
// Try connections.
SSLContext context = TestUtils.getSSLContext(source);
TestUtils.assertConnectionSucceeds(context, "android.com", 443);
TestUtils.assertUrlConnectionSucceeds(context, "android.com", 443);
}
public void testBadPin() throws Exception {
XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.bad_pin);
ApplicationConfig appConfig = new ApplicationConfig(source);
assertTrue(appConfig.hasPerDomainConfigs());
// Check android.com.
NetworkSecurityConfig config = appConfig.getConfigForHostname("android.com");
PinSet pinSet = config.getPins();
assertFalse(pinSet.pins.isEmpty());
// Try connections.
SSLContext context = TestUtils.getSSLContext(source);
TestUtils.assertConnectionFails(context, "android.com", 443);
TestUtils.assertUrlConnectionFails(context, "android.com", 443);
TestUtils.assertConnectionSucceeds(context, "google.com", 443);
}
public void testMultipleDomains() throws Exception {
XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.multiple_domains);
ApplicationConfig appConfig = new ApplicationConfig(source);
assertTrue(appConfig.hasPerDomainConfigs());
NetworkSecurityConfig config = appConfig.getConfigForHostname("android.com");
assertTrue(config.isCleartextTrafficPermitted());
assertFalse(config.isHstsEnforced());
assertFalse(config.getTrustAnchors().isEmpty());
PinSet pinSet = config.getPins();
assertTrue(pinSet.pins.isEmpty());
// Both android.com and google.com should use the same config
NetworkSecurityConfig other = appConfig.getConfigForHostname("google.com");
assertEquals(config, other);
// Try connections.
SSLContext context = TestUtils.getSSLContext(source);
TestUtils.assertConnectionSucceeds(context, "android.com", 443);
TestUtils.assertConnectionSucceeds(context, "google.com", 443);
TestUtils.assertConnectionFails(context, "developer.android.com", 443);
TestUtils.assertUrlConnectionSucceeds(context, "android.com", 443);
}
public void testMultipleDomainConfigs() throws Exception {
XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.multiple_configs);
ApplicationConfig appConfig = new ApplicationConfig(source);
assertTrue(appConfig.hasPerDomainConfigs());
// Should be two different config objects
NetworkSecurityConfig config = appConfig.getConfigForHostname("android.com");
NetworkSecurityConfig other = appConfig.getConfigForHostname("google.com");
MoreAsserts.assertNotEqual(config, other);
// Try connections.
SSLContext context = TestUtils.getSSLContext(source);
TestUtils.assertConnectionSucceeds(context, "android.com", 443);
TestUtils.assertConnectionSucceeds(context, "google.com", 443);
TestUtils.assertUrlConnectionSucceeds(context, "android.com", 443);
}
public void testIncludeSubdomains() throws Exception {
XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.subdomains);
ApplicationConfig appConfig = new ApplicationConfig(source);
assertTrue(appConfig.hasPerDomainConfigs());
// Try connections.
SSLContext context = TestUtils.getSSLContext(source);
TestUtils.assertConnectionSucceeds(context, "android.com", 443);
TestUtils.assertConnectionSucceeds(context, "developer.android.com", 443);
TestUtils.assertUrlConnectionSucceeds(context, "android.com", 443);
TestUtils.assertUrlConnectionSucceeds(context, "developer.android.com", 443);
TestUtils.assertConnectionFails(context, "google.com", 443);
}
public void testAttributes() throws Exception {
XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.attributes);
ApplicationConfig appConfig = new ApplicationConfig(source);
assertFalse(appConfig.hasPerDomainConfigs());
NetworkSecurityConfig config = appConfig.getConfigForHostname("");
assertTrue(config.isHstsEnforced());
assertFalse(config.isCleartextTrafficPermitted());
}
public void testResourcePemCertificateSource() throws Exception {
XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.resource_anchors_pem);
ApplicationConfig appConfig = new ApplicationConfig(source);
// Check android.com.
NetworkSecurityConfig config = appConfig.getConfigForHostname("android.com");
assertTrue(config.isCleartextTrafficPermitted());
assertFalse(config.isHstsEnforced());
assertEquals(2, config.getTrustAnchors().size());
// Try connections.
SSLContext context = TestUtils.getSSLContext(source);
TestUtils.assertConnectionSucceeds(context, "android.com", 443);
TestUtils.assertConnectionFails(context, "developer.android.com", 443);
TestUtils.assertUrlConnectionFails(context, "google.com", 443);
TestUtils.assertUrlConnectionSucceeds(context, "android.com", 443);
}
public void testResourceDerCertificateSource() throws Exception {
XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.resource_anchors_der);
ApplicationConfig appConfig = new ApplicationConfig(source);
// Check android.com.
NetworkSecurityConfig config = appConfig.getConfigForHostname("android.com");
assertTrue(config.isCleartextTrafficPermitted());
assertFalse(config.isHstsEnforced());
assertEquals(2, config.getTrustAnchors().size());
// Try connections.
SSLContext context = TestUtils.getSSLContext(source);
TestUtils.assertConnectionSucceeds(context, "android.com", 443);
TestUtils.assertConnectionFails(context, "developer.android.com", 443);
TestUtils.assertUrlConnectionFails(context, "google.com", 443);
TestUtils.assertUrlConnectionSucceeds(context, "android.com", 443);
}
public void testNestedDomainConfigs() throws Exception {
XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.nested_domains);
ApplicationConfig appConfig = new ApplicationConfig(source);
assertTrue(appConfig.hasPerDomainConfigs());
NetworkSecurityConfig parent = appConfig.getConfigForHostname("android.com");
NetworkSecurityConfig child = appConfig.getConfigForHostname("developer.android.com");
MoreAsserts.assertNotEqual(parent, child);
MoreAsserts.assertEmpty(parent.getPins().pins);
MoreAsserts.assertNotEmpty(child.getPins().pins);
// Check that the child inherited the cleartext value and anchors.
assertFalse(child.isCleartextTrafficPermitted());
MoreAsserts.assertNotEmpty(child.getTrustAnchors());
// Test connections.
SSLContext context = TestUtils.getSSLContext(source);
TestUtils.assertConnectionSucceeds(context, "android.com", 443);
TestUtils.assertConnectionSucceeds(context, "developer.android.com", 443);
}
public void testNestedDomainConfigsOverride() throws Exception {
XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.nested_domains_override);
ApplicationConfig appConfig = new ApplicationConfig(source);
assertTrue(appConfig.hasPerDomainConfigs());
NetworkSecurityConfig parent = appConfig.getConfigForHostname("android.com");
NetworkSecurityConfig child = appConfig.getConfigForHostname("developer.android.com");
MoreAsserts.assertNotEqual(parent, child);
assertTrue(parent.isCleartextTrafficPermitted());
assertFalse(child.isCleartextTrafficPermitted());
}
public void testDebugOverridesDisabled() throws Exception {
XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.debug_basic, false);
ApplicationConfig appConfig = new ApplicationConfig(source);
NetworkSecurityConfig config = appConfig.getConfigForHostname("");
Set<TrustAnchor> anchors = config.getTrustAnchors();
MoreAsserts.assertEmpty(anchors);
SSLContext context = TestUtils.getSSLContext(source);
TestUtils.assertConnectionFails(context, "android.com", 443);
TestUtils.assertConnectionFails(context, "developer.android.com", 443);
}
public void testBasicDebugOverrides() throws Exception {
XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.debug_basic, true);
ApplicationConfig appConfig = new ApplicationConfig(source);
NetworkSecurityConfig config = appConfig.getConfigForHostname("");
Set<TrustAnchor> anchors = config.getTrustAnchors();
MoreAsserts.assertNotEmpty(anchors);
for (TrustAnchor anchor : anchors) {
assertTrue(anchor.overridesPins);
}
SSLContext context = TestUtils.getSSLContext(source);
TestUtils.assertConnectionSucceeds(context, "android.com", 443);
TestUtils.assertConnectionSucceeds(context, "developer.android.com", 443);
}
public void testDebugOverridesWithDomain() throws Exception {
XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.debug_domain, true);
ApplicationConfig appConfig = new ApplicationConfig(source);
NetworkSecurityConfig config = appConfig.getConfigForHostname("android.com");
Set<TrustAnchor> anchors = config.getTrustAnchors();
boolean foundDebugCA = false;
for (TrustAnchor anchor : anchors) {
if (anchor.certificate.getSubjectDN().toString().equals(DEBUG_CA_SUBJ)) {
foundDebugCA = true;
assertTrue(anchor.overridesPins);
}
}
assertTrue(foundDebugCA);
SSLContext context = TestUtils.getSSLContext(source);
TestUtils.assertConnectionSucceeds(context, "android.com", 443);
TestUtils.assertConnectionSucceeds(context, "developer.android.com", 443);
}
public void testDebugInherit() throws Exception {
XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.debug_domain, true);
ApplicationConfig appConfig = new ApplicationConfig(source);
NetworkSecurityConfig config = appConfig.getConfigForHostname("android.com");
Set<TrustAnchor> anchors = config.getTrustAnchors();
boolean foundDebugCA = false;
for (TrustAnchor anchor : anchors) {
if (anchor.certificate.getSubjectDN().toString().equals(DEBUG_CA_SUBJ)) {
foundDebugCA = true;
assertTrue(anchor.overridesPins);
}
}
assertTrue(foundDebugCA);
assertTrue(anchors.size() > 1);
SSLContext context = TestUtils.getSSLContext(source);
TestUtils.assertConnectionSucceeds(context, "android.com", 443);
TestUtils.assertConnectionSucceeds(context, "developer.android.com", 443);
}
private void testBadConfig(int configId) throws Exception {
try {
XmlConfigSource source = new XmlConfigSource(getContext(), configId);
ApplicationConfig appConfig = new ApplicationConfig(source);
appConfig.getConfigForHostname("android.com");
fail("Bad config " + getContext().getResources().getResourceName(configId)
+ " did not fail to parse");
} catch (RuntimeException e) {
MoreAsserts.assertAssignableFrom(XmlConfigSource.ParserException.class,
e.getCause());
}
}
public void testBadConfig0() throws Exception {
testBadConfig(R.xml.bad_config0);
}
public void testBadConfig1() throws Exception {
testBadConfig(R.xml.bad_config1);
}
public void testBadConfig2() throws Exception {
testBadConfig(R.xml.bad_config2);
}
public void testBadConfig3() throws Exception {
testBadConfig(R.xml.bad_config3);
}
public void testBadConfig4() throws Exception {
testBadConfig(R.xml.bad_config4);
}
public void testBadConfig5() throws Exception {
testBadConfig(R.xml.bad_config4);
}
public void testTrustManagerKeystore() throws Exception {
XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.bad_pin, true);
ApplicationConfig appConfig = new ApplicationConfig(source);
Provider provider = new NetworkSecurityConfigProvider();
TrustManagerFactory tmf =
TrustManagerFactory.getInstance("PKIX", provider);
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(null);
int i = 0;
for (X509Certificate cert : SystemCertificateSource.getInstance().getCertificates()) {
keystore.setEntry(String.valueOf(i),
new KeyStore.TrustedCertificateEntry(cert),
null);
i++;
}
tmf.init(keystore);
TrustManager[] tms = tmf.getTrustManagers();
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tms, null);
TestUtils.assertConnectionSucceeds(context, "android.com" , 443);
}
public void testDebugDedup() throws Exception {
XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.override_dedup, true);
ApplicationConfig appConfig = new ApplicationConfig(source);
assertTrue(appConfig.hasPerDomainConfigs());
// Check android.com.
NetworkSecurityConfig config = appConfig.getConfigForHostname("android.com");
PinSet pinSet = config.getPins();
assertFalse(pinSet.pins.isEmpty());
// Check that all TrustAnchors come from the override pins debug source.
for (TrustAnchor anchor : config.getTrustAnchors()) {
assertTrue(anchor.overridesPins);
}
// Try connections.
SSLContext context = TestUtils.getSSLContext(source);
TestUtils.assertConnectionSucceeds(context, "android.com", 443);
TestUtils.assertUrlConnectionSucceeds(context, "android.com", 443);
}
public void testExtraDebugResource() throws Exception {
XmlConfigSource source =
new XmlConfigSource(getContext(), R.xml.extra_debug_resource, true);
ApplicationConfig appConfig = new ApplicationConfig(source);
assertFalse(appConfig.hasPerDomainConfigs());
NetworkSecurityConfig config = appConfig.getConfigForHostname("");
MoreAsserts.assertNotEmpty(config.getTrustAnchors());
// Check that the _debug file is ignored if debug is false.
source = new XmlConfigSource(getContext(), R.xml.extra_debug_resource, false);
appConfig = new ApplicationConfig(source);
assertFalse(appConfig.hasPerDomainConfigs());
config = appConfig.getConfigForHostname("");
MoreAsserts.assertEmpty(config.getTrustAnchors());
}
public void testExtraDebugResourceIgnored() throws Exception {
// Verify that parsing the extra debug config resource fails only when debugging is true.
XmlConfigSource source =
new XmlConfigSource(getContext(), R.xml.bad_extra_debug_resource, false);
ApplicationConfig appConfig = new ApplicationConfig(source);
// Force parsing the config file.
appConfig.getConfigForHostname("");
source = new XmlConfigSource(getContext(), R.xml.bad_extra_debug_resource, true);
appConfig = new ApplicationConfig(source);
try {
appConfig.getConfigForHostname("");
fail("Bad extra debug resource did not fail to parse");
} catch (RuntimeException expected) {
}
}
public void testDomainWhitespaceTrimming() throws Exception {
XmlConfigSource source =
new XmlConfigSource(getContext(), R.xml.domain_whitespace, false);
ApplicationConfig appConfig = new ApplicationConfig(source);
NetworkSecurityConfig defaultConfig = appConfig.getConfigForHostname("");
MoreAsserts.assertNotEqual(defaultConfig, appConfig.getConfigForHostname("developer.android.com"));
MoreAsserts.assertNotEqual(defaultConfig, appConfig.getConfigForHostname("android.com"));
SSLContext context = TestUtils.getSSLContext(source);
TestUtils.assertConnectionSucceeds(context, "android.com", 443);
TestUtils.assertConnectionSucceeds(context, "developer.android.com", 443);
}
}
|
package org.hisp.dhis.light.interpretation.action;
/*
* Copyright (c) 2004-2015, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import org.hisp.dhis.interpretation.Interpretation;
import org.hisp.dhis.interpretation.InterpretationService;
import com.opensymphony.xwork2.Action;
/**
* @author Paul Mark Castillo
*/
public class GetInterpretation
implements Action
{
// -------------------------------------------------------------------------
// Dependencies
// -------------------------------------------------------------------------
private InterpretationService interpretationService;
public void setInterpretationService( InterpretationService interpretationService )
{
this.interpretationService = interpretationService;
}
// -------------------------------------------------------------------------
// Input & Output
// -------------------------------------------------------------------------
private int interpretationId;
public int getInterpretationId()
{
return interpretationId;
}
public void setInterpretationId( int interpretationId )
{
this.interpretationId = interpretationId;
}
private Interpretation interpretation;
public Interpretation getInterpretation()
{
return interpretation;
}
public void setInterpretation( Interpretation interpretation )
{
this.interpretation = interpretation;
}
// -------------------------------------------------------------------------
// Action Implementation
// -------------------------------------------------------------------------
@Override
public String execute()
throws Exception
{
setInterpretation( interpretationService.getInterpretation( interpretationId ) );
return SUCCESS;
}
}
|
package com.sanki.mywanandroid.ui.activity;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.SuppressLint;
import android.app.ActivityOptions;
import android.content.Intent;
import android.widget.TextView;
import com.sanki.mywanandroid.R;
import com.sanki.mywanandroid.app.ActivityCollector;
import com.sanki.mywanandroid.base.BaseActivity;
import com.sanki.mywanandroid.utils.DensityUtil;
public class SplashActivity extends BaseActivity {
private TextView tvLogo;
@Override
public int getLayoutId() {
return R.layout.activity_splash;
}
@Override
public void createPresenter() {
}
@Override
public void init() {
tvLogo=findViewById(R.id.tv_logo);
ActivityCollector.getInstance().addActivity(this);
tvLogo.animate().scaleX(0.5f).scaleY(0.5f).translationY(-DensityUtil.dip2px(this,150)).setStartDelay(1000)
.setDuration(600)
.setListener(new AnimatorListenerAdapter() {
@SuppressLint("NewApi")
@Override
public void onAnimationEnd(Animator animation) {
Intent intent = new Intent(SplashActivity.this, MainActivity.class);
startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(SplashActivity.this,tvLogo,"logo").toBundle());
// finish();
}
}).start();
}
}
|
package com.marekhakala.mynomadlifeapp.UI.Adapter;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.net.Uri;
import android.view.View;
import android.view.ViewGroup;
import com.bumptech.glide.Glide;
import com.marekhakala.mynomadlifeapp.DataModel.CityPlaceToWorkEntity;
import com.marekhakala.mynomadlifeapp.R;
import com.marekhakala.mynomadlifeapp.UI.Component.OnCityPlaceToWorkItemClickListener;
import java.util.List;
public class CityPlacesToWorkDSRecyclerViewAdapter extends AbstractDataSourceRecyclerViewAdapter<CityPlaceToWorkEntity, CityPlacesToWorkViewViewHolder> {
private OnCityPlaceToWorkItemClickListener listener = null;
public CityPlacesToWorkDSRecyclerViewAdapter(Context context, List<CityPlaceToWorkEntity> results) {
super(context, results);
}
public void setListener(OnCityPlaceToWorkItemClickListener listener) {
this.listener = listener;
}
public CityPlacesToWorkViewViewHolder onCreateDataSourceViewHolder(ViewGroup viewGroup, int viewType) {
View view = inflater.inflate(R.layout.item_city_place_to_work, viewGroup, false);
return new CityPlacesToWorkViewViewHolder(view);
}
@Override
public void onBindDataSourceViewHolder(CityPlacesToWorkViewViewHolder holder, int position) {
final CityPlaceToWorkEntity cityPlaceToWorkEntity = results.get(position);
Glide.with(context)
.load(cityPlaceToWorkEntity.getImageUrl())
.placeholder(R.drawable.placeholder_loading)
.centerCrop()
.crossFade()
.into(holder.image);
holder.image.setColorFilter(Color.argb(90, 0, 0, 0), PorterDuff.Mode.DARKEN);
holder.nameText.setText(cityPlaceToWorkEntity.getName());
holder.subNameText.setText(cityPlaceToWorkEntity.getSubName());
holder.webButton.setOnClickListener(view -> {
getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(cityPlaceToWorkEntity.getDataUrl())));
});
holder.distanceText.setText(cityPlaceToWorkEntity.getDistance());
holder.navigationFab.setOnClickListener(view -> {
if(listener != null)
listener.onClicked(cityPlaceToWorkEntity, view, position);
});
}
@Override
public void removeItem(CityPlaceToWorkEntity item) {}
}
|
package org.smartframework.cloud.api.core.annotation;
import org.smartframework.cloud.api.core.annotation.enums.SignType;
import java.lang.annotation.*;
/**
* 接口数据安全(加解密、签名)注解
*
* @author collin
* @date 2021-03-28
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequireDataSecurity {
/**
* 请求参数是否需要解密
*/
boolean requestDecrypt() default true;
/**
* 响应信息是否需要加密
*/
boolean responseEncrypt() default true;
/**
* 签名控制(默认:请求参数需要验签,且响应参数需要签名)
*/
SignType sign() default SignType.ALL;
}
|
/*
* Copyright (c) 1998-2018 John Caron and University Corporation for Atmospheric Research/Unidata
* See LICENSE for license information.
*/
package ucar.nc2.iosp.misc;
import ucar.ma2.*;
import ucar.nc2.*;
import ucar.nc2.constants.AxisType;
import ucar.nc2.constants.CDM;
import ucar.nc2.util.CancelTask;
import ucar.unidata.io.RandomAccessFile;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* National Lightning Detection Network (NLDN)
*
* @author caron
* @see "http://www.unidata.ucar.edu/data/lightning.html"
* @since Nov 19, 2008
*/
public class Nldn extends AbstractLightningIOSP {
/*
* Field Example
* -------------------+---------------------
* date/time (msec) 09/22/93 10:22:33.334
* latitude 47.33
* longitude -87.116
* polarity/signal strength -188.7
* multiplicity 6
* ellipse angle 174
* semi-major axis 6.0
* eccentricity 2.0
* chi-square 1.0
*
* The specifics for the binary NLDN data record contained in the IDD is:
*
* Size Name Description
* --------+---------+----------------------------------------------------
* char[4] NLDN 'NLDN' marks the start of record
* int[4] tsec time in seconds since 1970
* int[4] nsec nanoseconds since tsec (seems to be thousandths)
* int[4] lat latitude [deg] * 1000
* int[4] lon longitude [deg] * 1000
* short[2] fill padding
* short[2] sgnl signal strength * 10 [150 NLDN measures ~= 30 kAmps]
* short[2] fill padding
* short[2] mult multiplicity [#strokes per flash]
* char[1] fill padding
* char[1] semimaj semi-major axis
* char[1] eccent eccentricity
* char[1] angle ellipse angle
* char[1] chisqr chi-square
*
*/
/**
* The magic mushroom
*/
private static final String MAGIC = "NLDN";
/**
* The structure members
*/
private StructureMembers sm;
/**
* The time in seconds variable name
*/
private static final String TSEC = "tsec";
/**
* The time in nanoseconds from TSEC variable name
*/
private static final String NSEC = "nsec";
/**
* The chi squared variable name
*/
private static final String CHISQR = "chisqr";
/**
* The fill variable name
*/
private static final String FILL = "fill";
/**
* header size
*/
private static final int recHeader = 84;
/**
* record size
*/
private static final int recSize = 28;
/**
* Check if this is a valid file for this IOServiceProvider.
* You must make this method thread safe, ie dont keep any state.
*
* @param raf RandomAccessFile
* @return true if valid.
* @throws IOException if read error
*/
public boolean isValidFile(RandomAccessFile raf) throws IOException {
raf.seek(0);
String test = raf.readString(MAGIC.length());
return test.equals(MAGIC);
}
/**
* Get a unique id for this file type.
*
* @return registered id of the file type
* @see "http://www.unidata.ucar.edu/software/netcdf-java/formats/FileTypes.html"
*/
public String getFileTypeId() {
return "NLDN";
}
/**
* Get a human-readable description for this file type.
*
* @return description of the file type
* @see "http://www.unidata.ucar.edu/software/netcdf-java/formats/FileTypes.html"
*/
public String getFileTypeDescription() {
return "National Lightning Detection Network";
}
/**
* Open existing file, and populate ncfile with it. This method is only
* called by the NetcdfFile constructor on itself. The provided NetcdfFile
* object will be empty except for the location String and the
* IOServiceProvider associated with this NetcdfFile object.
*
* @param raf the file to work on, it has already passed the
* isValidFile() test.
* @param ncfile add objects to this empty NetcdfFile
* @param cancelTask used to monitor user cancellation; may be null.
* @throws IOException if read error
*/
public void open(RandomAccessFile raf, NetcdfFile ncfile, CancelTask cancelTask) throws IOException {
super.open(raf, ncfile, cancelTask);
Structure seq = new Sequence(ncfile, null, null, RECORD);
ncfile.addVariable(null, seq);
/*
* makeLightningVariable(NetcdfFile ncfile, Group group,
* Structure seq, String name,
* DataType dataType, String dims,
* String longName, String cfName,
* String units, AxisType type) {
*/
Variable v = makeLightningVariable(ncfile, null, seq, TSEC, DataType.INT, "", "time of stroke", null,
secondsSince1970, AxisType.Time);
seq.addMemberVariable(v);
v = makeLightningVariable(ncfile, null, seq, "nsec", DataType.INT, "", "nanoseconds since tsec", null, "1.0e-9 s",
null);
seq.addMemberVariable(v);
v = makeLightningVariable(ncfile, null, seq, LAT, DataType.INT, "", "latitude", "latitude", CDM.LAT_UNITS,
AxisType.Lat);
v.addAttribute(new Attribute(CDM.SCALE_FACTOR, 1.0e-3f));
seq.addMemberVariable(v);
v = makeLightningVariable(ncfile, null, seq, LON, DataType.INT, "", "longitude", "longitude", CDM.LON_UNITS,
AxisType.Lon);
v.addAttribute(new Attribute(CDM.SCALE_FACTOR, 1.0e-3f));
seq.addMemberVariable(v);
v = makeLightningVariable(ncfile, null, seq, SIGNAL, DataType.SHORT, "",
"signal strength/polarity [150 NLDN measures ~= 30 kAmps]", null, "", null);
v.addAttribute(new Attribute(CDM.SCALE_FACTOR, 1.0e-1f));
seq.addMemberVariable(v);
v = makeLightningVariable(ncfile, null, seq, MULTIPLICITY, DataType.BYTE, "", "multiplicity [#strokes per flash]",
null, "", null);
seq.addMemberVariable(v);
v = new Variable(ncfile, null, seq, FILL);
v.setDataType(DataType.BYTE);
v.setDimensions("");
seq.addMemberVariable(v);
v = makeLightningVariable(ncfile, null, seq, MAJOR_AXIS, DataType.BYTE, "", "error ellipse semi-major axis", null,
"", null);
seq.addMemberVariable(v);
v = makeLightningVariable(ncfile, null, seq, ECCENTRICITY, DataType.BYTE, "", "error ellipse eccentricity ", null,
"", null);
seq.addMemberVariable(v);
v = makeLightningVariable(ncfile, null, seq, ELLIPSE_ANGLE, DataType.BYTE, "",
"error ellipse axis angle of orientation ", null, "degrees", null);
seq.addMemberVariable(v);
v = makeLightningVariable(ncfile, null, seq, CHISQR, DataType.BYTE, "", "chi-squared", null, "", null);
seq.addMemberVariable(v);
addLightningGlobalAttributes(ncfile);
ncfile.finish();
sm = seq.makeStructureMembers();
sm.findMember(TSEC).setDataParam(0);
sm.findMember(NSEC).setDataParam(4);
sm.findMember(LAT).setDataParam(8);
sm.findMember(LON).setDataParam(12);
sm.findMember(SIGNAL).setDataParam(18);
sm.findMember(MULTIPLICITY).setDataParam(22);
sm.findMember(FILL).setDataParam(23);
sm.findMember(MAJOR_AXIS).setDataParam(24);
sm.findMember(ECCENTRICITY).setDataParam(25);
sm.findMember(ELLIPSE_ANGLE).setDataParam(26);
sm.findMember(CHISQR).setDataParam(27);
sm.setStructureSize(recSize);
}
/**
* Add the global attributes.
*
* @param ncfile the file to add to
*/
protected void addLightningGlobalAttributes(NetcdfFile ncfile) {
super.addLightningGlobalAttributes(ncfile);
ncfile.addAttribute(null, new Attribute("title", "NLDN Lightning Data"));
ncfile.addAttribute(null, new Attribute(CDM.CONVENTIONS, "NLDN-CDM"));
}
/*
* The specifics for the binary NLDN data record contained in the IDD is:
*
* Size Name Description
* --------+---------+----------------------------------------------------
* char[4] NLDN 'NLDN' marks the start of record
* int[4] tsec time in seconds since 1970
* int[4] nsec nanoseconds since tsec (seems to be thousandths)
* int[4] lat latitude [deg] * 1000
* int[4] lon longitude [deg] * 1000
* short[2] fill padding
* short[2] sgnl signal strength * 10 [150 NLDN measures ~= 30 kAmps]
* short[2] fill padding
* short[2] mult multiplicity [#strokes per flash]
* char[1] fill padding
* char[1] semimaj semi-major axis
* char[1] eccent eccentricity
* char[1] angle ellipse angle
* char[1] chisqr chi-square
*/
/*
* public Array readData(Variable v2, Section section) throws IOException, InvalidRangeException {
* Range r = section.getRange(0);
* int nrecs = r.length();
* byte[] bb = new byte[nrecs * recSize];
*
* int pos = 0;
* Range.Iterator iter = r.getIterator();
* while (iter.hasNext()) {
* int index = iter.next();
* raf.seek(recHeader + index * recSize);
* raf.read(bb, pos, recSize);
* pos += recSize;
* }
*
* return new ArrayStructureBB(sm, new int[]{nrecs}, ByteBuffer.wrap(bb), 0);
* }
*/
/**
* Read data from a top level Variable and return a memory resident Array.
* This Array has the same element type as the Variable, and the requested shape.
*
* @param v2 a top-level Variable
* @param section the section of data to read.
* There must be a Range for each Dimension in the variable, in order.
* Note: no nulls allowed. IOSP may not modify.
* @return the requested data in a memory-resident Array
* @throws IOException if read error
* @see ucar.ma2.Range
*/
public Array readData(Variable v2, Section section) throws IOException {
return new ArraySequence(sm, new SeqIter(), nelems);
}
private int nelems = -1;
/**
* Get the structure iterator
*
* @param s the Structure
* @param bufferSize the buffersize
* @return the data iterator
* @throws java.io.IOException if problem reading data
*/
public StructureDataIterator getStructureIterator(Structure s, int bufferSize) throws java.io.IOException {
return new SeqIter();
}
/**
* Sequence Iterator
*
* @author Unidata Development Team
*/
private class SeqIter implements StructureDataIterator {
/**
* done?
*/
private int done = 0;
/**
* number bytes already read
*/
private int alreadyRead = 0;
/**
* next index
*/
private int nextIndex = 0;
/**
* the wrapped asbb
*/
private ArrayStructureBB asbb = null;
/**
* total bytes
*/
private long totalBytes;
/**
* bytes read
*/
private long bytesRead;
/**
* Create a new one
*
* @throws IOException problem reading the file
*/
SeqIter() throws IOException {
totalBytes = (int) raf.length();
raf.seek(0);
}
@Override
public StructureDataIterator reset() {
done = 0;
alreadyRead = 0;
bytesRead = 0;
nextIndex = 0;
try {
raf.seek(0);
} catch (IOException e) {
throw new RuntimeException(e);
}
return this;
}
@Override
public boolean hasNext() throws IOException {
return done < alreadyRead || readHeader();
}
@Override
public StructureData next() {
done++;
return asbb.getStructureData(nextIndex++);
}
/**
* Read the header
*
* @return true if okay
* @throws IOException problem reading file
*/
private boolean readHeader() throws IOException {
if ((bytesRead + recHeader) > totalBytes) {
nelems = done; // record the number of elements for next time
return false;
}
byte[] b = new byte[recHeader];
raf.readFully(b);
bytesRead += recHeader;
ByteBuffer bb = ByteBuffer.wrap(b);
int count = bb.getInt(8);
if (count == 0) {
return readHeader();
}
if ((bytesRead + count * recSize) > totalBytes) {
return false;
}
byte[] data = new byte[count * recSize];
raf.readFully(data);
bytesRead += count * recSize;
alreadyRead += count;
nextIndex = 0;
ByteBuffer bbdata = ByteBuffer.wrap(data);
asbb = new ArrayStructureBB(sm, new int[] {count}, bbdata, 0);
return true;
}
@Override
public int getCurrentRecno() {
return done - 1;
}
}
// this is thye start of a buffererd iterator
/*
* private class MySDIter implements StructureDataIterator {
* private int done = 0;
* private int readStart = 0;
* private int recsAlreadyRead = 0;
* private int readAtaTime;
* private ArrayStructureBB asbb = null;
*
* private int recsLeft;
* private int recsDone;
*
* MySDIter(int bufferSize) throws IOException {
* setBufferSize( bufferSize);
* recsLeft = (int) raf.length() / recSize;
* recsDone = 0;
* }
*
* public boolean hasNext() {
* if (done < recsAlreadyRead) return true;
* return (recsLeft > 0);
* }
*
* public StructureDataIterator reset() {
* done = 0;
* readStart = 0;
* readRead = 0;
* return this;
* }
*
* public StructureData next() throws IOException {
* if (done >= readStart) {
* readNextBuffer();
* }
* done++;
* return asbb.getStructureData( readRead++);
* }
*
* private void readNextBuffer() throws IOException {
* bytesLeft = (int)(raf.length() - raf.getFilePointer());
* int recsLeft = bytesLeft / recSize;
* int recsToRead = Math.min(recsLeft, readAtaTime);
*
* byte[] bb = new byte[recsToRead * recSize];
* ByteBuffer.wrap(bb);
* asbb = new ArrayStructureBB(sm, new int[]{nrecs}, bb, 0);
*
* recsAlreadyRead += recsToRead;
* readRead = 0;
* }
*
* public void setBufferSize(int bytes) {
* if (done > 0) return; // too late
* if (bytes <= 0)
* bytes = defaultBufferSize;
* readAtaTime = Math.max( 10, bytes / recSize);
* }
* }
*/
}
|
package com.dieam.reactnativepushnotification.modules;
import android.app.IntentService;
import android.content.Intent;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
public class RNPushNotificationRegistrationService extends IntentService {
private static final String TAG = "RNPushNotification";
public RNPushNotificationRegistrationService() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
String SenderID = intent.getStringExtra("senderID");
try {
InstanceID instanceID = InstanceID.getInstance(this);
String token = instanceID.getToken(SenderID,
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
sendRegistrationToken(token);
} catch (Exception e) {
e.printStackTrace();
}
}
private void sendRegistrationToken(String token) {
Intent intent = new Intent(this.getPackageName() + ".RNPushNotificationRegisteredToken");
intent.putExtra("token", token);
sendBroadcast(intent);
}
}
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
end_comment
begin_package
DECL|package|org.apache.camel.language
package|package
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|language
package|;
end_package
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|ContextTestSupport
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|builder
operator|.
name|RouteBuilder
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Test
import|;
end_import
begin_class
DECL|class|BeanLanguageOGNLTest
specifier|public
class|class
name|BeanLanguageOGNLTest
extends|extends
name|ContextTestSupport
block|{
annotation|@
name|Test
DECL|method|testBeanLanguageOGNL ()
specifier|public
name|void
name|testBeanLanguageOGNL
parameter_list|()
throws|throws
name|Exception
block|{
name|String
name|reply
init|=
name|template
operator|.
name|requestBody
argument_list|(
literal|"direct:start"
argument_list|,
literal|"World"
argument_list|,
name|String
operator|.
name|class
argument_list|)
decl_stmt|;
name|assertEquals
argument_list|(
literal|"Hello World"
argument_list|,
name|reply
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|createRouteBuilder ()
specifier|protected
name|RouteBuilder
name|createRouteBuilder
parameter_list|()
throws|throws
name|Exception
block|{
return|return
operator|new
name|RouteBuilder
argument_list|()
block|{
annotation|@
name|Override
specifier|public
name|void
name|configure
parameter_list|()
throws|throws
name|Exception
block|{
name|from
argument_list|(
literal|"direct:start"
argument_list|)
operator|.
name|transform
argument_list|()
operator|.
name|method
argument_list|(
name|MyReallyCoolBean
operator|.
name|class
argument_list|,
literal|"getOther.greet"
argument_list|)
expr_stmt|;
block|}
block|}
return|;
block|}
DECL|class|MyReallyCoolBean
specifier|public
specifier|static
class|class
name|MyReallyCoolBean
block|{
DECL|field|other
specifier|private
name|MyOtherReallyCoolBean
name|other
init|=
operator|new
name|MyOtherReallyCoolBean
argument_list|()
decl_stmt|;
DECL|method|getOther ()
specifier|public
name|MyOtherReallyCoolBean
name|getOther
parameter_list|()
block|{
return|return
name|other
return|;
block|}
block|}
DECL|class|MyOtherReallyCoolBean
specifier|public
specifier|static
class|class
name|MyOtherReallyCoolBean
block|{
DECL|method|greet (String name)
specifier|public
name|String
name|greet
parameter_list|(
name|String
name|name
parameter_list|)
block|{
return|return
literal|"Hello "
operator|+
name|name
return|;
block|}
block|}
block|}
end_class
end_unit
|
/*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.server.api.marshalling.json;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonSerialize(using = StringContentSerializer.class)
public class StringContentMap implements Map<String, Object>, StringContent {
private String content;
public StringContentMap() {
}
public StringContentMap(String content) {
this.content = content;
}
@Override
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "StringContainer [content=" + content + "]";
}
@Override
public int size() {
throw new UnsupportedOperationException();
}
@Override
public boolean isEmpty() {
throw new UnsupportedOperationException();
}
@Override
public boolean containsKey(Object key) {
throw new UnsupportedOperationException();
}
@Override
public boolean containsValue(Object value) {
throw new UnsupportedOperationException();
}
@Override
public Object get(Object key) {
throw new UnsupportedOperationException();
}
@Override
public Object put(String key, Object value) {
throw new UnsupportedOperationException();
}
@Override
public Object remove(Object key) {
throw new UnsupportedOperationException();
}
@Override
public void putAll(Map<? extends String, ? extends Object> m) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public Set<String> keySet() {
throw new UnsupportedOperationException();
}
@Override
public Collection<Object> values() {
throw new UnsupportedOperationException();
}
@Override
public Set<Entry<String, Object>> entrySet() {
throw new UnsupportedOperationException();
}
}
|
/*-
* ============LICENSE_START=======================================================
* OPENECOMP - MSO
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.openecomp.mso.adapters.nwrest;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;
import org.jboss.resteasy.annotations.providers.NoJackson;
import org.openecomp.mso.openstack.exceptions.MsoExceptionCategory;
@XmlRootElement(name = "updateNetworkError")
@NoJackson
public class UpdateNetworkError extends NetworkExceptionResponse implements Serializable {
private static final long serialVersionUID = 46820809807914392L;
public UpdateNetworkError() {
super("");
}
public UpdateNetworkError(String message) {
super(message);
}
public UpdateNetworkError(String message, MsoExceptionCategory category, boolean unused, String messageid) {
super(message, category, unused, messageid);
}
}
|
/*
* Copyright 2002-2013 Drew Noakes
*
* 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.
*
* More information about this project is available at:
*
* http://drewnoakes.com/code/exif/
* http://code.google.com/p/metadata-extractor/
*/
package com.drew.metadata.exif;
import com.drew.imaging.jpeg.JpegSegmentMetadataReader;
import com.drew.imaging.jpeg.JpegSegmentType;
import com.drew.imaging.tiff.TiffProcessingException;
import com.drew.imaging.tiff.TiffReader;
import com.drew.lang.ByteArrayReader;
import com.drew.lang.RandomAccessReader;
import com.drew.lang.Rational;
import com.drew.lang.annotations.NotNull;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.makernotes.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* Decodes Exif binary data, populating a {@link Metadata} object with tag values in {@link ExifSubIFDDirectory},
* {@link ExifThumbnailDirectory}, {@link ExifInteropDirectory}, {@link GpsDirectory} and one of the many camera makernote directories.
*
* @author Drew Noakes http://drewnoakes.com
*/
public class ExifReader implements JpegSegmentMetadataReader
{
/** The number of bytes used per format descriptor. */
@NotNull
private static final int[] BYTES_PER_FORMAT = { 0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8 };
/** The number of formats known. */
private static final int MAX_FORMAT_CODE = 12;
// Format types
// TODO use an enum for these?
/** An 8-bit unsigned integer. */
private static final int FMT_BYTE = 1;
/** A fixed-length character string. */
private static final int FMT_STRING = 2;
/** An unsigned 16-bit integer. */
private static final int FMT_USHORT = 3;
/** An unsigned 32-bit integer. */
private static final int FMT_ULONG = 4;
private static final int FMT_URATIONAL = 5;
/** An 8-bit signed integer. */
private static final int FMT_SBYTE = 6;
private static final int FMT_UNDEFINED = 7;
/** A signed 16-bit integer. */
private static final int FMT_SSHORT = 8;
/** A signed 32-bit integer. */
private static final int FMT_SLONG = 9;
private static final int FMT_SRATIONAL = 10;
/** A 32-bit floating point number. */
private static final int FMT_SINGLE = 11;
/** A 64-bit floating point number. */
private static final int FMT_DOUBLE = 12;
/**
* The offset at which the TIFF data actually starts. This may be necessary when, for example, processing
* JPEG Exif data from APP0 which has a 6-byte preamble before starting the TIFF data.
*/
private static final String JPEG_EXIF_SEGMENT_PREAMBLE = "Exif\0\0";
private boolean _storeThumbnailBytes = true;
public boolean isStoreThumbnailBytes()
{
return _storeThumbnailBytes;
}
public void setStoreThumbnailBytes(boolean storeThumbnailBytes)
{
_storeThumbnailBytes = storeThumbnailBytes;
}
@NotNull
public Iterable<JpegSegmentType> getSegmentTypes()
{
return Arrays.asList(JpegSegmentType.APP1);
}
public boolean canProcess(@NotNull final byte[] segmentBytes, @NotNull final JpegSegmentType segmentType)
{
return segmentBytes.length >= JPEG_EXIF_SEGMENT_PREAMBLE.length() && new String(segmentBytes, 0, JPEG_EXIF_SEGMENT_PREAMBLE.length()).equalsIgnoreCase(JPEG_EXIF_SEGMENT_PREAMBLE);
}
public void extract(@NotNull final byte[] segmentBytes, @NotNull final Metadata metadata, @NotNull final JpegSegmentType segmentType)
{
if (segmentBytes == null)
throw new NullPointerException("segmentBytes cannot be null");
if (metadata == null)
throw new NullPointerException("metadata cannot be null");
if (segmentType == null)
throw new NullPointerException("segmentType cannot be null");
try {
ByteArrayReader reader = new ByteArrayReader(segmentBytes);
//
// Check for the header preamble
//
try {
if (!reader.getString(0, JPEG_EXIF_SEGMENT_PREAMBLE.length()).equals(JPEG_EXIF_SEGMENT_PREAMBLE)) {
// TODO what do to with this error state?
System.err.println("Invalid JPEG Exif segment preamble");
return;
}
} catch (IOException e) {
// TODO what do to with this error state?
e.printStackTrace(System.err);
return;
}
//
// Read the TIFF-formatted Exif data
//
new TiffReader().processTiff(
reader,
new ExifTiffHandler(metadata, _storeThumbnailBytes),
JPEG_EXIF_SEGMENT_PREAMBLE.length()
);
} catch (TiffProcessingException e) {
// TODO what do to with this error state?
e.printStackTrace(System.err);
} catch (IOException e) {
// TODO what do to with this error state?
e.printStackTrace(System.err);
}
}
/**
* Performs the Exif data extraction on a TIFF/RAW, adding found values to the specified
* instance of {@link Metadata}.
*
* @param reader The {@link com.drew.lang.RandomAccessReader} from which TIFF data should be read.
* @param metadata The Metadata object into which extracted values should be merged.
*/
@Deprecated
public void extractTiff(@NotNull final RandomAccessReader reader, @NotNull final Metadata metadata)
{
final ExifIFD0Directory directory = metadata.getOrCreateDirectory(ExifIFD0Directory.class);
try {
extractTiff(reader, metadata, directory, 0);
} catch (IOException e) {
directory.addError("IO problem: " + e.getMessage());
}
}
@Deprecated
private static void extractTiff(@NotNull final RandomAccessReader reader,
@NotNull final Metadata metadata,
@NotNull final Directory firstDirectory,
final int tiffHeaderOffset) throws IOException
{
// this should be either "MM" or "II"
String byteOrderIdentifier = reader.getString(tiffHeaderOffset, 2);
if ("MM".equals(byteOrderIdentifier)) {
reader.setMotorolaByteOrder(true);
} else if ("II".equals(byteOrderIdentifier)) {
reader.setMotorolaByteOrder(false);
} else {
firstDirectory.addError("Unclear distinction between Motorola/Intel byte ordering: " + byteOrderIdentifier);
return;
}
// Check the next two values for correctness.
final int tiffMarker = reader.getUInt16(2 + tiffHeaderOffset);
final int standardTiffMarker = 0x002A;
final int olympusRawTiffMarker = 0x4F52; // for ORF files
final int panasonicRawTiffMarker = 0x0055; // for RW2 files
if (tiffMarker != standardTiffMarker && tiffMarker != olympusRawTiffMarker && tiffMarker != panasonicRawTiffMarker) {
firstDirectory.addError("Unexpected TIFF marker after byte order identifier: 0x" + Integer.toHexString(tiffMarker));
return;
}
int firstIfdOffset = reader.getInt32(4 + tiffHeaderOffset) + tiffHeaderOffset;
// David Ekholm sent a digital camera image that has this problem
// TODO getLength should be avoided as it causes RandomAccessStreamReader to read to the end of the stream
if (firstIfdOffset >= reader.getLength() - 1) {
firstDirectory.addError("First Exif directory offset is beyond end of Exif data segment");
// First directory normally starts 14 bytes in -- try it here and catch another error in the worst case
firstIfdOffset = 14;
}
Set<Integer> processedIfdOffsets = new HashSet<Integer>();
processIFD(firstDirectory, processedIfdOffsets, firstIfdOffset, tiffHeaderOffset, metadata, reader);
// after the extraction process, if we have the correct tags, we may be able to store thumbnail information
ExifThumbnailDirectory thumbnailDirectory = metadata.getDirectory(ExifThumbnailDirectory.class);
if (thumbnailDirectory != null && thumbnailDirectory.containsTag(ExifThumbnailDirectory.TAG_THUMBNAIL_COMPRESSION)) {
Integer offset = thumbnailDirectory.getInteger(ExifThumbnailDirectory.TAG_THUMBNAIL_OFFSET);
Integer length = thumbnailDirectory.getInteger(ExifThumbnailDirectory.TAG_THUMBNAIL_LENGTH);
if (offset != null && length != null) {
try {
byte[] thumbnailData = reader.getBytes(tiffHeaderOffset + offset, length);
thumbnailDirectory.setThumbnailData(thumbnailData);
} catch (IOException ex) {
firstDirectory.addError("Invalid thumbnail data specification: " + ex.getMessage());
}
}
}
}
/**
* Processes a TIFF IFD, storing tag values in the specified {@link Directory}.
* <p/>
* IFD Header:
* <ul>
* <li><b>2 bytes</b> number of tags</li>
* </ul>
* Tag structure:
* <ul>
* <li><b>2 bytes</b> tag type</li>
* <li><b>2 bytes</b> format code (values 1 to 12, inclusive)</li>
* <li><b>4 bytes</b> component count</li>
* <li><b>4 bytes</b> inline value, or offset pointer if too large to fit in four bytes</li>
* </ul>
*
* @param directory the {@link Directory} to write extracted values into
* @param processedIfdOffsets the set of visited IFD offsets, to avoid revisiting the same IFD in an endless loop
* @param ifdOffset the offset within <code>reader</code> at which the IFD data starts
* @param tiffHeaderOffset the offset within <code>reader</code> at which the TIFF header starts
*/
@Deprecated
private static void processIFD(@NotNull final Directory directory,
@NotNull final Set<Integer> processedIfdOffsets,
final int ifdOffset,
final int tiffHeaderOffset,
@NotNull final Metadata metadata,
@NotNull final RandomAccessReader reader) throws IOException
{
// check for directories we've already visited to avoid stack overflows when recursive/cyclic directory structures exist
if (processedIfdOffsets.contains(Integer.valueOf(ifdOffset)))
return;
// remember that we've visited this directory so that we don't visit it again later
processedIfdOffsets.add(ifdOffset);
if (ifdOffset >= reader.getLength() || ifdOffset < 0) {
directory.addError("Ignored IFD marked to start outside data segment");
return;
}
// First two bytes in the IFD are the number of tags in this directory
int dirTagCount = reader.getUInt16(ifdOffset);
int dirLength = (2 + (12 * dirTagCount) + 4);
if (dirLength + ifdOffset > reader.getLength()) {
directory.addError("Illegally sized IFD");
return;
}
// Handle each tag in this directory
for (int tagNumber = 0; tagNumber < dirTagCount; tagNumber++) {
final int tagOffset = calculateTagOffset(ifdOffset, tagNumber);
// 2 bytes for the tag type
final int tagType = reader.getUInt16(tagOffset);
// 2 bytes for the format code
final int formatCode = reader.getUInt16(tagOffset + 2);
if (formatCode < 1 || formatCode > MAX_FORMAT_CODE) {
// This error suggests that we are processing at an incorrect index and will generate
// rubbish until we go out of bounds (which may be a while). Exit now.
directory.addError("Invalid TIFF tag format code: " + formatCode);
return;
}
// 4 bytes dictate the number of components in this tag's data
final int componentCount = reader.getInt32(tagOffset + 4);
if (componentCount < 0) {
directory.addError("Negative TIFF tag component count");
continue;
}
// each component may have more than one byte... calculate the total number of bytes
final int byteCount = componentCount * BYTES_PER_FORMAT[formatCode];
final int tagValueOffset;
if (byteCount > 4) {
// If it's bigger than 4 bytes, the dir entry contains an offset.
// dirEntryOffset must be passed, as some makernote implementations (e.g. Fujifilm) incorrectly use an
// offset relative to the start of the makernote itself, not the TIFF segment.
final int offsetVal = reader.getInt32(tagOffset + 8);
if (offsetVal + byteCount > reader.getLength()) {
// Bogus pointer offset and / or byteCount value
directory.addError("Illegal TIFF tag pointer offset");
continue;
}
tagValueOffset = tiffHeaderOffset + offsetVal;
} else {
// 4 bytes or less and value is in the dir entry itself
tagValueOffset = tagOffset + 8;
}
if (tagValueOffset < 0 || tagValueOffset > reader.getLength()) {
directory.addError("Illegal TIFF tag pointer offset");
continue;
}
// Check that this tag isn't going to allocate outside the bounds of the data array.
// This addresses an uncommon OutOfMemoryError.
if (byteCount < 0 || tagValueOffset + byteCount > reader.getLength()) {
directory.addError("Illegal number of bytes for TIFF tag data: " + byteCount);
continue;
}
//
// Special handling for certain known tags that point to or contain other chunks of data to be processed
//
if (tagType == ExifIFD0Directory.TAG_EXIF_SUB_IFD_OFFSET && directory instanceof ExifIFD0Directory) {
if (byteCount != 4) {
directory.addError("Exif SubIFD Offset tag should have a component count of four (bytes) for the offset.");
} else {
final int subDirOffset = tiffHeaderOffset + reader.getInt32(tagValueOffset);
processIFD(metadata.getOrCreateDirectory(ExifSubIFDDirectory.class), processedIfdOffsets, subDirOffset, tiffHeaderOffset, metadata, reader);
}
} else if (tagType == ExifSubIFDDirectory.TAG_INTEROP_OFFSET && directory instanceof ExifSubIFDDirectory) {
if (byteCount != 4) {
directory.addError("Exif Interop Offset tag should have a component count of four (bytes) for the offset.");
} else {
final int subDirOffset = tiffHeaderOffset + reader.getInt32(tagValueOffset);
processIFD(metadata.getOrCreateDirectory(ExifInteropDirectory.class), processedIfdOffsets, subDirOffset, tiffHeaderOffset, metadata, reader);
}
} else if (tagType == ExifIFD0Directory.TAG_GPS_INFO_OFFSET && directory instanceof ExifIFD0Directory) {
if (byteCount != 4) {
directory.addError("Exif GPS Info Offset tag should have a component count of four (bytes) for the offset.");
} else {
final int subDirOffset = tiffHeaderOffset + reader.getInt32(tagValueOffset);
processIFD(metadata.getOrCreateDirectory(GpsDirectory.class), processedIfdOffsets, subDirOffset, tiffHeaderOffset, metadata, reader);
}
} else if (tagType == ExifSubIFDDirectory.TAG_MAKERNOTE && directory instanceof ExifSubIFDDirectory) {
// The makernote tag contains the encoded makernote data directly.
// Pass the offset to this tag's value. Manufacturer/Model-specific logic will be used to
// determine the correct offset for further processing.
processMakernote(tagValueOffset, processedIfdOffsets, tiffHeaderOffset, metadata, reader);
} else {
processTag(directory, tagType, tagValueOffset, componentCount, formatCode, reader);
}
}
// at the end of each IFD is an optional link to the next IFD
final int finalTagOffset = calculateTagOffset(ifdOffset, dirTagCount);
int nextDirectoryOffset = reader.getInt32(finalTagOffset);
if (nextDirectoryOffset != 0) {
nextDirectoryOffset += tiffHeaderOffset;
if (nextDirectoryOffset >= reader.getLength()) {
// Last 4 bytes of IFD reference another IFD with an address that is out of bounds
// Note this could have been caused by jhead 1.3 cropping too much
return;
} else if (nextDirectoryOffset < ifdOffset) {
// Last 4 bytes of IFD reference another IFD with an address that is before the start of this directory
return;
}
// TODO in Exif, the only known 'follower' IFD is the thumbnail one, however this may not be the case
final ExifThumbnailDirectory nextDirectory = metadata.getOrCreateDirectory(ExifThumbnailDirectory.class);
processIFD(nextDirectory, processedIfdOffsets, nextDirectoryOffset, tiffHeaderOffset, metadata, reader);
}
}
@Deprecated
private static void processMakernote(final int makernoteOffset,
final @NotNull Set<Integer> processedIfdOffsets,
final int tiffHeaderOffset,
final @NotNull Metadata metadata,
final @NotNull RandomAccessReader reader) throws IOException
{
// Determine the camera model and makernote format
Directory ifd0Directory = metadata.getDirectory(ExifIFD0Directory.class);
if (ifd0Directory == null)
return;
String cameraMake = ifd0Directory.getString(ExifIFD0Directory.TAG_MAKE);
final String firstThreeChars = reader.getString(makernoteOffset, 3);
final String firstFourChars = reader.getString(makernoteOffset, 4);
final String firstFiveChars = reader.getString(makernoteOffset, 5);
final String firstSixChars = reader.getString(makernoteOffset, 6);
final String firstSevenChars = reader.getString(makernoteOffset, 7);
final String firstEightChars = reader.getString(makernoteOffset, 8);
final String firstTwelveChars = reader.getString(makernoteOffset, 12);
boolean byteOrderBefore = reader.isMotorolaByteOrder();
if ("OLYMP".equals(firstFiveChars) || "EPSON".equals(firstFiveChars) || "AGFA".equals(firstFourChars)) {
// Olympus Makernote
// Epson and Agfa use Olympus makernote standard: http://www.ozhiker.com/electronics/pjmt/jpeg_info/
processIFD(metadata.getOrCreateDirectory(OlympusMakernoteDirectory.class), processedIfdOffsets, makernoteOffset + 8, tiffHeaderOffset, metadata, reader);
} else if (cameraMake != null && cameraMake.trim().toUpperCase().startsWith("NIKON")) {
if ("Nikon".equals(firstFiveChars)) {
/* There are two scenarios here:
* Type 1: **
* :0000: 4E 69 6B 6F 6E 00 01 00-05 00 02 00 02 00 06 00 Nikon...........
* :0010: 00 00 EC 02 00 00 03 00-03 00 01 00 00 00 06 00 ................
* Type 3: **
* :0000: 4E 69 6B 6F 6E 00 02 00-00 00 4D 4D 00 2A 00 00 Nikon....MM.*...
* :0010: 00 08 00 1E 00 01 00 07-00 00 00 04 30 32 30 30 ............0200
*/
switch (reader.getUInt8(makernoteOffset + 6)) {
case 1:
processIFD(metadata.getOrCreateDirectory(NikonType1MakernoteDirectory.class), processedIfdOffsets, makernoteOffset + 8, tiffHeaderOffset, metadata, reader);
break;
case 2:
processIFD(metadata.getOrCreateDirectory(NikonType2MakernoteDirectory.class), processedIfdOffsets, makernoteOffset + 18, makernoteOffset + 10, metadata, reader);
break;
default:
ifd0Directory.addError("Unsupported Nikon makernote data ignored.");
break;
}
} else {
// The IFD begins with the first Makernote byte (no ASCII name). This occurs with CoolPix 775, E990 and D1 models.
processIFD(metadata.getOrCreateDirectory(NikonType2MakernoteDirectory.class), processedIfdOffsets, makernoteOffset, tiffHeaderOffset, metadata, reader);
}
} else if ("SONY CAM".equals(firstEightChars) || "SONY DSC".equals(firstEightChars)) {
processIFD(metadata.getOrCreateDirectory(SonyType1MakernoteDirectory.class), processedIfdOffsets, makernoteOffset + 12, tiffHeaderOffset, metadata, reader);
} else if ("SEMC MS\u0000\u0000\u0000\u0000\u0000".equals(firstTwelveChars)) {
// force MM for this directory
reader.setMotorolaByteOrder(true);
// skip 12 byte header + 2 for "MM" + 6
processIFD(metadata.getOrCreateDirectory(SonyType6MakernoteDirectory.class), processedIfdOffsets, makernoteOffset + 20, tiffHeaderOffset, metadata, reader);
} else if ("SIGMA\u0000\u0000\u0000".equals(firstEightChars) || "FOVEON\u0000\u0000".equals(firstEightChars)) {
processIFD(metadata.getOrCreateDirectory(SigmaMakernoteDirectory.class), processedIfdOffsets, makernoteOffset + 10, tiffHeaderOffset, metadata, reader);
} else if ("KDK".equals(firstThreeChars)) {
reader.setMotorolaByteOrder(firstSevenChars.equals("KDK INFO"));
processKodakMakernote(metadata.getOrCreateDirectory(KodakMakernoteDirectory.class), makernoteOffset, reader);
} else if ("Canon".equalsIgnoreCase(cameraMake)) {
processIFD(metadata.getOrCreateDirectory(CanonMakernoteDirectory.class), processedIfdOffsets, makernoteOffset, tiffHeaderOffset, metadata, reader);
} else if (cameraMake != null && cameraMake.toUpperCase().startsWith("CASIO")) {
if ("QVC\u0000\u0000\u0000".equals(firstSixChars)) {
processIFD(metadata.getOrCreateDirectory(CasioType2MakernoteDirectory.class), processedIfdOffsets, makernoteOffset + 6, tiffHeaderOffset, metadata, reader);
} else {
processIFD(metadata.getOrCreateDirectory(CasioType1MakernoteDirectory.class), processedIfdOffsets, makernoteOffset, tiffHeaderOffset, metadata, reader);
}
} else if ("FUJIFILM".equals(firstEightChars) || "Fujifilm".equalsIgnoreCase(cameraMake)) {
// Note that this also applies to certain Leica cameras, such as the Digilux-4.3
reader.setMotorolaByteOrder(false);
// the 4 bytes after "FUJIFILM" in the makernote point to the start of the makernote
// IFD, though the offset is relative to the start of the makernote, not the TIFF
// header (like everywhere else)
int ifdStart = makernoteOffset + reader.getInt32(makernoteOffset + 8);
processIFD(metadata.getOrCreateDirectory(FujifilmMakernoteDirectory.class), processedIfdOffsets, ifdStart, makernoteOffset, metadata, reader);
} else if (cameraMake != null && cameraMake.toUpperCase().startsWith("MINOLTA")) {
// Cases seen with the model starting with MINOLTA in capitals seem to have a valid Olympus makernote
// area that commences immediately.
processIFD(metadata.getOrCreateDirectory(OlympusMakernoteDirectory.class), processedIfdOffsets, makernoteOffset, tiffHeaderOffset, metadata, reader);
} else if ("KYOCERA".equals(firstSevenChars)) {
// http://www.ozhiker.com/electronics/pjmt/jpeg_info/kyocera_mn.html
processIFD(metadata.getOrCreateDirectory(KyoceraMakernoteDirectory.class), processedIfdOffsets, makernoteOffset + 22, tiffHeaderOffset, metadata, reader);
} else if ("LEICA".equals(firstFiveChars)) {
reader.setMotorolaByteOrder(false);
if ("Leica Camera AG".equals(cameraMake)) {
processIFD(metadata.getOrCreateDirectory(LeicaMakernoteDirectory.class), processedIfdOffsets, makernoteOffset + 8, tiffHeaderOffset, metadata, reader);
} else if ("LEICA".equals(cameraMake)) {
// Some Leica cameras use Panasonic makernote tags
processIFD(metadata.getOrCreateDirectory(PanasonicMakernoteDirectory.class), processedIfdOffsets, makernoteOffset + 8, tiffHeaderOffset, metadata, reader);
}
} else if ("Panasonic\u0000\u0000\u0000".equals(reader.getString(makernoteOffset, 12))) {
// NON-Standard TIFF IFD Data using Panasonic Tags. There is no Next-IFD pointer after the IFD
// Offsets are relative to the start of the TIFF header at the beginning of the EXIF segment
// more information here: http://www.ozhiker.com/electronics/pjmt/jpeg_info/panasonic_mn.html
processIFD(metadata.getOrCreateDirectory(PanasonicMakernoteDirectory.class), processedIfdOffsets, makernoteOffset + 12, tiffHeaderOffset, metadata, reader);
} else if ("AOC\u0000".equals(firstFourChars)) {
// NON-Standard TIFF IFD Data using Casio Type 2 Tags
// IFD has no Next-IFD pointer at end of IFD, and
// Offsets are relative to the start of the current IFD tag, not the TIFF header
// Observed for:
// - Pentax ist D
processIFD(metadata.getOrCreateDirectory(CasioType2MakernoteDirectory.class), processedIfdOffsets, makernoteOffset + 6, makernoteOffset, metadata, reader);
} else if (cameraMake != null && (cameraMake.toUpperCase().startsWith("PENTAX") || cameraMake.toUpperCase().startsWith("ASAHI"))) {
// NON-Standard TIFF IFD Data using Pentax Tags
// IFD has no Next-IFD pointer at end of IFD, and
// Offsets are relative to the start of the current IFD tag, not the TIFF header
// Observed for:
// - PENTAX Optio 330
// - PENTAX Optio 430
processIFD(metadata.getOrCreateDirectory(PentaxMakernoteDirectory.class), processedIfdOffsets, makernoteOffset, makernoteOffset, metadata, reader);
// } else if ("KC".equals(firstTwoChars) || "MINOL".equals(firstFiveChars) || "MLY".equals(firstThreeChars) || "+M+M+M+M".equals(firstEightChars)) {
// // This Konica data is not understood. Header identified in accordance with information at this site:
// // http://www.ozhiker.com/electronics/pjmt/jpeg_info/minolta_mn.html
// // TODO add support for minolta/konica cameras
// exifDirectory.addError("Unsupported Konica/Minolta data ignored.");
} else if ("SANYO\0\1\0".equals(firstEightChars)) {
processIFD(metadata.getOrCreateDirectory(SanyoMakernoteDirectory.class), processedIfdOffsets, makernoteOffset + 8, makernoteOffset, metadata, reader);
} else {
// The makernote is not comprehended by this library.
// If you are reading this and believe a particular camera's image should be processed, get in touch.
}
reader.setMotorolaByteOrder(byteOrderBefore);
}
@Deprecated
private static void processKodakMakernote(@NotNull final KodakMakernoteDirectory directory, final int tagValueOffset, @NotNull final RandomAccessReader reader)
{
// Kodak's makernote is not in IFD format. It has values at fixed offsets.
int dataOffset = tagValueOffset + 8;
try {
directory.setString(KodakMakernoteDirectory.TAG_KODAK_MODEL, reader.getString(dataOffset, 8));
directory.setInt(KodakMakernoteDirectory.TAG_QUALITY, reader.getUInt8(dataOffset + 9));
directory.setInt(KodakMakernoteDirectory.TAG_BURST_MODE, reader.getUInt8(dataOffset + 10));
directory.setInt(KodakMakernoteDirectory.TAG_IMAGE_WIDTH, reader.getUInt16(dataOffset + 12));
directory.setInt(KodakMakernoteDirectory.TAG_IMAGE_HEIGHT, reader.getUInt16(dataOffset + 14));
directory.setInt(KodakMakernoteDirectory.TAG_YEAR_CREATED, reader.getUInt16(dataOffset + 16));
directory.setByteArray(KodakMakernoteDirectory.TAG_MONTH_DAY_CREATED, reader.getBytes(dataOffset + 18, 2));
directory.setByteArray(KodakMakernoteDirectory.TAG_TIME_CREATED, reader.getBytes(dataOffset + 20, 4));
directory.setInt(KodakMakernoteDirectory.TAG_BURST_MODE_2, reader.getUInt16(dataOffset + 24));
directory.setInt(KodakMakernoteDirectory.TAG_SHUTTER_MODE, reader.getUInt8(dataOffset + 27));
directory.setInt(KodakMakernoteDirectory.TAG_METERING_MODE, reader.getUInt8(dataOffset + 28));
directory.setInt(KodakMakernoteDirectory.TAG_SEQUENCE_NUMBER, reader.getUInt8(dataOffset + 29));
directory.setInt(KodakMakernoteDirectory.TAG_F_NUMBER, reader.getUInt16(dataOffset + 30));
directory.setLong(KodakMakernoteDirectory.TAG_EXPOSURE_TIME, reader.getUInt32(dataOffset + 32));
directory.setInt(KodakMakernoteDirectory.TAG_EXPOSURE_COMPENSATION, reader.getInt16(dataOffset + 36));
directory.setInt(KodakMakernoteDirectory.TAG_FOCUS_MODE, reader.getUInt8(dataOffset + 56));
directory.setInt(KodakMakernoteDirectory.TAG_WHITE_BALANCE, reader.getUInt8(dataOffset + 64));
directory.setInt(KodakMakernoteDirectory.TAG_FLASH_MODE, reader.getUInt8(dataOffset + 92));
directory.setInt(KodakMakernoteDirectory.TAG_FLASH_FIRED, reader.getUInt8(dataOffset + 93));
directory.setInt(KodakMakernoteDirectory.TAG_ISO_SETTING, reader.getUInt16(dataOffset + 94));
directory.setInt(KodakMakernoteDirectory.TAG_ISO, reader.getUInt16(dataOffset + 96));
directory.setInt(KodakMakernoteDirectory.TAG_TOTAL_ZOOM, reader.getUInt16(dataOffset + 98));
directory.setInt(KodakMakernoteDirectory.TAG_DATE_TIME_STAMP, reader.getUInt16(dataOffset + 100));
directory.setInt(KodakMakernoteDirectory.TAG_COLOR_MODE, reader.getUInt16(dataOffset + 102));
directory.setInt(KodakMakernoteDirectory.TAG_DIGITAL_ZOOM, reader.getUInt16(dataOffset + 104));
directory.setInt(KodakMakernoteDirectory.TAG_SHARPNESS, reader.getInt8(dataOffset + 107));
} catch (IOException ex) {
directory.addError("Error processing Kodak makernote data: " + ex.getMessage());
}
}
@Deprecated
private static void processTag(@NotNull final Directory directory,
final int tagType,
final int tagValueOffset,
final int componentCount,
final int formatCode,
@NotNull final RandomAccessReader reader) throws IOException
{
// Directory simply stores raw values
// The display side uses a Descriptor class per directory to turn the raw values into 'pretty' descriptions
switch (formatCode) {
case FMT_UNDEFINED:
// this includes exif user comments
directory.setByteArray(tagType, reader.getBytes(tagValueOffset, componentCount));
break;
case FMT_STRING:
String string = reader.getNullTerminatedString(tagValueOffset, componentCount);
directory.setString(tagType, string);
break;
case FMT_SRATIONAL:
if (componentCount == 1) {
directory.setRational(tagType, new Rational(reader.getInt32(tagValueOffset), reader.getInt32(tagValueOffset + 4)));
} else if (componentCount > 1) {
Rational[] rationals = new Rational[componentCount];
for (int i = 0; i < componentCount; i++)
rationals[i] = new Rational(reader.getInt32(tagValueOffset + (8 * i)), reader.getInt32(tagValueOffset + 4 + (8 * i)));
directory.setRationalArray(tagType, rationals);
}
break;
case FMT_URATIONAL:
if (componentCount == 1) {
directory.setRational(tagType, new Rational(reader.getUInt32(tagValueOffset), reader.getUInt32(tagValueOffset + 4)));
} else if (componentCount > 1) {
Rational[] rationals = new Rational[componentCount];
for (int i = 0; i < componentCount; i++)
rationals[i] = new Rational(reader.getUInt32(tagValueOffset + (8 * i)), reader.getUInt32(tagValueOffset + 4 + (8 * i)));
directory.setRationalArray(tagType, rationals);
}
break;
case FMT_SINGLE:
if (componentCount == 1) {
directory.setFloat(tagType, reader.getFloat32(tagValueOffset));
} else {
float[] floats = new float[componentCount];
for (int i = 0; i < componentCount; i++)
floats[i] = reader.getFloat32(tagValueOffset + (i * 4));
directory.setFloatArray(tagType, floats);
}
break;
case FMT_DOUBLE:
if (componentCount == 1) {
directory.setDouble(tagType, reader.getDouble64(tagValueOffset));
} else {
double[] doubles = new double[componentCount];
for (int i = 0; i < componentCount; i++)
doubles[i] = reader.getDouble64(tagValueOffset + (i * 4));
directory.setDoubleArray(tagType, doubles);
}
break;
//
// Note that all integral types are stored as int32 internally (the largest supported by TIFF)
//
case FMT_SBYTE:
if (componentCount == 1) {
directory.setInt(tagType, reader.getInt8(tagValueOffset));
} else {
int[] bytes = new int[componentCount];
for (int i = 0; i < componentCount; i++)
bytes[i] = reader.getInt8(tagValueOffset + i);
directory.setIntArray(tagType, bytes);
}
break;
case FMT_BYTE:
if (componentCount == 1) {
directory.setInt(tagType, reader.getUInt8(tagValueOffset));
} else {
int[] bytes = new int[componentCount];
for (int i = 0; i < componentCount; i++)
bytes[i] = reader.getUInt8(tagValueOffset + i);
directory.setIntArray(tagType, bytes);
}
break;
case FMT_USHORT:
if (componentCount == 1) {
int i = reader.getUInt16(tagValueOffset);
directory.setInt(tagType, i);
} else {
int[] ints = new int[componentCount];
for (int i = 0; i < componentCount; i++)
ints[i] = reader.getUInt16(tagValueOffset + (i * 2));
directory.setIntArray(tagType, ints);
}
break;
case FMT_SSHORT:
if (componentCount == 1) {
int i = reader.getInt16(tagValueOffset);
directory.setInt(tagType, i);
} else {
int[] ints = new int[componentCount];
for (int i = 0; i < componentCount; i++)
ints[i] = reader.getInt16(tagValueOffset + (i * 2));
directory.setIntArray(tagType, ints);
}
break;
case FMT_SLONG:
case FMT_ULONG:
// NOTE 'long' in this case means 32 bit, not 64
if (componentCount == 1) {
int i = reader.getInt32(tagValueOffset);
directory.setInt(tagType, i);
} else {
int[] ints = new int[componentCount];
for (int i = 0; i < componentCount; i++)
ints[i] = reader.getInt32(tagValueOffset + (i * 4));
directory.setIntArray(tagType, ints);
}
break;
default:
directory.addError("Unknown format code " + formatCode + " for tag " + tagType);
}
}
/**
* Determine the offset at which a given InteropArray entry begins within the specified IFD.
*
* @param ifdStartOffset the offset at which the IFD starts
* @param entryNumber the zero-based entry number
*/
@Deprecated
private static int calculateTagOffset(int ifdStartOffset, int entryNumber)
{
// add 2 bytes for the tag count
// each entry is 12 bytes, so we skip 12 * the number seen so far
return ifdStartOffset + 2 + (12 * entryNumber);
}
}
|
/*
* (C) Copyright 2018 The DKBans Project (Davide Wietlisbach)
*
* @author Davide Wietlisbach
* @since 30.12.18 14:39
* @Website https://github.com/DevKrieger/DKBans
*
* The DKBans Project is under the Apache License, version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package ch.dkrieger.bansystem.lib.storage.sql.query;
import ch.dkrieger.bansystem.lib.storage.sql.SQL;
public class UpdateQuery extends ExecuteQuery {
public UpdateQuery(SQL sql, String query) {
super(sql, query);
}
public UpdateQuery set(String field, Object value) {
if (comma) query += ",";
query += " `"+field+"`=?";
values.add(value);
comma = true;
return this;
}
public UpdateQuery where(String key, Object value) {
if(and) query += " AND";
else query += " WHERE";
query +=" "+key+"=?";
values.add(value);
and = true;
return this;
}
}
|
package com.taotao.cloud.java.javaweb.p6_jsp.entity;
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
public User() {
}
}
|
package ohoz.aa04;
/*
Given a sentence of string, in that remove the palindrome words and print the remaining.
Input:
He did a good deed
Output:
He good
Input:
Hari speaks malayalam
Output:
Hari speaks
*/
public class AAA043 {
}
|
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.comprehendmedical.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.comprehendmedical.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* RxNormAttribute JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class RxNormAttributeJsonUnmarshaller implements Unmarshaller<RxNormAttribute, JsonUnmarshallerContext> {
public RxNormAttribute unmarshall(JsonUnmarshallerContext context) throws Exception {
RxNormAttribute rxNormAttribute = new RxNormAttribute();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("Type", targetDepth)) {
context.nextToken();
rxNormAttribute.setType(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("Score", targetDepth)) {
context.nextToken();
rxNormAttribute.setScore(context.getUnmarshaller(Float.class).unmarshall(context));
}
if (context.testExpression("RelationshipScore", targetDepth)) {
context.nextToken();
rxNormAttribute.setRelationshipScore(context.getUnmarshaller(Float.class).unmarshall(context));
}
if (context.testExpression("Id", targetDepth)) {
context.nextToken();
rxNormAttribute.setId(context.getUnmarshaller(Integer.class).unmarshall(context));
}
if (context.testExpression("BeginOffset", targetDepth)) {
context.nextToken();
rxNormAttribute.setBeginOffset(context.getUnmarshaller(Integer.class).unmarshall(context));
}
if (context.testExpression("EndOffset", targetDepth)) {
context.nextToken();
rxNormAttribute.setEndOffset(context.getUnmarshaller(Integer.class).unmarshall(context));
}
if (context.testExpression("Text", targetDepth)) {
context.nextToken();
rxNormAttribute.setText(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("Traits", targetDepth)) {
context.nextToken();
rxNormAttribute.setTraits(new ListUnmarshaller<RxNormTrait>(RxNormTraitJsonUnmarshaller.getInstance())
.unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return rxNormAttribute;
}
private static RxNormAttributeJsonUnmarshaller instance;
public static RxNormAttributeJsonUnmarshaller getInstance() {
if (instance == null)
instance = new RxNormAttributeJsonUnmarshaller();
return instance;
}
}
|
package me.camdenorrb.herochatbridge.bukkit.listeners;
import com.dthielke.herochat.ChatCompleteEvent;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import me.camdenorrb.herochatbridge.bukkit.BukkitPlugin;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
public final class PlayerListener implements Listener {
private final BukkitPlugin plugin;
public PlayerListener(final BukkitPlugin plugin) {
this.plugin = plugin;
}
@EventHandler(priority = EventPriority.MONITOR)
public void onChatComplete(final ChatCompleteEvent event) {
final ByteArrayDataOutput output = ByteStreams.newDataOutput();
output.writeUTF(event.getChannel().getName());
output.writeUTF(plugin.getSymbolPrefix());
output.writeUTF(event.getMsg());
output.writeUTF(event.getSender().getName());
event.getSender().getPlayer().sendPluginMessage(plugin, "herochat:bridge", output.toByteArray());
}
}
|
package fr.tduf.gui.installer.services.tasks;
import com.esotericsoftware.minlog.Log;
import fr.tduf.gui.installer.common.DisplayConstants;
import fr.tduf.gui.installer.domain.DatabaseContext;
import fr.tduf.gui.installer.domain.InstallerConfiguration;
import fr.tduf.gui.installer.domain.exceptions.StepException;
import javafx.beans.property.ObjectProperty;
import static fr.tduf.gui.installer.steps.GenericStep.StepType.*;
/**
* Orchestrates all steps for uninstall and handles errors
*/
public class UninstallTask extends InstallerTask {
private static final String THIS_CLASS_NAME = InstallTask.class.getSimpleName();
public UninstallTask(ObjectProperty<InstallerConfiguration> configuration, ObjectProperty<DatabaseContext> context) {
super(configuration, context);
}
@Override
protected Void call() throws StepException {
Log.info(THIS_CLASS_NAME, "->Starting uninstall");
updateMessage(DisplayConstants.STATUS_UNINSTALL_IN_PROGRESS);
callStepChain(
RETRIEVE_BACKUP,
REVERT_CAMERA,
RESTORE_SNAPSHOT,
RESTORE_FILES,
SAVE_DATABASE,
REMOVE_BACKUP);
updateMessage(DisplayConstants.STATUS_UNINSTALL_DONE);
Log.info(THIS_CLASS_NAME, "->Done uninstalling");
succeeded();
return null;
}
@Override
protected void handleStepException(StepException se) throws StepException {
Log.error(THIS_CLASS_NAME, "->Critical failure detected, no action will be intended yet.");
updateMessage(DisplayConstants.STATUS_UNINSTALL_KO);
Log.error(THIS_CLASS_NAME, "->Done uninstalling with error(s)");
throw se;
}
}
|
/*******************************************************************************
* * Copyright 2013 Impetus Infotech.
* *
* * 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.impetus.kundera.proxy.collection;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import com.impetus.kundera.metadata.model.Relation;
import com.impetus.kundera.persistence.PersistenceDelegator;
/**
* Proxy class used to represent instances for {@link Map}
*
* @author amresh.singh
*/
public class ProxyMap extends AbstractProxyBase implements ProxyCollection, Map
{
/**
* Default constructor
*/
public ProxyMap()
{
super();
}
public ProxyMap(final PersistenceDelegator delegator, final Relation relation)
{
super(delegator, relation);
}
@Override
public ProxyCollection getCopy()
{
ProxyCollection proxyCollection = new ProxyMap(getPersistenceDelegator(), getRelation());
proxyCollection.setRelationsMap(getRelationsMap());
return proxyCollection;
}
@Override
public Object getDataCollection()
{
return dataCollection != null && ! ((Map) dataCollection).isEmpty() ? dataCollection : null;
}
// ///////////////////////Methods from Collection interface ////////////////
@Override
public void clear()
{
eagerlyLoadDataCollection();
if (getDataCollection() != null && !(getDataCollection() instanceof ProxyCollection))
{
((Map)getDataCollection()).clear();
}
}
@Override
public boolean isEmpty()
{
boolean result = true;
eagerlyLoadDataCollection();
if (getDataCollection() != null && !(getDataCollection() instanceof ProxyCollection))
{
result = ((Map)getDataCollection()).isEmpty();
}
return result;
}
@Override
public int size()
{
eagerlyLoadDataCollection();
return dataCollection == null || dataCollection instanceof ProxyCollection ? 0 : ((Map) dataCollection).size();
}
// ///////////////////////Methods from Map interface ////////////////
@Override
public boolean containsKey(final Object arg0)
{
eagerlyLoadDataCollection();
final Map dataMap = (Map) dataCollection;
boolean result = false;
if (dataMap != null && !(dataMap instanceof ProxyMap) && !dataMap.isEmpty())
{
result = dataMap.containsKey(arg0);
}
return result;
}
@Override
public boolean containsValue(final Object arg0)
{
eagerlyLoadDataCollection();
final Map dataMap = (Map) dataCollection;
boolean result = false;
if (dataMap != null && !dataMap.isEmpty())
{
result = dataMap.containsValue(arg0);
}
return result;
}
@Override
public Set entrySet()
{
eagerlyLoadDataCollection();
final Map dataMap = (Map) dataCollection;
Set result = null;
if (dataMap != null && !dataMap.isEmpty())
{
result = dataMap.entrySet();
}
return result;
}
@Override
public Object get(final Object arg0)
{
eagerlyLoadDataCollection();
final Map dataMap = (Map) dataCollection;
Object result = null;
if (dataMap != null && !dataMap.isEmpty())
{
result = dataMap.get(arg0);
}
return result;
}
@Override
public Set keySet()
{
eagerlyLoadDataCollection();
final Map dataMap = (Map) dataCollection;
Set result = null;
if (dataMap != null && !dataMap.isEmpty())
{
result = dataMap.keySet();
}
return result;
}
@Override
public Object put(final Object arg0, final Object arg1)
{
eagerlyLoadDataCollection();
Map dataMap = (Map) dataCollection;
Object result = null;
if (dataMap != null)
{
result = dataMap.put(arg0, arg1);
}
return result;
}
@Override
public void putAll(final Map arg0)
{
eagerlyLoadDataCollection();
Map dataMap = (Map) dataCollection;
if (dataMap != null)
{
dataMap.putAll(arg0);
}
}
@Override
public Object remove(final Object arg0)
{
eagerlyLoadDataCollection();
Map dataMap = (Map) dataCollection;
Object result = null;
if (dataMap != null && !dataMap.isEmpty())
{
result = dataMap.remove(arg0);
}
return result;
}
@Override
public Collection values()
{
eagerlyLoadDataCollection();
final Map dataMap = (Map) dataCollection;
Collection result = null;
if (dataMap != null && !dataMap.isEmpty())
{
result = dataMap.values();
}
return result;
}
}
|
package kodlamaio.hrms.api.controllers;
import java.util.List;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import kodlamaio.hrms.business.abstracts.PersonalService;
import kodlamaio.hrms.core.utilities.result.DataResult;
import kodlamaio.hrms.core.utilities.result.Result;
import kodlamaio.hrms.entities.concretes.Personal;
@RestController
@RequestMapping("/api/personals")
@CrossOrigin
public class PersonalsController {
private final PersonalService personalService;
public PersonalsController(PersonalService personalService) {
this.personalService=personalService;
}
@GetMapping("/getall")
public DataResult<List<Personal>> getAll(){
return this.personalService.getAll();
}
@GetMapping("/getById")
public DataResult<Personal> getById(@RequestParam(value = "personalId") int personalId){
return this.personalService.getById(personalId);
}
@PostMapping("/add")
public Result add(@RequestBody Personal personal) {
return this.personalService.add(personal);
}
@PostMapping("/update")
public Result update(@RequestBody Personal personal) {
return this.personalService.update(personal);
}
@DeleteMapping("/delete")
public Result delete(@RequestParam Integer id) {
return this.personalService.delete(id);
}
}
|
/*
* Copyright Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags and
* the COPYRIGHT.txt file distributed with this work.
*
* 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.komodo.spi.query;
import org.komodo.spi.type.DataTypeService.DataTypeName;
public class QSColumn {
private final DataTypeName dataType;
private final String columnName;
private final String columnLabel;
public QSColumn(DataTypeName dataType, String columnName, String columnLabel) {
this.dataType = dataType;
this.columnName = columnName;
this.columnLabel = columnLabel;
}
public DataTypeName getDataType() {
return dataType;
}
public String getColumnName() {
return columnName;
}
public String getColumnLabel() {
return columnLabel;
}
}
|
package com.demo.evolving.net.lib.democode;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.codingcoderscode.evolving.base.CCBaseRxAppCompactActivity;
import com.codingcoderscode.lib.net.cache.mode.CCMode;
import com.codingcoderscode.lib.net.request.listener.CCNetResultListener;
import com.codingcoderscode.lib.net.request.canceler.CCCanceler;
import com.codingcoderscode.lib.net.request.entity.CCFile;
import com.codingcoderscode.lib.net.util.CCLogUtil;
import com.demo.evolving.net.lib.CCApplication;
import com.demo.evolving.net.lib.GlideImageLoader;
import com.demo.evolving.net.lib.R;
import com.demo.evolving.net.lib.TestRespObj;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
/**
* Created by CodingCodersCode on 2017/12/1.
*/
public class UploadRequestActivity extends CCBaseRxAppCompactActivity implements View.OnClickListener, EasyPermissions.PermissionCallbacks {
private final String LOG_TAG = getClass().getCanonicalName();
private TextView tv_start_upload;
private TextView tv_file_source;
private TextView tv_file_upload_status;
private TextView tv_file_upload_progress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_request);
initView();
}
private void initView(){
this.tv_start_upload = (TextView)findViewById(R.id.tv_start_upload);
this.tv_start_upload.setOnClickListener(this);
this.tv_file_source = (TextView)findViewById(R.id.tv_file_source);
this.tv_file_upload_status = (TextView)findViewById(R.id.tv_file_upload_status);
this.tv_file_upload_progress = (TextView)findViewById(R.id.tv_file_upload_progress);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.tv_start_upload:
onSelectImg();
break;
}
}
private void onSelectImg(){
ImagePicker imagePicker = ImagePicker.getInstance();
imagePicker.setImageLoader(new GlideImageLoader());
imagePicker.setShowCamera(true);
imagePicker.setSelectLimit(9);
imagePicker.setCrop(false);
Intent intent = new Intent(getApplicationContext(), ImageGridActivity.class);
startActivityForResult(intent, 100);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
if (data != null && requestCode == 100) {
List<ImageItem> images = (List<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
onStartUploadMethodTest(images);
}
}
}
/**
* 测试上传方法
* @param images
*/
private void onStartUploadMethodTest(List<ImageItem> images){
try {
Map<String, String> specifyHeaderMap = new HashMap<>();
specifyHeaderMap.put("specify_header_param1", "specify_header_value1");
specifyHeaderMap.put("specify_header_param2", "specify_header_value2");
specifyHeaderMap.put("specify_header_param3", "specify_header_value3");
Map<String, Object> txtParamMap = new HashMap<>();
txtParamMap.put("logic_txt_param1", "logic_txt_value1");
txtParamMap.put("logic_txt_param2", "logic_txt_value2");
txtParamMap.put("logic_txt_param3", "logic_txt_value3");
Map<String, CCFile> fileParamMap = new HashMap<>();
String fileInfoStr = "";
for (int i = 0; i < images.size(); i++){
ImageItem imageItem = images.get(i);
fileParamMap.put("fileKey" + i, new CCFile(imageItem.path));
fileInfoStr = fileInfoStr + "fileKey" + i + "===>" + imageItem.path + "\n\n";
}
this.tv_file_source.setText(fileInfoStr);
Map<String, String> pathMap = new HashMap<String, String>();
pathMap.put("{path1}", "path1_value1");
pathMap.put("{path2}", "path1_value2");
pathMap.put("{path3}", "path1_value3");
pathMap.put("{path4}", "path1_value4");
pathMap.put("{path5}", "path1_value5");
((CCApplication)this.getApplicationContext()).getCcRxNetManager().<String>upload("upload")
.setHeaderMap(specifyHeaderMap)
.setPathMap(pathMap)
//.setTxtRequestParam(txtParamMap)
//.setFileRequestParam(fileParamMap)
.setRetryCount(0)
.setCacheQueryMode(CCMode.QueryMode.MODE_NET)
.setCacheSaveMode(CCMode.SaveMode.MODE_NONE)
.setReqTag("test_login_req_tag")
.setCacheTag("test_login_req_cache_key")
.setCCNetCallback(new RxNetUploadProgressCallback())
.setResponseBeanType(String.class)
.executeAsync();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
@Override
public void onPermissionsGranted(int requestCode, List<String> perms) {
}
@Override
public void onPermissionsDenied(int requestCode, List<String> perms) {
if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
new AppSettingsDialog.Builder(this).build().show();
}
}
private int gProgress = 0;
private String gNetSpeed = "0B/s";
private long gCompletedSize = 0;
private long gFileSize = 0;
/**
* 上传进度回调
*/
private class RxNetUploadProgressCallback implements CCNetResultListener {
@Override
public <T> void onStartRequest(Object reqTag, CCCanceler canceler) {
CCLogUtil.printLog("d", LOG_TAG, "调用了RxNetUploadProgressCallback.onStartRequest方法,调用者reqTag=" + reqTag);
tv_file_upload_status.setText("开始上传");
tv_file_upload_progress.setText("文件标识:" + "" + "\n上传进度:" + 0 + "%\n上传速度:" + "0B/s" + "\n已上传大小:" + 0 + "B\n文件大小:" + 0 + "B");
}
@Override
public <T> void onDiskCacheQuerySuccess(Object reqTag, T response) {
}
@Override
public <T> void onDiskCacheQueryFail(Object reqTag, Throwable t) {
}
@Override
public <T> void onNetSuccess(Object reqTag, T response) {
}
@Override
public <T> void onNetFail(Object reqTag, Throwable t) {
}
@Override
public <T> void onRequestSuccess(Object reqTag, T response, int dataSourceMode) {
if (response != null) {
if (response instanceof TestRespObj) {
CCLogUtil.printLog("d", LOG_TAG, "调用了onSuccess方法,调用者reqTag=" + reqTag + ",响应数据是TestRespObj类型,response=" + ((TestRespObj) response).toString());
} else {
CCLogUtil.printLog("d", LOG_TAG, "调用了onSuccess方法,调用者reqTag=" + reqTag + ",但响应数据不是TestRespObj类型");
}
} else {
CCLogUtil.printLog("d", LOG_TAG, "调用了onSuccess方法,调用者reqTag=" + reqTag + ",但响应数据response == null");
}
tv_file_upload_status.setText("上传成功");
tv_file_upload_progress.setText("文件标识:" + "" + "\n上传进度:" + 0 + "%\n上传速度:" + "0B/s" + "\n已上传大小:" + 0 + "B\n文件大小:" + 0 + "B");
}
@Override
public <T> void onRequestFail(Object reqTag, Throwable t) {
tv_file_upload_status.setText("上传失败,详细失败信息见log,log窗口类型:Error");
tv_file_upload_progress.setText("文件标识:" + reqTag + "\n上传进度:" + 0 + "%\n上传速度:" + "0B/s" + "\n已上传大小:" + 0 + "B\n文件大小:" + 0 + "B");
CCLogUtil.printLog("d", LOG_TAG, "调用了RxNetUploadProgressCallback.onError方法,调用者reqTag=" + reqTag, t);
}
@Override
public <T> void onRequestComplete(Object reqTag) {
tv_file_upload_status.setText("上传完成");
tv_file_upload_progress.setText("文件标识:" + "" + "\n上传进度:" + 0 + "%\n上传速度:" + "0B/s" + "\n已上传大小:" + 0 + "B\n文件大小:" + 0 + "B");
CCLogUtil.printLog("d", LOG_TAG, "调用了RxNetUploadProgressCallback.onComplete方法,调用者reqTag=" + reqTag);
}
@Override
public <T> void onProgress(Object tag, int progress, long netSpeed, long completedSize, long fileSize) {
gProgress = progress;
gCompletedSize = completedSize;
gFileSize = fileSize;
if (netSpeed > 1024 * 1024){
gNetSpeed = netSpeed / (1024 * 1024) + "M/s";
}else if (netSpeed > 1024){
gNetSpeed = netSpeed / 1024 + "KB/s";
}else {
gNetSpeed = netSpeed + "B/s";
}
CCLogUtil.printLog("d", LOG_TAG, "调用了RxNetUploadProgressCallback.onProgress方法,调用者tag=" + tag + ",progress=" + gProgress + ",netSpeed=" + gNetSpeed + ",completedSize=" + gCompletedSize + ",fileSize=" + gFileSize);
tv_file_upload_progress.setText("文件标识:" + tag + "\n上传进度:" + gProgress + "%\n上传速度:" + gNetSpeed + "\n已上传大小:" + gCompletedSize + "B\n文件大小:" + gFileSize + "B");
}
@Override
public <T> void onProgressSave(Object reqTag, int progress, long netSpeed, long completedSize, long fileSize) {
}
@Override
public void onIntervalCallback() {
}
}
}
|
/*
* 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.
*/
/*
* $Id$
*/
package org.apache.qetest;
import java.util.Properties;
/**
* Factory constructor for various qetest-related objects.
*
* Currently only supports finding an appropriate instance
* of a file-based CheckService.
*
* @author Shane_Curcuru@lotus.com
* @version $Id$
*/
public abstract class QetestFactory
{
/** Constant denoting a default CheckService for Files. */
public static final String TYPE_FILES = "QetestFactory.FILECHECK";
/** Default TYPE_FILES implementation class. */
public static final String DEFAULT_TYPE_FILES = "org.apache.qetest.xsl.XHTFileCheckService";
/**
* Get a new CheckService of a specified type.
*
* Currently only supports the TYPE_FILES or your own FQCN.
*
* @param type FQCN or constant type of CheckService needed
* @return CheckService of the appropriate type; or a fallback
* type if not found and a fallback is available.
*/
public static CheckService newCheckService(Logger logger, String type)
{
CheckService service = null;
if (null == type)
{
logger.logMsg(Logger.ERRORMSG, "Warning: no type specified for newCheckService!");
return null;
}
else if (TYPE_FILES.equals(type))
{
// Return our default impl
Class fClazz = QetestUtils.testClassForName(DEFAULT_TYPE_FILES, null, null);
if (null == fClazz)
{
logger.logMsg(Logger.ERRORMSG, "Warning: no default fileChecker is available: " + DEFAULT_TYPE_FILES);
return null; //@todo should we throw exception instead?
}
try
{
service = (CheckService)fClazz.newInstance();
//logger.logMsg(Logger.TRACEMSG, TYPE_FILES + " is " + service);
}
catch (Exception e)
{
logger.logThrowable(Logger.ERRORMSG, e, "newCheckService(" + TYPE_FILES + ") threw");
}
return service;
}
else // Assume a classname of your impl
{
// Return our default impl
Class fClazz = QetestUtils.testClassForName(type, QetestUtils.defaultPackages, null);
if (null == fClazz)
{
logger.logMsg(Logger.ERRORMSG, "Warning: no fileChecker is available of type: " + type);
return null; //@todo should we throw exception instead?
}
try
{
service = (CheckService)fClazz.newInstance();
logger.logMsg(Logger.TRACEMSG, TYPE_FILES + " is " + service);
}
catch (Exception e)
{
logger.logThrowable(Logger.ERRORMSG, e, "newCheckService(" + TYPE_FILES + ") threw");
}
return service;
}
}
/**
* Get a new Reporter with some defaults.
*
* Will attempt to initialize the appropriate Reporter
* depending on the options passed in; if all else fails, will
* return at least a ConsoleLogger.
*
* @param options to create Reporter from
* @return appropriate Reporter instance, or a default one.
*/
public static Reporter newReporter(Properties options)
{
Reporter reporter = null;
if (null == options)
{
// Return a default Reporter
reporter = new Reporter(null);
reporter.addDefaultLogger(); // add default logger automatically
return reporter;
}
// Setup appropriate defaults for the Reporter
// Ensure we have an XMLFileLogger if we have a logName
String logF = options.getProperty(Logger.OPT_LOGFILE);
if ((logF != null) && (!logF.equals("")))
{
// We should ensure there's an XMLFileReporter
String r = options.getProperty(Reporter.OPT_LOGGERS);
if (r == null)
{
// Create the property if needed...
options.put(Reporter.OPT_LOGGERS,
"org.apache.qetest.XMLFileLogger");
}
else if (r.indexOf("XMLFileLogger") <= 0)
{
// ...otherwise append to existing list
options.put(Reporter.OPT_LOGGERS,
r + Reporter.LOGGER_SEPARATOR
+ "org.apache.qetest.XMLFileLogger");
}
}
// Ensure we have a ConsoleLogger unless asked not to
// @todo improve and document this feature
String noDefault = options.getProperty("noDefaultReporter");
if (noDefault == null)
{
// We should ensure there's an XMLFileReporter
String r = options.getProperty(Reporter.OPT_LOGGERS);
if (r == null)
{
options.put(Reporter.OPT_LOGGERS,
"org.apache.qetest.ConsoleLogger");
}
else if (r.indexOf("ConsoleLogger") <= 0)
{
options.put(Reporter.OPT_LOGGERS,
r + Reporter.LOGGER_SEPARATOR
+ "org.apache.qetest.ConsoleLogger");
}
}
// Pass our options directly to the reporter
// so it can use the same values in initialization
// A Reporter will auto-initialize from the values
// in the properties block
reporter = new Reporter(options);
return reporter;
}
/**
* Get a new Logger with some defaults.
*
* Currently a redirect to call (Logger)newReporter(options).
*
* @param options to create Logger from
* @return appropriate Logger instance, or a default one.
*/
public static Logger newLogger(Properties options)
{
return (Logger)newReporter(options);
}
/** Prevent instantiation - private constructor. */
private QetestFactory() { /* no-op */ }
} // end of class CheckService
|
/*
* Copyright 2012 SURFnet bv, The Netherlands
*
* 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 nl.surfnet.mujina.spring.security;
import java.util.Arrays;
import java.util.Collection;
import nl.surfnet.mujina.model.AuthenticationMethod;
import nl.surfnet.mujina.model.IdpConfiguration;
import nl.surfnet.mujina.model.SimpleAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Autowired
private IdpConfiguration idpConfiguration;
@SuppressWarnings("serial")
@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
final String name = authentication.getName();
final String password = authentication.getCredentials().toString();
/*
* First check if we know this user. Fallback user if Method.ALL otherwise
* an Exception
*/
Authentication authenticationForUser = getAuthenticationForUser(name, password);
if (idpConfiguration.getAuthentication() == AuthenticationMethod.Method.ALL) {
return authenticationForUser != null ? authenticationForUser : new SimpleAuthentication(name, password, Arrays.asList(
(GrantedAuthority) new GrantedAuthorityImpl("ROLE_USER"), (GrantedAuthority) new GrantedAuthorityImpl("ROLE_ADMIN")));
} else {
if (authenticationForUser == null) {
throw new AuthenticationException("Can not log in") {
};
}
return authenticationForUser;
}
}
private Authentication getAuthenticationForUser(String name, String password) {
final Collection<SimpleAuthentication> users = idpConfiguration.getUsers();
for (SimpleAuthentication user : users) {
if (user.getPrincipal().equals(name) && user.getCredentials().equals(password)) {
return user;
}
}
return null;
}
@SuppressWarnings("rawtypes")
@Override
public boolean supports(final Class method) {
return method.equals(UsernamePasswordAuthenticationToken.class);
}
}
|
/*
* Copyright (c) 2012, František Haas, Martin Lacina, Jaroslav Kotrč, Jiří Daniel
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the author nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package cz.cuni.mff.spl.evaluator.output;
import cz.cuni.mff.spl.annotation.Comparison;
import cz.cuni.mff.spl.annotation.Measurement;
import cz.cuni.mff.spl.deploy.store.IStore.IStoreDirectory;
import cz.cuni.mff.spl.deploy.store.IStore.IStoreDirectory.IStoreFile;
import cz.cuni.mff.spl.deploy.store.exception.StoreException;
import cz.cuni.mff.spl.evaluator.FileNameMapper;
import cz.cuni.mff.spl.evaluator.output.results.AnnotationEvaluationResult;
import cz.cuni.mff.spl.evaluator.output.results.FormulaEvaluationResult;
/**
* The Class OutputFileMappingImpl.
*
* @author Martin Lacina
*/
public class StoreSplOutputFileMappingImpl extends StoreBasicOutputFileMappingImpl implements SPLOutputFileMapping {
/** The file extension. */
private final String fileExtension;
/** The file prefix. */
private final String filePrefix;
/**
* Instantiates a new file mapping implementation.
*
* @param directory
* The directory to create new files in.
* @param extension
* The extension for created files.
*/
public StoreSplOutputFileMappingImpl(IStoreDirectory directory, String extension) {
super(directory);
this.filePrefix = "";
this.fileExtension = extension != null ? extension : "";
}
/**
* Instantiates a new file mapping implementation.
*
* @param directory
* The directory to create new files in.
* @param prefix
* The prefix for created files.
* @param extension
* The extension for created files.
*/
public StoreSplOutputFileMappingImpl(IStoreDirectory directory, String prefix, String extension) {
super(directory);
this.filePrefix = prefix != null ? prefix : "";
this.fileExtension = extension != null ? extension : "";
}
@Override
public IStoreFile getMeasurementOutputFile(Measurement measurement) throws StoreException {
String secondPrefix = FileNameMapper.getMeasurementFileNamePrefix(measurement);
return getOutputFile(measurement, secondPrefix);
}
@Override
public IStoreFile getComparisonOutputFile(Comparison comparison) throws StoreException {
String secondPrefix = FileNameMapper.getComparisonFileNamePrefix(comparison);
return getOutputFile(comparison, secondPrefix);
}
@Override
public IStoreFile getFormulaOutputFile(FormulaEvaluationResult formula) throws StoreException {
String secondPrefix = FileNameMapper.getFormulaFileNamePrefix(formula.getFormulaDeclaration().getFormula());
return getOutputFile(formula, secondPrefix);
}
@Override
public IStoreFile getAnnotationOutputFile(AnnotationEvaluationResult annotationEvaluationResult) throws StoreException {
String secondPrefix = FileNameMapper.getAnnotationFileNamePrefix(annotationEvaluationResult.getAnnotationLocation());
return getOutputFile(annotationEvaluationResult, secondPrefix);
}
/**
* Gets the output file.
*
* @param key
* The key.
* @param secondPrefix
* The second prefix of file prefix. When prefix is empty, than
* prefix is generated
* using {@link FileNameMapper#createPrefixProposal(Object)}.
* @return The output file.
* @throws StoreException
*/
protected IStoreFile getOutputFile(Object key, String secondPrefix) throws StoreException {
IStoreFile result = super.getIStoreFile(key);
if (result == null) {
if (secondPrefix == null) {
secondPrefix = "";
}
String prefix = this.filePrefix + secondPrefix;
result = super.getOutputFile(key, prefix, fileExtension);
}
return result;
}
}
|
import java.util.*;
public class CoinsTask {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int S = in.nextInt();
int mCoins = 0;
while(S/n != 0) {
mCoins+=1;
S-=n;
}
mCoins = S == 0? mCoins : mCoins+1;
System.out.print(mCoins);
}
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package org.pytorch.rn.core.audio;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Build;
import android.util.Log;
import androidx.core.app.ActivityCompat;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.module.annotations.ReactModule;
import org.jetbrains.annotations.NotNull;
import org.pytorch.rn.core.javascript.JSContext;
@ReactModule(name = "PyTorchCoreAudioModule")
public class AudioModule extends ReactContextBaseJavaModule {
public static final String TAG = "PTLAudioModule";
public static final String NAME = "PyTorchCoreAudioModule";
private static final int REQUEST_RECORD_AUDIO = 13;
private static final int SAMPLE_RATE = 16000;
private final ReactApplicationContext mReactContext;
public AudioModule(ReactApplicationContext reactContext) {
super(reactContext);
mReactContext = reactContext;
}
@NotNull
@Override
public String getName() {
return NAME;
}
@ReactMethod
public void record(final int length, final Promise promise) {
Log.d(TAG, "started recording");
requestMicrophonePermission();
final int recordingLength = SAMPLE_RATE * length;
Thread recordingThread =
new Thread(
() -> {
try {
final int bufferSize =
AudioRecord.getMinBufferSize(
SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
final AudioRecord record =
new AudioRecord(
MediaRecorder.AudioSource.DEFAULT,
SAMPLE_RATE,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
bufferSize);
if (record.getState() != AudioRecord.STATE_INITIALIZED) {
Log.e(TAG, "Audio Record can't initialize!");
return;
}
record.startRecording();
long shortsRead = 0;
int audioDataOffset = 0;
int shortsToCopy = 0;
short[] audioBuffer = new short[bufferSize / 2];
short[] audioData = new short[recordingLength];
while (shortsRead < recordingLength) {
int numberOfShort = record.read(audioBuffer, 0, audioBuffer.length);
shortsRead += numberOfShort;
shortsToCopy = Math.min(numberOfShort, recordingLength - audioDataOffset);
System.arraycopy(audioBuffer, 0, audioData, audioDataOffset, shortsToCopy);
audioDataOffset += shortsToCopy;
Log.d(TAG, String.format("shortsRead=%d", shortsRead));
}
record.stop();
record.release();
Audio audio = new Audio(audioData);
JSContext.NativeJSRef ref = JSContext.wrapObject(audio);
promise.resolve(ref.getJSRef());
} catch (Exception e) {
Log.e(TAG, "Error recording audio:", e);
promise.reject(e);
}
});
recordingThread.start();
}
private void requestMicrophonePermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ActivityCompat.requestPermissions(
mReactContext.getCurrentActivity(),
new String[] {android.Manifest.permission.RECORD_AUDIO},
REQUEST_RECORD_AUDIO);
}
}
}
|
/*
* Copyright 2015-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.elasticsearch.model;
import javax.annotation.Generated;
/**
*
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum DescribePackagesFilterName {
PackageID("PackageID"),
PackageName("PackageName"),
PackageStatus("PackageStatus");
private String value;
private DescribePackagesFilterName(String value) {
this.value = value;
}
@Override
public String toString() {
return this.value;
}
/**
* Use this in place of valueOf.
*
* @param value
* real value
* @return DescribePackagesFilterName corresponding to the value
*
* @throws IllegalArgumentException
* If the specified value does not map to one of the known values in this enum.
*/
public static DescribePackagesFilterName fromValue(String value) {
if (value == null || "".equals(value)) {
throw new IllegalArgumentException("Value cannot be null or empty!");
}
for (DescribePackagesFilterName enumEntry : DescribePackagesFilterName.values()) {
if (enumEntry.toString().equals(value)) {
return enumEntry;
}
}
throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
}
}
|
java.util.Date date = new java.util.Date(2011, 4, 9);
if (org.codehaus.groovy.runtime.DefaultGroovyMethods.isCase(new java.util.Date(20, 11, 23), date)) {
print("aaa");
print("bbb");
}
else if (org.codehaus.groovy.runtime.DefaultGroovyMethods.isCase(new java.util.ArrayList<java.lang.Integer>(java.util.Arrays.asList(1)), date)) {
print("bbb");
}
else {
print("ccc");
}
|
/*
* 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.jackrabbit.oak.spi.security.privilege;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import com.google.common.primitives.Longs;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.api.Tree;
import org.apache.jackrabbit.oak.api.Type;
import org.apache.jackrabbit.oak.plugins.memory.PropertyStates;
import org.apache.jackrabbit.oak.spi.security.authorization.permission.Permissions;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static com.google.common.base.Preconditions.checkArgument;
/**
* Internal representation of JCR privileges.
*/
public final class PrivilegeBits implements PrivilegeConstants {
private static final long NO_PRIVILEGE = 0;
private static final long READ_NODES = 1;
private static final long READ_PROPERTIES = READ_NODES << 1;
private static final long ADD_PROPERTIES = READ_PROPERTIES << 1;
private static final long ALTER_PROPERTIES = ADD_PROPERTIES << 1;
private static final long REMOVE_PROPERTIES = ALTER_PROPERTIES << 1;
private static final long ADD_CHILD_NODES = REMOVE_PROPERTIES << 1;
private static final long REMOVE_CHILD_NODES = ADD_CHILD_NODES << 1;
private static final long REMOVE_NODE = REMOVE_CHILD_NODES << 1;
private static final long READ_AC = REMOVE_NODE << 1;
private static final long MODIFY_AC = READ_AC << 1;
private static final long NODE_TYPE_MNGMT = MODIFY_AC << 1;
private static final long VERSION_MNGMT = NODE_TYPE_MNGMT << 1;
private static final long LOCK_MNGMT = VERSION_MNGMT << 1;
private static final long LIFECYCLE_MNGMT = LOCK_MNGMT << 1;
private static final long RETENTION_MNGMT = LIFECYCLE_MNGMT << 1;
private static final long WORKSPACE_MNGMT = RETENTION_MNGMT << 1;
private static final long NODE_TYPE_DEF_MNGMT = WORKSPACE_MNGMT << 1;
private static final long NAMESPACE_MNGMT = NODE_TYPE_DEF_MNGMT << 1;
private static final long PRIVILEGE_MNGMT = NAMESPACE_MNGMT << 1;
private static final long USER_MNGMT = PRIVILEGE_MNGMT << 1;
private static final long INDEX_DEFINITION_MNGMT = USER_MNGMT << 1;
private static final long READ = READ_NODES | READ_PROPERTIES;
private static final long MODIFY_PROPERTIES = ADD_PROPERTIES | ALTER_PROPERTIES | REMOVE_PROPERTIES;
private static final long WRITE = MODIFY_PROPERTIES | ADD_CHILD_NODES | REMOVE_CHILD_NODES | REMOVE_NODE;
private static final long WRITE2 = WRITE | NODE_TYPE_MNGMT;
public static final PrivilegeBits EMPTY = new PrivilegeBits(UnmodifiableData.EMPTY);
public static final Map<String, PrivilegeBits> BUILT_IN;
private static final Map<Long, String> BUILT_IN_BITS;
static {
Map<String, PrivilegeBits> privs = new HashMap<>();
privs.put(REP_READ_NODES, getInstance(READ_NODES));
privs.put(REP_READ_PROPERTIES, getInstance(READ_PROPERTIES));
privs.put(REP_ADD_PROPERTIES, getInstance(ADD_PROPERTIES));
privs.put(REP_ALTER_PROPERTIES, getInstance(ALTER_PROPERTIES));
privs.put(REP_REMOVE_PROPERTIES, getInstance(REMOVE_PROPERTIES));
privs.put(JCR_ADD_CHILD_NODES, getInstance(ADD_CHILD_NODES));
privs.put(JCR_REMOVE_CHILD_NODES, getInstance(REMOVE_CHILD_NODES));
privs.put(JCR_REMOVE_NODE, getInstance(REMOVE_NODE));
privs.put(JCR_READ_ACCESS_CONTROL, getInstance(READ_AC));
privs.put(JCR_MODIFY_ACCESS_CONTROL, getInstance(MODIFY_AC));
privs.put(JCR_NODE_TYPE_MANAGEMENT, getInstance(NODE_TYPE_MNGMT));
privs.put(JCR_VERSION_MANAGEMENT, getInstance(VERSION_MNGMT));
privs.put(JCR_LOCK_MANAGEMENT, getInstance(LOCK_MNGMT));
privs.put(JCR_LIFECYCLE_MANAGEMENT, getInstance(LIFECYCLE_MNGMT));
privs.put(JCR_RETENTION_MANAGEMENT, getInstance(RETENTION_MNGMT));
privs.put(JCR_WORKSPACE_MANAGEMENT, getInstance(WORKSPACE_MNGMT));
privs.put(JCR_NODE_TYPE_DEFINITION_MANAGEMENT, getInstance(NODE_TYPE_DEF_MNGMT));
privs.put(JCR_NAMESPACE_MANAGEMENT, getInstance(NAMESPACE_MNGMT));
privs.put(REP_PRIVILEGE_MANAGEMENT, getInstance(PRIVILEGE_MNGMT));
privs.put(REP_USER_MANAGEMENT, getInstance(USER_MNGMT));
privs.put(REP_INDEX_DEFINITION_MANAGEMENT, getInstance(INDEX_DEFINITION_MNGMT));
privs.put(JCR_READ, getInstance(READ));
privs.put(JCR_MODIFY_PROPERTIES, getInstance(MODIFY_PROPERTIES));
privs.put(JCR_WRITE, getInstance(WRITE));
privs.put(REP_WRITE, getInstance(WRITE2));
BUILT_IN = Collections.unmodifiableMap(privs);
Map<Long, String> bits = new HashMap<>();
bits.put(READ_NODES, REP_READ_NODES);
bits.put(READ_PROPERTIES, REP_READ_PROPERTIES);
bits.put(ADD_PROPERTIES, REP_ADD_PROPERTIES);
bits.put(ALTER_PROPERTIES, REP_ALTER_PROPERTIES);
bits.put(REMOVE_PROPERTIES, REP_REMOVE_PROPERTIES);
bits.put(ADD_CHILD_NODES, JCR_ADD_CHILD_NODES);
bits.put(REMOVE_CHILD_NODES, JCR_REMOVE_CHILD_NODES);
bits.put(REMOVE_NODE, JCR_REMOVE_NODE);
bits.put(READ_AC, JCR_READ_ACCESS_CONTROL);
bits.put(MODIFY_AC, JCR_MODIFY_ACCESS_CONTROL);
bits.put(NODE_TYPE_MNGMT, JCR_NODE_TYPE_MANAGEMENT);
bits.put(VERSION_MNGMT, JCR_VERSION_MANAGEMENT);
bits.put(LOCK_MNGMT, JCR_LOCK_MANAGEMENT);
bits.put(LIFECYCLE_MNGMT, JCR_LIFECYCLE_MANAGEMENT);
bits.put(RETENTION_MNGMT, JCR_RETENTION_MANAGEMENT);
bits.put(WORKSPACE_MNGMT, JCR_WORKSPACE_MANAGEMENT);
bits.put(NODE_TYPE_DEF_MNGMT, JCR_NODE_TYPE_DEFINITION_MANAGEMENT);
bits.put(NAMESPACE_MNGMT, JCR_NAMESPACE_MANAGEMENT);
bits.put(PRIVILEGE_MNGMT, REP_PRIVILEGE_MANAGEMENT);
bits.put(USER_MNGMT, REP_USER_MANAGEMENT);
bits.put(INDEX_DEFINITION_MNGMT, REP_INDEX_DEFINITION_MANAGEMENT);
bits.put(READ, JCR_READ);
bits.put(MODIFY_PROPERTIES, JCR_MODIFY_PROPERTIES);
bits.put(WRITE, JCR_WRITE);
bits.put(WRITE2, REP_WRITE);
BUILT_IN_BITS = Collections.unmodifiableMap(bits);
}
public static final PrivilegeBits NEXT_AFTER_BUILT_INS = getInstance(INDEX_DEFINITION_MNGMT).nextBits();
private final Data d;
/**
* Private constructor.
*
* @param d The data that backs this instance.
*/
private PrivilegeBits(Data d) {
this.d = d;
}
/**
* Creates a mutable instance of privilege bits.
*
* @return a new instance of privilege bits.
*/
public static PrivilegeBits getInstance() {
return new PrivilegeBits(new ModifiableData());
}
/**
* Creates a mutable instance of privilege bits.
*
* @param base The base for this mutable instance.
* @return a new instance of privilege bits.
*/
@NotNull
public static PrivilegeBits getInstance(@NotNull PrivilegeBits... base) {
PrivilegeBits bts = getInstance();
for (PrivilegeBits baseBits : base) {
bts.add(baseBits);
}
return bts;
}
/**
* Get or create an instance of privilege bits for a specific property that
* stores privileges.
*
* @param property The property state storing privilege bits information.
* @return an instance of {@code PrivilegeBits}
*/
@NotNull
public static PrivilegeBits getInstance(@Nullable PropertyState property) {
if (property == null) {
return EMPTY;
}
int size = property.count();
if (size == 1) {
return getInstance(property.getValue(Type.LONG, 0));
} else {
long[] longs = new long[size];
for (int i = 0; i < longs.length; i++) {
longs[i] = property.getValue(Type.LONG, i);
}
return getInstance(longs);
}
}
/**
* Get or create an instance of privilege bits for a privilege definition.
*
* @param tree A privilege definition tree or the privileges root.
* @return an instance of {@code PrivilegeBits}
*/
@NotNull
public static PrivilegeBits getInstance(@Nullable Tree tree) {
if (tree == null) {
return EMPTY;
}
String privName = tree.getName();
if (BUILT_IN.containsKey(privName)) {
return BUILT_IN.get(privName);
} else if (REP_PRIVILEGES.equals(privName)) {
return getInstance(tree.getProperty(REP_NEXT));
} else {
return getInstance(tree.getProperty(REP_BITS));
}
}
/**
* Internal method to get or create an instance of privilege bits for the
* specified long value.
*
* @param bits A long value.
* @return an instance of {@code PrivilegeBits}
*/
@NotNull
private static PrivilegeBits getInstance(long bits) {
if (bits == NO_PRIVILEGE) {
return EMPTY;
} else {
checkArgument(bits > NO_PRIVILEGE);
if (BUILT_IN_BITS != null) {
String key = BUILT_IN_BITS.get(bits);
if (key != null) {
return BUILT_IN.get(key);
}
}
return new PrivilegeBits(new UnmodifiableData(bits));
}
}
/**
* Internal method to create a new instance of {@code PrivilegeBits}.
*
* @param bits A long array.
* @return an instance of {@code PrivilegeBits}
*/
@NotNull
private static PrivilegeBits getInstance(long[] bits) {
return new PrivilegeBits(new UnmodifiableData(bits));
}
/**
* Calculate the granted permissions by evaluating the given privileges. Note,
* that only built-in privileges can be mapped to permissions. Any other
* privileges will be ignored.
*
* @param bits The set of privileges present at given tree.
* @param parentBits The privileges present on the parent tree. These are
* required in order to determine permissions that include a modification
* of the parent tree (add_child_nodes, remove_child_nodes).
* @param isAllow {@code true} if the privileges are granted; {@code false}
* otherwise.
* @return the resulting permissions.
*/
public static long calculatePermissions(@NotNull PrivilegeBits bits,
@NotNull PrivilegeBits parentBits,
boolean isAllow) {
long privs = bits.d.longValue();
long parentPrivs = parentBits.d.longValue();
long perm = Permissions.NO_PERMISSION;
if ((privs & READ) == READ) {
perm |= Permissions.READ;
} else {
if ((privs & READ_NODES) == READ_NODES) {
perm |= Permissions.READ_NODE;
} else if (((privs & READ_PROPERTIES) == READ_PROPERTIES)) {
perm |= Permissions.READ_PROPERTY;
}
}
if ((privs & MODIFY_PROPERTIES) == MODIFY_PROPERTIES) {
perm |= Permissions.SET_PROPERTY;
} else {
if ((privs & ADD_PROPERTIES) == ADD_PROPERTIES) {
perm |= Permissions.ADD_PROPERTY;
}
if ((privs & ALTER_PROPERTIES) == ALTER_PROPERTIES) {
perm |= Permissions.MODIFY_PROPERTY;
}
if ((privs & REMOVE_PROPERTIES) == REMOVE_PROPERTIES) {
perm |= Permissions.REMOVE_PROPERTY;
}
}
// add_node permission is granted through privilege on the parent.
if ((parentPrivs & ADD_CHILD_NODES) == ADD_CHILD_NODES) {
perm |= Permissions.ADD_NODE;
}
/*
remove_node is
allowed: only if remove_child_nodes privilege is present on
the parent AND remove_node is present on the node itself
denied : if either remove_child_nodes is denied on the parent
OR remove_node is denied on the node itself.
*/
if (isAllow) {
if ((parentPrivs & REMOVE_CHILD_NODES) == REMOVE_CHILD_NODES &&
(privs & REMOVE_NODE) == REMOVE_NODE) {
perm |= Permissions.REMOVE_NODE;
}
} else {
if ((parentPrivs & REMOVE_CHILD_NODES) == REMOVE_CHILD_NODES ||
(privs & REMOVE_NODE) == REMOVE_NODE) {
perm |= Permissions.REMOVE_NODE;
}
}
// modify_child_node_collection permission
if ((privs & ADD_CHILD_NODES) == ADD_CHILD_NODES &&
(privs & REMOVE_CHILD_NODES) == REMOVE_CHILD_NODES) {
perm |= Permissions.MODIFY_CHILD_NODE_COLLECTION;
}
// the remaining (special) permissions are simply defined on the node
if ((privs & READ_AC) == READ_AC) {
perm |= Permissions.READ_ACCESS_CONTROL;
}
if ((privs & MODIFY_AC) == MODIFY_AC) {
perm |= Permissions.MODIFY_ACCESS_CONTROL;
}
if ((privs & LIFECYCLE_MNGMT) == LIFECYCLE_MNGMT) {
perm |= Permissions.LIFECYCLE_MANAGEMENT;
}
if ((privs & LOCK_MNGMT) == LOCK_MNGMT) {
perm |= Permissions.LOCK_MANAGEMENT;
}
if ((privs & NODE_TYPE_MNGMT) == NODE_TYPE_MNGMT) {
perm |= Permissions.NODE_TYPE_MANAGEMENT;
}
if ((privs & RETENTION_MNGMT) == RETENTION_MNGMT) {
perm |= Permissions.RETENTION_MANAGEMENT;
}
if ((privs & VERSION_MNGMT) == VERSION_MNGMT) {
perm |= Permissions.VERSION_MANAGEMENT;
}
if ((privs & WORKSPACE_MNGMT) == WORKSPACE_MNGMT) {
perm |= Permissions.WORKSPACE_MANAGEMENT;
}
if ((privs & NODE_TYPE_DEF_MNGMT) == NODE_TYPE_DEF_MNGMT) {
perm |= Permissions.NODE_TYPE_DEFINITION_MANAGEMENT;
}
if ((privs & NAMESPACE_MNGMT) == NAMESPACE_MNGMT) {
perm |= Permissions.NAMESPACE_MANAGEMENT;
}
if ((privs & PRIVILEGE_MNGMT) == PRIVILEGE_MNGMT) {
perm |= Permissions.PRIVILEGE_MANAGEMENT;
}
if ((privs & USER_MNGMT) == USER_MNGMT) {
perm |= Permissions.USER_MANAGEMENT;
}
if ((privs & INDEX_DEFINITION_MNGMT) == INDEX_DEFINITION_MNGMT) {
perm |= Permissions.INDEX_DEFINITION_MANAGEMENT;
}
return perm;
}
/**
* Returns {@code true} if this privilege bits includes no privileges
* at all.
*
* @return {@code true} if this privilege bits includes no privileges
* at all; {@code false} otherwise.
* @see org.apache.jackrabbit.oak.spi.security.authorization.permission.Permissions#NO_PERMISSION
*/
public boolean isEmpty() {
return d.isEmpty();
}
/**
* Returns an unmodifiable instance.
*
* @return an unmodifiable {@code PrivilegeBits} instance.
*/
@NotNull
public PrivilegeBits unmodifiable() {
if (d instanceof ModifiableData) {
if (d.isSimple()) {
return getInstance(d.longValue());
} else {
long[] bits = d.longValues();
long[] copy = new long[bits.length];
System.arraycopy(bits, 0, copy, 0, bits.length);
return getInstance(copy);
}
} else {
return this;
}
}
@NotNull
public PrivilegeBits modifiable() {
if (d instanceof ModifiableData) {
return this;
} else {
return getInstance(this);
}
}
/**
* Returns {@code true} if all privileges defined by the specified
* {@code otherBits} are present in this instance.
*
* @param otherBits
* @return {@code true} if all privileges defined by the specified
* {@code otherBits} are included in this instance; {@code false}
* otherwise.
*/
public boolean includes(@NotNull PrivilegeBits otherBits) {
return d.includes(otherBits.d);
}
/**
* Adds the other privilege bits to this instance.
*
* @param other The other privilege bits to be added.
* @return The updated instance.
* @throws UnsupportedOperationException if this instance is immutable.
*/
@NotNull
public PrivilegeBits add(@NotNull PrivilegeBits other) {
if (d instanceof ModifiableData) {
((ModifiableData) d).add(other.d);
return this;
} else {
throw unsupported();
}
}
/**
* Subtracts the other PrivilegeBits from the this.<br>
* If the specified bits do not intersect with this, it isn't modified.<br>
* If {@code this} is included in {@code other} {@link #EMPTY empty}
* privilege bits is returned.
*
* @param other The other privilege bits to be subtracted from this instance.
* @return The updated instance.
* @throws UnsupportedOperationException if this instance is immutable.
*/
@NotNull
public PrivilegeBits diff(@NotNull PrivilegeBits other) {
if (d instanceof ModifiableData) {
((ModifiableData) d).diff(other.d);
return this;
} else {
throw unsupported();
}
}
/**
* Subtracts the {@code b} from {@code a} and adds the result (diff)
* to this instance.
*
* @param a An instance of privilege bits.
* @param b An instance of privilege bits.
* @return The updated instance.
* @throws UnsupportedOperationException if this instance is immutable.
*/
@NotNull
public PrivilegeBits addDifference(@NotNull PrivilegeBits a, @NotNull PrivilegeBits b) {
if (d instanceof ModifiableData) {
((ModifiableData) d).addDifference(a.d, b.d);
return this;
} else {
throw unsupported();
}
}
/**
* Retains the elements in this {@code PrivilegeBits} that are contained in
* the specified other {@code PrivilegeBits}.
*
* @param other Other privilege bits.
* @return This modifiable instance of privilege bits modified such it contains
* only privileges that were also contained in the {@code other} instance.
*/
@NotNull
public PrivilegeBits retain(@NotNull PrivilegeBits other) {
if (d instanceof ModifiableData) {
((ModifiableData) d).retain(other.d);
return this;
} else {
throw unsupported();
}
}
@NotNull
public PropertyState asPropertyState(String name) {
return PropertyStates.createProperty(name, Longs.asList(d.longValues()), Type.LONGS);
}
/**
* Method to calculate the next privilege bits associated with this instance.
*
* @return an new instance of {@code PrivilegeBits}
*/
@NotNull
public PrivilegeBits nextBits() {
if (this == EMPTY) {
return EMPTY;
} else {
return new PrivilegeBits(d.next());
}
}
/**
* Write this instance as property to the specified tree.
*
* @param tree The target tree.
*/
public void writeTo(@NotNull Tree tree) {
String name = (REP_PRIVILEGES.equals(tree.getName())) ? REP_NEXT : REP_BITS;
tree.setProperty(asPropertyState(name));
}
private static UnsupportedOperationException unsupported() {
return new UnsupportedOperationException("immutable privilege bits");
}
//-------------------------------------------------------------< Object >---
@Override
public int hashCode() {
return d.hashCode();
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (o instanceof PrivilegeBits) {
return d.equals(((PrivilegeBits) o).d);
} else {
return false;
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("PrivilegeBits: ");
if (d.isSimple()) {
sb.append(d.longValue());
} else {
sb.append(Arrays.toString(d.longValues()));
}
return sb.toString();
}
//------------------------------------------------------< inner classes >---
/**
* Base class for the internal privilege bits representation and handling.
*/
private abstract static class Data {
abstract boolean isEmpty();
abstract long longValue();
abstract long[] longValues();
abstract boolean isSimple();
abstract Data next();
abstract boolean includes(Data other);
/**
* Checks if all {@code otherBits} is already included in {@code bits}.
* <p>
* Truth table:
* <pre>
* | b\o | 0 | 1 |
* | 0 | 1 | 0 |
* | 1 | 1 | 1 |
* </pre>
* @param bits the super set of bits
* @param otherBits the bits to check against
* @return {@code true} if all other bits are included in bits.
*/
static boolean includes(long bits, long otherBits) {
return (bits | ~otherBits) == -1;
}
/**
* Checks if all {@code otherBits} is already included in {@code bits}.
* <p>
* Truth table:
* <pre>
* | b\o | 0 | 1 |
* | 0 | 1 | 0 |
* | 1 | 1 | 1 |
* </pre>
* @param bits the super set of bits
* @param otherBits the bits to check against
* @return {@code true} if all other bits are included in bits.
*/
static boolean includes(long[] bits, long[] otherBits) {
if (otherBits.length <= bits.length) {
// test for each long if is included
for (int i = 0; i < otherBits.length; i++) {
if ((bits[i] | ~otherBits[i]) != -1) {
return false;
}
}
return true;
} else {
// otherbits array is longer > cannot be included in bits
return false;
}
}
}
/**
* Immutable Data object
*/
private static final class UnmodifiableData extends Data {
private static final long MAX = Long.MAX_VALUE / 2;
private static final UnmodifiableData EMPTY = new UnmodifiableData(NO_PRIVILEGE);
private final long bits;
private final long[] bitsArr;
private final boolean isSimple;
private UnmodifiableData(long bits) {
this.bits = bits;
bitsArr = null;
isSimple = true;
}
private UnmodifiableData(long[] bitsArr) {
bits = NO_PRIVILEGE;
this.bitsArr = bitsArr;
isSimple = false;
}
@Override
boolean isEmpty() {
return this == EMPTY;
}
@Override
long longValue() {
return bits;
}
@Override
long[] longValues() {
if (isSimple) {
return new long[] { bits };
}
return bitsArr;
}
@Override
boolean isSimple() {
return isSimple;
}
@Override
Data next() {
if (this == EMPTY) {
return EMPTY;
} else if (isSimple) {
if (bits < MAX) {
long b = bits << 1;
return new UnmodifiableData(b);
} else {
return new UnmodifiableData(new long[]{bits}).next();
}
} else {
long[] bts;
long last = bitsArr[bitsArr.length - 1];
if (last < MAX) {
bts = new long[bitsArr.length];
System.arraycopy(bitsArr, 0, bts, 0, bitsArr.length);
bts[bts.length - 1] = last << 1;
} else {
bts = new long[bitsArr.length + 1];
bts[bts.length - 1] = 1;
}
return new UnmodifiableData(bts);
}
}
@Override
boolean includes(Data other) {
if (isSimple) {
return (other.isSimple()) && includes(bits, other.longValue());
} else {
return includes(bitsArr, other.longValues());
}
}
//---------------------------------------------------------< Object >---
@Override
public int hashCode() {
return (isSimple) ? Long.valueOf(bits).hashCode() : Arrays.hashCode(bitsArr);
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (o instanceof UnmodifiableData) {
UnmodifiableData d = (UnmodifiableData) o;
if (isSimple != d.isSimple) {
return false;
}
if (isSimple) {
return bits == d.bits;
} else {
return Arrays.equals(bitsArr, d.bitsArr);
}
} else {
return false;
}
}
}
/**
* Mutable implementation of the Data base class.
*/
private static final class ModifiableData extends Data {
private long[] bits;
private ModifiableData() {
bits = new long[]{NO_PRIVILEGE};
}
@Override
boolean isEmpty() {
return bits.length == 1 && bits[0] == NO_PRIVILEGE;
}
@Override
long longValue() {
return (bits.length == 1) ? bits[0] : NO_PRIVILEGE;
}
@Override
long[] longValues() {
return bits;
}
@Override
boolean isSimple() {
return bits.length == 1;
}
@Override
Data next() {
throw new UnsupportedOperationException("Not implemented.");
}
@Override
boolean includes(Data other) {
if (bits.length == 1) {
return other.isSimple() && includes(bits[0], other.longValue());
} else {
return includes(bits, other.longValues());
}
}
/**
* Add the other Data to this instance.
*
* @param other
*/
private void add(Data other) {
if (other != this) {
if (bits.length == 1 && other.isSimple()) {
bits[0] |= other.longValue();
} else {
or(other.longValues());
}
}
}
/**
* Subtract the other Data from this instance.
*
* @param other
*/
private void diff(Data other) {
if (bits.length == 1 && other.isSimple()) {
bits[0] = bits[0] & ~other.longValue();
} else {
bits = diff(bits, other.longValues());
}
}
/**
* Add the diff between the specified Data a and b.
*
* @param a
* @param b
*/
private void addDifference(Data a, Data b) {
if (a.isSimple() && b.isSimple()) {
bits[0] |= a.longValue() & ~b.longValue();
} else {
long[] diff = diff(a.longValues(), b.longValues());
or(diff);
}
}
private void or(long[] b) {
if (b.length > bits.length) {
// enlarge the array
long[] res = new long[b.length];
System.arraycopy(bits, 0, res, 0, bits.length);
bits = res;
}
for (int i = 0; i < b.length; i++) {
bits[i] |= b[i];
}
}
private void retain(Data other) {
if (isSimple()) {
bits[0] &= other.longValue();
} else {
long[] lvs = longValues();
long[] bLvs = other.longValues();
long[] res = (lvs.length <= bLvs.length) ? new long[lvs.length] : new long[bLvs.length];
int compactSize = -1;
for (int i = 0; i < res.length; i++) {
res[i] = (lvs[i] & bLvs[i]);
if (res[i] == 0) {
if (compactSize == -1) {
compactSize = i+1;
}
} else {
compactSize = -1;
}
}
if (compactSize != -1 && res.length > compactSize) {
bits = Arrays.copyOfRange(res, 0, compactSize);
} else {
bits = res;
}
}
}
private static long[] diff(long[] a, long[] b) {
int index = -1;
long[] res = new long[((a.length > b.length) ? a.length : b.length)];
for (int i = 0; i < res.length; i++) {
if (i < a.length && i < b.length) {
res[i] = a[i] & ~b[i];
} else {
res[i] = (i < a.length) ? a[i] : 0;
}
// remember start of trailing 0 array entries
if (res[i] != 0) {
index = -1;
} else if (index == -1) {
index = i;
}
}
switch (index) {
case -1:
// no need to remove trailing 0-long from the array
return res;
case 0:
// array consisting of one or multiple 0
return new long[]{NO_PRIVILEGE};
default:
// remove trailing 0-long entries from the array
long[] r2 = new long[index];
System.arraycopy(res, 0, r2, 0, index);
return r2;
}
}
}
}
|
package org.nervos.mercury.model.req;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
import org.nervos.ckb.address.AddressUtils;
import org.nervos.ckb.address.CodeHashType;
/** @author zjh @Created Date: 2021/7/17 @Description: @Modify by: */
public abstract class QueryAddress
implements JsonSerializer<QueryAddress>, JsonDeserializer<QueryAddress> {
public abstract String getAddress();
@Override
public QueryAddress deserialize(
JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
if (json.getAsJsonObject().has("KeyAddress")) {
return new KeyAddress(json.getAsJsonObject().get("KeyAddress").getAsString());
} else {
return new NormalAddress(json.getAsJsonObject().get("NormalAddress").getAsString());
}
}
public static QueryAddress getQueryAddressByAddress(String address) {
if (AddressUtils.parseAddressType(address) == CodeHashType.BLAKE160) {
return new KeyAddress(address);
}
return new NormalAddress(address);
}
@Override
public JsonElement serialize(QueryAddress src, Type typeOfSrc, JsonSerializationContext context) {
return context.serialize(src, src.getClass());
}
}
|
package io.luna.net.client;
import io.luna.LunaContext;
import io.luna.game.model.World;
import io.luna.game.model.mob.Player;
import io.luna.game.model.mob.PlayerCredentials;
import io.luna.game.model.mob.persistence.PlayerData;
import io.luna.game.service.LoginService;
import io.luna.game.service.LoginService.LoginRequest;
import io.luna.net.codec.game.GameMessageDecoder;
import io.luna.net.codec.game.GameMessageEncoder;
import io.luna.net.codec.login.LoginRequestMessage;
import io.luna.net.codec.login.LoginResponse;
import io.luna.net.codec.login.LoginResponseMessage;
import io.luna.net.msg.GameMessageRepository;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import org.mindrot.jbcrypt.BCrypt;
/**
* A {@link Client} implementation model representing login protocol I/O communications.
*
* @author lare96 <http://github.com/lare96>
*/
public class LoginClient extends Client<LoginRequestMessage> {
/**
* The context instance.
*/
private final LunaContext context;
/**
* The message repository.
*/
private final GameMessageRepository messageRepository;
/**
* The world.
*/
private final World world;
/**
* The login service.
*/
private final LoginService loginService;
/**
* Creates a new {@link Client}.
*
* @param channel The client's channel.
* @param messageRepository The message repository.
*/
public LoginClient(Channel channel, LunaContext context, GameMessageRepository messageRepository) {
super(channel);
this.context = context;
this.messageRepository = messageRepository;
world = context.getWorld();
loginService = world.getLoginService();
}
@Override
void onMessageReceived(LoginRequestMessage msg) {
String username = msg.getUsername();
String password = msg.getPassword();
var player = new Player(context, new PlayerCredentials(username, password));
if (!username.matches("^[a-z0-9_ ]{1,12}$") || password.isEmpty() || password.length() > 20) {
// Username/password format invalid, drop connection.
channel.close();
} else {
// Passed initial check, submit login request.
loginService.submit(username, new LoginRequest(player, this, msg));
}
}
/**
* Sends a login response to the client. Will add a disconnect listener for any response that isn't {@link LoginResponse#NORMAL}.
*/
public void sendLoginResponse(Player player, LoginResponse response) {
var channelFuture = channel.writeAndFlush(new LoginResponseMessage(response, player.getRights(), false));
if (response != LoginResponse.NORMAL) {
channelFuture.addListener(ChannelFutureListener.CLOSE);
}
}
/**
* Determines what the login response should be once the player's data is loaded.
*
* @param data The loaded data.
* @param enteredPassword The entered password.
*/
public LoginResponse getLoginResponse(PlayerData data, String enteredPassword) {
if (data == null) {
return LoginResponse.NORMAL;
} else if (!BCrypt.checkpw(enteredPassword, data.password)) {
return LoginResponse.INVALID_CREDENTIALS;
} else if (data.isBanned()) {
return LoginResponse.ACCOUNT_BANNED;
} else {
return LoginResponse.NORMAL;
}
}
/**
* Sends the final login response before the player is added to the world.
*
* @param player The player.
* @param data The data to sync with the player.
* @param message The login request message.
* @return {@code true} if the final login response {@link LoginResponse#NORMAL}.
*/
public boolean sendFinalLoginResponse(Player player, PlayerData data, LoginRequestMessage message) {
if (world.getPlayers().isFull()) {
sendLoginResponse(player, LoginResponse.WORLD_FULL);
return false;
} else if (world.getLogoutService().isSavePending(player.getUsername()) || world.getPlayer(player.getUsernameHash()).isPresent()) {
sendLoginResponse(player, LoginResponse.ACCOUNT_ONLINE);
return false;
} else {
var gameClient = new GameClient(channel, messageRepository);
channel.attr(KEY).set(gameClient);
player.setClient(gameClient);
player.loadData(data);
sendLoginResponse(player, LoginResponse.NORMAL);
var pipeline = channel.pipeline();
var messageEncoder = new GameMessageEncoder(message.getEncryptor());
var messageDecoder = new GameMessageDecoder(message.getDecryptor(), messageRepository);
pipeline.replace("login-encoder", "game-encoder", messageEncoder);
pipeline.replace("login-decoder", "game-decoder", messageDecoder);
return true;
}
}
}
|
package net.openhft.chronicle.wire.method;
import net.openhft.chronicle.wire.TextMethodTester;
import net.openhft.chronicle.wire.WireTestCommon;
import net.openhft.chronicle.wire.YamlMethodTester;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class TextMethodTesterTest extends WireTestCommon {
@SuppressWarnings("rawtypes")
@Test
public void run() throws IOException {
TextMethodTester test = new TextMethodTester<>(
"methods-out.yaml",
MockMethodsImpl::new,
MockMethods.class,
"methods-out.yaml")
.setup("methods-out.yaml") // calls made here are not validated in the output.
.run();
assertEquals(test.expected(), test.actual());
}
@Test
public void runTestEmptyOut() throws IOException {
TextMethodTester test = new TextMethodTester<>(
"methods-out.yaml",
NoopMockMethods::new,
MockMethods.class,
"methods-out-empty.yaml")
.setup("methods-out.yaml") // calls made here are not validated in the output.
.run();
assertEquals(test.expected(), test.actual());
}
@SuppressWarnings("rawtypes")
@Test
public void runYaml() throws IOException {
TextMethodTester test = new YamlMethodTester<>(
"methods-out.yaml",
MockMethodsImpl::new,
MockMethods.class,
"methods-out.yaml")
.setup("methods-out.yaml") // calls made here are not validated in the output.
.run();
assertEquals(test.expected(), test.actual());
}
@Test
public void checkExceptionsProvidedToHandler() throws IOException {
List<Exception> exceptions = new ArrayList<>();
TextMethodTester test = new TextMethodTester<>(
"methods-in-exception.yaml",
MockMethodsImpl::new,
MockMethods.class,
"methods-out-empty.yaml")
.onInvocationException(e -> exceptions.add(e))
.run();
assertEquals(test.expected(), test.actual());
assertEquals(3, exceptions.size());
}
}
|
package spelling;
import java.util.LinkedList;
/**
* A class that implements the Dictionary interface using a LinkedList
* @author Pei-Hsuan Chu
*/
public class DictionaryLL implements Dictionary
{
private LinkedList<String> dict;
// TODO: Add a constructor
public DictionaryLL(){
dict = new LinkedList<String>();
}
/** Add this word to the dictionary. Convert it to lowercase first
* for the assignment requirements.
* @param word The word to add
* @return true if the word was added to the dictionary
* (it wasn't already there). */
public boolean addWord(String word) {
// TODO: Implement this method
if(word==null){
System.out.println("uuu");
throw new NullPointerException("Word inserted cannot be empty");
}
else if(dict.contains(word.toLowerCase())){
return false;
}
else{
dict.add(word.toLowerCase());
//System.out.println("insert: "+word.toLowerCase());
return true;
}
}
/** Return the number of words in the dictionary */
public int size()
{
// TODO: Implement this method
//System.out.println("size is : "+dict.size());
return dict.size();
}
/** Is this a word according to this dictionary? */
public boolean isWord(String s) {
//TODO: Implement this method
int i = 0;
for(String scan: dict){
i+=1;
System.out.println("scan:"+scan+" "+i);
if(s.toLowerCase().equals(scan))
return true;
}
return false;
}
}
|
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* CustomFieldValueError.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.axis.v201705;
/**
* Errors specific to editing custom field values
*/
public class CustomFieldValueError extends com.google.api.ads.dfp.axis.v201705.ApiError implements java.io.Serializable {
/* The error reason represented by an enum. */
private com.google.api.ads.dfp.axis.v201705.CustomFieldValueErrorReason reason;
public CustomFieldValueError() {
}
public CustomFieldValueError(
java.lang.String fieldPath,
com.google.api.ads.dfp.axis.v201705.FieldPathElement[] fieldPathElements,
java.lang.String trigger,
java.lang.String errorString,
com.google.api.ads.dfp.axis.v201705.CustomFieldValueErrorReason reason) {
super(
fieldPath,
fieldPathElements,
trigger,
errorString);
this.reason = reason;
}
@Override
public String toString() {
return com.google.common.base.MoreObjects.toStringHelper(this.getClass())
.omitNullValues()
.add("errorString", getErrorString())
.add("fieldPath", getFieldPath())
.add("fieldPathElements", getFieldPathElements())
.add("reason", getReason())
.add("trigger", getTrigger())
.toString();
}
/**
* Gets the reason value for this CustomFieldValueError.
*
* @return reason * The error reason represented by an enum.
*/
public com.google.api.ads.dfp.axis.v201705.CustomFieldValueErrorReason getReason() {
return reason;
}
/**
* Sets the reason value for this CustomFieldValueError.
*
* @param reason * The error reason represented by an enum.
*/
public void setReason(com.google.api.ads.dfp.axis.v201705.CustomFieldValueErrorReason reason) {
this.reason = reason;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof CustomFieldValueError)) return false;
CustomFieldValueError other = (CustomFieldValueError) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = super.equals(obj) &&
((this.reason==null && other.getReason()==null) ||
(this.reason!=null &&
this.reason.equals(other.getReason())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = super.hashCode();
if (getReason() != null) {
_hashCode += getReason().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(CustomFieldValueError.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201705", "CustomFieldValueError"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("reason");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201705", "reason"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201705", "CustomFieldValueError.Reason"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
|
package org.ml_methods_group.common;
import javax.annotation.Nonnull;
import java.io.Serializable;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class Dataset implements Serializable, Iterable<Solution> {
private final List<Solution> values;
public Dataset(Collection<Solution> values) {
this(new ArrayList<>(values));
}
private Dataset(ArrayList<Solution> values) {
this.values = values;
}
public Dataset filter(Predicate<Solution> predicate) {
return new Dataset(getValues(predicate));
}
public List<Solution> getValues() {
return Collections.unmodifiableList(values);
}
public List<Solution> getValues(Predicate<Solution> predicate) {
return values.stream()
.filter(predicate)
.collect(Collectors.toList());
}
@Nonnull
@Override
public Iterator<Solution> iterator() {
return values.iterator();
}
}
|
package jdk6.test2;
/*
* 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.
*/
/**
* Sample class inside the package to be included in the javadoc
*
* @author <a href="mailto:vincent.siveton@gmail.com">Vincent Siveton</a>
*/
public class App2
{
/**
* The main method
*
* @param args an array of strings that contains the arguments
*/
public static void main( String[] args )
{
System.out.println( "Sample Application." );
}
/**
* Sample method that prints out the parameter string.
*
* @param str The string value to be printed.
*/
protected void sampleMethod( String str )
{
System.out.println( str );
}
}
|
package com.podio.item;
import java.util.List;
import org.codehaus.jackson.annotate.JsonProperty;
public class AppActivities {
private List<AppActivity> today;
private List<AppActivity> lastWeek;
public List<AppActivity> getToday() {
return today;
}
public void setToday(List<AppActivity> today) {
this.today = today;
}
public List<AppActivity> getLastWeek() {
return lastWeek;
}
@JsonProperty("last_week")
public void setLastWeek(List<AppActivity> lastWeek) {
this.lastWeek = lastWeek;
}
}
|
package org.convertertopdf.convert.implementation;
import org.convertertopdf.convert.OfficeConverter;
import org.convertertopdf.management.ConverterFactory;
import org.convertertopdf.util.EFormat;
import org.jodconverter.document.DefaultDocumentFormatRegistry;
import org.jodconverter.document.DocumentFormat;
/**
* Class responsable to convert DOC files to PDF.
*
* @author Thiago Leite e-mail: thiagoleiteecarvalho@gmail.com
*/
public final class DocConverter extends OfficeConverter {
/**
* This constructor should not be used directly. Only {@link ConverterFactory} is allowed to use it.
* @param skipValidation Indicates that validation should not be performed
*/
public DocConverter(boolean skipValidation) {
super(skipValidation);
}
/** {@inheritDoc} */
public EFormat getFormat() {
return EFormat.DOC;
}
/** {@inheritDoc} */
@Override
protected DocumentFormat getDocumentFormat() {
return DefaultDocumentFormatRegistry.DOC;
}
}
|
package es.amplia.oda.datastreams.mqtt;
import es.amplia.oda.comms.mqtt.api.MqttClientFactory;
import es.amplia.oda.comms.mqtt.api.MqttClientFactoryProxy;
import es.amplia.oda.core.commons.adc.AdcService;
import es.amplia.oda.core.commons.entities.ContentType;
import es.amplia.oda.core.commons.interfaces.DatastreamsGetter;
import es.amplia.oda.core.commons.interfaces.DatastreamsSetter;
import es.amplia.oda.core.commons.mqtt.MqttDatastreamsService;
import es.amplia.oda.core.commons.osgi.proxies.EventPublisherProxy;
import es.amplia.oda.core.commons.osgi.proxies.SerializerProxy;
import es.amplia.oda.core.commons.utils.*;
import es.amplia.oda.datastreams.mqtt.configuration.MqttDatastreamsConfigurationUpdateHandler;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Activator implements BundleActivator {
private static final Logger LOGGER = LoggerFactory.getLogger(Activator.class);
private MqttClientFactoryProxy mqttClientFactory;
private SerializerProxy serializer;
private EventPublisherProxy eventPublisher;
private MqttDatastreamsConfigurationUpdateHandler configHandler;
private ConfigurableBundle configurableBundle;
private ServiceRegistration<MqttDatastreamsService> mqttDatastreamServiceRegistration;
private ServiceListenerBundle<MqttClientFactory> mqttClientFactoryListener;
private MqttDatastreamsOrchestrator mqttDatastreamsOrchestrator;
@Override
public void start(BundleContext bundleContext) {
LOGGER.info("Starting MQTT datastreams bundle");
mqttClientFactory = new MqttClientFactoryProxy(bundleContext);
serializer = new SerializerProxy(bundleContext, ContentType.CBOR);
eventPublisher = new EventPublisherProxy(bundleContext);
ServiceRegistrationManagerWithKey<String, DatastreamsGetter> mqttDatastreamsGetterRegistrationManager =
new ServiceRegistrationManagerWithKeyOsgi<>(bundleContext, DatastreamsGetter.class);
ServiceRegistrationManagerWithKey<String, DatastreamsSetter> mqttDatastreamsSetterRegistrationManager =
new ServiceRegistrationManagerWithKeyOsgi<>(bundleContext, DatastreamsSetter.class);
mqttDatastreamsOrchestrator = new MqttDatastreamsOrchestrator(mqttClientFactory, serializer, eventPublisher,
mqttDatastreamsGetterRegistrationManager, mqttDatastreamsSetterRegistrationManager);
configHandler = new MqttDatastreamsConfigurationUpdateHandler(mqttDatastreamsOrchestrator);
mqttDatastreamServiceRegistration = bundleContext.registerService(MqttDatastreamsService.class,
mqttDatastreamsOrchestrator, null);
configurableBundle = new ConfigurableBundleImpl(bundleContext, configHandler);
mqttClientFactoryListener = new ServiceListenerBundle<>(bundleContext, MqttClientFactory.class,
this::onServiceChanged);
LOGGER.info("MQTT datastreams bundle started");
}
void onServiceChanged() {
try {
LOGGER.info("Applying new configuration for MQTT datastreams bundle");
configHandler.applyConfiguration();
} catch (Exception e) {
LOGGER.error("Error applying MQTT Datastreams configuration after MQTT Client Factory service changed: {0}",
e);
}
}
@Override
public void stop(BundleContext bundleContext) {
LOGGER.info("Stopping MQTT datastreams bundle");
mqttClientFactoryListener.close();
configurableBundle.close();
mqttDatastreamServiceRegistration.unregister();
mqttDatastreamsOrchestrator.close();
mqttClientFactory.close();
serializer.close();
eventPublisher.close();
LOGGER.info("MQTT datastreams bundle stopped");
}
}
|
package com.zygon.htm.sdr.core;
import com.zygon.htm.core.io.Input;
import com.zygon.htm.core.io.InputReceiver;
import com.zygon.htm.core.io.OutputProvider;
import java.util.Collection;
/**
*
* @author zygon
* @param <T>
*/
public class SynapseSet<T extends Input<?>> implements InputConductor {
/**
* This is the synapse overlap percentage required for the segment
* to be considered. If the segment does not reach this threshold
* then its overlap is set to 0.
*/
private static final double STIMULUS_OVERLAP_PCT = 0.1;
private final Collection<Synapse<T>> synapses;
public SynapseSet(Collection<Synapse<T>> synapses) {
this.synapses = synapses;
}
@Override
public double getValue() {
int connectedCount = 0;
for (Synapse synapse : this.synapses) {
synapse.activateNewInput();
if (synapse.isConnected() && synapse.getOutput() != null && synapse.getOutput().isActive()) {
connectedCount ++;
}
}
double overlap = (double) connectedCount / this.synapses.size();
if (overlap > 0.0 && overlap < STIMULUS_OVERLAP_PCT) {
overlap = 0.0;
}
return overlap;
}
void addOutputProviders(Collection<OutputProvider> outputProviders) {
for (Synapse syn : this.synapses) {
outputProviders.add(syn);
}
}
void addInputReceivers(Collection<InputReceiver> inputReceivers) {
for (Synapse syn : this.synapses) {
inputReceivers.add(syn);
}
}
@Override
public void provideFeedback(Feedback feedback) {
for (Feedback.Type type : feedback.getTypes()) {
switch (type) {
case ACTIVE_DUTY_CYCLE:
for (Synapse synapse : this.synapses) {
synapse.increasePermanence();
}
break;
case BOOST:
break;
case NEGATIVE: // fall through
case POSITIVE:
for (Synapse synapse : this.synapses) {
synapse.adjustPermanence();
}
break;
}
}
}
}
|
/*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright 2022 Gerrit Grunwald.
*
* 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 eu.hansolo.fx.glucostatus;
import com.dustinredmond.fxtrayicon.FXTrayIcon;
import eu.hansolo.applefx.MacosButton;
import eu.hansolo.applefx.MacosControl;
import eu.hansolo.applefx.MacosLabel;
import eu.hansolo.applefx.MacosScrollPane;
import eu.hansolo.applefx.MacosSeparator;
import eu.hansolo.applefx.MacosSlider;
import eu.hansolo.applefx.MacosSwitch;
import eu.hansolo.applefx.MacosSwitchBuilder;
import eu.hansolo.applefx.MacosTextField;
import eu.hansolo.applefx.MacosToggleButton;
import eu.hansolo.applefx.MacosToggleButtonBar;
import eu.hansolo.applefx.MacosToggleButtonBarSeparator;
import eu.hansolo.applefx.MacosWindow;
import eu.hansolo.applefx.MacosWindow.Style;
import eu.hansolo.applefx.tools.MacosSystemColor;
import eu.hansolo.fx.glucostatus.Records.DataPoint;
import eu.hansolo.fx.glucostatus.Records.GlucoEntry;
import eu.hansolo.fx.glucostatus.Statistics.StatisticCalculation;
import eu.hansolo.fx.glucostatus.Statistics.StatisticRange;
import eu.hansolo.fx.glucostatus.i18n.I18nKeys;
import eu.hansolo.fx.glucostatus.i18n.Translator;
import eu.hansolo.fx.glucostatus.notification.Notification;
import eu.hansolo.fx.glucostatus.notification.NotificationBuilder;
import eu.hansolo.fx.glucostatus.notification.Notifier;
import eu.hansolo.fx.glucostatus.notification.NotifierBuilder;
import eu.hansolo.jdktools.Architecture;
import eu.hansolo.jdktools.OperatingSystem;
import eu.hansolo.jdktools.util.Helper.OsArcMode;
import eu.hansolo.toolbox.tuples.Pair;
import eu.hansolo.toolbox.unit.UnitDefinition;
import eu.hansolo.toolboxfx.HelperFX;
import eu.hansolo.toolboxfx.geom.Point;
import javafx.animation.FadeTransition;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Task;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.CheckMenuItem;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.CustomMenuItem;
import javafx.scene.control.Dialog;
import javafx.scene.control.DialogPane;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.effect.BlurType;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.Border;
import javafx.scene.layout.BorderStroke;
import javafx.scene.layout.BorderStrokeStyle;
import javafx.scene.layout.BorderWidths;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.media.AudioClip;
import javafx.scene.paint.Color;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.LinearGradient;
import javafx.scene.paint.Paint;
import javafx.scene.paint.Stop;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.SVGPath;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.util.Duration;
import javax.swing.*;
import java.io.IOException;
import java.net.http.HttpResponse;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import static eu.hansolo.toolbox.unit.UnitDefinition.MILLIGRAM_PER_DECILITER;
import static eu.hansolo.toolbox.unit.UnitDefinition.MILLIMOL_PER_LITER;
public class Main extends Application {
private static final Insets GRAPH_INSETS = new Insets(5, 10, 5, 10);
private final Image icon = new Image(Main.class.getResourceAsStream("icon48x48.png"));
private final Image stageIcon = new Image(Main.class.getResourceAsStream("icon128x128.png"));
private final Translator translator = new Translator(I18nKeys.RESOURCE_NAME);
private ZonedDateTime lastUpdate = ZonedDateTime.now().minusMinutes(6);
private ZonedDateTime lastFullUpdate = ZonedDateTime.now().minusMinutes(5);
private AtomicBoolean switchingUnits = new AtomicBoolean(false);
private String nightscoutUrl = "";
private String nightscoutToken = "";
private MacosWindow macosWindow;
private boolean trayIconSupported;
private OsArcMode sysinfo;
private OperatingSystem operatingSystem;
private Architecture architecture;
private boolean darkMode;
private Color accentColor;
private ZonedDateTime lastNotification;
private ZonedDateTime lastSpeak;
private String voice;
private Notifier notifier;
private AudioClip notificationSound;
private Dialog aboutDialog;
private Stage stage;
private Region glassOverlay;
private HBox buttonHBox;
private AnchorPane mainPane;
private SVGPath reloadButton;
private SVGPath timeInRangeChartButton;
private SVGPath patternChartButton;
private SVGPath matrixButton;
private SVGPath exclamationMark;
private MacosLabel titleLabel;
private MacosLabel valueLabel;
private HBox last5DeltasLabel;
private MacosLabel timestampLabel;
private MacosLabel rangeAverageLabel;
private Text unit;
private Text delta0;
private Text delta1;
private Text delta2;
private Text delta3;
private Text delta4;
private AnchorPane vpane;
private StackPane pane;
private StackPane prefPane;
private MacosTextField nightscoutUrlTextField;
private MacosTextField nightscoutTokenTextField;
private MacosSwitch unitSwitch;
private MacosSwitch deltaChartSwitch;
private MacosSwitch voiceOutputSwitch;
private MacosSlider voiceOutputIntervalSlider;
private MacosSwitch tooLowSoundSwitch;
private MacosSwitch tooLowSpeakSwitch;
private MacosSwitch enableLowSoundSwitch;
private MacosSwitch lowSoundSwitch;
private MacosSwitch lowSpeakSwitch;
private MacosSwitch enableAcceptableLowSoundSwitch;
private MacosSwitch acceptableLowSoundSwitch;
private MacosSwitch enableAcceptableHighSoundSwitch;
private MacosSwitch acceptableHighSoundSwitch;
private MacosSwitch enableHighSoundSwitch;
private MacosSwitch highSoundSwitch;
private MacosSwitch tooHighSoundSwitch;
private MacosSlider tooLowIntervalSlider;
private MacosSlider tooHighIntervalSlider;
private MacosSlider minAcceptableSlider;
private MacosSlider minNormalSlider;
private MacosSlider maxNormalSlider;
private MacosSlider maxAcceptableSlider;
private Canvas canvas;
private GraphicsContext ctx;
private AnchorPane chartPane;
private boolean deltaChartVisible;
private ToggleGroup intervalToggleGroup;
private MacosToggleButton sevenDays;
private MacosToggleButton seventyTwoHours;
private MacosToggleButton fourtyEightHours;
private MacosToggleButton twentyFourHours;
private MacosToggleButton twelveHours;
private MacosToggleButton sixHours;
private MacosToggleButton threeHours;
private MacosToggleButtonBar toggleButtonBar;
private AnchorPane prefContentPane;
private SVGPath settingsIcon;
private MacosButton settingsButton;
private ScheduledService<Void> service;
private double minAcceptable;
private double minNormal;
private double maxNormal;
private double maxAcceptable;
private double minAcceptableFactor;
private double minNormalFactor;
private double maxNormalFactor;
private double maxAcceptableFactor;
private UnitDefinition currentUnit;
private boolean outdated;
private ObservableList<GlucoEntry> allEntries;
private List<GlucoEntry> entries;
private List<Double> deltas;
private double avg;
private BooleanProperty dialogVisible;
private double deltaMin;
private double deltaMax;
private GlucoEntry currentEntry;
private Color currentColor;
private TimeInterval currentInterval;
private Font ticklabelFont;
private Font smallTicklabelFont;
private boolean slowlyRising;
private boolean slowlyFalling;
private boolean hideMenu;
private FXTrayIcon trayIcon;
private EventHandler<MouseEvent> eventConsumer;
private DateTimeFormatter dtf;
// ******************** Initialization ************************************
@Override public void init() {
nightscoutUrl = PropertyManager.INSTANCE.getString(Constants.PROPERTIES_NIGHTSCOUT_URL);
nightscoutToken = PropertyManager.INSTANCE.getString(Constants.PROPERTIES_NIGHTSCOUT_TOKEN, "");
sysinfo = eu.hansolo.jdktools.util.Helper.getOperaringSystemArchitectureOperatingMode();
operatingSystem = sysinfo.operatingSystem();
architecture = sysinfo.architecture();
darkMode = eu.hansolo.applefx.tools.Helper.isDarkMode();
accentColor = eu.hansolo.applefx.tools.Helper.getMacosAccentColorAsColor();
currentUnit = MILLIGRAM_PER_DECILITER;
outdated = false;
currentInterval = TimeInterval.LAST_24_HOURS;
allEntries = FXCollections.observableArrayList();
entries = new ArrayList<>();
deltas = new ArrayList<>();
dialogVisible = new SimpleBooleanProperty(false);
deltaChartVisible = false;
lastNotification = ZonedDateTime.now();
lastSpeak = ZonedDateTime.now().minusMinutes(6);
notificationSound = new AudioClip(getClass().getResource(Constants.ALARM_SOUND_FILENAME).toExternalForm());
slowlyRising = false;
slowlyFalling = false;
currentEntry = new GlucoEntry("-1", 0, OffsetDateTime.now().toEpochSecond(), OffsetDateTime.now(), "", Trend.NONE, "", "", "", 2, 0, 0, 0, 0, 0, "");
dtf = DateTimeFormatter.ofPattern(translator.get(I18nKeys.DATE_TIME_FORMAT));
// Select voice that will be used for output (only on Macos)
Locale locale = Locale.getDefault();
if (locale.equals(Locale.GERMAN)) {
voice = "Anna";
} else if (locale.equals(Locale.ITALY)) {
voice = "Alice";
} else {
voice = "Samantha";
}
updateSettings();
ticklabelFont = Fonts.sfProTextRegular(10);
smallTicklabelFont = Fonts.sfProTextRegular(8);
// ToggleButton bar on top of the app
eventConsumer = evt -> {
ToggleButton src = (ToggleButton) evt.getSource();
if (src.isSelected()) { evt.consume(); }
};
intervalToggleGroup = new ToggleGroup();
sevenDays = createToggleButton(translator.get(I18nKeys.TIME_NAME_168_HOURS), intervalToggleGroup, eventConsumer, darkMode);
seventyTwoHours = createToggleButton(translator.get(I18nKeys.TIME_NAME_72_HOURS), intervalToggleGroup, eventConsumer, darkMode);
fourtyEightHours = createToggleButton(translator.get(I18nKeys.TIME_NAME_48_HOURS), intervalToggleGroup, eventConsumer, darkMode);
twentyFourHours = createToggleButton(translator.get(I18nKeys.TIME_NAME_24_HOURS), intervalToggleGroup, eventConsumer, darkMode);
twelveHours = createToggleButton(translator.get(I18nKeys.TIME_NAME_12_HOURS), intervalToggleGroup, eventConsumer, darkMode);
sixHours = createToggleButton(translator.get(I18nKeys.TIME_NAME_6_HOURS), intervalToggleGroup, eventConsumer, darkMode);
threeHours = createToggleButton(translator.get(I18nKeys.TIME_NAME_3_HOURS), intervalToggleGroup, eventConsumer, darkMode);
twentyFourHours.setSelected(true);
MacosToggleButtonBarSeparator sep1 = createSeparator(darkMode);
MacosToggleButtonBarSeparator sep2 = createSeparator(darkMode);
MacosToggleButtonBarSeparator sep3 = createSeparator(darkMode);
MacosToggleButtonBarSeparator sep4 = createSeparator(darkMode);
MacosToggleButtonBarSeparator sep5 = createSeparator(darkMode);
MacosToggleButtonBarSeparator sep6 = createSeparator(darkMode);
toggleButtonBar = new MacosToggleButtonBar(sevenDays, sep1, seventyTwoHours, sep2, fourtyEightHours, sep3, twentyFourHours, sep4, twelveHours, sep5, sixHours, sep6, threeHours);
toggleButtonBar.setDark(darkMode);
HBox.setHgrow(toggleButtonBar, Priority.ALWAYS);
// Settings button
settingsIcon = new SVGPath();
settingsIcon.setContent("M8.005,14.887c0.084,-0 0.168,-0.005 0.252,-0.014c0.084,-0.009 0.172,-0.013 0.262,-0.013l0.415,0.794c0.042,0.084 0.104,0.146 0.185,0.185c0.081,0.039 0.17,0.052 0.266,0.04c0.205,-0.036 0.322,-0.159 0.352,-0.37l0.127,-0.884c0.162,-0.048 0.324,-0.102 0.487,-0.162c0.162,-0.061 0.325,-0.124 0.487,-0.19l0.65,0.596c0.15,0.144 0.322,0.162 0.514,0.054c0.169,-0.102 0.235,-0.259 0.199,-0.469l-0.19,-0.876c0.139,-0.096 0.276,-0.198 0.411,-0.307c0.135,-0.108 0.263,-0.222 0.383,-0.343l0.822,0.334c0.198,0.079 0.367,0.036 0.505,-0.126c0.054,-0.066 0.086,-0.146 0.095,-0.239c0.009,-0.093 -0.014,-0.179 -0.068,-0.257l-0.469,-0.758c0.096,-0.139 0.185,-0.285 0.266,-0.438c0.081,-0.153 0.161,-0.308 0.239,-0.465l0.894,0.045c0.096,0 0.183,-0.025 0.261,-0.076c0.078,-0.052 0.133,-0.122 0.163,-0.212c0.036,-0.091 0.039,-0.179 0.009,-0.267c-0.03,-0.087 -0.082,-0.161 -0.154,-0.221l-0.704,-0.55c0.043,-0.163 0.08,-0.33 0.113,-0.501c0.033,-0.172 0.059,-0.345 0.077,-0.519l0.839,-0.271c0.205,-0.072 0.307,-0.207 0.307,-0.406c-0,-0.204 -0.102,-0.343 -0.307,-0.415l-0.839,-0.262c-0.018,-0.18 -0.044,-0.355 -0.077,-0.523c-0.033,-0.168 -0.07,-0.337 -0.113,-0.505l0.704,-0.551c0.072,-0.06 0.122,-0.132 0.149,-0.216c0.027,-0.085 0.026,-0.172 -0.004,-0.262c-0.03,-0.09 -0.085,-0.161 -0.163,-0.212c-0.078,-0.051 -0.165,-0.074 -0.261,-0.068l-0.894,0.036c-0.078,-0.162 -0.158,-0.319 -0.239,-0.469c-0.081,-0.15 -0.17,-0.295 -0.266,-0.433l0.469,-0.758c0.054,-0.078 0.077,-0.163 0.068,-0.253c-0.009,-0.09 -0.041,-0.168 -0.095,-0.235c-0.138,-0.168 -0.307,-0.213 -0.505,-0.135l-0.822,0.325c-0.12,-0.114 -0.248,-0.227 -0.383,-0.338c-0.135,-0.112 -0.272,-0.216 -0.411,-0.312l0.19,-0.866c0.036,-0.223 -0.03,-0.379 -0.199,-0.469c-0.192,-0.109 -0.364,-0.088 -0.514,0.063l-0.65,0.577c-0.162,-0.066 -0.325,-0.128 -0.487,-0.185c-0.163,-0.057 -0.325,-0.112 -0.487,-0.167l-0.127,-0.875c-0.03,-0.205 -0.147,-0.328 -0.352,-0.37c-0.096,-0.012 -0.185,0.002 -0.266,0.041c-0.081,0.039 -0.143,0.097 -0.185,0.176l-0.415,0.803c-0.09,-0.006 -0.178,-0.011 -0.262,-0.014c-0.084,-0.003 -0.168,-0.004 -0.252,-0.004c-0.097,-0 -0.185,0.001 -0.267,0.004c-0.081,0.003 -0.167,0.008 -0.257,0.014l-0.424,-0.803c-0.09,-0.175 -0.241,-0.247 -0.451,-0.217c-0.205,0.042 -0.319,0.165 -0.343,0.37l-0.127,0.875c-0.168,0.055 -0.333,0.109 -0.496,0.163c-0.162,0.054 -0.322,0.117 -0.478,0.189l-0.659,-0.577c-0.144,-0.151 -0.316,-0.172 -0.514,-0.063c-0.169,0.09 -0.232,0.246 -0.19,0.469l0.181,0.866c-0.139,0.096 -0.276,0.2 -0.411,0.312c-0.135,0.111 -0.263,0.224 -0.383,0.338l-0.813,-0.325c-0.198,-0.078 -0.367,-0.033 -0.505,0.135c-0.06,0.067 -0.093,0.145 -0.099,0.235c-0.006,0.09 0.015,0.172 0.063,0.244l0.469,0.767c-0.096,0.138 -0.185,0.283 -0.266,0.433c-0.081,0.15 -0.161,0.307 -0.239,0.469l-0.894,-0.036c-0.096,-0.006 -0.183,0.017 -0.261,0.068c-0.078,0.051 -0.133,0.122 -0.163,0.212c-0.03,0.09 -0.031,0.177 -0.004,0.262c0.027,0.084 0.079,0.156 0.158,0.216l0.695,0.551c-0.043,0.168 -0.08,0.337 -0.113,0.505c-0.033,0.168 -0.056,0.343 -0.068,0.523l-0.848,0.262c-0.199,0.072 -0.298,0.211 -0.298,0.415c0,0.205 0.099,0.34 0.298,0.406l0.848,0.271c0.012,0.174 0.035,0.347 0.068,0.519c0.033,0.171 0.07,0.338 0.113,0.501l-0.695,0.55c-0.079,0.06 -0.131,0.134 -0.158,0.221c-0.027,0.088 -0.026,0.176 0.004,0.267c0.03,0.09 0.085,0.16 0.163,0.212c0.078,0.051 0.165,0.076 0.261,0.076l0.894,-0.045c0.078,0.157 0.158,0.312 0.239,0.465c0.081,0.153 0.17,0.299 0.266,0.438l-0.469,0.758c-0.048,0.078 -0.069,0.164 -0.063,0.257c0.006,0.093 0.039,0.173 0.099,0.239c0.138,0.162 0.307,0.205 0.505,0.126l0.813,-0.334c0.12,0.121 0.248,0.235 0.383,0.343c0.135,0.109 0.272,0.211 0.411,0.307l-0.181,0.876c-0.042,0.21 0.021,0.367 0.19,0.469c0.192,0.108 0.364,0.09 0.514,-0.054l0.659,-0.596c0.156,0.066 0.316,0.129 0.478,0.19c0.163,0.06 0.328,0.114 0.496,0.162l0.127,0.884c0.024,0.211 0.138,0.334 0.343,0.37c0.096,0.012 0.185,-0.001 0.266,-0.04c0.081,-0.039 0.143,-0.101 0.185,-0.185l0.424,-0.794c0.09,-0 0.176,0.004 0.257,0.013c0.082,0.009 0.17,0.014 0.267,0.014Zm-0,-1.228c-0.795,0 -1.53,-0.145 -2.207,-0.437c-0.677,-0.292 -1.269,-0.697 -1.778,-1.214c-0.508,-0.517 -0.904,-1.118 -1.186,-1.8c-0.283,-0.683 -0.425,-1.416 -0.425,-2.198c0,-0.788 0.142,-1.525 0.425,-2.211c0.282,-0.686 0.678,-1.287 1.186,-1.805c0.509,-0.517 1.101,-0.922 1.778,-1.213c0.677,-0.292 1.412,-0.438 2.207,-0.438c0.788,-0 1.52,0.146 2.197,0.438c0.677,0.291 1.269,0.696 1.778,1.213c0.508,0.518 0.904,1.119 1.186,1.805c0.283,0.686 0.425,1.423 0.425,2.211c-0,0.782 -0.142,1.515 -0.425,2.198c-0.282,0.682 -0.678,1.283 -1.186,1.8c-0.509,0.517 -1.101,0.922 -1.778,1.214c-0.677,0.292 -1.409,0.437 -2.197,0.437Zm-0.028,-3.718c0.41,0 0.774,-0.118 1.092,-0.356c0.319,-0.238 0.572,-0.591 0.758,-1.06l4.504,-0l-0.01,-1.029l-4.494,-0c-0.186,-0.463 -0.439,-0.812 -0.758,-1.047c-0.318,-0.235 -0.682,-0.352 -1.092,-0.352c-0.054,0 -0.117,0.005 -0.189,0.014c-0.072,0.009 -0.169,0.025 -0.289,0.049l-2.256,-3.862l-0.92,0.523l2.292,3.899c-0.193,0.216 -0.333,0.431 -0.42,0.645c-0.087,0.214 -0.131,0.435 -0.131,0.663c0,0.211 0.042,0.42 0.127,0.627c0.084,0.208 0.222,0.423 0.415,0.646l-2.374,3.862l0.903,0.542l2.355,-3.827c0.114,0.03 0.211,0.048 0.289,0.054c0.078,0.006 0.144,0.009 0.198,0.009Zm-0.785,-1.922c0,-0.228 0.082,-0.418 0.244,-0.568c0.162,-0.151 0.349,-0.226 0.559,-0.226c0.223,0 0.416,0.075 0.578,0.226c0.162,0.15 0.244,0.34 0.244,0.568c-0,0.223 -0.082,0.412 -0.244,0.569c-0.162,0.156 -0.355,0.234 -0.578,0.234c-0.21,0 -0.397,-0.078 -0.559,-0.234c-0.162,-0.157 -0.244,-0.346 -0.244,-0.569Z");
settingsIcon.setFill(darkMode ? Constants.BRIGHT_TEXT : Constants.DARK_TEXT);
settingsButton = new MacosButton("");
settingsButton.setGraphic(settingsIcon);
settingsButton.setMinWidth(32);
settingsButton.setAlignment(Pos.CENTER);
settingsButton.setContentDisplay(ContentDisplay.CENTER);
HBox.setHgrow(settingsButton, Priority.NEVER);
HBox.setMargin(settingsButton, new Insets(0, 0, 0, 5));
buttonHBox = new HBox(10, toggleButtonBar, settingsButton);
buttonHBox.setPadding(new Insets(0, 10, 0, 10));
buttonHBox.setAlignment(Pos.CENTER);
currentColor = null == currentEntry ? Constants.GRAY : Helper.getColorForValue(currentUnit, UnitDefinition.MILLIGRAM_PER_DECILITER == currentUnit ? currentEntry.sgv() : Helper.mgPerDeciliterToMmolPerLiter(currentEntry.sgv()));
titleLabel = createLabel(translator.get(I18nKeys.APP_NAME), 20, false, false, Pos.CENTER);
AnchorPane.setTopAnchor(titleLabel, 5d);
AnchorPane.setRightAnchor(titleLabel, 0d);
AnchorPane.setLeftAnchor(titleLabel, 0d);
reloadButton = new SVGPath();
reloadButton.setContent("M10.993,22c1.508,0 2.924,-0.286 4.25,-0.859c1.326,-0.572 2.495,-1.367 3.508,-2.385c1.013,-1.018 1.807,-2.19 2.384,-3.517c0.577,-1.327 0.865,-2.74 0.865,-4.239c0,-1.499 -0.288,-2.912 -0.865,-4.239c-0.577,-1.327 -1.374,-2.499 -2.391,-3.517c-1.017,-1.018 -2.188,-1.813 -3.514,-2.385c-1.326,-0.573 -2.743,-0.859 -4.25,-0.859c-1.499,0 -2.911,0.286 -4.237,0.859c-1.326,0.572 -2.493,1.367 -3.501,2.385c-1.008,1.018 -1.8,2.19 -2.377,3.517c-0.577,1.327 -0.865,2.74 -0.865,4.239c-0,1.499 0.288,2.912 0.865,4.239c0.577,1.327 1.371,2.499 2.384,3.517c1.013,1.018 2.182,1.813 3.508,2.385c1.326,0.573 2.738,0.859 4.236,0.859Zm-4.999,-10.496c-0,-0.917 0.222,-1.744 0.667,-2.48c0.445,-0.737 1.029,-1.323 1.751,-1.759c0.722,-0.436 1.496,-0.654 2.322,-0.654l0.123,-0l-0.559,-0.586c-0.063,-0.064 -0.115,-0.146 -0.156,-0.246c-0.041,-0.1 -0.061,-0.204 -0.061,-0.313c-0,-0.218 0.074,-0.404 0.224,-0.559c0.15,-0.154 0.339,-0.232 0.566,-0.232c0.099,0 0.199,0.021 0.299,0.062c0.1,0.041 0.182,0.097 0.245,0.17l2.085,2.113c0.136,0.145 0.209,0.334 0.218,0.566c0.009,0.231 -0.064,0.42 -0.218,0.565l-2.098,2.072c-0.155,0.164 -0.332,0.245 -0.531,0.245c-0.227,0 -0.416,-0.077 -0.566,-0.231c-0.15,-0.155 -0.224,-0.341 -0.224,-0.559c-0,-0.218 0.072,-0.4 0.217,-0.545l0.872,-0.859c-0.045,-0.009 -0.104,-0.014 -0.177,-0.014c-0.608,0 -1.16,0.148 -1.655,0.443c-0.495,0.296 -0.89,0.693 -1.185,1.193c-0.295,0.5 -0.443,1.054 -0.443,1.663c0,0.609 0.148,1.161 0.443,1.656c0.295,0.495 0.69,0.891 1.185,1.186c0.495,0.295 1.047,0.443 1.655,0.443c0.609,-0 1.16,-0.148 1.655,-0.443c0.495,-0.295 0.888,-0.691 1.179,-1.186c0.29,-0.495 0.436,-1.047 0.436,-1.656c-0,-0.236 0.086,-0.439 0.258,-0.607c0.173,-0.168 0.377,-0.252 0.613,-0.252c0.227,0 0.427,0.084 0.6,0.252c0.172,0.168 0.259,0.371 0.259,0.607c-0,0.918 -0.225,1.756 -0.675,2.515c-0.449,0.759 -1.053,1.365 -1.812,1.819c-0.758,0.455 -1.596,0.682 -2.513,0.682c-0.926,-0 -1.766,-0.227 -2.52,-0.682c-0.754,-0.454 -1.355,-1.065 -1.805,-1.833c-0.449,-0.768 -0.674,-1.62 -0.674,-2.556Z");
reloadButton.setFill(darkMode ? Constants.BRIGHT_TEXT : Constants.DARK_TEXT);
AnchorPane.setTopAnchor(reloadButton, 10d);
AnchorPane.setRightAnchor(reloadButton, 10d);
valueLabel = createLabel("-", 92, true, true, Pos.CENTER);
AnchorPane.setTopAnchor(valueLabel, 50d);
AnchorPane.setRightAnchor(valueLabel, 0d);
AnchorPane.setLeftAnchor(valueLabel, 0d);
unit = createDeltaText(currentUnit.UNIT.getUnitShort() + " (", true, 16);
delta4 = createDeltaText("0.0, ", false, 14);
delta3 = createDeltaText("0.0, ", false, 14);
delta2 = createDeltaText("0.0, ", false, 14);
delta1 = createDeltaText("0.0, ", false, 14);
delta0 = createDeltaText("0.0)", true, 16);
last5DeltasLabel = new HBox(unit, delta4, delta3, delta2, delta1, delta0);
last5DeltasLabel.setAlignment(Pos.CENTER);
AnchorPane.setTopAnchor(last5DeltasLabel, 155d);
AnchorPane.setRightAnchor(last5DeltasLabel, 0d);
AnchorPane.setLeftAnchor(last5DeltasLabel, 0d);
timestampLabel = createLabel("-", 16, false, true, Pos.CENTER);
AnchorPane.setRightAnchor(timestampLabel, 0d);
AnchorPane.setBottomAnchor(timestampLabel, 72d);
AnchorPane.setLeftAnchor(timestampLabel, 0d);
rangeAverageLabel = createLabel("-", 24, true, true, Pos.CENTER);
AnchorPane.setRightAnchor(rangeAverageLabel, 0d);
AnchorPane.setBottomAnchor(rangeAverageLabel, 20d);
AnchorPane.setLeftAnchor(rangeAverageLabel, 0d);
patternChartButton = new SVGPath();
patternChartButton.setContent("M10.993,22c1.508,0 2.924,-0.286 4.25,-0.859c1.326,-0.572 2.495,-1.367 3.508,-2.385c1.013,-1.018 1.807,-2.19 2.384,-3.517c0.577,-1.327 0.865,-2.74 0.865,-4.239c0,-1.499 -0.288,-2.912 -0.865,-4.239c-0.577,-1.327 -1.374,-2.499 -2.391,-3.517c-1.017,-1.018 -2.188,-1.813 -3.514,-2.385c-1.326,-0.573 -2.743,-0.859 -4.25,-0.859c-1.499,0 -2.911,0.286 -4.237,0.859c-1.326,0.572 -2.493,1.367 -3.501,2.385c-1.008,1.018 -1.8,2.19 -2.377,3.517c-0.577,1.327 -0.865,2.74 -0.865,4.239c-0,1.499 0.288,2.912 0.865,4.239c0.577,1.327 1.371,2.499 2.384,3.517c1.013,1.018 2.182,1.813 3.508,2.385c1.326,0.573 2.738,0.859 4.236,0.859Zm-6.062,-6.911l0,-8.792c0,-0.19 0.068,-0.354 0.205,-0.49c0.136,-0.137 0.295,-0.205 0.476,-0.205c0.191,0 0.355,0.068 0.491,0.205c0.136,0.136 0.204,0.3 0.204,0.49l0,4.158l1.321,-1.363c0.273,-0.273 0.573,-0.409 0.9,-0.409c0.336,-0 0.635,0.136 0.899,0.409l1.866,1.949c0.036,0.045 0.073,0.041 0.109,-0.014l1.839,-1.854l-0.749,-0.736c-0.155,-0.145 -0.196,-0.311 -0.123,-0.497c0.073,-0.186 0.218,-0.311 0.436,-0.375l3.215,-0.831c0.2,-0.055 0.37,-0.014 0.511,0.122c0.14,0.137 0.184,0.3 0.129,0.491l-0.845,3.23c-0.063,0.228 -0.188,0.378 -0.374,0.45c-0.186,0.073 -0.352,0.032 -0.497,-0.122l-0.736,-0.764l-1.962,2.018c-0.272,0.281 -0.576,0.422 -0.912,0.422c-0.327,0 -0.631,-0.141 -0.913,-0.422l-1.839,-1.909c-0.036,-0.054 -0.077,-0.054 -0.123,0l-2.152,2.181l0,2.14c0,0.064 0.027,0.096 0.082,0.096l9.958,-0c0.181,-0 0.34,0.068 0.477,0.204c0.136,0.136 0.204,0.295 0.204,0.477c-0,0.191 -0.068,0.355 -0.204,0.491c-0.137,0.136 -0.296,0.204 -0.477,0.204l-10.476,0c-0.281,0 -0.508,-0.086 -0.681,-0.259c-0.172,-0.172 -0.259,-0.404 -0.259,-0.695Z");
patternChartButton.setFill(darkMode ? Constants.BRIGHT_TEXT : Constants.DARK_TEXT);
patternChartButton.setOpacity(0.5);
AnchorPane.setBottomAnchor(patternChartButton, 20d);
AnchorPane.setLeftAnchor(patternChartButton, 10d);
matrixButton = new SVGPath();
matrixButton.setContent("M10.993,22c1.508,0 2.924,-0.286 4.25,-0.859c1.326,-0.572 2.495,-1.367 3.508,-2.385c1.013,-1.018 1.807,-2.19 2.384,-3.517c0.577,-1.327 0.865,-2.74 0.865,-4.239c0,-1.499 -0.288,-2.912 -0.865,-4.239c-0.577,-1.327 -1.374,-2.499 -2.391,-3.517c-1.017,-1.018 -2.188,-1.813 -3.514,-2.385c-1.326,-0.573 -2.743,-0.859 -4.25,-0.859c-1.499,0 -2.911,0.286 -4.237,0.859c-1.326,0.572 -2.493,1.367 -3.501,2.385c-1.008,1.018 -1.8,2.19 -2.377,3.517c-0.577,1.327 -0.865,2.74 -0.865,4.239c-0,1.499 0.288,2.912 0.865,4.239c0.577,1.327 1.371,2.499 2.384,3.517c1.013,1.018 2.182,1.813 3.508,2.385c1.326,0.573 2.738,0.859 4.236,0.859Zm0.014,-5.861c-0.418,-0 -0.777,-0.15 -1.076,-0.45c-0.3,-0.3 -0.45,-0.659 -0.45,-1.077c0,-0.418 0.15,-0.777 0.45,-1.077c0.299,-0.3 0.658,-0.449 1.076,-0.449c0.408,-0 0.765,0.149 1.069,0.449c0.304,0.3 0.456,0.659 0.456,1.077c0,0.418 -0.152,0.777 -0.456,1.077c-0.304,0.3 -0.661,0.45 -1.069,0.45Zm-3.855,-0c-0.418,-0 -0.777,-0.15 -1.076,-0.45c-0.3,-0.3 -0.45,-0.659 -0.45,-1.077c0,-0.418 0.15,-0.777 0.45,-1.077c0.299,-0.3 0.658,-0.449 1.076,-0.449c0.417,-0 0.774,0.149 1.069,0.449c0.295,0.3 0.443,0.659 0.443,1.077c-0,0.427 -0.148,0.788 -0.443,1.084c-0.295,0.295 -0.652,0.443 -1.069,0.443Zm7.696,-0c-0.408,-0 -0.763,-0.15 -1.062,-0.45c-0.3,-0.3 -0.45,-0.659 -0.45,-1.077c0,-0.418 0.15,-0.777 0.45,-1.077c0.299,-0.3 0.654,-0.449 1.062,-0.449c0.418,-0 0.777,0.149 1.076,0.449c0.3,0.3 0.45,0.659 0.45,1.077c-0,0.418 -0.15,0.777 -0.45,1.077c-0.299,0.3 -0.658,0.45 -1.076,0.45Zm-3.841,-3.612c-0.418,-0 -0.777,-0.15 -1.076,-0.45c-0.3,-0.3 -0.45,-0.659 -0.45,-1.077c0,-0.418 0.15,-0.775 0.45,-1.07c0.299,-0.295 0.658,-0.443 1.076,-0.443c0.408,-0.009 0.765,0.136 1.069,0.436c0.304,0.3 0.456,0.659 0.456,1.077c0,0.418 -0.152,0.777 -0.456,1.077c-0.304,0.3 -0.661,0.45 -1.069,0.45Zm-3.855,-0c-0.418,-0 -0.777,-0.15 -1.076,-0.45c-0.3,-0.3 -0.45,-0.659 -0.45,-1.077c0,-0.418 0.15,-0.775 0.45,-1.07c0.299,-0.295 0.658,-0.443 1.076,-0.443c0.417,-0.009 0.774,0.136 1.069,0.436c0.295,0.3 0.443,0.659 0.443,1.077c-0,0.418 -0.148,0.777 -0.443,1.077c-0.295,0.3 -0.652,0.45 -1.069,0.45Zm7.696,-0c-0.408,-0 -0.763,-0.15 -1.062,-0.45c-0.3,-0.3 -0.45,-0.659 -0.45,-1.077c0,-0.418 0.15,-0.775 0.45,-1.07c0.299,-0.295 0.654,-0.443 1.062,-0.443c0.418,-0.009 0.777,0.136 1.076,0.436c0.3,0.3 0.45,0.659 0.45,1.077c-0,0.418 -0.15,0.777 -0.45,1.077c-0.299,0.3 -0.658,0.45 -1.076,0.45Zm-3.841,-3.599c-0.418,0 -0.777,-0.15 -1.076,-0.45c-0.3,-0.3 -0.45,-0.658 -0.45,-1.077c0,-0.427 0.15,-0.786 0.45,-1.076c0.299,-0.291 0.658,-0.441 1.076,-0.45c0.408,-0 0.765,0.148 1.069,0.443c0.304,0.295 0.456,0.656 0.456,1.083c0,0.419 -0.152,0.777 -0.456,1.077c-0.304,0.3 -0.661,0.45 -1.069,0.45Zm-3.855,0c-0.418,0 -0.777,-0.15 -1.076,-0.45c-0.3,-0.3 -0.45,-0.658 -0.45,-1.077c0,-0.418 0.15,-0.776 0.45,-1.076c0.299,-0.3 0.658,-0.45 1.076,-0.45c0.417,-0 0.774,0.15 1.069,0.45c0.295,0.3 0.443,0.658 0.443,1.076c-0,0.419 -0.148,0.777 -0.443,1.077c-0.295,0.3 -0.652,0.45 -1.069,0.45Zm7.696,0c-0.408,0 -0.763,-0.15 -1.062,-0.45c-0.3,-0.3 -0.45,-0.658 -0.45,-1.077c0,-0.427 0.15,-0.786 0.45,-1.076c0.299,-0.291 0.654,-0.441 1.062,-0.45c0.418,-0 0.777,0.148 1.076,0.443c0.3,0.295 0.45,0.656 0.45,1.083c-0,0.419 -0.15,0.777 -0.45,1.077c-0.299,0.3 -0.658,0.45 -1.076,0.45Z");
matrixButton.setFill(darkMode ? Constants.BRIGHT_TEXT : Constants.DARK_TEXT);
matrixButton.setOpacity(0.5);
AnchorPane.setTopAnchor(matrixButton, 10d);
AnchorPane.setLeftAnchor(matrixButton, 10d);
timeInRangeChartButton = new SVGPath();
timeInRangeChartButton.setContent("M10.993,22c1.508,0 2.924,-0.286 4.25,-0.859c1.326,-0.572 2.495,-1.367 3.508,-2.385c1.013,-1.018 1.807,-2.19 2.384,-3.517c0.577,-1.327 0.865,-2.74 0.865,-4.239c0,-1.499 -0.288,-2.912 -0.865,-4.239c-0.577,-1.327 -1.374,-2.499 -2.391,-3.517c-1.017,-1.018 -2.188,-1.813 -3.514,-2.385c-1.326,-0.573 -2.743,-0.859 -4.25,-0.859c-1.499,0 -2.911,0.286 -4.237,0.859c-1.326,0.572 -2.493,1.367 -3.501,2.385c-1.008,1.018 -1.8,2.19 -2.377,3.517c-0.577,1.327 -0.865,2.74 -0.865,4.239c-0,1.499 0.288,2.912 0.865,4.239c0.577,1.327 1.371,2.499 2.384,3.517c1.013,1.018 2.182,1.813 3.508,2.385c1.326,0.573 2.738,0.859 4.236,0.859Zm-5.421,-6.434c-0.282,0 -0.511,-0.081 -0.688,-0.245c-0.177,-0.164 -0.266,-0.382 -0.266,-0.654c-0,-0.255 0.089,-0.464 0.266,-0.627c0.177,-0.164 0.406,-0.246 0.688,-0.246l10.884,0c0.281,0 0.511,0.082 0.688,0.246c0.177,0.163 0.265,0.372 0.265,0.627c0,0.272 -0.088,0.49 -0.265,0.654c-0.177,0.164 -0.407,0.245 -0.688,0.245l-10.884,0Zm-0,-3.68c-0.282,-0 -0.511,-0.08 -0.688,-0.239c-0.177,-0.159 -0.266,-0.374 -0.266,-0.647c-0,-0.273 0.089,-0.488 0.266,-0.647c0.177,-0.159 0.406,-0.239 0.688,-0.239l10.884,0c0.281,0 0.511,0.08 0.688,0.239c0.177,0.159 0.265,0.374 0.265,0.647c0,0.273 -0.088,0.488 -0.265,0.647c-0.177,0.159 -0.407,0.239 -0.688,0.239l-10.884,-0Zm-0,-3.68c-0.282,-0 -0.511,-0.08 -0.688,-0.239c-0.177,-0.159 -0.266,-0.37 -0.266,-0.634c-0,-0.272 0.089,-0.49 0.266,-0.654c0.177,-0.164 0.406,-0.245 0.688,-0.245l10.884,-0c0.281,-0 0.511,0.081 0.688,0.245c0.177,0.164 0.265,0.382 0.265,0.654c0,0.264 -0.088,0.475 -0.265,0.634c-0.177,0.159 -0.407,0.239 -0.688,0.239l-10.884,-0Z");
timeInRangeChartButton.setFill(darkMode ? Constants.BRIGHT_TEXT : Constants.DARK_TEXT);
AnchorPane.setRightAnchor(timeInRangeChartButton, 10d);
AnchorPane.setBottomAnchor(timeInRangeChartButton, 20d);
mainPane = new AnchorPane(titleLabel, matrixButton, reloadButton, valueLabel, last5DeltasLabel, timestampLabel, rangeAverageLabel, patternChartButton, timeInRangeChartButton);
mainPane.setPrefSize(820, 295);
mainPane.setMinHeight(295);
mainPane.setBackground(new Background(new BackgroundFill(Constants.GRAY, CornerRadii.EMPTY, Insets.EMPTY)));
canvas = new Canvas(820, 365);
ctx = canvas.getGraphicsContext2D();
AnchorPane.setTopAnchor(canvas, 10d);
AnchorPane.setRightAnchor(canvas, 5d);
AnchorPane.setBottomAnchor(canvas, 5d);
AnchorPane.setLeftAnchor(canvas, 5d);
exclamationMark = new SVGPath();
exclamationMark.setContent("M7.743,54.287l41.48,-0c1.613,-0 2.995,-0.346 4.147,-1.037c1.153,-0.692 2.046,-1.619 2.679,-2.783c0.634,-1.164 0.951,-2.483 0.951,-3.958c-0,-0.622 -0.092,-1.262 -0.277,-1.918c-0.184,-0.657 -0.449,-1.285 -0.795,-1.884l-20.774,-36.053c-0.737,-1.29 -1.705,-2.27 -2.904,-2.938c-1.198,-0.668 -2.454,-1.003 -3.767,-1.003c-1.314,0 -2.57,0.335 -3.768,1.003c-1.198,0.668 -2.155,1.648 -2.869,2.938l-20.774,36.053c-0.715,1.221 -1.072,2.489 -1.072,3.802c0,1.475 0.311,2.794 0.933,3.958c0.622,1.164 1.515,2.091 2.679,2.783c1.164,0.691 2.541,1.037 4.131,1.037Zm0.034,-4.874c-0.829,-0 -1.503,-0.294 -2.022,-0.882c-0.518,-0.587 -0.777,-1.261 -0.777,-2.022c-0,-0.207 0.023,-0.438 0.069,-0.691c0.046,-0.254 0.138,-0.496 0.276,-0.726l20.74,-36.087c0.254,-0.461 0.605,-0.807 1.054,-1.037c0.45,-0.231 0.905,-0.346 1.366,-0.346c0.484,-0 0.939,0.115 1.365,0.346c0.426,0.23 0.778,0.576 1.054,1.037l20.74,36.121c0.231,0.438 0.346,0.899 0.346,1.383c-0,0.761 -0.259,1.435 -0.778,2.022c-0.518,0.588 -1.204,0.882 -2.057,0.882l-41.376,-0Zm20.74,-4.494c0.83,0 1.562,-0.294 2.195,-0.881c0.634,-0.588 0.951,-1.308 0.951,-2.161c-0,-0.875 -0.311,-1.601 -0.933,-2.177c-0.623,-0.577 -1.36,-0.865 -2.213,-0.865c-0.875,0 -1.624,0.294 -2.247,0.882c-0.622,0.587 -0.933,1.308 -0.933,2.16c0,0.83 0.317,1.544 0.951,2.143c0.633,0.599 1.377,0.899 2.229,0.899Zm0,-9.056c1.521,-0 2.293,-0.795 2.316,-2.385l0.45,-14.173c0.023,-0.76 -0.237,-1.4 -0.778,-1.918c-0.542,-0.519 -1.216,-0.778 -2.022,-0.778c-0.83,0 -1.504,0.254 -2.022,0.761c-0.519,0.507 -0.767,1.14 -0.744,1.901l0.381,14.207c0.046,1.59 0.852,2.385 2.419,2.385Z");
exclamationMark.setFill(darkMode ? Constants.BRIGHT_TEXT : Constants.DARK_TEXT);
exclamationMark.setVisible(false);
StackPane problemPane = new StackPane(exclamationMark);
AnchorPane.setTopAnchor(problemPane, 0d);
AnchorPane.setRightAnchor(problemPane, 0d);
AnchorPane.setBottomAnchor(problemPane, 0d);
AnchorPane.setLeftAnchor(problemPane, 0d);
chartPane = new AnchorPane(canvas, problemPane);
chartPane.setBackground(new Background(new BackgroundFill(Color.TRANSPARENT, new CornerRadii(10), Insets.EMPTY)));
chartPane.setMinWidth(650);
chartPane.setMinHeight(100);
glassOverlay = new Region();
glassOverlay.setOpacity(0.0);
glassOverlay.setBackground(new Background(new BackgroundFill(Color.rgb(0, 0, 0, 0.5), new CornerRadii(10), Insets.EMPTY)));
glassOverlay.setVisible(false);
glassOverlay.setManaged(false);
vpane = new AnchorPane(buttonHBox, mainPane, chartPane);
// Button Tool Bar
AnchorPane.setTopAnchor(buttonHBox, 10d);
AnchorPane.setRightAnchor(buttonHBox, 0d);
AnchorPane.setLeftAnchor(buttonHBox, 0d);
// Main Value
AnchorPane.setTopAnchor(mainPane, 45d);
AnchorPane.setRightAnchor(mainPane, 0d);
AnchorPane.setLeftAnchor(mainPane, 0d);
// ChartPane
AnchorPane.setTopAnchor(chartPane, 337d);
AnchorPane.setRightAnchor(chartPane, 0d);
AnchorPane.setBottomAnchor(chartPane, 0d);
AnchorPane.setLeftAnchor(chartPane, 0d);
prefPane = createPrefPane();
prefPane.setVisible(false);
prefPane.setManaged(false);
pane = new StackPane(vpane, glassOverlay, prefPane);
registerListeners();
}
// ******************** App lifecycle *************************************
@Override public void start(final Stage stage) {
this.stage = stage;
notifier = NotifierBuilder.create()
.owner(stage)
.popupLocation(OperatingSystem.MACOS == operatingSystem ? Pos.TOP_RIGHT : Pos.BOTTOM_RIGHT)
.popupLifeTime(Duration.millis(5000))
.build();
this.trayIconSupported = FXTrayIcon.isSupported();
if (trayIconSupported) {
switch (operatingSystem) {
case WINDOWS -> trayIcon = new FXTrayIcon(stage, getClass().getResource("icon48x48.png"));
case MACOS -> trayIcon = new FXTrayIcon(stage, Helper.createTextTrayIcon("--", Color.WHITE));
case LINUX -> trayIcon = new FXTrayIcon(stage, getClass().getResource("icon48x48.png"));
}
trayIcon.setTrayIconTooltip(translator.get(I18nKeys.APP_NAME));
trayIcon.addExitItem(false);
trayIcon.setApplicationTitle(translator.get(I18nKeys.APP_NAME));
MenuItem aboutItem = new MenuItem(translator.get(I18nKeys.ABOUT_MENU_ITEM));
aboutItem.setOnAction(e -> { if (!aboutDialog.isShowing()) { aboutDialog.showAndWait(); }});
trayIcon.addMenuItem(aboutItem);
MenuItem chartItem = new MenuItem(translator.get(I18nKeys.CHART_MENU_ITEM));
chartItem.setOnAction(e -> {
prefPane.setVisible(false);
prefPane.setManaged(false);
stage.show();
});
trayIcon.addMenuItem(chartItem);
MenuItem preferencesItem = new MenuItem(translator.get(I18nKeys.PREFERENCES_MENU_ITEM));
preferencesItem.setOnAction(e -> {
applySettingsToPreferences();
prefPane.setPrefSize(stage.getWidth(), stage.getHeight());
prefPane.setManaged(true);
prefPane.setVisible(true);
stage.show();
});
trayIcon.addMenuItem(preferencesItem);
trayIcon.addSeparator();
MenuItem quitItem = new MenuItem(translator.get(I18nKeys.QUIT_MENU_ITEM));
quitItem.setOnAction(e -> stop());
trayIcon.addMenuItem(quitItem);
trayIcon.show();
} else {
MenuBar menuBar = new MenuBar();
menuBar.setUseSystemMenuBar(true);
menuBar.setTranslateX(16);
Menu menu = new Menu(translator.get(I18nKeys.APP_NAME));
menu.setText(translator.get(I18nKeys.MENU));
menu.setOnShowing(e -> hideMenu = false);
menu.setOnHidden(e -> {
if (!hideMenu) {
menu.show();
}
});
CustomMenuItem aboutItem = new CustomMenuItem();
Label mainLabel = new Label(translator.get(I18nKeys.ABOUT_MENU_ITEM));
mainLabel.addEventHandler(MouseEvent.MOUSE_ENTERED, e -> hideMenu = false);
mainLabel.addEventHandler(MouseEvent.MOUSE_EXITED, e -> hideMenu = true);
aboutItem.setContent(mainLabel);
aboutItem.setHideOnClick(false);
aboutItem.setOnAction(e -> { if (!aboutDialog.isShowing()) { aboutDialog.showAndWait(); } });
menu.getItems().add(aboutItem);
CustomMenuItem chartItem = new CustomMenuItem();
Label chartLabel = new Label(translator.get(I18nKeys.CHART_MENU_ITEM));
chartLabel.addEventHandler(MouseEvent.MOUSE_ENTERED, e -> hideMenu = false);
chartLabel.addEventHandler(MouseEvent.MOUSE_EXITED, e -> hideMenu = true);
chartItem.setContent(chartLabel);
chartItem.setHideOnClick(false);
chartItem.setOnAction(e -> {
prefPane.setVisible(false);
prefPane.setManaged(false);
stage.show();
});
menu.getItems().add(chartItem);
CheckMenuItem preferencesItem = new CheckMenuItem();
preferencesItem.setVisible(true);
preferencesItem.setText(translator.get(I18nKeys.PREFERENCES_MENU_ITEM));
preferencesItem.selectedProperty().addListener(o -> {
applySettingsToPreferences();
prefPane.setPrefSize(stage.getWidth(), stage.getHeight());
prefPane.setManaged(true);
prefPane.setVisible(true);
stage.show();
});
menu.getItems().add(preferencesItem);
menu.getItems().add(new SeparatorMenuItem());
CustomMenuItem quitItem = new CustomMenuItem();
Label quitLabel = new Label(translator.get(I18nKeys.QUIT_MENU_ITEM));
quitLabel.addEventHandler(MouseEvent.MOUSE_ENTERED, e -> hideMenu = false);
quitLabel.addEventHandler(MouseEvent.MOUSE_EXITED, e -> hideMenu = true);
quitItem.setContent(quitLabel);
quitItem.setHideOnClick(false);
quitItem.setOnAction(e -> stop());
menu.getItems().add(quitItem);
menuBar.getMenus().add(menu);
mainPane.getChildren().add(menuBar);
}
//macosWindow = new MacosWindow(stage, pane, eu.hansolo.applefx.tools.Helper.isDarkMode(), eu.hansolo.applefx.tools.Helper.getMacosAccentColor(), Style.DECORATED, false);
macosWindow = new MacosWindow(stage, pane, eu.hansolo.applefx.tools.Helper.isDarkMode(), eu.hansolo.applefx.tools.Helper.getMacosAccentColor(), Style.DEFAULT, false);
Scene scene = new Scene(macosWindow);
scene.getStylesheets().add(Main.class.getResource("glucostatus.css").toExternalForm());
stage.setScene(scene);
stage.show();
stage.getIcons().add(stageIcon);
stage.centerOnScreen();
stage.setOnShowing(e -> {
ZonedDateTime now = ZonedDateTime.now();
if (now.toEpochSecond() - lastUpdate.toEpochSecond() > 300) {
allEntries.clear();
Helper.getEntriesFromLast30Days(nightscoutUrl + Constants.URL_API).thenAccept(l -> allEntries.addAll(l));
}
});
stage.setWidth(820);
stage.setHeight(735);
stage.setMinWidth(650);
stage.setMinHeight(500);
postStart();
}
private void postStart() {
if (null != nightscoutUrl && !nightscoutUrl.isEmpty()) {
Helper.getEntriesFromLast30Days(nightscoutUrl + Constants.URL_API).thenAccept(l -> {
allEntries.addAll(l);
Platform.runLater(() -> {
matrixButton.setOpacity(1.0);
patternChartButton.setOpacity(1.0);
});
lastFullUpdate = ZonedDateTime.now();
});
service = new ScheduledService<>() {
@Override protected Task<Void> createTask() {
Task task = new Task() {
@Override protected Object call() {
updateEntries();
return null;
}
};
return task;
}
};
service.setPeriod(Duration.millis(60000));
service.setRestartOnFailure(true);
service.start();
}
aboutDialog = createAboutDialog();
macosWindow.darkProperty().addListener((o, ov, nv) -> {
darkMode = nv;
Color color = darkMode ? Constants.BRIGHT_TEXT : Constants.DARK_TEXT;
settingsIcon.setFill(color);
titleLabel.setDark(darkMode);
valueLabel.setDark(darkMode);
unit.setFill(color);
delta4.setFill(color);
delta3.setFill(color);
delta2.setFill(color);
delta1.setFill(color);
delta0.setFill(color);
matrixButton.setFill(color);
reloadButton.setFill(color);
patternChartButton.setFill(color);
timeInRangeChartButton.setFill(color);
drawChart();
exclamationMark.setFill(color);
prefContentPane.setBackground(new Background(new BackgroundFill(darkMode ? MacosSystemColor.BACKGROUND.dark() : MacosSystemColor.BACKGROUND.aqua(), new CornerRadii(10), Insets.EMPTY)));
eu.hansolo.applefx.tools.Helper.getAllNodes(prefPane).stream().filter(node -> node instanceof MacosControl).forEach(node -> ((MacosControl) node).setDark(darkMode));
});
stage.widthProperty().addListener(o -> {
chartPane.setMaxWidth(stage.getWidth());
chartPane.setPrefWidth(stage.getWidth());
});
stage.heightProperty().addListener(o -> {
chartPane.setMaxHeight(stage.getHeight() - 285);
chartPane.setPrefHeight(stage.getHeight() - 285);
});
}
@Override public void stop() {
service.cancel();
Platform.exit();
System.exit(0);
}
// ******************** Methods *******************************************
private void registerListeners() {
chartPane.widthProperty().addListener((o, ov, nv) -> canvas.setWidth(nv.doubleValue() - 10));
chartPane.heightProperty().addListener((o, ov, nv) -> canvas.setHeight(nv.doubleValue() - 15));
allEntries.addListener((ListChangeListener<GlucoEntry>) c -> {
while (c.next()) {
if (c.wasAdded()) {
updateUI();
} else if (c.wasRemoved()) {
}
}
});
settingsButton.setOnAction(e -> {
applySettingsToPreferences();
prefPane.setManaged(true);
prefPane.setVisible(true);
});
matrixButton.setOnMousePressed(e -> matrixButton.setOpacity(0.75));
matrixButton.setOnMouseReleased(e -> {
matrixButton.setOpacity(1.0);
showMatrixChart();
});
reloadButton.setOnMousePressed(e -> reloadButton.setOpacity(0.75));
reloadButton.setOnMouseReleased(e -> {
reloadButton.setOpacity(1.0);
reloadAllEntries();
});
timeInRangeChartButton.setOnMousePressed(e -> timeInRangeChartButton.setOpacity(0.75));
timeInRangeChartButton.setOnMouseReleased(e -> {
timeInRangeChartButton.setOpacity(1.0);
showTimeInRangeChart();
});
patternChartButton.setOnMousePressed(e -> patternChartButton.setOpacity(0.75));
patternChartButton.setOnMouseReleased(e -> {
patternChartButton.setOpacity(1.0);
showPatternChart();
});
intervalToggleGroup.selectedToggleProperty().addListener((o, ov, nv) -> {
if (null == ov || null == nv) { return; }
if (ov.equals(nv)) { nv.setSelected(true); }
if (nv.equals(sevenDays)) {
currentInterval = TimeInterval.LAST_168_HOURS;
} else if (nv.equals(seventyTwoHours)) {
currentInterval = TimeInterval.LAST_72_HOURS;
} else if (nv.equals(fourtyEightHours)) {
currentInterval = TimeInterval.LAST_48_HOURS;
} else if (nv.equals(twentyFourHours)) {
currentInterval = TimeInterval.LAST_24_HOURS;
} else if (nv.equals(twelveHours)) {
currentInterval = TimeInterval.LAST_12_HOURS;
} else if (nv.equals(sixHours)) {
currentInterval = TimeInterval.LAST_6_HOURS;
} else if (nv.equals(threeHours)) {
currentInterval = TimeInterval.LAST_3_HOURS;
}
updateUI();
});
dialogVisible.addListener((o, ov, nv) -> {
if (nv) {
glassOverlay.setManaged(true);
glassOverlay.setVisible(true);
FadeTransition fade = new FadeTransition(Duration.millis(500), glassOverlay);
fade.setFromValue(0.0);
fade.setToValue(1.0);
fade.play();
} else {
FadeTransition fade = new FadeTransition(Duration.millis(500), glassOverlay);
fade.setFromValue(1.0);
fade.setToValue(0.0);
fade.setOnFinished(e -> {
glassOverlay.setManaged(false);
glassOverlay.setVisible(false);
});
fade.play();
}
});
canvas.widthProperty().addListener(o -> drawChart());
canvas.heightProperty().addListener(o -> drawChart());
}
private void updateEntries() {
if (null == nightscoutUrl || nightscoutUrl.isEmpty()) { return; }
GlucoEntry entryFound = null;
HttpResponse<String> response = Helper.get(nightscoutUrl + Constants.URL_API + Constants.URL_PARAM_COUNT_1, nightscoutToken);
if (null != response && null != response.body() && !response.body().isEmpty()) {
List<GlucoEntry> entry = Helper.getGlucoEntries(response.body());
entryFound = entry.isEmpty() ? null : entry.get(0);
}
if (allEntries.isEmpty()) { return; }
if (allEntries.get(0).datelong() == entryFound.datelong()) { return; }
allEntries.remove(allEntries.size() - 1);
allEntries.add(0, entryFound);
lastUpdate = ZonedDateTime.now();
}
private void reloadAllEntries() {
if (null != nightscoutUrl && !nightscoutUrl.isEmpty() && ZonedDateTime.now().toEpochSecond() - lastFullUpdate.toEpochSecond() > Constants.SECONDS_PER_MINUTE) {
matrixButton.setOpacity(0.5);
patternChartButton.setOpacity(0.5);
allEntries.clear();
Helper.getEntriesFromLast30Days(nightscoutUrl + Constants.URL_API).thenAccept(l -> {
allEntries.addAll(l);
Platform.runLater(() -> {
matrixButton.setOpacity(1.0);
patternChartButton.setOpacity(1.0);
});
lastFullUpdate = ZonedDateTime.now();
});
drawChart();
}
}
private boolean predict() {
if (null == allEntries || allEntries.isEmpty()) { return false; }
GlucoEntry currentEntry = allEntries.get(0);
List<GlucoEntry> last3Entries = allEntries.stream().limit(3).collect(Collectors.toList());
// Soon too low
boolean soonTooLow = last3Entries.stream().filter(entry -> Trend.DOUBLE_DOWN == entry.trend() || Trend.SINGLE_DOWN == entry.trend()).count() == 3;
// Soon too high
boolean soonTooHigh = last3Entries.stream().filter(entry -> Trend.DOUBLE_UP == entry.trend() || Trend.SINGLE_UP == entry.trend()).count() == 3;
if (soonTooLow) {
if (currentEntry.sgv() < PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MIN_ACCEPTABLE) && currentEntry.sgv() > Constants.DEFAULT_MIN_CRITICAL) {
String title = translator.get(I18nKeys.PREDICTION_TITLE_TOO_LOW);
String msg = translator.get(I18nKeys.PREDICTION_TOO_LOW);
Notification notification = NotificationBuilder.create().title(title).message(msg).image(icon).build();
if (PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_PLAY_SOUND_FOR_TOO_LOW_NOTIFICATION)) { notificationSound.play(); }
Platform.runLater(() -> { if (notifier.getNoOfPopups() == 0) { notifier.notify(notification); }});
return true;
}
} else if (soonTooHigh) {
if (currentEntry.sgv() < Constants.DEFAULT_MAX_CRITICAL && currentEntry.sgv() > Constants.DEFAULT_SOON_TOO_HIGH) {
String title = translator.get(I18nKeys.PREDICTION_TITLE_TOO_HIGH);
String msg = translator.get(I18nKeys.PREDICTION_TOO_HIGH);
Notification notification = NotificationBuilder.create().title(title).message(msg).image(icon).build();
if (PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_PLAY_SOUND_FOR_TOO_HIGH_NOTIFICATION)) { notificationSound.play(); }
Platform.runLater(() -> { if (notifier.getNoOfPopups() == 0) { notifier.notify(notification); }});
return true;
}
}
return false;
}
private void notifyIfNeeded() {
Trend trend = currentEntry.trend();
ZonedDateTime now = ZonedDateTime.now();
double value = currentEntry.sgv();
boolean voiceOutput = PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_VOICE_OUTPUT, false);
double voiceOutputInterval = PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_VOICE_OUTPUT_INTERVAL, 5.0) * 60.0;
double maxCritical = PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MAX_CRITICAL);
double maxAcceptable = PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MAX_ACCEPTABLE);
double maxNormal = PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MAX_NORMAL);
double minNormal = PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MIN_NORMAL);
double minAcceptable = PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MIN_ACCEPTABLE);
double minCritical = PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MIN_CRITICAL);
boolean showHighValueNotification = PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_SHOW_HIGH_VALUE_NOTIFICATION);
boolean showAcceptableHighValueNotification = PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_SHOW_ACCEPTABLE_HIGH_VALUE_NOTIFICATION);
boolean showLowValueNotification = PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_SHOW_LOW_VALUE_NOTIFICATION);
boolean showAcceptableLowValueNotification = PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_SHOW_ACCEPTABLE_LOW_VALUE_NOTIFICATION);
boolean playSoundForTooHighNotification = PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_PLAY_SOUND_FOR_TOO_HIGH_NOTIFICATION);
boolean playSoundForHighNotification = PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_PLAY_SOUND_FOR_HIGH_NOTIFICATION);
boolean playSoundForAcceptableHighNotification = PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_PLAY_SOUND_FOR_ACCEPTABLE_HIGH_NOTIFICATION);
boolean playSoundForTooLowNotification = PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_PLAY_SOUND_FOR_TOO_LOW_NOTIFICATION);
boolean speakTooLowNotification = PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_SPEAK_TOO_LOW_NOTIFICATION, false);
boolean playSoundForLowNotification = PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_PLAY_SOUND_FOR_LOW_NOTIFICATION);
boolean speakLowNotification = PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_SPEAK_LOW_NOTIFICATION, false);
boolean playSoundForAcceptableLowNotification = PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_PLAY_SOUND_FOR_ACCEPTABLE_LOW_NOTIFICATION);
double criticalMinNotificationInterval = PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_CRITICAL_MIN_NOTIFICATION_INTERVAL) * 60.0;
double criticalMaxNotificationInterval = PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_CRITICAL_MAX_NOTIFICATION_INTERVAL) * 60.0;
String format = MILLIGRAM_PER_DECILITER == currentUnit ? "%.0f" : "%.1f";
if (voiceOutput) {
if (now.toEpochSecond() - lastSpeak.toEpochSecond() > voiceOutputInterval) {
// Speak
if (OperatingSystem.MACOS == operatingSystem) {
String message = new StringBuilder().append(String.format(Locale.US, format, currentEntry.sgv())).append(" ").append(currentUnit.UNIT.getUnitName()).append(" ").append(translator.get(trend.getSpeakText())).toString();
speak(voice, message);
}
lastSpeak = now;
}
}
boolean playSound = false;
String msg = "";
if (value > maxCritical) {
// TOO HIGH
if (Trend.SINGLE_DOWN == trend || Trend.DOUBLE_DOWN == trend) {
return; // Was critical but is falling again -> no notification
} else if (trend == Trend.FLAT || Trend.FORTY_FIVE_DOWN == trend) {
if (now.toEpochSecond() - lastNotification.toEpochSecond() > criticalMaxNotificationInterval) {
msg = translator.get(I18nKeys.NOTIFICATION_GLUCOSE_TOO_HIGH);
if (playSoundForTooHighNotification) { playSound = true; }
}
} else {
msg = translator.get(I18nKeys.NOTIFICATION_GLUCOSE_TOO_HIGH);
if (playSoundForTooHighNotification) { playSound = true; }
}
} else if (value > maxAcceptable) {
// HIGH
if (showHighValueNotification) {
// High
if (Trend.SINGLE_UP == trend || Trend.DOUBLE_UP == trend) {
msg = translator.get(I18nKeys.NOTIFICATION_GLUCOSE_TOO_HIGH_SOON);
} else {
msg = translator.get(I18nKeys.NOTIFICATION_GLUCOSE_HIGH);
}
if (playSoundForHighNotification) { playSound = true; }
} else {
msg = "";
}
} else if (value > maxNormal) {
// ACCEPTABLE HIGH
if (showAcceptableHighValueNotification) {
if (Trend.SINGLE_UP == trend || Trend.DOUBLE_UP == trend) {
msg = translator.get(I18nKeys.NOTIFICATION_GLUCOSE_HIGH_SOON);
} else {
msg = translator.get(I18nKeys.NOTIFICATION_GLUCOSE_A_BIT_HIGH);
}
if (playSoundForAcceptableHighNotification) { playSound = true; }
} else {
msg = "";
}
} else if (value > minNormal) {
// NORMAL
} else if (value > minAcceptable) {
// ACCEPTABLE LOW
if (showAcceptableLowValueNotification) {
if (Trend.SINGLE_DOWN == trend || Trend.DOUBLE_DOWN == trend) {
msg = translator.get(I18nKeys.NOTIFICATION_GLUCOSE_LOW_SOON);
} else {
msg = translator.get(I18nKeys.NOTIFICATION_GLUCOSE_A_BIT_LOW);
}
if (playSoundForAcceptableLowNotification) { playSound = true; }
} else {
msg = "";
}
} else if (value > minCritical) {
// LOW
if (showLowValueNotification) {
if (Trend.SINGLE_DOWN == trend || Trend.DOUBLE_DOWN == trend) {
msg = translator.get(I18nKeys.NOTIFICATION_GLUCOSE_TOO_LOW_SOON);
} else {
msg = translator.get(I18nKeys.NOTIFICATION_GLUCOSE_LOW);
}
if (playSoundForLowNotification) { playSound = true; }
if (speakLowNotification) {
// Speak low notification
if (OperatingSystem.MACOS == operatingSystem) {
speak(voice, msg);
}
}
} else {
msg = "";
}
} else {
// TOO LOW
if (Trend.SINGLE_UP == trend || Trend.DOUBLE_UP == trend) {
return; // Was critical but is rising again -> no notification
} else if (Trend.FLAT == trend || Trend.FORTY_FIVE_UP == trend) {
if (now.toEpochSecond() - lastNotification.toEpochSecond() > criticalMinNotificationInterval) {
msg = translator.get(I18nKeys.NOTIFICATION_GLUCOSE_TOO_LOW);
if (playSoundForTooLowNotification) { playSound = true; }
if (speakTooLowNotification) {
// Speak
if (OperatingSystem.MACOS == operatingSystem) {
speak(voice, msg);
}
}
}
} else {
msg = translator.get(I18nKeys.NOTIFICATION_GLUCOSE_TOO_LOW);
if (playSoundForTooLowNotification) { playSound = true; }
if (speakTooLowNotification) {
// Speak
if (OperatingSystem.MACOS == operatingSystem) {
speak(voice, msg);
}
}
}
}
if (msg.isEmpty()) { return; }
String body = new StringBuilder().append(msg).append(" (").append(String.format(Locale.US, format, currentEntry.sgv())).append(" ").append(currentEntry.trend().getSymbol()).append(")").toString();
Notification notification = NotificationBuilder.create().title(translator.get(I18nKeys.NOTIFICATION_TITLE)).message(body).image(icon).build();
if (playSound) { notificationSound.play(); }
Platform.runLater(() -> { if (notifier.getNoOfPopups() == 0) { notifier.notify(notification); }});
lastNotification = now;
}
private void applySettingsToPreferences() {
nightscoutUrlTextField.setText(PropertyManager.INSTANCE.getString(Constants.PROPERTIES_NIGHTSCOUT_URL));
nightscoutTokenTextField.setText(PropertyManager.INSTANCE.getString(Constants.PROPERTIES_NIGHTSCOUT_TOKEN));
unitSwitch.setSelected(PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_UNIT_MG));
deltaChartSwitch.setSelected(PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_SHOW_DELTA_CHART));
voiceOutputSwitch.setSelected(PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_VOICE_OUTPUT, false));
voiceOutputIntervalSlider.setValue(PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_VOICE_OUTPUT_INTERVAL, 5));
tooLowSoundSwitch.setSelected(PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_PLAY_SOUND_FOR_TOO_LOW_NOTIFICATION));
tooLowSpeakSwitch.setSelected(PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_SPEAK_TOO_LOW_NOTIFICATION, false));
enableLowSoundSwitch.setSelected(PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_SHOW_LOW_VALUE_NOTIFICATION));
lowSpeakSwitch.setSelected(PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_SPEAK_LOW_NOTIFICATION, false));
lowSoundSwitch.setSelected(PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_PLAY_SOUND_FOR_LOW_NOTIFICATION));
enableAcceptableLowSoundSwitch.setSelected(PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_SHOW_ACCEPTABLE_LOW_VALUE_NOTIFICATION));
acceptableLowSoundSwitch.setSelected(PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_PLAY_SOUND_FOR_ACCEPTABLE_LOW_NOTIFICATION));
enableAcceptableHighSoundSwitch.setSelected(PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_SHOW_ACCEPTABLE_HIGH_VALUE_NOTIFICATION));
acceptableHighSoundSwitch.setSelected(PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_PLAY_SOUND_FOR_ACCEPTABLE_HIGH_NOTIFICATION));
enableHighSoundSwitch.setSelected(PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_SHOW_HIGH_VALUE_NOTIFICATION));
highSoundSwitch.setSelected(PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_PLAY_SOUND_FOR_HIGH_NOTIFICATION));
tooHighSoundSwitch.setSelected(PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_PLAY_SOUND_FOR_TOO_HIGH_NOTIFICATION));
tooLowIntervalSlider.setValue(PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_CRITICAL_MIN_NOTIFICATION_INTERVAL));
tooHighIntervalSlider.setValue(PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_CRITICAL_MAX_NOTIFICATION_INTERVAL));
minAcceptableSlider.setValue(UnitDefinition.MILLIGRAM_PER_DECILITER == currentUnit ? PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MIN_ACCEPTABLE) : Helper.mgPerDeciliterToMmolPerLiter(PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MIN_ACCEPTABLE)));
minNormalSlider.setValue(UnitDefinition.MILLIGRAM_PER_DECILITER == currentUnit ? PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MIN_NORMAL) : Helper.mgPerDeciliterToMmolPerLiter(PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MIN_NORMAL)));
maxNormalSlider.setValue(UnitDefinition.MILLIGRAM_PER_DECILITER == currentUnit ? PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MAX_NORMAL) : Helper.mgPerDeciliterToMmolPerLiter(PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MAX_NORMAL)));
maxAcceptableSlider.setValue(UnitDefinition.MILLIGRAM_PER_DECILITER == currentUnit ? PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MAX_ACCEPTABLE) : Helper.mgPerDeciliterToMmolPerLiter(PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MAX_ACCEPTABLE)));
}
private void savePreferencesToSettings() {
PropertyManager.INSTANCE.setString(Constants.PROPERTIES_NIGHTSCOUT_URL, nightscoutUrlTextField.getText());
PropertyManager.INSTANCE.setString(Constants.PROPERTIES_NIGHTSCOUT_TOKEN, nightscoutTokenTextField.getText());
PropertyManager.INSTANCE.setBoolean(Constants.PROPERTIES_UNIT_MG, unitSwitch.isSelected());
PropertyManager.INSTANCE.setBoolean(Constants.PROPERTIES_SHOW_DELTA_CHART, deltaChartSwitch.isSelected());
PropertyManager.INSTANCE.setBoolean(Constants.PROPERTIES_VOICE_OUTPUT, voiceOutputSwitch.isSelected());
PropertyManager.INSTANCE.setDouble(Constants.PROPERTIES_VOICE_OUTPUT_INTERVAL, voiceOutputIntervalSlider.getValue());
PropertyManager.INSTANCE.setBoolean(Constants.PROPERTIES_PLAY_SOUND_FOR_TOO_LOW_NOTIFICATION, tooLowSoundSwitch.isSelected());
PropertyManager.INSTANCE.setBoolean(Constants.PROPERTIES_SPEAK_TOO_LOW_NOTIFICATION, tooLowSpeakSwitch.isSelected());
PropertyManager.INSTANCE.setBoolean(Constants.PROPERTIES_SHOW_LOW_VALUE_NOTIFICATION, enableLowSoundSwitch.isSelected());
PropertyManager.INSTANCE.setBoolean(Constants.PROPERTIES_PLAY_SOUND_FOR_LOW_NOTIFICATION, lowSoundSwitch.isSelected());
PropertyManager.INSTANCE.setBoolean(Constants.PROPERTIES_SPEAK_LOW_NOTIFICATION, lowSpeakSwitch.isSelected());
PropertyManager.INSTANCE.setBoolean(Constants.PROPERTIES_SHOW_ACCEPTABLE_LOW_VALUE_NOTIFICATION, enableAcceptableLowSoundSwitch.isSelected());
PropertyManager.INSTANCE.setBoolean(Constants.PROPERTIES_PLAY_SOUND_FOR_ACCEPTABLE_LOW_NOTIFICATION, acceptableLowSoundSwitch.isSelected());
PropertyManager.INSTANCE.setBoolean(Constants.PROPERTIES_SHOW_ACCEPTABLE_HIGH_VALUE_NOTIFICATION, enableAcceptableHighSoundSwitch.isSelected());
PropertyManager.INSTANCE.setBoolean(Constants.PROPERTIES_PLAY_SOUND_FOR_ACCEPTABLE_HIGH_NOTIFICATION, acceptableHighSoundSwitch.isSelected());
PropertyManager.INSTANCE.setBoolean(Constants.PROPERTIES_SHOW_HIGH_VALUE_NOTIFICATION, enableHighSoundSwitch.isSelected());
PropertyManager.INSTANCE.setBoolean(Constants.PROPERTIES_PLAY_SOUND_FOR_HIGH_NOTIFICATION, highSoundSwitch.isSelected());
PropertyManager.INSTANCE.setBoolean(Constants.PROPERTIES_PLAY_SOUND_FOR_TOO_HIGH_NOTIFICATION, tooHighSoundSwitch.isSelected());
PropertyManager.INSTANCE.setDouble(Constants.PROPERTIES_CRITICAL_MIN_NOTIFICATION_INTERVAL, tooLowIntervalSlider.getValue());
PropertyManager.INSTANCE.setDouble(Constants.PROPERTIES_CRITICAL_MAX_NOTIFICATION_INTERVAL, tooHighIntervalSlider.getValue());
PropertyManager.INSTANCE.setDouble(Constants.PROPERTIES_MIN_ACCEPTABLE, UnitDefinition.MILLIGRAM_PER_DECILITER == currentUnit ? minAcceptableSlider.getValue() : Helper.mmolPerLiterToMgPerDeciliter(minAcceptableSlider.getValue()));
PropertyManager.INSTANCE.setDouble(Constants.PROPERTIES_MIN_NORMAL, UnitDefinition.MILLIGRAM_PER_DECILITER == currentUnit ? minNormalSlider.getValue() : Helper.mmolPerLiterToMgPerDeciliter(minNormalSlider.getValue()));
PropertyManager.INSTANCE.setDouble(Constants.PROPERTIES_MAX_NORMAL, UnitDefinition.MILLIGRAM_PER_DECILITER == currentUnit ? maxNormalSlider.getValue() : Helper.mmolPerLiterToMgPerDeciliter(maxNormalSlider.getValue()));
PropertyManager.INSTANCE.setDouble(Constants.PROPERTIES_MAX_ACCEPTABLE, UnitDefinition.MILLIGRAM_PER_DECILITER == currentUnit ? maxAcceptableSlider.getValue() : Helper.mmolPerLiterToMgPerDeciliter(maxAcceptableSlider.getValue()));
PropertyManager.INSTANCE.storeProperties();
nightscoutUrl = nightscoutUrlTextField.getText();
if (null != nightscoutUrl && !nightscoutUrl.isEmpty() && allEntries.isEmpty()) {
updateEntries();
if (null != service) { service.cancel(); }
Helper.getEntriesFromLast30Days(nightscoutUrl + Constants.URL_API).thenAccept(l -> allEntries.addAll(l));
service = new ScheduledService<>() {
@Override protected Task<Void> createTask() {
Task task = new Task() {
@Override protected Object call() {
updateEntries();
return null;
}
};
return task;
}
};
service.setPeriod(Duration.millis(60000));
service.setRestartOnFailure(true);
service.start();
}
nightscoutToken = nightscoutTokenTextField.getText();
updateSettings();
updateUI();
}
private void updateSettings() {
currentUnit = PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_UNIT_MG) ? MILLIGRAM_PER_DECILITER : MILLIMOL_PER_LITER;
deltaChartVisible = PropertyManager.INSTANCE.getBoolean(Constants.PROPERTIES_SHOW_DELTA_CHART);
minAcceptable = PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MIN_ACCEPTABLE);
minNormal = PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MIN_NORMAL);
maxNormal = PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MAX_NORMAL);
maxAcceptable = PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MAX_ACCEPTABLE);
minAcceptableFactor = 1.0 - minAcceptable / Constants.DEFAULT_GLUCO_RANGE;
minNormalFactor = 1.0 - minNormal / Constants.DEFAULT_GLUCO_RANGE;
maxNormalFactor = 1.0 - maxNormal / Constants.DEFAULT_GLUCO_RANGE;
maxAcceptableFactor = 1.0 - maxAcceptable / Constants.DEFAULT_GLUCO_RANGE;
}
private void updateUI() {
if (allEntries.isEmpty()) { return; }
Collections.sort(allEntries, Comparator.comparingLong(GlucoEntry::datelong).reversed());
long limit = OffsetDateTime.now().toEpochSecond() - currentInterval.getSeconds();
entries = allEntries.stream().filter(entry -> entry.datelong() > limit).collect(Collectors.toList());
// Use last entry if filtered list is empty
if (entries.isEmpty()) { entries.add(allEntries.get(0)); }
currentEntry = entries.get(0);
currentColor = null == currentEntry ? Constants.GRAY : Helper.getColorForValue(currentUnit, UnitDefinition.MILLIGRAM_PER_DECILITER == currentUnit ? currentEntry.sgv() : Helper.mgPerDeciliterToMmolPerLiter(currentEntry.sgv()));
Trend currentTrend = currentEntry.trend();
Trend currentDirection = Trend.getFromText(currentEntry.direction());
Trend trend = (Trend.NONE != currentDirection && currentTrend != currentDirection) ? currentDirection : currentTrend;
deltas.clear();
if (allEntries.size() > 13) {
for (int i = 12; i > 0; i--) {
double delta;
if (MILLIGRAM_PER_DECILITER == currentUnit) {
delta = allEntries.get(i - 1).sgv() - allEntries.get(i).sgv();
deltas.add(delta);
} else {
delta = Helper.mgPerDeciliterToMmolPerLiter(allEntries.get(i - 1).sgv()) - Helper.mgPerDeciliterToMmolPerLiter(allEntries.get(i).sgv());
deltas.add(delta);
}
}
deltaMin = deltas.stream().min(Comparator.naturalOrder()).get();
deltaMax = deltas.stream().max(Comparator.naturalOrder()).get();
if (MILLIMOL_PER_LITER == currentUnit) {
deltaMin = Helper.mgPerDeciliterToMmolPerLiter(deltaMin);
deltaMax = Helper.mgPerDeciliterToMmolPerLiter(deltaMax);
}
}
if (MILLIGRAM_PER_DECILITER == currentUnit) {
slowlyRising = deltas.stream().limit(4).filter(delta -> delta > 0).filter(delta -> delta < 3).count() == 4;
slowlyFalling = deltas.stream().limit(4).filter(delta -> delta < 0).filter(delta -> delta > -3).count() == 4;
} else {
slowlyRising = deltas.stream().limit(4).filter(delta -> delta > 0).filter(delta -> delta < Helper.mgPerDeciliterToMmolPerLiter(3)).count() == 4;
slowlyFalling = deltas.stream().limit(4).filter(delta -> delta < 0).filter(delta -> delta > Helper.mgPerDeciliterToMmolPerLiter(-3)).count() == 4;
}
String format = MILLIGRAM_PER_DECILITER == currentUnit ? "%.0f" : "%.1f";
double currentValue = UnitDefinition.MILLIGRAM_PER_DECILITER == currentUnit ? currentEntry.sgv() : Helper.mgPerDeciliterToMmolPerLiter(currentEntry.sgv());
String currentValueText = new StringBuilder().append(String.format(Locale.US, format, currentValue)).append(" ").append(trend.getSymbol()).toString();
Instant lastTimestamp = Instant.ofEpochSecond(currentEntry.datelong());
outdated = (OffsetDateTime.now().toEpochSecond() - lastTimestamp.getEpochSecond() > Constants.TIMEOUT_IN_SECONDS);
LocalDateTime dateTime = LocalDateTime.ofInstant(lastTimestamp, ZoneId.systemDefault());
if (MILLIGRAM_PER_DECILITER == currentUnit) {
avg = entries.stream().map(entry -> entry.sgv()).collect(Collectors.summingDouble(Double::doubleValue)) / entries.size();
} else {
avg = entries.stream().map(entry -> Helper.mgPerDeciliterToMmolPerLiter(entry.sgv())).collect(Collectors.summingDouble(Double::doubleValue)) / entries.size();
}
// Set value specific tray icon
if (null != trayIcon && OperatingSystem.MACOS == operatingSystem) {
SwingUtilities.invokeLater(() -> Platform.runLater(() -> {
String text = currentValueText + (outdated ? "\u26A0" : "");
trayIcon.setGraphic(Helper.createTextTrayIcon(text, Color.WHITE));
trayIcon.setTrayIconTooltip(text);
}));
}
Platform.runLater(() -> {
unit.setText(currentUnit.UNIT.getUnitShort() + " (");
if (deltas.isEmpty()) {
delta4.setText("-, ");
delta3.setText("-, ");
delta2.setText("-, ");
delta1.setText("-, ");
delta0.setText("-)");
} else {
delta4.setText(String.format(Locale.US, "%+.1f, ", deltas.get(7)));
delta3.setText(String.format(Locale.US, "%+.1f, ", deltas.get(8)));
delta2.setText(String.format(Locale.US, "%+.1f, ", deltas.get(9)));
delta1.setText(String.format(Locale.US, "%+.1f, ", deltas.get(10)));
delta0.setText(String.format(Locale.US, "%+.1f)", deltas.get(11)));
}
mainPane.setBackground(new Background(new BackgroundFill(currentColor, CornerRadii.EMPTY, Insets.EMPTY)));
valueLabel.setText(currentValueText);
//timestampLabel.setText(Constants.DTF.format(dateTime) + (outdated ? " \u26A0" : ""));
timestampLabel.setText(dtf.format(dateTime) + (outdated ? " \u26A0" : ""));
exclamationMark.setVisible(outdated);
rangeAverageLabel.setText(currentInterval.getUiString() + " (\u2300" + String.format(Locale.US, format, avg) + ")");
drawChart();
});
predict();
notifyIfNeeded();
}
private void drawChart() {
if (entries.isEmpty()) { return; }
Collections.sort(entries, Comparator.comparingLong(GlucoEntry::datelong));
double width = canvas.getWidth();
double height = canvas.getHeight();
double availableWidth = (width - GRAPH_INSETS.getLeft() - GRAPH_INSETS.getRight());
double availableHeight = (height - GRAPH_INSETS.getTop() - GRAPH_INSETS.getBottom());
boolean darkMode = eu.hansolo.applefx.tools.Helper.isDarkMode();
ctx.clearRect(0, 0, width, height);
ctx.setFill(darkMode ? Color.rgb(30, 28, 26) : Color.rgb(234, 233, 233));
ctx.fillRect(0, 0, width, height);
ctx.setFont(ticklabelFont);
ctx.setFill(Constants.BRIGHT_TEXT);
ctx.setStroke(darkMode ? Color.rgb(81, 80, 78) : Color.rgb(184, 183, 183));
ctx.setLineDashes(3, 4);
ctx.setLineWidth(1);
List<String> yAxisLabels = MILLIGRAM_PER_DECILITER == currentUnit ? Constants.yAxisLabelsMgPerDeciliter : Constants.yAxisLabelsMmolPerLiter;
// Draw chart
long chartStartEpoch = OffsetDateTime.now().minusSeconds(currentInterval.getSeconds()).toEpochSecond();
OffsetDateTime chartStartDate = OffsetDateTime.ofInstant(Instant.ofEpochSecond(chartStartEpoch), ZoneId.systemDefault());
// Get min entry if within range
GlucoEntry minEntry;
if (entries.get(0).datelong() < chartStartEpoch) {
GlucoEntry firstEntry = entries.get(0);
minEntry = new GlucoEntry(firstEntry.id(), firstEntry.sgv(), chartStartEpoch, chartStartDate, firstEntry.dateString(), firstEntry.trend(), firstEntry.direction(),
firstEntry.device(), firstEntry.type(), firstEntry.utcOffset(), firstEntry.noise(), firstEntry.filtered(), firstEntry.unfiltered(),
firstEntry.rssi(), firstEntry.delta(), firstEntry.sysTime());
} else if (entries.get(0).datelong() > chartStartEpoch) {
GlucoEntry firstEntry = entries.get(0);
minEntry = new GlucoEntry(firstEntry.id(), firstEntry.sgv(), chartStartEpoch, chartStartDate, firstEntry.dateString(), firstEntry.trend(), firstEntry.direction(),
firstEntry.device(), firstEntry.type(), firstEntry.utcOffset(), firstEntry.noise(), firstEntry.filtered(), firstEntry.unfiltered(),
firstEntry.rssi(), firstEntry.delta(), firstEntry.sysTime());
} else {
minEntry = entries.get(0);
}
double deltaTime = OffsetDateTime.now().toEpochSecond() - minEntry.datelong();
if (deltaTime > currentInterval.getSeconds()) {
deltaTime = OffsetDateTime.now().toEpochSecond() - OffsetDateTime.now().minusSeconds(currentInterval.getSeconds()).toEpochSecond();
} else if (deltaTime < currentInterval.getSeconds()) {
deltaTime = OffsetDateTime.now().toEpochSecond() - OffsetDateTime.now().minusSeconds(currentInterval.getSeconds()).toEpochSecond();
}
ZonedDateTime minDate = Helper.getZonedDateTimeFromEpochSeconds(minEntry.datelong());
double stepX = availableWidth / deltaTime;
double stepY = availableHeight / (Constants.DEFAULT_GLUCO_RANGE);
int hour = minDate.getHour();
ZonedDateTime adjMinDate = (hour == 23 && currentInterval != TimeInterval.LAST_12_HOURS) ? minDate.plusSeconds(TimeInterval.LAST_24_HOURS.getSeconds()) : minDate;
ZonedDateTime firstFullHour = (hour == 23 && currentInterval != TimeInterval.LAST_12_HOURS) ? ZonedDateTime.of(adjMinDate.plusDays(1).toLocalDate(), LocalTime.MIDNIGHT, ZoneId.systemDefault()) : adjMinDate;
long startX = firstFullHour.toEpochSecond() - minEntry.datelong();
int lastHour = -1;
double oneHourStep = Constants.SECONDS_PER_HOUR * stepX;
long hourCounter = 0;
// Collect nights
ZonedDateTime startTime = ZonedDateTime.ofInstant(Instant.ofEpochSecond(startX + minEntry.datelong()), ZoneId.systemDefault());
ZonedDateTime endTime = ZonedDateTime.ofInstant(Instant.ofEpochSecond(startX + minEntry.datelong() + currentInterval.getSeconds()), ZoneId.systemDefault());
int startHour = startTime.getHour();
int endHour = endTime.getHour();
boolean startsAtNight = false;
List<eu.hansolo.toolboxfx.geom.Rectangle> nights = new ArrayList<>();
// Chart starts at night
if (Constants.NIGHT_HOURS.contains(startHour)) {
double widthToNextFullHour = java.time.Duration.between(startTime, startTime.plusHours(1).truncatedTo(ChronoUnit.HOURS)).toSeconds() * stepX;
double w = widthToNextFullHour + (10 - Constants.NIGHT_HOURS.indexOf(startHour) - 1) * oneHourStep;
nights.add(new eu.hansolo.toolboxfx.geom.Rectangle(GRAPH_INSETS.getLeft(), GRAPH_INSETS.getTop(), w, availableHeight));
}
// Chart ends at night
if (Constants.NIGHT_HOURS.contains(endHour)) {
int dayOffset = startTime.getDayOfMonth() == endTime.getDayOfMonth() ? 0 : 1;
ZonedDateTime nightStart = ZonedDateTime.of(endTime.toLocalDate().minusDays(dayOffset), LocalTime.of(Constants.NIGHT_START, 0), ZoneId.systemDefault());
double w = availableWidth - (endTime.toEpochSecond() - nightStart.toEpochSecond()) * stepX;
nights.add(new eu.hansolo.toolboxfx.geom.Rectangle(GRAPH_INSETS.getLeft() + (nightStart.toEpochSecond() - startX) * stepX, GRAPH_INSETS.getTop(), w, availableHeight));
}
// Full nights
boolean nightStart = false;
double nightX = -1;
for (long i = startX ; i <= deltaTime ; i++) {
int h = ZonedDateTime.ofInstant(Instant.ofEpochSecond(i + minEntry.datelong()), ZoneId.systemDefault()).getHour();
double x = GRAPH_INSETS.getLeft() + i * stepX;
if (h != lastHour) {
if (!startsAtNight && Constants.NIGHT_START == h && !nightStart) {
nightStart = true;
nightX = x;
}
if (Constants.NIGHT_END == h && nightStart) {
nightStart = false;
nights.add(new eu.hansolo.toolboxfx.geom.Rectangle(nightX, GRAPH_INSETS.getTop(), 10 * oneHourStep, availableHeight));
}
}
lastHour = h;
}
if (nightStart) {
nights.add(new eu.hansolo.toolboxfx.geom.Rectangle(nightX, GRAPH_INSETS.getTop(), availableWidth - nightX + GRAPH_INSETS.getRight(), availableHeight));
}
// Draw nights
ctx.save();
ctx.setFill(darkMode ? Color.rgb(255, 255, 255, 0.1) : Color.rgb(0, 0, 0, 0.1));
nights.forEach(night -> ctx.fillRect(night.getX(), night.getY(), night.width, night.getHeight()));
ctx.restore();
// Draw vertical lines
ctx.setFill(darkMode ? Constants.BRIGHT_TEXT : Constants.DARK_TEXT);
ctx.setTextAlign(TextAlignment.CENTER);
long interval;
switch(currentInterval) {
case LAST_168_HOURS,
LAST_720_HOURS,
LAST_72_HOURS -> interval = TimeInterval.LAST_6_HOURS.getHours();
case LAST_48_HOURS -> interval = TimeInterval.LAST_3_HOURS.getHours();
default -> interval = 1;
}
hourCounter = 0;
for (long i = startX ; i <= deltaTime ; i++) {
int h = ZonedDateTime.ofInstant(Instant.ofEpochSecond(i + minEntry.datelong()), ZoneId.systemDefault()).getHour();
double x = GRAPH_INSETS.getLeft() + i * stepX;
if (h != lastHour && lastHour != -1 && i != startX) {
if (hourCounter % interval == 0) {
ctx.strokeLine(x, GRAPH_INSETS.getTop(), x, height - GRAPH_INSETS.getBottom());
switch (currentInterval) {
case LAST_3_HOURS, LAST_6_HOURS -> ctx.fillText(h + ":00", x, height - GRAPH_INSETS.getBottom() * 0.5);
default -> ctx.fillText(Integer.toString(h), x, height - GRAPH_INSETS.getBottom() * 0.25);
}
}
hourCounter++;
}
lastHour = h;
}
// Draw horizontal grid lines
ctx.setTextAlign(TextAlignment.RIGHT);
double yLabelStep = availableHeight / yAxisLabels.size();
for (int i = 0 ; i < yAxisLabels.size() ; i++) {
double y = height - GRAPH_INSETS.getBottom() - i * yLabelStep - yLabelStep;
ctx.strokeLine(GRAPH_INSETS.getLeft(), y, width - GRAPH_INSETS.getRight(), y);
ctx.fillText(yAxisLabels.get(i), GRAPH_INSETS.getLeft() * 2.5, y + 4);
}
ctx.setLineWidth(0.5);
ctx.setLineDashes();
// Draw acceptable limits
double minAcceptable = (height - GRAPH_INSETS.getBottom()) - PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MIN_ACCEPTABLE) * stepY;
double maxAcceptable = (height - GRAPH_INSETS.getBottom()) - PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MAX_ACCEPTABLE) * stepY;
ctx.setStroke(Constants.YELLOW);
ctx.strokeLine(3 * GRAPH_INSETS.getLeft(), minAcceptable, width - GRAPH_INSETS.getRight(), minAcceptable);
ctx.strokeLine(3 * GRAPH_INSETS.getLeft(), maxAcceptable, width - GRAPH_INSETS.getRight(), maxAcceptable);
// Draw normal area
double minNormal = (height - GRAPH_INSETS.getBottom()) - PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MIN_NORMAL) * stepY;
double maxNormal = (height - GRAPH_INSETS.getBottom()) - PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MAX_NORMAL) * stepY;
double heightNormal = (PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MAX_NORMAL) - PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MIN_NORMAL)) * stepY;
ctx.setFill(HelperFX.getColorWithOpacity(Constants.GREEN, 0.1));
ctx.setStroke(Constants.GREEN);
ctx.setLineWidth(1);
ctx.fillRect(3 * GRAPH_INSETS.getLeft(), maxNormal, availableWidth - 2 * GRAPH_INSETS.getRight(), heightNormal);
ctx.strokeLine( 3 * GRAPH_INSETS.getLeft(), minNormal, width - GRAPH_INSETS.getRight(), minNormal);
ctx.strokeLine(3 * GRAPH_INSETS.getLeft(), maxNormal, width - GRAPH_INSETS.getRight(), maxNormal);
// Draw average
double average;
if (UnitDefinition.MILLIGRAM_PER_DECILITER == currentUnit) {
average = (height - GRAPH_INSETS.getBottom()) - avg * stepY;
} else {
average = (height - GRAPH_INSETS.getBottom()) - (Helper.mmolPerLiterToMgPerDeciliter(avg)) * stepY;
}
ctx.setLineDashes(2,6);
ctx.setStroke(Helper.getColorForValue(currentUnit, avg));
ctx.strokeLine(GRAPH_INSETS.getLeft() * 3, average, width - GRAPH_INSETS.getRight(), average);
// Draw delta chart
ctx.setLineDashes();
if (deltaChartVisible) {
ctx.setStroke(darkMode ? Constants.BRIGHT_TEXT : Constants.DARK_TEXT);
ctx.setLineWidth(0.5);
double offsetX = GRAPH_INSETS.getLeft() + (availableWidth - Constants.DELTA_CHART_WIDTH) * 0.5;
double factorY = Constants.DELTA_CHART_HEIGHT / Math.max(Math.abs(deltaMax), Math.abs(deltaMin));
double boxWidth = 5;
double spacer = 5;
double zeroY = GRAPH_INSETS.getTop() + 50;
if (deltas.size() > 0) {
for (int i = 0; i < 12; i++) {
double delta = MILLIGRAM_PER_DECILITER == currentUnit ? deltas.get(i) : Helper.mgPerDeciliterToMmolPerLiter(deltas.get(i));
ctx.strokeRect(offsetX + i * (boxWidth + spacer), delta > 0 ? zeroY - Math.abs(delta * factorY) : zeroY, boxWidth, Math.abs(delta) * factorY);
}
}
}
// Draw line chart
ctx.setLineDashes();
ctx.setStroke(new LinearGradient(0, GRAPH_INSETS.getTop(), 0, height - GRAPH_INSETS.getBottom(), false, CycleMethod.NO_CYCLE,
new Stop(0.0, Constants.RED),
new Stop(Constants.DEFAULT_MAX_CRITICAL_FACTOR, Constants.RED),
new Stop(maxAcceptableFactor, Constants.ORANGE),
new Stop(maxNormalFactor, Constants.GREEN),
new Stop(minNormalFactor, Constants.GREEN),
new Stop(minAcceptableFactor, Constants.ORANGE),
new Stop(Constants.DEFAULT_MIN_CRITICAL_FACTOR, Constants.RED),
new Stop(1.0, Constants.RED)));
ctx.setLineWidth(2);
ctx.beginPath();
//ctx.moveTo(GRAPH_INSETS.getLeft() + startX + (entries.get(0).datelong() - minEntry.datelong()) * stepX, height - GRAPH_INSETS.getBottom() - entries.get(0).sgv() * stepY);
ctx.moveTo(GRAPH_INSETS.getLeft() + startX, height - GRAPH_INSETS.getBottom() - entries.get(0).sgv() * stepY);
for (int i = 0 ; i < entries.size() ; i++) {
GlucoEntry entry = entries.get(i);
ctx.lineTo(GRAPH_INSETS.getLeft() + startX + (entry.datelong() - minEntry.datelong()) * stepX, (height - GRAPH_INSETS.getBottom()) - entry.sgv() * stepY);
}
ctx.lineTo(width - GRAPH_INSETS.getRight(), (height - GRAPH_INSETS.getBottom()) - entries.get(entries.size() - 1).sgv() * stepY);
ctx.stroke();
}
private void speak(final String voice, final String msg) {
if (OperatingSystem.MACOS != operatingSystem || null == voice || voice.isEmpty() || null == msg || msg.isEmpty()) { return; }
final ProcessBuilder processBuilder = new ProcessBuilder();
final String message = new StringBuilder("say -v ").append(voice).append(" ").append(msg).toString();
processBuilder.command("sh", "-c", message);
try {
Process process = processBuilder.start();
process.waitFor();
} catch (InterruptedException | IOException e) {
e.printStackTrace();
}
}
// ******************** Factory methods ***********************************
private Text createDeltaText(final String text, final boolean bold, final double size) {
Text t = new Text(text);
t.setFont(bold ? Fonts.sfProRoundedBold(size) : Fonts.sfProRoundedRegular(size));
t.setFill(darkMode ? Constants.BRIGHT_TEXT : Constants.DARK_TEXT);
return t;
}
private MacosLabel createLabel(final String text, final double size, final boolean bold, final boolean rounded, final Pos alignment) {
MacosLabel label = new MacosLabel(text);
label.setDark(darkMode);
if (rounded) {
label.setFont(bold ? Fonts.sfProRoundedBold(size) : Fonts.sfProRoundedRegular(size));
} else {
label.setFont(bold ? Fonts.sfProTextBold(size) : Fonts.sfProTextRegular(size));
}
label.setAlignment(alignment);
return label;
}
private MacosLabel createLabel(final String text, final double size, final Paint color, final boolean bold, final Pos alignment, final Priority priority) {
MacosLabel label = new MacosLabel(text);
label.setFont(bold ? Fonts.sfProTextBold(size) : Fonts.sfProTextRegular(size));
label.setDark(darkMode);
label.setAlignment(alignment);
label.setPrefWidth(250);
HBox.setHgrow(label, priority);
return label;
}
private MacosToggleButton createToggleButton(final String text, final ToggleGroup toggleGroup, final EventHandler<MouseEvent> handler, final boolean dark) {
MacosToggleButton toggleButton = new MacosToggleButton(text);
toggleButton.setMaxWidth(Double.MAX_VALUE);
toggleButton.setToggleGroup(toggleGroup);
toggleButton.addEventFilter(MouseEvent.MOUSE_PRESSED, handler);
toggleButton.setDark(dark);
HBox.setHgrow(toggleButton, Priority.ALWAYS);
return toggleButton;
}
private MacosToggleButtonBarSeparator createSeparator(final boolean dark) {
MacosToggleButtonBarSeparator sep = new MacosToggleButtonBarSeparator();
sep.setDark(dark);
return sep;
}
// ******************** About *********************************************
private Dialog createAboutDialog() {
Dialog aboutDialog = new Dialog();
aboutDialog.setTitle(translator.get(I18nKeys.APP_NAME));
aboutDialog.initStyle(StageStyle.TRANSPARENT);
aboutDialog.initModality(Modality.WINDOW_MODAL);
DialogPane dialogPane = new DialogPane() {
@Override protected Node createButtonBar() {
ButtonBar buttonBar = (ButtonBar) super.createButtonBar();
buttonBar.setPadding(new Insets(0));
buttonBar.setVisible(false);
buttonBar.setManaged(false);
return buttonBar;
}
};
aboutDialog.setDialogPane(dialogPane);
Image img = new Image(Main.class.getResourceAsStream("icon128x128.png"));
Stage aboutDialogStage = (Stage) aboutDialog.getDialogPane().getScene().getWindow();
aboutDialogStage.getScene().setFill(Color.TRANSPARENT);
aboutDialogStage.setAlwaysOnTop(true);
aboutDialogStage.getScene().getStylesheets().add(Main.class.getResource("glucostatus.css").toExternalForm());
ImageView aboutImage = new ImageView(img);
aboutImage.setFitWidth(64);
aboutImage.setFitHeight(64);
MacosLabel nameLabel = new MacosLabel(translator.get(I18nKeys.APP_NAME));
nameLabel.setPrefWidth(Label.USE_COMPUTED_SIZE);
nameLabel.setMaxWidth(Double.MAX_VALUE);
nameLabel.setAlignment(Pos.CENTER);
nameLabel.setFont(Fonts.sfProTextBold(14));
nameLabel.setTextFill(darkMode ? Constants.BRIGHT_TEXT : Constants.DARK_TEXT);
MacosLabel descriptionLabel = new MacosLabel("\u00A9 Gerrit Grunwald 2022");
descriptionLabel.setPrefWidth(Label.USE_COMPUTED_SIZE);
descriptionLabel.setMaxWidth(Double.MAX_VALUE);
descriptionLabel.setFont(Fonts.sfProTextRegular(12));
descriptionLabel.setTextAlignment(TextAlignment.CENTER);
descriptionLabel.setAlignment(Pos.CENTER);
descriptionLabel.setTextFill(darkMode ? Constants.BRIGHT_TEXT : Constants.DARK_TEXT);
MacosButton closeButton = new MacosButton(translator.get(I18nKeys.ABOUT_ALERT_CLOSE_BUTTON));
closeButton.setDark(darkMode);
closeButton.setOnAction(e -> {
aboutDialog.setResult(Boolean.TRUE);
aboutDialog.close();
});
VBox.setMargin(closeButton, new Insets(20, 0, 0, 0));
VBox aboutTextBox = new VBox(10, nameLabel, descriptionLabel, closeButton);
aboutTextBox.setBackground(new Background(new BackgroundFill(Color.TRANSPARENT, CornerRadii.EMPTY, Insets.EMPTY)));
aboutTextBox.setAlignment(Pos.CENTER);
VBox aboutBox = new VBox(20, aboutImage, aboutTextBox);
aboutBox.setAlignment(Pos.CENTER);
aboutBox.setPadding(new Insets(20, 20, 20, 20));
aboutBox.setMinSize(260, 232);
aboutBox.setMaxSize(260, 232);
aboutBox.setPrefSize(260, 232);
aboutBox.setBackground(new Background(new BackgroundFill(darkMode ? MacosSystemColor.BACKGROUND.dark() : MacosSystemColor.BACKGROUND.aqua(), new CornerRadii(10), Insets.EMPTY)));
if (OperatingSystem.LINUX == operatingSystem && (Architecture.AARCH64 == architecture || Architecture.ARM64 == architecture)) {
aboutDialog.getDialogPane().setContent(new StackPane(aboutBox));
} else {
StackPane glassPane = new StackPane(aboutBox);
glassPane.setBackground(new Background(new BackgroundFill(Color.TRANSPARENT, CornerRadii.EMPTY, Insets.EMPTY)));
glassPane.setMinSize(260, 232);
glassPane.setMaxSize(260, 232);
glassPane.setPrefSize(260, 232);
glassPane.setEffect(new DropShadow(BlurType.TWO_PASS_BOX, Color.rgb(0, 0, 0, 0.35), 10.0, 0.0, 0.0, 5));
aboutDialog.getDialogPane().setContent(glassPane);
}
aboutDialog.getDialogPane().setBackground(new Background(new BackgroundFill(Color.TRANSPARENT, new CornerRadii(10), Insets.EMPTY)));
aboutDialog.setOnShowing(e -> aboutDialogStage.centerOnScreen());
return aboutDialog;
}
// ******************** Settings ******************************************
private StackPane createPrefPane() {
String format = MILLIGRAM_PER_DECILITER == currentUnit ? "%.0f" : "%.1f";
MacosButton backButton = new MacosButton("\u2190");
backButton.setDark(darkMode);
backButton.setFont(Fonts.sfProRoundedSemiBold(16));
backButton.setPadding(new Insets(2, 5, 2, 5));
AnchorPane.setTopAnchor(backButton, 10d);
AnchorPane.setLeftAnchor(backButton, 10d);
backButton.setOnAction(e -> {
prefPane.setVisible(false);
prefPane.setManaged(false);
savePreferencesToSettings();
});
MacosLabel settingsLabel = new MacosLabel(translator.get(I18nKeys.SETTINGS_TITLE));
settingsLabel.setDark(darkMode);
settingsLabel.setFont(Fonts.sfProTextBold(14));
AnchorPane.setTopAnchor(settingsLabel, 50d);
AnchorPane.setLeftAnchor(settingsLabel, 30d);
MacosLabel nightscoutUrlLabel = new MacosLabel(translator.get(I18nKeys.SETTINGS_NIGHTSCOUT_URL));
nightscoutUrlLabel.setDark(darkMode);
nightscoutUrlLabel.setFont(Fonts.sfProTextRegular(14));
nightscoutUrlTextField = new MacosTextField();
nightscoutUrlTextField.setDark(darkMode);
nightscoutUrlTextField.setFont(Fonts.sfProRoundedRegular(14));
nightscoutUrlTextField.setPrefWidth(TextField.USE_COMPUTED_SIZE);
nightscoutUrlTextField.setMaxWidth(Double.MAX_VALUE);
nightscoutUrlTextField.setPromptText("https://YOUR_DOMAIN.herokuapp.com");
HBox.setHgrow(nightscoutUrlTextField, Priority.ALWAYS);
HBox nightscoutUrlBox = new HBox(10, nightscoutUrlLabel, nightscoutUrlTextField);
nightscoutUrlBox.setAlignment(Pos.CENTER);
MacosLabel nightscoutTokenLabel = new MacosLabel(translator.get(I18nKeys.SETTINGS_NIGHTSCOUT_TOKEN));
nightscoutTokenLabel.setDark(darkMode);
nightscoutTokenLabel.setFont(Fonts.sfProTextRegular(14));
nightscoutTokenTextField = new MacosTextField();
nightscoutTokenTextField.setDark(darkMode);
nightscoutTokenTextField.setFont(Fonts.sfProRoundedRegular(14));
nightscoutTokenTextField.setPrefWidth(TextField.USE_COMPUTED_SIZE);
nightscoutTokenTextField.setMaxWidth(Double.MAX_VALUE);
HBox.setHgrow(nightscoutTokenTextField, Priority.ALWAYS);
HBox nightscoutTokenBox = new HBox(10, nightscoutTokenLabel, nightscoutTokenTextField);
nightscoutTokenBox.setAlignment(Pos.CENTER);
MacosSeparator s1 = new MacosSeparator(Orientation.HORIZONTAL);
s1.setDark(darkMode);
VBox.setMargin(s1, new Insets(5, 0, 5, 0));
unitSwitch = MacosSwitchBuilder.create().dark(darkMode).ios(true).selectedColor(accentColor).build();
MacosLabel unitLabel = new MacosLabel(translator.get(I18nKeys.SETTINGS_UNIT) + currentUnit.UNIT.getUnitShort());
unitLabel.setDark(darkMode);
unitLabel.setFont(Fonts.sfProTextRegular(14));
HBox.setHgrow(unitLabel, Priority.ALWAYS);
HBox unitBox = new HBox(10, unitSwitch, unitLabel);
unitBox.setAlignment(Pos.CENTER_LEFT);
unitSwitch.selectedProperty().addListener((o, ov, nv) -> {
switchingUnits.set(true);
currentUnit = nv ? MILLIGRAM_PER_DECILITER : MILLIMOL_PER_LITER;
unitLabel.setText(translator.get(I18nKeys.SETTINGS_UNIT) + currentUnit.UNIT.getUnitShort());
if (MILLIGRAM_PER_DECILITER == currentUnit) {
minAcceptableSlider.setMin(Constants.SETTINGS_MIN_ACCEPTABLE_MIN);
minAcceptableSlider.setMax(Constants.SETTINGS_MIN_ACCEPTABLE_MAX);
minAcceptableSlider.setMajorTickUnit(1);
minAcceptableSlider.setBlockIncrement(1);
minAcceptableSlider.setValue(PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MIN_ACCEPTABLE));
minNormalSlider.setMin(Constants.SETTINGS_MIN_NORMAL_MIN);
minNormalSlider.setMax(Constants.SETTINGS_MIN_NORMAL_MAX);
minNormalSlider.setMajorTickUnit(1);
minNormalSlider.setBlockIncrement(1);
minNormalSlider.setValue(PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MIN_NORMAL));
maxNormalSlider.setMin(Constants.SETTINGS_MAX_NORMAL_MIN);
maxNormalSlider.setMax(Constants.SETTINGS_MAX_NORMAL_MAX);
maxNormalSlider.setMajorTickUnit(5);
maxNormalSlider.setBlockIncrement(5);
maxNormalSlider.setValue(PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MAX_NORMAL));
maxAcceptableSlider.setMin(Constants.SETTINGS_MAX_ACCEPTABLE_MIN);
maxAcceptableSlider.setMax(Constants.SETTINGS_MAX_ACCEPTABLE_MAX);
maxAcceptableSlider.setMajorTickUnit(5);
maxAcceptableSlider.setBlockIncrement(5);
maxAcceptableSlider.setValue(PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MAX_ACCEPTABLE));
} else {
minAcceptableSlider.setMin(Helper.mgPerDeciliterToMmolPerLiter(Constants.SETTINGS_MIN_ACCEPTABLE_MIN));
minAcceptableSlider.setMax(Helper.mgPerDeciliterToMmolPerLiter(Constants.SETTINGS_MIN_ACCEPTABLE_MAX));
minAcceptableSlider.setMajorTickUnit(Helper.mgPerDeciliterToMmolPerLiter(1));
minAcceptableSlider.setBlockIncrement(Helper.mgPerDeciliterToMmolPerLiter(1));
minAcceptableSlider.setValue(Helper.mgPerDeciliterToMmolPerLiter(PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MIN_ACCEPTABLE)));
minNormalSlider.setMin(Helper.mgPerDeciliterToMmolPerLiter(Constants.SETTINGS_MIN_NORMAL_MIN));
minNormalSlider.setMax(Helper.mgPerDeciliterToMmolPerLiter(Constants.SETTINGS_MIN_NORMAL_MAX));
minNormalSlider.setMajorTickUnit(Helper.mgPerDeciliterToMmolPerLiter(1));
minNormalSlider.setBlockIncrement(Helper.mgPerDeciliterToMmolPerLiter(1));
minNormalSlider.setValue(Helper.mgPerDeciliterToMmolPerLiter(PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MIN_NORMAL)));
maxNormalSlider.setMin(Helper.mgPerDeciliterToMmolPerLiter(Constants.SETTINGS_MAX_NORMAL_MIN));
maxNormalSlider.setMax(Helper.mgPerDeciliterToMmolPerLiter(Constants.SETTINGS_MAX_NORMAL_MAX));
maxNormalSlider.setMajorTickUnit(Helper.mgPerDeciliterToMmolPerLiter(5));
maxNormalSlider.setBlockIncrement(Helper.mgPerDeciliterToMmolPerLiter(5));
maxNormalSlider.setValue(Helper.mgPerDeciliterToMmolPerLiter(PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MAX_NORMAL)));
maxAcceptableSlider.setMin(Helper.mgPerDeciliterToMmolPerLiter(Constants.SETTINGS_MAX_ACCEPTABLE_MIN));
maxAcceptableSlider.setMax(Helper.mgPerDeciliterToMmolPerLiter(Constants.SETTINGS_MAX_ACCEPTABLE_MAX));
maxAcceptableSlider.setMajorTickUnit(Helper.mgPerDeciliterToMmolPerLiter(5));
maxAcceptableSlider.setBlockIncrement(Helper.mgPerDeciliterToMmolPerLiter(5));
maxAcceptableSlider.setValue(Helper.mgPerDeciliterToMmolPerLiter(PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MAX_ACCEPTABLE)));
}
switchingUnits.set(false);
});
MacosSeparator s2 = new MacosSeparator(Orientation.HORIZONTAL);
s2.setDark(darkMode);
VBox.setMargin(s2, new Insets(5, 0, 5, 0));
deltaChartSwitch = MacosSwitchBuilder.create().dark(darkMode).ios(true).selectedColor(accentColor).build();
MacosLabel deltaChartLabel = new MacosLabel(translator.get(I18nKeys.SETTINGS_SHOW_DELTA_CHART));
deltaChartLabel.setDark(darkMode);
deltaChartLabel.setFont(Fonts.sfProTextRegular(14));
HBox.setHgrow(deltaChartLabel, Priority.ALWAYS);
HBox deltaChartBox = new HBox(10, deltaChartSwitch, deltaChartLabel);
deltaChartBox.setAlignment(Pos.CENTER_LEFT);
MacosSeparator s3 = new MacosSeparator(Orientation.HORIZONTAL);
s3.setDark(darkMode);
VBox.setMargin(s3, new Insets(5, 0, 10, 0));
voiceOutputSwitch = MacosSwitchBuilder.create().dark(darkMode).ios(true).selectedColor(accentColor).build();
MacosLabel voiceOutputLabel = createLabel(translator.get(I18nKeys.SETTINGS_VOICE_OUTPUT), 14, Constants.BRIGHT_TEXT, false, Pos.CENTER_LEFT, Priority.ALWAYS);
MacosLabel voiceOutputIntervalLabel = createLabel(translator.get(I18nKeys.SETTINGS_VOICE_OUTPUT_INTERVAL) + "5 min", 14, Constants.BRIGHT_TEXT, false, Pos.CENTER_LEFT, Priority.ALWAYS);
VBox.setMargin(voiceOutputIntervalLabel, new Insets(10, 0, 5, 0));
voiceOutputIntervalSlider = new MacosSlider();
voiceOutputIntervalSlider.setDark(darkMode);
voiceOutputIntervalSlider.setMin(5);
voiceOutputIntervalSlider.setMax(60);
voiceOutputIntervalSlider.setSnapToTicks(true);
voiceOutputIntervalSlider.setShowTickMarks(true);
voiceOutputIntervalSlider.setMinorTickCount(0);
voiceOutputIntervalSlider.setMajorTickUnit(5);
voiceOutputIntervalSlider.setBlockIncrement(5);
voiceOutputIntervalSlider.valueProperty().addListener((o, ov, nv) -> voiceOutputIntervalLabel.setText(translator.get(I18nKeys.SETTINGS_VOICE_OUTPUT_INTERVAL) + String.format(Locale.US, "%.0f", voiceOutputIntervalSlider.getValue()) + " min"));
VBox.setMargin(voiceOutputIntervalSlider, new Insets(5, 0, 5, 0));
if (OperatingSystem.MACOS != operatingSystem) {
voiceOutputSwitch.setVisible(false);
voiceOutputSwitch.setManaged(false);
voiceOutputLabel.setVisible(false);
voiceOutputLabel.setManaged(false);
voiceOutputIntervalLabel.setVisible(false);
voiceOutputIntervalLabel.setManaged(false);
voiceOutputIntervalSlider.setVisible(false);
voiceOutputIntervalSlider.setManaged(false);
}
HBox voiceOutputBox = new HBox(10, voiceOutputSwitch, voiceOutputLabel);
unitBox.setAlignment(Pos.CENTER_LEFT);
MacosLabel notificationsLabel = new MacosLabel(translator.get(I18nKeys.SETTINGS_NOTIFICATION_TITLE));
notificationsLabel.setDark(darkMode);
notificationsLabel.setFont(Fonts.sfProTextBold(14));
// Too low
MacosLabel tooLowLabel = createLabel(translator.get(I18nKeys.SETTINGS_TOO_LOW_VALUE_NOTIFICATION), 14, Constants.BRIGHT_TEXT, false, Pos.CENTER_LEFT, Priority.SOMETIMES);
MacosLabel tooLowSoundLabel = createLabel(translator.get(I18nKeys.SETTINGS_TOO_LOW_VALUE_NOTIFICATION_SOUND), 14, Constants.BRIGHT_TEXT, false, Pos.CENTER_RIGHT, Priority.ALWAYS);
tooLowSoundLabel.setMaxWidth(Double.MAX_VALUE);
tooLowSoundSwitch = MacosSwitchBuilder.create().dark(darkMode).ios(true).selectedColor(accentColor).build();
Region tooLowLeftSpacer = new Region();
MacosLabel tooLowSpeakLabel = createLabel(translator.get(I18nKeys.SETTINGS_TOO_LOW_VALUE_NOTIFICATION_SPEAK), 14, Constants.BRIGHT_TEXT, false, Pos.CENTER_RIGHT, Priority.NEVER);
tooLowSpeakSwitch = MacosSwitchBuilder.create().dark(darkMode).ios(true).selectedColor(accentColor).build();
HBox tooLowSpeakBox = new HBox(10, tooLowSpeakLabel, tooLowSpeakSwitch);
tooLowSpeakBox.setAlignment(Pos.CENTER);
Region tooLowRightSpacer = new Region();
if (OperatingSystem.MACOS != operatingSystem) {
tooLowSpeakBox.setVisible(false);
tooLowSpeakBox.setManaged(false);
}
HBox.setHgrow(tooLowLeftSpacer, Priority.ALWAYS);
HBox.setHgrow(tooLowSpeakBox, Priority.NEVER);
HBox.setHgrow(tooLowRightSpacer, Priority.ALWAYS);
HBox tooLowBox = new HBox(10, tooLowLabel, tooLowLeftSpacer, tooLowSpeakBox, tooLowRightSpacer, tooLowSoundLabel, tooLowSoundSwitch);
tooLowBox.setAlignment(Pos.CENTER_LEFT);
// Low
enableLowSoundSwitch = MacosSwitchBuilder.create().dark(darkMode).ios(true).selectedColor(accentColor).build();
MacosLabel lowLabel = createLabel(translator.get(I18nKeys.SETTINGS_LOW_VALUE_NOTIFICATION), 14, Constants.BRIGHT_TEXT, false, Pos.CENTER_LEFT, Priority.SOMETIMES);
MacosLabel lowSoundLabel = createLabel(translator.get(I18nKeys.SETTINGS_LOW_VALUE_NOTIFICATION_SOUND), 14, Constants.BRIGHT_TEXT, false, Pos.CENTER_RIGHT, Priority.ALWAYS);
lowSoundLabel.setMaxWidth(Double.MAX_VALUE);
lowSoundSwitch = MacosSwitchBuilder.create().dark(darkMode).ios(true).selectedColor(accentColor).build();
Region lowLeftSpacer = new Region();
MacosLabel lowSpeakLabel = createLabel(translator.get(I18nKeys.SETTINGS_LOW_VALUE_NOTIFICATION_SPEAK), 14, Constants.BRIGHT_TEXT, false, Pos.CENTER_RIGHT, Priority.NEVER);
lowSpeakSwitch = MacosSwitchBuilder.create().dark(darkMode).ios(true).selectedColor(accentColor).build();
HBox lowSpeakBox = new HBox(10, lowSpeakLabel, lowSpeakSwitch);
lowSpeakBox.setAlignment(Pos.CENTER);
Region lowRightSpacer = new Region();
if (OperatingSystem.MACOS != operatingSystem) {
lowSpeakBox.setVisible(false);
lowSpeakBox.setManaged(false);
}
HBox.setHgrow(lowLeftSpacer, Priority.ALWAYS);
HBox.setHgrow(lowSpeakBox, Priority.NEVER);
HBox.setHgrow(lowRightSpacer, Priority.ALWAYS);
HBox lowBox = new HBox(10, enableLowSoundSwitch, lowLabel, lowLeftSpacer, lowSpeakBox, lowRightSpacer, lowSoundLabel, lowSoundSwitch);
lowBox.setAlignment(Pos.CENTER_LEFT);
// Acceptable low
enableAcceptableLowSoundSwitch = MacosSwitchBuilder.create().dark(darkMode).ios(true).selectedColor(accentColor).build();
MacosLabel acceptableLowLabel = createLabel(translator.get(I18nKeys.SETTINGS_ACCEPTABLE_LOW_VALUE_NOTIFICATION), 14, Constants.BRIGHT_TEXT, false, Pos.CENTER_LEFT, Priority.SOMETIMES);
MacosLabel acceptableLowSoundLabel = createLabel(translator.get(I18nKeys.SETTINGS_ACCEPTABLE_LOW_VALUE_NOTIFICATION_SOUND), 14, Constants.BRIGHT_TEXT, false, Pos.CENTER_RIGHT, Priority.ALWAYS);
acceptableLowSoundLabel.setMaxWidth(Double.MAX_VALUE);
acceptableLowSoundSwitch = MacosSwitchBuilder.create().dark(darkMode).ios(true).selectedColor(accentColor).build();
HBox acceptableLowBox = new HBox(10, enableAcceptableLowSoundSwitch, acceptableLowLabel, acceptableLowSoundLabel, acceptableLowSoundSwitch);
acceptableLowBox.setAlignment(Pos.CENTER_LEFT);
// Acceptable high
enableAcceptableHighSoundSwitch = MacosSwitchBuilder.create().dark(darkMode).ios(true).selectedColor(accentColor).build();
MacosLabel acceptableHighLabel = createLabel(translator.get(I18nKeys.SETTINGS_ACCEPTABLE_HIGH_VALUE_NOTIFICATION), 14, Constants.BRIGHT_TEXT, false, Pos.CENTER_LEFT, Priority.SOMETIMES);
MacosLabel acceptableHighSoundLabel = createLabel(translator.get(I18nKeys.SETTINGS_ACCEPTABLE_HIGH_VALUE_NOTIFICATION_SOUND), 14, Constants.BRIGHT_TEXT, false, Pos.CENTER_RIGHT, Priority.ALWAYS);
acceptableHighSoundLabel.setMaxWidth(Double.MAX_VALUE);
acceptableHighSoundSwitch = MacosSwitchBuilder.create().dark(darkMode).ios(true).selectedColor(accentColor).build();
HBox acceptableHighBox = new HBox(10, enableAcceptableHighSoundSwitch, acceptableHighLabel, acceptableHighSoundLabel, acceptableHighSoundSwitch);
acceptableHighBox.setAlignment(Pos.CENTER_LEFT);
// High
enableHighSoundSwitch = MacosSwitchBuilder.create().dark(darkMode).ios(true).selectedColor(accentColor).build();
MacosLabel highLabel = createLabel(translator.get(I18nKeys.SETTINGS_HIGH_VALUE_NOTIFICATION), 14, Constants.BRIGHT_TEXT, false, Pos.CENTER_LEFT, Priority.SOMETIMES);
MacosLabel highSoundLabel = createLabel(translator.get(I18nKeys.SETTINGS_HIGH_VALUE_NOTIFICATION_SOUND), 14, Constants.BRIGHT_TEXT, false, Pos.CENTER_RIGHT, Priority.ALWAYS);
highSoundLabel.setMaxWidth(Double.MAX_VALUE);
highSoundSwitch = MacosSwitchBuilder.create().dark(darkMode).ios(true).selectedColor(accentColor).build();
HBox highBox = new HBox(10, enableHighSoundSwitch, highLabel, highSoundLabel, highSoundSwitch);
highBox.setAlignment(Pos.CENTER_LEFT);
// Too high
MacosLabel tooHighLabel = createLabel(translator.get(I18nKeys.SETTINGS_TOO_HIGH_VALUE_NOTIFICATION), 14, Constants.BRIGHT_TEXT, false, Pos.CENTER_LEFT, Priority.SOMETIMES);
MacosLabel tooHighSoundLabel = createLabel(translator.get(I18nKeys.SETTINGS_TOO_HIGH_VALUE_NOTIFICATION_SOUND), 14, Constants.BRIGHT_TEXT, false, Pos.CENTER_RIGHT, Priority.ALWAYS);
tooHighSoundLabel.setMaxWidth(Double.MAX_VALUE);
tooHighSoundSwitch = MacosSwitchBuilder.create().dark(darkMode).ios(true).selectedColor(accentColor).build();
HBox tooHighBox = new HBox(10, tooHighLabel, tooHighSoundLabel, tooHighSoundSwitch);
tooHighBox.setAlignment(Pos.CENTER_LEFT);
MacosSeparator s4 = new MacosSeparator(Orientation.HORIZONTAL);
s4.setDark(darkMode);
VBox.setMargin(s4, new Insets(5, 0, 5, 0));
// Too low interval
MacosLabel tooLowIntervalLabel = createLabel(translator.get(I18nKeys.SETTINGS_TOO_LOW_NOTIFICATION_INTERVAL) + "5 min", 14, Constants.BRIGHT_TEXT, false, Pos.CENTER_LEFT, Priority.SOMETIMES);
tooLowIntervalSlider = new MacosSlider();
tooLowIntervalSlider.setDark(darkMode);
tooLowIntervalSlider.setMin(5);
tooLowIntervalSlider.setMax(10);
tooLowIntervalSlider.setSnapToTicks(true);
tooLowIntervalSlider.setShowTickMarks(true);
tooLowIntervalSlider.setMinorTickCount(0);
tooLowIntervalSlider.setMajorTickUnit(1);
tooLowIntervalSlider.setBlockIncrement(1);
tooLowIntervalSlider.valueProperty().addListener((o, ov, nv) -> tooLowIntervalLabel.setText(translator.get(I18nKeys.SETTINGS_TOO_LOW_NOTIFICATION_INTERVAL) + String.format(Locale.US, "%.0f", tooLowIntervalSlider.getValue()) + " min"));
// Too high interval
MacosLabel tooHighIntervalLabel = createLabel(translator.get(I18nKeys.SETTINGS_TOO_HIGH_NOTIFICATION_INTERVAL) + "5 min", 14, Constants.BRIGHT_TEXT, false, Pos.CENTER_LEFT, Priority.SOMETIMES);
tooHighIntervalSlider = new MacosSlider();
tooHighIntervalSlider.setDark(darkMode);
tooHighIntervalSlider.setMin(5);
tooHighIntervalSlider.setMax(30);
tooHighIntervalSlider.setSnapToTicks(true);
tooHighIntervalSlider.setShowTickMarks(true);
tooHighIntervalSlider.setMinorTickCount(0);
tooHighIntervalSlider.setMajorTickUnit(5);
tooHighIntervalSlider.setBlockIncrement(5);
tooHighIntervalSlider.valueProperty().addListener((o, ov, nv) -> tooHighIntervalLabel.setText(translator.get(I18nKeys.SETTINGS_TOO_HIGH_NOTIFICATION_INTERVAL) + String.format(Locale.US, "%.0f", tooHighIntervalSlider.getValue()) + " min"));
MacosSeparator s5 = new MacosSeparator(Orientation.HORIZONTAL);
s5.setDark(darkMode);
VBox.setMargin(s5, new Insets(5, 0, 5, 0));
MacosLabel rangesLabel = new MacosLabel(translator.get(I18nKeys.SETTINGS_RANGES_TITLE));
rangesLabel.setDark(darkMode);
rangesLabel.setFont(Fonts.sfProTextBold(14));
MacosLabel minAcceptableLabel = createLabel(new StringBuilder().append(translator.get(I18nKeys.SETTINGS_MIN_ACCEPTABLE)).append(String.format(Locale.US, format, (UnitDefinition.MILLIGRAM_PER_DECILITER == currentUnit ? Constants.DEFAULT_MIN_ACCEPTABLE : Helper.mgPerDeciliterToMmolPerLiter(Constants.DEFAULT_MIN_ACCEPTABLE)))).append(" ").append(currentUnit.UNIT.getUnitShort()).toString(), 14, Constants.BRIGHT_TEXT, false, Pos.CENTER_LEFT, Priority.SOMETIMES);
minAcceptableSlider = new MacosSlider();
minAcceptableSlider.setDark(darkMode);
minAcceptableSlider.setMin(UnitDefinition.MILLIGRAM_PER_DECILITER == currentUnit ? Constants.SETTINGS_MIN_ACCEPTABLE_MIN : Helper.mgPerDeciliterToMmolPerLiter(Constants.SETTINGS_MIN_ACCEPTABLE_MIN));
minAcceptableSlider.setMax(UnitDefinition.MILLIGRAM_PER_DECILITER == currentUnit ? Constants.SETTINGS_MIN_ACCEPTABLE_MAX : Helper.mgPerDeciliterToMmolPerLiter(Constants.SETTINGS_MIN_ACCEPTABLE_MAX));
minAcceptableSlider.setSnapToTicks(true);
minAcceptableSlider.setShowTickMarks(true);
minAcceptableSlider.setMinorTickCount(0);
minAcceptableSlider.setMajorTickUnit(1);
minAcceptableSlider.setBlockIncrement(1);
minAcceptableSlider.setValue(UnitDefinition.MILLIGRAM_PER_DECILITER == currentUnit ? Constants.DEFAULT_MIN_ACCEPTABLE : Helper.mgPerDeciliterToMmolPerLiter(Constants.DEFAULT_MIN_ACCEPTABLE));
minAcceptableSlider.valueProperty().addListener((o, ov, nv) -> minAcceptableLabel.setText(new StringBuilder().append(translator.get(I18nKeys.SETTINGS_MIN_ACCEPTABLE)).append(String.format(Locale.US, format, minAcceptableSlider.getValue())).append(" ").append(currentUnit.UNIT.getUnitShort()).toString()));
MacosLabel minNormalLabel = createLabel(new StringBuilder().append(translator.get(I18nKeys.SETTINGS_MIN_NORMAL)).append(String.format(Locale.US, format, (UnitDefinition.MILLIGRAM_PER_DECILITER == currentUnit ? Constants.DEFAULT_MIN_NORMAL : Helper.mgPerDeciliterToMmolPerLiter(Constants.DEFAULT_MIN_NORMAL)))).append(" ").append(currentUnit.UNIT.getUnitShort()).toString(), 14, Constants.BRIGHT_TEXT, false, Pos.CENTER_LEFT, Priority.SOMETIMES);
minNormalSlider = new MacosSlider();
minNormalSlider.setDark(darkMode);
minNormalSlider.setMin(UnitDefinition.MILLIGRAM_PER_DECILITER == currentUnit ? Constants.SETTINGS_MIN_NORMAL_MIN : Helper.mgPerDeciliterToMmolPerLiter(Constants.SETTINGS_MIN_NORMAL_MIN));
minNormalSlider.setMax(UnitDefinition.MILLIGRAM_PER_DECILITER == currentUnit ? Constants.SETTINGS_MIN_NORMAL_MAX : Helper.mgPerDeciliterToMmolPerLiter(Constants.SETTINGS_MIN_NORMAL_MAX));
minNormalSlider.setSnapToTicks(true);
minNormalSlider.setShowTickMarks(true);
minNormalSlider.setMinorTickCount(0);
minNormalSlider.setMajorTickUnit(1);
minNormalSlider.setBlockIncrement(1);
minNormalSlider.setValue(UnitDefinition.MILLIGRAM_PER_DECILITER == currentUnit ? Constants.DEFAULT_MIN_NORMAL : Helper.mgPerDeciliterToMmolPerLiter(Constants.DEFAULT_MIN_NORMAL));
minNormalSlider.valueProperty().addListener((o, ov, nv) -> minNormalLabel.setText(new StringBuilder().append(translator.get(I18nKeys.SETTINGS_MIN_NORMAL)).append(String.format(Locale.US, format, minNormalSlider.getValue())).append(" ").append(currentUnit.UNIT.getUnitShort()).toString()));
MacosLabel maxNormalLabel = createLabel(new StringBuilder().append(translator.get(I18nKeys.SETTINGS_MAX_NORMAL)).append(String.format(Locale.US, format, (UnitDefinition.MILLIGRAM_PER_DECILITER == currentUnit ? Constants.DEFAULT_MAX_NORMAL : Helper.mgPerDeciliterToMmolPerLiter(Constants.DEFAULT_MAX_NORMAL)))).append(" ").append(currentUnit.UNIT.getUnitShort()).toString(), 14, Constants.BRIGHT_TEXT, false, Pos.CENTER_LEFT, Priority.SOMETIMES);
maxNormalSlider = new MacosSlider();
maxNormalSlider.setDark(darkMode);
maxNormalSlider.setMin(UnitDefinition.MILLIGRAM_PER_DECILITER == currentUnit ? Constants.SETTINGS_MAX_NORMAL_MIN : Helper.mgPerDeciliterToMmolPerLiter(Constants.SETTINGS_MAX_NORMAL_MIN));
maxNormalSlider.setMax(UnitDefinition.MILLIGRAM_PER_DECILITER == currentUnit ? Constants.SETTINGS_MAX_NORMAL_MAX : Helper.mgPerDeciliterToMmolPerLiter(Constants.SETTINGS_MAX_NORMAL_MAX));
maxNormalSlider.setSnapToTicks(true);
maxNormalSlider.setShowTickMarks(true);
maxNormalSlider.setMinorTickCount(0);
maxNormalSlider.setMajorTickUnit(5);
maxNormalSlider.setBlockIncrement(5);
maxNormalSlider.setValue(UnitDefinition.MILLIGRAM_PER_DECILITER == currentUnit ? Constants.DEFAULT_MAX_NORMAL : Helper.mgPerDeciliterToMmolPerLiter(Constants.DEFAULT_MAX_NORMAL));
maxNormalSlider.valueProperty().addListener((o, ov, nv) -> {
maxNormalLabel.setText(new StringBuilder().append("Max normal: ").append(String.format(Locale.US, format, maxNormalSlider.getValue())).append(" ").append(currentUnit.UNIT.getUnitShort()).toString());
if (switchingUnits.get()) { return; }
if (nv.doubleValue() > maxAcceptableSlider.getValue()) { maxAcceptableSlider.setValue(nv.doubleValue()); }
});
MacosLabel maxAcceptableLabel = createLabel(new StringBuilder().append(translator.get(I18nKeys.SETTINGS_MAX_ACCEPTABLE)).append(String.format(Locale.US, format, (UnitDefinition.MILLIGRAM_PER_DECILITER == currentUnit ? Constants.DEFAULT_MAX_ACCEPTABLE : Helper.mgPerDeciliterToMmolPerLiter(Constants.DEFAULT_MAX_ACCEPTABLE)))).append(" ").append(currentUnit.UNIT.getUnitShort()).toString(), 14, Constants.BRIGHT_TEXT, false, Pos.CENTER_LEFT, Priority.SOMETIMES);
maxAcceptableSlider = new MacosSlider();
maxAcceptableSlider.setDark(darkMode);
maxAcceptableSlider.setMin(UnitDefinition.MILLIGRAM_PER_DECILITER == currentUnit ? Constants.SETTINGS_MAX_ACCEPTABLE_MIN : Helper.mgPerDeciliterToMmolPerLiter(Constants.SETTINGS_MAX_ACCEPTABLE_MIN));
maxAcceptableSlider.setMax(UnitDefinition.MILLIGRAM_PER_DECILITER == currentUnit ? Constants.SETTINGS_MAX_ACCEPTABLE_MAX : Helper.mgPerDeciliterToMmolPerLiter(Constants.SETTINGS_MAX_ACCEPTABLE_MAX));
maxAcceptableSlider.setSnapToTicks(true);
maxAcceptableSlider.setShowTickMarks(true);
maxAcceptableSlider.setMinorTickCount(0);
maxAcceptableSlider.setMajorTickUnit(5);
maxAcceptableSlider.setBlockIncrement(5);
maxAcceptableSlider.setValue(UnitDefinition.MILLIGRAM_PER_DECILITER == currentUnit ? Constants.DEFAULT_MAX_ACCEPTABLE : Helper.mgPerDeciliterToMmolPerLiter(Constants.DEFAULT_MAX_ACCEPTABLE));
maxAcceptableSlider.valueProperty().addListener((o, ov, nv) -> {
maxAcceptableLabel.setText(new StringBuilder().append(translator.get(I18nKeys.SETTINGS_MAX_ACCEPTABLE)).append(String.format(Locale.US, format, maxAcceptableSlider.getValue())).append(" ").append(currentUnit.UNIT.getUnitShort()).toString());
if (switchingUnits.get()) { return; }
if (nv.doubleValue() < maxNormalSlider.getValue()) { maxNormalSlider.setValue(nv.doubleValue()); }
});
VBox settingsVBox = new VBox(5, nightscoutUrlBox, nightscoutTokenBox, s1, unitBox, s2, deltaChartBox, s3,
voiceOutputBox, voiceOutputIntervalLabel, voiceOutputIntervalSlider,
notificationsLabel, tooLowBox, lowBox, acceptableLowBox, acceptableHighBox, highBox, tooHighBox, s4,
tooLowIntervalLabel, tooLowIntervalSlider, tooHighIntervalLabel, tooHighIntervalSlider, s5,
rangesLabel, minAcceptableLabel, minAcceptableSlider, minNormalLabel, minNormalSlider, maxNormalLabel, maxNormalSlider, maxAcceptableLabel, maxAcceptableSlider);
settingsVBox.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
settingsVBox.setFillWidth(true);
MacosScrollPane scrollPane = new MacosScrollPane(settingsVBox);
scrollPane.setFitToWidth(true);
scrollPane.setFitToHeight(true);
scrollPane.setBackground(new Background(new BackgroundFill(Color.TRANSPARENT, CornerRadii.EMPTY, Insets.EMPTY)));
AnchorPane.setTopAnchor(scrollPane, 80d);
AnchorPane.setRightAnchor(scrollPane, 30d);
AnchorPane.setBottomAnchor(scrollPane, 20d);
AnchorPane.setLeftAnchor(scrollPane, 30d);
prefContentPane = new AnchorPane(backButton, settingsLabel, scrollPane);
prefContentPane.setBackground(new Background(new BackgroundFill(darkMode ? MacosSystemColor.BACKGROUND.dark() : MacosSystemColor.BACKGROUND.aqua(), new CornerRadii(10), Insets.EMPTY)));
StackPane prefPane = new StackPane(prefContentPane);
return prefPane;
}
// ******************** Time in Range Chart *******************************
private void showTimeInRangeChart() {
if (dialogVisible.get()) { return; }
dialogVisible.set(true);
double noOfValues = entries.size();
double pTooHigh = (entries.stream().filter(entry -> entry.sgv() > Constants.DEFAULT_MAX_CRITICAL).count() / noOfValues);
double pHigh = (entries.stream().filter(entry -> entry.sgv() > PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MAX_NORMAL)).filter(entry -> entry.sgv() <= PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MAX_CRITICAL)).count() / noOfValues);
double pNormal = (entries.stream().filter(entry -> entry.sgv() > PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MIN_NORMAL)).filter(entry -> entry.sgv() <= PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MAX_NORMAL)).count() / noOfValues);
double pLow = (entries.stream().filter(entry -> entry.sgv() > Constants.DEFAULT_MIN_CRITICAL).filter(entry -> entry.sgv() <= PropertyManager.INSTANCE.getDouble(Constants.PROPERTIES_MIN_NORMAL)).count() / noOfValues);
double pTooLow = (entries.stream().filter(entry -> entry.sgv() < Constants.DEFAULT_MIN_CRITICAL).count() / noOfValues);
MacosLabel titleLabel = createLabel(translator.get(I18nKeys.STATISTICS_TITLE), 24, true, false, Pos.CENTER);
titleLabel.setTextFill(darkMode ? Constants.BRIGHT_TEXT : Constants.DARK_TEXT);
MacosLabel timeIntervalLabel = createLabel(currentInterval.getUiString(), 20, false, false, Pos.CENTER);
timeIntervalLabel.setTextFill(darkMode ? Constants.BRIGHT_TEXT : Constants.DARK_TEXT);
double columnSize = 140;
Rectangle tooHighRect = createTimeInRangeRectangle(pTooHigh, columnSize, Constants.RED);
Rectangle highRect = createTimeInRangeRectangle(pHigh, columnSize, Constants.YELLOW);
Rectangle normalRect = createTimeInRangeRectangle(pNormal, columnSize, Constants.GREEN);
Rectangle lowRect = createTimeInRangeRectangle(pLow, columnSize, Constants.ORANGE);
Rectangle tooLowRect = createTimeInRangeRectangle(pTooLow, columnSize, Constants.RED);
VBox rectBox = new VBox(1, tooHighRect, highRect, normalRect, lowRect, tooLowRect);
Color textFill = darkMode ? Constants.BRIGHT_TEXT : Constants.DARK_TEXT;
MacosLabel tooHighValue = createTimeInRangeLabel(String.format(Locale.US, "%.0f%% ", pTooHigh * 100), 20, textFill, false, Pos.CENTER_RIGHT);
MacosLabel tooHighValueText = createTimeInRangeLabel(translator.get(I18nKeys.STATISTICS_TOO_HIGH), 20, textFill, false, Pos.CENTER_LEFT);
HBox tooHighText = new HBox(10, tooHighValue, tooHighValueText);
MacosLabel highValue = createTimeInRangeLabel(String.format(Locale.US, "%.0f%% ", pHigh * 100), 20, textFill, false, Pos.CENTER_RIGHT);
MacosLabel highValueText = createTimeInRangeLabel(translator.get(I18nKeys.STATISTICS_HIGH), 20, textFill, false, Pos.CENTER_LEFT);
HBox highText = new HBox(10, highValue, highValueText);
MacosLabel normalValue = createTimeInRangeLabel(String.format(Locale.US, "%.0f%% ", pNormal * 100), 22, textFill, true, Pos.CENTER_RIGHT);
MacosLabel normalValueText = createTimeInRangeLabel(translator.get(I18nKeys.STATISTICS_NORMAL), 22, textFill, true, Pos.CENTER_LEFT);
HBox normalText = new HBox(10, normalValue, normalValueText);
MacosLabel lowValue = createTimeInRangeLabel(String.format(Locale.US, "%.0f%% ", pLow * 100), 20, textFill, false, Pos.CENTER_RIGHT);
MacosLabel lowValueText = createTimeInRangeLabel(translator.get(I18nKeys.STATISTICS_LOW), 20, textFill, false, Pos.CENTER_LEFT);
HBox lowText = new HBox(10, lowValue, lowValueText);
MacosLabel tooLowValue = createTimeInRangeLabel(String.format(Locale.US, "%.0f%% ", pTooLow * 100), 20, textFill, false, Pos.CENTER_RIGHT);
MacosLabel tooLowValueText = createTimeInRangeLabel(translator.get(I18nKeys.STATISTICS_TOO_LOW), 20, textFill, false, Pos.CENTER_LEFT);
HBox tooLowText = new HBox(10, tooLowValue, tooLowValueText);
VBox textBox = new VBox(5, tooHighText, highText, normalText, lowText, tooLowText);
HBox inRangeBox = new HBox(10, rectBox, textBox);
VBox content = new VBox(20, titleLabel, timeIntervalLabel, inRangeBox);
content.setAlignment(Pos.CENTER);
content.setBackground(new Background(new BackgroundFill(Color.TRANSPARENT, new CornerRadii(10), Insets.EMPTY)));
Dialog dialog = new Dialog();
dialog.initOwner(stage);
dialog.setTitle("");
dialog.setHeaderText("");
DialogPane dialogPane = new DialogPane() {
@Override protected Node createButtonBar() {
ButtonBar buttonBar = (ButtonBar) super.createButtonBar();
buttonBar.getStyleClass().add("dialog-button-bar");
buttonBar.setButtonOrder(ButtonBar.BUTTON_ORDER_NONE);
return buttonBar;
}
};
dialogPane.getStylesheets().add(Main.class.getResource("glucostatus.css").toExternalForm());
dialogPane.setBackground(new Background(new BackgroundFill(darkMode ? Constants.DARK_BACKGROUND : Color.WHITE, new CornerRadii(10), Insets.EMPTY)));
dialogPane.setBorder(new Border(new BorderStroke(Color.rgb(78, 77, 76), BorderStrokeStyle.SOLID, new CornerRadii(10), new BorderWidths(1))));
dialogPane.setContent(content);
dialog.setDialogPane(dialogPane);
dialog.getDialogPane().getScene().setFill(Color.TRANSPARENT);
dialog.getDialogPane().setEffect(new DropShadow(BlurType.TWO_PASS_BOX, Color.rgb(0, 0, 0, 0.35), 10.0, 0.0, 0.0, 5));
dialog.setOnCloseRequest(e -> dialogVisible.set(false));
dialog.initStyle(StageStyle.TRANSPARENT);
MacosButton closeButton = new MacosButton(translator.get(I18nKeys.PATTERN_CLOSE_BUTTON));
closeButton.setDark(darkMode);
closeButton.setOnAction(e -> {
dialog.setResult(Boolean.TRUE);
dialog.close();
});
content.getChildren().add(closeButton);
Region spacer = new Region();
ButtonBar.setButtonData(spacer, ButtonBar.ButtonData.BIG_GAP);
HBox.setHgrow(spacer, Priority.ALWAYS);
dialogPane.applyCss();
HBox hbox = (HBox) dialogPane.lookup(".container");
hbox.getChildren().add(spacer);
dialog.setOnShowing(e -> {
dialog.setX(stage.getX() + (stage.getWidth() - dialog.getDialogPane().getLayoutBounds().getWidth()) * 0.425);
dialog.setY(stage.getY() + (stage.getHeight() - dialog.getDialogPane().getLayoutBounds().getHeight()) * 0.425);
});
Stage dialogStage = (Stage) dialogPane.getScene().getWindow();
dialogStage.setAlwaysOnTop(true);
dialogStage.toFront();
dialog.showAndWait();
}
private Rectangle createTimeInRangeRectangle(final double heightFactor, final double columnSize, final Color color) {
Rectangle rect = new Rectangle(50, heightFactor * 100 < 1 ? 1 : heightFactor * columnSize, color);
rect.setStroke(darkMode ? Constants.DARK_BACKGROUND : Constants.BRIGHT_BACKGROUND);
rect.setStrokeWidth(0.1);
return rect;
}
private MacosLabel createTimeInRangeLabel(final String text, final double size, final Paint color, final boolean bold, final Pos alignment) {
MacosLabel label = new MacosLabel(text);
label.setMinWidth(50);
label.setFont(bold ? Fonts.sfProTextBold(size) : Fonts.sfProTextRegular(size));
label.setTextFill(color);
label.setAlignment(alignment);
return label;
}
// ******************** Pattern Chart *************************************
private void showPatternChart() {
if (dialogVisible.get()) { return; }
dialogVisible.set(true);
MacosLabel titleLabel = createLabel(translator.get(I18nKeys.PATTERN_TITLE), 24, true, false, Pos.CENTER);
titleLabel.setTextFill(darkMode ? Constants.BRIGHT_TEXT : Constants.DARK_TEXT);
MacosLabel hbac1Label = createLabel(String.format(Locale.US, "HbAc1 %.1f%% " + translator.get(I18nKeys.HBAC1_RANGE), Helper.getHbA1c(allEntries, currentUnit)), 20, false, false, Pos.CENTER);
hbac1Label.setTextFill(darkMode ? Constants.BRIGHT_TEXT : Constants.DARK_TEXT);
long limit = OffsetDateTime.now().toEpochSecond() - TimeInterval.LAST_168_HOURS.getSeconds();
List<GlucoEntry> entriesLastWeek = allEntries.stream().filter(entry -> entry.datelong() > limit).collect(Collectors.toList());
Map<LocalTime, DataPoint> dataMap = Statistics.analyze(entriesLastWeek);
Pair<List<String>, List<String>> highAndLowZones = Statistics.findTimesWithLowAndHighValues(dataMap, 70, 180);
List<String> lowZones = highAndLowZones.getA();
List<String> highZones = highAndLowZones.getB();
ListView<String> zones = new ListView<>();
zones.setBackground(new Background(new BackgroundFill(Color.TRANSPARENT, CornerRadii.EMPTY, Insets.EMPTY)));
zones.setCellFactory(zoneListView -> new ZoneCell(darkMode));
zones.setPrefHeight(200);
zones.getItems().addAll(lowZones);
zones.getItems().addAll(highZones);
Canvas canvas = new Canvas(640, 300);
GraphicsContext ctx = canvas.getGraphicsContext2D();
double width = canvas.getWidth();
double height = canvas.getHeight();
double availableWidth = (width - GRAPH_INSETS.getLeft() - GRAPH_INSETS.getRight());
double availableHeight = (height - GRAPH_INSETS.getTop() - GRAPH_INSETS.getBottom());
ctx.clearRect(0, 0, width, height);
ctx.setFont(smallTicklabelFont);
ctx.setFill(darkMode ? Constants.BRIGHT_TEXT : Constants.DARK_TEXT);
ctx.setStroke(Color.rgb(81, 80, 78));
ctx.setLineDashes(3, 4);
ctx.setLineWidth(1);
List<String> yAxisLabels = MILLIGRAM_PER_DECILITER == currentUnit ? Constants.yAxisLabelsMgPerDeciliter : Constants.yAxisLabelsMmolPerLiter;
// Draw vertical grid lines
double stepX = availableWidth / 24;
double stepY = availableHeight / (Constants.DEFAULT_GLUCO_RANGE);
// Draw vertical grid lines
ctx.setFill(darkMode ? Constants.BRIGHT_TEXT : Constants.DARK_TEXT);
ctx.setTextAlign(TextAlignment.CENTER);
for (int i = 0 ; i <= 23 ; i++) {
double x = GRAPH_INSETS.getLeft() + i * stepX;
ctx.strokeLine(x, GRAPH_INSETS.getTop(), x, height - GRAPH_INSETS.getBottom());
ctx.fillText(Integer.toString(i), x, height - GRAPH_INSETS.getBottom() * 0.25);
}
// Draw horizontal grid lines
ctx.setTextAlign(TextAlignment.RIGHT);
double yLabelStep = availableHeight / yAxisLabels.size();
for (int i = 0 ; i < yAxisLabels.size() ; i++) {
double y = height - GRAPH_INSETS.getBottom() - i * yLabelStep - yLabelStep;
ctx.strokeLine(GRAPH_INSETS.getLeft(), y, width - GRAPH_INSETS.getRight(), y);
ctx.fillText(yAxisLabels.get(i), GRAPH_INSETS.getLeft() * 2.5, y + 4);
}
double chartStepX = availableWidth / 1440;
ctx.setLineDashes();
ctx.setStroke(darkMode ? Color.rgb(255, 255, 255, 0.5) : Color.rgb(0, 0, 0, 0.5));
ctx.setFill(darkMode ? Color.rgb(255, 255, 255, 0.1) : Color.rgb(0, 0, 0, 0.1));
Pair<List<Point>, List<Point>> pair = Helper.createValueRangePath(dataMap, StatisticRange.TEN_TO_NINETY, true);
List<Point> maxPoints = pair.getA();
List<Point> minPoints = pair.getB();
// Envelope curve upper part
ctx.moveTo(GRAPH_INSETS.getLeft() + maxPoints.get(0).getX() * chartStepX, (height - GRAPH_INSETS.getBottom()) - maxPoints.get(0).getY() * stepY);
maxPoints.forEach(p -> {
double x = GRAPH_INSETS.getLeft() + p.getX() * chartStepX;
double y = (height - GRAPH_INSETS.getBottom()) - p.getY() * stepY;
ctx.lineTo(x, y);
});
ctx.lineTo(GRAPH_INSETS.getLeft() + minPoints.get(0).getX() * chartStepX, (height - GRAPH_INSETS.getBottom()) - minPoints.get(0).getY() * stepY);
// Envelope curve lower part
minPoints.forEach(p -> {
double x = GRAPH_INSETS.getLeft() + p.getX() * chartStepX;
double y = (height - GRAPH_INSETS.getBottom()) - p.getY() * stepY;
ctx.lineTo(x, y);
});
ctx.lineTo(GRAPH_INSETS.getLeft() + maxPoints.get(0).getX() * chartStepX, (height - GRAPH_INSETS.getBottom()) - maxPoints.get(0).getY() * stepY);
ctx.closePath();
ctx.fill();
ctx.stroke();
// Draw line chart
List<Point> avgPoints = Helper.createAveragePath(dataMap, StatisticCalculation.MEDIAN, true);
ctx.setStroke(new LinearGradient(0, GRAPH_INSETS.getTop(), 0, height - GRAPH_INSETS.getBottom(), false, CycleMethod.NO_CYCLE,
new Stop(0.0, Constants.RED),
new Stop(Constants.DEFAULT_MAX_CRITICAL_FACTOR, Constants.RED),
new Stop(maxAcceptableFactor, Constants.ORANGE),
new Stop(maxNormalFactor, Constants.GREEN),
new Stop(minNormalFactor, Constants.GREEN),
new Stop(minAcceptableFactor, Constants.ORANGE),
new Stop(Constants.DEFAULT_MIN_CRITICAL_FACTOR, Constants.RED),
new Stop(1.0, Constants.RED)));
ctx.setLineWidth(2);
ctx.beginPath();
ctx.moveTo(GRAPH_INSETS.getLeft() + avgPoints.get(0).getX() * chartStepX, (height - GRAPH_INSETS.getBottom()) - avgPoints.get(0).getY() * stepY);
avgPoints.forEach(p -> {
double x = GRAPH_INSETS.getLeft() + p.getX() * chartStepX;
double y = (height - GRAPH_INSETS.getBottom()) - p.getY() * stepY;
ctx.lineTo(x, y);
});
ctx.stroke();
VBox content = new VBox(20, titleLabel, hbac1Label, zones, canvas);
content.setAlignment(Pos.CENTER);
content.setBackground(new Background(new BackgroundFill(Color.TRANSPARENT, new CornerRadii(10), Insets.EMPTY)));
Dialog dialog = new Dialog();
dialog.setTitle("");
dialog.setHeaderText("");
DialogPane dialogPane = new DialogPane() {
@Override protected Node createButtonBar() {
ButtonBar buttonBar = (ButtonBar) super.createButtonBar();
buttonBar.getStyleClass().add("dialog-button-bar");
buttonBar.setButtonOrder(ButtonBar.BUTTON_ORDER_NONE);
return buttonBar;
}
};
dialogPane.getStylesheets().add(Main.class.getResource("glucostatus.css").toExternalForm());
dialogPane.setBackground(new Background(new BackgroundFill(darkMode ? Constants.DARK_BACKGROUND : Color.WHITE, new CornerRadii(10), Insets.EMPTY)));
dialogPane.setBorder(new Border(new BorderStroke(Color.rgb(78, 77, 76), BorderStrokeStyle.SOLID, new CornerRadii(10),new BorderWidths(1))));
dialogPane.setContent(content);
dialog.setDialogPane(dialogPane);
dialog.getDialogPane().getScene().setFill(Color.TRANSPARENT);
dialog.getDialogPane().setEffect(new DropShadow(BlurType.TWO_PASS_BOX, Color.rgb(0, 0, 0, 0.35), 10.0, 0.0, 0.0, 5));
MacosButton closeButton = new MacosButton(translator.get(I18nKeys.PATTERN_CLOSE_BUTTON));
closeButton.setDark(darkMode);
closeButton.setOnAction(e -> {
dialog.setResult(Boolean.TRUE);
dialog.close();
});
content.getChildren().add(closeButton);
dialog.setOnCloseRequest(e -> dialogVisible.set(false));
dialog.initStyle(StageStyle.TRANSPARENT);
Region spacer = new Region();
ButtonBar.setButtonData(spacer, ButtonBar.ButtonData.BIG_GAP);
HBox.setHgrow(spacer, Priority.ALWAYS);
dialogPane.applyCss();
HBox hbox = (HBox) dialogPane.lookup(".container");
hbox.getChildren().add(spacer);
dialog.setOnShowing(e -> {
dialog.setX(stage.getX() + (stage.getWidth() - dialog.getDialogPane().getLayoutBounds().getWidth()) * 0.5);
dialog.setY(stage.getY() + (stage.getHeight() - dialog.getDialogPane().getLayoutBounds().getHeight()) * 0.1);
});
Stage dialogStage = (Stage) dialogPane.getScene().getWindow();
dialogStage.setAlwaysOnTop(true);
dialogStage.toFront();
dialog.showAndWait();
}
// ******************** Matrix Chart **************************************
private void showMatrixChart() {
if (dialogVisible.get()) { return; }
dialogVisible.set(true);
MacosLabel titleLabel = createLabel(translator.get(I18nKeys.MATRIX_TITLE), 24, true, false, Pos.CENTER);
titleLabel.setTextFill(darkMode ? Constants.BRIGHT_TEXT : Constants.DARK_TEXT);
MacosLabel subTitleLabel = createLabel(translator.get(I18nKeys.MATRIX_SUBTITLE), 16, false, false, Pos.CENTER);
subTitleLabel.setTextFill(darkMode ? Constants.BRIGHT_TEXT : Constants.DARK_TEXT);
MacosLabel hbac1Label = createLabel(String.format(Locale.US, "HbAc1 %.1f%% " + translator.get(I18nKeys.HBAC1_RANGE), Helper.getHbA1c(allEntries, currentUnit)), 20, false, false, Pos.CENTER);
hbac1Label.setTextFill(darkMode ? Constants.BRIGHT_TEXT : Constants.DARK_TEXT);
ThirtyDayView thirtyDayView = new ThirtyDayView(allEntries, currentUnit);
thirtyDayView.setDark(darkMode);
VBox content = new VBox(20, titleLabel, subTitleLabel, hbac1Label, thirtyDayView);
content.setAlignment(Pos.CENTER);
content.setBackground(new Background(new BackgroundFill(Color.TRANSPARENT, new CornerRadii(10), Insets.EMPTY)));
Dialog dialog = new Dialog();
dialog.setTitle("");
dialog.setHeaderText("");
DialogPane dialogPane = new DialogPane() {
@Override protected Node createButtonBar() {
ButtonBar buttonBar = (ButtonBar) super.createButtonBar();
buttonBar.getStyleClass().add("dialog-button-bar");
buttonBar.setButtonOrder(ButtonBar.BUTTON_ORDER_NONE);
return buttonBar;
}
};
dialogPane.getStylesheets().add(Main.class.getResource("glucostatus.css").toExternalForm());
dialogPane.setBackground(new Background(new BackgroundFill(darkMode ? Constants.DARK_BACKGROUND : Color.WHITE , new CornerRadii(10), Insets.EMPTY)));
dialogPane.setBorder(new Border(new BorderStroke(Color.rgb(78, 77, 76), BorderStrokeStyle.SOLID, new CornerRadii(10),new BorderWidths(1))));
dialogPane.setContent(content);
dialog.setDialogPane(dialogPane);
dialog.getDialogPane().getScene().setFill(Color.TRANSPARENT);
dialog.getDialogPane().setEffect(new DropShadow(BlurType.TWO_PASS_BOX, Color.rgb(0, 0, 0, 0.35), 10.0, 0.0, 0.0, 5));
dialog.setOnCloseRequest(e -> dialogVisible.set(false));
dialog.initStyle(StageStyle.TRANSPARENT);
MacosButton closeButton = new MacosButton(translator.get(I18nKeys.MATRIX_CLOSE_BUTTON));
closeButton.setDark(darkMode);
closeButton.setOnAction(e -> {
dialog.setResult(Boolean.TRUE);
dialog.close();
});
content.getChildren().add(closeButton);
Region spacer = new Region();
ButtonBar.setButtonData(spacer, ButtonBar.ButtonData.BIG_GAP);
HBox.setHgrow(spacer, Priority.ALWAYS);
dialogPane.applyCss();
HBox hbox = (HBox) dialogPane.lookup(".container");
hbox.getChildren().add(spacer);
dialog.setOnShowing(e -> {
dialog.setX(stage.getX() + (stage.getWidth() - dialog.getDialogPane().getLayoutBounds().getWidth()) * 0.5);
dialog.setY(stage.getY() + (stage.getHeight() - dialog.getDialogPane().getLayoutBounds().getHeight()) * 0.1);
});
Stage dialogStage = (Stage) dialogPane.getScene().getWindow();
dialogStage.setAlwaysOnTop(true);
dialogStage.toFront();
dialog.showAndWait();
}
public static void main(String[] args) {
launch(args);
}
}
|
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<Integer> result = new ArrayList<>();
private void preorder(TreeNode root) {
if (root == null)
return;
result.add(root.val);
preorder(root.left);
preorder(root.right);
}
public List<Integer> preorderTraversal(TreeNode root) {
preorder(root);
return result;
}
}
|
package com.mgcp.message.parameter.connectionParameters;
import com.mgcp.exceptions.MGCPParseException;
import com.mgcp.message.parameter.ParameterValue;
import com.noyan.util.NullUtil;
public class ConnectionParametersParameterValue extends ParameterValue {
private static final String finalShortname = "P";
public ConnectionParametersParameterValue() {
this(null);
}
public ConnectionParametersParameterValue(ConnectionParameters connectionParameters) {
super(connectionParameters);
this.shortname = finalShortname;
}
@Override
public ConnectionParameters getValue() {
return (ConnectionParameters) super.getValue();
}
@Override
public ConnectionParametersParameterValue parse(String text) throws MGCPParseException {
text = getValue(text);
return new ConnectionParametersParameterValue(ConnectionParameters.parse(text));
}
@Override
public boolean isMapped(String text) throws MGCPParseException {
if (NullUtil.isNull(text)) {
throw new MGCPParseException("text can not be null");
}
text = text.trim();
if (!text.startsWith(finalShortname)) {
return false;
}
text = text.substring(finalShortname.length()).trim();
if (!text.startsWith(":")) {
return false;
}
return true;
}
}
|
/*
* 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.dubbo.metadata.report.identifier;
import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR;
import static org.apache.dubbo.common.utils.PathUtils.buildPath;
import static org.apache.dubbo.metadata.MetadataConstants.DEFAULT_PATH_TAG;
import static org.apache.dubbo.metadata.MetadataConstants.KEY_SEPARATOR;
/**
* The Base class of MetadataIdentifier for service scope
* <p>
* 2019-08-09
*/
public class BaseApplicationMetadataIdentifier {
String application;
String getUniqueKey(KeyTypeEnum keyType, String... params) {
if (keyType == KeyTypeEnum.PATH) {
return getFilePathKey(params);
}
return getIdentifierKey(params);
}
String getIdentifierKey(String... params) {
return application + joinParams(KEY_SEPARATOR, params);
}
private String joinParams(String joinChar, String... params) {
if (params == null || params.length == 0) {
return "";
}
StringBuilder sb = new StringBuilder();
for (String param : params) {
sb.append(joinChar);
sb.append(param);
}
return sb.toString();
}
private String getFilePathKey(String... params) {
return getFilePathKey(DEFAULT_PATH_TAG, params);
}
private String getFilePathKey(String pathTag, String... params) {
return buildPath(pathTag, application, joinParams(PATH_SEPARATOR, params));
}
}
|
package org.dataone.cn.data.repository;
import org.dataone.cn.model.repository.H2RepositoryConfiguration;
import org.dataone.service.cn.replication.ReplicationRepositoryFactory;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@Configuration
@EnableJpaRepositories("org.dataone.cn.data.repository")
@ComponentScan("org.dataone.cn.data.repository")
public class ReplicationH2RepositoryFactory extends H2RepositoryConfiguration implements
ReplicationRepositoryFactory {
public ReplicationAttemptHistoryRepository getReplicationTryHistoryRepository() {
initContext();
return context.getBean(ReplicationAttemptHistoryRepository.class);
}
public ReplicationTaskRepository getReplicationTaskRepository() {
initContext();
return context.getBean(ReplicationTaskRepository.class);
}
@Override
public String getPackagesToScan() {
return "org.dataone.cn.data.repository";
}
}
|
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/automl/v1beta1/service.proto
package com.google.cloud.automl.v1beta1;
public interface UpdateDatasetRequestOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.automl.v1beta1.UpdateDatasetRequest)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* The dataset which replaces the resource on the server.
* </pre>
*
* <code>.google.cloud.automl.v1beta1.Dataset dataset = 1;</code>
*
* @return Whether the dataset field is set.
*/
boolean hasDataset();
/**
*
*
* <pre>
* The dataset which replaces the resource on the server.
* </pre>
*
* <code>.google.cloud.automl.v1beta1.Dataset dataset = 1;</code>
*
* @return The dataset.
*/
com.google.cloud.automl.v1beta1.Dataset getDataset();
/**
*
*
* <pre>
* The dataset which replaces the resource on the server.
* </pre>
*
* <code>.google.cloud.automl.v1beta1.Dataset dataset = 1;</code>
*/
com.google.cloud.automl.v1beta1.DatasetOrBuilder getDatasetOrBuilder();
/**
*
*
* <pre>
* The update mask applies to the resource.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return Whether the updateMask field is set.
*/
boolean hasUpdateMask();
/**
*
*
* <pre>
* The update mask applies to the resource.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return The updateMask.
*/
com.google.protobuf.FieldMask getUpdateMask();
/**
*
*
* <pre>
* The update mask applies to the resource.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder();
}
|
/**
* 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.iotdb.db.engine.overflow.metadata;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.iotdb.tsfile.utils.ReadWriteIOUtils;
/**
* Metadata of overflow RowGroup list.
*/
public class OFRowGroupListMetadata {
private String deviceId;
private List<OFSeriesListMetadata> seriesList;
private OFRowGroupListMetadata() {
}
public OFRowGroupListMetadata(String deviceId) {
this.deviceId = deviceId;
seriesList = new ArrayList<>();
}
/**
* function for deserializing data from input stream.
*/
public static OFRowGroupListMetadata deserializeFrom(InputStream inputStream) throws IOException {
OFRowGroupListMetadata ofRowGroupListMetadata = new OFRowGroupListMetadata();
ofRowGroupListMetadata.deviceId = ReadWriteIOUtils.readString(inputStream);
int size = ReadWriteIOUtils.readInt(inputStream);
List<OFSeriesListMetadata> list = new ArrayList<>();
for (int i = 0; i < size; i++) {
list.add(OFSeriesListMetadata.deserializeFrom(inputStream));
}
ofRowGroupListMetadata.seriesList = list;
return ofRowGroupListMetadata;
}
public static OFRowGroupListMetadata deserializeFrom(ByteBuffer buffer) throws IOException {
throw new IOException("The function has not been implemented.");
}
/**
* add OFSeriesListMetadata metadata to list.
*/
public void addSeriesListMetaData(OFSeriesListMetadata timeSeries) {
if (seriesList == null) {
seriesList = new ArrayList<OFSeriesListMetadata>();
}
seriesList.add(timeSeries);
}
public List<OFSeriesListMetadata> getSeriesList() {
return seriesList == null ? null : Collections.unmodifiableList(seriesList);
}
@Override
public String toString() {
return String.format("OFRowGroupListMetadata{ deviceId id: %s, series Lists: %s }", deviceId,
seriesList.toString());
}
public String getdeviceId() {
return deviceId;
}
/**
* function for serialing data to output stream.
*/
public int serializeTo(OutputStream outputStream) throws IOException {
int byteLen = 0;
byteLen += ReadWriteIOUtils.write(deviceId, outputStream);
int size = seriesList.size();
byteLen += ReadWriteIOUtils.write(size, outputStream);
for (OFSeriesListMetadata ofSeriesListMetadata : seriesList) {
byteLen += ofSeriesListMetadata.serializeTo(outputStream);
}
return byteLen;
}
/**
* function for serializing data to byte buffer.
*/
public int serializeTo(ByteBuffer buffer) throws IOException {
throw new IOException("The function has not been implemented.");
}
}
|
/*
* 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.
*
* 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.
*/
public interface RuntimeConstants {
/* Signature Characters */
char SIGC_VOID = 'V';
String SIG_VOID = "V";
char SIGC_BOOLEAN = 'Z';
String SIG_BOOLEAN = "Z";
char SIGC_BYTE = 'B';
String SIG_BYTE = "B";
char SIGC_CHAR = 'C';
String SIG_CHAR = "C";
char SIGC_SHORT = 'S';
String SIG_SHORT = "S";
char SIGC_INT = 'I';
String SIG_INT = "I";
char SIGC_LONG = 'J';
String SIG_LONG = "J";
char SIGC_FLOAT = 'F';
String SIG_FLOAT = "F";
char SIGC_DOUBLE = 'D';
String SIG_DOUBLE = "D";
char SIGC_ARRAY = '[';
String SIG_ARRAY = "[";
char SIGC_CLASS = 'L';
String SIG_CLASS = "L";
char SIGC_METHOD = '(';
String SIG_METHOD = "(";
char SIGC_ENDCLASS = ';';
String SIG_ENDCLASS = ";";
char SIGC_ENDMETHOD = ')';
String SIG_ENDMETHOD = ")";
char SIGC_PACKAGE = '/';
String SIG_PACKAGE = "/";
/* Class File Constants */
int JAVA_MAGIC = 0xcafebabe;
int JAVA_MIN_SUPPORTED_VERSION = 45;
int JAVA_MAX_SUPPORTED_VERSION = 48;
int JAVA_MAX_SUPPORTED_MINOR_VERSION = 0;
/* Generate class file version for 1.1 by default */
int JAVA_DEFAULT_VERSION = 45;
int JAVA_DEFAULT_MINOR_VERSION = 3;
/* Constant table */
int CONSTANT_UTF8 = 1;
int CONSTANT_UNICODE = 2;
int CONSTANT_INTEGER = 3;
int CONSTANT_FLOAT = 4;
int CONSTANT_LONG = 5;
int CONSTANT_DOUBLE = 6;
int CONSTANT_CLASS = 7;
int CONSTANT_STRING = 8;
int CONSTANT_FIELD = 9;
int CONSTANT_METHOD = 10;
int CONSTANT_INTERFACEMETHOD = 11;
int CONSTANT_NAMEANDTYPE = 12;
/* Access and modifier flags */
int ACC_PUBLIC = 0x00000001;
int ACC_PRIVATE = 0x00000002;
int ACC_PROTECTED = 0x00000004;
int ACC_STATIC = 0x00000008;
int ACC_FINAL = 0x00000010;
int ACC_SYNCHRONIZED = 0x00000020;
int ACC_VOLATILE = 0x00000040;
int ACC_TRANSIENT = 0x00000080;
int ACC_NATIVE = 0x00000100;
int ACC_INTERFACE = 0x00000200;
int ACC_ABSTRACT = 0x00000400;
int ACC_SUPER = 0x00000020;
int ACC_STRICT = 0x00000800;
/* Type codes */
int T_CLASS = 0x00000002;
int T_BOOLEAN = 0x00000004;
int T_CHAR = 0x00000005;
int T_FLOAT = 0x00000006;
int T_DOUBLE = 0x00000007;
int T_BYTE = 0x00000008;
int T_SHORT = 0x00000009;
int T_INT = 0x0000000a;
int T_LONG = 0x0000000b;
/* Opcodes */
int opc_try = -3;
int opc_dead = -2;
int opc_label = -1;
int opc_nop = 0;
int opc_aconst_null = 1;
int opc_iconst_m1 = 2;
int opc_iconst_0 = 3;
int opc_iconst_1 = 4;
int opc_iconst_2 = 5;
int opc_iconst_3 = 6;
int opc_iconst_4 = 7;
int opc_iconst_5 = 8;
int opc_lconst_0 = 9;
int opc_lconst_1 = 10;
int opc_fconst_0 = 11;
int opc_fconst_1 = 12;
int opc_fconst_2 = 13;
int opc_dconst_0 = 14;
int opc_dconst_1 = 15;
int opc_bipush = 16;
int opc_sipush = 17;
int opc_ldc = 18;
int opc_ldc_w = 19;
int opc_ldc2_w = 20;
int opc_iload = 21;
int opc_lload = 22;
int opc_fload = 23;
int opc_dload = 24;
int opc_aload = 25;
int opc_iload_0 = 26;
int opc_iload_1 = 27;
int opc_iload_2 = 28;
int opc_iload_3 = 29;
int opc_lload_0 = 30;
int opc_lload_1 = 31;
int opc_lload_2 = 32;
int opc_lload_3 = 33;
int opc_fload_0 = 34;
int opc_fload_1 = 35;
int opc_fload_2 = 36;
int opc_fload_3 = 37;
int opc_dload_0 = 38;
int opc_dload_1 = 39;
int opc_dload_2 = 40;
int opc_dload_3 = 41;
int opc_aload_0 = 42;
int opc_aload_1 = 43;
int opc_aload_2 = 44;
int opc_aload_3 = 45;
int opc_iaload = 46;
int opc_laload = 47;
int opc_faload = 48;
int opc_daload = 49;
int opc_aaload = 50;
int opc_baload = 51;
int opc_caload = 52;
int opc_saload = 53;
int opc_istore = 54;
int opc_lstore = 55;
int opc_fstore = 56;
int opc_dstore = 57;
int opc_astore = 58;
int opc_istore_0 = 59;
int opc_istore_1 = 60;
int opc_istore_2 = 61;
int opc_istore_3 = 62;
int opc_lstore_0 = 63;
int opc_lstore_1 = 64;
int opc_lstore_2 = 65;
int opc_lstore_3 = 66;
int opc_fstore_0 = 67;
int opc_fstore_1 = 68;
int opc_fstore_2 = 69;
int opc_fstore_3 = 70;
int opc_dstore_0 = 71;
int opc_dstore_1 = 72;
int opc_dstore_2 = 73;
int opc_dstore_3 = 74;
int opc_astore_0 = 75;
int opc_astore_1 = 76;
int opc_astore_2 = 77;
int opc_astore_3 = 78;
int opc_iastore = 79;
int opc_lastore = 80;
int opc_fastore = 81;
int opc_dastore = 82;
int opc_aastore = 83;
int opc_bastore = 84;
int opc_castore = 85;
int opc_sastore = 86;
int opc_pop = 87;
int opc_pop2 = 88;
int opc_dup = 89;
int opc_dup_x1 = 90;
int opc_dup_x2 = 91;
int opc_dup2 = 92;
int opc_dup2_x1 = 93;
int opc_dup2_x2 = 94;
int opc_swap = 95;
int opc_iadd = 96;
int opc_ladd = 97;
int opc_fadd = 98;
int opc_dadd = 99;
int opc_isub = 100;
int opc_lsub = 101;
int opc_fsub = 102;
int opc_dsub = 103;
int opc_imul = 104;
int opc_lmul = 105;
int opc_fmul = 106;
int opc_dmul = 107;
int opc_idiv = 108;
int opc_ldiv = 109;
int opc_fdiv = 110;
int opc_ddiv = 111;
int opc_irem = 112;
int opc_lrem = 113;
int opc_frem = 114;
int opc_drem = 115;
int opc_ineg = 116;
int opc_lneg = 117;
int opc_fneg = 118;
int opc_dneg = 119;
int opc_ishl = 120;
int opc_lshl = 121;
int opc_ishr = 122;
int opc_lshr = 123;
int opc_iushr = 124;
int opc_lushr = 125;
int opc_iand = 126;
int opc_land = 127;
int opc_ior = 128;
int opc_lor = 129;
int opc_ixor = 130;
int opc_lxor = 131;
int opc_iinc = 132;
int opc_i2l = 133;
int opc_i2f = 134;
int opc_i2d = 135;
int opc_l2i = 136;
int opc_l2f = 137;
int opc_l2d = 138;
int opc_f2i = 139;
int opc_f2l = 140;
int opc_f2d = 141;
int opc_d2i = 142;
int opc_d2l = 143;
int opc_d2f = 144;
int opc_i2b = 145;
int opc_i2c = 146;
int opc_i2s = 147;
int opc_lcmp = 148;
int opc_fcmpl = 149;
int opc_fcmpg = 150;
int opc_dcmpl = 151;
int opc_dcmpg = 152;
int opc_ifeq = 153;
int opc_ifne = 154;
int opc_iflt = 155;
int opc_ifge = 156;
int opc_ifgt = 157;
int opc_ifle = 158;
int opc_if_icmpeq = 159;
int opc_if_icmpne = 160;
int opc_if_icmplt = 161;
int opc_if_icmpge = 162;
int opc_if_icmpgt = 163;
int opc_if_icmple = 164;
int opc_if_acmpeq = 165;
int opc_if_acmpne = 166;
int opc_goto = 167;
int opc_jsr = 168;
int opc_ret = 169;
int opc_tableswitch = 170;
int opc_lookupswitch = 171;
int opc_ireturn = 172;
int opc_lreturn = 173;
int opc_freturn = 174;
int opc_dreturn = 175;
int opc_areturn = 176;
int opc_return = 177;
int opc_getstatic = 178;
int opc_putstatic = 179;
int opc_getfield = 180;
int opc_putfield = 181;
int opc_invokevirtual = 182;
int opc_invokespecial = 183;
int opc_invokestatic = 184;
int opc_invokeinterface = 185;
int opc_xxxunusedxxx = 186;
int opc_new = 187;
int opc_newarray = 188;
int opc_anewarray = 189;
int opc_arraylength = 190;
int opc_athrow = 191;
int opc_checkcast = 192;
int opc_instanceof = 193;
int opc_monitorenter = 194;
int opc_monitorexit = 195;
int opc_wide = 196;
int opc_multianewarray = 197;
int opc_ifnull = 198;
int opc_ifnonnull = 199;
int opc_goto_w = 200;
int opc_jsr_w = 201;
int opc_breakpoint = 202;
/* Opcode Names */
String opcNames[] = {
"nop",
"aconst_null",
"iconst_m1",
"iconst_0",
"iconst_1",
"iconst_2",
"iconst_3",
"iconst_4",
"iconst_5",
"lconst_0",
"lconst_1",
"fconst_0",
"fconst_1",
"fconst_2",
"dconst_0",
"dconst_1",
"bipush",
"sipush",
"ldc",
"ldc_w",
"ldc2_w",
"iload",
"lload",
"fload",
"dload",
"aload",
"iload_0",
"iload_1",
"iload_2",
"iload_3",
"lload_0",
"lload_1",
"lload_2",
"lload_3",
"fload_0",
"fload_1",
"fload_2",
"fload_3",
"dload_0",
"dload_1",
"dload_2",
"dload_3",
"aload_0",
"aload_1",
"aload_2",
"aload_3",
"iaload",
"laload",
"faload",
"daload",
"aaload",
"baload",
"caload",
"saload",
"istore",
"lstore",
"fstore",
"dstore",
"astore",
"istore_0",
"istore_1",
"istore_2",
"istore_3",
"lstore_0",
"lstore_1",
"lstore_2",
"lstore_3",
"fstore_0",
"fstore_1",
"fstore_2",
"fstore_3",
"dstore_0",
"dstore_1",
"dstore_2",
"dstore_3",
"astore_0",
"astore_1",
"astore_2",
"astore_3",
"iastore",
"lastore",
"fastore",
"dastore",
"aastore",
"bastore",
"castore",
"sastore",
"pop",
"pop2",
"dup",
"dup_x1",
"dup_x2",
"dup2",
"dup2_x1",
"dup2_x2",
"swap",
"iadd",
"ladd",
"fadd",
"dadd",
"isub",
"lsub",
"fsub",
"dsub",
"imul",
"lmul",
"fmul",
"dmul",
"idiv",
"ldiv",
"fdiv",
"ddiv",
"irem",
"lrem",
"frem",
"drem",
"ineg",
"lneg",
"fneg",
"dneg",
"ishl",
"lshl",
"ishr",
"lshr",
"iushr",
"lushr",
"iand",
"land",
"ior",
"lor",
"ixor",
"lxor",
"iinc",
"i2l",
"i2f",
"i2d",
"l2i",
"l2f",
"l2d",
"f2i",
"f2l",
"f2d",
"d2i",
"d2l",
"d2f",
"i2b",
"i2c",
"i2s",
"lcmp",
"fcmpl",
"fcmpg",
"dcmpl",
"dcmpg",
"ifeq",
"ifne",
"iflt",
"ifge",
"ifgt",
"ifle",
"if_icmpeq",
"if_icmpne",
"if_icmplt",
"if_icmpge",
"if_icmpgt",
"if_icmple",
"if_acmpeq",
"if_acmpne",
"goto",
"jsr",
"ret",
"tableswitch",
"lookupswitch",
"ireturn",
"lreturn",
"freturn",
"dreturn",
"areturn",
"return",
"getstatic",
"putstatic",
"getfield",
"putfield",
"invokevirtual",
"invokespecial",
"invokestatic",
"invokeinterface",
"xxxunusedxxx",
"new",
"newarray",
"anewarray",
"arraylength",
"athrow",
"checkcast",
"instanceof",
"monitorenter",
"monitorexit",
"wide",
"multianewarray",
"ifnull",
"ifnonnull",
"goto_w",
"jsr_w",
"breakpoint"
};
/* Opcode Lengths */
int opcLengths[] = {
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
2,
3,
2,
3,
3,
2,
2,
2,
2,
2,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
2,
2,
2,
2,
2,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
3,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
3,
3,
3,
3,
3,
3,
3,
3,
3,
3,
3,
3,
3,
3,
3,
3,
2,
99,
99,
1,
1,
1,
1,
1,
1,
3,
3,
3,
3,
3,
3,
3,
5,
0,
3,
2,
3,
1,
1,
3,
3,
1,
1,
0,
4,
3,
3,
5,
5,
1
};
}
|
package com.brandonhogan.kotlintest.commons;
import android.content.Context;
import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.module.GlideModule;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
/**
* Created by Brandon on 2/9/2017.
* Description :
*/
//public class MyGlideModule implements GlideModule {
// @Override
// public void applyOptions(Context context, GlideBuilder builder) {
// // Do nothing.
// }
//
// @Override
// public void registerComponents(Context context, Glide glide) {
// final OkHttpClient.Builder builder = new OkHttpClient.Builder();
//
// // set your timeout here
// builder.readTimeout(60, TimeUnit.SECONDS);
// builder.writeTimeout(60, TimeUnit.SECONDS);
// builder.connectTimeout(60, TimeUnit.SECONDS);
//
// glide.register(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(builder.build()));
// }
//}
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.server;
import io.airlift.http.client.HttpClient;
import io.airlift.http.client.Request;
import io.airlift.http.client.UnexpectedResponseException;
import io.airlift.http.client.jetty.JettyHttpClient;
import io.airlift.json.JsonCodec;
import io.prestosql.client.QueryResults;
import io.prestosql.plugin.tpch.TpchPlugin;
import io.prestosql.server.testing.TestingPrestoServer;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.util.List;
import static io.airlift.http.client.HttpUriBuilder.uriBuilderFrom;
import static io.airlift.http.client.JsonResponseHandler.createJsonResponseHandler;
import static io.airlift.http.client.Request.Builder.prepareGet;
import static io.airlift.http.client.Request.Builder.preparePost;
import static io.airlift.http.client.StaticBodyGenerator.createStaticBodyGenerator;
import static io.airlift.json.JsonCodec.jsonCodec;
import static io.airlift.json.JsonCodec.listJsonCodec;
import static io.airlift.testing.Closeables.closeQuietly;
import static io.prestosql.client.PrestoHeaders.PRESTO_USER;
import static io.prestosql.execution.QueryState.RUNNING;
import static io.prestosql.testing.TestingAccessControlManager.TestingPrivilegeType.VIEW_QUERY;
import static io.prestosql.testing.TestingAccessControlManager.privilege;
import static io.prestosql.testing.assertions.Assert.assertEquals;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
@Test(singleThreaded = true)
public class TestQueryStateInfoResource
{
private static final String LONG_LASTING_QUERY = "SELECT * FROM tpch.sf1.lineitem";
private static final JsonCodec<QueryResults> QUERY_RESULTS_JSON_CODEC = jsonCodec(QueryResults.class);
private TestingPrestoServer server;
private HttpClient client;
private QueryResults queryResults;
@BeforeClass
public void setUp()
{
server = TestingPrestoServer.create();
server.installPlugin(new TpchPlugin());
server.createCatalog("tpch", "tpch");
client = new JettyHttpClient();
Request request1 = preparePost()
.setUri(uriBuilderFrom(server.getBaseUrl()).replacePath("/v1/statement").build())
.setBodyGenerator(createStaticBodyGenerator(LONG_LASTING_QUERY, UTF_8))
.setHeader(PRESTO_USER, "user1")
.build();
queryResults = client.execute(request1, createJsonResponseHandler(QUERY_RESULTS_JSON_CODEC));
client.execute(prepareGet().setUri(queryResults.getNextUri()).build(), createJsonResponseHandler(QUERY_RESULTS_JSON_CODEC));
Request request2 = preparePost()
.setUri(uriBuilderFrom(server.getBaseUrl()).replacePath("/v1/statement").build())
.setBodyGenerator(createStaticBodyGenerator(LONG_LASTING_QUERY, UTF_8))
.setHeader(PRESTO_USER, "user2")
.build();
QueryResults queryResults2 = client.execute(request2, createJsonResponseHandler(jsonCodec(QueryResults.class)));
client.execute(prepareGet().setUri(queryResults2.getNextUri()).build(), createJsonResponseHandler(QUERY_RESULTS_JSON_CODEC));
// queries are started in the background, so they may not all be immediately visible
while (true) {
List<BasicQueryInfo> queryInfos = client.execute(
prepareGet()
.setUri(uriBuilderFrom(server.getBaseUrl()).replacePath("/v1/query").build())
.setHeader(PRESTO_USER, "unknown")
.build(),
createJsonResponseHandler(listJsonCodec(BasicQueryInfo.class)));
if ((queryInfos.size() == 2) && queryInfos.stream().allMatch(info -> info.getState() == RUNNING)) {
break;
}
}
}
@AfterClass(alwaysRun = true)
public void tearDown()
{
closeQuietly(server, client);
}
@Test
public void testGetAllQueryStateInfos()
{
List<QueryStateInfo> infos = client.execute(
prepareGet()
.setUri(server.resolve("/v1/queryState"))
.setHeader(PRESTO_USER, "unknown")
.build(),
createJsonResponseHandler(listJsonCodec(QueryStateInfo.class)));
assertEquals(infos.size(), 2);
}
@Test
public void testGetQueryStateInfosForUser()
{
List<QueryStateInfo> infos = client.execute(
prepareGet()
.setUri(server.resolve("/v1/queryState?user=user2"))
.setHeader(PRESTO_USER, "unknown")
.build(),
createJsonResponseHandler(listJsonCodec(QueryStateInfo.class)));
assertEquals(infos.size(), 1);
}
@Test
public void testGetQueryStateInfosForUserNoResult()
{
List<QueryStateInfo> infos = client.execute(
prepareGet()
.setUri(server.resolve("/v1/queryState?user=user3"))
.setHeader(PRESTO_USER, "unknown")
.build(),
createJsonResponseHandler(listJsonCodec(QueryStateInfo.class)));
assertTrue(infos.isEmpty());
}
@Test
public void testGetQueryStateInfo()
{
QueryStateInfo info = client.execute(
prepareGet()
.setUri(server.resolve("/v1/queryState/" + queryResults.getId()))
.setHeader(PRESTO_USER, "unknown")
.build(),
createJsonResponseHandler(jsonCodec(QueryStateInfo.class)));
assertNotNull(info);
}
@Test
public void testGetAllQueryStateInfosDenied()
{
List<QueryStateInfo> infos = client.execute(
prepareGet()
.setUri(server.resolve("/v1/queryState"))
.setHeader(PRESTO_USER, "any-other-user")
.build(),
createJsonResponseHandler(listJsonCodec(QueryStateInfo.class)));
assertEquals(infos.size(), 2);
testGetAllQueryStateInfosDenied("user1", 1);
testGetAllQueryStateInfosDenied("any-other-user", 0);
}
private void testGetAllQueryStateInfosDenied(String executionUser, int expectedCount)
{
server.getAccessControl().deny(privilege(executionUser, "query", VIEW_QUERY));
try {
List<QueryStateInfo> infos = client.execute(
prepareGet()
.setUri(server.resolve("/v1/queryState"))
.setHeader(PRESTO_USER, executionUser)
.build(),
createJsonResponseHandler(listJsonCodec(QueryStateInfo.class)));
assertEquals(infos.size(), expectedCount);
}
finally {
server.getAccessControl().reset();
}
}
@Test
public void testGetQueryStateInfoDenied()
{
server.getAccessControl().deny(privilege("query", VIEW_QUERY));
try {
assertThatThrownBy(() -> client.execute(
prepareGet()
.setUri(server.resolve("/v1/queryState/" + queryResults.getId()))
.setHeader(PRESTO_USER, "unknown")
.build(),
createJsonResponseHandler(jsonCodec(QueryStateInfo.class))))
.isInstanceOf(UnexpectedResponseException.class)
.matches(throwable -> ((UnexpectedResponseException) throwable).getStatusCode() == 403);
}
finally {
server.getAccessControl().reset();
}
}
@Test(expectedExceptions = UnexpectedResponseException.class, expectedExceptionsMessageRegExp = "Expected response code .*, but was 404")
public void testGetQueryStateInfoNo()
{
client.execute(
prepareGet().setUri(server.resolve("/v1/queryState/123")).build(),
createJsonResponseHandler(jsonCodec(QueryStateInfo.class)));
}
}
|
/*
* Copyright (c) 2015, 2018, 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 java.net.http;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
/**
* A WebSocket Client.
*
* <p> {@code WebSocket} instances are created through {@link Builder}.
*
* <p> WebSocket has an input and an output side. These sides are independent
* from each other. A side can either be open or closed. Once closed, the side
* remains closed. WebSocket messages are sent through a {@code WebSocket} and
* received through a {@code WebSocket.Listener} associated with it. Messages
* can be sent until the WebSocket's output is closed, and received until the
* WebSocket's input is closed.
*
* <p> A send method is any of the {@code sendText}, {@code sendBinary},
* {@code sendPing}, {@code sendPong} and {@code sendClose} methods of
* {@code WebSocket}. A send method initiates a send operation and returns a
* {@code CompletableFuture} which completes once the operation has completed.
* If the {@code CompletableFuture} completes normally the operation is
* considered succeeded. If the {@code CompletableFuture} completes
* exceptionally, the operation is considered failed. An operation that has been
* initiated but not yet completed is considered pending.
*
* <p> A receive method is any of the {@code onText}, {@code onBinary},
* {@code onPing}, {@code onPong} and {@code onClose} methods of
* {@code Listener}. WebSocket initiates a receive operation by invoking a
* receive method on the listener. The listener then must return a
* {@code CompletionStage} which completes once the operation has completed.
*
* <p> To control receiving of messages, a WebSocket maintains an
* <a id="counter">internal counter</a>. This counter's value is a number of
* times the WebSocket has yet to invoke a receive method. While this counter is
* zero the WebSocket does not invoke receive methods. The counter is
* incremented by {@code n} when {@code request(n)} is called. The counter is
* decremented by one when the WebSocket invokes a receive method.
* {@code onOpen} and {@code onError} are not receive methods. WebSocket invokes
* {@code onOpen} prior to any other methods on the listener. WebSocket invokes
* {@code onOpen} at most once. WebSocket may invoke {@code onError} at any
* given time. If the WebSocket invokes {@code onError} or {@code onClose}, then
* no further listener's methods will be invoked, no matter the value of the
* counter. For a newly built WebSocket the counter is zero.
*
* <p> Unless otherwise stated, {@code null} arguments will cause methods
* of {@code WebSocket} to throw {@code NullPointerException}, similarly,
* {@code WebSocket} will not pass {@code null} arguments to methods of
* {@code Listener}. The state of a WebSocket is not changed by the invocations
* that throw or return a {@code CompletableFuture} that completes with one of
* the {@code NullPointerException}, {@code IllegalArgumentException},
* {@code IllegalStateException} exceptions.
*
* <p> {@code WebSocket} handles received Ping and Close messages automatically
* (as per the WebSocket Protocol) by replying with Pong and Close messages. If
* the listener receives Ping or Close messages, no mandatory actions from the
* listener are required.
*
* @apiNote The relationship between a WebSocket and the associated Listener is
* analogous to that of a Subscription and the associated Subscriber of type
* {@link java.util.concurrent.Flow}.
*
* @since 11
*/
public interface WebSocket {
/**
* The WebSocket Close message status code (<code>{@value}</code>),
* indicating normal closure, meaning that the purpose for which the
* connection was established has been fulfilled.
*
* @see #sendClose(int, String)
* @see Listener#onClose(WebSocket, int, String)
*/
int NORMAL_CLOSURE = 1000;
/**
* A builder of {@linkplain WebSocket WebSocket Clients}.
*
* <p> Builders are created by invoking
* {@link HttpClient#newWebSocketBuilder HttpClient.newWebSocketBuilder}.
* The intermediate (setter-like) methods change the state of the builder
* and return the same builder they have been invoked on. If an intermediate
* method is not invoked, an appropriate default value (or behavior) will be
* assumed. A {@code Builder} is not safe for use by multiple threads
* without external synchronization.
*
* @since 11
*/
interface Builder {
/**
* Adds the given name-value pair to the list of additional HTTP headers
* sent during the opening handshake.
*
* <p> Headers defined in the
* <a href="https://tools.ietf.org/html/rfc6455#section-11.3">WebSocket
* Protocol</a> are illegal. If this method is not invoked, no
* additional HTTP headers will be sent.
*
* @param name
* the header name
* @param value
* the header value
*
* @return this builder
*/
Builder header(String name, String value);
/**
* Sets a timeout for establishing a WebSocket connection.
*
* <p> If the connection is not established within the specified
* duration then building of the {@code WebSocket} will fail with
* {@link HttpTimeoutException}. If this method is not invoked then the
* infinite timeout is assumed.
*
* @param timeout
* the timeout, non-{@linkplain Duration#isNegative() negative},
* non-{@linkplain Duration#ZERO ZERO}
*
* @return this builder
*/
Builder connectTimeout(Duration timeout);
/**
* Sets a request for the given subprotocols.
*
* <p> After the {@code WebSocket} has been built, the actual
* subprotocol can be queried through
* {@link WebSocket#getSubprotocol WebSocket.getSubprotocol()}.
*
* <p> Subprotocols are specified in the order of preference. The most
* preferred subprotocol is specified first. If there are any additional
* subprotocols they are enumerated from the most preferred to the least
* preferred.
*
* <p> Subprotocols not conforming to the syntax of subprotocol
* identifiers are illegal. If this method is not invoked then no
* subprotocols will be requested.
*
* @param mostPreferred
* the most preferred subprotocol
* @param lesserPreferred
* the lesser preferred subprotocols
*
* @return this builder
*/
Builder subprotocols(String mostPreferred, String... lesserPreferred);
/**
* Builds a {@link WebSocket} connected to the given {@code URI} and
* associated with the given {@code Listener}.
*
* <p> Returns a {@code CompletableFuture} which will either complete
* normally with the resulting {@code WebSocket} or complete
* exceptionally with one of the following errors:
* <ul>
* <li> {@link IOException} -
* if an I/O error occurs
* <li> {@link WebSocketHandshakeException} -
* if the opening handshake fails
* <li> {@link HttpTimeoutException} -
* if the opening handshake does not complete within
* the timeout
* <li> {@link InterruptedException} -
* if the operation is interrupted
* <li> {@link SecurityException} -
* if a security manager has been installed and it denies
* {@link java.net.URLPermission access} to {@code uri}.
* <a href="HttpClient.html#securitychecks">Security checks</a>
* contains more information relating to the security context
* in which the listener is invoked.
* <li> {@link IllegalArgumentException} -
* if any of the arguments of this builder's methods are
* illegal
* </ul>
*
* @param uri
* the WebSocket URI
* @param listener
* the listener
*
* @return a {@code CompletableFuture} with the {@code WebSocket}
*/
CompletableFuture<WebSocket> buildAsync(URI uri, Listener listener);
}
/**
* The receiving interface of {@code WebSocket}.
*
* <p> A {@code WebSocket} invokes methods of the associated listener
* passing itself as an argument. These methods are invoked in a thread-safe
* manner, such that the next invocation may start only after the previous
* one has finished.
*
* <p> When data has been received, the {@code WebSocket} invokes a receive
* method. Methods {@code onText}, {@code onBinary}, {@code onPing} and
* {@code onPong} must return a {@code CompletionStage} that completes once
* the message has been received by the listener. If a listener's method
* returns {@code null} rather than a {@code CompletionStage},
* {@code WebSocket} will behave as if the listener returned a
* {@code CompletionStage} that is already completed normally.
*
* <p> An {@code IOException} raised in {@code WebSocket} will result in an
* invocation of {@code onError} with that exception (if the input is not
* closed). Unless otherwise stated if the listener's method throws an
* exception or a {@code CompletionStage} returned from a method completes
* exceptionally, the WebSocket will invoke {@code onError} with this
* exception.
*
* @apiNote The strict sequential order of invocations from
* {@code WebSocket} to {@code Listener} means, in particular, that the
* {@code Listener}'s methods are treated as non-reentrant. This means that
* {@code Listener} implementations do not need to be concerned with
* possible recursion or the order in which they invoke
* {@code WebSocket.request} in relation to their processing logic.
*
* <p> Careful attention may be required if a listener is associated
* with more than a single {@code WebSocket}. In this case invocations
* related to different instances of {@code WebSocket} may not be ordered
* and may even happen concurrently.
*
* <p> {@code CompletionStage}s returned from the receive methods have
* nothing to do with the
* <a href="WebSocket.html#counter">counter of invocations</a>.
* Namely, a {@code CompletionStage} does not have to be completed in order
* to receive more invocations of the listener's methods.
* Here is an example of a listener that requests invocations, one at a
* time, until a complete message has been accumulated, then processes
* the result, and completes the {@code CompletionStage}:
* <pre>{@code WebSocket.Listener listener = new WebSocket.Listener() {
*
* List<CharSequence> parts = new ArrayList<>();
* CompletableFuture<?> accumulatedMessage = new CompletableFuture<>();
*
* public CompletionStage<?> onText(WebSocket webSocket,
* CharSequence message,
* boolean last) {
* parts.add(message);
* webSocket.request(1);
* if (last) {
* processWholeText(parts);
* parts = new ArrayList<>();
* accumulatedMessage.complete(null);
* CompletionStage<?> cf = accumulatedMessage;
* accumulatedMessage = new CompletableFuture<>();
* return cf;
* }
* return accumulatedMessage;
* }
* ...
* } } </pre>
*
* @since 11
*/
interface Listener {
/**
* A {@code WebSocket} has been connected.
*
* <p> This is the initial invocation and it is made once. It is
* typically used to make a request for more invocations.
*
* @implSpec The default implementation is equivalent to:
* <pre>{@code webSocket.request(1); }</pre>
*
* @param webSocket
* the WebSocket that has been connected
*/
default void onOpen(WebSocket webSocket) { webSocket.request(1); }
/**
* A textual data has been received.
*
* <p> Return a {@code CompletionStage} which will be used by the
* {@code WebSocket} as an indication it may reclaim the
* {@code CharSequence}. Do not access the {@code CharSequence} after
* this {@code CompletionStage} has completed.
*
* @implSpec The default implementation is equivalent to:
* <pre>{@code webSocket.request(1);
* return null; }</pre>
*
* @implNote The {@code data} is always a legal UTF-16 sequence.
*
* @param webSocket
* the WebSocket on which the data has been received
* @param data
* the data
* @param last
* whether this invocation completes the message
*
* @return a {@code CompletionStage} which completes when the
* {@code CharSequence} may be reclaimed; or {@code null} if it may be
* reclaimed immediately
*/
default CompletionStage<?> onText(WebSocket webSocket,
CharSequence data,
boolean last) {
webSocket.request(1);
return null;
}
/**
* A binary data has been received.
*
* <p> This data is located in bytes from the buffer's position to its
* limit.
*
* <p> Return a {@code CompletionStage} which will be used by the
* {@code WebSocket} as an indication it may reclaim the
* {@code ByteBuffer}. Do not access the {@code ByteBuffer} after
* this {@code CompletionStage} has completed.
*
* @implSpec The default implementation is equivalent to:
* <pre>{@code webSocket.request(1);
* return null; }</pre>
*
* @param webSocket
* the WebSocket on which the data has been received
* @param data
* the data
* @param last
* whether this invocation completes the message
*
* @return a {@code CompletionStage} which completes when the
* {@code ByteBuffer} may be reclaimed; or {@code null} if it may be
* reclaimed immediately
*/
default CompletionStage<?> onBinary(WebSocket webSocket,
ByteBuffer data,
boolean last) {
webSocket.request(1);
return null;
}
/**
* A Ping message has been received.
*
* <p> As guaranteed by the WebSocket Protocol, the message consists of
* not more than {@code 125} bytes. These bytes are located from the
* buffer's position to its limit.
*
* <p> Given that the WebSocket implementation will automatically send a
* reciprocal pong when a ping is received, it is rarely required to
* send a pong message explicitly when a ping is received.
*
* <p> Return a {@code CompletionStage} which will be used by the
* {@code WebSocket} as a signal it may reclaim the
* {@code ByteBuffer}. Do not access the {@code ByteBuffer} after
* this {@code CompletionStage} has completed.
*
* @implSpec The default implementation is equivalent to:
* <pre>{@code webSocket.request(1);
* return null; }</pre>
*
* @param webSocket
* the WebSocket on which the message has been received
* @param message
* the message
*
* @return a {@code CompletionStage} which completes when the
* {@code ByteBuffer} may be reclaimed; or {@code null} if it may be
* reclaimed immediately
*/
default CompletionStage<?> onPing(WebSocket webSocket,
ByteBuffer message) {
webSocket.request(1);
return null;
}
/**
* A Pong message has been received.
*
* <p> As guaranteed by the WebSocket Protocol, the message consists of
* not more than {@code 125} bytes. These bytes are located from the
* buffer's position to its limit.
*
* <p> Return a {@code CompletionStage} which will be used by the
* {@code WebSocket} as a signal it may reclaim the
* {@code ByteBuffer}. Do not access the {@code ByteBuffer} after
* this {@code CompletionStage} has completed.
*
* @implSpec The default implementation is equivalent to:
* <pre>{@code webSocket.request(1);
* return null; }</pre>
*
* @param webSocket
* the WebSocket on which the message has been received
* @param message
* the message
*
* @return a {@code CompletionStage} which completes when the
* {@code ByteBuffer} may be reclaimed; or {@code null} if it may be
* reclaimed immediately
*/
default CompletionStage<?> onPong(WebSocket webSocket,
ByteBuffer message) {
webSocket.request(1);
return null;
}
/**
* Receives a Close message indicating the WebSocket's input has been
* closed.
*
* <p> This is the last invocation from the specified {@code WebSocket}.
* By the time this invocation begins the WebSocket's input will have
* been closed.
*
* <p> A Close message consists of a status code and a reason for
* closing. The status code is an integer from the range
* {@code 1000 <= code <= 65535}. The {@code reason} is a string which
* has a UTF-8 representation not longer than {@code 123} bytes.
*
* <p> If the WebSocket's output is not already closed, the
* {@code CompletionStage} returned by this method will be used as an
* indication that the WebSocket's output may be closed. The WebSocket
* will close its output at the earliest of completion of the returned
* {@code CompletionStage} or invoking either of the {@code sendClose}
* or {@code abort} methods.
*
* @apiNote Returning a {@code CompletionStage} that never completes,
* effectively disables the reciprocating closure of the output.
*
* <p> To specify a custom closure code or reason code the
* {@code sendClose} method may be invoked from inside the
* {@code onClose} invocation:
* <pre>{@code public CompletionStage<?> onClose(WebSocket webSocket,
* int statusCode,
* String reason) {
* webSocket.sendClose(CUSTOM_STATUS_CODE, CUSTOM_REASON);
* return new CompletableFuture<Void>();
* } } </pre>
*
* @implSpec The default implementation of this method returns
* {@code null}, indicating that the output should be closed
* immediately.
*
* @param webSocket
* the WebSocket on which the message has been received
* @param statusCode
* the status code
* @param reason
* the reason
*
* @return a {@code CompletionStage} which completes when the
* {@code WebSocket} may be closed; or {@code null} if it may be
* closed immediately
*/
default CompletionStage<?> onClose(WebSocket webSocket,
int statusCode,
String reason) {
return null;
}
/**
* An error has occurred.
*
* <p> This is the last invocation from the specified WebSocket. By the
* time this invocation begins both the WebSocket's input and output
* will have been closed. A WebSocket may invoke this method on the
* associated listener at any time after it has invoked {@code onOpen},
* regardless of whether or not any invocations have been requested from
* the WebSocket.
*
* <p> If an exception is thrown from this method, resulting behavior is
* undefined.
*
* @param webSocket
* the WebSocket on which the error has occurred
* @param error
* the error
*/
default void onError(WebSocket webSocket, Throwable error) { }
}
/**
* Sends textual data with characters from the given character sequence.
*
* <p> The character sequence must not be modified until the
* {@code CompletableFuture} returned from this method has completed.
*
* <p> A {@code CompletableFuture} returned from this method can
* complete exceptionally with:
* <ul>
* <li> {@link IllegalStateException} -
* if there is a pending text or binary send operation
* or if the previous binary data does not complete the message
* <li> {@link IOException} -
* if an I/O error occurs, or if the output is closed
* </ul>
*
* @implNote If {@code data} is a malformed UTF-16 sequence, the operation
* will fail with {@code IOException}.
*
* @param data
* the data
* @param last
* {@code true} if this invocation completes the message,
* {@code false} otherwise
*
* @return a {@code CompletableFuture} that completes, with this WebSocket,
* when the data has been sent
*/
CompletableFuture<WebSocket> sendText(CharSequence data, boolean last);
/**
* Sends binary data with bytes from the given buffer.
*
* <p> The data is located in bytes from the buffer's position to its limit.
* Upon normal completion of a {@code CompletableFuture} returned from this
* method the buffer will have no remaining bytes. The buffer must not be
* accessed until after that.
*
* <p> The {@code CompletableFuture} returned from this method can
* complete exceptionally with:
* <ul>
* <li> {@link IllegalStateException} -
* if there is a pending text or binary send operation
* or if the previous textual data does not complete the message
* <li> {@link IOException} -
* if an I/O error occurs, or if the output is closed
* </ul>
*
* @param data
* the data
* @param last
* {@code true} if this invocation completes the message,
* {@code false} otherwise
*
* @return a {@code CompletableFuture} that completes, with this WebSocket,
* when the data has been sent
*/
CompletableFuture<WebSocket> sendBinary(ByteBuffer data, boolean last);
/**
* Sends a Ping message with bytes from the given buffer.
*
* <p> The message consists of not more than {@code 125} bytes from the
* buffer's position to its limit. Upon normal completion of a
* {@code CompletableFuture} returned from this method the buffer will
* have no remaining bytes. The buffer must not be accessed until after that.
*
* <p> The {@code CompletableFuture} returned from this method can
* complete exceptionally with:
* <ul>
* <li> {@link IllegalStateException} -
* if there is a pending ping or pong send operation
* <li> {@link IllegalArgumentException} -
* if the message is too long
* <li> {@link IOException} -
* if an I/O error occurs, or if the output is closed
* </ul>
*
* @param message
* the message
*
* @return a {@code CompletableFuture} that completes, with this WebSocket,
* when the Ping message has been sent
*/
CompletableFuture<WebSocket> sendPing(ByteBuffer message);
/**
* Sends a Pong message with bytes from the given buffer.
*
* <p> The message consists of not more than {@code 125} bytes from the
* buffer's position to its limit. Upon normal completion of a
* {@code CompletableFuture} returned from this method the buffer will have
* no remaining bytes. The buffer must not be accessed until after that.
*
* <p> Given that the WebSocket implementation will automatically send a
* reciprocal pong when a ping is received, it is rarely required to send a
* pong message explicitly.
*
* <p> The {@code CompletableFuture} returned from this method can
* complete exceptionally with:
* <ul>
* <li> {@link IllegalStateException} -
* if there is a pending ping or pong send operation
* <li> {@link IllegalArgumentException} -
* if the message is too long
* <li> {@link IOException} -
* if an I/O error occurs, or if the output is closed
* </ul>
*
* @param message
* the message
*
* @return a {@code CompletableFuture} that completes, with this WebSocket,
* when the Pong message has been sent
*/
CompletableFuture<WebSocket> sendPong(ByteBuffer message);
/**
* Initiates an orderly closure of this WebSocket's output by
* sending a Close message with the given status code and the reason.
*
* <p> The {@code statusCode} is an integer from the range
* {@code 1000 <= code <= 4999}. Status codes {@code 1002}, {@code 1003},
* {@code 1006}, {@code 1007}, {@code 1009}, {@code 1010}, {@code 1012},
* {@code 1013} and {@code 1015} are illegal. Behaviour in respect to other
* status codes is implementation-specific. A legal {@code reason} is a
* string that has a UTF-8 representation not longer than {@code 123} bytes.
*
* <p> A {@code CompletableFuture} returned from this method can
* complete exceptionally with:
* <ul>
* <li> {@link IllegalArgumentException} -
* if {@code statusCode} is illegal, or
* if {@code reason} is illegal
* <li> {@link IOException} -
* if an I/O error occurs, or if the output is closed
* </ul>
*
* <p> Unless the {@code CompletableFuture} returned from this method
* completes with {@code IllegalArgumentException}, or the method throws
* {@code NullPointerException}, the output will be closed.
*
* <p> If not already closed, the input remains open until a Close message
* {@linkplain Listener#onClose(WebSocket, int, String) received}, or
* {@code abort} is invoked, or an
* {@linkplain Listener#onError(WebSocket, Throwable) error} occurs.
*
* @apiNote Use the provided integer constant {@link #NORMAL_CLOSURE} as a
* status code and an empty string as a reason in a typical case:
* <pre>{@code CompletableFuture<WebSocket> webSocket = ...
* webSocket.thenCompose(ws -> ws.sendText("Hello, ", false))
* .thenCompose(ws -> ws.sendText("world!", true))
* .thenCompose(ws -> ws.sendClose(WebSocket.NORMAL_CLOSURE, ""))
* .join(); }</pre>
*
* The {@code sendClose} method does not close this WebSocket's input. It
* merely closes this WebSocket's output by sending a Close message. To
* enforce closing the input, invoke the {@code abort} method. Here is an
* example of an application that sends a Close message, and then starts a
* timer. Once no data has been received within the specified timeout, the
* timer goes off and the alarm aborts {@code WebSocket}:
* <pre>{@code MyAlarm alarm = new MyAlarm(webSocket::abort);
* WebSocket.Listener listener = new WebSocket.Listener() {
*
* public CompletionStage<?> onText(WebSocket webSocket,
* CharSequence data,
* boolean last) {
* alarm.snooze();
* ...
* }
* ...
* };
* ...
* Runnable startTimer = () -> {
* MyTimer idleTimer = new MyTimer();
* idleTimer.add(alarm, 30, TimeUnit.SECONDS);
* };
* webSocket.sendClose(WebSocket.NORMAL_CLOSURE, "ok").thenRun(startTimer);
* } </pre>
*
* @param statusCode
* the status code
* @param reason
* the reason
*
* @return a {@code CompletableFuture} that completes, with this WebSocket,
* when the Close message has been sent
*/
CompletableFuture<WebSocket> sendClose(int statusCode, String reason);
/**
* Increments the counter of invocations of receive methods.
*
* <p> This WebSocket will invoke {@code onText}, {@code onBinary},
* {@code onPing}, {@code onPong} or {@code onClose} methods on the
* associated listener (i.e. receive methods) up to {@code n} more times.
*
* @apiNote The parameter of this method is the number of invocations being
* requested from this WebSocket to the associated listener, not the number
* of messages. Sometimes a message may be delivered to the listener in a
* single invocation, but not always. For example, Ping, Pong and Close
* messages are delivered in a single invocation of {@code onPing},
* {@code onPong} and {@code onClose} methods respectively. However, whether
* or not Text and Binary messages are delivered in a single invocation of
* {@code onText} and {@code onBinary} methods depends on the boolean
* argument ({@code last}) of these methods. If {@code last} is
* {@code false}, then there is more to a message than has been delivered to
* the invocation.
*
* <p> Here is an example of a listener that requests invocations, one at a
* time, until a complete message has been accumulated, and then processes
* the result:
* <pre>{@code WebSocket.Listener listener = new WebSocket.Listener() {
*
* StringBuilder text = new StringBuilder();
*
* public CompletionStage<?> onText(WebSocket webSocket,
* CharSequence message,
* boolean last) {
* text.append(message);
* if (last) {
* processCompleteTextMessage(text);
* text = new StringBuilder();
* }
* webSocket.request(1);
* return null;
* }
* ...
* } } </pre>
*
* @param n
* the number of invocations
*
* @throws IllegalArgumentException
* if {@code n <= 0}
*/
void request(long n);
/**
* Returns the subprotocol used by this WebSocket.
*
* @return the subprotocol, or an empty string if there's no subprotocol
*/
String getSubprotocol();
/**
* Tells whether this WebSocket's output is closed.
*
* <p> If this method returns {@code true}, subsequent invocations will also
* return {@code true}.
*
* @return {@code true} if closed, {@code false} otherwise
*/
boolean isOutputClosed();
/**
* Tells whether this WebSocket's input is closed.
*
* <p> If this method returns {@code true}, subsequent invocations will also
* return {@code true}.
*
* @return {@code true} if closed, {@code false} otherwise
*/
boolean isInputClosed();
/**
* Closes this WebSocket's input and output abruptly.
*
* <p> When this method returns both the input and the output will have been
* closed. Any pending send operations will fail with {@code IOException}.
* Subsequent invocations of {@code abort} will have no effect.
*/
void abort();
}
|
package model.supervised.bagging;
import data.DataSet;
import utils.array.ArraySumUtil;
import utils.random.RandomUtils;
import utils.sort.SortIntDoubleUtils;
/**
* Created by hanxuan on 11/3/15 for machine_learning.
*/
public class BaggingClassification extends BootstrapAveraging{
private int classCount = 0;
@Override
public double predict(double[] feature) {
double[] votes = probs(feature);
int[] indexes = RandomUtils.getIndexes(classCount);
SortIntDoubleUtils.sort(indexes, votes);
return indexes[classCount - 1];
}
@Override
public void initialize(DataSet d) {
super.initialize(d);
classCount = d.getLabels().getIndexClassMap().size();
}
public double[] probs(double[] feature) {
double[] votes = new double[classCount];
for (int i = 0; i < predictables.length; i++) {
votes[(int) predictables[i].predict(feature)] += 1;
}
return ArraySumUtil.normalize(votes);
}
}
|
package com.git.workshop.database;
import com.git.workshop.database.dao.UserDao;
import com.git.workshop.database.model.User;
import androidx.room.Database;
import androidx.room.RoomDatabase;
@Database(entities = {User.class}, version = 2, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
}
|
package logbook.bean;
import java.io.Serializable;
import java.util.List;
import javax.json.JsonObject;
import logbook.bean.BattleTypes.ICombinedBattle;
import logbook.bean.BattleTypes.IFormation;
import logbook.bean.BattleTypes.IMidnightBattle;
import logbook.bean.BattleTypes.INSupport;
import logbook.internal.JsonHelper;
import lombok.Data;
/**
* 夜戦(連合艦隊)
*
*/
@Data
public class CombinedBattleSpMidnight implements ICombinedBattle, IMidnightBattle, IFormation, INSupport, Serializable {
private static final long serialVersionUID = -364877629377359534L;
/** api_dock_id/api_deck_id */
private Integer dockId;
/** api_ship_ke */
private List<Integer> shipKe;
/** api_ship_lv */
private List<Integer> shipLv;
/** api_f_nowhps */
private List<Integer> fNowhps;
/** api_f_maxhps */
private List<Integer> fMaxhps;
/** api_e_nowhps */
private List<Integer> eNowhps;
/** api_e_maxhps */
private List<Integer> eMaxhps;
/** api_f_nowhps_combined */
private List<Integer> fNowhpsCombined;
/** api_f_maxhps_combined */
private List<Integer> fMaxhpsCombined;
/** api_eSlot */
private List<List<Integer>> eSlot;
/** api_fParam */
private List<List<Integer>> fParam;
/** api_eParam */
private List<List<Integer>> eParam;
/** api_fParam_combined */
private List<List<Integer>> fParamCombined;
/** api_formation */
private List<Integer> formation;
/** api_friendly_info */
private BattleTypes.FriendlyInfo friendlyInfo;
/** api_friendly_battle */
private BattleTypes.FriendlyBattle friendlyBattle;
/** api_touch_plane */
private List<Integer> touchPlane;
/** api_flare_pos */
private List<Integer> flarePos;
/** api_hougeki */
private BattleTypes.MidnightHougeki hougeki;
/** api_n_support_flag */
private Integer nSupportFlag;
/** api_n_support_info */
private BattleTypes.SupportInfo nSupportInfo;
/**
* JsonObjectから{@link CombinedBattleSpMidnight}を構築します
*
* @param json JsonObject
* @return {@link CombinedBattleSpMidnight}
*/
public static CombinedBattleSpMidnight toBattle(JsonObject json) {
CombinedBattleSpMidnight bean = new CombinedBattleSpMidnight();
JsonHelper.bind(json)
.setInteger("api_dock_id", bean::setDockId)
.setInteger("api_deck_id", bean::setDockId)
.setIntegerList("api_ship_ke", bean::setShipKe)
.setIntegerList("api_ship_lv", bean::setShipLv)
.setIntegerList("api_f_nowhps", bean::setFNowhps)
.setIntegerList("api_f_maxhps", bean::setFMaxhps)
.setIntegerList("api_e_nowhps", bean::setENowhps)
.setIntegerList("api_e_maxhps", bean::setEMaxhps)
.setIntegerList("api_f_nowhps_combined", bean::setFNowhpsCombined)
.setIntegerList("api_f_maxhps_combined", bean::setFMaxhpsCombined)
.set("api_eSlot", bean::setESlot, JsonHelper.toList(JsonHelper::toIntegerList))
.set("api_fParam", bean::setFParam, JsonHelper.toList(JsonHelper::toIntegerList))
.set("api_eParam", bean::setEParam, JsonHelper.toList(JsonHelper::toIntegerList))
.set("api_fParam_combined", bean::setFParamCombined, JsonHelper.toList(JsonHelper::toIntegerList))
.setIntegerList("api_formation", bean::setFormation)
.set("api_friendly_info", bean::setFriendlyInfo, BattleTypes.FriendlyInfo::toFriendlyInfo)
.set("api_friendly_battle", bean::setFriendlyBattle, BattleTypes.FriendlyBattle::toFriendlyBattle)
.setIntegerList("api_touch_plane", bean::setTouchPlane)
.setIntegerList("api_flare_pos", bean::setFlarePos)
.set("api_hougeki", bean::setHougeki, BattleTypes.MidnightHougeki::toMidnightHougeki)
.setInteger("api_n_support_flag", bean::setNSupportFlag)
.set("api_n_support_info", bean::setNSupportInfo, BattleTypes.SupportInfo::toSupportInfo);
return bean;
}
}
|
/*
* The MIT License
*
* Copyright (c) 2009-2021 PrimeTek
*
* 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.primefaces.component.treetable;
import org.primefaces.PrimeFaces;
import org.primefaces.component.api.DynamicColumn;
import org.primefaces.component.api.UIColumn;
import org.primefaces.component.api.UITree;
import org.primefaces.component.celleditor.CellEditor;
import org.primefaces.component.column.Column;
import org.primefaces.component.columngroup.ColumnGroup;
import org.primefaces.component.columns.Columns;
import org.primefaces.component.row.Row;
import org.primefaces.component.tree.Tree;
import org.primefaces.model.*;
import org.primefaces.model.filter.FilterConstraint;
import org.primefaces.model.filter.FunctionFilterConstraint;
import org.primefaces.renderkit.DataRenderer;
import org.primefaces.renderkit.RendererUtils;
import org.primefaces.util.*;
import org.primefaces.visit.ResetInputVisitCallback;
import javax.el.ELContext;
import javax.faces.FacesException;
import javax.faces.component.EditableValueHolder;
import javax.faces.component.UIComponent;
import javax.faces.component.UINamingContainer;
import javax.faces.component.ValueHolder;
import javax.faces.component.visit.VisitContext;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.primefaces.component.api.UITree.ROOT_ROW_KEY;
public class TreeTableRenderer extends DataRenderer {
private static final Logger LOGGER = Logger.getLogger(TreeTableRenderer.class.getName());
private static final String SB_DECODE_SELECTION = TreeTableRenderer.class.getName() + "#decodeSelection";
@Override
public void decode(FacesContext context, UIComponent component) {
TreeTable tt = (TreeTable) component;
if (tt.getSelectionMode() != null) {
TreeNode root = tt.getValue();
decodeSelection(context, tt, root);
}
if (tt.isSortRequest(context)) {
decodeSort(context, tt);
}
tt.decodeColumnResizeState(context);
decodeBehaviors(context, component);
}
protected void decodeSelection(FacesContext context, TreeTable tt, TreeNode root) {
boolean multiple = tt.isMultipleSelectionMode();
Class<?> selectionType = tt.getSelectionType();
if (multiple && !selectionType.isArray() && !List.class.isAssignableFrom(selectionType)) {
throw new FacesException("Multiple selection reference must be an Array or a List for TreeTable " + tt.getClientId());
}
Map<String, String> params = context.getExternalContext().getRequestParameterMap();
String clientId = tt.getClientId(context);
//decode selection
String selectionValue = params.get(tt.getClientId(context) + "_selection");
if (isValueBlank(selectionValue)) {
if (multiple) {
tt.setSelection(selectionType.isArray() ? new TreeNode[0] : Collections.emptyList());
}
else {
tt.setSelection(null);
}
}
else {
String[] selectedRowKeys = selectionValue.split(",");
if (multiple) {
List<TreeNode> selectedNodes = new ArrayList<>();
for (int i = 0; i < selectedRowKeys.length; i++) {
tt.setRowKey(root, selectedRowKeys[i]);
TreeNode rowNode = tt.getRowNode();
if (rowNode != null) {
selectedNodes.add(rowNode);
}
}
tt.setSelection(selectionType.isArray() ? selectedNodes.toArray(new TreeNode[selectedNodes.size()]) : selectedNodes);
}
else {
tt.setRowKey(root, selectedRowKeys[0]);
tt.setSelection(tt.getRowNode());
}
tt.setRowKey(root, null); //cleanup
}
if (tt.isCheckboxSelectionMode() && tt.isSelectionRequest(context)) {
String selectedNodeRowKey = params.get(clientId + "_instantSelection");
tt.setRowKey(root, selectedNodeRowKey);
TreeNode selectedNode = tt.getRowNode();
List<String> descendantRowKeys = new ArrayList<>();
tt.populateRowKeys(selectedNode, descendantRowKeys);
int size = descendantRowKeys.size();
StringBuilder sb = SharedStringBuilder.get(context, SB_DECODE_SELECTION);
for (int i = 0; i < size; i++) {
sb.append(descendantRowKeys.get(i));
if (i != (size - 1)) {
sb.append(",");
}
}
PrimeFaces.current().ajax().addCallbackParam("descendantRowKeys", sb.toString());
sb.setLength(0);
descendantRowKeys = null;
}
}
@Override
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
TreeTable tt = (TreeTable) component;
TreeNode root = tt.getValue();
String clientId = tt.getClientId(context);
Map<String, String> params = context.getExternalContext().getRequestParameterMap();
preRender(context, tt);
if (tt.isExpandRequest(context)) {
String nodeKey = params.get(clientId + "_expand");
tt.setRowKey(root, nodeKey);
TreeNode node = tt.getRowNode();
node.setExpanded(true);
if (tt.getExpandMode().equals("self")) {
encodeNode(context, tt, root, node);
}
else {
encodeNodeChildren(context, tt, root, node);
}
}
else if (tt.isCollapseRequest(context)) {
String nodeKey = params.get(clientId + "_collapse");
tt.setRowKey(root, nodeKey);
TreeNode node = tt.getRowNode();
node.setExpanded(false);
}
else if (tt.isFilterRequest(context)) {
tt.updateFilteredValue(context, null);
tt.setValue(null);
tt.setFirst(0);
//update rows with rpp value
String rppValue = params.get(clientId + "_rppDD");
if (rppValue != null && !"*".equals(rppValue)) {
tt.setRows(Integer.parseInt(rppValue));
}
filter(context, tt, tt.getValue());
sort(tt);
encodeTbody(context, tt, tt.getValue(), true);
if (tt.isMultiViewState()) {
Map<String, FilterMeta> filterBy = tt.getFilterByAsMap();
TreeTableState ts = tt.getMultiViewState(true);
ts.setFilterBy(filterBy);
if (tt.isPaginator()) {
ts.setFirst(tt.getFirst());
ts.setRows(tt.getRows());
}
}
}
else if (tt.isSortRequest(context)) {
encodeSort(context, tt, root);
}
else if (tt.isRowEditRequest(context)) {
encodeRowEdit(context, tt, root);
}
else if (tt.isCellEditRequest(context)) {
encodeCellEdit(context, tt, root);
}
else if (tt.isPaginationRequest(context)) {
tt.updatePaginationData(context);
encodeNodeChildren(context, tt, root, root, tt.getFirst(), tt.getRows());
}
else {
filter(context, tt, tt.getValue());
sort(tt);
encodeMarkup(context, tt);
encodeScript(context, tt);
}
}
protected void preRender(FacesContext context, TreeTable tt) {
Map<String, FilterMeta> filterBy = tt.initFilterBy(context);
// required a second time here as preRender is only called in DT when the request is not "_encodeFeature"
if (tt.isFilterRequest(context)) {
tt.updateFilterByValuesWithFilterRequest(context, filterBy);
}
tt.resetDynamicColumns();
if (tt.isMultiViewState()) {
tt.restoreMultiViewState();
}
}
protected void encodeScript(FacesContext context, TreeTable tt) throws IOException {
String selectionMode = tt.getSelectionMode();
WidgetBuilder wb = getWidgetBuilder(context);
wb.init("TreeTable", tt)
.attr("selectionMode", selectionMode, null)
.attr("resizableColumns", tt.isResizableColumns(), false)
.attr("liveResize", tt.isLiveResize(), false)
.attr("scrollable", tt.isScrollable(), false)
.attr("scrollHeight", tt.getScrollHeight(), null)
.attr("scrollWidth", tt.getScrollWidth(), null)
.attr("nativeElements", tt.isNativeElements(), false)
.attr("expandMode", tt.getExpandMode(), "children")
.attr("disabledTextSelection", tt.isDisabledTextSelection(), true);
if (tt.isStickyHeader()) {
wb.attr("stickyHeader", true);
}
//Editing
if (tt.isEditable()) {
wb.attr("editable", true)
.attr("editMode", tt.getEditMode())
.attr("saveOnCellBlur", tt.isSaveOnCellBlur(), true)
.attr("cellEditMode", tt.getCellEditMode(), "eager")
.attr("cellSeparator", tt.getCellSeparator(), null)
.attr("editInitEvent", tt.getEditInitEvent());
}
//Filtering
if (tt.isFilteringEnabled()) {
wb.attr("filter", true)
.attr("filterEvent", tt.getFilterEvent(), null)
.attr("filterDelay", tt.getFilterDelay(), Integer.MAX_VALUE);
}
if (tt.isSortingEnabled()) {
wb.attr("sorting", true);
if (tt.isMultiSort()) {
wb.attr("multiSort", true)
.nativeAttr("sortMetaOrder", tt.getSortMetaAsString(), null);
}
if (tt.isAllowUnsorting()) {
wb.attr("allowUnsorting", true);
}
}
if (tt.isPaginator()) {
encodePaginatorConfig(context, tt, wb);
}
encodeClientBehaviors(context, tt);
wb.finish();
}
protected void encodeMarkup(FacesContext context, TreeTable tt) throws IOException {
ResponseWriter writer = context.getResponseWriter();
String clientId = tt.getClientId(context);
boolean scrollable = tt.isScrollable();
boolean resizable = tt.isResizableColumns();
TreeNode root = tt.getValue();
boolean hasPaginator = tt.isPaginator();
if (root == null) {
throw new FacesException("treeTable's value must not be null. ClientId: " + clientId);
}
if (!(root instanceof TreeNode)) {
throw new FacesException("treeTable's value must be an instance of " + TreeNode.class.getName() + ". ClientId: " + clientId);
}
if (hasPaginator) {
tt.calculateFirst();
}
if (root.getRowKey() == null) {
root.setRowKey(ROOT_ROW_KEY);
tt.buildRowKeys(root);
tt.initPreselection();
}
//default sort
if (tt.isDefaultSort()) {
sort(tt);
}
String containerClass = tt.isResizableColumns() ? TreeTable.RESIZABLE_CONTAINER_CLASS : TreeTable.CONTAINER_CLASS;
containerClass = scrollable ? containerClass + " " + TreeTable.SCROLLABLE_CONTAINER_CLASS : containerClass;
containerClass = tt.getStyleClass() == null ? containerClass : containerClass + " " + tt.getStyleClass();
containerClass = tt.isShowUnselectableCheckbox() ? containerClass + " ui-treetable-checkbox-all" : containerClass;
containerClass = tt.isShowGridlines() ? containerClass + " " + TreeTable.GRIDLINES_CLASS : containerClass;
containerClass = "small".equals(tt.getSize()) ? containerClass + " " + TreeTable.SMALL_SIZE_CLASS : containerClass;
containerClass = "large".equals(tt.getSize()) ? containerClass + " " + TreeTable.LARGE_SIZE_CLASS : containerClass;
writer.startElement("div", null);
writer.writeAttribute("id", clientId, "id");
writer.writeAttribute("class", containerClass, null);
if (tt.getStyle() != null) {
writer.writeAttribute("style", tt.getStyle(), null);
}
if (scrollable) {
encodeScrollableMarkup(context, tt, root);
}
else {
encodeRegularMarkup(context, tt, root);
}
if (tt.getSelectionMode() != null) {
encodeStateHolder(context, tt, clientId + "_selection", tt.getSelectedRowKeysAsString());
}
if (scrollable) {
encodeStateHolder(context, tt, clientId + "_scrollState", tt.getScrollState());
}
if (resizable) {
encodeStateHolder(context, tt, tt.getClientId(context) + "_resizableColumnState", tt.getColumnsWidthForClientSide());
}
writer.endElement("div");
}
protected void encodeScrollableMarkup(FacesContext context, TreeTable tt, TreeNode root) throws IOException {
String tableStyle = tt.getTableStyle();
String tableStyleClass = tt.getTableStyleClass();
boolean hasPaginator = tt.isPaginator();
String paginatorPosition = tt.getPaginatorPosition();
encodeScrollAreaStart(context, tt, TreeTable.SCROLLABLE_HEADER_CLASS, TreeTable.SCROLLABLE_HEADER_BOX_CLASS,
tableStyle, tableStyleClass, "header", TreeTable.HEADER_CLASS);
if (hasPaginator && !"bottom".equalsIgnoreCase(paginatorPosition)) {
encodePaginatorMarkup(context, tt, "top");
}
encodeThead(context, tt);
encodeScrollAreaEnd(context);
encodeScrollBody(context, tt, root, tableStyle, tableStyleClass);
encodeScrollAreaStart(context, tt, TreeTable.SCROLLABLE_FOOTER_CLASS, TreeTable.SCROLLABLE_FOOTER_BOX_CLASS,
tableStyle, tableStyleClass, "footer", TreeTable.FOOTER_CLASS);
encodeTfoot(context, tt);
if (hasPaginator && !"top".equalsIgnoreCase(paginatorPosition)) {
encodePaginatorMarkup(context, tt, "bottom");
}
encodeScrollAreaEnd(context);
}
protected void encodeScrollBody(FacesContext context, TreeTable tt, TreeNode root, String tableStyle, String tableStyleClass) throws IOException {
ResponseWriter writer = context.getResponseWriter();
String scrollHeight = tt.getScrollHeight();
writer.startElement("div", null);
writer.writeAttribute("class", TreeTable.SCROLLABLE_BODY_CLASS, null);
if (scrollHeight != null && scrollHeight.indexOf('%') == -1) {
writer.writeAttribute("style", "height:" + scrollHeight + "px", null);
}
writer.startElement("table", null);
writer.writeAttribute("role", "grid", null);
if (tableStyle != null) {
writer.writeAttribute("style", tableStyle, null);
}
if (tableStyleClass != null) {
writer.writeAttribute("class", tableStyleClass, null);
}
encodeTbody(context, tt, root, false);
writer.endElement("table");
writer.endElement("div");
}
protected void encodeScrollAreaStart(FacesContext context, TreeTable tt, String containerClass, String containerBoxClass,
String tableStyle, String tableStyleClass, String facet, String facetClass) throws IOException {
ResponseWriter writer = context.getResponseWriter();
writer.startElement("div", null);
writer.writeAttribute("class", containerClass, null);
encodeFacet(context, tt, tt.getFacet(facet), facetClass);
writer.startElement("div", null);
writer.writeAttribute("class", containerBoxClass, null);
writer.startElement("table", null);
writer.writeAttribute("role", "grid", null);
if (tableStyle != null) {
writer.writeAttribute("style", tableStyle, null);
}
if (tableStyleClass != null) {
writer.writeAttribute("class", tableStyleClass, null);
}
}
protected void encodeScrollAreaEnd(FacesContext context) throws IOException {
ResponseWriter writer = context.getResponseWriter();
writer.endElement("table");
writer.endElement("div");
writer.endElement("div");
}
protected void encodeRegularMarkup(FacesContext context, TreeTable tt, TreeNode root) throws IOException {
ResponseWriter writer = context.getResponseWriter();
boolean hasPaginator = tt.isPaginator();
String paginatorPosition = tt.getPaginatorPosition();
encodeFacet(context, tt, tt.getFacet("header"), TreeTable.HEADER_CLASS);
if (tt.isPaginator() && !"bottom".equalsIgnoreCase(paginatorPosition)) {
encodePaginatorMarkup(context, tt, "top");
}
writer.startElement("table", tt);
writer.writeAttribute("role", "treegrid", null);
if (tt.getTableStyle() != null) {
writer.writeAttribute("style", tt.getTableStyle(), null);
}
if (tt.getTableStyleClass() != null) {
writer.writeAttribute("class", tt.getTableStyleClass(), null);
}
encodeThead(context, tt);
encodeTfoot(context, tt);
encodeTbody(context, tt, root, false);
writer.endElement("table");
if (hasPaginator && !"top".equalsIgnoreCase(paginatorPosition)) {
encodePaginatorMarkup(context, tt, "bottom");
}
encodeFacet(context, tt, tt.getFacet("footer"), TreeTable.FOOTER_CLASS);
}
protected void encodeThead(FacesContext context, TreeTable tt) throws IOException {
ResponseWriter writer = context.getResponseWriter();
ColumnGroup group = tt.getColumnGroup("header");
String clientId = tt.getClientId(context);
writer.startElement("thead", null);
writer.writeAttribute("id", clientId + "_head", null);
if (group != null && group.isRendered()) {
context.getAttributes().put(Constants.HELPER_RENDERER, "columnGroup");
for (UIComponent child : group.getChildren()) {
if (child.isRendered()) {
if (child instanceof Row) {
Row headerRow = (Row) child;
String rowClass = headerRow.getStyleClass();
String rowStyle = headerRow.getStyle();
writer.startElement("tr", null);
writer.writeAttribute("role", "row", null);
if (rowClass != null) {
writer.writeAttribute("class", rowClass, null);
}
if (rowStyle != null) {
writer.writeAttribute("style", rowStyle, null);
}
for (UIComponent headerRowChild : headerRow.getChildren()) {
if (headerRowChild.isRendered()) {
if (headerRowChild instanceof Column) {
encodeColumnHeader(context, tt, (Column) headerRowChild);
}
else if (headerRowChild instanceof Columns) {
List<DynamicColumn> dynamicColumns = ((Columns) headerRowChild).getDynamicColumns();
for (DynamicColumn dynaColumn : dynamicColumns) {
dynaColumn.applyModel();
encodeColumnHeader(context, tt, dynaColumn);
}
}
else {
headerRowChild.encodeAll(context);
}
}
}
writer.endElement("tr");
}
else {
child.encodeAll(context);
}
}
}
context.getAttributes().remove(Constants.HELPER_RENDERER);
}
else {
writer.startElement("tr", null);
writer.writeAttribute("role", "row", null);
List<UIColumn> columns = tt.getColumns();
for (int i = 0; i < columns.size(); i++) {
UIColumn column = columns.get(i);
if (column instanceof Column) {
encodeColumnHeader(context, tt, column);
}
else if (column instanceof DynamicColumn) {
DynamicColumn dynamicColumn = (DynamicColumn) column;
dynamicColumn.applyModel();
encodeColumnHeader(context, tt, dynamicColumn);
}
}
writer.endElement("tr");
}
writer.endElement("thead");
}
protected void encodeTbody(FacesContext context, TreeTable tt, TreeNode root, boolean dataOnly) throws IOException {
ResponseWriter writer = context.getResponseWriter();
String clientId = tt.getClientId(context);
boolean empty = (root == null || root.getChildCount() == 0);
UIComponent emptyFacet = tt.getFacet("emptyMessage");
if (!dataOnly) {
writer.startElement("tbody", null);
writer.writeAttribute("id", clientId + "_data", null);
writer.writeAttribute("class", TreeTable.DATA_CLASS, null);
}
if (empty) {
writer.startElement("tr", null);
writer.writeAttribute("class", TreeTable.EMPTY_MESSAGE_ROW_CLASS, null);
writer.startElement("td", null);
writer.writeAttribute("colspan", tt.getColumnsCount(), null);
if (ComponentUtils.shouldRenderFacet(emptyFacet)) {
emptyFacet.encodeAll(context);
}
else {
writer.writeText(tt.getEmptyMessage(), "emptyMessage");
}
writer.endElement("td");
writer.endElement("tr");
}
if (root != null) {
if (tt.isPaginator()) {
int first = tt.getFirst();
int rows = tt.getRows() == 0 ? tt.getRowCount() : tt.getRows();
encodeNodeChildren(context, tt, root, root, first, rows);
}
else {
encodeNodeChildren(context, tt, root, root);
}
}
tt.setRowKey(root, null);
if (!dataOnly) {
writer.endElement("tbody");
}
}
protected void encodeNode(FacesContext context, TreeTable tt, TreeNode root, TreeNode treeNode) throws IOException {
ResponseWriter writer = context.getResponseWriter();
String rowKey = treeNode.getRowKey();
String parentRowKey = treeNode.getParent().getRowKey();
tt.setRowKey(root, rowKey);
String icon = treeNode.isExpanded() ? TreeTable.COLLAPSE_ICON : TreeTable.EXPAND_ICON;
int depth = rowKey.split(UITree.SEPARATOR).length - 1;
boolean selectionEnabled = tt.isSelectionEnabled();
boolean selectable = treeNode.isSelectable() && selectionEnabled;
boolean checkboxSelection = selectionEnabled && tt.isCheckboxSelectionMode();
boolean selected = treeNode.isSelected();
boolean partialSelected = treeNode.isPartialSelected();
boolean nativeElements = tt.isNativeElements();
List<UIColumn> columns = tt.getColumns();
String rowStyleClass = selected ? TreeTable.SELECTED_ROW_CLASS : TreeTable.ROW_CLASS;
rowStyleClass = selectable ? rowStyleClass + " " + TreeTable.SELECTABLE_NODE_CLASS : rowStyleClass;
rowStyleClass = rowStyleClass + " " + treeNode.getType();
rowStyleClass = rowStyleClass + " ui-node-level-" + (rowKey.split("_").length);
if (partialSelected) {
rowStyleClass = rowStyleClass + " " + TreeTable.PARTIAL_SELECTED_CLASS;
}
String userRowStyleClass = tt.getRowStyleClass();
if (userRowStyleClass != null) {
rowStyleClass = rowStyleClass + " " + userRowStyleClass;
}
if (tt.isEditingRow()) {
rowStyleClass = rowStyleClass + " " + TreeTable.EDITING_ROW_CLASS;
}
writer.startElement("tr", null);
writer.writeAttribute("id", tt.getClientId(context) + "_node_" + rowKey, null);
writer.writeAttribute("class", rowStyleClass, null);
writer.writeAttribute("role", "row", null);
writer.writeAttribute(HTML.ARIA_EXPANDED, String.valueOf(treeNode.isExpanded()), null);
writer.writeAttribute("data-rk", rowKey, null);
if (parentRowKey != null) {
writer.writeAttribute("data-prk", parentRowKey, null);
}
if (selectionEnabled) {
writer.writeAttribute(HTML.ARIA_SELECTED, String.valueOf(selected), null);
}
for (int i = 0; i < columns.size(); i++) {
UIColumn column = columns.get(i);
ColumnMeta columnMeta = tt.getColumnMeta().get(column.getColumnKey(tt, rowKey));
if (column.isDynamic()) {
((DynamicColumn) column).applyModel();
}
if (column.isRendered()) {
boolean columnVisible = column.isVisible();
if (columnMeta != null && columnMeta.getVisible() != null) {
columnVisible = columnMeta.getVisible();
}
String columnStyleClass = column.getStyleClass();
String columnStyle = column.getStyle();
int rowspan = column.getRowspan();
int colspan = column.getColspan();
int responsivePriority = column.getResponsivePriority();
if (responsivePriority > 0) {
columnStyleClass = (columnStyleClass == null)
? "ui-column-p-" + responsivePriority
: columnStyleClass + " ui-column-p-" + responsivePriority;
}
if (column.getCellEditor() != null) {
columnStyleClass = (columnStyleClass == null) ? TreeTable.EDITABLE_COLUMN_CLASS : TreeTable.EDITABLE_COLUMN_CLASS + " " + columnStyleClass;
}
if (!columnVisible) {
columnStyleClass = (columnStyleClass == null) ? TreeTable.HIDDEN_COLUMN_CLASS : columnStyleClass + " " + TreeTable.HIDDEN_COLUMN_CLASS;
}
writer.startElement("td", null);
writer.writeAttribute("role", "gridcell", null);
if (columnStyle != null) {
writer.writeAttribute("style", columnStyle, null);
}
if (columnStyleClass != null) {
writer.writeAttribute("class", columnStyleClass, null);
}
if (rowspan != 1) {
writer.writeAttribute("rowspan", rowspan, null);
}
if (colspan != 1) {
writer.writeAttribute("colspan", colspan, null);
}
if (i == 0) {
for (int j = 0; j < depth; j++) {
writer.startElement("span", null);
writer.writeAttribute("class", TreeTable.INDENT_CLASS, null);
writer.endElement("span");
}
writer.startElement("span", null);
writer.writeAttribute("class", icon, null);
if (treeNode.isLeaf()) {
writer.writeAttribute("style", "visibility:hidden", null);
}
writer.endElement("span");
if (checkboxSelection) {
if (!nativeElements) {
RendererUtils.encodeCheckbox(context, selected, partialSelected, !selectable, Tree.CHECKBOX_CLASS);
}
else {
renderNativeCheckbox(context, tt, selected, partialSelected);
}
}
}
column.renderChildren(context);
writer.endElement("td");
}
}
writer.endElement("tr");
if (treeNode.isExpanded()) {
encodeNodeChildren(context, tt, root, treeNode);
}
}
public void encodeColumnHeader(FacesContext context, TreeTable tt, UIColumn column) throws IOException {
if (!column.isRendered()) {
return;
}
ColumnMeta columnMeta = tt.getColumnMeta().get(column.getColumnKey());
ResponseWriter writer = context.getResponseWriter();
UIComponent header = column.getFacet("header");
String headerText = column.getHeaderText();
boolean columnVisible = column.isVisible();
if (columnMeta != null && columnMeta.getVisible() != null) {
columnVisible = columnMeta.getVisible();
}
int colspan = column.getColspan();
int rowspan = column.getRowspan();
boolean sortable = tt.isColumnSortable(context, column);
boolean filterable = tt.isColumnFilterable(column);
SortMeta sortMeta = null;
String style = column.getStyle();
String width = column.getWidth();
String columnClass = sortable ? TreeTable.SORTABLE_COLUMN_HEADER_CLASS : TreeTable.COLUMN_HEADER_CLASS;
columnClass = !columnVisible ? columnClass + " " + TreeTable.HIDDEN_COLUMN_CLASS : columnClass;
columnClass = !column.isToggleable() ? columnClass + " " + TreeTable.STATIC_COLUMN_CLASS : columnClass;
String userColumnClass = column.getStyleClass();
if (column.isResizable()) {
columnClass = columnClass + " " + TreeTable.RESIZABLE_COLUMN_CLASS;
}
if (userColumnClass != null) {
columnClass = columnClass + " " + userColumnClass;
}
columnClass = filterable ? columnClass + " " + TreeTable.FILTER_COLUMN_CLASS : columnClass;
if (sortable) {
sortMeta = tt.getSortByAsMap().get(column.getColumnKey());
if (sortMeta.isActive()) {
columnClass += " ui-state-active";
}
}
int responsivePriority = column.getResponsivePriority();
if (responsivePriority > 0) {
columnClass = columnClass + " ui-column-p-" + responsivePriority;
}
if (width != null) {
String unit = endsWithLenghtUnit(width) ? Constants.EMPTY_STRING : "px";
if (style != null) {
style = style + ";width:" + width + unit;
}
else {
style = "width:" + width + unit;
}
}
String ariaHeaderLabel = getHeaderLabel(context, column);
writer.startElement("th", null);
writer.writeAttribute("id", column.getContainerClientId(context), null);
writer.writeAttribute("class", columnClass, null);
writer.writeAttribute("role", "columnheader", null);
writer.writeAttribute(HTML.ARIA_LABEL, ariaHeaderLabel, null);
if (style != null) {
writer.writeAttribute("style", style, null);
}
if (rowspan != 1) {
writer.writeAttribute("rowspan", rowspan, null);
}
if (colspan != 1) {
writer.writeAttribute("colspan", colspan, null);
}
writer.startElement("span", null);
writer.writeAttribute("class", "ui-column-title", null);
if (ComponentUtils.shouldRenderFacet(header)) {
header.encodeAll(context);
}
else if (headerText != null) {
writer.writeText(headerText, null);
}
writer.endElement("span");
if (sortable && sortMeta != null) {
String sortIcon = resolveDefaultSortIcon(sortMeta);
if (sortIcon != null) {
writer.startElement("span", null);
writer.writeAttribute("class", sortIcon, null);
writer.endElement("span");
if (tt.isMultiSort()) {
writer.startElement("span", null);
writer.writeAttribute("class", TreeTable.SORTABLE_PRIORITY_CLASS, null);
writer.endElement("span");
}
}
}
if (filterable) {
encodeFilter(context, tt, column);
}
writer.endElement("th");
}
protected String resolveDefaultSortIcon(SortMeta sortMeta) {
SortOrder sortOrder = sortMeta.getOrder();
String sortIcon = TreeTable.SORTABLE_COLUMN_ICON_CLASS;
if (sortOrder.isAscending()) {
sortIcon = TreeTable.SORTABLE_COLUMN_ASCENDING_ICON_CLASS;
}
else if (sortOrder.isDescending()) {
sortIcon = TreeTable.SORTABLE_COLUMN_DESCENDING_ICON_CLASS;
}
return sortIcon;
}
protected void encodeFilter(FacesContext context, TreeTable tt, UIColumn column) throws IOException {
if (tt.isGlobalFilterOnly()) {
return;
}
ResponseWriter writer = context.getResponseWriter();
UIComponent filterFacet = column.getFacet("filter");
if (!ComponentUtils.shouldRenderFacet(filterFacet)) {
String separator = String.valueOf(UINamingContainer.getSeparatorChar(context));
boolean disableTabbing = tt.getScrollWidth() != null;
String filterId = column.getContainerClientId(context) + separator + "filter";
Object filterValue = tt.getFilterValue(column);
filterValue = (filterValue == null) ? Constants.EMPTY_STRING : filterValue.toString();
String filterStyleClass = getStyleClassBuilder(context)
.add(TreeTable.COLUMN_INPUT_FILTER_CLASS)
.add(column.getFilterStyleClass())
.build();
writer.startElement("input", null);
writer.writeAttribute("id", filterId, null);
writer.writeAttribute("name", filterId, null);
writer.writeAttribute("class", filterStyleClass, null);
writer.writeAttribute("value", filterValue, null);
writer.writeAttribute("autocomplete", "off", null);
if (disableTabbing) {
writer.writeAttribute("tabindex", "-1", null);
}
if (column.getFilterStyle() != null) {
writer.writeAttribute("style", column.getFilterStyle(), null);
}
if (column.getFilterMaxLength() != Integer.MAX_VALUE) {
writer.writeAttribute("maxlength", column.getFilterMaxLength(), null);
}
writer.endElement("input");
}
else {
Object filterValue = tt.getFilterValue(column);
if (filterValue != null) {
((ValueHolder) filterFacet).setValue(filterValue);
}
writer.startElement("div", null);
writer.writeAttribute("class", TreeTable.COLUMN_CUSTOM_FILTER_CLASS, null);
filterFacet.encodeAll(context);
writer.endElement("div");
}
}
protected void encodeNodeChildren(FacesContext context, TreeTable tt, TreeNode root, TreeNode treeNode) throws IOException {
int childCount = treeNode.getChildCount();
encodeNodeChildren(context, tt, root, treeNode, 0, childCount);
}
protected void encodeNodeChildren(FacesContext context, TreeTable tt, TreeNode root, TreeNode treeNode, int first, int size) throws IOException {
if (size > 0) {
List<TreeNode> children = treeNode.getChildren();
int childCount = treeNode.getChildCount();
int last = (first + size);
if (last > childCount) {
last = childCount;
}
for (int i = first; i < last; i++) {
encodeNode(context, tt, root, children.get(i));
}
}
}
protected void encodeFacet(FacesContext context, TreeTable tt, UIComponent facet, String styleClass) throws IOException {
if (!ComponentUtils.shouldRenderFacet(facet)) {
return;
}
ResponseWriter writer = context.getResponseWriter();
writer.startElement("div", null);
writer.writeAttribute("class", styleClass, null);
facet.encodeAll(context);
writer.endElement("div");
}
protected void encodeTfoot(FacesContext context, TreeTable tt) throws IOException {
ResponseWriter writer = context.getResponseWriter();
ColumnGroup group = tt.getColumnGroup("footer");
boolean hasFooterColumn = tt.hasFooterColumn();
boolean shouldRenderFooter = (hasFooterColumn || group != null);
if (!shouldRenderFooter) {
return;
}
writer.startElement("tfoot", null);
if (group != null && group.isRendered()) {
context.getAttributes().put(Constants.HELPER_RENDERER, "columnGroup");
for (UIComponent child : group.getChildren()) {
if (child.isRendered()) {
if (child instanceof Row) {
Row footerRow = (Row) child;
String rowClass = footerRow.getStyleClass();
String rowStyle = footerRow.getStyle();
writer.startElement("tr", null);
if (rowClass != null) {
writer.writeAttribute("class", rowClass, null);
}
if (rowStyle != null) {
writer.writeAttribute("style", rowStyle, null);
}
for (UIComponent footerRowChild : footerRow.getChildren()) {
if (footerRowChild.isRendered()) {
if (footerRowChild instanceof Column) {
encodeColumnFooter(context, tt, (Column) footerRowChild);
}
else if (footerRowChild instanceof Columns) {
List<DynamicColumn> dynamicColumns = ((Columns) footerRowChild).getDynamicColumns();
for (DynamicColumn dynaColumn : dynamicColumns) {
dynaColumn.applyModel();
encodeColumnFooter(context, tt, dynaColumn);
}
}
else {
footerRowChild.encodeAll(context);
}
}
}
writer.endElement("tr");
}
else {
child.encodeAll(context);
}
}
}
context.getAttributes().remove(Constants.HELPER_RENDERER);
}
else if (hasFooterColumn) {
writer.startElement("tr", null);
List<UIColumn> columns = tt.getColumns();
for (int i = 0; i < columns.size(); i++) {
UIColumn column = columns.get(i);
if (column instanceof Column) {
encodeColumnFooter(context, tt, column);
}
else if (column instanceof DynamicColumn) {
DynamicColumn dynamicColumn = (DynamicColumn) column;
dynamicColumn.applyModel();
encodeColumnFooter(context, tt, dynamicColumn);
}
}
writer.endElement("tr");
}
writer.endElement("tfoot");
}
public void encodeColumnFooter(FacesContext context, TreeTable table, UIColumn column) throws IOException {
if (!column.isRendered()) {
return;
}
ResponseWriter writer = context.getResponseWriter();
int colspan = column.getColspan();
int rowspan = column.getRowspan();
UIComponent footerFacet = column.getFacet("footer");
String footerText = column.getFooterText();
String style = column.getStyle();
String columnStyleClass = column.getStyleClass();
columnStyleClass = (columnStyleClass == null) ? TreeTable.COLUMN_HEADER_CLASS : TreeTable.COLUMN_HEADER_CLASS + " " + columnStyleClass;
int responsivePriority = column.getResponsivePriority();
if (responsivePriority > 0) {
columnStyleClass = columnStyleClass + " ui-column-p-" + responsivePriority;
}
writer.startElement("td", null);
writer.writeAttribute("class", columnStyleClass, null);
if (style != null) {
writer.writeAttribute("style", style, null);
}
if (rowspan != 1) {
writer.writeAttribute("rowspan", rowspan, null);
}
if (colspan != 1) {
writer.writeAttribute("colspan", colspan, null);
}
if (ComponentUtils.shouldRenderFacet(footerFacet)) {
footerFacet.encodeAll(context);
}
else if (footerText != null) {
writer.writeText(footerText, null);
}
writer.endElement("td");
}
@Override
public void encodeChildren(FacesContext facesContext, UIComponent component) throws IOException {
//Do nothing
}
@Override
public boolean getRendersChildren() {
return true;
}
private void encodeStateHolder(FacesContext context, TreeTable tt, String name, String value) throws IOException {
ResponseWriter writer = context.getResponseWriter();
writer.startElement("input", null);
writer.writeAttribute("id", name, null);
writer.writeAttribute("name", name, null);
writer.writeAttribute("type", "hidden", null);
writer.writeAttribute("value", value, null);
writer.endElement("input");
}
protected String resolveSortIcon(SortMeta sortMeta) {
if (sortMeta == null) {
return null;
}
SortOrder sortOrder = sortMeta.getOrder();
if (sortOrder == SortOrder.ASCENDING) {
return TreeTable.SORTABLE_COLUMN_ASCENDING_ICON_CLASS;
}
else if (sortOrder == SortOrder.DESCENDING) {
return TreeTable.SORTABLE_COLUMN_DESCENDING_ICON_CLASS;
}
return null;
}
protected void decodeSort(FacesContext context, TreeTable tt) {
Map<String, String> params = context.getExternalContext().getRequestParameterMap();
String clientId = tt.getClientId(context);
String sortKey = params.get(clientId + "_sortKey");
String sortDir = params.get(clientId + "_sortDir");
String[] sortKeys = sortKey.split(",");
String[] sortOrders = sortDir.split(",");
if (sortKeys.length != sortOrders.length) {
throw new FacesException("sortKeys != sortDirs");
}
Map<String, SortMeta> sortByMap = tt.getSortByAsMap();
Map<String, Integer> sortKeysIndexes = IntStream.range(0, sortKeys.length).boxed()
.collect(Collectors.toMap(i -> sortKeys[i], i -> i));
for (Map.Entry<String, SortMeta> entry : sortByMap.entrySet()) {
SortMeta sortMeta = entry.getValue();
if (sortMeta.isHeaderRow()) {
continue;
}
Integer index = sortKeysIndexes.get(entry.getKey());
if (index != null) {
sortMeta.setOrder(SortOrder.of(sortOrders[index]));
sortMeta.setPriority(index);
}
else {
sortMeta.setOrder(SortOrder.UNSORTED);
sortMeta.setPriority(SortMeta.MIN_PRIORITY);
}
}
}
protected void encodeSort(FacesContext context, TreeTable tt, TreeNode root) throws IOException {
sort(tt);
encodeTbody(context, tt, root, true);
if (tt.isMultiViewState()) {
Map<String, SortMeta> sortMeta = tt.getSortByAsMap();
TreeTableState ts = tt.getMultiViewState(true);
ts.setSortBy(sortMeta);
if (tt.isPaginator()) {
ts.setFirst(tt.getFirst());
ts.setRows(tt.getRows());
}
}
}
public void sort(TreeTable tt) {
TreeNode root = tt.getValue();
if (root == null) {
return;
}
Map<String, SortMeta> sortBy = tt.getSortByAsMap();
if (sortBy.isEmpty()) {
return;
}
Locale dataLocale = tt.resolveDataLocale();
tt.forEachColumn(column -> {
SortMeta meta = sortBy.get(column.getColumnKey());
if (meta == null || !meta.isActive()) {
return true;
}
if (column instanceof DynamicColumn) {
((DynamicColumn) column).applyStatelessModel();
}
TreeUtils.sortNode(root, new TreeNodeComparator(
meta.getSortBy(),
tt.getVar(),
meta.getOrder(),
meta.getFunction(),
meta.isCaseSensitiveSort(),
dataLocale));
tt.updateRowKeys(root);
return true;
});
String selectedRowKeys = tt.getSelectedRowKeysAsString();
if (selectedRowKeys != null) {
PrimeFaces.current().ajax().addCallbackParam("selection", selectedRowKeys);
}
}
protected void renderNativeCheckbox(FacesContext context, TreeTable tt, boolean checked, boolean partialSelected) throws IOException {
ResponseWriter writer = context.getResponseWriter();
writer.startElement("input", null);
writer.writeAttribute("type", "checkbox", null);
writer.writeAttribute("name", tt.getContainerClientId(context) + "_checkbox", null);
if (checked) {
writer.writeAttribute("checked", "checked", null);
}
if (partialSelected) {
writer.writeAttribute("class", "ui-treetable-indeterminate", null);
}
writer.endElement("input");
}
public void encodeRowEdit(FacesContext context, TreeTable tt, TreeNode root) throws IOException {
Map<String, String> params = context.getExternalContext().getRequestParameterMap();
String clientId = tt.getClientId(context);
String editedRowKey = params.get(clientId + "_rowEditIndex");
String action = params.get(clientId + "_rowEditAction");
tt.setRowKey(root, editedRowKey);
TreeNode node = tt.getRowNode();
if ("cancel".equals(action)) {
VisitContext visitContext = null;
for (UIColumn column : tt.getColumns()) {
for (UIComponent grandkid : column.getChildren()) {
if (grandkid instanceof CellEditor) {
UIComponent inputFacet = grandkid.getFacet("input");
if (inputFacet instanceof EditableValueHolder) {
((EditableValueHolder) inputFacet).resetValue();
}
else {
if (visitContext == null) {
visitContext = VisitContext.createVisitContext(context, null, ComponentUtils.VISIT_HINTS_SKIP_UNRENDERED);
}
inputFacet.visitTree(visitContext, ResetInputVisitCallback.INSTANCE);
}
}
}
}
}
encodeNode(context, tt, root, node);
}
public void encodeCellEdit(FacesContext context, TreeTable tt, TreeNode root) throws IOException {
Map<String, String> params = context.getExternalContext().getRequestParameterMap();
String clientId = tt.getClientId(context);
String[] cellInfo = params.get(clientId + "_cellInfo").split(",");
String rowKey = cellInfo[0];
int cellIndex = Integer.parseInt(cellInfo[1]);
int i = -1;
UIColumn column = null;
for (UIColumn col : tt.getColumns()) {
if (col.isRendered()) {
i++;
if (i == cellIndex) {
column = col;
break;
}
}
}
if (column == null) {
throw new FacesException("No column found for cellIndex: " + cellIndex);
}
tt.setRowKey(root, rowKey);
if (column.isDynamic()) {
DynamicColumn dynamicColumn = (DynamicColumn) column;
dynamicColumn.applyStatelessModel();
}
if (tt.isCellEditCancelRequest(context) || tt.isCellEditInitRequest(context)) {
column.getCellEditor().getFacet("input").encodeAll(context);
}
else {
column.getCellEditor().getFacet("output").encodeAll(context);
}
if (column.isDynamic()) {
((DynamicColumn) column).cleanStatelessModel();
}
}
public void filter(FacesContext context, TreeTable tt, TreeNode root) throws IOException {
Map<String, FilterMeta> filterBy = tt.getFilterByAsMap();
if (filterBy.isEmpty()) {
return;
}
Locale filterLocale = LocaleUtils.getCurrentLocale(context);
// collect filtered / valid node rowKeys
List<String> filteredRowKeys = tt.getFilteredRowKeys();
filteredRowKeys.clear();
collectFilteredRowKeys(context, tt, root, root, filterBy, filterLocale, filteredRowKeys);
// recreate tree node
TreeNode filteredValue = cloneTreeNode(tt, root, root.getParent());
createFilteredValueFromRowKeys(tt, root, filteredValue, filteredRowKeys);
tt.updateFilteredValue(context, filteredValue);
tt.setValue(filteredValue);
tt.setRowKey(root, null);
//Metadata for callback
if (tt.isPaginator()) {
PrimeFaces.current().ajax().addCallbackParam("totalRecords", filteredValue.getChildCount());
}
if (tt.getSelectedRowKeysAsString() != null) {
PrimeFaces.current().ajax().addCallbackParam("selection", tt.getSelectedRowKeysAsString());
}
}
protected void collectFilteredRowKeys(FacesContext context, TreeTable tt, TreeNode<?> root, TreeNode<?> node, Map<String, FilterMeta> filterBy,
Locale filterLocale, List<String> filteredRowKeys) throws IOException {
ELContext elContext = context.getELContext();
FilterMeta globalFilter = filterBy.get(FilterMeta.GLOBAL_FILTER_KEY);
boolean hasGlobalFilterFunction = globalFilter != null && globalFilter.getConstraint() instanceof FunctionFilterConstraint;
int childCount = node.getChildCount();
AtomicBoolean localMatch = new AtomicBoolean();
AtomicBoolean globalMatch = new AtomicBoolean();
for (int i = 0; i < childCount; i++) {
TreeNode childNode = node.getChildren().get(i);
String rowKey = childNode.getRowKey();
tt.setRowKey(root, rowKey);
localMatch.set(true);
globalMatch.set(false);
if (hasGlobalFilterFunction) {
globalMatch.set(globalFilter.getConstraint().isMatching(context, childNode, globalFilter.getFilterValue(), filterLocale));
}
tt.forEachColumn(column -> {
FilterMeta filter = filterBy.get(column.getColumnKey(tt, rowKey));
if (filter == null || filter.isGlobalFilter()) {
return true;
}
Object columnValue = filter.getLocalValue(elContext, column);
if (globalFilter != null && globalFilter.isActive() && !globalMatch.get() && !hasGlobalFilterFunction) {
FilterConstraint constraint = globalFilter.getConstraint();
Object filterValue = globalFilter.getFilterValue();
globalMatch.set(constraint.isMatching(context, columnValue, filterValue, filterLocale));
}
if (!filter.isActive()) {
return true;
}
FilterConstraint constraint = filter.getConstraint();
Object filterValue = filter.getFilterValue();
localMatch.set(constraint.isMatching(context, columnValue, filterValue, filterLocale));
return localMatch.get();
});
boolean matches = localMatch.get();
if (globalFilter != null && globalFilter.isActive()) {
matches = matches && globalMatch.get();
}
if (matches) {
filteredRowKeys.add(rowKey);
}
collectFilteredRowKeys(context, tt, root, childNode, filterBy, filterLocale, filteredRowKeys);
}
}
private void createFilteredValueFromRowKeys(TreeTable tt, TreeNode<?> node, TreeNode<?> filteredNode, List<String> filteredRowKeys) {
int childCount = node.getChildCount();
for (int i = 0; i < childCount; i++) {
TreeNode childNode = node.getChildren().get(i);
String rowKeyOfChildNode = childNode.getRowKey();
for (String rk : filteredRowKeys) {
if (rk.equals(rowKeyOfChildNode) || rk.startsWith(rowKeyOfChildNode + "_") || rowKeyOfChildNode.startsWith(rk + "_")) {
TreeNode newNode = cloneTreeNode(tt, childNode, filteredNode);
if (rk.startsWith(rowKeyOfChildNode + "_")) {
newNode.setExpanded(true);
}
createFilteredValueFromRowKeys(tt, childNode, newNode, filteredRowKeys);
break;
}
}
}
}
protected TreeNode cloneTreeNode(TreeTable tt, TreeNode<?> node, TreeNode<?> parent) {
TreeNode clone = null;
// equals check instead of instanceof to allow subclassing
if (CheckboxTreeNode.class.equals(node.getClass())) {
clone = new CheckboxTreeNode(node.getType(), node.getData(), parent);
}
// equals check instead of instanceof to allow subclassing
else if (DefaultTreeNode.class.equals(node.getClass())) {
clone = new DefaultTreeNode(node.getType(), node.getData(), parent);
}
if (clone == null && tt.isCloneOnFilter()) {
if (node instanceof Cloneable) {
try {
Method cloneMethod = node.getClass().getMethod("clone");
if (cloneMethod != null) {
cloneMethod.setAccessible(true);
clone = (TreeNode) cloneMethod.invoke(node);
}
}
catch (NoSuchMethodException e) {
LOGGER.warning(node.getClass().getName() + " declares Cloneable but no clone() method found!");
}
catch (InvocationTargetException | IllegalAccessException e) {
LOGGER.warning(node.getClass().getName() + "#clone() not accessible!");
}
}
else {
try {
Constructor<? extends TreeNode> ctor = node.getClass().getConstructor(node.getClass());
clone = ctor.newInstance(node);
}
catch (NoSuchMethodException e) {
// ignore
}
catch (InvocationTargetException | IllegalAccessException | InstantiationException e) {
LOGGER.warning("Could not clone " + node.getClass().getName()
+ " via public " + node.getClass().getSimpleName() + "() constructor!");
}
if (clone == null) {
try {
Constructor<? extends TreeNode> ctor = node.getClass().getConstructor(String.class, Object.class, TreeNode.class);
clone = ctor.newInstance(node.getType(), node.getData(), parent);
}
catch (NoSuchMethodException e) {
// ignore
}
catch (InvocationTargetException | IllegalAccessException | InstantiationException e) {
LOGGER.warning("Could not clone " + node.getClass().getName()
+ " via public " + node.getClass().getSimpleName() + "(String type, Object data, TreeNode parent) constructor!");
}
}
}
}
if (clone == null) {
if (node instanceof CheckboxTreeNode) {
clone = new CheckboxTreeNode(node.getType(), node.getData(), parent);
}
else {
clone = new DefaultTreeNode(node.getType(), node.getData(), parent);
}
}
clone.setSelectable(node.isSelectable());
clone.setSelected(node.isSelected());
clone.setExpanded(node.isExpanded());
return clone;
}
}
|
package ch.goodrick.brewcontrol.service;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.junit.Test;
import ch.goodrick.brewcontrol.common.PhysicalQuantity;
import ch.goodrick.brewcontrol.sensor.CalibratedTemperatureSensor;
public class CalibratedTemperatureSensorTest extends CalibratedTemperatureSensor {
@Test
public void testGetCalibratedValue() {
calibrate(0, 102, 0);
assertEquals(49, getCalibratedValue(50), 0.1);
calibrate(-1, 101, 0);
assertEquals(0d, getCalibratedValue(-1), 0.1);
assertEquals(1d, getCalibratedValue(0), 0.1);
assertEquals(50d, getCalibratedValue(50), 0.1);
assertEquals(100d, getCalibratedValue(101), 0.1);
}
@Override
public String getID() {
// TODO Auto-generated method stub
return null;
}
@Override
public Double getValue() throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public PhysicalQuantity getPhysicalQuantity() {
// TODO Auto-generated method stub
return null;
}
}
|
/*
* Copyright 2007-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazon.ion.impl;
import com.amazon.ion.IonReader;
import com.amazon.ion.IonTestCase;
import com.amazon.ion.IonWriter;
import com.amazon.ion.system.IonTextWriterBuilder;
import java.io.IOException;
import java.io.StringWriter;
import org.junit.Test;
public class IonMarkupWriterTest extends IonTestCase {
private String input =
"abcd::{ hello:( sexp 1 2 \"str\" ), 'list':[ 3.2, 32e-1], " +
"blob:annot::" +
"{{ T25lIEJpZyBGYXQgVGVzdCBCbG9iIEZvciBZb3VyIFBsZWFzdXJl }} }";
private String sExpected =
"<beforeAnnotations STRUCT><beforeEachAnnotation STRUCT>abcd" +
"<afterEachAnnotation STRUCT>::<afterAnnotations STRUCT>" +
"<beforeData STRUCT>{<afterStepIn STRUCT><beforeFieldName SEXP>" +
"hello<afterFieldName SEXP>:<beforeData SEXP>(<afterStepIn SEXP>" +
"<beforeData SYMBOL>sexp<afterData SYMBOL><beforeSeparator SEXP> " +
"<afterSeparator SEXP><beforeData INT>1<afterData INT>" +
"<beforeSeparator SEXP> <afterSeparator SEXP><beforeData INT>" +
"2<afterData INT><beforeSeparator SEXP> <afterSeparator SEXP>" +
"<beforeData STRING>\"str\"<afterData STRING><beforeStepOut SEXP>" +
")<afterData SEXP><beforeSeparator STRUCT>,<afterSeparator STRUCT>" +
"<beforeFieldName LIST>list<afterFieldName LIST>:<beforeData LIST>" +
"[<afterStepIn LIST><beforeData DECIMAL>3.2<afterData DECIMAL>" +
"<beforeSeparator LIST>,<afterSeparator LIST><beforeData FLOAT>" +
"3.2e0<afterData FLOAT><beforeStepOut LIST>]<afterData LIST>" +
"<beforeSeparator STRUCT>,<afterSeparator STRUCT>" +
"<beforeFieldName BLOB>blob<afterFieldName BLOB>:<beforeAnnotations" +
" BLOB><beforeEachAnnotation BLOB>annot<afterEachAnnotation BLOB>::" +
"<afterAnnotations BLOB><beforeData BLOB>" +
"{{T25lIEJpZyBGYXQgVGVzdCBCbG9iIEZvciBZb3VyIFBsZWFzdXJl}}<afterData" +
" BLOB><beforeStepOut STRUCT>}<afterData STRUCT>";
// TODO amzn/ion-java/issues/57 determine if platform specific newlines are appropriate for pretty printing
private String pExpected = String.format(
"%n<beforeAnnotations STRUCT><beforeEachAnnotation STRUCT>abcd" +
"<afterEachAnnotation STRUCT>::<afterAnnotations STRUCT><beforeData" +
" STRUCT>{<afterStepIn STRUCT>%n <beforeFieldName SEXP>hello" +
"<afterFieldName SEXP>: <beforeData SEXP>(<afterStepIn SEXP>%n " +
"<beforeData SYMBOL>sexp<afterData SYMBOL><beforeSeparator SEXP>" +
"%n <afterSeparator SEXP><beforeData INT>1<afterData INT>" +
"<beforeSeparator SEXP>%n <afterSeparator SEXP><beforeData INT>2" +
"<afterData INT><beforeSeparator SEXP>%n <afterSeparator SEXP>" +
"<beforeData STRING>\"str\"<afterData STRING><beforeStepOut SEXP>%n " +
")<afterData SEXP><beforeSeparator STRUCT>,%n " +
"<afterSeparator STRUCT><beforeFieldName LIST>list<afterFieldName " +
"LIST>: <beforeData LIST>[<afterStepIn LIST>%n <beforeData " +
"DECIMAL>3.2<afterData DECIMAL><beforeSeparator LIST>,%n " +
"<afterSeparator LIST><beforeData FLOAT>3.2e0<afterData FLOAT>" +
"<beforeStepOut LIST>%n ]<afterData LIST><beforeSeparator STRUCT>" +
",%n <afterSeparator STRUCT><beforeFieldName BLOB>blob" +
"<afterFieldName BLOB>: <beforeAnnotations BLOB>" +
"<beforeEachAnnotation BLOB>annot<afterEachAnnotation BLOB>::" +
"<afterAnnotations BLOB><beforeData BLOB>" +
"{{ T25lIEJpZyBGYXQgVGVzdCBCbG9iIEZvciBZb3VyIFBsZWFzdXJl }}" +
"<afterData BLOB><beforeStepOut STRUCT>%n}<afterData STRUCT>"
);
@Test
public void testStandardCallback()
throws IOException
{
// Write to a StringWriter for testing
StringWriter out = new StringWriter();
IonReader ionReader = system().newReader(input);
_Private_IonTextWriterBuilder builder = (_Private_IonTextWriterBuilder)
IonTextWriterBuilder.standard();
IonWriter ionWriter = builder
.withCallbackBuilder(new TestMarkupCallback.Builder())
.build(out);
write(ionReader, ionWriter);
assertEquals("Markup callback with standard Ion Writer, " +
"error with data:\n" + input + "\n",
sExpected, out.toString());
}
@Test
public void testPrettyCallback()
throws IOException
{
// Write to a StringWriter for testing
StringWriter out = new StringWriter();
IonReader ionReader = system().newReader(input);
_Private_IonTextWriterBuilder builder = (_Private_IonTextWriterBuilder)
IonTextWriterBuilder.pretty();
IonWriter ionWriter = builder
.withCallbackBuilder(new TestMarkupCallback.Builder())
.build(out);
write(ionReader, ionWriter);
assertEquals("Markup callback with pretty printing Ion Writer," +
" error with data:\n" + input + "\n",
pExpected, out.toString());
}
@Test
public void testEscaping() throws IOException
{
String input = "These should be escaped <>&";
String expected = "<><><>&&&<><><>\"These should be escaped <>&\"";
StringWriter out = new StringWriter();
_Private_IonTextWriterBuilder builder = (_Private_IonTextWriterBuilder)
IonTextWriterBuilder.standard();
IonWriter ionWriter = builder
.withCallbackBuilder(new EscapingCallback.Builder())
.build(out);
ionWriter.writeString(input);
ionWriter.finish();
assertEquals("Escaping failed, with data:\n" + input + "\n",
expected, out.toString());
}
public void write(IonReader ionReader, IonWriter ionWriter)
throws IOException
{
assertNotNull("ionReader is null", ionReader);
assertNotNull("ionWriter is null", ionWriter);
ionWriter.writeValues(ionReader);
ionWriter.close();
ionReader.close();
}
}
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.swt.tests.junit;
import junit.framework.TestCase;
import org.eclipse.swt.graphics.Point;
/**
* Automated Test Suite for class org.eclipse.swt.graphics.Point
*
* @see org.eclipse.swt.graphics.Point
*/
public class Test_org_eclipse_swt_graphics_Point extends TestCase {
public void test_ConstructorII() {
// Test new Point (int x, int y)
Point p = new Point(3, 4);
assertEquals(3, p.x);
assertEquals(4, p.y);
p = new Point(-4, -3);
assertEquals(-4, p.x);
assertEquals(-3, p.y);
p = new Point(500000, 700000);
assertEquals(500000, p.x);
assertEquals(700000, p.y);
}
public void test_equalsLjava_lang_Object() {
Point p1 = new Point(5, 5);
Point p2 = new Point(5, 5);
assertTrue("Points should be equal", p1.equals(p2));
p1 = new Point(-5, -5);
p2 = new Point(-5, -5);
assertTrue("Points should be equal", p1.equals(p2));
p2 = new Point(3, 4);
assertTrue("Points should not be equal", !p1.equals(p2));
}
public void test_hashCode() {
Point p1 = new Point(5, 5);
Point p2 = new Point(5, 5);
assertTrue("Points should have the same hashCode", p1.hashCode() == p2.hashCode());
}
public void test_toString() {
Point p = new Point(3, 4);
assertNotNull(p.toString());
assertTrue(p.toString().length() > 0);
assertEquals("Point {3, 4}", p.toString());
}
}
|
/*
* Copyright (c) 2021-2022. CropDB 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 xyz.vopen.framework.cropdb.index.fulltext.languages;
import xyz.vopen.framework.cropdb.index.fulltext.Language;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* French stop words
*
* @author <a href="mailto:iskp.me@gmail.com">Elve.Xu</a>
* @since 2.1.0
*/
public class French implements Language {
@Override
public Set<String> stopWords() {
return new HashSet<>(
Arrays.asList(
"a",
"abord",
"absolument",
"afin",
"ah",
"ai",
"aie",
"aient",
"aies",
"ailleurs",
"ainsi",
"ait",
"allaient",
"allo",
"allons",
"allô",
"alors",
"anterieur",
"anterieure",
"anterieures",
"apres",
"après",
"as",
"assez",
"attendu",
"au",
"aucun",
"aucune",
"aucuns",
"aujourd",
"aujourd'hui",
"aupres",
"auquel",
"aura",
"aurai",
"auraient",
"aurais",
"aurait",
"auras",
"aurez",
"auriez",
"aurions",
"aurons",
"auront",
"aussi",
"autre",
"autrefois",
"autrement",
"autres",
"autrui",
"aux",
"auxquelles",
"auxquels",
"avaient",
"avais",
"avait",
"avant",
"avec",
"avez",
"aviez",
"avions",
"avoir",
"avons",
"ayant",
"ayez",
"ayons",
"b",
"bah",
"bas",
"basee",
"bat",
"beau",
"beaucoup",
"bien",
"bigre",
"bon",
"boum",
"bravo",
"brrr",
"c",
"car",
"ce",
"ceci",
"cela",
"celle",
"celle-ci",
"celle-là",
"celles",
"celles-ci",
"celles-là",
"celui",
"celui-ci",
"celui-là",
"celà",
"cent",
"cependant",
"certain",
"certaine",
"certaines",
"certains",
"certes",
"ces",
"cet",
"cette",
"ceux",
"ceux-ci",
"ceux-là",
"chacun",
"chacune",
"chaque",
"cher",
"chers",
"chez",
"chiche",
"chut",
"chère",
"chères",
"ci",
"cinq",
"cinquantaine",
"cinquante",
"cinquantième",
"cinquième",
"clac",
"clic",
"combien",
"comme",
"comment",
"comparable",
"comparables",
"compris",
"concernant",
"contre",
"couic",
"crac",
"d",
"da",
"dans",
"de",
"debout",
"dedans",
"dehors",
"deja",
"delà",
"depuis",
"dernier",
"derniere",
"derriere",
"derrière",
"des",
"desormais",
"desquelles",
"desquels",
"dessous",
"dessus",
"deux",
"deuxième",
"deuxièmement",
"devant",
"devers",
"devra",
"devrait",
"different",
"differentes",
"differents",
"différent",
"différente",
"différentes",
"différents",
"dire",
"directe",
"directement",
"dit",
"dite",
"dits",
"divers",
"diverse",
"diverses",
"dix",
"dix-huit",
"dix-neuf",
"dix-sept",
"dixième",
"doit",
"doivent",
"donc",
"dont",
"dos",
"douze",
"douzième",
"dring",
"droite",
"du",
"duquel",
"durant",
"dès",
"début",
"désormais",
"e",
"effet",
"egale",
"egalement",
"egales",
"eh",
"elle",
"elle-même",
"elles",
"elles-mêmes",
"en",
"encore",
"enfin",
"entre",
"envers",
"environ",
"es",
"essai",
"est",
"et",
"etant",
"etc",
"etre",
"eu",
"eue",
"eues",
"euh",
"eurent",
"eus",
"eusse",
"eussent",
"eusses",
"eussiez",
"eussions",
"eut",
"eux",
"eux-mêmes",
"exactement",
"excepté",
"extenso",
"exterieur",
"eûmes",
"eût",
"eûtes",
"f",
"fais",
"faisaient",
"faisant",
"fait",
"faites",
"façon",
"feront",
"fi",
"flac",
"floc",
"fois",
"font",
"force",
"furent",
"fus",
"fusse",
"fussent",
"fusses",
"fussiez",
"fussions",
"fut",
"fûmes",
"fût",
"fûtes",
"g",
"gens",
"h",
"ha",
"haut",
"hein",
"hem",
"hep",
"hi",
"ho",
"holà",
"hop",
"hormis",
"hors",
"hou",
"houp",
"hue",
"hui",
"huit",
"huitième",
"hum",
"hurrah",
"hé",
"hélas",
"i",
"ici",
"il",
"ils",
"importe",
"j",
"je",
"jusqu",
"jusque",
"juste",
"k",
"l",
"la",
"laisser",
"laquelle",
"las",
"le",
"lequel",
"les",
"lesquelles",
"lesquels",
"leur",
"leurs",
"longtemps",
"lors",
"lorsque",
"lui",
"lui-meme",
"lui-même",
"là",
"lès",
"m",
"ma",
"maint",
"maintenant",
"mais",
"malgre",
"malgré",
"maximale",
"me",
"meme",
"memes",
"merci",
"mes",
"mien",
"mienne",
"miennes",
"miens",
"mille",
"mince",
"mine",
"minimale",
"moi",
"moi-meme",
"moi-même",
"moindres",
"moins",
"mon",
"mot",
"moyennant",
"multiple",
"multiples",
"même",
"mêmes",
"n",
"na",
"naturel",
"naturelle",
"naturelles",
"ne",
"neanmoins",
"necessaire",
"necessairement",
"neuf",
"neuvième",
"ni",
"nombreuses",
"nombreux",
"nommés",
"non",
"nos",
"notamment",
"notre",
"nous",
"nous-mêmes",
"nouveau",
"nouveaux",
"nul",
"néanmoins",
"nôtre",
"nôtres",
"o",
"oh",
"ohé",
"ollé",
"olé",
"on",
"ont",
"onze",
"onzième",
"ore",
"ou",
"ouf",
"ouias",
"oust",
"ouste",
"outre",
"ouvert",
"ouverte",
"ouverts",
"o|",
"où",
"p",
"paf",
"pan",
"par",
"parce",
"parfois",
"parle",
"parlent",
"parler",
"parmi",
"parole",
"parseme",
"partant",
"particulier",
"particulière",
"particulièrement",
"pas",
"passé",
"pendant",
"pense",
"permet",
"personne",
"personnes",
"peu",
"peut",
"peuvent",
"peux",
"pff",
"pfft",
"pfut",
"pif",
"pire",
"pièce",
"plein",
"plouf",
"plupart",
"plus",
"plusieurs",
"plutôt",
"possessif",
"possessifs",
"possible",
"possibles",
"pouah",
"pour",
"pourquoi",
"pourrais",
"pourrait",
"pouvait",
"prealable",
"precisement",
"premier",
"première",
"premièrement",
"pres",
"probable",
"probante",
"procedant",
"proche",
"près",
"psitt",
"pu",
"puis",
"puisque",
"pur",
"pure",
"q",
"qu",
"quand",
"quant",
"quant-à-soi",
"quanta",
"quarante",
"quatorze",
"quatre",
"quatre-vingt",
"quatrième",
"quatrièmement",
"que",
"quel",
"quelconque",
"quelle",
"quelles",
"quelqu'un",
"quelque",
"quelques",
"quels",
"qui",
"quiconque",
"quinze",
"quoi",
"quoique",
"r",
"rare",
"rarement",
"rares",
"relative",
"relativement",
"remarquable",
"rend",
"rendre",
"restant",
"reste",
"restent",
"restrictif",
"retour",
"revoici",
"revoilà",
"rien",
"s",
"sa",
"sacrebleu",
"sait",
"sans",
"sapristi",
"sauf",
"se",
"sein",
"seize",
"selon",
"semblable",
"semblaient",
"semble",
"semblent",
"sent",
"sept",
"septième",
"sera",
"serai",
"seraient",
"serais",
"serait",
"seras",
"serez",
"seriez",
"serions",
"serons",
"seront",
"ses",
"seul",
"seule",
"seulement",
"si",
"sien",
"sienne",
"siennes",
"siens",
"sinon",
"six",
"sixième",
"soi",
"soi-même",
"soient",
"sois",
"soit",
"soixante",
"sommes",
"son",
"sont",
"sous",
"souvent",
"soyez",
"soyons",
"specifique",
"specifiques",
"speculatif",
"stop",
"strictement",
"subtiles",
"suffisant",
"suffisante",
"suffit",
"suis",
"suit",
"suivant",
"suivante",
"suivantes",
"suivants",
"suivre",
"sujet",
"superpose",
"sur",
"surtout",
"t",
"ta",
"tac",
"tandis",
"tant",
"tardive",
"te",
"tel",
"telle",
"tellement",
"telles",
"tels",
"tenant",
"tend",
"tenir",
"tente",
"tes",
"tic",
"tien",
"tienne",
"tiennes",
"tiens",
"toc",
"toi",
"toi-même",
"ton",
"touchant",
"toujours",
"tous",
"tout",
"toute",
"toutefois",
"toutes",
"treize",
"trente",
"tres",
"trois",
"troisième",
"troisièmement",
"trop",
"très",
"tsoin",
"tsouin",
"tu",
"té",
"u",
"un",
"une",
"unes",
"uniformement",
"unique",
"uniques",
"uns",
"v",
"va",
"vais",
"valeur",
"vas",
"vers",
"via",
"vif",
"vifs",
"vingt",
"vivat",
"vive",
"vives",
"vlan",
"voici",
"voie",
"voient",
"voilà",
"vont",
"vos",
"votre",
"vous",
"vous-mêmes",
"vu",
"vé",
"vôtre",
"vôtres",
"w",
"x",
"y",
"z",
"zut",
"à",
"â",
"ça",
"ès",
"étaient",
"étais",
"était",
"étant",
"état",
"étiez",
"étions",
"été",
"étée",
"étées",
"étés",
"êtes",
"être",
"ô"));
}
}
|
package org.hisp.dhis.dataanalysis;
/*
* Copyright (c) 2004-2018, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hisp.dhis.category.CategoryOptionCombo;
import org.hisp.dhis.common.ValueType;
import org.hisp.dhis.commons.filter.Filter;
import org.hisp.dhis.commons.filter.FilterUtils;
import org.hisp.dhis.dataelement.DataElement;
import org.hisp.dhis.datavalue.DeflatedDataValue;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.period.Period;
import org.hisp.dhis.system.filter.DataElementValueTypesFilter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author Halvdan Hoem Grelland
*/
public class DefaultFollowupAnalysisService
implements FollowupAnalysisService
{
private static final Log log = LogFactory.getLog( DefaultFollowupAnalysisService.class );
private static final Filter<DataElement> DE_NUMERIC_FILTER = new DataElementValueTypesFilter( ValueType.NUMERIC_TYPES );
// -------------------------------------------------------------------------
// Dependencies
// -------------------------------------------------------------------------
private DataAnalysisStore dataAnalysisStore;
public void setDataAnalysisStore( DataAnalysisStore dataAnalysisStore )
{
this.dataAnalysisStore = dataAnalysisStore;
}
// -------------------------------------------------------------------------
// FollowupAnalysisService implementation
// -------------------------------------------------------------------------
@Override
public List<DeflatedDataValue> getFollowupDataValues( Collection<OrganisationUnit> parents,
Collection<DataElement> dataElements, Collection<Period> periods, int limit )
{
if ( parents == null || parents.size() == 0 || limit < 1 )
{
return new ArrayList<>();
}
Set<DataElement> elements = new HashSet<>( dataElements );
FilterUtils.filter( elements, DE_NUMERIC_FILTER );
Set<CategoryOptionCombo> categoryOptionCombos = new HashSet<>();
for ( DataElement dataElement : elements )
{
categoryOptionCombos.addAll( dataElement.getCategoryOptionCombos() );
}
log.debug( "Starting min-max analysis, no of data elements: " + elements.size() + ", no of parent org units: " + parents.size() );
return dataAnalysisStore.getFollowupDataValues( elements, categoryOptionCombos, periods, parents, limit );
}
}
|
package net.moonlightflower.wc3libs.misc;
public class UnsupportedFormatException extends Exception {
private String _msg;
@Override
public String toString() {
return _msg;
}
public UnsupportedFormatException(String msg) {
_msg = msg;
}
}
|
package im.shimo.navigators;
import androidx.annotation.NonNull;
import com.facebook.react.uimanager.LayoutShadowNode;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.ViewGroupManager;
public class SplitPlaceholderManager extends ViewGroupManager<SplitPlaceholder> {
@NonNull
@Override
public String getName() {
return "RNNativeSplitPlaceholder";
}
@NonNull
@Override
protected SplitPlaceholder createViewInstance(@NonNull ThemedReactContext reactContext) {
return new SplitPlaceholder(reactContext);
}
@Override
public LayoutShadowNode createShadowNodeInstance() {
return new SceneShadowNode();
}
@Override
public Class<? extends LayoutShadowNode> getShadowNodeClass() {
return SceneShadowNode.class;
}
}
|
package de.neozo.jblockchain.node;
public abstract class Config {
/**
* Address of a Node to use for initialization
*/
public static final String MASTER_NODE_ADDRESS = "http://localhost:8080";
/**
* Minimum number of leading zeros every block hash has to fulfill
*/
public static final int DIFFICULTY = 1;
/**
* Maximum numver of Transactions a Block can hold
*/
public static final int MAX_TRANSACTIONS_PER_BLOCK = 5;
}
|
/*
* 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.jackrabbit.oak.plugins.segment.standby.client;
import static org.apache.jackrabbit.oak.plugins.segment.standby.codec.Messages.newGetHeadReq;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import java.io.Closeable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.jackrabbit.oak.plugins.segment.RecordId;
import org.apache.jackrabbit.oak.plugins.segment.standby.codec.RecordIdDecoder;
import org.apache.jackrabbit.oak.plugins.segment.standby.codec.ReplyDecoder;
import org.apache.jackrabbit.oak.plugins.segment.standby.store.CommunicationObserver;
import org.apache.jackrabbit.oak.plugins.segment.standby.store.StandbyStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StandbyClientHandler extends SimpleChannelInboundHandler<RecordId>
implements Closeable {
private static final Logger log = LoggerFactory
.getLogger(StandbyClientHandler.class);
private final StandbyStore store;
private final CommunicationObserver observer;
private final AtomicBoolean running;
private final int readTimeoutMs;
private final boolean autoClean;
private EventExecutorGroup loaderExecutor;
private ChannelHandlerContext ctx;
public StandbyClientHandler(final StandbyStore store,
CommunicationObserver observer, AtomicBoolean running,
int readTimeoutMs, boolean autoClean) {
this.store = store;
this.observer = observer;
this.running = running;
this.readTimeoutMs = readTimeoutMs;
this.autoClean = autoClean;
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
this.ctx = ctx;
log.debug("sending head request");
ctx.writeAndFlush(newGetHeadReq(this.observer.getID()));
log.debug("did send head request");
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, RecordId msg)
throws Exception {
setHead(msg);
};
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
synchronized void setHead(RecordId head) {
if (store.getHead().getRecordId().equals(head)) {
// all sync'ed up
log.debug("no changes on sync.");
return;
}
log.debug("updating current head to " + head);
ctx.pipeline().remove(ReadTimeoutHandler.class);
ctx.pipeline().remove(RecordIdDecoder.class);
ctx.pipeline().remove(this);
ctx.pipeline().addLast(new ReplyDecoder(store));
loaderExecutor = new DefaultEventExecutorGroup(4);
SegmentLoaderHandler h2 = new SegmentLoaderHandler(store, head,
loaderExecutor, this.observer.getID(), running, readTimeoutMs,
autoClean);
ctx.pipeline().addLast(loaderExecutor, h2);
h2.channelActive(ctx);
log.debug("updating current head finished");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
log.error("Exception caught, closing channel.", cause);
close();
}
@Override
public synchronized void close() {
if (ctx != null) {
for (ChannelHandler h : ctx.pipeline().toMap().values()) {
ctx.pipeline().remove(h);
}
ctx.close();
ctx = null;
}
if (loaderExecutor != null && !loaderExecutor.isShuttingDown()) {
loaderExecutor.shutdownGracefully(0, 1, TimeUnit.SECONDS)
.syncUninterruptibly();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.