text
stringlengths 7
1.01M
|
|---|
package io.kestra.cli.commands.flows;
import io.kestra.cli.AbstractCommand;
import io.kestra.core.models.flows.Flow;
import io.kestra.core.models.hierarchies.GraphCluster;
import io.kestra.core.serializers.YamlFlowParser;
import io.kestra.core.services.Graph2DotService;
import io.kestra.core.services.GraphService;
import io.micronaut.context.ApplicationContext;
import lombok.extern.slf4j.Slf4j;
import picocli.CommandLine;
import java.nio.file.Path;
import jakarta.inject.Inject;
@CommandLine.Command(
name = "dot",
description = "generate a dot graph from a file"
)
@Slf4j
public class FlowDotCommand extends AbstractCommand {
@CommandLine.Parameters(index = "0", description = "the flow file to display")
private Path file;
@Inject
private ApplicationContext applicationContext;
public FlowDotCommand() {
super(false);
}
@Override
public Integer call() throws Exception {
super.call();
YamlFlowParser parser = applicationContext.getBean(YamlFlowParser.class);
Flow flow = parser.parse(file.toFile());
GraphCluster graph = GraphService.of(flow, null);
stdOut(Graph2DotService.dot(graph.getGraph()));
return 0;
}
}
|
package com.example.covid19tracker;
/**
* Model Class for the centre
*/
public class Centre {
String centerName;
String centerAddress;
String centerFromTiming;
String centerToTiming;
String fees;
String vaccineName;
String availability;
int ageLimit;
public Centre(String centerName, String centerAddress, String centerFromTiming, String centerToTiming, String fees, String vaccineName, String availability, int ageLimit) {
this.centerName = centerName;
this.centerAddress = centerAddress;
this.centerFromTiming = centerFromTiming;
this.centerToTiming = centerToTiming;
this.fees = fees;
this.vaccineName = vaccineName;
this.availability = availability;
this.ageLimit = ageLimit;
}
public String getCenterName() {
return centerName;
}
public void setCenterName(String centerName) {
this.centerName = centerName;
}
public String getCenterAddress() {
return centerAddress;
}
public void setCenterAddress(String centerAddress) {
this.centerAddress = centerAddress;
}
public String getVaccineName() {
return vaccineName;
}
public void setVaccineName(String vaccineName) {
this.vaccineName = vaccineName;
}
public String getCenterFromTiming() {
return centerFromTiming;
}
public void setCenterFromTiming(String centerFromTiming) {
this.centerFromTiming = centerFromTiming;
}
public String getCenterToTiming() {
return centerToTiming;
}
public void setCenterToTiming(String centerToTiming) {
this.centerToTiming = centerToTiming;
}
public String getFees() {
return fees;
}
public void setFees(String fees) {
this.fees = fees;
}
public String getAvailability() {
return availability;
}
public void setAvailability(String availability) {
this.availability = availability;
}
public int getAgeLimit() {
return ageLimit;
}
public void setAgeLimit(int ageLimit) {
this.ageLimit = ageLimit;
}
}
|
package com.heima.apis.article;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
public interface ApArticleContentControllerApi {
/**
* 保存app端文章内容
* @param apArticleContent
* @return
*/
ResponseResult saveArticleContent(ApArticleContent apArticleContent);
}
|
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.
/**
* CreativeWrapperOrdering.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.admanager.axis.v202102;
public class CreativeWrapperOrdering implements java.io.Serializable {
private java.lang.String _value_;
private static java.util.HashMap _table_ = new java.util.HashMap();
// Constructor
protected CreativeWrapperOrdering(java.lang.String value) {
_value_ = value;
_table_.put(_value_,this);
}
public static final java.lang.String _NO_PREFERENCE = "NO_PREFERENCE";
public static final java.lang.String _INNER = "INNER";
public static final java.lang.String _OUTER = "OUTER";
public static final CreativeWrapperOrdering NO_PREFERENCE = new CreativeWrapperOrdering(_NO_PREFERENCE);
public static final CreativeWrapperOrdering INNER = new CreativeWrapperOrdering(_INNER);
public static final CreativeWrapperOrdering OUTER = new CreativeWrapperOrdering(_OUTER);
public java.lang.String getValue() { return _value_;}
public static CreativeWrapperOrdering fromValue(java.lang.String value)
throws java.lang.IllegalArgumentException {
CreativeWrapperOrdering enumeration = (CreativeWrapperOrdering)
_table_.get(value);
if (enumeration==null) throw new java.lang.IllegalArgumentException();
return enumeration;
}
public static CreativeWrapperOrdering fromString(java.lang.String value)
throws java.lang.IllegalArgumentException {
return fromValue(value);
}
public boolean equals(java.lang.Object obj) {return (obj == this);}
public int hashCode() { return toString().hashCode();}
public java.lang.String toString() { return _value_;}
public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);}
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumSerializer(
_javaType, _xmlType);
}
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumDeserializer(
_javaType, _xmlType);
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(CreativeWrapperOrdering.class);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202102", "CreativeWrapperOrdering"));
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
}
|
package io.github.lmm1990.spring.boot.starter;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringBootStarterApplicationTests {
@Test
void contextLoads() {
}
}
|
/*
* Copyright 2000-2020 Vaadin Ltd.
*
* 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.vaadin.flow.component;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.util.stream.Collectors;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Document;
import com.vaadin.flow.dom.Element;
/**
* A component which encapsulates a given HTML fragment with a single root
* element.
* <p>
* Note that it is the developer's responsibility to sanitize and remove any
* dangerous parts of the HTML before sending it to the user through this
* component. Passing raw input data to the user will possibly lead to
* cross-site scripting attacks.
* <p>
* This component does not expand the HTML fragment into a server side DOM tree
* so you cannot traverse or modify the HTML on the server. The root element can
* be accessed through {@link #getElement()} and the inner HTML through
* {@link #getInnerHtml()}.
* <p>
* The HTML fragment cannot be changed after creation. You should create a new
* instance to encapsulate another fragment.
*
* @author Vaadin Ltd
* @since 1.0
*/
public class Html extends Component {
private static final PropertyDescriptor<String, String> innerHtmlDescriptor = PropertyDescriptors
.propertyWithDefault("innerHTML", "");
/**
* Creates an instance based on the HTML fragment read from the stream. The
* fragment must have exactly one root element.
* <p>
* A best effort is done to parse broken HTML but no guarantees are given
* for how invalid HTML is handled.
* <p>
* Any heading or trailing whitespace is removed while parsing but any
* whitespace inside the root tag is preserved.
*
* @param stream
* the input stream which provides the HTML in UTF-8
* @throws UncheckedIOException
* if reading the stream fails
*/
public Html(InputStream stream) {
super(null);
if (stream == null) {
throw new IllegalArgumentException("HTML stream cannot be null");
}
try {
setOuterHtml(Jsoup.parse(stream, UTF_8.name(), ""));
} catch (IOException e) {
throw new UncheckedIOException("Unable to read HTML from stream",
e);
}
}
/**
* Creates an instance based on the given HTML fragment. The fragment must
* have exactly one root element.
* <p>
* A best effort is done to parse broken HTML but no guarantees are given
* for how invalid HTML is handled.
* <p>
* Any heading or trailing whitespace is removed while parsing but any
* whitespace inside the root tag is preserved.
*
* @param outerHtml
* the HTML to wrap
*/
public Html(String outerHtml) {
super(null);
if (outerHtml == null || outerHtml.isEmpty()) {
throw new IllegalArgumentException("HTML cannot be null or empty");
}
setOuterHtml(Jsoup.parse(outerHtml));
}
private void setOuterHtml(Document doc) {
int nrChildren = doc.body().children().size();
if (nrChildren != 1) {
String message = "HTML must contain exactly one top level element (ignoring text nodes). Found "
+ nrChildren;
if (nrChildren > 1) {
String tagNames = doc.body().children().stream()
.map(org.jsoup.nodes.Element::tagName)
.collect(Collectors.joining(", "));
message += " elements with the tag names " + tagNames;
}
throw new IllegalArgumentException(message);
}
org.jsoup.nodes.Element root = doc.body().child(0);
Attributes attrs = root.attributes();
Component.setElement(this, new Element(root.tagName()));
attrs.forEach(this::setAttribute);
doc.outputSettings().prettyPrint(false);
setInnerHtml(root.html());
}
private void setAttribute(Attribute attribute) {
String name = attribute.getKey();
String value = attribute.getValue();
if (value == null) {
value = "";
}
getElement().setAttribute(name, value);
}
/**
* Sets the inner HTML, i.e. everything inside the root element.
*
* @param innerHtml
* the inner HTML, not <code>null</code>
*/
private void setInnerHtml(String innerHtml) {
set(innerHtmlDescriptor, innerHtml);
}
/**
* Gets the inner HTML, i.e. everything inside the root element.
*
* @return the inner HTML, not <code>null</code>
*/
public String getInnerHtml() {
return get(innerHtmlDescriptor);
}
}
|
/*
* 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 ncai.funcs;
/**
* @author Petr Ivanov
*
*/
public class GetFrameCount01n extends Thread{
public native void TestFunction();
public native void TestFunction1();
public static native boolean stopsignal();
public static native void resumeagent();
static boolean NoLibrary = false;
static {
try{
System.loadLibrary("GetFrameCount01n");
}
catch(Throwable e){
NoLibrary = true;
}
}
GetFrameCount01n(String name)
{
super(name);
}
static public void main(String args[]) {
if(NoLibrary) return;
new GetFrameCount01n("java_thread").start();
special_method();
/*
while(!stopsignal()){
try {
sleep(100, 0); // milliseconds
} catch (java.lang.InterruptedException ie) {}
System.out.println("\tJAVA: main: ...");
}
try {
sleep(1000, 0); // milliseconds
} catch (java.lang.InterruptedException ie) {}
System.out.println("\tJAVA: main - exit");
*/
return;
}
public void test_java_func1(){
System.out.println("thread - java func1\n");
TestFunction();
}
public void test_java_func2(){
System.out.println("thread - java func2\n");
test_java_func3();
}
public void test_java_func3(){
System.out.println("thread - java func3\n");
TestFunction1();
resumeagent(); /*
while(!stopsignal())
{
try {
sleep(100, 0); // milliseconds
} catch (java.lang.InterruptedException ie) {}
//System.out.println("\tJAVA: Thread: ...");
}*/
}
static public void special_method() {
/*
* Transfer control to native part.
*/
try {
throw new InterruptedException();
} catch (Throwable tex) { }
return;
}
public void run() {
System.out.println("thread - java run\n");
test_java_func1();
}
}
|
package org.cloudfoundry.community.servicebroker.brooklyn.config;
import org.apache.brooklyn.util.text.Strings;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties
@ConfigurationProperties(prefix="brooklyn")
public class BrooklynConfig {
private String uri;
private String username;
private String password;
private String location;
private boolean allCatalogVersions;
private String namespace;
public boolean includesAllCatalogVersions() {
return allCatalogVersions;
}
public void setAllCatalogVersions(boolean allCatalogVersions) {
this.allCatalogVersions = allCatalogVersions;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String toFullUrl(String... resource){
StringBuilder sb = new StringBuilder();
sb.append(getUri());
for(String s : resource){
sb.append("/");
sb.append(s);
}
return sb.toString();
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getLocation() {
if (Strings.isBlank(location)) return "localhost";
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getNamespace() {
return namespace;
}
public void setNamespace(String namespace) {
this.namespace = namespace;
}
}
|
/*
* 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.beam.runners.jet;
import com.google.auto.service.AutoService;
import org.apache.beam.sdk.PipelineRunner;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.PipelineOptionsRegistrar;
import org.apache.beam.sdk.runners.PipelineRunnerRegistrar;
import org.apache.beam.vendor.guava.v20_0.com.google.common.collect.ImmutableList;
/**
* Contains the {@link PipelineRunnerRegistrar} and {@link PipelineOptionsRegistrar} for the {@link
* JetRunner}.
*
* <p>{@link AutoService} will register Apex's implementations of the {@link PipelineRunner} and
* {@link PipelineOptions} as available pipeline runner services.
*/
public final class JetRunnerRegistrar {
private JetRunnerRegistrar() {}
/** Registers the {@link JetRunner}. */
@AutoService(PipelineRunnerRegistrar.class)
public static class Runner implements PipelineRunnerRegistrar {
@Override
public Iterable<Class<? extends PipelineRunner<?>>> getPipelineRunners() {
return ImmutableList.of(JetRunner.class);
}
}
/** Registers the {@link JetPipelineOptions}. */
@AutoService(PipelineOptionsRegistrar.class)
public static class Options implements PipelineOptionsRegistrar {
@Override
public Iterable<Class<? extends PipelineOptions>> getPipelineOptions() {
return ImmutableList.of(JetPipelineOptions.class);
}
}
}
|
/**
* Copyright 2019 MetaRing s.r.l.
*
* 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.metaring.framework.controller;
import com.metaring.framework.Core;
import com.metaring.framework.SysKB;
import com.metaring.framework.util.StringUtil;
import com.metaring.framework.util.log.Logger;
public abstract class AbstractBaseController extends ToolsAccessor {
private Logger logger;
private boolean javaTest;
public AbstractBaseController(Logger logger, Boolean test) {
this.logger = logger;
this.setLoggerStackPosition();
this.setTest(test);
}
public AbstractBaseController(SysKB sysKB, Logger logger) {
this(logger, Core.SYSKB.isSystemInTestMode());
}
public AbstractBaseController(Boolean test) {
this(Core.SYSKB.getSystemLogger(), test);
}
public AbstractBaseController() {
this(Core.SYSKB.getSystemLogger(), Core.SYSKB.isSystemInTestMode());
}
protected void setLoggerStackPosition() {
long actualStackPosition = this.logger.getActualStackPosition();
long newStackPositionLong = actualStackPosition + 1;
Long newStackPosition = newStackPositionLong;
this.logger.setActualStackPosition(newStackPosition);
}
public Boolean getTest() {
return this.javaTest ? true : false;
}
public void setTest(Boolean test) {
this.javaTest = test == true;
}
public Logger getLogger() {
return this.logger;
}
protected boolean isTest() {
return this.javaTest;
}
protected String concatenate(String message, String ... messages) {
if (messages != null && messages.length > 0) {
StringBuilder sb = new StringBuilder(message);
for (int i = 0; i < messages.length; ++i) {
String messageString = messages[i];
sb.append(messageString);
if (i >= messages.length - 1) continue;
sb.append(", ");
}
String finalText = sb.toString();
String concatenatedText = finalText;
return concatenatedText;
}
return message;
}
protected void info(String messageString, String ... messages) {
String message = this.concatenate(messageString, messages);
this.logger.info(message);
}
protected void entering(String prefix) {
this.logger.entering(prefix);
}
protected void entering() {
this.logger.entering();
}
protected void exiting(String prefix) {
this.logger.exiting(prefix);
}
protected void exiting() {
this.logger.exiting();
}
protected void debug(String messageString, String ... messages) {
String message = this.concatenate(messageString, messages);
this.logger.debug(message);
}
protected void config(String parameterNameString, Object parameterValue) {
String parameterName = parameterNameString;
this.logger.config(parameterName, parameterValue);
}
protected void warning(String messageString, String ... messages) {
String message = this.concatenate(messageString, messages);
this.logger.warning(message);
}
protected void severe(String messageString, String ... messages) {
String message = this.concatenate(messageString, messages);
this.logger.severe(message);
}
protected void severe(Throwable t, String ... messages) {
String errorMessage = StringUtil.fromThrowableToString(t);
String message = this.concatenate(errorMessage, messages);
this.logger.severe(message);
}
}
|
/*
* Copyright 2016 camunda services GmbH.
*
* 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.camunda.bpm.engine.test.standalone.entity;
import java.util.ArrayList;
import java.util.List;
import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
/**
*
* @author Christopher Zell <christopher.zell@camunda.com>
*/
public class ExecutionEntityTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testRestoreProcessInstance() {
//given parent execution
List<ExecutionEntity> entities = new ArrayList<ExecutionEntity>();
ExecutionEntity parent = new ExecutionEntity();
parent.setId("parent");
entities.add(parent);
//when restore process instance is called
parent.restoreProcessInstance(entities, null, null, null, null, null, null);
//then no problem should occure
//when child is added and restore is called again
ExecutionEntity entity = new ExecutionEntity();
entity.setId("child");
entity.setParentId(parent.getId());
entities.add(entity);
parent.restoreProcessInstance(entities, null, null, null, null, null, null);
//then again no problem should occure
//when parent is deleted from the list
entities.remove(parent);
//then exception is thrown because child reference to parent which does not exist anymore
thrown.expect(ProcessEngineException.class);
thrown.expectMessage("Cannot resolve parent with id 'parent' of execution 'child', perhaps it was deleted in the meantime");
parent.restoreProcessInstance(entities, null, null, null, null, null, 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.ofbiz.accounting.thirdparty.valuelink;
import java.math.BigDecimal;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import javolution.util.FastMap;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.HttpClientException;
import org.ofbiz.base.util.StringUtil;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.collections.ResourceBundleMapWrapper;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.util.EntityUtil;
import org.ofbiz.entity.util.EntityUtilProperties;
import org.ofbiz.order.order.OrderReadHelper;
import org.ofbiz.product.store.ProductStoreWorker;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.GenericServiceException;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ModelService;
import org.ofbiz.service.ServiceUtil;
/**
* ValueLinkServices - Integration with ValueLink Gift Cards
*/
public class ValueLinkServices {
public static final String module = ValueLinkServices.class.getName();
public final static String resource = "AccountingUiLabels";
public final static String resourceError = "AccountingErrorUiLabels";
public final static String resourceOrder = "OrderUiLabels";
// generate/display new public/private/kek keys
public static Map<String, Object> createKeys(DispatchContext dctx, Map<String, Object> context) {
Delegator delegator = dctx.getDelegator();
Properties props = getProperties(context);
ValueLinkApi vl = ValueLinkApi.getInstance(delegator, props);
vl.reload();
Boolean kekOnly = context.get("kekOnly") != null ? (Boolean) context.get("kekOnly") : Boolean.FALSE;
String kekTest = (String) context.get("kekTest");
Debug.logInfo("KEK Only : " + kekOnly.booleanValue(), module);
StringBuffer buf = vl.outputKeyCreation(kekOnly.booleanValue(), kekTest);
String output = buf.toString();
Debug.logInfo(":: Key Generation Output ::\n\n" + output, module);
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("output", output);
return result;
}
// test the KEK encryption
public static Map<String, Object> testKekEncryption(DispatchContext dctx, Map<String, Object> context) {
Delegator delegator = dctx.getDelegator();
//GenericValue userLogin = (GenericValue) context.get("userLogin");
Properties props = getProperties(context);
// get an api instance
ValueLinkApi vl = ValueLinkApi.getInstance(delegator, props);
vl.reload();
String testString = (String) context.get("kekTest");
Integer mode = (Integer) context.get("mode");
byte[] testBytes = StringUtil.fromHexString(testString);
// place holder
byte[] testEncryption = null;
String desc = "";
if (mode.intValue() == 1) {
// encrypt the test bytes
testEncryption = vl.encryptViaKek(testBytes);
desc = "Encrypted";
} else {
// decrypt the test bytes
testEncryption = vl.decryptViaKek(testBytes);
desc = "Decrypted";
}
// setup the output
StringBuilder buf = new StringBuilder();
buf.append("======== Begin Test String (").append(testString.length()).append(") ========\n");
buf.append(testString).append("\n");
buf.append("======== End Test String ========\n\n");
buf.append("======== Begin Test Bytes (").append(testBytes.length).append(") ========\n");
buf.append(StringUtil.toHexString(testBytes)).append("\n");
buf.append("======== End Test Bytes ========\n\n");
buf.append("======== Begin Test Bytes ").append(desc).append(" (").append(testEncryption.length).append(") ========\n");
buf.append(StringUtil.toHexString(testEncryption)).append("\n");
buf.append("======== End Test Bytes ").append(desc).append(" ========\n\n");
String output = buf.toString();
Debug.logInfo(":: KEK Test Output ::\n\n" + output, module);
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("output", output);
return result;
}
// change working key service
public static Map<String, Object> assignWorkingKey(DispatchContext dctx, Map<String, Object> context) {
Delegator delegator = dctx.getDelegator();
GenericValue userLogin = (GenericValue) context.get("userLogin");
Properties props = getProperties(context);
Locale locale = (Locale) context.get("locale");
// get an api instance
ValueLinkApi vl = ValueLinkApi.getInstance(delegator, props);
vl.reload();
// place holder
byte[] mwk = null;
// see if we passed in the DES hex string
String desHexString = (String) context.get("desHexString");
if (UtilValidate.isEmpty(desHexString)) {
mwk = vl.generateMwk();
} else {
mwk = vl.generateMwk(StringUtil.fromHexString(desHexString));
}
// encrypt the mwk
String mwkHex = StringUtil.toHexString(vl.encryptViaKek(mwk));
// build the request
Map<String, Object> request = vl.getInitialRequestMap(context);
request.put("Interface", "Encrypt");
request.put("EncryptKey", mwkHex);
request.put("EncryptID", Long.valueOf(vl.getWorkingKeyIndex().longValue() + 1));
// send the request
Map<String, Object> response = null;
try {
response = vl.send(request);
} catch (HttpClientException e) {
Debug.logError(e, "Problem communicating with VL");
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkCannotUpdateWorkingKey", locale));
}
Debug.logInfo("Response : " + response, module);
// on success update the database / reload the cached api
if (response != null) {
String responseCode = (String) response.get("responsecode");
if (responseCode.equals("00")) {
GenericValue vlKeys = GenericValue.create(vl.getGenericValue());
vlKeys.set("lastWorkingKey", vlKeys.get("workingKey"));
vlKeys.set("workingKey", StringUtil.toHexString(mwk));
vlKeys.set("workingKeyIndex", request.get("EncryptID"));
vlKeys.set("lastModifiedDate", UtilDateTime.nowTimestamp());
vlKeys.set("lastModifiedByUserLogin", userLogin != null ? userLogin.get("userLoginId") : null);
try {
vlKeys.store();
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to store updated keys; the keys were changed with ValueLink : " + vlKeys, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkCannotStoreWorkingKey", locale));
}
vl.reload();
return ServiceUtil.returnSuccess();
} else {
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkTransactionFailed",
UtilMisc.toMap("responseCode", responseCode), locale));
}
} else {
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkReceivedEmptyResponse", locale));
}
}
public static Map<String, Object> activate(DispatchContext dctx, Map<String, Object> context) {
Delegator delegator = dctx.getDelegator();
Properties props = getProperties(context);
String vlPromoCode = (String) context.get("vlPromoCode");
String cardNumber = (String) context.get("cardNumber");
String pin = (String) context.get("pin");
String currency = (String) context.get("currency");
String orderId = (String) context.get("orderId");
String partyId = (String) context.get("partyId");
BigDecimal amount = (BigDecimal) context.get("amount");
Locale locale = (Locale) context.get("locale");
// override interface for void/rollback
String iFace = (String) context.get("Interface");
// get an api instance
ValueLinkApi vl = ValueLinkApi.getInstance(delegator, props);
Map<String, Object> request = vl.getInitialRequestMap(context);
request.put("Interface", iFace != null ? iFace : "Activate");
if (UtilValidate.isNotEmpty(vlPromoCode)) {
request.put("PromoCode", vlPromoCode);
}
request.put("Amount", vl.getAmount(amount));
request.put("LocalCurr", vl.getCurrency(currency));
if (UtilValidate.isNotEmpty(cardNumber)) {
request.put("CardNo", cardNumber);
}
if (UtilValidate.isNotEmpty(pin)) {
request.put("PIN", vl.encryptPin(pin));
}
// user defined field #1
if (UtilValidate.isNotEmpty(orderId)) {
request.put("User1", orderId);
}
// user defined field #2
if (UtilValidate.isNotEmpty(partyId)) {
request.put("User2", partyId);
}
// set the timeout reversal
setTimeoutReversal(dctx, context, request);
// send the request
Map<String, Object> response = null;
try {
response = vl.send(request);
} catch (HttpClientException e) {
Debug.logError(e, "Problem communicating with VL");
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkUnableToActivateGiftCard", locale));
}
if (response != null) {
String responseCode = (String) response.get("responsecode");
Map<String, Object> result = ServiceUtil.returnSuccess();
if (responseCode.equals("00")) {
result.put("processResult", Boolean.TRUE);
result.put("pin", vl.decryptPin((String) response.get("pin")));
} else {
result.put("processResult", Boolean.FALSE);
result.put("pin", response.get("PIN"));
}
result.put("responseCode", responseCode);
result.put("authCode", response.get("authcode"));
result.put("cardNumber", response.get("cardno"));
result.put("amount", vl.getAmount((String) response.get("currbal")));
result.put("expireDate", response.get("expiredate"));
result.put("cardClass", response.get("cardclass"));
result.put("referenceNum", response.get("traceno"));
Debug.logInfo("Activate Result : " + result, module);
return result;
} else {
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkReceivedEmptyResponse", locale));
}
}
public static Map<String, Object> linkPhysicalCard(DispatchContext dctx, Map<String, Object> context) {
Delegator delegator = dctx.getDelegator();
Properties props = getProperties(context);
String virtualCard = (String) context.get("virtualCard");
String virtualPin = (String) context.get("virtualPin");
String physicalCard = (String) context.get("physicalCard");
String physicalPin = (String) context.get("physicalPin");
String partyId = (String) context.get("partyId");
Locale locale = (Locale) context.get("locale");
// get an api instance
ValueLinkApi vl = ValueLinkApi.getInstance(delegator, props);
Map<String, Object> request = vl.getInitialRequestMap(context);
request.put("Interface", "Link");
request.put("VCardNo", virtualCard);
request.put("VPIN", vl.encryptPin(virtualPin));
request.put("PCardNo", physicalCard);
request.put("PPIN", vl.encryptPin(physicalPin));
// user defined field #2
if (UtilValidate.isNotEmpty(partyId)) {
request.put("User2", partyId);
}
// send the request
Map<String, Object> response = null;
try {
response = vl.send(request);
} catch (HttpClientException e) {
Debug.logError(e, "Problem communicating with VL");
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkUnableToLinkGiftCard", locale));
}
if (response != null) {
String responseCode = (String) response.get("responsecode");
Map<String, Object> result = ServiceUtil.returnSuccess(UtilProperties.getMessage(resource,
"AccountingValueLinkGiftCardActivated", locale));
if (responseCode.equals("00")) {
result.put("processResult", Boolean.TRUE);
} else {
result.put("processResult", Boolean.FALSE);
}
result.put("responseCode", responseCode);
result.put("authCode", response.get("authcode"));
result.put("amount", vl.getAmount((String) response.get("newbal")));
result.put("expireDate", response.get("expiredate"));
result.put("cardClass", response.get("cardclass"));
result.put("referenceNum", response.get("traceno"));
Debug.logInfo("Link Result : " + result, module);
return result;
} else {
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkReceivedEmptyResponse", locale));
}
}
public static Map<String, Object> disablePin(DispatchContext dctx, Map<String, Object> context) {
Delegator delegator = dctx.getDelegator();
Properties props = getProperties(context);
String cardNumber = (String) context.get("cardNumber");
String pin = (String) context.get("pin");
String orderId = (String) context.get("orderId");
String partyId = (String) context.get("partyId");
BigDecimal amount = (BigDecimal) context.get("amount");
Locale locale = (Locale) context.get("locale");
// get an api instance
ValueLinkApi vl = ValueLinkApi.getInstance(delegator, props);
Map<String, Object> request = vl.getInitialRequestMap(context);
request.put("Interface", "Disable");
request.put("CardNo", cardNumber);
request.put("PIN", vl.encryptPin(pin));
request.put("Amount", vl.getAmount(amount));
// user defined field #1
if (UtilValidate.isNotEmpty(orderId)) {
request.put("User1", orderId);
}
// user defined field #2
if (UtilValidate.isNotEmpty(partyId)) {
request.put("User2", partyId);
}
// send the request
Map<String, Object> response = null;
try {
response = vl.send(request);
} catch (HttpClientException e) {
Debug.logError(e, "Problem communicating with VL");
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkUnableToDisablePin", locale));
}
if (response != null) {
String responseCode = (String) response.get("responsecode");
Map<String, Object> result = ServiceUtil.returnSuccess(UtilProperties.getMessage(resource,
"AccountingValueLinkPinDisabled", locale));
if (responseCode.equals("00")) {
result.put("processResult", Boolean.TRUE);
} else {
result.put("processResult", Boolean.FALSE);
}
result.put("responseCode", responseCode);
result.put("balance", vl.getAmount((String) response.get("currbal")));
result.put("expireDate", response.get("expiredate"));
result.put("cardClass", response.get("cardclass"));
result.put("referenceNum", response.get("traceno"));
Debug.logInfo("Disable Result : " + result, module);
return result;
} else {
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkReceivedEmptyResponse", locale));
}
}
public static Map<String, Object> redeem(DispatchContext dctx, Map<String, Object> context) {
Delegator delegator = dctx.getDelegator();
Properties props = getProperties(context);
String cardNumber = (String) context.get("cardNumber");
String pin = (String) context.get("pin");
String currency = (String) context.get("currency");
String orderId = (String) context.get("orderId");
String partyId = (String) context.get("partyId");
BigDecimal amount = (BigDecimal) context.get("amount");
Locale locale = (Locale) context.get("locale");
// override interface for void/rollback
String iFace = (String) context.get("Interface");
// get an api instance
ValueLinkApi vl = ValueLinkApi.getInstance(delegator, props);
Map<String, Object> request = vl.getInitialRequestMap(context);
request.put("Interface", iFace != null ? iFace : "Redeem");
request.put("CardNo", cardNumber);
request.put("PIN", vl.encryptPin(pin));
request.put("Amount", vl.getAmount(amount));
request.put("LocalCurr", vl.getCurrency(currency));
// user defined field #1
if (UtilValidate.isNotEmpty(orderId)) {
request.put("User1", orderId);
}
// user defined field #2
if (UtilValidate.isNotEmpty(partyId)) {
request.put("User2", partyId);
}
// set the timeout reversal
setTimeoutReversal(dctx, context, request);
// send the request
Map<String, Object> response = null;
try {
response = vl.send(request);
} catch (HttpClientException e) {
Debug.logError(e, "Problem communicating with VL");
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkUnableToRedeemGiftCard", locale));
}
if (response != null) {
String responseCode = (String) response.get("responsecode");
Map<String, Object> result = ServiceUtil.returnSuccess();
if (responseCode.equals("00")) {
result.put("processResult", Boolean.TRUE);
} else {
result.put("processResult", Boolean.FALSE);
}
result.put("responseCode", responseCode);
result.put("authCode", response.get("authcode"));
result.put("previousAmount", vl.getAmount((String) response.get("prevbal")));
result.put("amount", vl.getAmount((String) response.get("newbal")));
result.put("expireDate", response.get("expiredate"));
result.put("cardClass", response.get("cardclass"));
result.put("cashBack", vl.getAmount((String) response.get("cashback")));
result.put("referenceNum", response.get("traceno"));
Debug.logInfo("Redeem Result : " + result, module);
return result;
} else {
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkReceivedEmptyResponse", locale));
}
}
public static Map<String, Object> reload(DispatchContext dctx, Map<String, Object> context) {
Delegator delegator = dctx.getDelegator();
Properties props = getProperties(context);
String cardNumber = (String) context.get("cardNumber");
String pin = (String) context.get("pin");
String currency = (String) context.get("currency");
String orderId = (String) context.get("orderId");
String partyId = (String) context.get("partyId");
BigDecimal amount = (BigDecimal) context.get("amount");
Locale locale = (Locale) context.get("locale");
// override interface for void/rollback
String iFace = (String) context.get("Interface");
// get an api instance
ValueLinkApi vl = ValueLinkApi.getInstance(delegator, props);
Map<String, Object> request = vl.getInitialRequestMap(context);
request.put("Interface", iFace != null ? iFace : "Reload");
request.put("CardNo", cardNumber);
request.put("PIN", vl.encryptPin(pin));
request.put("Amount", vl.getAmount(amount));
request.put("LocalCurr", vl.getCurrency(currency));
// user defined field #1
if (UtilValidate.isNotEmpty(orderId)) {
request.put("User1", orderId);
}
// user defined field #2
if (UtilValidate.isNotEmpty(partyId)) {
request.put("User2", partyId);
}
// set the timeout reversal
setTimeoutReversal(dctx, context, request);
// send the request
Map<String, Object> response = null;
try {
response = vl.send(request);
} catch (HttpClientException e) {
Debug.logError(e, "Problem communicating with VL");
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkUnableToReloadGiftCard", locale));
}
if (response != null) {
String responseCode = (String) response.get("responsecode");
Map<String, Object> result = ServiceUtil.returnSuccess();
if (responseCode.equals("00")) {
result.put("processResult", Boolean.TRUE);
} else {
result.put("processResult", Boolean.FALSE);
}
result.put("responseCode", responseCode);
result.put("authCode", response.get("authcode"));
result.put("previousAmount", vl.getAmount((String) response.get("prevbal")));
result.put("amount", vl.getAmount((String) response.get("newbal")));
result.put("expireDate", response.get("expiredate"));
result.put("cardClass", response.get("cardclass"));
result.put("referenceNum", response.get("traceno"));
Debug.logInfo("Reload Result : " + result, module);
return result;
} else {
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkReceivedEmptyResponse", locale));
}
}
public static Map<String, Object> balanceInquire(DispatchContext dctx, Map<String, Object> context) {
Delegator delegator = dctx.getDelegator();
Properties props = getProperties(context);
String cardNumber = (String) context.get("cardNumber");
String pin = (String) context.get("pin");
String currency = (String) context.get("currency");
String orderId = (String) context.get("orderId");
String partyId = (String) context.get("partyId");
Locale locale = (Locale) context.get("locale");
// get an api instance
ValueLinkApi vl = ValueLinkApi.getInstance(delegator, props);
Map<String, Object> request = vl.getInitialRequestMap(context);
request.put("Interface", "Balance");
request.put("CardNo", cardNumber);
request.put("PIN", vl.encryptPin(pin));
request.put("LocalCurr", vl.getCurrency(currency));
// user defined field #1
if (UtilValidate.isNotEmpty(orderId)) {
request.put("User1", orderId);
}
// user defined field #2
if (UtilValidate.isNotEmpty(partyId)) {
request.put("User2", partyId);
}
// send the request
Map<String, Object> response = null;
try {
response = vl.send(request);
} catch (HttpClientException e) {
Debug.logError(e, "Problem communicating with VL");
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkUnableToCallBalanceInquiry", locale));
}
if (response != null) {
String responseCode = (String) response.get("responsecode");
Map<String, Object> result = ServiceUtil.returnSuccess();
if (responseCode.equals("00")) {
result.put("processResult", Boolean.TRUE);
} else {
result.put("processResult", Boolean.FALSE);
}
result.put("responseCode", responseCode);
result.put("balance", vl.getAmount((String) response.get("currbal")));
result.put("expireDate", response.get("expiredate"));
result.put("cardClass", response.get("cardclass"));
result.put("referenceNum", response.get("traceno"));
Debug.logInfo("Balance Result : " + result, module);
return result;
} else {
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkReceivedEmptyResponse", locale));
}
}
public static Map<String, Object> transactionHistory(DispatchContext dctx, Map<String, Object> context) {
Delegator delegator = dctx.getDelegator();
Properties props = getProperties(context);
String cardNumber = (String) context.get("cardNumber");
String pin = (String) context.get("pin");
String orderId = (String) context.get("orderId");
String partyId = (String) context.get("partyId");
Locale locale = (Locale) context.get("locale");
// get an api instance
ValueLinkApi vl = ValueLinkApi.getInstance(delegator, props);
Map<String, Object> request = vl.getInitialRequestMap(context);
request.put("Interface", "History");
request.put("CardNo", cardNumber);
request.put("PIN", vl.encryptPin(pin));
// user defined field #1
if (UtilValidate.isNotEmpty(orderId)) {
request.put("User1", orderId);
}
// user defined field #2
if (UtilValidate.isNotEmpty(partyId)) {
request.put("User2", partyId);
}
// send the request
Map<String, Object> response = null;
try {
response = vl.send(request);
} catch (HttpClientException e) {
Debug.logError(e, "Problem communicating with VL");
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkUnableToCallHistoryInquiry", locale));
}
if (response != null) {
String responseCode = (String) response.get("responsecode");
Map<String, Object> result = ServiceUtil.returnSuccess();
if (responseCode.equals("00")) {
result.put("processResult", Boolean.TRUE);
} else {
result.put("processResult", Boolean.FALSE);
}
result.put("responseCode", responseCode);
result.put("balance", vl.getAmount((String) response.get("currbal")));
result.put("history", response.get("history"));
result.put("expireDate", response.get("expiredate"));
result.put("cardClass", response.get("cardclass"));
result.put("referenceNum", response.get("traceno"));
Debug.logInfo("History Result : " + result, module);
return result;
} else {
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkReceivedEmptyResponse", locale));
}
}
public static Map<String, Object> refund(DispatchContext dctx, Map<String, Object> context) {
Delegator delegator = dctx.getDelegator();
Properties props = getProperties(context);
String cardNumber = (String) context.get("cardNumber");
String pin = (String) context.get("pin");
String currency = (String) context.get("currency");
String orderId = (String) context.get("orderId");
String partyId = (String) context.get("partyId");
BigDecimal amount = (BigDecimal) context.get("amount");
Locale locale = (Locale) context.get("locale");
// override interface for void/rollback
String iFace = (String) context.get("Interface");
// get an api instance
ValueLinkApi vl = ValueLinkApi.getInstance(delegator, props);
Map<String, Object> request = vl.getInitialRequestMap(context);
request.put("Interface", iFace != null ? iFace : "Refund");
request.put("CardNo", cardNumber);
request.put("PIN", vl.encryptPin(pin));
request.put("Amount", vl.getAmount(amount));
request.put("LocalCurr", vl.getCurrency(currency));
// user defined field #1
if (UtilValidate.isNotEmpty(orderId)) {
request.put("User1", orderId);
}
// user defined field #2
if (UtilValidate.isNotEmpty(partyId)) {
request.put("User2", partyId);
}
// set the timeout reversal
setTimeoutReversal(dctx, context, request);
// send the request
Map<String, Object> response = null;
try {
response = vl.send(request);
} catch (HttpClientException e) {
Debug.logError(e, "Problem communicating with VL");
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkUnableToRefundGiftCard", locale));
}
if (response != null) {
String responseCode = (String) response.get("responsecode");
Map<String, Object> result = ServiceUtil.returnSuccess();
if (responseCode.equals("00")) {
result.put("processResult", Boolean.TRUE);
} else {
result.put("processResult", Boolean.FALSE);
}
result.put("responseCode", responseCode);
result.put("authCode", response.get("authcode"));
result.put("previousAmount", vl.getAmount((String) response.get("prevbal")));
result.put("amount", vl.getAmount((String) response.get("newbal")));
result.put("expireDate", response.get("expiredate"));
result.put("cardClass", response.get("cardclass"));
result.put("referenceNum", response.get("traceno"));
Debug.logInfo("Refund Result : " + result, module);
return result;
} else {
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkReceivedEmptyResponse", locale));
}
}
public static Map<String, Object> voidRedeem(DispatchContext dctx, Map<String, Object> context) {
context.put("Interface", "Redeem/Void");
return redeem(dctx, context);
}
public static Map<String, Object> voidRefund(DispatchContext dctx, Map<String, Object> context) {
context.put("Interface", "Refund/Void");
return refund(dctx, context);
}
public static Map<String, Object> voidReload(DispatchContext dctx, Map<String, Object> context) {
context.put("Interface", "Reload/Void");
return reload(dctx, context);
}
public static Map<String, Object> voidActivate(DispatchContext dctx, Map<String, Object> context) {
context.put("Interface", "Activate/Void");
return activate(dctx, context);
}
public static Map<String, Object> timeOutReversal(DispatchContext dctx, Map<String, Object> context) {
String vlInterface = (String) context.get("Interface");
Locale locale = (Locale) context.get("locale");
Debug.logInfo("704 Interface : " + vlInterface, module);
if (vlInterface != null) {
if (vlInterface.startsWith("Activate")) {
if (vlInterface.equals("Activate/Rollback")) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkThisTransactionIsNotSupported", locale));
}
return activate(dctx, context);
} else if (vlInterface.startsWith("Redeem")) {
return redeem(dctx, context);
} else if (vlInterface.startsWith("Reload")) {
return reload(dctx, context);
} else if (vlInterface.startsWith("Refund")) {
return refund(dctx, context);
}
}
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkTransactionNotValid", locale));
}
// 0704 Timeout Reversal (Supports - Activate/Void, Redeem, Redeem/Void, Reload, Reload/Void, Refund, Refund/Void)
private static void setTimeoutReversal(DispatchContext dctx, Map<String, Object> ctx, Map<String, Object> request) {
String vlInterface = (String) request.get("Interface");
// clone the context
Map<String, Object> context = FastMap.newInstance();
context.putAll(ctx);
// append the rollback interface
if (!vlInterface.endsWith("Rollback")) {
context.put("Interface", vlInterface + "/Rollback");
} else {
// no need to re-run ourself we are persisted
return;
}
// set the old tx time and number
context.put("MerchTime", request.get("MerchTime"));
context.put("TermTxnNo", request.get("TermTxnNo"));
// Activate/Rollback is not supported by valuelink
if (!vlInterface.equals("Activate")) {
// create the listener
Debug.logInfo("Set 704 context : " + context, module);
try {
dctx.getDispatcher().addRollbackService("vlTimeOutReversal", context, false);
//dctx.getDispatcher().addCommitService("vlTimeOutReversal", context, false);
} catch (GenericServiceException e) {
Debug.logError(e, "Unable to setup 0704 Timeout Reversal", module);
}
}
}
private static Properties getProperties(Map<String, Object> context) {
String paymentProperties = (String) context.get("paymentConfig");
if (paymentProperties == null) {
paymentProperties = "payment.properties";
}
return UtilProperties.getProperties(paymentProperties);
}
// payment processing wrappers (process/release/refund)
public static Map<String, Object> giftCardProcessor(DispatchContext dctx, Map<String, Object> context) {
Delegator delegator = dctx.getDelegator();
LocalDispatcher dispatcher = dctx.getDispatcher();
GenericValue userLogin = (GenericValue) context.get("userLogin");
Locale locale = (Locale) context.get("locale");
GenericValue giftCard = (GenericValue) context.get("giftCard");
GenericValue party = (GenericValue) context.get("billToParty");
String paymentConfig = (String) context.get("paymentConfig");
String currency = (String) context.get("currency");
String orderId = (String) context.get("orderId");
BigDecimal amount = (BigDecimal) context.get("processAmount");
// make sure we have a currency
if (currency == null) {
currency = EntityUtilProperties.getPropertyValue("general.properties", "currency.uom.id.default", "USD", delegator);
}
Map<String, Object> redeemCtx = FastMap.newInstance();
redeemCtx.put("userLogin", userLogin);
redeemCtx.put("paymentConfig", paymentConfig);
redeemCtx.put("cardNumber", giftCard.get("cardNumber"));
redeemCtx.put("pin", giftCard.get("pinNumber"));
redeemCtx.put("currency", currency);
redeemCtx.put("orderId", orderId);
redeemCtx.put("partyId", party.get("partyId"));
redeemCtx.put("amount", amount);
// invoke the redeem service
Map<String, Object> redeemResult = null;
try {
redeemResult = dispatcher.runSync("redeemGiftCard", redeemCtx);
} catch (GenericServiceException e) {
Debug.logError(e, "Problem calling the redeem service", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkUnableToRedeemGiftCardFailure", locale));
}
Map<String, Object> result = ServiceUtil.returnSuccess();
if (redeemResult != null) {
Boolean processResult = (Boolean) redeemResult.get("processResult");
// confirm the amount redeemed; since VL does not error in insufficient funds
if (processResult.booleanValue()) {
BigDecimal previous = (BigDecimal) redeemResult.get("previousAmount");
if (previous == null) previous = BigDecimal.ZERO;
BigDecimal current = (BigDecimal) redeemResult.get("amount");
if (current == null) current = BigDecimal.ZERO;
BigDecimal redeemed = previous.subtract(current);
Debug.logInfo("Redeemed (" + amount + "): " + redeemed + " / " + previous + " : " + current, module);
if (redeemed.compareTo(amount) < 0) {
// we didn't redeem enough void the transaction and return false
Map<String, Object> voidResult = null;
try {
voidResult = dispatcher.runSync("voidRedeemGiftCard", redeemCtx);
} catch (GenericServiceException e) {
Debug.logError(e, module);
}
if (ServiceUtil.isError(voidResult)) {
return voidResult;
}
processResult = Boolean.FALSE;
amount = redeemed;
result.put("authMessage", "Gift card did not contain enough funds");
}
}
result.put("processAmount", amount);
result.put("authFlag", redeemResult.get("responseCode"));
result.put("authResult", processResult);
result.put("captureResult", processResult);
result.put("authCode", redeemResult.get("authCode"));
result.put("captureCode", redeemResult.get("authCode"));
result.put("authRefNum", redeemResult.get("referenceNum"));
result.put("captureRefNum", redeemResult.get("referenceNum"));
}
return result;
}
public static Map<String, Object> giftCardRelease(DispatchContext dctx, Map<String, Object> context) {
Delegator delegator = dctx.getDelegator();
LocalDispatcher dispatcher = dctx.getDispatcher();
GenericValue userLogin = (GenericValue) context.get("userLogin");
Locale locale = (Locale) context.get("locale");
GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
String paymentConfig = (String) context.get("paymentConfig");
String currency = (String) context.get("currency");
BigDecimal amount = (BigDecimal) context.get("releaseAmount");
// get the orderId for tracking
String orderId = paymentPref.getString("orderId");
// get the GiftCard VO
GenericValue giftCard = null;
try {
giftCard = paymentPref.getRelatedOne("GiftCard", false);
} catch (GenericEntityException e) {
Debug.logError("Unable to get GiftCard from OrderPaymentPreference", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
"AccountingGiftCerticateNumberCannotLocateItFromOrderPaymentPreference", locale));
}
if (giftCard == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkUnableToReleaseGiftCard", locale));
}
// make sure we have a currency
if (currency == null) {
currency = EntityUtilProperties.getPropertyValue("general.properties", "currency.uom.id.default", "USD", delegator);
}
Map<String, Object> redeemCtx = FastMap.newInstance();
redeemCtx.put("userLogin", userLogin);
redeemCtx.put("paymentConfig", paymentConfig);
redeemCtx.put("cardNumber", giftCard.get("cardNumber"));
redeemCtx.put("pin", giftCard.get("pinNumber"));
redeemCtx.put("currency", currency);
redeemCtx.put("orderId", orderId);
redeemCtx.put("amount", amount);
// invoke the void redeem service
Map<String, Object> redeemResult = null;
try {
redeemResult = dispatcher.runSync("voidRedeemGiftCard", redeemCtx);
} catch (GenericServiceException e) {
Debug.logError(e, "Problem calling the redeem service", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkUnableToRedeemGiftCardFailure", locale));
}
Map<String, Object> result = ServiceUtil.returnSuccess();
if (redeemResult != null) {
Boolean processResult = (Boolean) redeemResult.get("processResult");
result.put("releaseAmount", redeemResult.get("amount"));
result.put("releaseFlag", redeemResult.get("responseCode"));
result.put("releaseResult", processResult);
result.put("releaseCode", redeemResult.get("authCode"));
result.put("releaseRefNum", redeemResult.get("referenceNum"));
}
return result;
}
public static Map<String, Object> giftCardRefund(DispatchContext dctx, Map<String, Object> context) {
Delegator delegator = dctx.getDelegator();
LocalDispatcher dispatcher = dctx.getDispatcher();
GenericValue userLogin = (GenericValue) context.get("userLogin");
Locale locale = (Locale) context.get("locale");
GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
String paymentConfig = (String) context.get("paymentConfig");
String currency = (String) context.get("currency");
BigDecimal amount = (BigDecimal) context.get("refundAmount");
// get the orderId for tracking
String orderId = paymentPref.getString("orderId");
// get the GiftCard VO
GenericValue giftCard = null;
try {
giftCard = paymentPref.getRelatedOne("GiftCard", false);
} catch (GenericEntityException e) {
Debug.logError("Unable to get GiftCard from OrderPaymentPreference", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
"AccountingGiftCerticateNumberCannotLocateItFromOrderPaymentPreference", locale));
}
if (giftCard == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkUnableToReleaseGiftCard", locale));
}
// make sure we have a currency
if (currency == null) {
currency = EntityUtilProperties.getPropertyValue("general.properties", "currency.uom.id.default", "USD", delegator);
}
Map<String, Object> refundCtx = FastMap.newInstance();
refundCtx.put("userLogin", userLogin);
refundCtx.put("paymentConfig", paymentConfig);
refundCtx.put("cardNumber", giftCard.get("cardNumber"));
refundCtx.put("pin", giftCard.get("pinNumber"));
refundCtx.put("currency", currency);
refundCtx.put("orderId", orderId);
refundCtx.put("amount", amount);
// invoke the refund service
Map<String, Object> redeemResult = null;
try {
redeemResult = dispatcher.runSync("refundGiftCard", refundCtx);
} catch (GenericServiceException e) {
Debug.logError(e, "Problem calling the refund service", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkUnableToRefundGiftCardFailure", locale));
}
Map<String, Object> result = ServiceUtil.returnSuccess();
if (redeemResult != null) {
Boolean processResult = (Boolean) redeemResult.get("processResult");
result.put("refundAmount", redeemResult.get("amount"));
result.put("refundFlag", redeemResult.get("responseCode"));
result.put("refundResult", processResult);
result.put("refundCode", redeemResult.get("authCode"));
result.put("refundRefNum", redeemResult.get("referenceNum"));
}
return result;
}
// item fulfillment wrappers (purchase/reload)
public static Map<String, Object> giftCardPurchase(DispatchContext dctx, Map<String, Object> context) {
// this service should always be called via FULFILLMENT_EXTASYNC
LocalDispatcher dispatcher = dctx.getDispatcher();
Delegator delegator = dctx.getDelegator();
GenericValue userLogin = (GenericValue) context.get("userLogin");
GenericValue orderItem = (GenericValue) context.get("orderItem");
Locale locale = (Locale) context.get("locale");
// order ID for tracking
String orderId = orderItem.getString("orderId");
// the order header for store info
GenericValue orderHeader = null;
try {
orderHeader = orderItem.getRelatedOne("OrderHeader", false);
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to get OrderHeader from OrderItem",module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrder,
"OrderOrderNotFound", UtilMisc.toMap("orderId", orderId), locale));
}
// get the order read helper
OrderReadHelper orh = new OrderReadHelper(orderHeader);
// get the currency
String currency = orh.getCurrency();
// make sure we have a currency
if (currency == null) {
currency = EntityUtilProperties.getPropertyValue("general.properties", "currency.uom.id.default", "USD", delegator);
}
// get the product store
String productStoreId = null;
if (orderHeader != null) {
productStoreId = orh.getProductStoreId();
}
if (productStoreId == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
"AccountingGiftCerticateNumberCannotProcess", locale));
}
// payment config
GenericValue paymentSetting = ProductStoreWorker.getProductStorePaymentSetting(delegator, productStoreId, "GIFT_CARD", null, true);
String paymentConfig = null;
if (paymentSetting != null) {
paymentConfig = paymentSetting.getString("paymentPropertiesPath");
}
if (paymentConfig == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
"AccountingFinAccountSetting",
UtilMisc.toMap("productStoreId", productStoreId, "finAccountTypeId", "GIFT_CARD"), locale));
}
// party ID for tracking
GenericValue placingParty = orh.getPlacingParty();
String partyId = null;
if (placingParty != null) {
partyId = placingParty.getString("partyId");
}
// amount/quantity of the gift card(s)
BigDecimal amount = orderItem.getBigDecimal("unitPrice");
BigDecimal quantity = orderItem.getBigDecimal("quantity");
// the product entity needed for information
GenericValue product = null;
try {
product = orderItem.getRelatedOne("Product", false);
} catch (GenericEntityException e) {
Debug.logError("Unable to get Product from OrderItem", module);
}
if (product == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
"AccountingGiftCerticateNumberCannotFulfill", locale));
}
// get the productFeature type TYPE (VL promo code)
GenericValue typeFeature = null;
try {
Map<String, Object> fields = UtilMisc.toMap("productId", product.get("productId"), "productFeatureTypeId", "TYPE");
List<String> order = UtilMisc.toList("-fromDate");
List<GenericValue> featureAppls = delegator.findByAnd("ProductFeatureAndAppl", fields, order, true);
featureAppls = EntityUtil.filterByDate(featureAppls);
typeFeature = EntityUtil.getFirst(featureAppls);
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkUnableToGetFeatureType", locale));
}
if (typeFeature == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkFeatureTypeRequested",
UtilMisc.toMap("productId", product.get("productId")), locale));
}
// get the VL promo code
String promoCode = typeFeature.getString("idCode");
if (UtilValidate.isEmpty(promoCode)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkPromoCodeInvalid", locale));
}
// survey information
String surveyId = UtilProperties.getPropertyValue(paymentConfig, "payment.giftcert.purchase.surveyId");
// get the survey response
GenericValue surveyResponse = null;
try {
Map<String, Object> fields = UtilMisc.<String, Object>toMap("orderId", orderId,
"orderItemSeqId", orderItem.get("orderItemSeqId"), "surveyId", surveyId);
List<String> order = UtilMisc.toList("-responseDate");
List<GenericValue> responses = delegator.findByAnd("SurveyResponse", fields, order, false);
// there should be only one
surveyResponse = EntityUtil.getFirst(responses);
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
"AccountingGiftCerticateNumberCannotFulfill", locale));
}
// get the response answers
List<GenericValue> responseAnswers = null;
try {
responseAnswers = surveyResponse.getRelated("SurveyResponseAnswer", null, null, false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
"AccountingGiftCerticateNumberCannotFulfillFromSurveyAnswers", locale));
}
// make a map of answer info
Map<String, Object> answerMap = FastMap.newInstance();
if (responseAnswers != null) {
for (GenericValue answer : responseAnswers) {
GenericValue question = null;
try {
question = answer.getRelatedOne("SurveyQuestion", false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
"AccountingGiftCerticateNumberCannotFulfillFromSurveyAnswers", locale));
}
if (question != null) {
String desc = question.getString("description");
String ans = answer.getString("textResponse"); // only support text response types for now
answerMap.put(desc, ans);
}
}
}
// get the send to email address - key defined in properties file
String sendToKey = UtilProperties.getPropertyValue(paymentConfig, "payment.giftcert.purchase.survey.sendToEmail");
String sendToEmail = (String) answerMap.get(sendToKey);
// get the copyMe flag and set the order email address
String orderEmails = orh.getOrderEmailString();
String copyMeField = UtilProperties.getPropertyValue(paymentConfig, "payment.giftcert.purchase.survey.copyMe");
String copyMeResp = copyMeField != null ? (String) answerMap.get(copyMeField) : null;
boolean copyMe = (UtilValidate.isNotEmpty(copyMeField)
&& UtilValidate.isNotEmpty(copyMeResp) && "true".equalsIgnoreCase(copyMeResp)) ? true : false;
int qtyLoop = quantity.intValue();
for (int i = 0; i < qtyLoop; i++) {
// activate a gift card
Map<String, Object> activateCtx = FastMap.newInstance();
activateCtx.put("paymentConfig", paymentConfig);
activateCtx.put("vlPromoCode", promoCode);
activateCtx.put("currency", currency);
activateCtx.put("partyId", partyId);
activateCtx.put("orderId", orderId);
activateCtx.put("amount", amount);
activateCtx.put("userLogin", userLogin);
boolean failure = false;
Map<String, Object> activateResult = null;
try {
activateResult = dispatcher.runSync("activateGiftCard", activateCtx);
} catch (GenericServiceException e) {
Debug.logError(e, "Unable to activate gift card(s)", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkUnableToActivateGiftCard", locale));
}
Boolean processResult = (Boolean) activateResult.get("processResult");
if (activateResult == null || activateResult.containsKey(ModelService.ERROR_MESSAGE) || !processResult.booleanValue()) {
failure = true;
}
if (!failure) {
// set the void on rollback
try {
dispatcher.addRollbackService("voidActivateGiftCard", activateCtx, false);
} catch (GenericServiceException e) {
Debug.logError(e, "Unable to setup Activate/Void on error", module);
}
}
// create the fulfillment record
Map<String, Object> vlFulFill = FastMap.newInstance();
vlFulFill.put("typeEnumId", "GC_ACTIVATE");
vlFulFill.put("merchantId", UtilProperties.getPropertyValue(paymentConfig, "payment.valuelink.merchantId"));
vlFulFill.put("partyId", partyId);
vlFulFill.put("orderId", orderId);
vlFulFill.put("orderItemSeqId", orderItem.get("orderItemSeqId"));
vlFulFill.put("surveyResponseId", surveyResponse.get("surveyResponseId"));
vlFulFill.put("cardNumber", activateResult.get("cardNumber"));
vlFulFill.put("pinNumber", activateResult.get("pin"));
vlFulFill.put("amount", activateResult.get("amount"));
vlFulFill.put("responseCode", activateResult.get("responseCode"));
vlFulFill.put("referenceNum", activateResult.get("referenceNum"));
vlFulFill.put("authCode", activateResult.get("authCode"));
vlFulFill.put("userLogin", userLogin);
try {
dispatcher.runAsync("createGcFulFillmentRecord", vlFulFill, true);
} catch (GenericServiceException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
"AccountingGiftCerticateNumberCannotStoreFulfillmentInfo",
UtilMisc.toMap("errorString", e.toString() ), locale));
}
if (failure) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkUnableToActivateGiftCard", locale));
}
// add some information to the answerMap for the email
answerMap.put("cardNumber", activateResult.get("cardNumber"));
answerMap.put("pinNumber", activateResult.get("pin"));
answerMap.put("amount", activateResult.get("amount"));
// get the email setting for this email type
GenericValue productStoreEmail = null;
String emailType = "PRDS_GC_PURCHASE";
try {
productStoreEmail = delegator.findOne("ProductStoreEmailSetting", UtilMisc.toMap("productStoreId", productStoreId, "emailType", emailType), false);
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to get product store email setting for gift card purchase", module);
}
if (productStoreEmail == null) {
Debug.logError("No gift card purchase email setting found for this store; cannot send gift card information", module);
} else {
answerMap.put("locale", locale);
// set the bcc address(s)
String bcc = productStoreEmail.getString("bccAddress");
if (copyMe) {
if (UtilValidate.isNotEmpty(bcc)) {
bcc = bcc + "," + orderEmails;
} else {
bcc = orderEmails;
}
}
Map<String, Object> emailCtx = FastMap.newInstance();
String bodyScreenLocation = productStoreEmail.getString("bodyScreenLocation");
if (UtilValidate.isEmpty(bodyScreenLocation)) {
bodyScreenLocation = ProductStoreWorker.getDefaultProductStoreEmailScreenLocation(emailType);
}
emailCtx.put("bodyScreenUri", bodyScreenLocation);
emailCtx.put("bodyParameters", answerMap);
emailCtx.put("sendTo", sendToEmail);
emailCtx.put("contentType", productStoreEmail.get("contentType"));
emailCtx.put("sendFrom", productStoreEmail.get("fromAddress"));
emailCtx.put("sendCc", productStoreEmail.get("ccAddress"));
emailCtx.put("sendBcc", bcc);
emailCtx.put("subject", productStoreEmail.getString("subject"));
emailCtx.put("userLogin", userLogin);
// send off the email async so we will retry on failed attempts
try {
dispatcher.runAsync("sendMailFromScreen", emailCtx);
} catch (GenericServiceException e) {
Debug.logError(e, "Problem sending mail", module);
// this is fatal; we will rollback and try again later
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
"AccountingGiftCerticateNumberCannotSendEmailNotice",
UtilMisc.toMap("errorString", e.toString()), locale));
}
}
}
return ServiceUtil.returnSuccess();
}
public static Map<String, Object> giftCardReload(DispatchContext dctx, Map<String, Object> context) {
// this service should always be called via FULFILLMENT_EXTSYNC
LocalDispatcher dispatcher = dctx.getDispatcher();
Delegator delegator = dctx.getDelegator();
GenericValue userLogin = (GenericValue) context.get("userLogin");
GenericValue orderItem = (GenericValue) context.get("orderItem");
Locale locale = (Locale) context.get("locale");
// order ID for tracking
String orderId = orderItem.getString("orderId");
// the order header for store info
GenericValue orderHeader = null;
try {
orderHeader = orderItem.getRelatedOne("OrderHeader", false);
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to get OrderHeader from OrderItem",module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrder,
"OrderOrderNotFound", UtilMisc.toMap("orderId", orderId), locale));
}
// get the order read helper
OrderReadHelper orh = new OrderReadHelper(orderHeader);
// get the currency
String currency = orh.getCurrency();
// make sure we have a currency
if (currency == null) {
currency = EntityUtilProperties.getPropertyValue("general.properties", "currency.uom.id.default", "USD", delegator);
}
// get the product store
String productStoreId = null;
if (orderHeader != null) {
productStoreId = orh.getProductStoreId();
}
if (productStoreId == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
"AccountingGiftCerticateNumberCannotProcess",
UtilMisc.toMap("orderId", orderId), locale));
}
// payment config
GenericValue paymentSetting = ProductStoreWorker.getProductStorePaymentSetting(delegator, productStoreId, "GIFT_CARD", null, true);
String paymentConfig = null;
if (paymentSetting != null) {
paymentConfig = paymentSetting.getString("paymentPropertiesPath");
}
if (paymentConfig == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
"AccountingGiftCerticateNumberCannotGetPaymentConfiguration", locale));
}
// party ID for tracking
GenericValue placingParty = orh.getPlacingParty();
String partyId = null;
if (placingParty != null) {
partyId = placingParty.getString("partyId");
}
// amount of the gift card reload
BigDecimal amount = orderItem.getBigDecimal("unitPrice");
// survey information
String surveyId = UtilProperties.getPropertyValue(paymentConfig, "payment.giftcert.reload.surveyId");
// get the survey response
GenericValue surveyResponse = null;
try {
Map<String, Object> fields = UtilMisc.toMap("orderId", orderId,
"orderItemSeqId", orderItem.get("orderItemSeqId"), "surveyId", surveyId);
List<String> order = UtilMisc.toList("-responseDate");
List<GenericValue> responses = delegator.findByAnd("SurveyResponse", fields, order, false);
// there should be only one
surveyResponse = EntityUtil.getFirst(responses);
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
"AccountingGiftCerticateNumberCannotFulfill", locale));
}
// get the response answers
List<GenericValue> responseAnswers = null;
try {
responseAnswers = surveyResponse.getRelated("SurveyResponseAnswer", null, null, false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
"AccountingGiftCerticateNumberCannotFulfillFromSurveyAnswers", locale));
}
// make a map of answer info
Map<String, Object> answerMap = FastMap.newInstance();
if (responseAnswers != null) {
for (GenericValue answer : responseAnswers) {
GenericValue question = null;
try {
question = answer.getRelatedOne("SurveyQuestion", false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
"AccountingGiftCerticateNumberCannotFulfillFromSurveyAnswers", locale));
}
if (question != null) {
String desc = question.getString("description");
String ans = answer.getString("textResponse"); // only support text response types for now
answerMap.put(desc, ans);
}
}
}
String cardNumberKey = UtilProperties.getPropertyValue(paymentConfig, "payment.giftcert.reload.survey.cardNumber");
String pinNumberKey = UtilProperties.getPropertyValue(paymentConfig, "payment.giftcert.reload.survey.pinNumber");
String cardNumber = (String) answerMap.get(cardNumberKey);
String pinNumber = (String) answerMap.get(pinNumberKey);
// reload the gift card
Map<String, Object> reloadCtx = FastMap.newInstance();
reloadCtx.put("paymentConfig", paymentConfig);
reloadCtx.put("currency", currency);
reloadCtx.put("partyId", partyId);
reloadCtx.put("orderId", orderId);
reloadCtx.put("cardNumber", cardNumber);
reloadCtx.put("pin", pinNumber);
reloadCtx.put("amount", amount);
reloadCtx.put("userLogin", userLogin);
Map<String, Object> reloadResult = null;
try {
reloadResult = dispatcher.runSync("reloadGiftCard", reloadCtx);
} catch (GenericServiceException e) {
Debug.logError(e, "Unable to reload gift card", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkUnableToReloadGiftCard", locale));
}
// create the fulfillment record
Map<String, Object> vlFulFill = FastMap.newInstance();
vlFulFill.put("typeEnumId", "GC_RELOAD");
vlFulFill.put("merchantId", UtilProperties.getPropertyValue(paymentConfig, "payment.valuelink.merchantId"));
vlFulFill.put("partyId", partyId);
vlFulFill.put("orderId", orderId);
vlFulFill.put("orderItemSeqId", orderItem.get("orderItemSeqId"));
vlFulFill.put("surveyResponseId", surveyResponse.get("surveyResponseId"));
vlFulFill.put("cardNumber", cardNumber);
vlFulFill.put("pinNumber", pinNumber);
vlFulFill.put("amount", amount);
vlFulFill.put("responseCode", reloadResult.get("responseCode"));
vlFulFill.put("referenceNum", reloadResult.get("referenceNum"));
vlFulFill.put("authCode", reloadResult.get("authCode"));
vlFulFill.put("userLogin", userLogin);
try {
dispatcher.runAsync("createGcFulFillmentRecord", vlFulFill, true);
} catch (GenericServiceException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
"AccountingGiftCerticateNumberCannotStoreFulfillmentInfo", locale));
}
Boolean processResult = (Boolean) reloadResult.get("processResult");
if (reloadResult == null || reloadResult.containsKey(ModelService.ERROR_MESSAGE) || !processResult.booleanValue()) {
Debug.logError("Reload Failed Need to Refund : " + reloadResult, module);
// process the return
try {
Map<String, Object> refundCtx = UtilMisc.<String, Object>toMap("orderItem", orderItem,
"partyId", partyId, "userLogin", userLogin);
dispatcher.runAsync("refundGcPurchase", refundCtx, null, true, 300, true);
} catch (GenericServiceException e) {
Debug.logError(e, "ERROR! Unable to call create refund service; this failed reload will NOT be refunded", module);
}
String responseCode = "-1";
if (processResult != null) {
responseCode = (String) reloadResult.get("responseCode");
}
if ("17".equals(responseCode)) {
Debug.logError("Error code : " + responseCode + " : Max Balance Exceeded", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkUnableToRefundGiftCardMaxBalanceExceeded", locale));
} else {
Debug.logError("Error code : " + responseCode + " : Processing Error", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingValueLinkUnableToReloadGiftCardFailed", locale));
}
}
// add some information to the answerMap for the email
answerMap.put("processResult", reloadResult.get("processResult"));
answerMap.put("responseCode", reloadResult.get("responseCode"));
answerMap.put("previousAmount", reloadResult.get("previousAmount"));
answerMap.put("amount", reloadResult.get("amount"));
// get the email setting for this email type
GenericValue productStoreEmail = null;
String emailType = "PRDS_GC_RELOAD";
try {
productStoreEmail = delegator.findOne("ProductStoreEmailSetting", UtilMisc.toMap("productStoreId", productStoreId, "emailType", emailType), false);
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to get product store email setting for gift card purchase", module);
}
if (productStoreEmail == null) {
Debug.logError("No gift card purchase email setting found for this store; cannot send gift card information", module);
} else {
Map<String, Object> emailCtx = FastMap.newInstance();
answerMap.put("locale", locale);
String bodyScreenLocation = productStoreEmail.getString("bodyScreenLocation");
if (UtilValidate.isEmpty(bodyScreenLocation)) {
bodyScreenLocation = ProductStoreWorker.getDefaultProductStoreEmailScreenLocation(emailType);
}
emailCtx.put("bodyScreenUri", bodyScreenLocation);
emailCtx.put("bodyParameters", answerMap);
emailCtx.put("sendTo", orh.getOrderEmailString());
emailCtx.put("contentType", productStoreEmail.get("contentType"));
emailCtx.put("sendFrom", productStoreEmail.get("fromAddress"));
emailCtx.put("sendCc", productStoreEmail.get("ccAddress"));
emailCtx.put("sendBcc", productStoreEmail.get("bccAddress"));
emailCtx.put("subject", productStoreEmail.getString("subject"));
emailCtx.put("userLogin", userLogin);
// send off the email async so we will retry on failed attempts
try {
dispatcher.runAsync("sendMailFromScreen", emailCtx);
} catch (GenericServiceException e) {
Debug.logError(e, "Problem sending mail", module);
// this is fatal; we will rollback and try again later
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingGiftCerticateNumberCannotSendEmailNotice",
UtilMisc.toMap("errorString", e.toString()), locale));
}
}
return ServiceUtil.returnSuccess();
}
}
|
// Template Source: IBaseMethodCollectionPage.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests.extensions;
import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.concurrency.ICallback;
import com.microsoft.graph.models.extensions.ItemActivityStat;
import java.util.Arrays;
import java.util.EnumSet;
import com.microsoft.graph.requests.extensions.IDriveItemGetActivitiesByIntervalCollectionRequestBuilder;
import com.google.gson.JsonObject;
import com.microsoft.graph.http.IBaseCollectionPage;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The interface for the Drive Item Get Activities By Interval Collection Page.
*/
public interface IDriveItemGetActivitiesByIntervalCollectionPage extends IBaseCollectionPage<ItemActivityStat, IDriveItemGetActivitiesByIntervalCollectionRequestBuilder> {
}
|
package com.tomaximo.puroguramu.ijframe;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyVetoException;
import java.io.IOException;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import com.shoukaiseki.gui.flowlayout.ModifiedFlowLayout;
import com.shoukaiseki.gui.jtextpane.JTextPaneDoc;
import com.shoukaiseki.gui.owern.swing.ijframe.MusukoOwnerJnf;
import com.tomaximo.puroguramu.tuuyou.IconSigenn;
import com.tomaximo.tuuyouclass.KonntenntuOutToJInternalFrame;
public class PrintJyouhou extends MusukoOwnerJnf implements ScrollPaneConstants {
private JTextPaneDoc textPane;
private JLabel jl;
public JPopupMenu jPopupMenu = new JPopupMenu();
/**
*
*/
public PrintJyouhou() {
textPane = new JTextPaneDoc();
textPane.setCursor(new Cursor(Cursor.TEXT_CURSOR));
textPane.setText("信息输出窗口!");
textPane.setFont(new Font("宋体", Font.BOLD, 13));
textPane.setLayout(new ModifiedFlowLayout());// 加不加都感觉有效果,如果一段英文无空格就会出现不会自动换行
JScrollPane jsp = new JScrollPane(textPane);// 新建一个滚动条界面,将文本框传入
// 滚动条
jsp.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_AS_NEEDED);
jl = new JLabel("状态无异常!", SwingConstants.LEFT);
// Box box = Box.createVerticalBox(); // 竖结构
// box.add(jl1);
// box.add(Box.createVerticalStrut(8)); // 两行的间距
Box box2 = Box.createHorizontalBox(); // 横结构
box2.add(new JLabel("状态栏:", SwingConstants.LEFT));
box2.add(Box.createHorizontalStrut(8));// 间距
box2.add(jl);
box2.add(Box.createHorizontalStrut(8));// 间距
// box2.add(jb_insert);
jsp.setBorder(BorderFactory.createEtchedBorder());// 分界线
this.add(jsp, BorderLayout.CENTER);
this.add(box2, BorderLayout.SOUTH);
this.setSize(700, 500);
// 隐藏frame的标题栏,此功暂时关闭,以方便使用window事件
this.setLocation(200, 150);
this.setVisible(true);
this.setTitle("信息输出窗口!");
textPane.cleanText();
this.setResizable(true);
// this.setClosable(true);
this.setMaximizable(true);
this.setIconifiable(true);
setBorder(BorderFactory.createEmptyBorder());
jsp.setBorder(BorderFactory.createEmptyBorder());
box2.setBorder(BorderFactory.createEmptyBorder());
// textPane.setBackground(Color.red);
// jsp.setBackground(Color.red);
box2.setBackground(Color.red);
// this.getContentPane().setBackground(Color.red);
popupMenuInit();
textPane.add(jPopupMenu);
textPane.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent er) {
// 是否右键单击
if (er.getClickCount() == 1
&& SwingUtilities.isRightMouseButton(er)) {
jPopupMenu.show(textPane, er.getX(), er.getY());
}
}
});
}
/**
* 菜单初始化
*/
public void popupMenuInit() {
JMenuItem clear = new JMenuItem("清空 ",IconSigenn.CLEAR);
// JMenuItem item2 = new JMenuItem("编辑节点 ");
// JMenuItem item3 = new JMenuItem("删除节点 ");
jPopupMenu.add(clear);
// jPopupMenu.add(item2);
// jPopupMenu.add(item3);
clear.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
textPane.cleanText();
}
});
}
/**
*
*/
public void println(String konntenntu) {
println(konntenntu, false);
}
/**
*
*/
public void println(String konntenntu,boolean b) {
try {
textPane.addLastLine(konntenntu, b);
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void printLabel(String s){
jl.setText(s);
}
public void printLabel(int s){
jl.setText(Integer.toString(s));
}
public JTextPaneDoc getTextPane()
{
return this.textPane;
}
public void setTextPane(JTextPaneDoc jtpd){
this.textPane=jtpd;
}
}
|
package com.alibaba.edas.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DubboConsumer {
public static void main(String[] args) {
SpringApplication.run(DubboConsumer.class, args);
}
}
|
package com.example.nikosweather;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
|
package SeedingSubmission;
import battlecode.common.RobotController;
public class Helipad extends Building {
public Helipad(RobotController rc) {
super(rc);
}
}
|
/**
* TLS-Attacker - A Modular Penetration Testing Framework for TLS
*
* Copyright 2014-2022 Ruhr University Bochum, Paderborn University, Hackmanit GmbH
*
* Licensed under Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0.txt
*/
package de.rub.nds.tlsattacker.core.crypto.ec;
import java.math.BigInteger;
public class EllipticCurveGost2001SetC extends EllipticCurveOverF2m {
public EllipticCurveGost2001SetC() {
super(new BigInteger("70390085352083305199547718019018437841079516630045180471284346843705633502616"),
new BigInteger("32858"),
new BigInteger("70390085352083305199547718019018437841079516630045180471284346843705633502619"),
new BigInteger("0"),
new BigInteger("29818893917731240733471273240314769927240550812383695689146495261604565990247"),
new BigInteger("70390085352083305199547718019018437840920882647164081035322601458352298396601"));
}
}
|
package com.treasure_data.td_import.integration;
import java.io.IOException;
import org.junit.Ignore;
@Ignore
public class HeaderlessTSVFileGenerator extends TSVFileGenerator {
public HeaderlessTSVFileGenerator(String fileName, String[] header)
throws IOException {
super(fileName, header);
}
@Override
public void writeHeader() throws IOException {
// header-less
}
}
|
package xyz.ibat.flexibleindicator;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("xyz.ibat.flexibleindicator", appContext.getPackageName());
}
}
|
/*
Copyright (c) 2016 Robert Atkinson
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted (subject to the limitations in the disclaimer below) 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 Robert Atkinson nor the names of his contributors may be used to
endorse or promote products derived from this software without specific prior
written permission.
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS
LICENSE. 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 FITNESSFOR 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.
*/
package org.firstinspires.ftc.teamcode.test;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
@TeleOp(name="LED Testing", group="Test")
//@Disabled
public class TestLED extends LinearOpMode {
@Override
public void runOpMode() {
// Wait for the game to start (driver presses PLAY)
waitForStart();
// run until the end of the match (driver presses STOP)
while (opModeIsActive()&&!isStopRequested()) {
telemetry.addData("Distance","");
telemetry.update();
}
}
}
|
package uk.gov.ida.hub.config.data;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.util.concurrent.ListenableFuture;
import org.apache.http.client.methods.HttpGet;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import uk.gov.ida.hub.config.ConfigConfiguration;
import uk.gov.ida.hub.config.configuration.SelfServiceConfig;
import uk.gov.ida.hub.config.domain.remoteconfig.RemoteConfigCollection;
import uk.gov.ida.hub.config.domain.remoteconfig.RemoteMatchingServiceConfig;
import uk.gov.ida.hub.config.domain.remoteconfig.RemoteServiceProviderConfig;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.time.Instant;
import java.util.Date;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class S3ConfigSourceTest {
private static final String CERT_MSA_BANANA_ENCRYPTION = "MIIDFDCCAfwCCQDEj/3MbRb8jzANBgkqhkiG9w0BAQsFADBMMQswCQYDVQQGEwJVSzEPMA0GA1UEBwwGTG9uZG9uMQwwCgYDVQQKDANHRFMxHjAcBgNVBAMMFUJhbmFuYSBNU0EgRW5jcnlwdGlvbjAeFw0xOTA2MjgxNDI0MzFaFw0zOTA2MjgxNDI0MzFaMEwxCzAJBgNVBAYTAlVLMQ8wDQYDVQQHDAZMb25kb24xDDAKBgNVBAoMA0dEUzEeMBwGA1UEAwwVQmFuYW5hIE1TQSBFbmNyeXB0aW9uMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1FuGXjWgeNNJ7a5todg/+gQO+xKUf6/tJ0wIW4dHS1lEOnk3mWu5fCtyTbDG9O+O22EOqmxMzsF6Kl/U6qRhmqs8bmc5pW9AQ67JMlMYCmrLq/VhF2aQ9rZV/Dx9rd2xuU6IkJPWWryY6qFfNrh6CDHzFzM5y+iGAXNLj1Z0TY8J38hjgRWCjSq9XD8tYW3SFfsonMRm71CvLGNl0WQu3WEGMu4yDqQjH8QT7LF1IF3obSeUPJKDnVIKa5/7THu/Lrekon8LJ5BbBYeBvahqpbQbvf2UK+lEvgCOUupGoPjz6mQ97tjHXCtE04xMyDEkMFy2urnNv2e2eVuy0VHE4wIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQCacP1D5haveoTdwhxnWnCwgc6TFiMd4g5Io31bXOvwShmqcYoJ7t9gdD7ZiPMJPbcF/YGCCk/BSEUtvYOPaRJV7C3BIZEPnewoQXyhX1uKzSqsYFIssl7DyUuItnmLZCQ4+OHpp1JMprDaWoF5hk2TdgqSv/fNlxt0193ayLzV+Dt34LhaS/pwXEBG/WtmJW3fygEOnmqmL4SMfG6nvvd/pOxAUeMEnzct3lJ5j2Qv/c0k43fUsy267gIRz/dpB/zlEzA6uUnrCNVdz+1AVjzvo9kf7H/4cA348mnBnh/USbRoIXhPkbPp5GuD3Q2CHvAL+bqVcQVNAJr6HKl+OwC4";
private static final String CERT_MSA_BANANA_SIGNING = "MIIDDjCCAfYCCQCEmqzN+B9I0TANBgkqhkiG9w0BAQsFADBJMQswCQYDVQQGEwJVSzEPMA0GA1UEBwwGTG9uZG9uMQwwCgYDVQQKDANHRFMxGzAZBgNVBAMMEkJhbmFuYSBNU0EgU2lnbmluZzAeFw0xOTA2MjgxNDIzNDVaFw0zOTA2MjgxNDIzNDVaMEkxCzAJBgNVBAYTAlVLMQ8wDQYDVQQHDAZMb25kb24xDDAKBgNVBAoMA0dEUzEbMBkGA1UEAwwSQmFuYW5hIE1TQSBTaWduaW5nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwic0bJaHNqQNyZhFb2fE0ATFOWRO/DxDECeVLFsSyPbh0WUD4jVXJkvvSVK95DN1wdp63d0z02ErVgcMYaNnPI1Obpvl2MSWnJV33FGYOOCMDPgntigfRkrYVfTcEA4VmZ57r0tvmHGtCMUVo9CON9KA/FGBp1wnqLq89lQY2fmtk2wLxAWTjkcafKvkU2CLSrAZ6QAbJKCVMqeWyM2Fv6xxC2cUly+ygL/5wj21et9683tJDD3nAtt4wbfbYYXnGNCYJO86pK1Q3pZ+hLBDTmK0o73uVksqIFX64Qw5naYu9UztdgOZCNLwCfbdhFoThvmV+KWElHYTaSv38I91UwIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQBbu8Tmk3MuTS7kEHjxaQFSHIll1Ts9eM1cZarv2cNSayyvdevImf8MP3mtQKYtUTOaKlyYJ1MbI+Pi76NyyvUbCaeoP14R6FgSBe6fTrDgPiBe9+tIagBRkid0daV+h1S3M3Omwrvm/Ct7WfxbA+i4ioTHS6lLUgJVHxU1PyACrPdtdJfAk0pGmDEpm4rn9ZJYRhwfv4KiRf/bhxdcuvSwp5tQCFRwWzfoKoJF/54CKk/8Fo+oYqaNaiZ75/eaOCyXXsdvAFpLQpwn8OV6ASo1GisJL67PycSV6UMl8hGjz9ne8QlNz06Y/H+i4PJu1NLkM5QFShjhvywecuIzbqN3";
private static final String CERT_VSP_APPLE_SIGNING = "MIIDDDCCAfQCCQCJ/3Eyv/MZMDANBgkqhkiG9w0BAQsFADBIMQswCQYDVQQGEwJVSzEPMA0GA1UEBwwGTG9uZG9uMQwwCgYDVQQKDANHRFMxGjAYBgNVBAMMEUFwcGxlIFZTUCBTaWduaW5nMB4XDTE5MDYyODE0MTMzM1oXDTM5MDYyODE0MTMzM1owSDELMAkGA1UEBhMCVUsxDzANBgNVBAcMBkxvbmRvbjEMMAoGA1UECgwDR0RTMRowGAYDVQQDDBFBcHBsZSBWU1AgU2lnbmluZzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAN0MGCJFJ1nRvgD3Scgr3TdK365pvHp0i8x5G/XmVnXU8sdrr2EgY27UV6CNJI95aE5Tt90JHr/XCOTEdY9zsu5wCVizx7o3g/6LsrTNGDkiz8pLuvygOm2zr32m70qw2IXtuXjLEJwhqcWjWOL5Tx7szFrVfClXhQcCQwuYFe57449/makLqPSY9pUYAX9juaDYjcMjTtShJ9AVov3Z7j0KgAVNRLFG97EiniD0vglxs7L6wguU3QP0PC0iTSk83zTxoho76bcFDZDoFWs3LhLALUOchntjeSBbWC61EzIVWp7kA0JM6Kg8FW7zljE7MG+yVy+Qggqmxo+pTBi2LqkCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAF0MnpSXv0A0UJ+l2MN3A9kbg8T6m92blqiPrwnaTsj7tLAOCk6CY7V5X5No2LnQ5TB2mOzsaQ3a/YGP6TtaYaCnyZ4bkqVuviAwwNPj7QiKEJIi9/sVUcmVne/qPUozrcM/sz4L8+GhrgZjAwWWqDnEpdybQjqaOMB7kbTMiOL0psYDy7FRpU79+usUTns4ZQw21ucFRE10eMdbYkQYsHYM1TpzXhJnJ2YY4pSUgbHEibQoBAcK0YUErJDmUFukfsfa29T9DMS3R3RHeQQIBpEwTiThUxfAsrVX2R1xqoylLN9nhEi5Nhv+/n6ZZxN3FGw2ebzavowbDCsuyJxVPyg==";
private static final String CERT_VSP_BANANA_SIGNING = "MIIDDjCCAfYCCQC4nnLu8fPLIjANBgkqhkiG9w0BAQsFADBJMQswCQYDVQQGEwJVSzEPMA0GA1UEBwwGTG9uZG9uMQwwCgYDVQQKDANHRFMxGzAZBgNVBAMMEkJhbmFuYSBWU1AgU2lnbmluZzAeFw0xOTA2MjgxNDIyMjZaFw0zOTA2MjgxNDIyMjZaMEkxCzAJBgNVBAYTAlVLMQ8wDQYDVQQHDAZMb25kb24xDDAKBgNVBAoMA0dEUzEbMBkGA1UEAwwSQmFuYW5hIFZTUCBTaWduaW5nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3JmFyYO0pF6krivSlsJgpe9AMmr88FmUpShUquNUvQIe6tQtPp436azXLozlZXyPR+nJ6EfE6H/m5jhobwOuq7EGRKU2pjEwveTLB1qI1NOUCEBkv5ii9Bm+3xkiF840U15D8ftjr20VLcCDuyI/bbLqS4rDC7syaSeD6SN7k4ifRhIyfxaXBHts7m++6zKENisH+2laQ/GYNP2/TZHXvxS2CWXGgw5RDhY7LbOEZldU/PPlW8WkqCDgUFEdRa65Pe6c22zsPYMD+JsuIkW0bE0uceAY6ja5sNyEBkEZe/1A409O6+q6OhyTAtJ5ewcNSIx4L0eh5MM5AQ4zFTJRuwIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQBP4WBZufGxcGoKvZnyTTbprpbEA/pILC0pNK/7Dku3m1zR8zEpSehnbaWKWO9KpSvuak1Kp983BdczcJy/0zSml+RkN46yia65eebZniWFtJ32/TgpW2ALbqLjVCfr4h5OinPouf4yKCDpSvb8CtFsHCeHDh9EdWtoZzDgeFJqPADwP9/A6asyKIOVag5QuCUqlEpr7lcAWKWYb7eQsL105WdssOQF1R/W70x4TCbK72U0t3pRbBEab10JrjUpPscc+NnEKgz33zILTXjEO1FeEcdTGcs5AvwR2GIwAg2IBGZY/USyD6LKmvHS3tvyxWbM9qnw00Fr3Cl15ZpWzClK";
private static final String BUCKET_NAME = "s3BucketName";
private static final String OBJECT_KEY = "s3ObjectName";
private String selfServiceConfigEnabledJson = "{" +
" \"enabled\" : \"true\"," +
" \"cacheExpiry\" : \"5s\","+
" \"s3BucketName\": \""+BUCKET_NAME+"\"," +
" \"s3ObjectKey\": \""+OBJECT_KEY+"\"" +
"}";
private String selfServiceConfigDisabledJson = "{" +
" \"enabled\" : \"false\"" +
"}";
private String selfServiceConfigShortCacheJson = "{" +
" \"enabled\" : \"true\"," +
" \"cacheExpiry\" : \"1ms\","+
" \"s3BucketName\": \""+BUCKET_NAME+"\"," +
" \"s3ObjectKey\": \""+OBJECT_KEY+"\"" +
"}";
@Mock
private AmazonS3 s3Client;
@Mock
private S3Object s3Object;
@Mock
private S3Object s3Object2;
@Mock
private ObjectMetadata objectMetadata;
@Mock
private ObjectMetadata objectMetadata2;
@Mock
private ConfigConfiguration configConfiguration;
private ObjectMapper objectMapper;
@Before
public void setUp(){
objectMapper = new ObjectMapper();
}
@Test
/**
* Tests to make sure we can process the JSON to an object
*/
public void getRemoteConfigReturnsRemoteConfigCollection() throws Exception {
SelfServiceConfig selfServiceConfig = objectMapper.readValue(selfServiceConfigEnabledJson, SelfServiceConfig.class);
when(s3Client.getObject(new GetObjectRequest(BUCKET_NAME, OBJECT_KEY))).thenReturn(s3Object);
when(s3Object.getObjectContent()).thenReturn(getObjectStream("/remote-test-config.json"));
when(s3Object.getObjectMetadata()).thenReturn(objectMetadata);
when(objectMetadata.getLastModified()).thenReturn(new Date());
S3ConfigSource testSource = new S3ConfigSource(selfServiceConfig, s3Client, objectMapper);
RemoteConfigCollection result = testSource.getRemoteConfig();
Map<String, RemoteMatchingServiceConfig> msConfigs = result.getMatchingServiceAdapters();
assertThat(msConfigs.size()).isEqualTo(3);
assertThat(msConfigs.get("https://msa.bananaregistry.test.com").getName()).isEqualTo("Banana Registry MSA");
assertThat(msConfigs.get("https://msa.bananaregistry.test.com").getEncryptionCertificate()).contains(CERT_MSA_BANANA_ENCRYPTION);
assertThat(msConfigs.get("https://msa.bananaregistry.test.com").getSignatureVerificationCertificates().size()).isEqualTo(1);
assertThat(msConfigs.get("https://msa.bananaregistry.test.com").getSignatureVerificationCertificates().get(0)).contains(CERT_MSA_BANANA_SIGNING);
Map<String, RemoteServiceProviderConfig> spConfigs = result.getServiceProviders();
assertThat(spConfigs.size()).isEqualTo(3);
RemoteServiceProviderConfig spConfig2 = spConfigs.get("2");
assertThat(spConfig2.getName()).isEqualTo("Apple Registry VSP");
assertThat(spConfig2.getSignatureVerificationCertificates().size()).isEqualTo(1);
assertThat(spConfig2.getSignatureVerificationCertificates().get(0)).contains(CERT_VSP_APPLE_SIGNING);
RemoteServiceProviderConfig spConfig3 = spConfigs.get("3");
assertThat(spConfig3.getName()).isEqualTo("Banana Registry VSP");
assertThat(spConfig3.getSignatureVerificationCertificates().size()).isEqualTo(1);
assertThat(spConfig3.getSignatureVerificationCertificates().get(0)).contains(CERT_VSP_BANANA_SIGNING);
}
@Test
public void getRemoteConfigReturnsEmptyRemoteConfigWhenSelfServiceDisabled() throws IOException {
SelfServiceConfig selfServiceConfig = objectMapper.readValue(selfServiceConfigDisabledJson, SelfServiceConfig.class);
S3ConfigSource testSource = new S3ConfigSource(selfServiceConfig, null, objectMapper);
RemoteConfigCollection result = testSource.getRemoteConfig();
assertThat(result).isNotNull();
assertThat(result.getServiceProviders().size()).isEqualTo(0);
assertThat(result.getMatchingServiceAdapters().size()).isEqualTo(0);
assertThat(result.getConnectedServices().size()).isEqualTo(0);
}
@Test
public void getRemoteConfigReturnsCachedConfigWhenRepeatedlyCalled() throws IOException {
SelfServiceConfig selfServiceConfig = objectMapper.readValue(selfServiceConfigEnabledJson, SelfServiceConfig.class);
when(s3Client.getObject(new GetObjectRequest(BUCKET_NAME, OBJECT_KEY))).thenReturn(s3Object);
when(s3Object.getObjectContent()).thenReturn(getObjectStream("/remote-test-config.json"));
when(s3Object.getObjectMetadata()).thenReturn(objectMetadata);
when(objectMetadata.getLastModified()).thenReturn(new Date());
S3ConfigSource testSource = new S3ConfigSource(selfServiceConfig, s3Client, objectMapper);
RemoteConfigCollection result1 = testSource.getRemoteConfig();
RemoteConfigCollection result2 = testSource.getRemoteConfig();
verify(s3Object, times(1)).getObjectContent();
assertThat(result1 == result2);
}
@Test
public void getRemoteConfigOnlyRetrievesNewContentWhenLastModifiedChanges() throws Exception {
SelfServiceConfig selfServiceConfig = objectMapper.readValue(selfServiceConfigShortCacheJson, SelfServiceConfig.class);
when(s3Client.getObject(new GetObjectRequest(BUCKET_NAME, OBJECT_KEY))).thenReturn(s3Object);
when(s3Object.getObjectContent()).thenReturn(getObjectStream("/remote-test-config.json"));
when(s3Object.getObjectMetadata()).thenReturn(objectMetadata);
when(objectMetadata.getLastModified()).thenReturn(Date.from(Instant.now().minusMillis(10000)));
S3ConfigSource testSource = new S3ConfigSource(selfServiceConfig, s3Client, objectMapper);
var testCacheLoader = testSource.getCacheLoader();
RemoteConfigCollection result1 = testSource.getRemoteConfig();
ListenableFuture<RemoteConfigCollection> task = testCacheLoader.reload("test", result1);
while(!task.isDone()){
Thread.yield();
}
RemoteConfigCollection result2 = task.get();
assertThat((result1 == result2)).isTrue();
verify(s3Object, times(1)).getObjectContent();
when(s3Client.getObject(any(GetObjectRequest.class))).thenReturn(s3Object2);
when(s3Object2.getObjectMetadata()).thenReturn(objectMetadata2);
when(s3Object2.getObjectContent()).thenReturn(getObjectStream("/remote-test-config.json"));
when(objectMetadata2.getLastModified()).thenReturn(Date.from(Instant.now()));
ListenableFuture<RemoteConfigCollection> task2 = testCacheLoader.reload("test", result1);
while(!task2.isDone()){
Thread.yield();
}
verify(s3Object2, times(1)).getObjectContent();
verify(objectMetadata2, times(1)).getLastModified();
}
private S3ObjectInputStream getObjectStream(String resource) throws FileNotFoundException {
URL url = this.getClass().getResource(resource);
File initialFile = new File(url.getFile());
InputStream testStream = new FileInputStream(initialFile);
return new S3ObjectInputStream(testStream, new HttpGet());
}
}
|
/*
* 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.aliyuncs.slb.transform.v20140515;
import java.util.ArrayList;
import java.util.List;
import com.aliyuncs.slb.model.v20140515.DescribeCACertificatesResponse;
import com.aliyuncs.slb.model.v20140515.DescribeCACertificatesResponse.CACertificate;
import com.aliyuncs.slb.model.v20140515.DescribeCACertificatesResponse.CACertificate.Tag;
import com.aliyuncs.transform.UnmarshallerContext;
public class DescribeCACertificatesResponseUnmarshaller {
public static DescribeCACertificatesResponse unmarshall(DescribeCACertificatesResponse describeCACertificatesResponse, UnmarshallerContext context) {
describeCACertificatesResponse.setRequestId(context.stringValue("DescribeCACertificatesResponse.RequestId"));
List<CACertificate> cACertificates = new ArrayList<CACertificate>();
for (int i = 0; i < context.lengthValue("DescribeCACertificatesResponse.CACertificates.Length"); i++) {
CACertificate cACertificate = new CACertificate();
cACertificate.setRegionId(context.stringValue("DescribeCACertificatesResponse.CACertificates["+ i +"].RegionId"));
cACertificate.setCACertificateId(context.stringValue("DescribeCACertificatesResponse.CACertificates["+ i +"].CACertificateId"));
cACertificate.setCACertificateName(context.stringValue("DescribeCACertificatesResponse.CACertificates["+ i +"].CACertificateName"));
cACertificate.setFingerprint(context.stringValue("DescribeCACertificatesResponse.CACertificates["+ i +"].Fingerprint"));
cACertificate.setResourceGroupId(context.stringValue("DescribeCACertificatesResponse.CACertificates["+ i +"].ResourceGroupId"));
cACertificate.setCreateTime(context.stringValue("DescribeCACertificatesResponse.CACertificates["+ i +"].CreateTime"));
cACertificate.setCreateTimeStamp(context.longValue("DescribeCACertificatesResponse.CACertificates["+ i +"].CreateTimeStamp"));
cACertificate.setExpireTime(context.stringValue("DescribeCACertificatesResponse.CACertificates["+ i +"].ExpireTime"));
cACertificate.setExpireTimeStamp(context.longValue("DescribeCACertificatesResponse.CACertificates["+ i +"].ExpireTimeStamp"));
cACertificate.setCommonName(context.stringValue("DescribeCACertificatesResponse.CACertificates["+ i +"].CommonName"));
List<Tag> tags = new ArrayList<Tag>();
for (int j = 0; j < context.lengthValue("DescribeCACertificatesResponse.CACertificates["+ i +"].Tags.Length"); j++) {
Tag tag = new Tag();
tag.setTagKey(context.stringValue("DescribeCACertificatesResponse.CACertificates["+ i +"].Tags["+ j +"].TagKey"));
tag.setTagValue(context.stringValue("DescribeCACertificatesResponse.CACertificates["+ i +"].Tags["+ j +"].TagValue"));
tags.add(tag);
}
cACertificate.setTags(tags);
cACertificates.add(cACertificate);
}
describeCACertificatesResponse.setCACertificates(cACertificates);
return describeCACertificatesResponse;
}
}
|
package com.ctrip.soa.artemis.cluster;
/**
* Created by Qiang Zhao on 10/07/2016.
*/
public interface NodeInitializer {
public enum TargetType {
REGISTRY, DISCOVERY
}
TargetType target();
boolean initialize();
}
|
package com.sms.model;
import com.sms.model.course.StdDTO;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
//TODO: Yara - should be moved to /model/course/
public class AttendanceDTO {
//TODO: Yara - should be attendanceDate - remember to change model in Angular too
private Date attendanceData;
private List<StdDTO> students = new ArrayList<>();
private int attendCount ;
private int totalStd ;
public int getTotalStd() {
return totalStd;
}
public void setTotalStd(int totalStd) {
this.totalStd = totalStd;
}
public AttendanceDTO() {
}
public int getAttendCount() {
return attendCount;
}
public void setAttendCount(int attendCount) {
this.attendCount = attendCount;
}
public Date getAttendanceData() {
return attendanceData;
}
public void setAttendanceData(Date attendanceData) {
this.attendanceData = attendanceData;
}
public List<StdDTO> getStudents() {
return students;
}
public void setStudents(List<StdDTO> students) {
this.students = students;
}
@Override
public String toString() {
return "\nAttendanceDTO{" +
"attendanceData=" + attendanceData +
", students=" + students +
'}';
}
}
|
package nieltg.ev3cube;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest
{
@Test
public void addition_isCorrect () throws Exception
{
assertEquals (4, 2 + 2);
}
}
|
package io.lacuna.bifurcan.durable;
import io.lacuna.bifurcan.DurableInput;
import io.lacuna.bifurcan.DurableOutput;
import java.util.Objects;
import static io.lacuna.bifurcan.durable.BlockPrefix.BlockType.*;
import static io.lacuna.bifurcan.durable.Encodings.readPrefixedUVLQ;
import static io.lacuna.bifurcan.durable.Encodings.writePrefixedUVLQ;
public class BlockPrefix {
public enum BlockType {
// root (2 bits)
PRIMITIVE,
TABLE,
DIFF, // continuation
COLLECTION, // continuation
// 3 bits preceded by COLLECTION
HASH_MAP,
SORTED_MAP,
HASH_SET,
SORTED_SET,
LIST,
COLLECTION_PLACEHOLDER_0,
COLLECTION_PLACEHOLDER_1,
EXTENDED, // continuation
// 3 bits preceded by DIFF
DIFF_HASH_MAP,
DIFF_SORTED_MAP,
DIFF_HASH_SET,
DIFF_SORTED_SET,
SLICE_LIST,
CONCAT_LIST,
DIFF_PLACEHOLDER_0,
DIFF_PLACEHOLDER_1,
// 3 bits preceded by COLLECTION and EXTENDED
DIRECTED_GRAPH,
DIRECTED_ACYCLIC_GRAPH,
UNDIRECTED_GRAPH,
EXTENDED_PLACEHOLDER_0,
EXTENDED_PLACEHOLDER_1,
EXTENDED_PLACEHOLDER_2,
EXTENDED_PLACEHOLDER_3,
EXTENDED_PLACEHOLDER_4,
}
private static final BlockType[] TYPES = BlockType.values();
public final long length;
public final BlockType type;
public BlockPrefix(long length, BlockType type) {
this.length = length;
this.type = type;
}
@Override
public int hashCode() {
return Objects.hash(length, type);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof BlockPrefix) {
BlockPrefix p = (BlockPrefix) obj;
return length == p.length
&& type == p.type;
}
return false;
}
@Override
public String toString() {
return "[ length=" + length + ", type=" + type + " ]";
}
public static BlockPrefix decode(DurableInput in) {
byte firstByte = in.readByte();
int root = (firstByte & 0b11000000) >> 6;
if (root < DIFF.ordinal()) {
return new BlockPrefix(readPrefixedUVLQ(firstByte, 2, in), TYPES[root]);
} else if (root == DIFF.ordinal()) {
int diff = (firstByte & 0b00111000) >> 3;
return new BlockPrefix(readPrefixedUVLQ(firstByte, 5, in), TYPES[diff + DIFF_HASH_MAP.ordinal()]);
} else {
int collection = (firstByte & 0b00111000) >> 3;
if (collection + HASH_MAP.ordinal() == EXTENDED.ordinal()) {
int extended = firstByte & 0b00000111;
return new BlockPrefix(in.readUVLQ(), TYPES[extended + DIRECTED_GRAPH.ordinal()]);
} else {
return new BlockPrefix(readPrefixedUVLQ(firstByte, 5, in), TYPES[collection + HASH_MAP.ordinal()]);
}
}
}
public void encode(DurableOutput out) {
if (type.ordinal() >= DIRECTED_GRAPH.ordinal()) {
out.writeByte(0b11111000 | (type.ordinal() - DIRECTED_GRAPH.ordinal()));
out.writeUVLQ(length);
} else if (type.ordinal() >= DIFF_HASH_MAP.ordinal()) {
writePrefixedUVLQ(0b10000 | (type.ordinal() - DIFF_HASH_MAP.ordinal()), 5, length, out);
} else if (type.ordinal() >= HASH_MAP.ordinal()) {
writePrefixedUVLQ(0b11000 | (type.ordinal() - HASH_MAP.ordinal()), 5, length, out);
} else {
writePrefixedUVLQ(type.ordinal(), 2, length, out);
}
}
}
|
package kashyapbhat.in.aep.Instructor.Model;
/**
* Created by Kashyap Bhat on 17/02/19.
*/
public class InstructorPojo {
private int qno;
private String ques;
private String keyword;
private int tolMarks;
private String text;
public InstructorPojo(int qno, String ques, String keyword, int tolMarks, String text) {
this.qno = qno;
this.ques = ques;
this.keyword = keyword;
this.tolMarks = tolMarks;
this.text = text;
}
public String getQues() {
return ques;
}
public void setQues(String ques) {
this.ques = ques;
}
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public int getTolMarks() {
return tolMarks;
}
public void setTolMarks(int tolMarks) {
this.tolMarks = tolMarks;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getQno() {
return qno;
}
public void setQno(int qno) {
this.qno = qno;
}
}
|
// Copyright 2016 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.model.registry.label;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static google.registry.model.common.EntityGroupRoot.getCrossTldKey;
import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.model.ofy.Ofy.RECOMMENDED_MEMCACHE_EXPIRATION;
import static google.registry.model.registry.label.ReservationType.FULLY_BLOCKED;
import static google.registry.model.registry.label.ReservationType.RESERVED_FOR_ANCHOR_TENANT;
import static google.registry.model.registry.label.ReservationType.UNRESERVED;
import static google.registry.util.CollectionUtils.nullToEmpty;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import com.google.common.base.Optional;
import com.google.common.base.Splitter;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.VoidWork;
import com.googlecode.objectify.annotation.Cache;
import com.googlecode.objectify.annotation.Embed;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Mapify;
import com.googlecode.objectify.mapper.Mapper;
import google.registry.config.RegistryEnvironment;
import google.registry.model.registry.Registry;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import javax.annotation.Nullable;
/**
* A reserved list entity, persisted to Datastore, that is used to check domain label reservations.
*/
@Entity
@Cache(expirationSeconds = RECOMMENDED_MEMCACHE_EXPIRATION)
public final class ReservedList
extends BaseDomainLabelList<ReservationType, ReservedList.ReservedListEntry> {
@Mapify(ReservedListEntry.LabelMapper.class)
Map<String, ReservedListEntry> reservedListMap;
boolean shouldPublish = true;
/**
* A reserved list entry entity, persisted to Datastore, that represents a single label and its
* reservation type.
*/
@Embed
public static class ReservedListEntry
extends DomainLabelEntry<ReservationType, ReservedListEntry> {
ReservationType reservationType;
/**
* Contains the auth code necessary to register a domain with this label.
* Note that this field will only ever be populated for entries with type
* RESERVED_FOR_ANCHOR_TENANT.
*/
String authCode;
/** Mapper for use with @Mapify */
static class LabelMapper implements Mapper<String, ReservedListEntry> {
@Override
public String getKey(ReservedListEntry entry) {
return entry.getLabel();
}
}
public static ReservedListEntry create(
String label,
ReservationType reservationType,
@Nullable String authCode,
String comment) {
if (authCode != null) {
checkArgument(reservationType == RESERVED_FOR_ANCHOR_TENANT,
"Only anchor tenant reservations should have an auth code configured");
} else {
checkArgument(reservationType != RESERVED_FOR_ANCHOR_TENANT,
"Anchor tenant reservations must have an auth code configured");
}
ReservedListEntry entry = new ReservedListEntry();
entry.label = label;
entry.reservationType = reservationType;
entry.authCode = authCode;
entry.comment = comment;
return entry;
}
@Override
public ReservationType getValue() {
return reservationType;
}
public String getAuthCode() {
return authCode;
}
}
@Override
protected boolean refersToKey(Registry registry, Key<? extends BaseDomainLabelList<?, ?>> key) {
return registry.getReservedLists().contains(key);
}
/** Determines whether the ReservedList is in use on any Registry */
public boolean isInUse() {
return !getReferencingTlds().isEmpty();
}
/**
* Returns whether this reserved list is included in the concatenated list of reserved terms
* published to Google Drive for viewing by registrars.
*/
public boolean getShouldPublish() {
return shouldPublish;
}
public ImmutableMap<String, ReservedListEntry> getReservedListEntries() {
return ImmutableMap.copyOf(nullToEmpty(reservedListMap));
}
/**
* Gets a ReservedList by name using the caching layer.
*
* @return An Optional<ReservedList> that has a value if a reserved list exists by the given
* name, or absent if not.
* @throws UncheckedExecutionException if some other error occurs while trying to load the
* ReservedList from the cache or Datastore.
*/
public static Optional<ReservedList> get(String listName) {
return getFromCache(listName, cache);
}
/** Loads a ReservedList from its Objectify key. */
public static Optional<ReservedList> load(Key<ReservedList> key) {
return get(key.getName());
}
/**
* Queries the set of all reserved lists associated with the specified tld and returns the
* reservation type of the first occurrence of label seen. If the label is in none of the lists,
* it returns UNRESERVED.
*/
public static ReservationType getReservation(String label, String tld) {
checkNotNull(label, "label");
if (label.length() == 0) {
return FULLY_BLOCKED;
}
ReservedListEntry entry = getReservedListEntry(label, tld);
return (entry != null) ? entry.reservationType : UNRESERVED;
}
/**
* Returns true if the given label and TLD is reserved for an anchor tenant, and the given
* auth code matches the one set on the reservation.
*/
public static boolean matchesAnchorTenantReservation(String label, String tld, String authCode) {
ReservedListEntry entry = getReservedListEntry(label, tld);
return entry != null
&& entry.reservationType == RESERVED_FOR_ANCHOR_TENANT
&& Objects.equals(entry.getAuthCode(), authCode);
}
/**
* Helper function to retrieve the entry associated with this label and TLD, or null if no such
* entry exists.
*/
@Nullable
private static ReservedListEntry getReservedListEntry(String label, String tld) {
Registry registry = Registry.get(checkNotNull(tld, "tld"));
ImmutableSet<Key<ReservedList>> reservedLists = registry.getReservedLists();
ImmutableSet<ReservedList> lists = loadReservedLists(reservedLists);
ReservedListEntry entry = null;
// Loop through all reservation lists and check each one for the inputted label, and return
// the most severe ReservationType found.
for (ReservedList rl : lists) {
Map<String, ReservedListEntry> entries = rl.getReservedListEntries();
ReservedListEntry nextEntry = entries.get(label);
if (nextEntry != null
&& (entry == null || nextEntry.reservationType.compareTo(entry.reservationType) > 0)) {
entry = nextEntry;
}
}
return entry;
}
private static ImmutableSet<ReservedList> loadReservedLists(
ImmutableSet<Key<ReservedList>> reservedListKeys) {
ImmutableSet.Builder<ReservedList> builder = new ImmutableSet.Builder<>();
for (Key<ReservedList> listKey : reservedListKeys) {
try {
builder.add(cache.get(listKey.getName()));
} catch (ExecutionException e) {
throw new UncheckedExecutionException(String.format(
"Could not load the reserved list '%s' from the cache", listKey.getName()), e);
}
}
return builder.build();
}
private static LoadingCache<String, ReservedList> cache = CacheBuilder
.newBuilder()
.expireAfterWrite(
RegistryEnvironment.get().config().getDomainLabelListCacheDuration().getMillis(),
MILLISECONDS)
.build(new CacheLoader<String, ReservedList>() {
@Override
public ReservedList load(String listName) {
return ofy().load().type(ReservedList.class).parent(getCrossTldKey()).id(listName).now();
}});
/** Deletes the ReservedList with the given name. */
public static void delete(final String listName) {
final ReservedList reservedList = ReservedList.get(listName).orNull();
checkState(
reservedList != null,
"Attempted to delete reserved list %s which doesn't exist",
listName);
ofy().transactNew(new VoidWork() {
@Override
public void vrun() {
ofy().delete().entity(reservedList).now();
}
});
cache.invalidate(listName);
}
/**
* Gets the {@link ReservationType} of a label in a single ReservedList, or returns an absent
* Optional if none exists in the list.
*
* <p>Note that this logic is significantly less complicated than the getReservation() methods,
* which are applicable to an entire Registry, and need to check across multiple reserved lists.
*/
public Optional<ReservationType> getReservationInList(String label) {
ReservedListEntry entry = getReservedListEntries().get(label);
return Optional.fromNullable(entry == null ? null : entry.reservationType);
}
@Override
@Nullable
ReservedListEntry createFromLine(String originalLine) {
List<String> lineAndComment = splitOnComment(originalLine);
if (lineAndComment.isEmpty()) {
return null;
}
String line = lineAndComment.get(0);
String comment = lineAndComment.get(1);
List<String> parts = Splitter.on(',').trimResults().splitToList(line);
checkArgument(parts.size() == 2 || parts.size() == 3,
"Could not parse line in reserved list: %s", originalLine);
String label = parts.get(0);
ReservationType reservationType = ReservationType.valueOf(parts.get(1));
String authCode = (parts.size() > 2) ? parts.get(2) : null;
return ReservedListEntry.create(label, reservationType, authCode, comment);
}
@Override
public Builder asBuilder() {
return new Builder(clone(this));
}
/**
* A builder for constructing {@link ReservedList} objects, since they are immutable.
*/
public static class Builder extends BaseDomainLabelList.Builder<ReservedList, Builder> {
public Builder() {}
private Builder(ReservedList instance) {
super(instance);
}
public Builder setReservedListMap(ImmutableMap<String, ReservedListEntry> reservedListMap) {
getInstance().reservedListMap = reservedListMap;
return this;
}
public Builder setShouldPublish(boolean shouldPublish) {
getInstance().shouldPublish = shouldPublish;
return this;
}
/**
* Updates the reservedListMap from input lines.
*
* @throws IllegalArgumentException if the lines cannot be parsed correctly.
*/
public Builder setReservedListMapFromLines(Iterable<String> lines) {
return setReservedListMap(getInstance().parse(lines));
}
}
}
|
package com.fr.swift.cloud.source.alloter;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fr.swift.cloud.source.alloter.impl.hash.HashAllotRule;
import com.fr.swift.cloud.source.alloter.impl.line.LineAllotRule;
/**
* @author anchore
* @date 2018/6/5
*/
@JsonIgnoreProperties("type")
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, defaultImpl = LineAllotRule.class)
@JsonSubTypes({
@JsonSubTypes.Type(value = LineAllotRule.class),
@JsonSubTypes.Type(value = HashAllotRule.class),
})
public interface AllotRule {
Type getType();
int getCapacity();
interface Type {
String name();
}
String getCubePath(int order);
}
|
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* gradle plugin from the resource data it found. It
* should not be modified by hand.
*/
package android.support.v4;
public final class R {
private R() {}
public static final class attr {
private attr() {}
public static final int alpha = 0x7f020027;
public static final int coordinatorLayoutStyle = 0x7f02006a;
public static final int font = 0x7f02007f;
public static final int fontProviderAuthority = 0x7f020081;
public static final int fontProviderCerts = 0x7f020082;
public static final int fontProviderFetchStrategy = 0x7f020083;
public static final int fontProviderFetchTimeout = 0x7f020084;
public static final int fontProviderPackage = 0x7f020085;
public static final int fontProviderQuery = 0x7f020086;
public static final int fontStyle = 0x7f020087;
public static final int fontVariationSettings = 0x7f020088;
public static final int fontWeight = 0x7f020089;
public static final int keylines = 0x7f020099;
public static final int layout_anchor = 0x7f02009c;
public static final int layout_anchorGravity = 0x7f02009d;
public static final int layout_behavior = 0x7f02009e;
public static final int layout_dodgeInsetEdges = 0x7f02009f;
public static final int layout_insetEdge = 0x7f0200a0;
public static final int layout_keyline = 0x7f0200a1;
public static final int statusBarBackground = 0x7f0200dc;
public static final int ttcIndex = 0x7f02010f;
}
public static final class color {
private color() {}
public static final int notification_action_color_filter = 0x7f040043;
public static final int notification_icon_bg_color = 0x7f040044;
public static final int notification_material_background_media_default_color = 0x7f040045;
public static final int primary_text_default_material_dark = 0x7f04004e;
public static final int ripple_material_light = 0x7f040053;
public static final int secondary_text_default_material_dark = 0x7f040055;
public static final int secondary_text_default_material_light = 0x7f040056;
}
public static final class dimen {
private dimen() {}
public static final int compat_button_inset_horizontal_material = 0x7f05004e;
public static final int compat_button_inset_vertical_material = 0x7f05004f;
public static final int compat_button_padding_horizontal_material = 0x7f050050;
public static final int compat_button_padding_vertical_material = 0x7f050051;
public static final int compat_control_corner_material = 0x7f050052;
public static final int compat_notification_large_icon_max_height = 0x7f050053;
public static final int compat_notification_large_icon_max_width = 0x7f050054;
public static final int notification_action_icon_size = 0x7f050064;
public static final int notification_action_text_size = 0x7f050065;
public static final int notification_big_circle_margin = 0x7f050066;
public static final int notification_content_margin_start = 0x7f050067;
public static final int notification_large_icon_height = 0x7f050068;
public static final int notification_large_icon_width = 0x7f050069;
public static final int notification_main_column_padding_top = 0x7f05006a;
public static final int notification_media_narrow_margin = 0x7f05006b;
public static final int notification_right_icon_size = 0x7f05006c;
public static final int notification_right_side_padding_top = 0x7f05006d;
public static final int notification_small_icon_background_padding = 0x7f05006e;
public static final int notification_small_icon_size_as_large = 0x7f05006f;
public static final int notification_subtext_size = 0x7f050070;
public static final int notification_top_pad = 0x7f050071;
public static final int notification_top_pad_large_text = 0x7f050072;
public static final int subtitle_corner_radius = 0x7f050073;
public static final int subtitle_outline_width = 0x7f050074;
public static final int subtitle_shadow_offset = 0x7f050075;
public static final int subtitle_shadow_radius = 0x7f050076;
}
public static final class drawable {
private drawable() {}
public static final int notification_action_background = 0x7f060055;
public static final int notification_bg = 0x7f060056;
public static final int notification_bg_low = 0x7f060057;
public static final int notification_bg_low_normal = 0x7f060058;
public static final int notification_bg_low_pressed = 0x7f060059;
public static final int notification_bg_normal = 0x7f06005a;
public static final int notification_bg_normal_pressed = 0x7f06005b;
public static final int notification_icon_background = 0x7f06005c;
public static final int notification_template_icon_bg = 0x7f06005d;
public static final int notification_template_icon_low_bg = 0x7f06005e;
public static final int notification_tile_bg = 0x7f06005f;
public static final int notify_panel_notification_icon_bg = 0x7f060060;
}
public static final class id {
private id() {}
public static final int action0 = 0x7f070006;
public static final int action_container = 0x7f07000e;
public static final int action_divider = 0x7f070010;
public static final int action_image = 0x7f070011;
public static final int action_text = 0x7f070017;
public static final int actions = 0x7f070018;
public static final int async = 0x7f07001e;
public static final int blocking = 0x7f070020;
public static final int bottom = 0x7f070021;
public static final int cancel_action = 0x7f070023;
public static final int chronometer = 0x7f070028;
public static final int end = 0x7f070038;
public static final int end_padder = 0x7f070039;
public static final int forever = 0x7f07003f;
public static final int icon = 0x7f070044;
public static final int icon_group = 0x7f070045;
public static final int info = 0x7f070048;
public static final int italic = 0x7f070049;
public static final int left = 0x7f07004a;
public static final int line1 = 0x7f07004b;
public static final int line3 = 0x7f07004c;
public static final int media_actions = 0x7f07004f;
public static final int none = 0x7f070059;
public static final int normal = 0x7f07005a;
public static final int notification_background = 0x7f07005b;
public static final int notification_main_column = 0x7f07005c;
public static final int notification_main_column_container = 0x7f07005d;
public static final int right = 0x7f070062;
public static final int right_icon = 0x7f070063;
public static final int right_side = 0x7f070064;
public static final int start = 0x7f07007d;
public static final int status_bar_latest_event_content = 0x7f07007e;
public static final int tag_transition_group = 0x7f070082;
public static final int tag_unhandled_key_event_manager = 0x7f070083;
public static final int tag_unhandled_key_listeners = 0x7f070084;
public static final int text = 0x7f070085;
public static final int text2 = 0x7f070086;
public static final int time = 0x7f070089;
public static final int title = 0x7f07008a;
public static final int top = 0x7f07008d;
}
public static final class integer {
private integer() {}
public static final int cancel_button_image_alpha = 0x7f080002;
public static final int status_bar_notification_info_maxnum = 0x7f080004;
}
public static final class layout {
private layout() {}
public static final int notification_action = 0x7f09001f;
public static final int notification_action_tombstone = 0x7f090020;
public static final int notification_media_action = 0x7f090021;
public static final int notification_media_cancel_action = 0x7f090022;
public static final int notification_template_big_media = 0x7f090023;
public static final int notification_template_big_media_custom = 0x7f090024;
public static final int notification_template_big_media_narrow = 0x7f090025;
public static final int notification_template_big_media_narrow_custom = 0x7f090026;
public static final int notification_template_custom_big = 0x7f090027;
public static final int notification_template_icon_group = 0x7f090028;
public static final int notification_template_lines_media = 0x7f090029;
public static final int notification_template_media = 0x7f09002a;
public static final int notification_template_media_custom = 0x7f09002b;
public static final int notification_template_part_chronometer = 0x7f09002c;
public static final int notification_template_part_time = 0x7f09002d;
}
public static final class string {
private string() {}
public static final int status_bar_notification_info_overflow = 0x7f0b0036;
}
public static final class style {
private style() {}
public static final int TextAppearance_Compat_Notification = 0x7f0c00f2;
public static final int TextAppearance_Compat_Notification_Info = 0x7f0c00f3;
public static final int TextAppearance_Compat_Notification_Info_Media = 0x7f0c00f4;
public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0c00f5;
public static final int TextAppearance_Compat_Notification_Line2_Media = 0x7f0c00f6;
public static final int TextAppearance_Compat_Notification_Media = 0x7f0c00f7;
public static final int TextAppearance_Compat_Notification_Time = 0x7f0c00f8;
public static final int TextAppearance_Compat_Notification_Time_Media = 0x7f0c00f9;
public static final int TextAppearance_Compat_Notification_Title = 0x7f0c00fa;
public static final int TextAppearance_Compat_Notification_Title_Media = 0x7f0c00fb;
public static final int Widget_Compat_NotificationActionContainer = 0x7f0c0163;
public static final int Widget_Compat_NotificationActionText = 0x7f0c0164;
public static final int Widget_Support_CoordinatorLayout = 0x7f0c0165;
}
public static final class styleable {
private styleable() {}
public static final int[] ColorStateListItem = { 0x10101a5, 0x101031f, 0x7f020027 };
public static final int ColorStateListItem_android_color = 0;
public static final int ColorStateListItem_android_alpha = 1;
public static final int ColorStateListItem_alpha = 2;
public static final int[] CoordinatorLayout = { 0x7f020099, 0x7f0200dc };
public static final int CoordinatorLayout_keylines = 0;
public static final int CoordinatorLayout_statusBarBackground = 1;
public static final int[] CoordinatorLayout_Layout = { 0x10100b3, 0x7f02009c, 0x7f02009d, 0x7f02009e, 0x7f02009f, 0x7f0200a0, 0x7f0200a1 };
public static final int CoordinatorLayout_Layout_android_layout_gravity = 0;
public static final int CoordinatorLayout_Layout_layout_anchor = 1;
public static final int CoordinatorLayout_Layout_layout_anchorGravity = 2;
public static final int CoordinatorLayout_Layout_layout_behavior = 3;
public static final int CoordinatorLayout_Layout_layout_dodgeInsetEdges = 4;
public static final int CoordinatorLayout_Layout_layout_insetEdge = 5;
public static final int CoordinatorLayout_Layout_layout_keyline = 6;
public static final int[] FontFamily = { 0x7f020081, 0x7f020082, 0x7f020083, 0x7f020084, 0x7f020085, 0x7f020086 };
public static final int FontFamily_fontProviderAuthority = 0;
public static final int FontFamily_fontProviderCerts = 1;
public static final int FontFamily_fontProviderFetchStrategy = 2;
public static final int FontFamily_fontProviderFetchTimeout = 3;
public static final int FontFamily_fontProviderPackage = 4;
public static final int FontFamily_fontProviderQuery = 5;
public static final int[] FontFamilyFont = { 0x1010532, 0x1010533, 0x101053f, 0x101056f, 0x1010570, 0x7f02007f, 0x7f020087, 0x7f020088, 0x7f020089, 0x7f02010f };
public static final int FontFamilyFont_android_font = 0;
public static final int FontFamilyFont_android_fontWeight = 1;
public static final int FontFamilyFont_android_fontStyle = 2;
public static final int FontFamilyFont_android_ttcIndex = 3;
public static final int FontFamilyFont_android_fontVariationSettings = 4;
public static final int FontFamilyFont_font = 5;
public static final int FontFamilyFont_fontStyle = 6;
public static final int FontFamilyFont_fontVariationSettings = 7;
public static final int FontFamilyFont_fontWeight = 8;
public static final int FontFamilyFont_ttcIndex = 9;
public static final int[] GradientColor = { 0x101019d, 0x101019e, 0x10101a1, 0x10101a2, 0x10101a3, 0x10101a4, 0x1010201, 0x101020b, 0x1010510, 0x1010511, 0x1010512, 0x1010513 };
public static final int GradientColor_android_startColor = 0;
public static final int GradientColor_android_endColor = 1;
public static final int GradientColor_android_type = 2;
public static final int GradientColor_android_centerX = 3;
public static final int GradientColor_android_centerY = 4;
public static final int GradientColor_android_gradientRadius = 5;
public static final int GradientColor_android_tileMode = 6;
public static final int GradientColor_android_centerColor = 7;
public static final int GradientColor_android_startX = 8;
public static final int GradientColor_android_startY = 9;
public static final int GradientColor_android_endX = 10;
public static final int GradientColor_android_endY = 11;
public static final int[] GradientColorItem = { 0x10101a5, 0x1010514 };
public static final int GradientColorItem_android_color = 0;
public static final int GradientColorItem_android_offset = 1;
}
}
|
package com.deco2800.potatoes.util;
import com.deco2800.potatoes.collisions.Box2D;
import com.deco2800.potatoes.collisions.Shape2D;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.PriorityQueue;
import java.util.function.Predicate;
import java.util.stream.Stream;
import java.util.stream.Collectors;
import static java.lang.Math.ceil;
import static java.lang.Math.floor;
/**
* Class for storing sets of 2D points, and doing spatial queries on them.
*
* Acts as a mapping from instances of generic type Key to Shape2D instances. All instances of Key
* are considered to be globally unique within the RTree. As well as performing standard lookup
* queries (backed by a hashmap) from Key instances to Shape2Ds, this structure allows for reverse
* lookups from Shape2D instances to Key instances (or sets of Key instances, depending on the
* lookup type).
*
* WARNINGS: this class assumes that the shapes inserted into it have a degree of sanity.
* It is assumed that any subset of the positions in the RTree with size greater than or equal to
* Block.BLOCK_SIZE * Block.MIN_RATIO will be capable of having a Box2D drawn surrounding them with
* non-zero side lengths.
*/
public class RTree<Key> {
// Lookup table from keys to shapes.
private Map<Key, Shape2D> forwardLookup;
// Root node of the RTree itself.
private Block<Key> root;
/**
* Creates an empty RTree.
*/
public RTree() {
forwardLookup = new HashMap<>();
root = Block.root();
}
/**
* Inserts a new key/position pair into the RTree.
*
* @param k
* The key of the key/position pair being inserted.
* @param position
* The position associated with they key.
*/
public void insert(Key k, Shape2D position) {
forwardLookup.put(k, position);
if (root.insert(new Bucket(k, position))) {
// split the root
List<Block> newRoot = new ArrayList<>();
newRoot.add(root.split());
newRoot.add(root);
root = Block.branch(newRoot);
}
}
/**
* Moves a key within the RTree to a new position.
*
* @param k
* The key being moved.
* @param newPosition
* The new position to be associated with the key.
*/
public void move(Key k, Shape2D newPosition) {
remove(k);
insert(k, newPosition);
}
/**
* Removes a key/position pair from the RTree.
*
* @param k
* The key of the key/position pair being removed.
*/
public void remove(Key k) {
Shape2D position = forwardLookup.remove(k);
if (position != null) {
root.remove(new Bucket<>(k, position));
if (root.isBranch() && root.getChildren().size() == 1) {
root = (Block<Key>) root.getChildren().get(0);
}
}
}
/**
* Finds the position associated with a key in the RTree.
*
* @param k
* The key being queried.
* @return
* The position associated with that key within the RTree.
*/
public Shape2D find(Key k) {
return forwardLookup.get(k);
}
/**
* Finds the nearest key to a given position (by the Shape2D distance method) where the additionalCheck returns true. Ties are broken
* arbitrarily.
*
* @param position
* The position keys are searched near.
* @param additionalCheck
* The additional requirement for the result
* @return
* The key that is closest to the position.
*/
public Key findClosest(Shape2D position, Predicate<Key> additionalCheck) {
return root.findClosest(position, additionalCheck);
}
/**
* Finds the nearest key to a given position (by the Shape2D distance method). Ties are broken
* arbitrarily.
*
* @param position
* The position keys are searched near.
* @return
* The key that is closest to the position.
*/
public Key findClosest(Shape2D position) {
return root.findClosest(position, (x) -> true);
}
/**
* Finds the keys within the RTree that overlap the given position (by the Shape2D overlaps
* method).
*
* @param position
* The position that overlaps are checked with.
* @return
* The keys that are within this shape.
*/
public Collection<Key> findOverlapping(Shape2D position) {
Collection<Key> output = new ArrayList<>();
root.addAllOverlapping(position, output);
return output;
}
/**
* Internal block of storage within the RTree.
* This represents a node within the tree, which either stores a list of child blocks, or a
* list of child buckets.
*
*/
private static class Block<Key> {
// Number of nodes within a block.
private static final int BLOCK_SIZE = 20;
private static final float MIN_RATIO = 0.4f;
// Child nodes of the block. If isLeaf is true, then leafChildren must be an actual
// array and the value of children is undefined. If is false, then children must be an
// actual array, and the value of leafChildren is undefined.
private final boolean isLeaf;
private List<Block<Key>> children;
private List<Bucket<Key>> leafChildren;
// A Box2D guaranteed to contain all children of this block.
private Box2D minimumBoundingRectangle;
/**
* Partial constructor, for internal use only.
*
* @param isLeaf
* Is this block a leaf node or not?
*/
private Block(boolean isLeaf) {
this.isLeaf = isLeaf;
}
/**
* Creates a new root block.
*/
public static Block root() {
Block output = new Block(true);
output.leafChildren = new ArrayList<>();
output.minimumBoundingRectangle = null;
return output;
}
/**
* Create a new leaf block.
*
* @param children
* The children of the block.
*/
public static Block leaf(List<Bucket> children) {
Block output = new Block(true);
output.leafChildren = children;
output.minimumBoundingRectangle = Box2D.surrounding(children.stream().map(child -> child.position)).get();
return output;
}
/**
* Create a new branch (internal, non-leaf) block.
*
* @param children
* The children of the block.
*/
public static Block branch(List<Block> children) {
Block output = new Block(false);
output.children = children;
output.minimumBoundingRectangle = Box2D.surrounding(
children.stream().map(child -> child.minimumBoundingRectangle)).get();
return output;
}
/**
* Getter, returns whether this node is not a leaf.
*
* @return
* True for branches, false for leaves.
*/
public boolean isBranch() {
return !isLeaf;
}
/**
* Getter for children. Does not return a copy, and should only be called on the root node.
*/
public List getChildren() {
return isLeaf ? leafChildren : children;
}
/**
* Inserts a bucket into one of the child buckets.
*
* @param b
* The bucket being inserted.
* @require
* This must not be a leaf node.
*/
private void insertIntoChildBucket(Bucket b) {
int selection = -1;
float cheapest = Float.MAX_VALUE;
for (int i = 0; i < children.size(); ++i) {
Box2D newBounds = Box2D.surrounding(Stream.of(
children.get(i).minimumBoundingRectangle, b.getPosition())).get();
float cost = newBounds.getXLength() + newBounds.getYLength();
if (cost < cheapest) {
selection = i;
cheapest = cost;
}
}
if (children.get(selection).insert(b)) {
children.add(children.get(selection).split());
}
}
/**
* If this block has overflown during a resize operation, this method will remove ~half of
* the children from this block, and return a new block containing those children.
*
* @require
* This block is not a leaf node, and it has overflown.
* @return
* The new block containing ~half of this block's children.
*/
private Block splitBranch() {
boolean isResultHorizontal = true;
float cheapest = Float.MAX_VALUE;
int splitIndex = -1;
children.sort(Comparator.comparingDouble(
child -> child.minimumBoundingRectangle.getX()));
for (int i = (int) ceil(MIN_RATIO * BLOCK_SIZE);
i < floor((1 - MIN_RATIO) * BLOCK_SIZE); ++i) {
Optional<Box2D> maybeFirst = Box2D.surrounding(children.stream()
.limit(i)
.map(j -> j.minimumBoundingRectangle));
Optional<Box2D> maybeSecond = Box2D.surrounding(children.stream()
.skip(i)
.map(j -> j.minimumBoundingRectangle));
if (!maybeFirst.isPresent() || !maybeSecond.isPresent()) {
continue;
}
Box2D first = maybeFirst.get(), second = maybeSecond.get();
float cost = first.getXLength() + first.getYLength() + second.getXLength()
+ second.getYLength();
if (cost < cheapest) {
splitIndex = i;
}
}
children.sort(Comparator.comparingDouble(
child -> child.minimumBoundingRectangle.getY()));
for (int i = (int) ceil(MIN_RATIO * BLOCK_SIZE);
i < floor((1 - MIN_RATIO) * BLOCK_SIZE); ++i) {
Optional<Box2D> maybeFirst = Box2D.surrounding(children.stream()
.limit(i)
.map(j -> j.minimumBoundingRectangle));
Optional<Box2D> maybeSecond = Box2D.surrounding(children.stream()
.skip(i)
.map(j -> j.minimumBoundingRectangle));
if (!maybeFirst.isPresent() || !maybeSecond.isPresent()) {
continue;
}
Box2D first = maybeFirst.get(), second = maybeSecond.get();
float cost = first.getXLength() + first.getYLength() + second.getXLength()
+ second.getYLength();
if (cost < cheapest) {
isResultHorizontal = false;
splitIndex = i;
}
}
if (isResultHorizontal) {
children.sort(Comparator.comparingDouble(
child -> child.minimumBoundingRectangle.getX()));
}
List<Block> newChildren = children.stream().skip(splitIndex).collect(Collectors.toList());
children = children.stream().limit(splitIndex).collect(Collectors.toList());
minimumBoundingRectangle =
Box2D.surrounding(children.stream().map(j -> j.minimumBoundingRectangle)).get();
return Block.branch(newChildren);
}
/**
* If this block has overflown during a resize operation, this method will remove ~half of
* the children from this block, and return a new block containing those children.
*
* @require
* This block is a leaf node, and it has overflown.
* @return
* The new block containing ~half of this block's children.
*/
private Block splitLeaf() {
boolean isResultHorizontal = true;
float cheapest = Float.MAX_VALUE;
int splitIndex = -1;
leafChildren.sort(Comparator.comparingDouble(
child -> child.getPosition().getX()));
for (int i = (int) ceil(MIN_RATIO * BLOCK_SIZE);
i < floor((1 - MIN_RATIO) * BLOCK_SIZE); ++i) {
Optional<Box2D> maybeFirst = Box2D.surrounding(leafChildren.stream()
.limit(i)
.map(j -> j.getPosition()));
Optional<Box2D> maybeSecond = Box2D.surrounding(leafChildren.stream()
.skip(i)
.map(j -> j.getPosition()));
if (!maybeFirst.isPresent() || !maybeSecond.isPresent()) {
continue;
}
Box2D first = maybeFirst.get(), second = maybeSecond.get();
float cost = first.getXLength() + first.getYLength() + second.getXLength()
+ second.getYLength();
if (cost < cheapest) {
splitIndex = i;
}
}
leafChildren.sort(Comparator.comparingDouble(
child -> child.getPosition().getY()));
for (int i = (int) ceil(MIN_RATIO * BLOCK_SIZE);
i < floor((1 - MIN_RATIO) * BLOCK_SIZE); ++i) {
Optional<Box2D> maybeFirst = Box2D.surrounding(leafChildren.stream()
.limit(i)
.map(j -> j.getPosition()));
Optional<Box2D> maybeSecond = Box2D.surrounding(leafChildren.stream()
.skip(i)
.map(j -> j.getPosition()));
if (!maybeFirst.isPresent() || !maybeSecond.isPresent()) {
continue;
}
Box2D first = maybeFirst.get(), second = maybeSecond.get();
float cost = first.getXLength() + first.getYLength() + second.getXLength()
+ second.getYLength();
if (cost < cheapest) {
isResultHorizontal = false;
splitIndex = i;
}
}
if (isResultHorizontal) {
leafChildren.sort(Comparator.comparingDouble(
child -> child.getPosition().getX()));
}
List<Bucket> newChildren =
leafChildren.stream().skip(splitIndex).collect(Collectors.toList());
leafChildren = leafChildren.stream().limit(splitIndex).collect(Collectors.toList());
minimumBoundingRectangle =
Box2D.surrounding(leafChildren.stream().map(j -> j.getPosition())).get();
return Block.leaf(newChildren);
}
/**
* If this block has overflown during a resize operation, this method will remove ~half of
* the children from this block, and return a new block containing these children. If this
* node is a leaf node, the node returned will also be a leaf node, and vice versa.
*/
public Block split() {
if (isLeaf) {
return splitLeaf();
} else {
return splitBranch();
}
}
/**
* Inserts a new bucket into this block.
*
* @param b
* The bucket being inserted.
* @return
* True if the node has overflown and needs to be resized.
*/
public boolean insert(Bucket b) {
if (isLeaf) {
leafChildren.add(b);
if (leafChildren.size() <= BLOCK_SIZE) { // do not nead to overflow
minimumBoundingRectangle = Box2D.surrounding(
Stream.of(minimumBoundingRectangle, b.getPosition())).orElse(null);
return false;
} else { // need to overflow, so why bother dealing with the other stuff?
return true;
}
} else {
insertIntoChildBucket(b);
minimumBoundingRectangle = Box2D.surrounding(children.stream()
.map(child -> child.minimumBoundingRectangle)).get();
return children.size() > BLOCK_SIZE;
}
}
/**
* Joins two buckets together.
* @param other
* The bucket being joined.
* @require
* Either this and other are both leafs, or they are both branches.
*/
private void join(Block other) {
if (isLeaf) {
leafChildren.addAll(other.leafChildren);
minimumBoundingRectangle = Box2D.surrounding(
leafChildren.stream().map(child -> child.getPosition())).get();
} else {
children.addAll(other.children);
minimumBoundingRectangle = Box2D.surrounding(
children.stream().map(child -> child.minimumBoundingRectangle)).get();
}
}
/**
* Removes a bucket from this block.
*
* @param b
* The bucket being removed.
* @return
* True if the node has underflowed and needs to be resized.
* @require
* The bucket b is inside the current minimumBoundingRectangle.
*/
public boolean remove(Bucket b) {
if (isLeaf) {
if (leafChildren.contains(b)) {
leafChildren.remove(b);
}
minimumBoundingRectangle = Box2D.surrounding(
leafChildren.stream().map(child -> child.getPosition())).get();
return leafChildren.size() < MIN_RATIO * BLOCK_SIZE;
} else {
Block toBeMaybeJoined = null;
for (Block child: children) {
if (child.minimumBoundingRectangle.overlaps(b.getPosition())
&& child.remove(b)) {
// child has overflown
toBeMaybeJoined = child;
break;
}
}
final Block toBeJoined = toBeMaybeJoined;
// handle joining
if (toBeJoined != null) {
Block joinWith = children.stream().filter(child -> !child.equals(toBeJoined))
.min(Comparator.comparingDouble(child -> {
Box2D newBounds = Box2D.surrounding(Stream.of(child, toBeJoined)
.map(block -> block.minimumBoundingRectangle)).get();
return newBounds.getXLength() + newBounds.getYLength();
})).get();
children.remove(joinWith);
toBeJoined.join(joinWith);
}
if (children.size() < MIN_RATIO * BLOCK_SIZE) {
return true;
} else {
minimumBoundingRectangle = Box2D.surrounding(
children.stream().map(child -> child.minimumBoundingRectangle)).get();
return false;
}
}
}
/**
* Finds all the keys within this subset of the RTree that overlap the given position, and
* add them to an existing collection.
*
* @param position
* The position that overlaps are checked with.
* @param output
* The collection that outputs are appended to.
*/
public void addAllOverlapping(Shape2D position, Collection<Key> output) {
if (isLeaf) {
leafChildren.stream()
.filter(child -> child.getPosition().overlaps(position))
.map(child -> child.getKey())
.forEach(key -> output.add(key));
} else {
children.stream()
.filter(child -> child.minimumBoundingRectangle.overlaps(position))
.forEach(child -> child.addAllOverlapping(position, output));
}
}
/**
* Finds the key that is closest to a given position. It is assumed that this method is
* only called on the root node.
*
* @param position
* The position whos nearest neighbour is being found.
* @return
* The key of the nearest neighbour. Null if the RTree is empty.
*/
public Key findClosest(Shape2D position, Predicate<Key> additionalCheck) {
if (isLeaf && leafChildren.size() == 0) {
return null;
}
Key output = null;
float currentDistance = Float.MAX_VALUE;
PriorityQueue<Block> queue = new PriorityQueue<>(Comparator.comparingDouble(
child -> child.minimumBoundingRectangle.distance(position)));
if (isLeaf) {
queue.add(this);
} else {
queue.addAll(children);
}
while (!queue.isEmpty() && queue.peek().minimumBoundingRectangle.distance(position) <
currentDistance) {
Block<Key> head = queue.poll();
if (head.isLeaf) {
for (Bucket<Key> bucket: head.leafChildren) {
if (bucket.getPosition().distance(position) < currentDistance && additionalCheck.test(bucket.getKey())) {
currentDistance = bucket.getPosition().distance(position);
output = bucket.getKey();
}
}
} else {
queue.addAll(head.children);
}
}
return output;
}
}
/**
* Class to store a single key/value pair.
*/
private static class Bucket<Key> {
private Key k;
private Shape2D position;
public Bucket(Key k, Shape2D position) {
this.k = k;
this.position = position;
}
public Key getKey() {
return k;
}
public Shape2D getPosition() {
return position;
}
public void setPosition(Shape2D position) {
this.position = position;
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (!(other instanceof Bucket)) {
return false;
}
Bucket<Key> otherBucket = (Bucket<Key>) other;
// all equality cares about is the key, different position doesn't matter
return otherBucket.getKey().equals(k);
}
@Override
public int hashCode() {
return k.hashCode();
}
}
}
|
/*
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.batik.css.dom;
import org.apache.batik.css.engine.value.FloatValue;
import org.apache.batik.css.engine.value.Value;
import org.apache.batik.css.engine.value.svg.ICCColor;
import org.apache.batik.util.CSSConstants;
import org.w3c.dom.DOMException;
import org.w3c.dom.css.CSSPrimitiveValue;
import org.w3c.dom.css.CSSValue;
import org.w3c.dom.svg.SVGPaint;
/**
* This class implements the {@link SVGPaint} interface.
*
* @author <a href="mailto:stephane@hillion.org">Stephane Hillion</a>
* @version $Id: CSSOMSVGPaint.java 1733416 2016-03-03 07:07:13Z gadams $
*/
public class CSSOMSVGPaint extends CSSOMSVGColor implements SVGPaint {
/**
* Creates a new CSSOMSVGPaint.
*/
public CSSOMSVGPaint(ValueProvider vp) {
super(vp);
}
/**
* Sets the modification handler of this value.
*/
public void setModificationHandler(ModificationHandler h) {
if (!(h instanceof PaintModificationHandler)) {
throw new IllegalArgumentException();
}
super.setModificationHandler(h);
}
/**
* <b>DOM</b>: Implements {@link
* org.w3c.dom.svg.SVGColor#getColorType()}.
*/
public short getColorType() {
throw new DOMException(DOMException.INVALID_ACCESS_ERR, "");
}
/**
* <b>DOM</b>: Implements {@link
* org.w3c.dom.svg.SVGPaint#getPaintType()}.
*/
public short getPaintType() {
Value value = valueProvider.getValue();
switch (value.getCssValueType()) {
case CSSValue.CSS_PRIMITIVE_VALUE:
switch (value.getPrimitiveType()) {
case CSSPrimitiveValue.CSS_IDENT: {
String str = value.getStringValue();
if (str.equalsIgnoreCase(CSSConstants.CSS_NONE_VALUE)) {
return SVG_PAINTTYPE_NONE;
} else if (str.equalsIgnoreCase
(CSSConstants.CSS_CURRENTCOLOR_VALUE)) {
return SVG_PAINTTYPE_CURRENTCOLOR;
}
return SVG_PAINTTYPE_RGBCOLOR;
}
case CSSPrimitiveValue.CSS_RGBCOLOR:
return SVG_PAINTTYPE_RGBCOLOR;
case CSSPrimitiveValue.CSS_URI:
return SVG_PAINTTYPE_URI;
}
break;
case CSSValue.CSS_VALUE_LIST:
Value v0 = value.item(0);
Value v1 = value.item(1);
switch (v0.getPrimitiveType()) {
case CSSPrimitiveValue.CSS_IDENT:
return SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR;
case CSSPrimitiveValue.CSS_URI:
if (v1.getCssValueType() == CSSValue.CSS_VALUE_LIST)
// Should probably check this more deeply...
return SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR;
switch (v1.getPrimitiveType()) {
case CSSPrimitiveValue.CSS_IDENT: {
String str = v1.getStringValue();
if (str.equalsIgnoreCase(CSSConstants.CSS_NONE_VALUE)) {
return SVG_PAINTTYPE_URI_NONE;
} else if (str.equalsIgnoreCase
(CSSConstants.CSS_CURRENTCOLOR_VALUE)) {
return SVG_PAINTTYPE_URI_CURRENTCOLOR;
}
return SVG_PAINTTYPE_URI_RGBCOLOR;
}
case CSSPrimitiveValue.CSS_RGBCOLOR:
return SVG_PAINTTYPE_URI_RGBCOLOR;
}
case CSSPrimitiveValue.CSS_RGBCOLOR:
return SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR;
}
}
return SVG_PAINTTYPE_UNKNOWN;
}
/**
* <b>DOM</b>: Implements {@link org.w3c.dom.svg.SVGPaint#getUri()}.
*/
public String getUri() {
switch (getPaintType()) {
case SVG_PAINTTYPE_URI:
return valueProvider.getValue().getStringValue();
case SVG_PAINTTYPE_URI_NONE:
case SVG_PAINTTYPE_URI_CURRENTCOLOR:
case SVG_PAINTTYPE_URI_RGBCOLOR:
case SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR:
return valueProvider.getValue().item(0).getStringValue();
}
throw new InternalError();
}
/**
* <b>DOM</b>: Implements {@link org.w3c.dom.svg.SVGPaint#setUri(String)}.
*/
public void setUri(String uri) {
if (handler == null) {
throw new DOMException
(DOMException.NO_MODIFICATION_ALLOWED_ERR, "");
} else {
((PaintModificationHandler)handler).uriChanged(uri);
}
}
/**
* <b>DOM</b>: Implements {@link
* org.w3c.dom.svg.SVGPaint#setPaint(short,String,String,String)}.
*/
public void setPaint(short paintType, String uri,
String rgbColor, String iccColor) {
if (handler == null) {
throw new DOMException
(DOMException.NO_MODIFICATION_ALLOWED_ERR, "");
} else {
((PaintModificationHandler)handler).paintChanged
(paintType, uri, rgbColor, iccColor);
}
}
/**
* To manage the modifications on a SVGPaint value.
*/
public interface PaintModificationHandler extends ModificationHandler {
/**
* Called when the URI has been modified.
*/
void uriChanged(String uri);
/**
* Called when the paint value has beem modified.
*/
void paintChanged(short type, String uri, String rgb, String icc);
}
/**
* Provides an abstract implementation of a PaintModificationHandler.
*/
public abstract class AbstractModificationHandler
implements PaintModificationHandler {
/**
* Returns the associated value.
*/
protected abstract Value getValue();
/**
* Called when the red value text has changed.
*/
public void redTextChanged(String text) throws DOMException {
switch (getPaintType()) {
case SVG_PAINTTYPE_RGBCOLOR:
text = "rgb(" +
text + ", " +
getValue().getGreen().getCssText() + ", " +
getValue().getBlue().getCssText() + ')';
break;
case SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR:
text = "rgb(" +
text + ", " +
getValue().item(0).getGreen().getCssText() + ", " +
getValue().item(0).getBlue().getCssText() + ") " +
getValue().item(1).getCssText();
break;
case SVG_PAINTTYPE_URI_RGBCOLOR:
text = getValue().item(0) +
" rgb(" +
text + ", " +
getValue().item(1).getGreen().getCssText() + ", " +
getValue().item(1).getBlue().getCssText() + ')';
break;
case SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR:
text = getValue().item(0) +
" rgb(" +
text + ", " +
getValue().item(1).getGreen().getCssText() + ", " +
getValue().item(1).getBlue().getCssText() + ") " +
getValue().item(2).getCssText();
break;
default:
throw new DOMException
(DOMException.NO_MODIFICATION_ALLOWED_ERR, "");
}
textChanged(text);
}
/**
* Called when the red float value has changed.
*/
public void redFloatValueChanged(short unit, float value)
throws DOMException {
String text;
switch (getPaintType()) {
case SVG_PAINTTYPE_RGBCOLOR:
text = "rgb(" +
FloatValue.getCssText(unit, value) + ", " +
getValue().getGreen().getCssText() + ", " +
getValue().getBlue().getCssText() + ')';
break;
case SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR:
text = "rgb(" +
FloatValue.getCssText(unit, value) + ", " +
getValue().item(0).getGreen().getCssText() + ", " +
getValue().item(0).getBlue().getCssText() + ") " +
getValue().item(1).getCssText();
break;
case SVG_PAINTTYPE_URI_RGBCOLOR:
text = getValue().item(0) +
" rgb(" +
FloatValue.getCssText(unit, value) + ", " +
getValue().item(1).getGreen().getCssText() + ", " +
getValue().item(1).getBlue().getCssText() + ')';
break;
case SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR:
text = getValue().item(0) +
" rgb(" +
FloatValue.getCssText(unit, value) + ", " +
getValue().item(1).getGreen().getCssText() + ", " +
getValue().item(1).getBlue().getCssText() + ") " +
getValue().item(2).getCssText();
break;
default:
throw new DOMException
(DOMException.NO_MODIFICATION_ALLOWED_ERR, "");
}
textChanged(text);
}
/**
* Called when the green value text has changed.
*/
public void greenTextChanged(String text) throws DOMException {
switch (getPaintType()) {
case SVG_PAINTTYPE_RGBCOLOR:
text = "rgb(" +
getValue().getRed().getCssText() + ", " +
text + ", " +
getValue().getBlue().getCssText() + ')';
break;
case SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR:
text = "rgb(" +
getValue().item(0).getRed().getCssText() + ", " +
text + ", " +
getValue().item(0).getBlue().getCssText() + ") " +
getValue().item(1).getCssText();
break;
case SVG_PAINTTYPE_URI_RGBCOLOR:
text = getValue().item(0) +
" rgb(" +
getValue().item(1).getRed().getCssText() + ", " +
text + ", " +
getValue().item(1).getBlue().getCssText() + ')';
break;
case SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR:
text = getValue().item(0) +
" rgb(" +
getValue().item(1).getRed().getCssText() + ", " +
text + ", " +
getValue().item(1).getBlue().getCssText() + ") " +
getValue().item(2).getCssText();
break;
default:
throw new DOMException
(DOMException.NO_MODIFICATION_ALLOWED_ERR, "");
}
textChanged(text);
}
/**
* Called when the green float value has changed.
*/
public void greenFloatValueChanged(short unit, float value)
throws DOMException {
String text;
switch (getPaintType()) {
case SVG_PAINTTYPE_RGBCOLOR:
text = "rgb(" +
getValue().getRed().getCssText() + ", " +
FloatValue.getCssText(unit, value) + ", " +
getValue().getBlue().getCssText() + ')';
break;
case SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR:
text = "rgb(" +
getValue().item(0).getRed().getCssText() + ", " +
FloatValue.getCssText(unit, value) + ", " +
getValue().item(0).getBlue().getCssText() + ") " +
getValue().item(1).getCssText();
break;
case SVG_PAINTTYPE_URI_RGBCOLOR:
text = getValue().item(0) +
" rgb(" +
getValue().item(1).getRed().getCssText() + ", " +
FloatValue.getCssText(unit, value) + ", " +
getValue().item(1).getBlue().getCssText() + ')';
break;
case SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR:
text = getValue().item(0) +
" rgb(" +
getValue().item(1).getRed().getCssText() + ", " +
FloatValue.getCssText(unit, value) + ", " +
getValue().item(1).getBlue().getCssText() + ") " +
getValue().item(2).getCssText();
break;
default:
throw new DOMException
(DOMException.NO_MODIFICATION_ALLOWED_ERR, "");
}
textChanged(text);
}
/**
* Called when the blue value text has changed.
*/
public void blueTextChanged(String text) throws DOMException {
switch (getPaintType()) {
case SVG_PAINTTYPE_RGBCOLOR:
text = "rgb(" +
getValue().getRed().getCssText() + ", " +
getValue().getGreen().getCssText() + ", " +
text + ')';
break;
case SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR:
text = "rgb(" +
getValue().item(0).getRed().getCssText() + ", " +
getValue().item(0).getGreen().getCssText() + ", " +
text + ") " +
getValue().item(1).getCssText();
break;
case SVG_PAINTTYPE_URI_RGBCOLOR:
text = getValue().item(0) +
" rgb(" +
getValue().item(1).getRed().getCssText() + ", " +
getValue().item(1).getGreen().getCssText() + ", " +
text + ")";
break;
case SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR:
text = getValue().item(0) +
" rgb(" +
getValue().item(1).getRed().getCssText() + ", " +
getValue().item(1).getGreen().getCssText() + ", " +
text + ") " +
getValue().item(2).getCssText();
break;
default:
throw new DOMException
(DOMException.NO_MODIFICATION_ALLOWED_ERR, "");
}
textChanged(text);
}
/**
* Called when the blue float value has changed.
*/
public void blueFloatValueChanged(short unit, float value)
throws DOMException {
String text;
switch (getPaintType()) {
case SVG_PAINTTYPE_RGBCOLOR:
text = "rgb(" +
getValue().getRed().getCssText() + ", " +
getValue().getGreen().getCssText() + ", " +
FloatValue.getCssText(unit, value) + ')';
break;
case SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR:
text = "rgb(" +
getValue().item(0).getRed().getCssText() + ", " +
getValue().item(0).getGreen().getCssText() + ", " +
FloatValue.getCssText(unit, value) + ") " +
getValue().item(1).getCssText();
break;
case SVG_PAINTTYPE_URI_RGBCOLOR:
text = getValue().item(0) +
" rgb(" +
getValue().item(1).getRed().getCssText() + ", " +
getValue().item(1).getGreen().getCssText() + ", " +
FloatValue.getCssText(unit, value) + ')';
break;
case SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR:
text = getValue().item(0) +
" rgb(" +
getValue().item(1).getRed().getCssText() + ", " +
getValue().item(1).getGreen().getCssText() + ", " +
FloatValue.getCssText(unit, value) + ") " +
getValue().item(2).getCssText();
break;
default:
throw new DOMException
(DOMException.NO_MODIFICATION_ALLOWED_ERR, "");
}
textChanged(text);
}
/**
* Called when the RGBColor text has changed.
*/
public void rgbColorChanged(String text) throws DOMException {
switch (getPaintType()) {
case SVG_PAINTTYPE_RGBCOLOR:
break;
case SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR:
text += getValue().item(1).getCssText();
break;
case SVG_PAINTTYPE_URI_RGBCOLOR:
text = getValue().item(0).getCssText() + ' ' + text;
break;
case SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR:
text = getValue().item(0).getCssText() + ' ' + text + ' ' +
getValue().item(2).getCssText();
break;
default:
throw new DOMException
(DOMException.NO_MODIFICATION_ALLOWED_ERR, "");
}
textChanged(text);
}
/**
* Called when the RGBColor and the ICCColor text has changed.
*/
public void rgbColorICCColorChanged(String rgb, String icc)
throws DOMException {
switch (getPaintType()) {
case SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR:
textChanged(rgb + ' ' + icc);
break;
case SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR:
textChanged(getValue().item(0).getCssText() + ' ' +
rgb + ' ' + icc);
break;
default:
throw new DOMException
(DOMException.NO_MODIFICATION_ALLOWED_ERR, "");
}
}
/**
* Called when the SVGColor has changed.
*/
public void colorChanged(short type, String rgb, String icc)
throws DOMException {
switch (type) {
case SVG_PAINTTYPE_CURRENTCOLOR:
textChanged("currentcolor");
break;
case SVG_PAINTTYPE_RGBCOLOR:
textChanged(rgb);
break;
case SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR:
textChanged(rgb + ' ' + icc);
break;
default:
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "");
}
}
/**
* Called when the ICC color profile has changed.
*/
public void colorProfileChanged(String cp) throws DOMException {
switch (getPaintType()) {
case SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR:
StringBuffer sb =
new StringBuffer(getValue().item(0).getCssText());
sb.append(" icc-color(");
sb.append(cp);
ICCColor iccc = (ICCColor)getValue().item(1);
for (int i = 0; i < iccc.getLength(); i++) {
sb.append( ',' );
sb.append(iccc.getColor(i));
}
sb.append( ')' );
textChanged(sb.toString());
break;
case SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR:
sb = new StringBuffer(getValue().item(0).getCssText());
sb.append( ' ' );
sb.append(getValue().item(1).getCssText());
sb.append(" icc-color(");
sb.append(cp);
iccc = (ICCColor)getValue().item(1);
for (int i = 0; i < iccc.getLength(); i++) {
sb.append( ',' );
sb.append(iccc.getColor(i));
}
sb.append( ')' );
textChanged(sb.toString());
break;
default:
throw new DOMException
(DOMException.NO_MODIFICATION_ALLOWED_ERR, "");
}
}
/**
* Called when the ICC colors has changed.
*/
public void colorsCleared() throws DOMException {
switch (getPaintType()) {
case SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR:
StringBuffer sb =
new StringBuffer(getValue().item(0).getCssText());
sb.append(" icc-color(");
ICCColor iccc = (ICCColor)getValue().item(1);
sb.append(iccc.getColorProfile());
sb.append( ')' );
textChanged(sb.toString());
break;
case SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR:
sb = new StringBuffer(getValue().item(0).getCssText());
sb.append( ' ' );
sb.append(getValue().item(1).getCssText());
sb.append(" icc-color(");
iccc = (ICCColor)getValue().item(1);
sb.append(iccc.getColorProfile());
sb.append( ')' );
textChanged(sb.toString());
break;
default:
throw new DOMException
(DOMException.NO_MODIFICATION_ALLOWED_ERR, "");
}
}
/**
* Called when the ICC colors has been initialized.
*/
public void colorsInitialized(float f) throws DOMException {
switch (getPaintType()) {
case SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR:
StringBuffer sb =
new StringBuffer(getValue().item(0).getCssText());
sb.append(" icc-color(");
ICCColor iccc = (ICCColor)getValue().item(1);
sb.append(iccc.getColorProfile());
sb.append( ',' );
sb.append(f);
sb.append( ')' );
textChanged(sb.toString());
break;
case SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR:
sb = new StringBuffer(getValue().item(0).getCssText());
sb.append( ' ' );
sb.append(getValue().item(1).getCssText());
sb.append(" icc-color(");
iccc = (ICCColor)getValue().item(1);
sb.append(iccc.getColorProfile());
sb.append( ',' );
sb.append(f);
sb.append( ')' );
textChanged(sb.toString());
break;
default:
throw new DOMException
(DOMException.NO_MODIFICATION_ALLOWED_ERR, "");
}
}
/**
* Called when the ICC color has been inserted.
*/
public void colorInsertedBefore(float f, int idx) throws DOMException {
switch (getPaintType()) {
case SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR:
StringBuffer sb =
new StringBuffer(getValue().item(0).getCssText());
sb.append(" icc-color(");
ICCColor iccc = (ICCColor)getValue().item(1);
sb.append(iccc.getColorProfile());
for (int i = 0; i < idx; i++) {
sb.append( ',' );
sb.append(iccc.getColor(i));
}
sb.append( ',' );
sb.append(f);
for (int i = idx; i < iccc.getLength(); i++) {
sb.append( ',' );
sb.append(iccc.getColor(i));
}
sb.append( ')' );
textChanged(sb.toString());
break;
case SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR:
sb = new StringBuffer(getValue().item(0).getCssText());
sb.append( ' ' );
sb.append(getValue().item(1).getCssText());
sb.append(" icc-color(");
iccc = (ICCColor)getValue().item(1);
sb.append(iccc.getColorProfile());
for (int i = 0; i < idx; i++) {
sb.append( ',' );
sb.append(iccc.getColor(i));
}
sb.append( ',' );
sb.append(f);
for (int i = idx; i < iccc.getLength(); i++) {
sb.append( ',' );
sb.append(iccc.getColor(i));
}
sb.append( ')' );
textChanged(sb.toString());
break;
default:
throw new DOMException
(DOMException.NO_MODIFICATION_ALLOWED_ERR, "");
}
}
/**
* Called when the ICC color has been replaced.
*/
public void colorReplaced(float f, int idx) throws DOMException {
switch (getPaintType()) {
case SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR:
StringBuffer sb =
new StringBuffer(getValue().item(0).getCssText());
sb.append(" icc-color(");
ICCColor iccc = (ICCColor)getValue().item(1);
sb.append(iccc.getColorProfile());
for (int i = 0; i < idx; i++) {
sb.append( ',' );
sb.append(iccc.getColor(i));
}
sb.append( ',' );
sb.append(f);
for (int i = idx + 1; i < iccc.getLength(); i++) {
sb.append( ',' );
sb.append(iccc.getColor(i));
}
sb.append( ')' );
textChanged(sb.toString());
break;
case SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR:
sb = new StringBuffer(getValue().item(0).getCssText());
sb.append( ' ' );
sb.append(getValue().item(1).getCssText());
sb.append(" icc-color(");
iccc = (ICCColor)getValue().item(1);
sb.append(iccc.getColorProfile());
for (int i = 0; i < idx; i++) {
sb.append( ',' );
sb.append(iccc.getColor(i));
}
sb.append( ',' );
sb.append(f);
for (int i = idx + 1; i < iccc.getLength(); i++) {
sb.append( ',' );
sb.append(iccc.getColor(i));
}
sb.append( ')' );
textChanged(sb.toString());
break;
default:
throw new DOMException
(DOMException.NO_MODIFICATION_ALLOWED_ERR, "");
}
}
/**
* Called when the ICC color has been removed.
*/
public void colorRemoved(int idx) throws DOMException {
switch (getPaintType()) {
case SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR:
StringBuffer sb =
new StringBuffer(getValue().item(0).getCssText());
sb.append(" icc-color(");
ICCColor iccc = (ICCColor)getValue().item(1);
sb.append(iccc.getColorProfile());
for (int i = 0; i < idx; i++) {
sb.append( ',' );
sb.append(iccc.getColor(i));
}
for (int i = idx + 1; i < iccc.getLength(); i++) {
sb.append( ',' );
sb.append(iccc.getColor(i));
}
sb.append( ')' );
textChanged(sb.toString());
break;
case SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR:
sb = new StringBuffer(getValue().item(0).getCssText());
sb.append( ' ' );
sb.append(getValue().item(1).getCssText());
sb.append(" icc-color(");
iccc = (ICCColor)getValue().item(1);
sb.append(iccc.getColorProfile());
for (int i = 0; i < idx; i++) {
sb.append( ',' );
sb.append(iccc.getColor(i));
}
for (int i = idx + 1; i < iccc.getLength(); i++) {
sb.append( ',' );
sb.append(iccc.getColor(i));
}
sb.append( ')' );
textChanged(sb.toString());
break;
default:
throw new DOMException
(DOMException.NO_MODIFICATION_ALLOWED_ERR, "");
}
}
/**
* Called when the ICC color has been append.
*/
public void colorAppend(float f) throws DOMException {
switch (getPaintType()) {
case SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR:
StringBuffer sb =
new StringBuffer(getValue().item(0).getCssText());
sb.append(" icc-color(");
ICCColor iccc = (ICCColor)getValue().item(1);
sb.append(iccc.getColorProfile());
for (int i = 0; i < iccc.getLength(); i++) {
sb.append( ',' );
sb.append(iccc.getColor(i));
}
sb.append( ',' );
sb.append(f);
sb.append( ')' );
textChanged(sb.toString());
break;
case SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR:
sb = new StringBuffer(getValue().item(0).getCssText());
sb.append( ' ' );
sb.append(getValue().item(1).getCssText());
sb.append(" icc-color(");
iccc = (ICCColor)getValue().item(1);
sb.append(iccc.getColorProfile());
for (int i = 0; i < iccc.getLength(); i++) {
sb.append( ',' );
sb.append(iccc.getColor(i));
}
sb.append( ',' );
sb.append(f);
sb.append( ')' );
textChanged(sb.toString());
break;
default:
throw new DOMException
(DOMException.NO_MODIFICATION_ALLOWED_ERR, "");
}
}
/**
* Called when the URI has been modified.
*/
public void uriChanged(String uri) {
textChanged("url(" + uri + ") none");
}
/**
* Called when the paint value has beem modified.
*/
public void paintChanged(short type, String uri,
String rgb, String icc) {
switch (type) {
case SVG_PAINTTYPE_NONE:
textChanged("none");
break;
case SVG_PAINTTYPE_CURRENTCOLOR:
textChanged("currentcolor");
break;
case SVG_PAINTTYPE_RGBCOLOR:
textChanged(rgb);
break;
case SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR:
textChanged(rgb + ' ' + icc);
break;
case SVG_PAINTTYPE_URI:
textChanged("url(" + uri + ')' );
break;
case SVG_PAINTTYPE_URI_NONE:
textChanged("url(" + uri + ") none");
break;
case SVG_PAINTTYPE_URI_CURRENTCOLOR:
textChanged("url(" + uri + ") currentcolor");
break;
case SVG_PAINTTYPE_URI_RGBCOLOR:
textChanged("url(" + uri + ") " + rgb);
break;
case SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR:
textChanged("url(" + uri + ") " + rgb + ' ' + icc);
}
}
}
}
|
/**
* ------------------------------------------------------------------------------------------------
*
* Copyright 2015 - Giorgio Desideri
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
**/
package net.sf.gee.l2mn.stun.message.attribute;
import java.io.Serializable;
import java.util.Arrays;
/**
* https://tools.ietf.org/html/rfc5389#section-15
*
* {@code
* After the STUN header are zero or more attributes. Each attribute
* MUST be TLV encoded, with a 16-bit type, 16-bit length, and value.
* Each STUN attribute MUST end on a 32-bit boundary. As mentioned
* above, all fields in an attribute are transmitted most significant
* bit first.
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type | Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Value (variable) ....
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Figure 4: Format of STUN Attributes
*
* The value in the length field MUST contain the length of the Value
* part of the attribute, prior to padding, measured in bytes. Since
* STUN aligns attributes on 32-bit boundaries, attributes whose content
* is not a multiple of 4 bytes are padded with 1, 2, or 3 bytes of
* padding so that its value contains a multiple of 4 bytes. The
* padding bits are ignored, and may be any value.
* }
*
* @author Giorgio Desideri - giorgio.desideri@gmail.com
*
*/
public abstract class MessageAttribute implements Serializable {
private static final long serialVersionUID = 1L;
private int type = 0;
private int length = 0;
private byte[] value = null;
/**
*
*/
public MessageAttribute() {
super();
}
/**
* @param type
*/
public MessageAttribute(int type) {
this();
this.type = type;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public byte[] getValue() {
return value;
}
public void setValue(byte[] value) {
this.value = value;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + type;
result = prime * result + Arrays.hashCode(value);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MessageAttribute other = (MessageAttribute) obj;
if (type != other.type)
return false;
if (!Arrays.equals(value, other.value))
return false;
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("MessageAttribute [type=").append(type).append(", length=").append(length)
.append(", ");
if (value != null)
builder.append("value=").append(Arrays.toString(value));
builder.append("]");
return builder.toString();
}
}
|
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.data.ldap;
import javax.naming.ldap.LdapContext;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.ldap.repository.LdapRepository;
import org.springframework.data.ldap.repository.support.LdapRepositoryFactoryBean;
/**
* {@link EnableAutoConfiguration Auto-configuration} for Spring Data's LDAP Repositories.
*
* @author Eddú Meléndez
* @since 1.5.0
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ LdapContext.class, LdapRepository.class })
@ConditionalOnProperty(prefix = "spring.data.ldap.repositories", name = "enabled", havingValue = "true", matchIfMissing = true)
@ConditionalOnMissingBean(LdapRepositoryFactoryBean.class)
@Import(LdapRepositoriesRegistrar.class)
public class LdapRepositoriesAutoConfiguration {
}
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.util;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.NlsSafe;
import com.intellij.openapi.util.text.StringUtil;
import org.jdom.Element;
import org.jdom.Verifier;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class PropertiesComponentImpl extends PropertiesComponent implements PersistentStateComponent<Element> {
private static final Logger LOG = Logger.getInstance(PropertiesComponentImpl.class);
private final Map<String, String> myMap = new ConcurrentHashMap<>();
@NonNls private static final String ELEMENT_PROPERTY = "property";
@NonNls private static final String ATTRIBUTE_NAME = "name";
@NonNls private static final String ATTRIBUTE_VALUE = "value";
PropertiesComponentImpl() {
}
private void doPut(@NotNull String key, @NotNull String value) {
String reason = Verifier.checkCharacterData(key);
if (reason != null) {
LOG.error(reason);
}
myMap.put(key, value);
incModificationCount();
}
@Override
public Element getState() {
Element parentNode = new Element("state");
List<String> keys = new ArrayList<>(myMap.keySet());
keys.sort(null);
for (final String key : keys) {
String value = myMap.get(key);
if (value != null) {
Element element = new Element(ELEMENT_PROPERTY);
element.setAttribute(ATTRIBUTE_NAME, key);
element.setAttribute(ATTRIBUTE_VALUE, value);
parentNode.addContent(element);
}
}
return parentNode;
}
@Override
public void loadState(final @NotNull Element parentNode) {
myMap.clear();
for (Element e : parentNode.getChildren(ELEMENT_PROPERTY)) {
String name = e.getAttributeValue(ATTRIBUTE_NAME);
if (name != null) {
myMap.put(name, e.getAttributeValue(ATTRIBUTE_VALUE));
}
}
}
@Override
public @NlsSafe String getValue(@NotNull String name) {
return myMap.get(name);
}
@Override
public void setValue(@NotNull String name, @Nullable String value) {
if (value == null) {
unsetValue(name);
}
else {
doPut(name, value);
}
}
@Override
public void setValue(@NotNull String name, @Nullable String value, @Nullable String defaultValue) {
if (value == null || value.equals(defaultValue)) {
unsetValue(name);
}
else {
doPut(name, value);
}
}
@Override
public void setValue(@NotNull String name, float value, float defaultValue) {
if (value == defaultValue) {
unsetValue(name);
}
else {
doPut(name, String.valueOf(value));
}
}
@Override
public void setValue(@NotNull String name, int value, int defaultValue) {
if (value == defaultValue) {
unsetValue(name);
}
else {
doPut(name, String.valueOf(value));
}
}
@Override
public void setValue(@NotNull String name, boolean value, boolean defaultValue) {
if (value == defaultValue) {
unsetValue(name);
}
else {
setValue(name, String.valueOf(value));
}
}
@Override
public void unsetValue(@NotNull String name) {
myMap.remove(name);
incModificationCount();
}
@Override
public boolean isValueSet(@NotNull String name) {
return myMap.containsKey(name);
}
@Override
public String @Nullable [] getValues(@NotNull @NonNls String name) {
final String value = getValue(name);
return value != null ? value.split("\n") : null;
}
@Override
public void setValues(@NotNull @NonNls String name, String[] values) {
if (values == null) {
setValue(name, null);
}
else {
setValue(name, StringUtil.join(values, "\n"));
}
}
}
|
/**
* 版权所有 (TMS)
*/
package com.lhjz.portal.controller;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.lhjz.portal.base.BaseController;
import com.lhjz.portal.component.MailSender;
import com.lhjz.portal.constant.SysConstant;
import com.lhjz.portal.entity.Chat;
import com.lhjz.portal.entity.ChatAt;
import com.lhjz.portal.entity.ChatStow;
import com.lhjz.portal.entity.Label;
import com.lhjz.portal.entity.Log;
import com.lhjz.portal.entity.security.Group;
import com.lhjz.portal.entity.security.GroupMember;
import com.lhjz.portal.entity.security.User;
import com.lhjz.portal.model.Mail;
import com.lhjz.portal.model.RespBody;
import com.lhjz.portal.pojo.Enum.Action;
import com.lhjz.portal.pojo.Enum.ChatType;
import com.lhjz.portal.pojo.Enum.Prop;
import com.lhjz.portal.pojo.Enum.Status;
import com.lhjz.portal.pojo.Enum.Target;
import com.lhjz.portal.pojo.Enum.VoteType;
import com.lhjz.portal.repository.ChatAtRepository;
import com.lhjz.portal.repository.ChatRepository;
import com.lhjz.portal.repository.ChatStowRepository;
import com.lhjz.portal.repository.GroupMemberRepository;
import com.lhjz.portal.repository.GroupRepository;
import com.lhjz.portal.repository.LabelRepository;
import com.lhjz.portal.repository.LogRepository;
import com.lhjz.portal.util.CollectionUtil;
import com.lhjz.portal.util.DateUtil;
import com.lhjz.portal.util.MapUtil;
import com.lhjz.portal.util.StringUtil;
import com.lhjz.portal.util.TemplateUtil;
import com.lhjz.portal.util.WebUtil;
/**
*
* @author xi
*
* @date 2015年3月28日 下午1:19:05
*
*/
@Controller
@RequestMapping("admin/chat")
public class ChatController extends BaseController {
static Logger logger = LoggerFactory.getLogger(ChatController.class);
@Autowired
ChatRepository chatRepository;
@Autowired
GroupRepository groupRepository;
@Autowired
GroupMemberRepository groupMemberRepository;
@Autowired
LogRepository logRepository;
@Autowired
ChatAtRepository chatAtRepository;
@Autowired
ChatStowRepository chatStowRepository;
@Autowired
LabelRepository labelRepository;
@Autowired
MailSender mailSender;
String dynamicAction = "admin/dynamic";
@RequestMapping(value = "create", method = RequestMethod.POST)
@ResponseBody
public RespBody create(
@RequestParam("baseURL") String baseURL,
@RequestParam(value = "usernames", required = false) String usernames,
@RequestParam(value = "groups", required = false) String groups,
@RequestParam("content") String content,
@RequestParam(value = "preMore", defaultValue = "true") Boolean preMore,
@RequestParam("lastId") Long lastId,
@RequestParam("contentHtml") String contentHtml) {
if (StringUtil.isEmpty(content)) {
return RespBody.failed("提交内容不能为空!");
}
final User loginUser = getLoginUser();
Chat chat = new Chat();
chat.setContent(content);
chat.setCreateDate(new Date());
chat.setCreator(loginUser);
chat.setStatus(Status.New);
chat.setType(ChatType.Msg);
Chat chat2 = chatRepository.saveAndFlush(chat);
log(Action.Create, Target.Chat, chat2.getId());
final String href = baseURL + dynamicAction + "?id=" + chat2.getId();
final String html = contentHtml;
final Mail mail = Mail.instance();
if (StringUtil.isNotEmpty(usernames) || StringUtil.isNotEmpty(groups)) {
Map<String, User> atUserMap = new HashMap<String, User>();
if (StringUtil.isNotEmpty(usernames)) {
String[] usernameArr = usernames.split(",");
Arrays.asList(usernameArr).stream().forEach((username) -> {
User user = getUser(username);
if (user != null) {
mail.addUsers(user);
atUserMap.put(user.getUsername(), user);
}
});
}
if (StringUtil.isNotEmpty(groups)) {
String[] groupArr = groups.split(",");
Arrays.asList(groupArr)
.stream()
.forEach(
(group) -> {
List<Group> groupList = groupRepository
.findByGroupName(group);
if (groupList.size() > 0) {
List<GroupMember> groupMembers = groupMemberRepository
.findByGroup(groupList.get(0));
groupMembers.stream().forEach(
gm -> {
User user = getUser(gm
.getUsername());
if (user != null) {
mail.addUsers(user);
atUserMap.put(user
.getUsername(),
user);
}
});
}
});
}
List<ChatAt> chatAtList = new ArrayList<ChatAt>();
// 保存chatAt关系
atUserMap.values().forEach((user) -> {
ChatAt chatAt = new ChatAt();
chatAt.setChat(chat2);
chatAt.setAtUser(user);
chatAt.setCreateDate(new Date());
chatAt.setCreator(loginUser);
chatAtList.add(chatAt);
});
chatAtRepository.save(chatAtList);
chatAtRepository.flush();
try {
mailSender.sendHtmlByQueue(
String.format("DCST-沟通动态@消息_%s", DateUtil.format(new Date(), DateUtil.FORMAT7)),
TemplateUtil.process("templates/mail/mail-dynamic", MapUtil.objArr2Map("user", loginUser,
"date", new Date(), "href", href, "title", "下面的沟通消息中有@到你", "content", html)),
getLoginUserName(loginUser), mail.get());
} catch (Exception e) {
e.printStackTrace();
}
}
if (!preMore && chatRepository.countQueryRecent(lastId) <= 50) {
List<Chat> chats = chatRepository.queryRecent(lastId);
return RespBody.succeed(chats);
}
return RespBody.succeed(chat2);
}
@RequestMapping(value = "update", method = RequestMethod.POST)
@ResponseBody
public RespBody update(
@RequestParam("id") Long id,
@RequestParam("version") Long version,
@RequestParam("content") String content,
@RequestParam("baseURL") String baseURL,
@RequestParam(value = "usernames", required = false) String usernames,
@RequestParam(value = "groups", required = false) String groups,
@RequestParam(value = "diff", required = false) String diff,
@RequestParam(value = "contentHtmlOld", required = false) String contentHtmlOld,
@RequestParam(value = "contentHtml", required = false) String contentHtml) {
if (StringUtil.isEmpty(content)) {
return RespBody.failed("更新内容不能为空!");
}
final User loginUser = getLoginUser();
Chat chat = chatRepository.findOne(id);
Boolean isOpenEdit = chat.getOpenEdit() == null ? false : chat
.getOpenEdit();
if (!isSuperOrCreator(chat.getCreator().getUsername()) && !isOpenEdit) {
return RespBody.failed("您没有权限编辑该消息内容!");
}
if (chat.getVersion() != version.longValue()) {
return RespBody.failed("该消息已经被其他人更新,请刷新消息重新编辑提交!");
}
if (content.equals(chat.getContent())) {
return RespBody.failed("修改内容没有任何变更的内容!");
}
chat.setContent(content);
chat.setUpdateDate(new Date());
chat.setUpdater(loginUser);
chat.setStatus(Status.Updated);
Chat chat2 = chatRepository.saveAndFlush(chat);
log(Action.Update, Target.Chat, chat2.getId());
final String href = baseURL + dynamicAction + "?id=" + chat2.getId();
final String html;
if(StringUtil.isNotEmpty(diff)) {
html = "<h3>内容(Markdown)变更对比:</h3><b>原文链接:</b> <a href=\"" + href + "\">" + href + "</a><hr/>" + diff;
} else {
html = "<h3>编辑后内容:</h3>" + contentHtml + "<hr/><h3>编辑前内容:</h3>" + contentHtmlOld;
}
final Mail mail = Mail.instance();
if (StringUtil.isNotEmpty(usernames) || StringUtil.isNotEmpty(groups)) {
Map<String, User> atUserMap = new HashMap<String, User>();
if (StringUtil.isNotEmpty(usernames)) {
String[] usernameArr = usernames.split(",");
Arrays.asList(usernameArr).stream().forEach((username) -> {
User user = getUser(username);
if (user != null) {
mail.addUsers(user);
atUserMap.put(user.getUsername(), user);
}
});
}
if (StringUtil.isNotEmpty(groups)) {
String[] groupArr = groups.split(",");
Arrays.asList(groupArr)
.stream()
.forEach(
(group) -> {
List<Group> groupList = groupRepository
.findByGroupName(group);
if (groupList.size() > 0) {
List<GroupMember> groupMembers = groupMemberRepository
.findByGroup(groupList.get(0));
groupMembers.stream().forEach(
gm -> {
User user = getUser(gm
.getUsername());
if (user != null) {
mail.addUsers(user);
atUserMap.put(user
.getUsername(),
user);
}
});
}
});
}
List<ChatAt> chatAtList = new ArrayList<ChatAt>();
// 保存chatAt关系
atUserMap.values().forEach(
(user) -> {
ChatAt chatAt2 = chatAtRepository
.findOneByChatAndAtUser(chat2, user);
if (chatAt2 == null) {
ChatAt chatAt = new ChatAt();
chatAt.setChat(chat2);
chatAt.setAtUser(user);
chatAtList.add(chatAt);
} else {
chatAt2.setStatus(Status.New);
chatAtList.add(chatAt2);
}
});
chatAtRepository.save(chatAtList);
chatAtRepository.flush();
try {
mailSender.sendHtmlByQueue(
String.format("DCST-沟通动态编辑@消息_%s", DateUtil.format(new Date(), DateUtil.FORMAT7)),
TemplateUtil.process("templates/mail/mail-dynamic", MapUtil.objArr2Map("user", loginUser,
"date", new Date(), "href", href, "title", "下面编辑的沟通消息中有@到你", "content", html)),
getLoginUserName(loginUser), mail.get());
} catch (Exception e) {
e.printStackTrace();
}
}
return RespBody.succeed(chat2);
}
@RequestMapping(value = "delete", method = RequestMethod.POST)
@ResponseBody
public RespBody delete(@RequestParam("id") Long id) {
Chat chat = chatRepository.findOne(id);
if (chat == null) {
return RespBody.failed("删除聊天内容不存在!");
}
if (!isSuperOrCreator(chat.getCreator().getUsername())) {
return RespBody.failed("您没有权限删除该消息内容!");
}
List<ChatAt> chatAts = chatAtRepository.findByChat(chat);
chatAtRepository.delete(chatAts);
chatAtRepository.flush();
List<ChatStow> chatStows = chatStowRepository.findByChat(chat);
chatStowRepository.delete(chatStows);
chatStowRepository.flush();
chatRepository.delete(chat);
chatRepository.flush();
log(Action.Delete, Target.Chat, chat.getId(), chat);
return RespBody.succeed(id);
}
@RequestMapping(value = { "get", "get/unmask" }, method = RequestMethod.GET)
@ResponseBody
public RespBody get(@RequestParam("id") Long id) {
Chat chat = chatRepository.findOne(id);
if (chat == null) {
return RespBody.failed("获取聊天内容不存在!");
}
return RespBody.succeed(chat);
}
@RequestMapping(value = { "poll", "poll/unmask" }, method = RequestMethod.GET)
@ResponseBody
public RespBody poll(
@RequestParam("lastId") Long lastId,
@RequestParam("lastEvtId") Long lastEvtId,
@RequestParam(value = "isAt", required = false, defaultValue = "false") Boolean isAt) {
long cnt = isAt ? chatRepository.countQueryRecentAt(
WebUtil.getUsername(), lastId) : chatRepository
.countQueryRecent(lastId);
long cntLogs = logRepository.countQueryRecent(lastEvtId);
long cntAtUserNew = chatAtRepository.countChatAtUserNew(WebUtil
.getUsername());
Long[] data = new Long[] { lastId, cnt, lastEvtId, cntLogs,
cntAtUserNew };
List<Log> logs = logRepository.queryRecent(lastEvtId);
return RespBody.succeed(data).addMsg(logs);
}
@RequestMapping(value = { "getNews", "getNews/unmask" }, method = RequestMethod.GET)
@ResponseBody
public RespBody getNews(@RequestParam("lastId") Long lastId) {
List<Chat> chats = chatRepository.queryRecent(lastId);
return RespBody.succeed(chats);
}
@RequestMapping(value = "more", method = RequestMethod.GET)
@ResponseBody
public RespBody more(
@PageableDefault(sort = { "createDate" }, direction = Direction.DESC) Pageable pageable) {
Page<Chat> chats = chatRepository.findAll(pageable);
chats = new PageImpl<Chat>(CollectionUtil.reverseList(chats
.getContent()), pageable, chats.getTotalElements());
return RespBody.succeed(chats);
}
@RequestMapping(value = "more/old", method = RequestMethod.GET)
@ResponseBody
public RespBody moreOld(
@RequestParam("startId") Long startId,
@RequestParam(value = "size", required = false, defaultValue = "10") int size) {
List<Chat> chats = chatRepository.queryMoreOld(startId, size);
long countAllOld = chatRepository.countAllOld(startId);
Map<String, Object> map = new HashMap<>();
map.put("content", CollectionUtil.reverseList(chats));
map.put("hasMore", countAllOld > chats.size());
map.put("countMore", countAllOld - chats.size());
map.put("numberOfElements", chats.size());
map.put("size", size);
return RespBody.succeed(map);
}
@RequestMapping(value = "more/new", method = RequestMethod.GET)
@ResponseBody
public RespBody moreNew(
@RequestParam("startId") Long startId,
@RequestParam(value = "size", required = false, defaultValue = "10") int size) {
List<Chat> chats = chatRepository.queryMoreNew(startId, size);
long countAllNew = chatRepository.countAllNew(startId);
Map<String, Object> map = new HashMap<>();
map.put("content", chats);
map.put("hasMore", countAllNew > chats.size());
map.put("countMore", countAllNew - chats.size());
map.put("numberOfElements", chats.size());
map.put("size", size);
return RespBody.succeed(map);
}
@RequestMapping(value = "moreLogs", method = RequestMethod.GET)
@ResponseBody
public RespBody moreLogs(
@PageableDefault(sort = { "createDate" }, direction = Direction.DESC) Pageable pageable) {
Page<Log> logs = logRepository.findByTarget(Target.Translate, pageable);
return RespBody.succeed(logs);
}
@RequestMapping(value = { "search", "search/unmask" }, method = RequestMethod.GET)
@ResponseBody
public RespBody search(
@PageableDefault(sort = { "createDate" }, direction = Direction.DESC) Pageable pageable,
@RequestParam(value = "search", required = true) String search) {
Page<Chat> chats = null;
if (search.startsWith(SysConstant.FILTER_PRE)) {
String query = search.substring(SysConstant.FILTER_PRE.length());
String[] querys = query.split(":");
final List<User> users = new ArrayList<>();
String searchContent = null;
if (querys.length > 0) {
Stream.of(querys[0].split("&")).filter((name) -> {
return StringUtil.isNotEmpty(name.trim());
}).forEach((name) -> {
User user = getUser(name);
if (user != null) {
users.add(user);
}
});
}
if (querys.length > 1) {
searchContent = querys[1].trim();
}
if (CollectionUtil.isNotEmpty(users)) {
if (StringUtil.isNotEmpty(searchContent)) {
chats = chatRepository.findByCreatorInAndContentContainingIgnoreCase(
users, searchContent, pageable);
} else {
chats = chatRepository.findByCreatorIn(users, pageable);
}
} else {
return RespBody.failed("查询指定创建者不存在!");
}
} else {
chats = chatRepository.findByContentLike("%" + search + "%",
pageable);
}
return RespBody.succeed(chats);
}
@RequestMapping(value = { "searchBy", "searchBy/unmask" }, method = RequestMethod.GET)
@ResponseBody
public RespBody searchBy(
@RequestParam(value = "id") Long id,
@PageableDefault(sort = { "createDate" }, direction = Direction.DESC) Pageable pageable) {
long cntGtId = chatRepository.countGtId(id);
int size = pageable.getPageSize();
long page = cntGtId / size;
if (cntGtId % size == 0) {
page--;
}
pageable = new PageRequest(page > -1 ? (int) page : 0, size,
Direction.DESC, "createDate");
Page<Chat> chats = chatRepository.findAll(pageable);
chats = new PageImpl<Chat>(CollectionUtil.reverseList(chats
.getContent()), pageable, chats.getTotalElements());
return RespBody.succeed(chats);
}
private boolean isVoterExists(String voters) {
boolean isExits = false;
if (voters != null) {
String loginUsername = WebUtil.getUsername();
String[] voterArr = voters.split(",");
for (String voter : voterArr) {
if (voter.equals(loginUsername)) {
isExits = true;
break;
}
}
}
return isExits;
}
@RequestMapping(value = { "vote", "vote/unmask" }, method = RequestMethod.POST)
@ResponseBody
public RespBody vote(@RequestParam("id") Long id,
@RequestParam("baseURL") String baseURL,
@RequestParam("contentHtml") String contentHtml,
@RequestParam(value = "type", required = false) String type) {
Chat chat = chatRepository.findOne(id);
if (chat == null) {
return RespBody.failed("投票聊天内容不存在!");
}
String loginUsername = WebUtil.getUsername();
Chat chat2 = null;
String title = "";
final User loginUser = getLoginUser();
if (VoteType.Zan.name().equalsIgnoreCase(type)) {
String voteZan = chat.getVoteZan();
if (isVoterExists(voteZan)) {
return RespBody.failed("您已经投票[赞]过!");
} else {
chat.setVoteZan(voteZan == null ? loginUsername : voteZan + ','
+ loginUsername);
Integer voteZanCnt = chat.getVoteZanCnt();
if (voteZanCnt == null) {
voteZanCnt = 0;
}
chat.setVoteZanCnt(++voteZanCnt);
chat2 = chatRepository.saveAndFlush(chat);
title = loginUser.getName() + "[" + loginUsername
+ "]赞了你的沟通消息!";
}
} else {
String voteCai = chat.getVoteCai();
if (isVoterExists(voteCai)) {
return RespBody.failed("您已经投票[踩]过!");
} else {
chat.setVoteCai(voteCai == null ? loginUsername : voteCai + ','
+ loginUsername);
Integer voteCaiCnt = chat.getVoteCaiCnt();
if (voteCaiCnt == null) {
voteCaiCnt = 0;
}
chat.setVoteCaiCnt(++voteCaiCnt);
chat2 = chatRepository.saveAndFlush(chat);
title = loginUser.getName() + "[" + loginUsername
+ "]踩了你的沟通消息!";
}
}
final String href = baseURL + dynamicAction + "?id=" + id;
final String titleHtml = title;
final Mail mail = Mail.instance().addUsers(chat.getCreator());
final String html = "<h3>投票沟通消息内容:</h3><hr/>" + contentHtml;
try {
mailSender
.sendHtmlByQueue(String.format("DCST-沟通动态投票@消息_%s", DateUtil.format(new Date(), DateUtil.FORMAT7)),
TemplateUtil.process("templates/mail/mail-dynamic", MapUtil.objArr2Map("user", loginUser,
"date", new Date(), "href", href, "title", titleHtml, "content", html)),
getLoginUserName(loginUser), mail.get());
} catch (Exception e) {
e.printStackTrace();
}
log(Action.Vote, Target.Chat, chat.getId(), chat2);
return RespBody.succeed(chat2);
}
@RequestMapping(value = { "getAtChats", "getAtChats/unmask" }, method = RequestMethod.GET)
@ResponseBody
public RespBody getAtChats(
@PageableDefault(sort = { "createDate" }, direction = Direction.DESC) Pageable pageable) {
Page<ChatAt> chatAts = chatAtRepository.findByChatNotNullAndAtUserAndStatus(
getLoginUser(), Status.New, pageable);
return RespBody.succeed(chatAts);
}
@RequestMapping(value = { "markAsReaded", "markAsReaded/unmask" }, method = RequestMethod.POST)
@ResponseBody
public RespBody markAsReaded(@RequestParam("chatAtId") Long chatAtId) {
ChatAt chatAt = chatAtRepository.findOne(chatAtId);
if (chatAt == null) {
return RespBody.failed("@消息不存在,可能已经被删除!");
}
chatAt.setStatus(Status.Readed);
chatAtRepository.saveAndFlush(chatAt);
return RespBody.succeed(chatAt);
}
@RequestMapping(value = { "markAsReadedByChat", "markAsReadedByChat/unmask" }, method = RequestMethod.POST)
@ResponseBody
public RespBody markAsReadedByChat(@RequestParam("chatId") Long chatId) {
Chat chat = chatRepository.findOne(chatId);
if (chat == null) {
return RespBody.failed("@消息不存在,可能已经被删除!");
}
int cnt = chatAtRepository.markChatAsReaded(chat, getLoginUser());
return RespBody.succeed(cnt);
}
@RequestMapping(value = { "markAllAsReaded",
"markAllAsReaded/unmask" }, method = RequestMethod.POST)
@ResponseBody
public RespBody markAllAsReaded() {
int cnt = chatAtRepository.markChatAllAsReaded(getLoginUser());
return RespBody.succeed(cnt);
}
@RequestMapping(value = { "stow", "stow/unmask" }, method = RequestMethod.POST)
@ResponseBody
public RespBody stow(@RequestParam("id") Long id) {
Chat chat = chatRepository.findOne(id);
if (chat == null) {
return RespBody.failed("收藏消息不存在,可能已经被删除!");
}
User loginUser = getLoginUser();
ChatStow chatStow = chatStowRepository.findOneByChatAndStowUser(chat,
loginUser);
if (chatStow != null) {
return RespBody.failed("收藏消息重复!");
}
ChatStow chatStow2 = new ChatStow();
chatStow2.setChat(chat);
chatStow2.setStowUser(loginUser);
ChatStow chatStow3 = chatStowRepository.saveAndFlush(chatStow2);
return RespBody.succeed(chatStow3);
}
@RequestMapping(value = { "removeStow", "removeStow/unmask" }, method = RequestMethod.POST)
@ResponseBody
public RespBody removeStow(@RequestParam("id") Long id) {
chatStowRepository.delete(id);
return RespBody.succeed(id);
}
@RequestMapping(value = { "getStows", "getStows/unmask" }, method = RequestMethod.GET)
@ResponseBody
public RespBody getStows() {
List<ChatStow> chatStows = chatStowRepository.findByChatNotNullAndStowUserAndStatus(
getLoginUser(), Status.New);
return RespBody.succeed(chatStows);
}
@RequestMapping(value = "getReplies", method = RequestMethod.GET)
@ResponseBody
public RespBody getReplies(@RequestParam("id") Long id) {
// [回复#871](http://translation.sh1.newtouch.com/admin/dynamic?id=871)
String query = StringUtil.replaceByKV(
"%[回复#{id}](%/admin/dynamic?id={id})%", "id", id);
List<Chat> chats = chatRepository.queryReplies(id, query);
return RespBody.succeed(chats);
}
@RequestMapping(value = "openEdit", method = RequestMethod.POST)
@ResponseBody
public RespBody openEdit(@RequestParam("id") Long id,
@RequestParam("open") Boolean open) {
Chat chat = chatRepository.findOne(id);
if (chat == null) {
return RespBody.failed("操作消息不存在,可能已经被删除!");
}
chat.setOpenEdit(open);
chatRepository.saveAndFlush(chat);
return RespBody.succeed();
}
@RequestMapping(value = { "asWiki", "asWiki/unmask" }, method = RequestMethod.POST)
@ResponseBody
public RespBody asWiki(@RequestParam("id") Long id,
@RequestParam("baseURL") String baseURL,
@RequestParam("title") String title,
@RequestParam(value = "privated", required = false) Boolean privated,
@RequestParam(value = "labels", required = false) String labels) {
if (StringUtil.isEmpty(title)) {
return RespBody.failed("标题不能为空!");
}
Chat chat = chatRepository.findOne(id);
if (chat == null) {
return RespBody.failed("聊天内容不存在!");
}
chat.setTitle(title);
chat.setType(ChatType.Wiki);
chat.setPrivated(privated == null ? false : privated);
Chat chat2 = chatRepository.saveAndFlush(chat);
if (StringUtil.isNotEmpty(labels)) {
List<Label> labelList = new ArrayList<Label>();
String[] labelArr = labels.split(SysConstant.COMMA);
Stream.of(labelArr).forEach((lbl) -> {
Label label = new Label();
label.setCreateDate(new Date());
label.setCreator(WebUtil.getUsername());
label.setName(lbl);
label.setStatus(Status.New);
label.setChat(chat2);
labelList.add(label);
});
labelRepository.save(labelList);
labelRepository.flush();
}
logWithProperties(Action.Update, Target.Chat, chat2.getId(),
Prop.Title.name(), title);
return RespBody.succeed(id);
}
@RequestMapping(value = { "updateWiki", "updateWiki/unmask" }, method = RequestMethod.POST)
@ResponseBody
public RespBody updateWiki(@RequestParam("id") Long id,
@RequestParam("baseURL") String baseURL,
@RequestParam("title") String title,
@RequestParam(value = "privated", required = false) Boolean privated,
@RequestParam(value = "labels", required = false) String labels) {
if (StringUtil.isEmpty(title)) {
return RespBody.failed("标题不能为空!");
}
Chat chat = chatRepository.findOne(id);
if (chat == null) {
return RespBody.failed("聊天内容不存在!");
}
if (!isSuperOrCreator(chat.getCreator().getUsername())) {
return RespBody.failed("您没有权限编辑该消息内容!");
}
String oldTitle = chat.getTitle();
chat.setTitle(title);
if (privated != null) {
chat.setPrivated(privated);
}
Chat chat2 = chatRepository.saveAndFlush(chat);
if (StringUtil.isNotEmpty(labels)) {
List<Label> labelList2 = labelRepository.findByChat(chat2);
labelRepository.delete(labelList2);
labelRepository.flush();
List<Label> labelList = new ArrayList<Label>();
String[] labelArr = labels.split(SysConstant.COMMA);
Stream.of(labelArr).forEach((lbl) -> {
Label label = new Label();
label.setCreateDate(new Date());
label.setCreator(WebUtil.getUsername());
label.setName(lbl);
label.setStatus(Status.New);
label.setChat(chat2);
labelList.add(label);
});
labelRepository.save(labelList);
labelRepository.flush();
}
logWithProperties(Action.Update, Target.Chat, chat2.getId(),
Prop.Title.name(), title, oldTitle);
return RespBody.succeed(id);
}
@RequestMapping(value = "deleteWiki", method = RequestMethod.POST)
@ResponseBody
public RespBody deleteWiki(@RequestParam("id") Long id) {
Chat chat = chatRepository.findOne(id);
if (chat == null) {
return RespBody.failed("博文不存在!");
}
if (!isSuperOrCreator(chat.getCreator().getUsername())) {
return RespBody.failed("您没有权限编辑该消息内容!");
}
chat.setType(ChatType.Msg);
chatRepository.saveAndFlush(chat);
return RespBody.succeed(id);
}
@RequestMapping(value = { "addLabel", "addLabel/unmask" }, method = RequestMethod.POST)
@ResponseBody
public RespBody addLabel(@RequestParam("id") Long id,
@RequestParam("baseURL") String baseURL,
@RequestParam("label") String label) {
if (StringUtil.isEmpty(label)) {
return RespBody.failed("标签不能为空!");
}
Chat chat = chatRepository.findOne(id);
if (chat == null) {
return RespBody.failed("聊天内容不存在!");
}
Label label2 = new Label();
label2.setCreateDate(new Date());
label2.setCreator(WebUtil.getUsername());
label2.setName(label);
label2.setStatus(Status.New);
label2.setChat(chat);
labelRepository.save(label2);
labelRepository.flush();
logWithProperties(Action.Update, Target.Chat, chat.getId(),
Prop.Labels.name(), label);
return RespBody.succeed(id);
}
@RequestMapping(value = { "deleteLabel", "deleteLabel/unmask" }, method = RequestMethod.POST)
@ResponseBody
public RespBody deleteLabel(@RequestParam("baseURL") String baseURL,
@RequestParam("labelId") Long labelId) {
Label label = labelRepository.findOne(labelId);
if (!isSuperOrCreator(label.getCreator())) {
return RespBody.failed("您没有权限删除该标签!");
}
labelRepository.delete(labelId);
log(Action.Delete, Target.Label, labelId);
return RespBody.succeed(labelId);
}
}
|
/*
* Copyright 2020 Crown Copyright
*
* 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 uk.gov.gchq.gaffer.doc.function;
import uk.gov.gchq.koryphe.impl.function.StringReplace;
public class StringReplaceExample extends FunctionExample {
public StringReplaceExample() {
super(StringReplace.class);
}
public static void main(final String[] args) {
new StringReplaceExample().runAndPrint();
}
@Override
protected void runExamples() {
replaceStrings();
}
private void replaceStrings() {
// ---------------------------------------------------------
final StringReplace function = new StringReplace("[tea", "cake");
// ---------------------------------------------------------
runExample(function, null, "tea", "Tea", "TEA", "brainteaser", null, "coffee", 5L);
}
}
|
/*
* ARX: Powerful Data Anonymization
* Copyright 2012 - 2021 Fabian Prasser and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.deidentifier.arx;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* This class encapsulates a generalization scheme
* @author Fabian Prasser
*/
public class DataGeneralizationScheme implements Serializable, Cloneable { // NO_UCD
/**
* A specific generalization degree
* @author Fabian Prasser
*
*/
public static enum GeneralizationDegree implements Serializable {
NONE(0d),
LOW(0.2d),
LOW_MEDIUM(0.4d),
MEDIUM(0.5d),
MEDIUM_HIGH(0.6d),
HIGH(0.8d),
COMPLETE(1d);
/** Factor*/
private final double factor;
/**
* Constructor
* @param factor
*/
private GeneralizationDegree(double factor) {
this.factor = factor;
}
/**
* Returns the factor
* @return
*/
protected double getFactor() {
return this.factor;
}
}
/** SVUID*/
private static final long serialVersionUID = -5402090022629905154L;
/**
* Creates a new data generalization scheme
* @return
*/
public static DataGeneralizationScheme create() {
return new DataGeneralizationScheme(null, null);
}
/**
* Creates a new data generalization scheme
* @param data
* @return
*/
public static DataGeneralizationScheme create(Data data) {
return new DataGeneralizationScheme(data, null);
}
/**
* Creates a new data generalization scheme
* @param data
* @param degree
* @return
*/
public static DataGeneralizationScheme create(Data data, GeneralizationDegree degree) {
return new DataGeneralizationScheme(data, degree);
}
/**
* Creates a new data generalization scheme
* @param degree
* @return
*/
public static DataGeneralizationScheme create(GeneralizationDegree degree) {
return new DataGeneralizationScheme(null, degree);
}
/** Degrees */
private Map<String, GeneralizationDegree> degrees = new HashMap<String, GeneralizationDegree>();
/** Levels */
private Map<String, Integer> levels = new HashMap<String, Integer>();
/** Degree */
private GeneralizationDegree degree = null;
/** Data */
private Set<String> attributes;
/**
* Creates a new instance
* @param data
* @param degree
*/
private DataGeneralizationScheme(Data data, GeneralizationDegree degree) {
if (data != null) {
this.attributes = new HashSet<String>();
for (int i=0; i<data.getHandle().getNumColumns(); i++) {
this.attributes.add(data.getHandle().getAttributeName(i));
}
} else {
this.attributes = null;
}
this.degree = degree;
}
/**
* Clone method
*/
public DataGeneralizationScheme clone() {
DataGeneralizationScheme result = new DataGeneralizationScheme(null, null);
result.degrees = new HashMap<String, GeneralizationDegree>(this.degrees);
result.degree = this.degree;
result.levels = new HashMap<String, Integer>(this.levels);
result.attributes = this.attributes != null ? new HashSet<String>(this.attributes) : null;
return result;
}
/**
* Defines a specific generalization degree
* @param degree
* @return
*/
public DataGeneralizationScheme generalize(GeneralizationDegree degree) {
this.degree = degree;
return this;
}
/**
* Defines a specific generalization degree
* @param attribute
* @param degree
* @return
*/
public DataGeneralizationScheme generalize(String attribute, GeneralizationDegree degree) {
check(attribute);
this.degrees.put(attribute, degree);
return this;
}
/**
* Defines a specific generalization level
* @param attribute
* @param level
* @return
*/
public DataGeneralizationScheme generalize(String attribute, int level) {
check(attribute);
if (level < 0) {
throw new IllegalArgumentException("Invalid generalization level: " + level);
}
this.levels.put(attribute, level);
return this;
}
/**
* Returns the overall generalization degree, if any
* @return
*/
public GeneralizationDegree getGeneralizationDegree() {
return this.degree;
}
/**
* Returns a generalization level as defined by this class
* @param attribute
* @param definition
* @return
*/
public int getGeneralizationLevel(String attribute, DataDefinition definition) {
int result = 0;
if (definition.isHierarchyAvailable(attribute)) {
if (this.levels.containsKey(attribute)) {
result = this.levels.get(attribute);
} else if (this.degrees.containsKey(attribute)) {
result = (int) Math.round( (this.degrees.get(attribute).getFactor() *
(double) definition.getMaximumGeneralization(attribute)));
} else if (this.degree != null) {
result = (int) Math.round(this.degree.getFactor() *
(double) definition.getMaximumGeneralization(attribute));
}
}
result = Math.max(result, definition.getMinimumGeneralization(attribute));
result = Math.min(result, definition.getMaximumGeneralization(attribute));
return result;
}
/**
* Checks the given attribute
* @param attribute
*/
private void check(String attribute) {
if (attributes != null && !attributes.contains(attribute)) {
throw new IllegalArgumentException("Unknown attribute: " + attribute);
}
}
}
|
package com.toldcalculator.android.tc.model.dao;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.OnConflictStrategy;
import android.arch.persistence.room.Query;
import com.toldcalculator.android.tc.model.entity.TakeoffData;
@Dao
public interface TakeoffDataDao {
@Insert(onConflict = OnConflictStrategy.FAIL)
long insert(TakeoffData takeoffData);
@Query(Queries.HIGHALT_HIGHWEIGHT_HIGHTEMP)
TakeoffData selectHighAll(int altitude, int weight, int temperature);
@Query(Queries.HIGHALT_HIGHWEIGHT_LOWTEMP)
TakeoffData selectHighAltHighWTLowTemp(int altitude, int weight, int temperature);
@Query(Queries.HIGHALT_LOWWEIGHT_HIGHTEMP)
TakeoffData selectHighAltLowWTHighTemp(int altitude, int weight, int temperature);
@Query(Queries.HIGHALT_LOWWEIGHT_LOWTEMP)
TakeoffData selectHighAltLowWtLowTemp(int altitude, int weight, int temperature);
@Query(Queries.LOWALT_HIGHWEIGHT_HIGHTEMP)
TakeoffData selectLowAltHighWTHighTemp(int altitude, int weight, int temperature);
@Query(Queries.LOWALT_HIGHWEIGHT_LOWTEMP)
TakeoffData selectLowAltHighWTLowTemp(int altitude, int weight, int temperature);
@Query(Queries.LOWALT_LOWWEIGHT_HIGHTEMP)
TakeoffData selectLowAltLowWTHighTemp(int altitude, int weight, int temperature);
@Query(Queries.LOWALT_LOWWEIGHT_LOWTEMP)
TakeoffData selectLowAll(int altitude, int weight, int temperature);
}
|
/*
* Copyright (c) 2016. Axon Framework
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.axonframework.samples.bank.web.dto;
import lombok.Value;
@Value
public class DepositDto {
private String bankAccountId;
private long amount;
}
|
/**
* Licensed to Big Data Genomics (BDG) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The BDG 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.bdgenomics.adam.apis.java;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.spark.api.java.JavaRDD;
import org.bdgenomics.adam.apis.java.JavaADAMContext;
import org.bdgenomics.adam.models.RecordGroupDictionary;
import org.bdgenomics.adam.models.SequenceDictionary;
import org.bdgenomics.adam.rdd.ADAMContext;
import org.bdgenomics.adam.rdd.fragment.FragmentRDD;
import org.bdgenomics.formats.avro.AlignmentRecord;
/**
* A simple test class for the JavaADAMRDD/Context. Writes an RDD of fragments to
* disk and reads it back.
*/
class JavaADAMFragmentConduit {
public static FragmentRDD conduit(FragmentRDD recordRdd,
ADAMContext ac) throws IOException {
// make temp directory and save file
Path tempDir = Files.createTempDirectory("javaAC");
String fileName = tempDir.toString() + "/testRdd.fragment.adam";
recordRdd.save(fileName);
// create a new adam context and load the file
JavaADAMContext jac = new JavaADAMContext(ac);
return jac.loadFragments(fileName);
}
}
|
/*
* Configurate
* Copyright (C) zml and Configurate contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.spongepowered.configurate.transformation;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.spongepowered.configurate.transformation.NodePath.path;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.Test;
import org.spongepowered.configurate.BasicConfigurationNode;
import org.spongepowered.configurate.ScopedConfigurationNode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ConfigurationTransformationTest {
private static Object[] arr(final Object... path) {
return path;
}
@Test
public void testComparator() {
doTestComparator(BasicConfigurationNode.root());
}
private <T extends ScopedConfigurationNode<T>> void doTestComparator(final T node) {
final List<NodePath> unsortedKeys = Arrays.asList(
path("a", "c", "c"),
path("a", "b"),
path("a", "b", "c"),
path("a", "b", "d"),
path("a", "b", "c", "d"),
path("a", "c"),
path("a", "b", "b")
);
final List<NodePath> autoSortedKeys = new ArrayList<>();
final List<NodePath> expectedSortedKeys = Arrays.asList(
path("a", "b", "b"),
path("a", "b", "c", "d"),
path("a", "b", "c"),
path("a", "b", "d"),
path("a", "b"),
path("a", "c", "c"),
path("a", "c")
);
final TransformAction<T> action = (inputPath, valueAtPath) -> {
autoSortedKeys.add(inputPath.clone());
return null;
};
final ConfigurationTransformation.Builder<T> build = ConfigurationTransformation.builder();
for (NodePath path : unsortedKeys) {
build.addAction(path, action);
}
for (NodePath path : unsortedKeys) {
final T child = node.getNode(path);
if (child.isVirtual()) {
child.setValue("meaningless test value");
}
}
build.build().apply(node);
assertEquals(expectedSortedKeys, autoSortedKeys);
}
@Test
public void testWildcardMatching() {
final BasicConfigurationNode node = BasicConfigurationNode.root();
final List<NodePath> wildcardMatch = Arrays.asList(
path("a", ConfigurationTransformation.WILDCARD_OBJECT, "c"),
path("a", ConfigurationTransformation.WILDCARD_OBJECT, "d"),
path("a", "c", "c"),
path("b", ConfigurationTransformation.WILDCARD_OBJECT, "d", ConfigurationTransformation.WILDCARD_OBJECT,
"f")
);
final List<NodePath> populatedResults = new ArrayList<>();
final List<NodePath> expectedResult = Arrays.asList(
path("a", "c", "c"),
path("a", "c", "c"),
path("a", "d", "c"),
path("a", "b", "c"),
path("a", "c", "d"),
path("a", "d", "d"),
path("b", "c", "d", "e", "f"),
path("b", "c", "d", "f", "f"),
path("b", "d", "d", "e", "f"),
path("b", "d", "d", "f", "f")
);
final TransformAction<BasicConfigurationNode> action = (path, valueAthPath) -> {
populatedResults.add(path.clone());
return null;
};
final ConfigurationTransformation.Builder<BasicConfigurationNode> build = ConfigurationTransformation.builder();
for (NodePath path : wildcardMatch) {
build.addAction(path, action);
}
for (NodePath path : expectedResult) {
node.getNode(path).setValue("lame");
}
build.build().apply(node);
assertEquals(expectedResult, populatedResults);
}
@Test
public void testMoveNode() {
final BasicConfigurationNode node = BasicConfigurationNode.root();
final Object nodeValue = new Object();
node.getNode("old", "path").setValue(nodeValue);
ConfigurationTransformation.<BasicConfigurationNode>builder()
.addAction(path("old", "path"),
(inputPath, valueAtPath) -> arr("new", "path"))
.build().apply(node);
assertTrue(node.getNode("old", "path").isVirtual());
assertEquals(nodeValue, node.getNode("new", "path").getValue());
}
@Test
public void testChainedTransformations() {
final BasicConfigurationNode node = BasicConfigurationNode.root();
node.getNode("a").setValue("something?");
final List<String> actualOutput = new ArrayList<>();
final List<String> expectedOutput = ImmutableList.of("one", "two");
transformChained(actualOutput, node);
assertEquals(expectedOutput, actualOutput);
}
@SuppressWarnings("unchecked")
private <T extends ScopedConfigurationNode<T>> void transformChained(final List<String> actualOutput, final T node) {
ConfigurationTransformation.chain(ConfigurationTransformation.<T>builder().addAction(path("a"), (inputPath, valueAtPath) -> {
actualOutput.add("one");
return null;
}).build(), ConfigurationTransformation.<T>builder().addAction(path("a"), (inputPath, valueAtPath) -> {
actualOutput.add("two");
return null;
}).build()).apply(node);
}
@Test
public void testMoveToBase() {
final BasicConfigurationNode node = BasicConfigurationNode.root();
node.getNode("sub", "key").setValue("value");
node.getNode("at-parent").setValue("until-change");
transformMoveToBase(node);
assertEquals("value", node.getNode("key").getValue());
assertNull(node.getNode("at-parent").getValue());
}
private <T extends ScopedConfigurationNode<T>> void transformMoveToBase(final T node) {
ConfigurationTransformation.<T>builder()
.addAction(path("sub"), (inputPath, valueAtPath) -> {
return new Object[0];
}).build().apply(node);
}
@Test
public void testMoveStrategy() {
final ConfigurationTransformation.Builder<BasicConfigurationNode> build = ConfigurationTransformation.<BasicConfigurationNode>builder()
.addAction(path("one"), (inputPath, valueAtPath) -> arr("two"));
final BasicConfigurationNode overwritten = createMoveNode();
final BasicConfigurationNode merged = createMoveNode();
build.setMoveStrategy(MoveStrategy.OVERWRITE).build().apply(overwritten);
build.setMoveStrategy(MoveStrategy.MERGE).build().apply(merged);
assertEquals("always", overwritten.getNode("two", "fun").getValue());
assertEquals("always", merged.getNode("two", "fun").getValue());
assertNull(overwritten.getNode("two", "evil").getValue());
assertEquals("always", merged.getNode("two", "evil").getValue());
}
private BasicConfigurationNode createMoveNode() {
final BasicConfigurationNode ret = BasicConfigurationNode.root();
ret.getNode("one", "fun").setValue("always");
ret.getNode("two", "evil").setValue("always");
return ret;
}
@Test
public void testCorrectNodePassed() {
final BasicConfigurationNode node = BasicConfigurationNode.root();
final BasicConfigurationNode child = node.getNode("childNode").setValue("something");
ConfigurationTransformation.<BasicConfigurationNode>builder()
.addAction(path("childNode"), (inputPath, valueAtPath) -> {
assertEquals(child, valueAtPath);
return null;
}).build().apply(node);
}
@Test
public void testVersionedTransformation() {
final BasicConfigurationNode target = BasicConfigurationNode.root();
target.getNode("dummy").setValue("whatever");
final List<Integer> updatedVersions = new ArrayList<>();
this.<BasicConfigurationNode>buildVersionedTransformation(updatedVersions).apply(target);
assertEquals(2, target.getNode("version").getInt());
assertEquals(ImmutableList.of(0, 1, 2), updatedVersions);
}
private <T extends ScopedConfigurationNode<T>> ConfigurationTransformation<T> buildVersionedTransformation(final List<Integer> updatedVersions) {
return ConfigurationTransformation.<T>versionedBuilder()
.addVersion(0, ConfigurationTransformation.<T>builder()
.addAction(path("dummy"), (inputPath, valueAtPath) -> {
updatedVersions.add(0);
return null;
}).build())
.addVersion(2, ConfigurationTransformation.<T>builder()
.addAction(path("dummy"), (inputPath, valueAtPath) -> {
updatedVersions.add(2);
return null;
}).build())
.addVersion(1, ConfigurationTransformation.<T>builder()
.addAction(path("dummy"), (inputPath, valueAtPath) -> {
updatedVersions.add(1);
return null;
}).build())
.build();
}
}
|
/*
* Copyright 2018 JDCLOUD.COM
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:#www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*
*
*
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
package com.jdcloud.sdk.service.captcha.model;
/**
* amountStatistics
*/
public class AmountStatistics implements java.io.Serializable {
private static final long serialVersionUID = 1L;
/**
* 免费总数
*/
private Integer free;
/**
* 付费总数
*/
private Integer charge;
/**
* 总数
*/
private Integer total;
/**
* get 免费总数
*
* @return
*/
public Integer getFree() {
return free;
}
/**
* set 免费总数
*
* @param free
*/
public void setFree(Integer free) {
this.free = free;
}
/**
* get 付费总数
*
* @return
*/
public Integer getCharge() {
return charge;
}
/**
* set 付费总数
*
* @param charge
*/
public void setCharge(Integer charge) {
this.charge = charge;
}
/**
* get 总数
*
* @return
*/
public Integer getTotal() {
return total;
}
/**
* set 总数
*
* @param total
*/
public void setTotal(Integer total) {
this.total = total;
}
/**
* set 免费总数
*
* @param free
*/
public AmountStatistics free(Integer free) {
this.free = free;
return this;
}
/**
* set 付费总数
*
* @param charge
*/
public AmountStatistics charge(Integer charge) {
this.charge = charge;
return this;
}
/**
* set 总数
*
* @param total
*/
public AmountStatistics total(Integer total) {
this.total = total;
return this;
}
}
|
package client;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.net.SocketTimeoutException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import shared.messages.KVMessage;
import shared.messages.IKVMessage;
import shared.messages.IKVMessage.StatusType;
import exceptions.InvalidMessageException;
public class KVStore implements KVCommInterface {
private static final String PROMPT = "KVStore> ";
private static final int RESPONSE_TIME = 90 * 1000;
// private static final int RESPONSE_TIME = 10 * 1000;
private static final int HEARTBEAT_INTERVAL = 1000;
private static final int HEARTBEAT_TRANSMISSION = HEARTBEAT_INTERVAL * 10;
private static final int HEARTBEAT_RETRIES = 3;
private static final int BUFFER_SIZE = 1024;
private static final int DROP_SIZE = 1024 * BUFFER_SIZE;
private static final char LINE_FEED = 0x0A;
private static final char RETURN = 0x0D;
public volatile static boolean test = false;
private static Logger logger = Logger.getRootLogger();
private boolean running;
private String address;
private int port;
private Socket clientSocket;
private OutputStream output;
private InputStream input;
private long lastResponse;
ScheduledFuture<?> heartbeatThread;
private int missedHeartbeats = 0;
public int output_port;
/**
* Initialize KVStore with address and port of KVServer
*
* @param address the address of the KVServer
* @param port the port of the KVServer
*/
public KVStore(String address, int port) {
this.address = address;
this.port = port;
}
@Override
public void connect() throws UnknownHostException, IOException {
System.out.println(PROMPT + "Trying to connect ...");
logger.info("Trying to connect ...");
clientSocket = new Socket(address, port);
clientSocket.setSoTimeout(RESPONSE_TIME);
output = clientSocket.getOutputStream();
input = clientSocket.getInputStream();
output_port = clientSocket.getLocalPort();
setRunning(true);
setLastResponse(System.currentTimeMillis());
// TODO: Try and figure out what the problem is:
if (!test) {
scheduleHeartbeat();
}
System.out.println(PROMPT + "Connected!");
logger.info("Connection established to " + address + " on port " + port);
}
@Override
public void disconnect() {
try {
System.out.println(PROMPT + "Trying to disconnect ...");
logger.info("Trying to disconnect ...");
setRunning(false);
if (clientSocket != null) {
input.close();
output.close();
clientSocket.close();
clientSocket = null;
System.out.println(PROMPT + "Connection closed!");
logger.info("Connection closed!");
}
} catch (IOException ioe) {
printError("Unable to close connection!");
logger.error("Unable to close connection!", ioe);
}
}
@Override
public IKVMessage put(String key, String value) throws Exception {
KVMessage msg = new KVMessage(key, value, StatusType.PUT);
long sentTime = System.currentTimeMillis();
long expectedTime = sentTime + RESPONSE_TIME;
sendMessage(msg, false);
KVMessage res = null;
// while (true) {
// res = receiveMessage(false);
// if (System.currentTimeMillis() > expectedTime) break;
// if (res != null && res.getStatus() != StatusType.HEARTBEAT) break;
// }
do {
res = receiveMessage(false);
} while (res.getStatus() == StatusType.HEARTBEAT && System.currentTimeMillis() < expectedTime);
logger.debug("build new res put");
if (res == null || res.getStatus() == StatusType.HEARTBEAT) {
res = new KVMessage(key, "Timed out after " + RESPONSE_TIME / 1000 + " seconds", StatusType.PUT_ERROR);
}
return res;
}
@Override
public IKVMessage get(String key) throws Exception {
KVMessage msg = new KVMessage(key, null, StatusType.GET);
long sentTime = System.currentTimeMillis();
long expectedTime = sentTime + RESPONSE_TIME;
sendMessage(msg, false);
KVMessage res = null;
// while (true) {
// res = receiveMessage(false);
// if (System.currentTimeMillis() > expectedTime) break;
// if (res != null && res.getStatus() != StatusType.HEARTBEAT) break;
// }
do {
res = receiveMessage(false);
} while (res.getStatus() == StatusType.HEARTBEAT && System.currentTimeMillis() < expectedTime);
if (res == null) {
res = new KVMessage(key, "Timed out after " + RESPONSE_TIME / 1000 + " seconds", StatusType.GET_ERROR);
}
return res;
}
private void scheduleHeartbeat() {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
heartbeatThread = scheduler.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
if (getLastResponse() + HEARTBEAT_TRANSMISSION * (1 + missedHeartbeats) < System.currentTimeMillis()) {
byte msgBytes[] = { StatusType.HEARTBEAT.getVal() };
KVMessage msg;
KVMessage res;
try {
msg = new KVMessage(msgBytes);
sendMessage(msg, true);
res = receiveMessage(true);
setMissedHeartbeats(0);
} catch (InvalidMessageException e) {
logger.error("Unable to construct message!");
logger.error(e);
} catch (Exception e) {
setMissedHeartbeats(missedHeartbeats + 1);
if (missedHeartbeats > HEARTBEAT_RETRIES) {
disconnect("Server unresponsive... Shutting down!");
} else {
if (missedHeartbeats == 1) {
System.out.println();
System.out.println(PROMPT + "Server not responding");
logger.warn("Server not responding. Sending heartbeats ...");
}
logger.warn("Heartbeat " + missedHeartbeats + " of " + HEARTBEAT_RETRIES);
System.out.println("Trial " + missedHeartbeats + " of " + HEARTBEAT_RETRIES);
}
}
}
}
}, 0, HEARTBEAT_INTERVAL, TimeUnit.MILLISECONDS);
}
public int getMissedHeartbeats() {
return missedHeartbeats;
}
public void setMissedHeartbeats(int missedHeartbeats) {
this.missedHeartbeats = missedHeartbeats;
}
public void disconnect(String msg) {
try {
heartbeatThread.cancel(false);
System.out.println(PROMPT + msg);
System.out.print("KVClient> ");
logger.warn(msg);
setRunning(false);
if (clientSocket != null) {
input.close();
output.close();
clientSocket.close();
clientSocket = null;
}
} catch (IOException ioe) {
printError("Unable to close connection!");
logger.error("Unable to close connection!", ioe);
}
}
public boolean isRunning() {
return running;
}
public void setRunning(boolean run) {
running = run;
}
public long getLastResponse() {
return lastResponse;
}
public synchronized void setLastResponse(long response) {
lastResponse = response;
}
public synchronized void closeConnection() {
disconnect("Client closed connection");
}
public synchronized KVMessage receiveMessage(boolean heartbeat) throws IOException, InvalidMessageException, Exception {
if (!isRunning()) throw new IOException("Store is not running!");
int index = 0;
byte[] msgBytes = null, tmp = null;
byte[] bufferBytes = new byte[BUFFER_SIZE];
/* read first char from stream */
byte read = (byte) input.read();
boolean reading = true;
logger.debug("First read:" + read);
if (read == -1) {
throw new Exception("Reached end of stream!");
}
setLastResponse(System.currentTimeMillis());
while (read != LINE_FEED && read != -1 && reading) {/* LF, error, drop */
/* if buffer filled, copy to msg array */
if (index == BUFFER_SIZE) {
if (msgBytes == null) {
tmp = new byte[BUFFER_SIZE];
System.arraycopy(bufferBytes, 0, tmp, 0, BUFFER_SIZE);
} else {
tmp = new byte[msgBytes.length + BUFFER_SIZE];
System.arraycopy(msgBytes, 0, tmp, 0, msgBytes.length);
System.arraycopy(bufferBytes, 0, tmp, msgBytes.length,
BUFFER_SIZE);
}
msgBytes = tmp;
bufferBytes = new byte[BUFFER_SIZE];
index = 0;
}
/* only read valid characters, i.e. letters and numbers */
// if((read > 31 && read < 127)) {
bufferBytes[index] = read;
index++;
// }
/* stop reading if DROP_SIZE is reached */
if (msgBytes != null && msgBytes.length + index >= DROP_SIZE) {
reading = false;
}
/* read next char from stream */
read = (byte) input.read();
}
logger.debug("Last read:" + read);
if (msgBytes == null) {
tmp = new byte[index];
System.arraycopy(bufferBytes, 0, tmp, 0, index);
} else {
tmp = new byte[msgBytes.length + index];
System.arraycopy(msgBytes, 0, tmp, 0, msgBytes.length);
System.arraycopy(bufferBytes, 0, tmp, msgBytes.length, index);
}
msgBytes = tmp;
/* build final result */
KVMessage msg = new KVMessage(msgBytes);
if (!heartbeat) {
logger.info("RECEIVE: STATUS="
+ msg.getStatus() + " KEY=" + msg.getKey() + " VALUE=" + msg.getValue());
}
return msg;
}
public synchronized void sendMessage(KVMessage msg, boolean heartbeat) throws IOException {
if (!isRunning()) throw new IOException("Store is not running!");
byte[] msgBytes = msg.getMsgBytes();
output.write(msgBytes, 0, msgBytes.length);
output.flush();
if (!heartbeat) {
logger.info("SEND: STATUS="
+ msg.getStatus() + " KEY=" + msg.getKey() + " VALUE=" + msg.getValue());
}
}
private void printError(String error) {
System.out.println(PROMPT + "Error! " + error);
}
}
|
package io.github.gronnmann.coinflipper.hook;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import com.SirBlobman.combatlogx.api.ICombatLogX;
import com.SirBlobman.combatlogx.api.utility.ICombatManager;
public final class HookCombatLogX10 {
private HookCombatLogX10() {}
private static final HookCombatLogX10 hook = new HookCombatLogX10();
public static HookCombatLogX10 getHook(){
return hook;
}
private ICombatManager combatManager;
public void register(){
ICombatLogX combatLogX = (ICombatLogX) Bukkit.getPluginManager().getPlugin("CombatLogX");
this.combatManager = combatLogX.getCombatManager();
}
public boolean isTagged(Player player) {
return this.combatManager.isInCombat(player);
}
}
|
package io.rukkit;
import java.io.*;
import org.yaml.snakeyaml.*;
public class RukkitProperties
{
public static RukkitProperties readProfile() {
File f = new File(Rukkit.getEnvPath() + "/rukkit.yml");
if (f.isDirectory() || !f.exists()) {
f.delete();
try
{
f.createNewFile();
Yaml y = new Yaml();
RukkitProperties conf = new RukkitProperties();
y.dump(conf, new FileWriter(f));
}
catch (IOException e)
{
e.printStackTrace();
}
}
return new RukkitProperties();
}
public int serverTick = 10;;
public void setServerTick(int serverTick)
{
this.serverTick = serverTick;
}
public int getServerTick()
{
return serverTick;
}
}
|
/*
* Copyright 2010-2020 Australian Signals Directorate
*
* 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 au.gov.asd.tac.constellation.views.analyticview.analytics;
import au.gov.asd.tac.constellation.graph.schema.attribute.SchemaAttribute;
import au.gov.asd.tac.constellation.graph.schema.visual.concept.VisualConcept;
import au.gov.asd.tac.constellation.plugins.Plugin;
import au.gov.asd.tac.constellation.plugins.PluginInfo;
import au.gov.asd.tac.constellation.plugins.algorithms.sna.SnaConcept;
import au.gov.asd.tac.constellation.plugins.algorithms.sna.centrality.DegreeCentralityPlugin;
import au.gov.asd.tac.constellation.plugins.parameters.PluginParameters;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.openide.util.NbBundle;
import org.openide.util.lookup.ServiceProvider;
import org.openide.util.lookup.ServiceProviders;
/**
* The Degree Centrality analytic for the Analytic View.
*
* @author cygnus_x-1
*/
@ServiceProviders({
@ServiceProvider(service = AnalyticPlugin.class),
@ServiceProvider(service = Plugin.class)
})
@PluginInfo(tags = {"ANALYTIC"})
@AnalyticInfo(analyticCategory = "Centrality")
@NbBundle.Messages("DegreeCentralityAnalytic=Degree Centrality Analytic")
public class DegreeCentralityAnalytic extends ScoreAnalyticPlugin {
@Override
public String getDocumentationUrl() {
return "nbdocs://au.gov.asd.tac.constellation.views.analyticview/au/gov/asd/tac/constellation/views/analyticview/docs/analyticview-analytic-degree-centrality.html";
}
@Override
public Set<SchemaAttribute> getPrerequisiteAttributes() {
final Set<SchemaAttribute> analyticAttributes = super.getPrerequisiteAttributes();
analyticAttributes.add(VisualConcept.TransactionAttribute.SELECTED);
return Collections.unmodifiableSet(analyticAttributes);
}
@Override
public Set<SchemaAttribute> getAnalyticAttributes(final PluginParameters parameters) {
final boolean includeConnectionsIn = parameters.getBooleanValue(DegreeCentralityPlugin.INCLUDE_CONNECTIONS_IN_PARAMETER_ID);
final boolean includeConnectionsOut = parameters.getBooleanValue(DegreeCentralityPlugin.INCLUDE_CONNECTIONS_OUT_PARAMETER_ID);
final Set<SchemaAttribute> analyticAttributes = new HashSet<>();
analyticAttributes.add(includeConnectionsIn && !includeConnectionsOut ? SnaConcept.VertexAttribute.IN_DEGREE_CENTRALITY
: !includeConnectionsIn && includeConnectionsOut ? SnaConcept.VertexAttribute.OUT_DEGREE_CENTRALITY
: SnaConcept.VertexAttribute.DEGREE_CENTRALITY);
return Collections.unmodifiableSet(analyticAttributes);
}
@Override
public Class<? extends Plugin> getAnalyticPlugin() {
return DegreeCentralityPlugin.class;
}
}
|
/*
* Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencentcloudapi.tcaplusdb.v20190823.models;
import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;
public class ModifyTableQuotasResponse extends AbstractModel{
/**
* Number of scaled tables
*/
@SerializedName("TotalCount")
@Expose
private Long TotalCount;
/**
* List of table scaling results
*/
@SerializedName("TableResults")
@Expose
private TableResultNew [] TableResults;
/**
* The unique request ID, which is returned for each request. RequestId is required for locating a problem.
*/
@SerializedName("RequestId")
@Expose
private String RequestId;
/**
* Get Number of scaled tables
* @return TotalCount Number of scaled tables
*/
public Long getTotalCount() {
return this.TotalCount;
}
/**
* Set Number of scaled tables
* @param TotalCount Number of scaled tables
*/
public void setTotalCount(Long TotalCount) {
this.TotalCount = TotalCount;
}
/**
* Get List of table scaling results
* @return TableResults List of table scaling results
*/
public TableResultNew [] getTableResults() {
return this.TableResults;
}
/**
* Set List of table scaling results
* @param TableResults List of table scaling results
*/
public void setTableResults(TableResultNew [] TableResults) {
this.TableResults = TableResults;
}
/**
* Get The unique request ID, which is returned for each request. RequestId is required for locating a problem.
* @return RequestId The unique request ID, which is returned for each request. RequestId is required for locating a problem.
*/
public String getRequestId() {
return this.RequestId;
}
/**
* Set The unique request ID, which is returned for each request. RequestId is required for locating a problem.
* @param RequestId The unique request ID, which is returned for each request. RequestId is required for locating a problem.
*/
public void setRequestId(String RequestId) {
this.RequestId = RequestId;
}
/**
* Internal implementation, normal users should not use it.
*/
public void toMap(HashMap<String, String> map, String prefix) {
this.setParamSimple(map, prefix + "TotalCount", this.TotalCount);
this.setParamArrayObj(map, prefix + "TableResults.", this.TableResults);
this.setParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
|
/*
* The MIT License
*
* Copyright 2017 Siggi.
*
* 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 hk.siggi.bukkit.nbt.v1_9_R2;
import java.util.Set;
import net.minecraft.server.v1_9_R2.NBTBase;
import net.minecraft.server.v1_9_R2.NBTTagCompound;
import net.minecraft.server.v1_9_R2.NBTTagList;
final class NBTCompound extends hk.siggi.bukkit.nbt.NBTCompound<NBTCompound, NBTList> {
public final NBTTagCompound compound;
public NBTCompound() {
this.compound = new NBTTagCompound();
}
public NBTCompound(NBTTagCompound compound) {
this.compound = compound;
}
@Override
public NBTTagCompound getNMSCompound() {
return compound;
}
@Override
public int getType(String key) {
return compound.get(key).getTypeId();
}
@Override
public byte getByte(String key) {
return compound.getByte(key);
}
@Override
public void setByte(String key, byte value) {
compound.setByte(key, value);
}
@Override
public short getShort(String key) {
return compound.getShort(key);
}
@Override
public void setShort(String key, short value) {
compound.setShort(key, value);
}
@Override
public int getInt(String key) {
return compound.getInt(key);
}
@Override
public void setInt(String key, int value) {
compound.setInt(key, value);
}
@Override
public long getLong(String key) {
return compound.getLong(key);
}
@Override
public void setLong(String key, long value) {
compound.setLong(key, value);
}
@Override
public float getFloat(String key) {
return compound.getFloat(key);
}
@Override
public void setFloat(String key, float value) {
compound.setFloat(key, value);
}
@Override
public double getDouble(String key) {
return compound.getDouble(key);
}
@Override
public void setDouble(String key, double value) {
compound.setDouble(key, value);
}
@Override
public byte[] getByteArray(String key) {
return compound.getByteArray(key);
}
@Override
public void setByteArray(String key, byte[] value) {
compound.setByteArray(key, value);
}
@Override
public String getString(String key) {
return compound.getString(key);
}
@Override
public void setString(String key, String value) {
compound.setString(key, value);
}
@Override
public NBTList getList(String key) {
NBTBase base = compound.get(key);
if (base instanceof NBTTagList) {
return new NBTList((NBTTagList) base);
}
return new NBTList();
}
@Override
public void setList(String key, NBTList list) {
this.compound.set(key, list.list);
}
@Override
public NBTCompound getCompound(String key) {
return new NBTCompound(compound.getCompound(key));
}
@Override
public void setCompound(String key, NBTCompound compound) {
this.compound.set(key, compound.compound);
}
@Override
public int[] getIntArray(String key) {
return this.compound.getIntArray(key);
}
@Override
public void setIntArray(String key, int[] value) {
this.compound.setIntArray(key, value);
}
@Override
public long[] getLongArray(String key) {
throw new UnsupportedOperationException("LongArray is only available in Minecraft 1.13 and newer.");
}
@Override
public void setLongArray(String key, long[] value) {
throw new UnsupportedOperationException("LongArray is only available in Minecraft 1.13 and newer.");
}
@Override
public Set<String> keySet() {
return this.compound.c();
}
@Override
public int size() {
return this.compound.d();
}
@Override
public void remove(String key) {
this.compound.remove(key);
}
@Override
public boolean equals(Object object) {
if (object instanceof NBTCompound) {
return ((NBTCompound) object).compound.equals(compound);
} else {
return super.equals(object);
}
}
@Override
public int hashCode() {
int hash = 3;
hash = 13 * hash + compound.hashCode();
return hash;
}
@Override
public NBTCompound copy() {
return new NBTCompound((NBTTagCompound) compound.clone());
}
}
|
package org.hl7.fhir.r4.model.codesystems;
/*
Copyright (c) 2011+, HL7, Inc.
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 HL7 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 HOLDER 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.
*/
// Generated on Thu, Dec 27, 2018 10:06-0500 for FHIR v4.0.0
import org.hl7.fhir.exceptions.FHIRException;
public enum RequestStatus {
/**
* The request has been created but is not yet complete or ready for action.
*/
DRAFT,
/**
* The request is in force and ready to be acted upon.
*/
ACTIVE,
/**
* The request (and any implicit authorization to act) has been temporarily withdrawn but is expected to resume in the future.
*/
ONHOLD,
/**
* The request (and any implicit authorization to act) has been terminated prior to the known full completion of the intended actions. No further activity should occur.
*/
REVOKED,
/**
* The activity described by the request has been fully performed. No further activity will occur.
*/
COMPLETED,
/**
* This request should never have existed and should be considered 'void'. (It is possible that real-world decisions were based on it. If real-world activity has occurred, the status should be "cancelled" rather than "entered-in-error".).
*/
ENTEREDINERROR,
/**
* The authoring/source system does not know which of the status values currently applies for this request. Note: This concept is not to be used for "other" - one of the listed statuses is presumed to apply, but the authoring/source system does not know which.
*/
UNKNOWN,
/**
* added to help the parsers
*/
NULL;
public static RequestStatus fromCode(String codeString) throws FHIRException {
if (codeString == null || "".equals(codeString))
return null;
if ("draft".equals(codeString))
return DRAFT;
if ("active".equals(codeString))
return ACTIVE;
if ("on-hold".equals(codeString))
return ONHOLD;
if ("revoked".equals(codeString))
return REVOKED;
if ("completed".equals(codeString))
return COMPLETED;
if ("entered-in-error".equals(codeString))
return ENTEREDINERROR;
if ("unknown".equals(codeString))
return UNKNOWN;
throw new FHIRException("Unknown RequestStatus code '"+codeString+"'");
}
public String toCode() {
switch (this) {
case DRAFT: return "draft";
case ACTIVE: return "active";
case ONHOLD: return "on-hold";
case REVOKED: return "revoked";
case COMPLETED: return "completed";
case ENTEREDINERROR: return "entered-in-error";
case UNKNOWN: return "unknown";
default: return "?";
}
}
public String getSystem() {
return "http://hl7.org/fhir/request-status";
}
public String getDefinition() {
switch (this) {
case DRAFT: return "The request has been created but is not yet complete or ready for action.";
case ACTIVE: return "The request is in force and ready to be acted upon.";
case ONHOLD: return "The request (and any implicit authorization to act) has been temporarily withdrawn but is expected to resume in the future.";
case REVOKED: return "The request (and any implicit authorization to act) has been terminated prior to the known full completion of the intended actions. No further activity should occur.";
case COMPLETED: return "The activity described by the request has been fully performed. No further activity will occur.";
case ENTEREDINERROR: return "This request should never have existed and should be considered 'void'. (It is possible that real-world decisions were based on it. If real-world activity has occurred, the status should be \"cancelled\" rather than \"entered-in-error\".).";
case UNKNOWN: return "The authoring/source system does not know which of the status values currently applies for this request. Note: This concept is not to be used for \"other\" - one of the listed statuses is presumed to apply, but the authoring/source system does not know which.";
default: return "?";
}
}
public String getDisplay() {
switch (this) {
case DRAFT: return "Draft";
case ACTIVE: return "Active";
case ONHOLD: return "On Hold";
case REVOKED: return "Revoked";
case COMPLETED: return "Completed";
case ENTEREDINERROR: return "Entered in Error";
case UNKNOWN: return "Unknown";
default: return "?";
}
}
}
|
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* 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.intellij.codeInspection;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.ThreeState;
import com.intellij.xml.psi.XmlPsiBundle;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public abstract class XmlSuppressableInspectionTool extends LocalInspectionTool implements BatchSuppressableTool {
@NonNls static final String ALL = "ALL";
public static SuppressQuickFix @NotNull [] getSuppressFixes(@NotNull String toolId) {
return getSuppressFixes(toolId, new DefaultXmlSuppressionProvider());
}
public static SuppressQuickFix @NotNull [] getSuppressFixes(@NotNull String toolId, @NotNull XmlSuppressionProvider provider) {
return new SuppressQuickFix[]{new SuppressTagStatic(toolId, provider), new SuppressForFile(toolId, provider),
new SuppressAllForFile(provider)};
}
public abstract static class XmlSuppressFix implements InjectionAwareSuppressQuickFix, ContainerBasedSuppressQuickFix {
protected final String myId;
protected final XmlSuppressionProvider myProvider;
private ThreeState myShouldBeAppliedToInjectionHost = ThreeState.UNSURE;
protected XmlSuppressFix(String inspectionId, XmlSuppressionProvider suppressionProvider) {
myId = inspectionId;
myProvider = suppressionProvider;
}
protected XmlSuppressFix(String id) {
this(id, new DefaultXmlSuppressionProvider());
}
@Override
public boolean isAvailable(@NotNull Project project, @NotNull PsiElement context) {
return context.isValid() && getContainer(context) != null;
}
@Override
@NotNull
public String getFamilyName() {
return getName();
}
@Nullable
@Override
public PsiElement getContainer(@Nullable PsiElement context) {
return null;
}
@NotNull
@Override
public ThreeState isShouldBeAppliedToInjectionHost() {
return myShouldBeAppliedToInjectionHost;
}
@Override
public void setShouldBeAppliedToInjectionHost(@NotNull ThreeState shouldBeAppliedToInjectionHost) {
myShouldBeAppliedToInjectionHost = shouldBeAppliedToInjectionHost;
}
@Override
public boolean isSuppressAll() {
return false;
}
}
public static class SuppressTagStatic extends XmlSuppressFix {
public SuppressTagStatic(String inspectionId, XmlSuppressionProvider suppressionProvider) {
super(inspectionId, suppressionProvider);
}
public SuppressTagStatic(String id) {
super(id);
}
@NotNull
@Override
public String getName() {
return XmlPsiBundle.message("xml.suppressable.for.tag.title");
}
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
PsiElement element = descriptor.getPsiElement();
if (PsiTreeUtil.getParentOfType(element, XmlTag.class) == null) return;
myProvider.suppressForTag(element, myId);
}
@Nullable
@Override
public PsiElement getContainer(@Nullable PsiElement context) {
return PsiTreeUtil.getParentOfType(context, XmlTag.class);
}
}
public static class SuppressForFile extends XmlSuppressFix {
public SuppressForFile(String inspectionId, XmlSuppressionProvider suppressionProvider) {
super(inspectionId, suppressionProvider);
}
public SuppressForFile(String id) {
super(id);
}
@NotNull
@Override
public String getName() {
return XmlPsiBundle.message("xml.suppressable.for.file.title");
}
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
PsiElement element = descriptor.getPsiElement();
myProvider.suppressForFile(element, myId);
}
@Nullable
@Override
public PsiElement getContainer(@Nullable PsiElement context) {
return context == null || !context.isValid() ? null : context.getContainingFile();
}
}
public static class SuppressAllForFile extends SuppressForFile {
public SuppressAllForFile(XmlSuppressionProvider provider) {
super(ALL, provider);
}
public SuppressAllForFile() {
super(ALL);
}
@NotNull
@Override
public String getName() {
return XmlPsiBundle.message("xml.suppressable.all.for.file.title");
}
}
}
|
/*
* 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.netbeans.modules.j2ee.ddloaders.web.test.util;
import java.io.File;
import java.awt.*;
import org.netbeans.modules.xml.multiview.ToolBarMultiViewElement;
import org.netbeans.modules.xml.multiview.ui.DefaultTablePanel;
import org.netbeans.modules.xml.multiview.ui.SectionPanel;
import org.netbeans.modules.j2ee.ddloaders.web.DDDataObject;
import org.netbeans.modules.j2ee.ddloaders.web.multiview.DDBeanTableModel;
import javax.swing.*;
import org.netbeans.modules.xml.multiview.XmlMultiViewDataObject;
/**
*
* @author Milan Kuchtiak
*/
public class Helper {
public static File getDDFile(File dataDir) {
String result = dataDir.getAbsolutePath() + "/projects/webapp/web/WEB-INF/web.xml";
return new File(result);
}
public static DDBeanTableModel getContextParamsTableModel(final DDDataObject dObj) {
final ToolBarMultiViewElement multiViewElement = getMultiViewElement(dObj);
JPanel sectionPanel = getSectionPanel(multiViewElement);
Component[] children = sectionPanel.getComponents();
DefaultTablePanel tablePanel = null;
for (int i = 0; i < children.length; i++) {
if (children[i] instanceof DefaultTablePanel) {
tablePanel = (DefaultTablePanel) children[i];
break;
}
}
return (DDBeanTableModel) tablePanel.getModel();
}
private static JPanel getSectionPanel(final ToolBarMultiViewElement multiViewElement) {
return new StepIterator() {
JPanel sectionPanel;
public boolean step() throws Exception {
SectionPanel outerPanel = multiViewElement.getSectionView().findSectionPanel("context_params");
sectionPanel = outerPanel == null ? null : outerPanel.getInnerPanel();
return sectionPanel != null;
}
}.sectionPanel;
}
public static ToolBarMultiViewElement getMultiViewElement(final DDDataObject dObj) {
return new StepIterator() {
ToolBarMultiViewElement multiViewElement;
public boolean step() throws Exception {
multiViewElement = dObj.getActiveMVElement();
return multiViewElement != null;
}
}.multiViewElement;
}
public static void sleep(int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException ex){}
}
public static void waitForDispatchThread() {
if (SwingUtilities.isEventDispatchThread()) {
return;
}
final boolean[] finished = new boolean[]{false};
SwingUtilities.invokeLater(new Runnable() {
public void run() {
finished[0] = true;
}
});
new StepIterator() {
public boolean step() throws Exception {
return finished[0];
}
};
}
}
|
/*
* Copyright 2019 Arcus 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 arcus.app.account.settings.walkthroughs;
public class SetupWalkthroughs {
private int mTitleResId;
private int mLayoutResId;
private int mDescriptionResId;
private int mPictureResID;
SetupWalkthroughs(int layoutResId, int titleResId, int descriptionResId, int pictureResID) {
mTitleResId = titleResId;
mDescriptionResId = descriptionResId;
mLayoutResId = layoutResId;
mPictureResID = pictureResID;
}
public int getTitleResId() {
return mTitleResId;
}
public int getDescriptionId() {
return mDescriptionResId;
}
public int getLayoutResId(){
return mLayoutResId;
}
public int getImageId() {
return mPictureResID;
}
}
|
/**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2016 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
package ti.modules.titanium.network.socket;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollFunction;
import org.appcelerator.kroll.KrollProxy;
import org.appcelerator.kroll.annotations.Kroll;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.TiC;
import org.appcelerator.titanium.io.TiStream;
import org.appcelerator.titanium.util.TiConvert;
import org.appcelerator.titanium.util.TiStreamHelper;
import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkRequest;
import ti.modules.titanium.BufferProxy;
@SuppressLint("NewApi")
@Kroll.proxy(creatableInModule=SocketModule.class)
public class TCPProxy extends KrollProxy implements TiStream
{
private static final String TAG = "TCPProxy";
//private boolean initialized = false;
private Socket clientSocket = null;
private ServerSocket serverSocket = null;
private boolean accepting = false;
private KrollDict acceptOptions = null;
private int state = 0;
private InputStream inputStream = null;
public TCPProxy()
{
super();
state = SocketModule.INITIALIZED;
}
@Kroll.method
public void connect() throws Exception
{
if ((state != SocketModule.LISTENING) && (state != SocketModule.CONNECTED)) {
Object host = getProperty("host");
Object port = getProperty("port");
if((host != null) && (port != null) && (TiConvert.toInt(port) > 0)) {
new ConnectedSocketThread().start();
} else {
throw new IllegalArgumentException("Unable to call connect, socket must have a valid host and port");
}
} else {
throw new Exception("Unable to call connect on socket in <" + state + "> state");
}
}
@Kroll.method
public void listen() throws Exception
{
if ((state != SocketModule.LISTENING) && (state != SocketModule.CONNECTED)) {
Object port = getProperty("port");
Object listenQueueSize = getProperty("listenQueueSize");
try {
if ((port != null) && (listenQueueSize != null)) {
serverSocket = new ServerSocket(TiConvert.toInt(port), TiConvert.toInt(listenQueueSize));
} else if (port != null) {
serverSocket = new ServerSocket(TiConvert.toInt(port));
} else {
serverSocket = new ServerSocket();
}
new ListeningSocketThread().start();
state = SocketModule.LISTENING;
} catch (IOException e) {
e.printStackTrace();
state = SocketModule.ERROR;
throw new Exception("Unable to listen, IO error");
}
} else {
throw new Exception("Unable to call listen on socket in <" + state + "> state");
}
}
@Kroll.method
public void accept(KrollDict acceptOptions) throws Exception
{
if (state != SocketModule.LISTENING) {
throw new Exception("Socket is not listening, unable to call accept");
}
this.acceptOptions = acceptOptions;
accepting = true;
}
private void closeSocket() throws IOException {
state = SocketModule.CLOSING; // set socket state to uninitialized to prevent use while closing
if (clientSocket != null) {
clientSocket.close();
clientSocket = null;
}
if (serverSocket != null) {
serverSocket.close();
serverSocket = null;
}
updateState(SocketModule.CLOSED, "closed", null);
fireEvent("close");
}
@Kroll.setProperty @Kroll.method
public void setHost(String host)
{
setSocketProperty("host", host);
}
@Kroll.setProperty @Kroll.method
public void setPort(int port)
{
setSocketProperty("port", port);
}
@Kroll.setProperty @Kroll.method
public void setTimeout(int timeout)
{
setSocketProperty("timeout", timeout);
}
@Kroll.setProperty @Kroll.method
public void setOptions(KrollDict options)
{
// not implemented yet - reserved for future use
Log.i(TAG, "setting options on socket is not supported yet");
}
@Kroll.setProperty @Kroll.method
public void setListenQueueSize(int listenQueueSize)
{
setSocketProperty("listenQueueSize", listenQueueSize);
}
@Kroll.setProperty @Kroll.method
public void setConnected(KrollFunction connected)
{
setSocketProperty("connected", connected);
}
@Kroll.setProperty @Kroll.method
public void setError(KrollFunction error)
{
setSocketProperty("error", error);
}
@Kroll.setProperty @Kroll.method
public void setAccepted(KrollFunction accepted)
{
setSocketProperty("accepted", accepted);
}
private void setSocketProperty(String propertyName, Object propertyValue)
{
if ((state != SocketModule.LISTENING) && (state != SocketModule.CONNECTED)) {
setProperty(propertyName, propertyValue);
} else {
Log.e(TAG, "Unable to set property <" + propertyName + "> on socket in <" + state + "> state");
}
}
@Kroll.getProperty @Kroll.method
public int getState()
{
return state;
}
private ConnectivityManager getConnectivityManager()
{
ConnectivityManager cm = null;
Context a = TiApplication.getInstance();
if (a != null) {
cm = (ConnectivityManager) a.getSystemService(Context.CONNECTIVITY_SERVICE);
} else {
Log.w(TAG, "Activity is null when trying to retrieve the connectivity service", Log.DEBUG_MODE);
}
return cm;
}
private class ConnectedSocketThread extends Thread
{
public ConnectedSocketThread()
{
super("ConnectedSocketThread");
}
public void run()
{
final String host = TiConvert.toString(getProperty("host"));
int transportType = TiConvert.toInt(getProperty("transportType"), -1);
final int timeout = TiConvert.toInt(getProperty("timeout"), -1);
final int port = TiConvert.toInt(getProperty("port"));
try {
clientSocket = new Socket();
if (timeout >= 0) {
clientSocket.setSoTimeout(timeout);
}
if (TiC.LOLLIPOP_OR_GREATER && transportType > 0) {
final ConnectivityManager cm = getConnectivityManager();
NetworkRequest.Builder req = new NetworkRequest.Builder();
req.addTransportType(transportType);
cm.requestNetwork(req.build(), new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
cm.unregisterNetworkCallback(this);
try {
network.bindSocket(clientSocket);
// if (timeout >= 0) {
// clientSocket.connect(new InetSocketAddress(host, port), timeout);
//
// } else {
clientSocket.connect(new InetSocketAddress(host, port));
// }
updateState(SocketModule.CONNECTED, "connected", buildConnectedCallbackArgs());
} catch (IOException e) {
updateState(SocketModule.ERROR, "error", buildErrorCallbackArgs(e.getLocalizedMessage(), -1));
}
}
});
} else {
if (timeout >= 0) {
clientSocket.connect(new InetSocketAddress(host, port), timeout);
} else {
clientSocket.connect(new InetSocketAddress(host, port));
}
updateState(SocketModule.CONNECTED, "connected", buildConnectedCallbackArgs());
}
} catch (IOException e) {
e.printStackTrace();
updateState(SocketModule.ERROR, "error", buildErrorCallbackArgs(e.getLocalizedMessage(), -1));
}
}
}
private class ListeningSocketThread extends Thread
{
public ListeningSocketThread()
{
super("ListeningSocketThread");
}
public void run()
{
while(true) {
if(accepting) {
try {
// Check if serverSocket is valid, if not exit
if (serverSocket == null) {
break;
}
Socket acceptedSocket = serverSocket.accept();
TCPProxy acceptedTcpProxy = new TCPProxy();
acceptedTcpProxy.clientSocket = acceptedSocket;
acceptedTcpProxy.setProperty("host", acceptedTcpProxy.clientSocket.getInetAddress().getHostAddress());
acceptedTcpProxy.setProperty("port", acceptedTcpProxy.clientSocket.getPort());
Object optionValue;
if((optionValue = acceptOptions.get("timeout")) != null) {
acceptedTcpProxy.setProperty("timeout", TiConvert.toInt(optionValue, 0));
}
if((optionValue = acceptOptions.get("error")) != null) {
if(optionValue instanceof KrollFunction) {
acceptedTcpProxy.setProperty("error", (KrollFunction) optionValue);
}
}
acceptedTcpProxy.state = SocketModule.CONNECTED;
Object callback = getProperty("accepted");
if (callback instanceof KrollFunction) {
((KrollFunction) callback).callAsync(getKrollObject(), buildAcceptedCallbackArgs(acceptedTcpProxy));
}
accepting = false;
} catch (IOException e) {
if (state == SocketModule.LISTENING) {
e.printStackTrace();
updateState(SocketModule.ERROR, "error", buildErrorCallbackArgs(e.getLocalizedMessage(), 0));
}
break;
}
} else {
try {
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
Log.e(TAG, "Listening thread interrupted");
}
}
}
}
}
private KrollDict buildConnectedCallbackArgs()
{
KrollDict callbackArgs = new KrollDict();
callbackArgs.put("socket", this);
return callbackArgs;
}
private KrollDict buildErrorCallbackArgs(String error, int errorCode)
{
KrollDict callbackArgs = new KrollDict();
callbackArgs.put("socket", this);
callbackArgs.putCodeAndMessage(errorCode, error);
callbackArgs.put("errorCode", errorCode);
return callbackArgs;
}
private KrollDict buildAcceptedCallbackArgs(TCPProxy acceptedTcpProxy)
{
KrollDict callbackArgs = new KrollDict();
callbackArgs.put("socket", this);
callbackArgs.put("inbound", acceptedTcpProxy);
return callbackArgs;
}
public void updateState(int state, String callbackName, KrollDict callbackArgs)
{
this.state = state;
if (state == SocketModule.ERROR) {
try {
if (clientSocket != null) {
clientSocket.close();
}
if (serverSocket != null) {
serverSocket.close();
}
} catch (IOException e) {
Log.w(TAG, "Unable to close socket in error state", Log.DEBUG_MODE);
}
}
Object callback = getProperty(callbackName);
if (callback instanceof KrollFunction) {
((KrollFunction) callback).callAsync(getKrollObject(), callbackArgs);
}
}
@Kroll.method
public boolean isConnected()
{
if (state == SocketModule.CONNECTED) {
return true;
}
return false;
}
// TiStream interface methods
@Kroll.method
public int read(Object args[]) throws IOException
{
if (!isConnected()) {
throw new IOException("Unable to read from socket, not connected");
}
BufferProxy bufferProxy = null;
int offset = 0;
int length = 0;
Number position = null;
if(args.length > 0) {
if(args[0] instanceof BufferProxy) {
bufferProxy = (BufferProxy) args[0];
length = bufferProxy.getLength();
} else {
throw new IllegalArgumentException("Invalid buffer argument");
}
if(args.length > 1) {
if(args[1] instanceof Number) {
offset = ((Number)args[1]).intValue();
} else {
throw new IllegalArgumentException("Invalid offset argument");
}
}
if(args.length > 2) {
if(args[2] instanceof Number) {
length = ((Number)args[2]).intValue();
} else {
throw new IllegalArgumentException("Invalid length argument");
}
}
if(args.length > 3) {
if(args[3] instanceof Number) {
position = ((Number)args[3]);
} else {
throw new IllegalArgumentException("Invalid position argument");
}
}
}
if (inputStream == null) {
inputStream = clientSocket.getInputStream();
}
try {
return TiStreamHelper.read(inputStream, bufferProxy, offset, length, position);
} catch (IOException e) {
e.printStackTrace();
if (state != SocketModule.CLOSED) {
closeSocket();
}
throw e;
}
// return -1;
}
@Kroll.method
public int write(Object args[]) throws IOException
{
if(!isConnected())
{
throw new IOException("Unable to write to socket, not connected");
}
byte[] bytes = null;
int offset = 0;
int length = 0;
if(args.length == 1 || args.length == 3) {
if(args.length > 0) {
bytes = TiConvert.toBytes(args[0]);
}
if(args.length == 3) {
if(args[1] instanceof Integer) {
offset = ((Integer)args[1]).intValue();
} else if(args[1] instanceof Double) {
offset = ((Double)args[1]).intValue();
} else {
throw new IllegalArgumentException("Invalid offset argument");
}
if(args[2] instanceof Integer) {
length = ((Integer)args[2]).intValue();
} else if(args[2] instanceof Double) {
length = ((Double)args[2]).intValue();
} else {
throw new IllegalArgumentException("Invalid length argument");
}
}
} else {
throw new IllegalArgumentException("Invalid number of arguments");
}
if(bytes == null) {
throw new IllegalArgumentException("Invalid buffer argument");
}
length = bytes.length;
try {
return TiStreamHelper.write(clientSocket.getOutputStream(), bytes, offset, length);
} catch (IOException e) {
e.printStackTrace();
closeSocket();
updateState(SocketModule.ERROR, "error", buildErrorCallbackArgs(e.getLocalizedMessage(), 0));
throw new IOException("Unable to write to socket, IO error");
}
}
@Kroll.method
public boolean isWritable()
{
return isConnected();
}
@Kroll.method
public boolean isReadable()
{
return isConnected();
}
@Kroll.method
public void close() throws IOException
{
if (state == SocketModule.CLOSED) {
return;
}
// if((state != SocketModule.CONNECTED) && (state != SocketModule.LISTENING)) {
// throw new IOException("Socket is not connected or listening, unable to call close on socket in <" + state + "> state");
// }
try {
closeSocket();
} catch (IOException e) {
e.printStackTrace();
throw new IOException("Error occured when closing socket");
}
}
@Override
public String getApiName()
{
return "Ti.Network.Socket.TCP";
}
}
|
package ru.swayfarer.swl2.jfx.scene.controls;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.shape.Rectangle;
import ru.swayfarer.swl2.collections.CollectionsSWL;
import ru.swayfarer.swl2.collections.extended.IExtendedList;
import ru.swayfarer.swl2.jfx.scene.layout.JfxStackedPane;
import ru.swayfarer.swl2.jfx.scene.layout.JfxStackedPane.AlligmentType;
import ru.swayfarer.swl2.markers.ConcattedString;
import ru.swayfarer.swl2.string.StringUtils;
public class TitleBar {
public Rectangle header = new Rectangle();
public Label lblTitle = new Label();
public IExtendedList<Button> buttons = CollectionsSWL.createExtendedList();
public JfxStackedPane pnButtons = new JfxStackedPane().setAlligment(AlligmentType.HORIZONTAL);
public Button btnClose = new Button("X");
public TitleBar(@ConcattedString Object... title)
{
String titleStr = StringUtils.concat(title);
lblTitle.setText(titleStr);
}
}
|
/**
*
*/
/**
* @author Feng Kuok
*
*/
package org.makersoft.mvc.mapping;
|
/*-*
* Copyright © 2010-2015 Atilika Inc. and contributors (see CONTRIBUTORS.md)
*
* 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 distributed with this work in the LICENSE.md file. You may
* also obtain a copy of the License from
*
* 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.atilika.kuromoji.util;
public class StringUtils {
public static String join(String[] values, String separator) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < values.length; i++) {
builder.append(values[i]);
if (i < values.length - 1) {
builder.append(separator);
}
}
return builder.toString();
}
}
|
/*
* Copyright 2018 ACINQ SAS
*
* 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 fr.acinq.eclair.wallet.tasks;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import android.util.Log;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.util.HashMap;
import java.util.Map;
public class QRCodeTask extends AsyncTask<String, Integer, Bitmap> {
public interface AsyncQRCodeResponse {
void processFinish(Bitmap output);
}
private AsyncQRCodeResponse delegate;
private static final String TAG = "QRCodeTask";
private final QRCodeWriter writer = new QRCodeWriter();
private final int width;
private final int height;
private final String source;
public QRCodeTask(AsyncQRCodeResponse delegate, String source, int width, int height){
this.delegate = delegate;
this.width = width;
this.height = height;
this.source = "bitcoin:" + source;
}
@Override
protected Bitmap doInBackground(String... params) {
final Map<EncodeHintType, Object> hintsMap = new HashMap<>();
hintsMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
hintsMap.put(EncodeHintType.MARGIN, 2);
final int qrWidth = 50;
final int qrHeight= 50;
try {
BitMatrix matrix = writer.encode(source, BarcodeFormat.QR_CODE, qrWidth, qrHeight, hintsMap);
final int[] pixels = new int[qrWidth * qrHeight];
for (int j = 0; j < qrHeight; j++) {
final int offset = j * qrWidth;
for (int i = 0; i < qrWidth; i++) {
pixels[offset + i] = matrix.get(i, j) ? Color.BLACK : 0xffffffff;
}
}
return Bitmap.createScaledBitmap(Bitmap.createBitmap(pixels, qrWidth, qrHeight, Bitmap.Config.ARGB_8888), width, height, false);
} catch (WriterException e) {
Log.w(TAG, "Failed to generate QR code for source " + source + " with cause=" + e.getMessage());
return null;
}
}
protected void onPostExecute(Bitmap result) {
delegate.processFinish(result);
}
}
|
/*
* 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.camel.builder.component.dsl;
import javax.annotation.Generated;
import org.apache.camel.Component;
import org.apache.camel.builder.component.AbstractComponentBuilder;
import org.apache.camel.builder.component.ComponentBuilder;
import org.apache.camel.component.ignite.events.IgniteEventsComponent;
/**
* Receive events from an Ignite cluster by creating a local event listener.
*
* Generated by camel-package-maven-plugin - do not edit this file!
*/
@Generated("org.apache.camel.maven.packaging.ComponentDslMojo")
public interface IgniteEventsComponentBuilderFactory {
/**
* Ignite Events (camel-ignite)
* Receive events from an Ignite cluster by creating a local event listener.
*
* Category: messaging,eventbus
* Since: 2.17
* Maven coordinates: org.apache.camel:camel-ignite
*
* @return the dsl builder
*/
static IgniteEventsComponentBuilder igniteEvents() {
return new IgniteEventsComponentBuilderImpl();
}
/**
* Builder for the Ignite Events component.
*/
interface IgniteEventsComponentBuilder
extends
ComponentBuilder<IgniteEventsComponent> {
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions occurred while the consumer is trying to
* pickup incoming messages, or the likes, will now be processed as a
* message and handled by the routing Error Handler. By default the
* consumer will use the org.apache.camel.spi.ExceptionHandler to deal
* with exceptions, that will be logged at WARN or ERROR level and
* ignored.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default IgniteEventsComponentBuilder bridgeErrorHandler(
boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* The resource from where to load the configuration. It can be a: URL,
* String or InputStream type.
*
* The option is a: <code>java.lang.Object</code> type.
*
* Group: consumer
*
* @param configurationResource the value to set
* @return the dsl builder
*/
default IgniteEventsComponentBuilder configurationResource(
java.lang.Object configurationResource) {
doSetProperty("configurationResource", configurationResource);
return this;
}
/**
* To use an existing Ignite instance.
*
* The option is a: <code>org.apache.ignite.Ignite</code>
* type.
*
* Group: consumer
*
* @param ignite the value to set
* @return the dsl builder
*/
default IgniteEventsComponentBuilder ignite(
org.apache.ignite.Ignite ignite) {
doSetProperty("ignite", ignite);
return this;
}
/**
* Allows the user to set a programmatic ignite configuration.
*
* The option is a:
* <code>org.apache.ignite.configuration.IgniteConfiguration</code> type.
*
* Group: consumer
*
* @param igniteConfiguration the value to set
* @return the dsl builder
*/
default IgniteEventsComponentBuilder igniteConfiguration(
org.apache.ignite.configuration.IgniteConfiguration igniteConfiguration) {
doSetProperty("igniteConfiguration", igniteConfiguration);
return this;
}
/**
* Whether autowiring is enabled. This is used for automatic autowiring
* options (the option must be marked as autowired) by looking up in the
* registry to find if there is a single instance of matching type,
* which then gets configured on the component. This can be used for
* automatic configuring JDBC data sources, JMS connection factories,
* AWS Clients, etc.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: advanced
*
* @param autowiredEnabled the value to set
* @return the dsl builder
*/
default IgniteEventsComponentBuilder autowiredEnabled(
boolean autowiredEnabled) {
doSetProperty("autowiredEnabled", autowiredEnabled);
return this;
}
}
class IgniteEventsComponentBuilderImpl
extends
AbstractComponentBuilder<IgniteEventsComponent>
implements
IgniteEventsComponentBuilder {
@Override
protected IgniteEventsComponent buildConcreteComponent() {
return new IgniteEventsComponent();
}
@Override
protected boolean setPropertyOnComponent(
Component component,
String name,
Object value) {
switch (name) {
case "bridgeErrorHandler": ((IgniteEventsComponent) component).setBridgeErrorHandler((boolean) value); return true;
case "configurationResource": ((IgniteEventsComponent) component).setConfigurationResource((java.lang.Object) value); return true;
case "ignite": ((IgniteEventsComponent) component).setIgnite((org.apache.ignite.Ignite) value); return true;
case "igniteConfiguration": ((IgniteEventsComponent) component).setIgniteConfiguration((org.apache.ignite.configuration.IgniteConfiguration) value); return true;
case "autowiredEnabled": ((IgniteEventsComponent) component).setAutowiredEnabled((boolean) value); return true;
default: return false;
}
}
}
}
|
package changs.android.utils;
import android.os.Build;
import android.text.Html;
import android.util.Base64;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2016/8/7
* desc : 编码解码相关工具类
* </pre>
*/
public class EncodeUtils {
private EncodeUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
/**
* URL编码
* <p>若想自己指定字符集,可以使用{@link #urlEncode(String input, String charset)}方法</p>
*
* @param input 要编码的字符
* @return 编码为UTF-8的字符串
*/
public static String urlEncode(String input) {
return urlEncode(input, "UTF-8");
}
/**
* URL编码
* <p>若系统不支持指定的编码字符集,则直接将input原样返回</p>
*
* @param input 要编码的字符
* @param charset 字符集
* @return 编码为字符集的字符串
*/
public static String urlEncode(String input, String charset) {
try {
return URLEncoder.encode(input, charset);
} catch (UnsupportedEncodingException e) {
return input;
}
}
/**
* URL解码
* <p>若想自己指定字符集,可以使用 {@link #urlDecode(String input, String charset)}方法</p>
*
* @param input 要解码的字符串
* @return URL解码后的字符串
*/
public static String urlDecode(String input) {
return urlDecode(input, "UTF-8");
}
/**
* URL解码
* <p>若系统不支持指定的解码字符集,则直接将input原样返回</p>
*
* @param input 要解码的字符串
* @param charset 字符集
* @return URL解码为指定字符集的字符串
*/
public static String urlDecode(String input, String charset) {
try {
return URLDecoder.decode(input, charset);
} catch (UnsupportedEncodingException e) {
return input;
}
}
/**
* Base64编码
*
* @param input 要编码的字符串
* @return Base64编码后的字符串
*/
public static byte[] base64Encode(String input) {
return base64Encode(input.getBytes());
}
/**
* Base64编码
*
* @param input 要编码的字节数组
* @return Base64编码后的字符串
*/
public static byte[] base64Encode(byte[] input) {
return Base64.encode(input, Base64.NO_WRAP);
}
/**
* Base64编码
*
* @param input 要编码的字节数组
* @return Base64编码后的字符串
*/
public static String base64Encode2String(byte[] input) {
return Base64.encodeToString(input, Base64.NO_WRAP);
}
/**
* Base64解码
*
* @param input 要解码的字符串
* @return Base64解码后的字符串
*/
public static byte[] base64Decode(String input) {
return Base64.decode(input, Base64.NO_WRAP);
}
/**
* Base64解码
*
* @param input 要解码的字符串
* @return Base64解码后的字符串
*/
public static byte[] base64Decode(byte[] input) {
return Base64.decode(input, Base64.NO_WRAP);
}
/**
* Base64URL安全编码
* <p>将Base64中的URL非法字符�?,/=转为其他字符, 见RFC3548</p>
*
* @param input 要Base64URL安全编码的字符串
* @return Base64URL安全编码后的字符串
*/
public static byte[] base64UrlSafeEncode(String input) {
return Base64.encode(input.getBytes(), Base64.URL_SAFE);
}
/**
* Html编码
*
* @param input 要Html编码的字符串
* @return Html编码后的字符串
*/
public static String htmlEncode(CharSequence input) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
return Html.escapeHtml(input);
} else {
// 参照Html.escapeHtml()中代码
StringBuilder out = new StringBuilder();
for (int i = 0, len = input.length(); i < len; i++) {
char c = input.charAt(i);
if (c == '<') {
out.append("<");
} else if (c == '>') {
out.append(">");
} else if (c == '&') {
out.append("&");
} else if (c >= 0xD800 && c <= 0xDFFF) {
if (c < 0xDC00 && i + 1 < len) {
char d = input.charAt(i + 1);
if (d >= 0xDC00 && d <= 0xDFFF) {
i++;
int codepoint = 0x010000 | (int) c - 0xD800 << 10 | (int) d - 0xDC00;
out.append("&#").append(codepoint).append(";");
}
}
} else if (c > 0x7E || c < ' ') {
out.append("&#").append((int) c).append(";");
} else if (c == ' ') {
while (i + 1 < len && input.charAt(i + 1) == ' ') {
out.append(" ");
i++;
}
out.append(' ');
} else {
out.append(c);
}
}
return out.toString();
}
}
/**
* Html解码
*
* @param input 待解码的字符串
* @return Html解码后的字符串
*/
@SuppressWarnings("deprecation")
public static CharSequence htmlDecode(String input) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return Html.fromHtml(input, Html.FROM_HTML_MODE_LEGACY);
} else {
return Html.fromHtml(input);
}
}
}
|
/*
* Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: Number.java,v 1.2.4.1 2005/09/21 09:40:51 pvedula Exp $
*/
package com.sun.org.apache.xalan.internal.xsltc.compiler;
import java.util.ArrayList;
import com.sun.org.apache.bcel.internal.classfile.Field;
import com.sun.org.apache.bcel.internal.generic.ALOAD;
import com.sun.org.apache.bcel.internal.generic.ILOAD;
import com.sun.org.apache.bcel.internal.generic.ASTORE;
import com.sun.org.apache.bcel.internal.generic.BranchHandle;
import com.sun.org.apache.bcel.internal.generic.CHECKCAST;
import com.sun.org.apache.bcel.internal.generic.ConstantPoolGen;
import com.sun.org.apache.bcel.internal.generic.GETFIELD;
import com.sun.org.apache.bcel.internal.generic.GOTO;
import com.sun.org.apache.bcel.internal.generic.IFNONNULL;
import com.sun.org.apache.bcel.internal.generic.INVOKESPECIAL;
import com.sun.org.apache.bcel.internal.generic.INVOKESTATIC;
import com.sun.org.apache.bcel.internal.generic.INVOKEVIRTUAL;
import com.sun.org.apache.bcel.internal.generic.InstructionList;
import com.sun.org.apache.bcel.internal.generic.D2I;
import com.sun.org.apache.bcel.internal.generic.LocalVariableGen;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.sun.org.apache.bcel.internal.generic.PUSH;
import com.sun.org.apache.bcel.internal.generic.PUTFIELD;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ClassGenerator;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.MatchGenerator;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.MethodGenerator;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.NodeCounterGenerator;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.RealType;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.TypeCheckError;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.Util;
/**
* @author Jacek Ambroziak
* @author Santiago Pericas-Geertsen
*/
final class Number extends Instruction implements Closure {
private static final int LEVEL_SINGLE = 0;
private static final int LEVEL_MULTIPLE = 1;
private static final int LEVEL_ANY = 2;
static final private String[] ClassNames = {
"com.sun.org.apache.xalan.internal.xsltc.dom.SingleNodeCounter", // LEVEL_SINGLE
"com.sun.org.apache.xalan.internal.xsltc.dom.MultipleNodeCounter", // LEVEL_MULTIPLE
"com.sun.org.apache.xalan.internal.xsltc.dom.AnyNodeCounter" // LEVEL_ANY
};
static final private String[] FieldNames = {
"___single_node_counter", // LEVEL_SINGLE
"___multiple_node_counter", // LEVEL_MULTIPLE
"___any_node_counter" // LEVEL_ANY
};
private Pattern _from = null;
private Pattern _count = null;
private Expression _value = null;
private AttributeValueTemplate _lang = null;
private AttributeValueTemplate _format = null;
private AttributeValueTemplate _letterValue = null;
private AttributeValueTemplate _groupingSeparator = null;
private AttributeValueTemplate _groupingSize = null;
private int _level = LEVEL_SINGLE;
private boolean _formatNeeded = false;
private String _className = null;
private ArrayList _closureVars = null;
// -- Begin Closure interface --------------------
/**
* Returns true if this closure is compiled in an inner class (i.e.
* if this is a real closure).
*/
public boolean inInnerClass() {
return (_className != null);
}
/**
* Returns a reference to its parent closure or null if outermost.
*/
public Closure getParentClosure() {
return null;
}
/**
* Returns the name of the auxiliary class or null if this predicate
* is compiled inside the Translet.
*/
public String getInnerClassName() {
return _className;
}
/**
* Add new variable to the closure.
*/
public void addVariable(VariableRefBase variableRef) {
if (_closureVars == null) {
_closureVars = new ArrayList();
}
// Only one reference per variable
if (!_closureVars.contains(variableRef)) {
_closureVars.add(variableRef);
}
}
// -- End Closure interface ----------------------
public void parseContents(Parser parser) {
final int count = _attributes.getLength();
for (int i = 0; i < count; i++) {
final String name = _attributes.getQName(i);
final String value = _attributes.getValue(i);
if (name.equals("value")) {
_value = parser.parseExpression(this, name, null);
}
else if (name.equals("count")) {
_count = parser.parsePattern(this, name, null);
}
else if (name.equals("from")) {
_from = parser.parsePattern(this, name, null);
}
else if (name.equals("level")) {
if (value.equals("single")) {
_level = LEVEL_SINGLE;
}
else if (value.equals("multiple")) {
_level = LEVEL_MULTIPLE;
}
else if (value.equals("any")) {
_level = LEVEL_ANY;
}
}
else if (name.equals("format")) {
_format = new AttributeValueTemplate(value, parser, this);
_formatNeeded = true;
}
else if (name.equals("lang")) {
_lang = new AttributeValueTemplate(value, parser, this);
_formatNeeded = true;
}
else if (name.equals("letter-value")) {
_letterValue = new AttributeValueTemplate(value, parser, this);
_formatNeeded = true;
}
else if (name.equals("grouping-separator")) {
_groupingSeparator = new AttributeValueTemplate(value, parser, this);
_formatNeeded = true;
}
else if (name.equals("grouping-size")) {
_groupingSize = new AttributeValueTemplate(value, parser, this);
_formatNeeded = true;
}
}
}
public Type typeCheck(SymbolTable stable) throws TypeCheckError {
if (_value != null) {
Type tvalue = _value.typeCheck(stable);
if (tvalue instanceof RealType == false) {
_value = new CastExpr(_value, Type.Real);
}
}
if (_count != null) {
_count.typeCheck(stable);
}
if (_from != null) {
_from.typeCheck(stable);
}
if (_format != null) {
_format.typeCheck(stable);
}
if (_lang != null) {
_lang.typeCheck(stable);
}
if (_letterValue != null) {
_letterValue.typeCheck(stable);
}
if (_groupingSeparator != null) {
_groupingSeparator.typeCheck(stable);
}
if (_groupingSize != null) {
_groupingSize.typeCheck(stable);
}
return Type.Void;
}
/**
* True if the has specified a value for this instance of number.
*/
public boolean hasValue() {
return _value != null;
}
/**
* Returns <tt>true</tt> if this instance of number has neither
* a from nor a count pattern.
*/
public boolean isDefault() {
return _from == null && _count == null;
}
private void compileDefault(ClassGenerator classGen,
MethodGenerator methodGen) {
int index;
ConstantPoolGen cpg = classGen.getConstantPool();
InstructionList il = methodGen.getInstructionList();
int[] fieldIndexes = getXSLTC().getNumberFieldIndexes();
if (fieldIndexes[_level] == -1) {
Field defaultNode = new Field(ACC_PRIVATE,
cpg.addUtf8(FieldNames[_level]),
cpg.addUtf8(NODE_COUNTER_SIG),
null,
cpg.getConstantPool());
// Add a new private field to this class
classGen.addField(defaultNode);
// Get a reference to the newly added field
fieldIndexes[_level] = cpg.addFieldref(classGen.getClassName(),
FieldNames[_level],
NODE_COUNTER_SIG);
}
// Check if field is initialized (runtime)
il.append(classGen.loadTranslet());
il.append(new GETFIELD(fieldIndexes[_level]));
final BranchHandle ifBlock1 = il.append(new IFNONNULL(null));
// Create an instance of DefaultNodeCounter
index = cpg.addMethodref(ClassNames[_level],
"getDefaultNodeCounter",
"(" + TRANSLET_INTF_SIG
+ DOM_INTF_SIG
+ NODE_ITERATOR_SIG
+ ")" + NODE_COUNTER_SIG);
il.append(classGen.loadTranslet());
il.append(methodGen.loadDOM());
il.append(methodGen.loadIterator());
il.append(new INVOKESTATIC(index));
il.append(DUP);
// Store the node counter in the field
il.append(classGen.loadTranslet());
il.append(SWAP);
il.append(new PUTFIELD(fieldIndexes[_level]));
final BranchHandle ifBlock2 = il.append(new GOTO(null));
// Backpatch conditionals
ifBlock1.setTarget(il.append(classGen.loadTranslet()));
il.append(new GETFIELD(fieldIndexes[_level]));
ifBlock2.setTarget(il.append(NOP));
}
/**
* Compiles a constructor for the class <tt>_className</tt> that
* inherits from {Any,Single,Multiple}NodeCounter. This constructor
* simply calls the same constructor in the super class.
*/
private void compileConstructor(ClassGenerator classGen) {
MethodGenerator cons;
final InstructionList il = new InstructionList();
final ConstantPoolGen cpg = classGen.getConstantPool();
cons = new MethodGenerator(ACC_PUBLIC,
com.sun.org.apache.bcel.internal.generic.Type.VOID,
new com.sun.org.apache.bcel.internal.generic.Type[] {
Util.getJCRefType(TRANSLET_INTF_SIG),
Util.getJCRefType(DOM_INTF_SIG),
Util.getJCRefType(NODE_ITERATOR_SIG),
com.sun.org.apache.bcel.internal.generic.Type.BOOLEAN
},
new String[] {
"dom",
"translet",
"iterator",
"hasFrom"
},
"<init>", _className, il, cpg);
il.append(ALOAD_0); // this
il.append(ALOAD_1); // translet
il.append(ALOAD_2); // DOM
il.append(new ALOAD(3)); // iterator
il.append(new ILOAD(4)); // hasFrom
int index = cpg.addMethodref(ClassNames[_level],
"<init>",
"(" + TRANSLET_INTF_SIG
+ DOM_INTF_SIG
+ NODE_ITERATOR_SIG
+ "Z)V");
il.append(new INVOKESPECIAL(index));
il.append(RETURN);
classGen.addMethod(cons);
}
/**
* This method compiles code that is common to matchesFrom() and
* matchesCount() in the auxillary class.
*/
private void compileLocals(NodeCounterGenerator nodeCounterGen,
MatchGenerator matchGen,
InstructionList il)
{
int field;
LocalVariableGen local;
ConstantPoolGen cpg = nodeCounterGen.getConstantPool();
// Get NodeCounter._iterator and store locally
local = matchGen.addLocalVariable("iterator",
Util.getJCRefType(NODE_ITERATOR_SIG),
null, null);
field = cpg.addFieldref(NODE_COUNTER, "_iterator",
ITERATOR_FIELD_SIG);
il.append(ALOAD_0); // 'this' pointer on stack
il.append(new GETFIELD(field));
local.setStart(il.append(new ASTORE(local.getIndex())));
matchGen.setIteratorIndex(local.getIndex());
// Get NodeCounter._translet and store locally
local = matchGen.addLocalVariable("translet",
Util.getJCRefType(TRANSLET_SIG),
null, null);
field = cpg.addFieldref(NODE_COUNTER, "_translet",
"Lcom/sun/org/apache/xalan/internal/xsltc/Translet;");
il.append(ALOAD_0); // 'this' pointer on stack
il.append(new GETFIELD(field));
il.append(new CHECKCAST(cpg.addClass(TRANSLET_CLASS)));
local.setStart(il.append(new ASTORE(local.getIndex())));
nodeCounterGen.setTransletIndex(local.getIndex());
// Get NodeCounter._document and store locally
local = matchGen.addLocalVariable("document",
Util.getJCRefType(DOM_INTF_SIG),
null, null);
field = cpg.addFieldref(_className, "_document", DOM_INTF_SIG);
il.append(ALOAD_0); // 'this' pointer on stack
il.append(new GETFIELD(field));
// Make sure we have the correct DOM type on the stack!!!
local.setStart(il.append(new ASTORE(local.getIndex())));
matchGen.setDomIndex(local.getIndex());
}
private void compilePatterns(ClassGenerator classGen,
MethodGenerator methodGen)
{
int current;
int field;
LocalVariableGen local;
MatchGenerator matchGen;
NodeCounterGenerator nodeCounterGen;
_className = getXSLTC().getHelperClassName();
nodeCounterGen = new NodeCounterGenerator(_className,
ClassNames[_level],
toString(),
ACC_PUBLIC | ACC_SUPER,
null,
classGen.getStylesheet());
InstructionList il = null;
ConstantPoolGen cpg = nodeCounterGen.getConstantPool();
// Add a new instance variable for each var in closure
final int closureLen = (_closureVars == null) ? 0 :
_closureVars.size();
for (int i = 0; i < closureLen; i++) {
VariableBase var =
((VariableRefBase) _closureVars.get(i)).getVariable();
nodeCounterGen.addField(new Field(ACC_PUBLIC,
cpg.addUtf8(var.getEscapedName()),
cpg.addUtf8(var.getType().toSignature()),
null, cpg.getConstantPool()));
}
// Add a single constructor to the class
compileConstructor(nodeCounterGen);
/*
* Compile method matchesFrom()
*/
if (_from != null) {
il = new InstructionList();
matchGen =
new MatchGenerator(ACC_PUBLIC | ACC_FINAL,
com.sun.org.apache.bcel.internal.generic.Type.BOOLEAN,
new com.sun.org.apache.bcel.internal.generic.Type[] {
com.sun.org.apache.bcel.internal.generic.Type.INT,
},
new String[] {
"node",
},
"matchesFrom", _className, il, cpg);
compileLocals(nodeCounterGen,matchGen,il);
// Translate Pattern
il.append(matchGen.loadContextNode());
_from.translate(nodeCounterGen, matchGen);
_from.synthesize(nodeCounterGen, matchGen);
il.append(IRETURN);
nodeCounterGen.addMethod(matchGen);
}
/*
* Compile method matchesCount()
*/
if (_count != null) {
il = new InstructionList();
matchGen = new MatchGenerator(ACC_PUBLIC | ACC_FINAL,
com.sun.org.apache.bcel.internal.generic.Type.BOOLEAN,
new com.sun.org.apache.bcel.internal.generic.Type[] {
com.sun.org.apache.bcel.internal.generic.Type.INT,
},
new String[] {
"node",
},
"matchesCount", _className, il, cpg);
compileLocals(nodeCounterGen,matchGen,il);
// Translate Pattern
il.append(matchGen.loadContextNode());
_count.translate(nodeCounterGen, matchGen);
_count.synthesize(nodeCounterGen, matchGen);
il.append(IRETURN);
nodeCounterGen.addMethod(matchGen);
}
getXSLTC().dumpClass(nodeCounterGen.getJavaClass());
// Push an instance of the newly created class
cpg = classGen.getConstantPool();
il = methodGen.getInstructionList();
final int index = cpg.addMethodref(_className, "<init>",
"(" + TRANSLET_INTF_SIG
+ DOM_INTF_SIG
+ NODE_ITERATOR_SIG
+ "Z)V");
il.append(new NEW(cpg.addClass(_className)));
il.append(DUP);
il.append(classGen.loadTranslet());
il.append(methodGen.loadDOM());
il.append(methodGen.loadIterator());
il.append(_from != null ? ICONST_1 : ICONST_0);
il.append(new INVOKESPECIAL(index));
// Initialize closure variables
for (int i = 0; i < closureLen; i++) {
final VariableRefBase varRef = (VariableRefBase) _closureVars.get(i);
final VariableBase var = varRef.getVariable();
final Type varType = var.getType();
// Store variable in new closure
il.append(DUP);
il.append(var.loadInstruction());
il.append(new PUTFIELD(
cpg.addFieldref(_className, var.getEscapedName(),
varType.toSignature())));
}
}
public void translate(ClassGenerator classGen, MethodGenerator methodGen) {
int index;
final ConstantPoolGen cpg = classGen.getConstantPool();
final InstructionList il = methodGen.getInstructionList();
// Push "this" for the call to characters()
il.append(classGen.loadTranslet());
if (hasValue()) {
compileDefault(classGen, methodGen);
_value.translate(classGen, methodGen);
// Using java.lang.Math.floor(number + 0.5) to return a double value
il.append(new PUSH(cpg, 0.5));
il.append(DADD);
index = cpg.addMethodref(MATH_CLASS, "floor", "(D)D");
il.append(new INVOKESTATIC(index));
// Call setValue on the node counter
index = cpg.addMethodref(NODE_COUNTER,
"setValue",
"(D)" + NODE_COUNTER_SIG);
il.append(new INVOKEVIRTUAL(index));
}
else if (isDefault()) {
compileDefault(classGen, methodGen);
}
else {
compilePatterns(classGen, methodGen);
}
// Call setStartNode()
if (!hasValue()) {
il.append(methodGen.loadContextNode());
index = cpg.addMethodref(NODE_COUNTER,
SET_START_NODE,
"(I)" + NODE_COUNTER_SIG);
il.append(new INVOKEVIRTUAL(index));
}
// Call getCounter() with or without args
if (_formatNeeded) {
if (_format != null) {
_format.translate(classGen, methodGen);
}
else {
il.append(new PUSH(cpg, "1"));
}
if (_lang != null) {
_lang.translate(classGen, methodGen);
}
else {
il.append(new PUSH(cpg, "en")); // TODO ??
}
if (_letterValue != null) {
_letterValue.translate(classGen, methodGen);
}
else {
il.append(new PUSH(cpg, Constants.EMPTYSTRING));
}
if (_groupingSeparator != null) {
_groupingSeparator.translate(classGen, methodGen);
}
else {
il.append(new PUSH(cpg, Constants.EMPTYSTRING));
}
if (_groupingSize != null) {
_groupingSize.translate(classGen, methodGen);
}
else {
il.append(new PUSH(cpg, "0"));
}
index = cpg.addMethodref(NODE_COUNTER, "getCounter",
"(" + STRING_SIG + STRING_SIG
+ STRING_SIG + STRING_SIG
+ STRING_SIG + ")" + STRING_SIG);
il.append(new INVOKEVIRTUAL(index));
}
else {
index = cpg.addMethodref(NODE_COUNTER, "setDefaultFormatting",
"()" + NODE_COUNTER_SIG);
il.append(new INVOKEVIRTUAL(index));
index = cpg.addMethodref(NODE_COUNTER, "getCounter",
"()" + STRING_SIG);
il.append(new INVOKEVIRTUAL(index));
}
// Output the resulting string to the handler
il.append(methodGen.loadHandler());
index = cpg.addMethodref(TRANSLET_CLASS,
CHARACTERSW,
CHARACTERSW_SIG);
il.append(new INVOKEVIRTUAL(index));
}
}
|
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 smoketest.flyway;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class SampleFlywayApplication {
public static void main(String[] args) {
SpringApplication.run(SampleFlywayApplication.class, args);
}
@Bean
public CommandLineRunner runner(PersonRepository repository) {
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception {
System.err.println(repository.findAll());
}
};
}
}
|
package com.example.ame_simonsays;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.example.ame_simonsays", appContext.getPackageName());
}
}
|
package uk.gov.hmcts.dts.fact.controllers.admin;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import uk.gov.hmcts.dts.fact.exception.NotFoundException;
import uk.gov.hmcts.dts.fact.model.OpeningTime;
import uk.gov.hmcts.dts.fact.services.admin.AdminCourtOpeningTimeService;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import static java.nio.file.Files.readAllBytes;
import static java.util.Arrays.asList;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(AdminCourtOpeningTimesController.class)
@AutoConfigureMockMvc(addFilters = false)
public class AdminCourtOpeningTimesControllerTest {
private static final String BASE_PATH = "/courts/";
private static final String CHILD_PATH = "/openingTimes";
private static final String TEST_SLUG = "unknownSlug";
private static final Path TEST_OPENING_TIMES_PATH = Paths.get("src/test/resources/opening-times.json");
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
@Autowired
private transient MockMvc mockMvc;
@MockBean
private AdminCourtOpeningTimeService adminService;
@Test
void retrieveOpeningTimesShouldReturnCourtOpeningTimes() throws Exception {
final String expectedJson = getOpeningTimesJson();
final List<OpeningTime> openingTimes = asList(OBJECT_MAPPER.readValue(expectedJson, OpeningTime[].class));
when(adminService.getCourtOpeningTimesBySlug(TEST_SLUG)).thenReturn(openingTimes);
mockMvc.perform(get(BASE_PATH + TEST_SLUG + CHILD_PATH))
.andExpect(status().isOk())
.andExpect(content().json(expectedJson));
}
@Test
void retrieveOpeningTimeShouldReturnNotFoundForUnknownCourtSlug() throws Exception {
when(adminService.getCourtOpeningTimesBySlug(TEST_SLUG)).thenThrow(new NotFoundException(TEST_SLUG));
mockMvc.perform(get(BASE_PATH + TEST_SLUG + CHILD_PATH))
.andExpect(status().isNotFound())
.andExpect(content().string("Not found: " + TEST_SLUG));
}
@Test
void updateOpeningTimesShouldReturnUpdatedCourtOpeningTimes() throws Exception {
final String expectedJson = getOpeningTimesJson();
final List<OpeningTime> openingTimes = asList(OBJECT_MAPPER.readValue(expectedJson, OpeningTime[].class));
when(adminService.updateCourtOpeningTimes(TEST_SLUG, openingTimes)).thenReturn(openingTimes);
mockMvc.perform(put(BASE_PATH + TEST_SLUG + CHILD_PATH)
.content(expectedJson)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().json(expectedJson));
}
@Test
void updateOpeningTimesShouldReturnNotFoundForUnknownCourtSlug() throws Exception {
final String json = getOpeningTimesJson();
final List<OpeningTime> openingTimes = asList(OBJECT_MAPPER.readValue(json, OpeningTime[].class));
when(adminService.updateCourtOpeningTimes(TEST_SLUG, openingTimes)).thenThrow(new NotFoundException(TEST_SLUG));
mockMvc.perform(put(BASE_PATH + TEST_SLUG + CHILD_PATH)
.content(json)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNotFound())
.andExpect(content().string("Not found: " + TEST_SLUG));
}
private static String getOpeningTimesJson() throws IOException {
return new String(readAllBytes(TEST_OPENING_TIMES_PATH));
}
}
|
/**
* Copyright (C) 2014-2016 LinkedIn Corp. (pinot-core@linkedin.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.linkedin.pinot.core.io.writer.impl;
import com.linkedin.pinot.common.utils.MmapUtils;
import com.linkedin.pinot.core.io.readerwriter.PinotDataBufferMemoryManager;
import com.linkedin.pinot.core.segment.memory.PinotDataBuffer;
import java.io.File;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class MmapMemoryManagerTest {
private String _tmpDir;
@BeforeClass
public void setUp() {
_tmpDir = System.getProperty("java.io.tmpdir") + "/" + MmapMemoryManagerTest.class.getSimpleName();
File dir = new File(_tmpDir);
FileUtils.deleteQuietly(dir);
dir.mkdir();
dir.deleteOnExit();
}
@AfterClass
public void tearDown() {
new File(_tmpDir).delete();
}
@Test
public void testLargeBlocks() throws Exception {
final String segmentName = "someSegment";
PinotDataBufferMemoryManager memoryManager = new MmapMemoryManager(_tmpDir, segmentName);
final long s1 = 2 * MmapMemoryManager.getDefaultFileLength();
final long s2 = 1000;
final String col1 = "col1";
final String col2 = "col2";
final byte value = 34;
PinotDataBuffer buf1 = memoryManager.allocate(s1, col1);
// Verify that we can write to and read from the buffer
ByteBuffer b1 = buf1.toDirectByteBuffer(0, (int) s1);
b1.putLong(0, s1);
Assert.assertEquals(b1.getLong(0), s1);
b1.put((int) s1 - 1, value);
Assert.assertEquals(b1.get((int) s1 - 1), value);
PinotDataBuffer buf2 = memoryManager.allocate(s2, col2);
ByteBuffer b2 = buf2.toDirectByteBuffer(0, (int) s2);
b2.putLong(0, s2);
Assert.assertEquals(b2.getLong(0), s2);
File dir = new File(_tmpDir);
File[] files = dir.listFiles();
Assert.assertEquals(files.length, 2);
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
return o1.getName().compareTo(o2.getName());
}
});
String fileName = files[0].getName();
Assert.assertTrue(fileName.contains(segmentName));
fileName = files[1].getName();
Assert.assertTrue(fileName.contains(segmentName));
buf1.close();
buf2.close();
memoryManager.close();
List<Pair<MmapUtils.AllocationContext, Integer>> allocationContexts = MmapUtils.getAllocationsAndSizes();
Assert.assertEquals(allocationContexts.size(), 0);
Assert.assertEquals(new File(_tmpDir).listFiles().length, 0);
}
@Test
public void testSmallBlocksForSameColumn() throws Exception {
final String segmentName = "someSegment";
PinotDataBufferMemoryManager memoryManager = new MmapMemoryManager(_tmpDir, segmentName);
final long s1 = 500;
final long s2 = 1000;
final String col1 = "col1";
PinotDataBuffer buf1 = memoryManager.allocate(s1, col1);
PinotDataBuffer buf2 = memoryManager.allocate(s2, col1);
ByteBuffer b1 = buf1.toDirectByteBuffer(0, (int) s1);
b1.putLong(0, s1);
ByteBuffer b2 = buf2.toDirectByteBuffer(0, (int) s2);
b2.putLong(0, s2);
Assert.assertEquals(b1.getLong(0), s1);
Assert.assertEquals(b2.getLong(0), s2);
File dir = new File(_tmpDir);
Assert.assertEquals(dir.listFiles().length, 1);
buf1.close();
buf2.close();
memoryManager.close();
List<Pair<MmapUtils.AllocationContext, Integer>> allocationContexts = MmapUtils.getAllocationsAndSizes();
Assert.assertEquals(allocationContexts.size(), 0);
Assert.assertEquals(dir.listFiles().length, 0);
}
@Test
public void testCornerConditions() throws Exception {
final String segmentName = "someSegment";
PinotDataBufferMemoryManager memoryManager = new MmapMemoryManager(_tmpDir, segmentName);
final long s1 = MmapMemoryManager.getDefaultFileLength() - 1;
final long s2 = 1;
final long s3 = 100 * 1024 * 1024;
final String colName = "col";
final byte v1 = 56;
final byte v2 = 11;
final byte v3 = 32;
// Allocate a buffer 1 less than the default file length, and write the last byte of the buffer.
PinotDataBuffer b1 = memoryManager.allocate(s1, colName);
ByteBuffer bb1 = b1.toDirectByteBuffer(0, (int) s1);
bb1.put((int) s1 - 1, v1);
// Allocate another buffer that is 1 byte in size, should be in the same file.
// Write a value in the byte.
PinotDataBuffer b2 = memoryManager.allocate(s2, colName);
ByteBuffer bb2 = b2.toDirectByteBuffer(0, (int) s2);
bb2.put((int) s2 - 1, v2);
// Verify that there is only one file.
File dir = new File(_tmpDir);
Assert.assertEquals(dir.listFiles().length, 1);
// Now allocate another buffer that will open a second file, write a value in the first byte of the buffer.
PinotDataBuffer b3 = memoryManager.allocate(s3, colName);
ByteBuffer bb3 = b3.toDirectByteBuffer(0, (int) s3);
bb3.put(0, v3);
// Ensure that there are 2 files.
Assert.assertEquals(dir.listFiles().length, 2);
// Make sure that the values written are preserved.
Assert.assertEquals(bb1.get((int) s1 - 1), v1);
Assert.assertEquals(bb2.get((int) s2 - 1), v2);
Assert.assertEquals(bb3.get(0), v3);
memoryManager.close();
List<Pair<MmapUtils.AllocationContext, Integer>> allocationContexts = MmapUtils.getAllocationsAndSizes();
Assert.assertEquals(allocationContexts.size(), 0);
}
}
|
package com.alipay.api.response;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: alipay.open.lottery.region.create response.
*
* @author auto create
* @since 1.0, 2020-01-07 19:36:55
*/
public class AlipayOpenLotteryRegionCreateResponse extends AlipayResponse {
private static final long serialVersionUID = 1678663529212823931L;
/**
* 商家入驻ID
*/
@ApiField("region_id")
private String regionId;
public void setRegionId(String regionId) {
this.regionId = regionId;
}
public String getRegionId( ) {
return this.regionId;
}
}
|
/*
* Copyright 2000-2018 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.server.rest.swagger;
import io.swagger.models.Swagger;
import io.swagger.util.Json;
import io.swagger.util.Yaml;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import jetbrains.buildServer.server.rest.APIController;
import jetbrains.buildServer.server.rest.util.AdditionalMediaTypes;
import jetbrains.buildServer.serverSide.TeamCityProperties;
@Provider
@Produces({MediaType.APPLICATION_JSON, AdditionalMediaTypes.APPLICATION_YAML})
public class SwaggerSerializers implements MessageBodyWriter<Swagger> {
public static final String CHARSET_NAME = "UTF-8";
public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return Swagger.class.isAssignableFrom(type);
}
public long getSize(Swagger data, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return -1;
}
public void writeTo(Swagger data,
Class<?> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, Object> headers,
OutputStream out) throws IOException {
// TODO: Consider something better instead of writeValueAsString. Catch 'pipe broken (connection closed)' errors
final boolean pretty = TeamCityProperties.getBoolean(APIController.REST_RESPONSE_PRETTYFORMAT);
if (mediaType.isCompatible(MediaType.APPLICATION_JSON_TYPE)) {
if (pretty) {
out.write(Json.pretty().writeValueAsString(data).getBytes(CHARSET_NAME));
} else {
out.write(Json.mapper().writeValueAsString(data).getBytes(CHARSET_NAME));
}
} else if (mediaType.isCompatible(AdditionalMediaTypes.APPLICATION_YAML_TYPE)) {
if (pretty) {
out.write(Yaml.pretty().writeValueAsString(data).getBytes(CHARSET_NAME));
} else {
out.write(Yaml.mapper().writeValueAsString(data).getBytes(CHARSET_NAME));
}
}
}
}
|
/*
* Copyright 2021 DADi590
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.dadi590.assist_c_a.Modules.Telephony;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.telephony.PhoneNumberUtils;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.dadi590.assist_c_a.GlobalUtils.UtilsGeneral;
import java.util.ArrayList;
import java.util.Collection;
/**
* <p>Global telephony-related utilities.</p>
*/
public final class UtilsTelephony {
/**
* <p>Private empty constructor so the class can't be instantiated (utility class).</p>
*/
private UtilsTelephony() {
}
/**
* <p>The URI to be used to retrieve contacts from SIM cards (or how Google calls them - ICC cards, which would
* stand for Integrated Circuits Card).</p>
* <br>
* <p>Note: this was found on StackOverflow and seems to work on Lollipop 5.1 at least.</p>
* <br>
* <p>Started to be used on Android 1.6 (API 4), according to
* <a href="https://androidforums.com/threads/sim-contacts.374255/">this</a>. On Android 1.5 (API 3) it was
* "content://sim/adn".</p>
*/
private static final Uri ICC_URI_API4PLUS = Uri.parse("content://icc/adn");
public static final int ALL_CONTACTS = 0;
public static final int CONTACTS_SIM = 1;
public static final String NO_MATCHES = "3234_NO_MATCHES";
public static final String MULTIPLE_MATCHES = "3234_MULTIPLE_MATCHES";
public static final String CONTENT_URI_ERROR = "3234_CONTENT_URI_ERROR";
/**
* <p>Gets the name of a contact through its phone number.</p>
* <br>
* <p><u>---CONSTANTS---</u></p>
* <p>- {@link #ALL_CONTACTS} --> for {@code location_search}: search everywhere for the contact</p>
* <p>- {@link #CONTACTS_SIM} --> for {@code location_search}: search only on the SIM contacts for the contact</p>
* <p>- {@link #NO_MATCHES} --> returned when no number was found for the given phone number</p>
* <p>- {@link #MULTIPLE_MATCHES} --> returned when multiple contacts were found for the given phone number</p>
* <p>- {@link #CONTENT_URI_ERROR} --> returned if a wrong value was used the parameter {@code location_search}</p>
* <p><u>---CONSTANTS---</u></p>
*
* @param number the phone number of the contact
* @param location_search location where to look for the contact
*
* @return the name of the contact or one of the constants
*/
@NonNull
public static String getNameFromNum(@NonNull final String number, final int location_search) {
final Uri uri_to_use;
switch (location_search) {
case (ALL_CONTACTS):
uri_to_use = ContactsContract.Contacts.CONTENT_URI;
// This seems to give the contacts of the entire phone: SIM card, phone storage and accounts like Google,
// Whatsapp...
break;
case (CONTACTS_SIM):
uri_to_use = ICC_URI_API4PLUS;
break;
default:
return CONTENT_URI_ERROR;
}
final ContentResolver contentResolver = UtilsGeneral.getContext().getContentResolver();
int num_matches = 0;
String last_name_found = "";
try (final Cursor cursor = contentResolver.query(uri_to_use, null, null, null, null)) {
final Collection<String> matches = new ArrayList<>(10); // 10 matches at most, I guess?
// todo Put this in a thread!!! --> "Skipped 135 frames!"
if (location_search == ALL_CONTACTS) {
if ((cursor != null ? cursor.getCount() : 0) > 0) {
while (cursor.moveToNext()) {
final String id = cursor.getString(cursor.getColumnIndex(BaseColumns._ID));
final String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
//System.out.println("Name: " + name);
if (cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
try (
final Cursor cursor1 = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null)
) {
while (cursor1.moveToNext()) {
final String phoneNo = cursor1.getString(cursor1.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
//System.out.println("Number: " + phoneNo);
if (PhoneNumberUtils.compareStrictly(number, phoneNo)) {
// Nota: os métodos compareStrictly() só estão disponíveis com as classes escondidas/internas ativadas (ver código-fonte --> @UnsupportedAppUsage).
/*System.out.println("---Name: " + name);
System.out.println("---Number: " + phoneNo);*/
boolean already_found = false;
for (final String match : matches) {
if (match.equals(name)) {
already_found = true;
break;
}
}
if (!already_found) {
matches.add(name);
last_name_found = name;
++num_matches;
}
}
}
}
}
}
}
} else if (location_search == CONTACTS_SIM) {
// Leave it even being "always true" - until another location is added... Might prevent bugs.
while (cursor.moveToNext()) {
final String name = cursor.getString(cursor.getColumnIndex("name"));
//listContactId.add(cursorSim.getString(cursorSim.getColumnIndex("_id")));
final String phoneNo = cursor.getString(cursor.getColumnIndex("number"));
/*System.out.println("Name: " + name);
System.out.println("Phone Number: " + phoneNo);*/
if (PhoneNumberUtils.compareStrictly(number, phoneNo)) {
// Note: the compareStrictly() methods are only available with the hidden/internal classes showing
/*System.out.println("---Name: " + name);
System.out.println("---Number: " + phoneNo);*/
boolean already_found = false;
for (final String match : matches) {
if (match.equals(name)) {
already_found = true;
break;
}
}
if (!already_found) {
matches.add(name);
last_name_found = name;
++num_matches;
}
}
}
}
}
/*System.out.println("OOOOOOOOOOOOOOOOOOO");
System.out.println(num_matches);
System.out.println(last_name_found);
System.out.println("OOOOOOOOOOOOOOOOOOO");*/
if (num_matches == 0) {
return NO_MATCHES;
} else if (num_matches == 1) {
return last_name_found;
} else {
return MULTIPLE_MATCHES;
}
}
/**
* <p>Checks if a number is a private number.</p>
*
* @param number the phone number got directly from the incoming call
*
* @return true if it's a private number, false otherwise
*/
public static boolean isPrivateNumber(@Nullable final String number) {
// Note: looked up how the ISPs normally represent private numbers and the final code I made was this.
// Has been detecting correctly - if the number is really private (go to Phone settings change that), this
// says it's a private number.
// Hasn't said a normal number is a private one, so all seems alright.
if (number != null && !number.isEmpty()) {
// This below is to check if it's a valid phone number, since it's neither null nor an empty string.
// When PayPal sends a message, the "number" is "PayPal". In that case, converting to a long throws an error.
// In that case, it's because it's some name (not a private number then).
// If the conversion works, then check if the number is greater or equal to 0 ("Private numbers are sent to
// the phone as -1 or -2.", according with a StackOverflow user), and in that case, it's not a private number.
try {
if (Long.parseLong(number) >= 0L) {
return false;
}
} catch (final NumberFormatException ignored) {
return false;
}
}
return true;
}
/**
* <p>Returns what the assistant should say about the given number.</p>
* <br>
* <p>For example, for a phone number, it will separate all digits, so the assistant can spell the number. For
* an alphanumeric number (like PayPal), it will return a string to warn it's a alphanumeric number. Will also warn
* about multiple matches on the number.</p>
*
* @param number the number of the contact
*
* @return what the assistant should say
*/
@NonNull
public static String getWhatToSayAboutNumber(@NonNull final String number) {
final String ret = getNameFromNum(number, ALL_CONTACTS);
if (ret.equals(NO_MATCHES)) {
if (PhoneNumberUtils.isGlobalPhoneNumber(number)) {
// In case it's a phone number, separate each digit and spell. So +351123456789 will be rewritten as
// + 3 5 1 1 2 3 4 5 6 7 8 9. Instead of saying 23 trillions and 47 billions (lol), it will say number by
// number. This is in case the TTS engine doesn't recognize the number pattern (Ivona for Android doesn't
// recognize Portugal numbers, for example, but recognizes US numbers - don't care anymore then).
return number.replace("", " ").trim();
} else {
// In case the "number" is "PayPal", for example, don't spell. Instead, warn about it and say the name
// that came.
return "an alphanumeric number: " + number;
}
} else if (ret.equals(MULTIPLE_MATCHES)) {
return "Attention - Multiple matches on " + number.replace("", " ").trim();
}
return ret;
}
public static final String ERROR = "3234_ERROR_1";
public static final String NO_CALLS_DETECTED = "3234_NO_CALLS_DETECTED";
/**
* <p>Gets the number and type of last call detected on the phone.</p>
* <br>
* <p><u>---CONSTANTS---</u></p>
* <p>- {@link #ERROR} --> returned if there was an error</p>
* <p>- {@link #NO_CALLS_DETECTED} --> returned if no calls were detected on the phone</p>
* <p><u>---CONSTANTS---</u></p>
*
* @return a String[] of 2 indexes: in index 0 the phone number, in index 1 one of the {@link CallLog.Calls#TYPE}s
* of the call. On both indexes at the same time only might be one of the constants.
*/
@NonNull
public static String[] getLastCall() {
final ContentResolver contentResolver = UtilsGeneral.getContext().getContentResolver();
try (final Cursor cursor = contentResolver.query(CallLog.Calls.CONTENT_URI, null, null, null, null)) {
if (cursor == null) {
return new String[]{ERROR, ERROR};
}
if (cursor.moveToLast()) { //starts pulling logs from last - you can use moveToFirst() for first logs
final String phNumber = cursor.getString(cursor.getColumnIndexOrThrow(CallLog.Calls.NUMBER));
final String type = cursor.getString(cursor.getColumnIndexOrThrow(CallLog.Calls.TYPE));
cursor.close();
return new String[]{phNumber, type};
}
}
return new String[]{NO_CALLS_DETECTED, NO_CALLS_DETECTED};
}
/**
* <p>Gets the {@link CallLog.Calls#TYPE} of the last call of the given phone number.</p>
*
* @param number the phone number
*
* @return one of the {@link CallLog.Calls#TYPE}s of call
*/
public static int getTypeLastCallByNum(@NonNull final String number) {
final ContentResolver contentResolver = UtilsGeneral.getContext().getContentResolver();
try (final Cursor cursor = contentResolver.query(CallLog.Calls.CONTENT_URI, null, null, null, null)) {
if (cursor == null) {
return -2;
}
do {
final String phNumber = cursor.getString(cursor.getColumnIndexOrThrow(CallLog.Calls.NUMBER));
if (PhoneNumberUtils.compareStrictly(phNumber, number)) {
return Integer.parseInt(cursor.getString(cursor.getColumnIndexOrThrow(CallLog.Calls.TYPE)));
}
} while (cursor.moveToPrevious());
}
return -1;
}
/*public static void getCallLogs() {
ContentResolver cr = contexto.getContentResolver();
Cursor c = cr.query(CallLog.Calls.CONTENT_URI, null, null, null, null);
if (c == null) {
return;
}
System.out.println("LLLLLLLLLLLLLLLLLLLLL");
int totalCall = 10; // integer call log limit
if (c.moveToLast()) { //starts pulling logs from last - you can use moveToFirst() for first logs
System.out.println("TTTTTTTTTTTTTTTTTTT");
int j = 0;
do {
String phNumber = c.getString(c.getColumnIndexOrThrow(CallLog.Calls.NUMBER));
String callDate = c.getString(c.getColumnIndexOrThrow(CallLog.Calls.DATE));
String callDuration = c.getString(c.getColumnIndexOrThrow(CallLog.Calls.DURATION));
Date dateFormat = new Date(Long.parseLong(callDate));
String callDayTimes = String.valueOf(dateFormat);
String direction = null;
switch (Integer.parseInt(c.getString(c.getColumnIndexOrThrow(CallLog.Calls.TYPE)))) {
case (CallLog.Calls.OUTGOING_TYPE):
direction = "OUTGOING";
break;
case (CallLog.Calls.INCOMING_TYPE):
direction = "INCOMING";
break;
case (CallLog.Calls.MISSED_TYPE):
direction = "MISSED";
System.out.println(phNumber);
System.out.println(dateFormat.toString());
break;
default:
break;
}
//Toast.makeText(context, phNumber + callDuration + callDayTimes + direction, Toast.LENGTH_SHORT).show();
// you can use strings in this line
++j;
}
while (c.moveToPrevious() && j < totalCall);
}
c.close();
}*/
}
|
package net.violet.platform.api.actions.anim;
import java.util.ArrayList;
import java.util.List;
import net.violet.platform.api.actions.AbstractAction;
import net.violet.platform.api.actions.ActionParam;
import net.violet.platform.datamodel.Application;
import net.violet.platform.datamodel.Application.ApplicationClass;
import net.violet.platform.dataobjects.AnimData;
import net.violet.platform.util.Constantes;
public class Get extends AbstractAction {
/**
* Returns all the animations names (list of String).
*
* @see
*/
@Override
protected Object doProcessRequest(ActionParam inParam) {
final List<String> result = new ArrayList<String>();
for (final AnimData inAnim : AnimData.findAllAnim()) {
result.add(inAnim.getLabel());
}
return result;
}
/**
* @see net.violet.platform.api.actions.Action#isCacheable()
*/
public boolean isCacheable() {
return true;
}
/**
* Object informations may be cached one day
*
* @see net.violet.platform.api.actions.Action#getExpirationTime()
*/
public long getExpirationTime() {
return Constantes.ONE_DAY_IN_S;
}
/**
* Read Only action
*
* @see net.violet.platform.api.actions.Action#getType()
*/
public ActionType getType() {
return ActionType.GET;
}
@Override
public List<ApplicationClass> getAuthorizedApplicationClasses() {
return Application.CLASSES_ALL;
}
}
|
package twitter4jads.stats;
import com.google.common.collect.Lists;
import twitter4jads.*;
import twitter4jads.api.TwitterAdsStatApi;
import twitter4jads.internal.models4j.TwitterException;
import twitter4jads.models.Granularity;
import twitter4jads.models.TwitterSegmentationType;
import twitter4jads.models.ads.*;
import twitter4jads.util.TwitterAdUtil;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
/**
* User: shivraj
* Date: 12/05/16 2:08 PM.
*/
public class GetAsyncTweetStatsForAccount extends BaseAdsTest {
public static void main(String[] args) {
TwitterAds twitterAdsInstance = getTwitterAdsInstance();
TwitterAdsStatApi statApi = twitterAdsInstance.getStatApi();
String until = "2020-10-21";
String since = "2020-10-04";
try {
BaseAdsResponse<JobDetails> twitterAsyncJob = statApi.createAsyncJob("18ce55907vh", TwitterEntityType.CAMPAIGN, Lists.newArrayList("eilx6", "eim4z", "eisvd", "ehd9i", "ehb9n", "eisuu", "eilxr", "eipmm", "eim8s"), since, until, Boolean.FALSE, Granularity.DAY, Placement.ALL_ON_TWITTER, Optional.of(TwitterSegmentationType.INTERESTS), null, null);
BaseAdsListResponseIterable<JobDetails> jobExecutionDetails;
boolean flag;
long timeOut = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(2);
do {
flag = false; //continue iterating as long as status of job of job is either queued, uploading or processing
TwitterAdUtil.reallySleep(10000L);
jobExecutionDetails = statApi.getJobExecutionDetails("18ce55907vh", Lists.newArrayList(twitterAsyncJob.getData().getJobId()));
for (BaseAdsListResponse<JobDetails> base : jobExecutionDetails) {
List<JobDetails> baselist = base.getData();
for (JobDetails jd : baselist) {
if ((jd != null) && (jd.getStatus() != TwitterAsyncQueryStatus.SUCCESS)) {
flag = true;
}
}
}
} while (flag && System.currentTimeMillis() <= timeOut);
List<TwitterEntityStatistics> twitterEntityStatsList = Lists.newArrayList();
for (BaseAdsListResponse<JobDetails> base : jobExecutionDetails) {
List<JobDetails> baselist = base.getData();
for (JobDetails jd : baselist) {
BaseAdsListResponse<TwitterEntityStatistics> allTwitterEntityStat = statApi.fetchJobDataAsync(jd.getUrl());
if(allTwitterEntityStat == null || allTwitterEntityStat.getData() == null){
continue;
}
twitterEntityStatsList.addAll(allTwitterEntityStat.getData());
}
System.out.println(twitterEntityStatsList.size());
}
} catch (TwitterException e) {
System.err.println(e.getErrorMessage());
}
}
}
|
package packageName.boot.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import packageName.domain.ExampleDomain;
import packageName.domain.port.ObtainExample;
import packageName.domain.port.RequestExample;
import packageName.repository.config.JpaAdapterConfig;
@Configuration
@Import(JpaAdapterConfig.class)
public class BootstrapConfig {
@Bean
public RequestExample getRequestExample(ObtainExample obtainExample) {
return new ExampleDomain(obtainExample);
}
}
|
package com.util;
import java.io.*;
import java.util.Iterator;
import java.awt.*;
import java.awt.image.*;
import java.awt.Graphics;
import java.awt.color.ColorSpace;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
public class ImageCut {
/**
* 对图片裁剪,并把裁剪完蛋新图片保存 。
*
* @param srcpath
* 源图片路径
* @param subpath
* 剪切图片存放路径
* @param x
* 剪切点x坐标
* @param y
* 剪切点y坐标
* @param width
* 剪切宽度
* @param height
* 剪切高度
* @throws IOException
*/
public static void abscut(String srcpath, String subpath, int x, int y,
int width, int height) {
FileInputStream is = null;
ImageInputStream iis = null;
try {
// 读取图片文件
is = new FileInputStream(srcpath);
/**//*
* 返回包含所有当前已注册 ImageReader 的 Iterator,这些 ImageReader 声称能够解码指定格式。
* 参数:formatName - 包含非正式格式名称 . (例如 "jpeg" 或 "tiff")等 。
*/
String suffix = srcpath.substring(srcpath.lastIndexOf(".") + 1);
Iterator<ImageReader> it = ImageIO
.getImageReadersByFormatName(suffix);
ImageReader reader = it.next();
// 获取图片流
iis = ImageIO.createImageInputStream(is);
/**//*
* <p>iis:读取源.true:只向前搜索 </p>.将它标记为 ‘只向前搜索’。
* 此设置意味着包含在输入源中的图像将只按顺序读取,可能允许 reader
* 避免缓存包含与以前已经读取的图像关联的数据的那些输入部分。
*/
reader.setInput(iis, true);
/**//*
* <p>描述如何对流进行解码的类<p>.用于指定如何在输入时从 Java Image I/O
* 框架的上下文中的流转换一幅图像或一组图像。用于特定图像格式的插件 将从其 ImageReader 实现的
* getDefaultReadParam 方法中返回 ImageReadParam 的实例。
*/
ImageReadParam param = reader.getDefaultReadParam();
/**//*
* 图片裁剪区域。Rectangle 指定了坐标空间中的一个区域,通过 Rectangle 对象
* 的左上顶点的坐标(x,y)、宽度和高度可以定义这个区域。
*/
Rectangle rect = new Rectangle(x, y, width, height);
// 提供一个 BufferedImage,将其用作解码像素数据的目标。
param.setSourceRegion(rect);
/**//*
* 使用所提供的 ImageReadParam 读取通过索引 imageIndex 指定的对象,并将 它作为一个完整的
* BufferedImage 返回。
*/
BufferedImage bi = reader.read(0, param);
// 保存新图片
ImageIO.write(bi, "jpg", new File(subpath));
} catch (Exception e) {
// TODO: handle exception
}
finally {
try {
if (is != null)
is.close();
if (iis != null)
iis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 缩放图像
*
* @param srcImageFile
* 源图像文件地址
* @param result
* 缩放后的图像地址
* @param scale
* 缩放比例
* @param flag
* 缩放选择:true 放大; false 缩小;
*/
public static void scale(String srcImageFile, String result, int scale,
boolean flag) {
try {
BufferedImage src = ImageIO.read(new File(srcImageFile)); // 读入文件
int width = src.getWidth(); // 得到源图宽
int height = src.getHeight(); // 得到源图长
if (flag) {
// 放大
width = width * scale;
height = height * scale;
} else {
// 缩小
width = width / scale;
height = height / scale;
}
Image image = src.getScaledInstance(width, height,
Image.SCALE_DEFAULT);
BufferedImage tag = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
g.dispose();
ImageIO.write(tag, "JPEG", new File(result));// 输出到文件流
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 重新生成按指定宽度和高度的图像
*
* @param srcImageFile
* 源图像文件地址
* @param result
* 新的图像地址
* @param _width
* 设置新的图像宽度
* @param _height
* 设置新的图像高度
*/
public static void scale(String srcImageFile, String result, int _width,
int _height) {
scale(srcImageFile, result, _width, _height, 0, 0);
}
public static void scale(String srcImageFile, String result, int _width,
int _height, int x, int y) {
try {
BufferedImage src = ImageIO.read(new File(srcImageFile)); // 读入文件
int width = src.getWidth(); // 得到源图宽
int height = src.getHeight(); // 得到源图长
if (width > _width) {
width = _width;
}
if (height > _height) {
height = _height;
}
Image image = src.getScaledInstance(width, height,
Image.SCALE_DEFAULT);
BufferedImage tag = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, x, y, null); // 绘制缩小后的图
g.dispose();
ImageIO.write(tag, "JPEG", new File(result));// 输出到文件流
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 图像类型转换 GIF->JPG GIF->PNG PNG->JPG PNG->GIF(X)
*/
public static void convert(String source, String result) {
try {
File f = new File(source);
f.canRead();
f.canWrite();
BufferedImage src = ImageIO.read(f);
ImageIO.write(src, "JPG", new File(result));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 彩色转为黑白
*
* @param source
* @param result
*/
public static void gray(String source, String result) {
try {
BufferedImage src = ImageIO.read(new File(source));
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
ColorConvertOp op = new ColorConvertOp(cs, null);
src = op.filter(src, null);
ImageIO.write(src, "JPEG", new File(result));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args) {
// 晕。。。搞成多个了...
// cut("c:/images/ipomoea.jpg", "c:/images/t/ipomoea.jpg", 200, 150);
// ok
// gray("c:/images/ipomoea.jpg", "c:/images/t/ipomoea.jpg");
// convert("c:/images/ipomoea.jpg", "c:/images/t/ipomoea.gif");
// scale("c:/images/5105049910001020110718648723.jpg",
// "c:/images/t/5105049910001020110718648725.jpg",154,166,157,208);
// scale("c:/images/rose1.jpg",
// "c:/images/t/rose1.jpg",154,166,157,208);
// scale("c:/images/rose1.jpg", "c:/images/t/rose2.jpg",154,166,10,10);
abscut("C:/Users/Administrator/Desktop/1422424579634.jpeg",
"C:/Users/Administrator/Desktop/1422424579475.jpeg", 100, 100,
100, 100);
}
public static void cutImageByProportion(String srcImageFile,String dirImageFile, float x, float y, float destWidth,
float destHeight){
try {
BufferedImage src = ImageIO.read(new File(srcImageFile)); // 读入文件
float width = src.getWidth(); // 得到源图宽
float height = src.getHeight(); // 得到源图长
int newx=Math.round(x*width);
int newy=Math.round(y*height);
int newdestWidth=Math.round(destWidth*width);
int newdestHeight=Math.round(destHeight*height);
abscut(srcImageFile,dirImageFile,newx,newy,newdestWidth,newdestHeight);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
/*
* 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.camel.processor;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.ValidationException;
import org.apache.camel.spi.CamelInternalProcessorAdvice;
import org.apache.camel.spi.Contract;
import org.apache.camel.spi.DataType;
import org.apache.camel.spi.DataTypeAware;
import org.apache.camel.spi.Transformer;
import org.apache.camel.spi.Validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A {@link CamelInternalProcessorAdvice} which applies {@link Transformer} and {@link Validator}
* according to the data type Contract.
* <p/>
* The default camel {@link Message} implements {@link DataTypeAware} which
* holds a {@link DataType} to indicate current message type. If the input type
* declared by {@link org.apache.camel.model.InputTypeDefinition} is different from current IN message type,
* camel internal processor look for a Transformer which transforms from the current
* message type to the expected message type before routing.
* After routing, if the output type declared by {@link org.apache.camel.model.OutputTypeDefinition} is different
* from current OUT message (or IN message if no OUT), camel look for a Transformer and apply.
*
* @see Transformer
* @see Validator
* @see org.apache.camel.model.InputTypeDefinition
* @see org.apache.camel.model.OutputTypeDefinition
*/
public class ContractAdvice implements CamelInternalProcessorAdvice {
private static final Logger LOG = LoggerFactory.getLogger(ContractAdvice.class);
private Contract contract;
public ContractAdvice(Contract contract) {
this.contract = contract;
}
@Override
public Object before(Exchange exchange) throws Exception {
if (!(exchange.getIn() instanceof DataTypeAware)) {
return null;
}
try {
DataType to = contract.getInputType();
if (to != null) {
DataTypeAware target = (DataTypeAware) exchange.getIn();
DataType from = target.getDataType();
if (!to.equals(from)) {
LOG.debug("Looking for transformer for INPUT: from='{}', to='{}'", from, to);
doTransform(exchange.getIn(), from, to);
target.setDataType(to);
}
if (contract.isValidateInput()) {
doValidate(exchange.getIn(), to);
}
}
} catch (Exception e) {
exchange.setException(e);
}
return null;
}
@Override
public void after(Exchange exchange, Object data) throws Exception {
if (exchange.isFailed()) {
// TODO can we add FAULT_TYPE processing?
return;
}
Message target = exchange.getMessage();
if (!(target instanceof DataTypeAware)) {
return;
}
try {
DataType to = contract.getOutputType();
if (to != null) {
DataTypeAware typeAwareTarget = (DataTypeAware)target;
DataType from = typeAwareTarget.getDataType();
if (!to.equals(from)) {
LOG.debug("Looking for transformer for OUTPUT: from='{}', to='{}'", from, to);
doTransform(target, from, to);
typeAwareTarget.setDataType(to);
}
if (contract.isValidateOutput()) {
doValidate(target, to);
}
}
} catch (Exception e) {
exchange.setException(e);
}
}
@Override
public boolean hasState() {
return false;
}
private void doTransform(Message message, DataType from, DataType to) throws Exception {
if (from == null) {
// If 'from' is null, only Java-Java convertion is performed.
// It means if 'to' is other than Java, it's assumed to be already in expected type.
convertIfRequired(message, to);
return;
}
// transform into 'from' type before performing declared transformation
convertIfRequired(message, from);
if (applyMatchedTransformer(message, from, to)) {
// Found matched transformer. Java-Java transformer is also allowed.
return;
} else if (from.isJavaType()) {
// Try TypeConverter as a fallback for Java->Java transformation
convertIfRequired(message, to);
// If Java->Other transformation required but no transformer matched,
// then assume it's already in expected type, i.e. do nothing.
return;
} else if (applyTransformerChain(message, from, to)) {
// Other->Other transformation - found a transformer chain
return;
}
throw new IllegalArgumentException("No Transformer found for [from='" + from + "', to='" + to + "']");
}
private boolean convertIfRequired(Message message, DataType type) throws Exception {
// TODO for better performance it may be better to add TypeConverterTransformer
// into transformer registry automatically to avoid unnecessary scan in transformer registry
if (type != null && type.isJavaType() && type.getName() != null && message != null && message.getBody() != null) {
CamelContext context = message.getExchange().getContext();
Class<?> typeJava = getClazz(type.getName(), context);
if (!typeJava.isAssignableFrom(message.getBody().getClass())) {
LOG.debug("Converting to '{}'", typeJava.getName());
message.setBody(message.getMandatoryBody(typeJava));
return true;
}
}
return false;
}
private boolean applyTransformer(Transformer transformer, Message message, DataType from, DataType to) throws Exception {
if (transformer != null) {
LOG.debug("Applying transformer: from='{}', to='{}', transformer='{}'", from, to, transformer);
transformer.transform(message, from, to);
return true;
}
return false;
}
private boolean applyMatchedTransformer(Message message, DataType from, DataType to) throws Exception {
Transformer transformer = message.getExchange().getContext().resolveTransformer(from, to);
return applyTransformer(transformer, message, from, to);
}
private boolean applyTransformerChain(Message message, DataType from, DataType to) throws Exception {
CamelContext context = message.getExchange().getContext();
Transformer fromTransformer = context.resolveTransformer(from.getModel());
Transformer toTransformer = context.resolveTransformer(to.getModel());
if (fromTransformer != null && toTransformer != null) {
LOG.debug("Applying transformer 1/2: from='{}', to='{}', transformer='{}'", from, to, fromTransformer);
fromTransformer.transform(message, from, new DataType(Object.class));
LOG.debug("Applying transformer 2/2: from='{}', to='{}', transformer='{}'", from, to, toTransformer);
toTransformer.transform(message, new DataType(Object.class), to);
return true;
}
return false;
}
private Class<?> getClazz(String type, CamelContext context) throws Exception {
return context.getClassResolver().resolveMandatoryClass(type);
}
private void doValidate(Message message, DataType type) throws ValidationException {
Validator validator = message.getExchange().getContext().resolveValidator(type);
if (validator != null) {
LOG.debug("Applying validator: type='{}', validator='{}'", type, validator);
validator.validate(message, type);
} else {
throw new ValidationException(message.getExchange(), String.format("No Validator found for '%s'", type));
}
}
}
|
package org.hkijena.jipipe.extensions.imagejalgorithms.ij1.roi;
import org.hkijena.jipipe.api.JIPipeDocumentation;
import org.hkijena.jipipe.api.JIPipeNode;
import org.hkijena.jipipe.api.JIPipeProgressInfo;
import org.hkijena.jipipe.api.data.JIPipeData;
import org.hkijena.jipipe.api.data.JIPipeDataSlot;
import org.hkijena.jipipe.api.nodes.*;
import org.hkijena.jipipe.api.nodes.categories.DataSourceNodeTypeCategory;
import org.hkijena.jipipe.extensions.imagejdatatypes.datatypes.ROIListData;
@JIPipeDocumentation(name = "Generate missing ROI lists", description = "Generates empty ROI lists for data that are not paired " +
"with a matching ROI in the same data batch. ")
@JIPipeNode(nodeTypeCategory = DataSourceNodeTypeCategory.class)
@JIPipeInputSlot(value = JIPipeData.class, slotName = "Data", autoCreate = true)
@JIPipeInputSlot(value = ROIListData.class, slotName = "ROI", autoCreate = true, optional = true)
@JIPipeOutputSlot(value = ROIListData.class, slotName = "ROI", autoCreate = true)
public class GenerateMissingRoiListsAlgorithm extends JIPipeMissingDataGeneratorAlgorithm {
public GenerateMissingRoiListsAlgorithm(JIPipeNodeInfo info) {
super(info);
}
public GenerateMissingRoiListsAlgorithm(GenerateMissingRoiListsAlgorithm other) {
super(other);
}
@Override
protected void runGenerator(JIPipeMergingDataBatch dataBatch, JIPipeDataSlot inputSlot, JIPipeDataSlot outputSlot, JIPipeProgressInfo progressInfo) {
dataBatch.addOutputData(outputSlot, new ROIListData(), progressInfo);
}
}
|
/**
* 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.zookeeper.server.quorum;
import java.io.IOException;
import java.util.Properties;
import javax.management.JMException;
import javax.security.sasl.SaslException;
import org.apache.yetus.audience.InterfaceAudience;
import org.apache.zookeeper.server.util.JvmPauseMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.zookeeper.jmx.ManagedUtil;
import org.apache.zookeeper.metrics.MetricsProvider;
import org.apache.zookeeper.metrics.MetricsProviderLifeCycleException;
import org.apache.zookeeper.metrics.impl.MetricsProviderBootstrap;
import org.apache.zookeeper.server.ExitCode;
import org.apache.zookeeper.server.ServerCnxnFactory;
import org.apache.zookeeper.server.ZKDatabase;
import org.apache.zookeeper.server.DatadirCleanupManager;
import org.apache.zookeeper.server.ServerMetrics;
import org.apache.zookeeper.server.ZooKeeperServerMain;
import org.apache.zookeeper.server.admin.AdminServer.AdminServerException;
import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.server.persistence.FileTxnSnapLog.DatadirException;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
/**
*
* <h2>Configuration file</h2>
*
* When the main() method of this class is used to start the program, the first
* argument is used as a path to the config file, which will be used to obtain
* configuration information. This file is a Properties file, so keys and
* values are separated by equals (=) and the key/value pairs are separated
* by new lines. The following is a general summary of keys used in the
* configuration file. For full details on this see the documentation in
* docs/index.html
* <ol>
* <li>dataDir - The directory where the ZooKeeper data is stored.</li>
* <li>dataLogDir - The directory where the ZooKeeper transaction log is stored.</li>
* <li>clientPort - The port used to communicate with clients.</li>
* <li>tickTime - The duration of a tick in milliseconds. This is the basic
* unit of time in ZooKeeper.</li>
* <li>initLimit - The maximum number of ticks that a follower will wait to
* initially synchronize with a leader.</li>
* <li>syncLimit - The maximum number of ticks that a follower will wait for a
* message (including heartbeats) from the leader.</li>
* <li>server.<i>id</i> - This is the host:port[:port] that the server with the
* given id will use for the quorum protocol.</li>
* </ol>
* In addition to the config file. There is a file in the data directory called
* "myid" that contains the server id as an ASCII decimal value.
*
*/
@InterfaceAudience.Public
public class QuorumPeerMain {
private static final Logger LOG = LoggerFactory.getLogger(QuorumPeerMain.class);
private static final String USAGE = "Usage: QuorumPeerMain configfile";
protected QuorumPeer quorumPeer;
/**
* To start the replicated server specify the configuration file name on
* the command line.
* @param args path to the configfile
*/
public static void main(String[] args) {
QuorumPeerMain main = new QuorumPeerMain();
try {
main.initializeAndRun(args);
} catch (IllegalArgumentException e) {
LOG.error("Invalid arguments, exiting abnormally", e);
LOG.info(USAGE);
System.err.println(USAGE);
System.exit(ExitCode.INVALID_INVOCATION.getValue());
} catch (ConfigException e) {
LOG.error("Invalid config, exiting abnormally", e);
System.err.println("Invalid config, exiting abnormally");
System.exit(ExitCode.INVALID_INVOCATION.getValue());
} catch (DatadirException e) {
LOG.error("Unable to access datadir, exiting abnormally", e);
System.err.println("Unable to access datadir, exiting abnormally");
System.exit(ExitCode.UNABLE_TO_ACCESS_DATADIR.getValue());
} catch (AdminServerException e) {
LOG.error("Unable to start AdminServer, exiting abnormally", e);
System.err.println("Unable to start AdminServer, exiting abnormally");
System.exit(ExitCode.ERROR_STARTING_ADMIN_SERVER.getValue());
} catch (Exception e) {
LOG.error("Unexpected exception, exiting abnormally", e);
System.exit(ExitCode.UNEXPECTED_ERROR.getValue());
}
LOG.info("Exiting normally");
System.exit(ExitCode.EXECUTION_FINISHED.getValue());
}
protected void initializeAndRun(String[] args)
throws ConfigException, IOException, AdminServerException
{
QuorumPeerConfig config = new QuorumPeerConfig();
if (args.length == 1) {
config.parse(args[0]);
}
// Start and schedule the the purge task
DatadirCleanupManager purgeMgr = new DatadirCleanupManager(config
.getDataDir(), config.getDataLogDir(), config
.getSnapRetainCount(), config.getPurgeInterval());
purgeMgr.start();
if (args.length == 1 && config.isDistributed()) {
runFromConfig(config);
} else {
LOG.warn("Either no config or no quorum defined in config, running "
+ " in standalone mode");
// there is only server in the quorum -- run as standalone
ZooKeeperServerMain.main(args);
}
}
public void runFromConfig(QuorumPeerConfig config)
throws IOException, AdminServerException
{
try {
ManagedUtil.registerLog4jMBeans();
} catch (JMException e) {
LOG.warn("Unable to register log4j JMX control", e);
}
LOG.info("Starting quorum peer");
MetricsProvider metricsProvider;
try {
metricsProvider = MetricsProviderBootstrap
.startMetricsProvider(config.getMetricsProviderClassName(),
config.getMetricsProviderConfiguration());
} catch (MetricsProviderLifeCycleException error) {
throw new IOException("Cannot boot MetricsProvider " + config.getMetricsProviderClassName(),
error);
}
try {
ServerMetrics.metricsProviderInitialized(metricsProvider);
ServerCnxnFactory cnxnFactory = null;
ServerCnxnFactory secureCnxnFactory = null;
if (config.getClientPortAddress() != null) {
cnxnFactory = ServerCnxnFactory.createFactory();
cnxnFactory.configure(config.getClientPortAddress(),
config.getMaxClientCnxns(),
config.getClientPortListenBacklog(), false);
}
if (config.getSecureClientPortAddress() != null) {
secureCnxnFactory = ServerCnxnFactory.createFactory();
secureCnxnFactory.configure(config.getSecureClientPortAddress(),
config.getMaxClientCnxns(),
config.getClientPortListenBacklog(), true);
}
quorumPeer = getQuorumPeer();
quorumPeer.setTxnFactory(new FileTxnSnapLog(
config.getDataLogDir(),
config.getDataDir()));
quorumPeer.enableLocalSessions(config.areLocalSessionsEnabled());
quorumPeer.enableLocalSessionsUpgrading(
config.isLocalSessionsUpgradingEnabled());
//quorumPeer.setQuorumPeers(config.getAllMembers());
quorumPeer.setElectionType(config.getElectionAlg());
quorumPeer.setMyid(config.getServerId());
quorumPeer.setTickTime(config.getTickTime());
quorumPeer.setMinSessionTimeout(config.getMinSessionTimeout());
quorumPeer.setMaxSessionTimeout(config.getMaxSessionTimeout());
quorumPeer.setInitLimit(config.getInitLimit());
quorumPeer.setSyncLimit(config.getSyncLimit());
quorumPeer.setObserverMasterPort(config.getObserverMasterPort());
quorumPeer.setConfigFileName(config.getConfigFilename());
quorumPeer.setClientPortListenBacklog(config.getClientPortListenBacklog());
quorumPeer.setZKDatabase(new ZKDatabase(quorumPeer.getTxnFactory()));
quorumPeer.setQuorumVerifier(config.getQuorumVerifier(), false);
if (config.getLastSeenQuorumVerifier()!=null) {
quorumPeer.setLastSeenQuorumVerifier(config.getLastSeenQuorumVerifier(), false);
}
quorumPeer.initConfigInZKDatabase();
quorumPeer.setCnxnFactory(cnxnFactory);
quorumPeer.setSecureCnxnFactory(secureCnxnFactory);
quorumPeer.setSslQuorum(config.isSslQuorum());
quorumPeer.setUsePortUnification(config.shouldUsePortUnification());
quorumPeer.setLearnerType(config.getPeerType());
quorumPeer.setSyncEnabled(config.getSyncEnabled());
quorumPeer.setQuorumListenOnAllIPs(config.getQuorumListenOnAllIPs());
if (config.sslQuorumReloadCertFiles) {
quorumPeer.getX509Util().enableCertFileReloading();
}
// sets quorum sasl authentication configurations
quorumPeer.setQuorumSaslEnabled(config.quorumEnableSasl);
if(quorumPeer.isQuorumSaslAuthEnabled()){
quorumPeer.setQuorumServerSaslRequired(config.quorumServerRequireSasl);
quorumPeer.setQuorumLearnerSaslRequired(config.quorumLearnerRequireSasl);
quorumPeer.setQuorumServicePrincipal(config.quorumServicePrincipal);
quorumPeer.setQuorumServerLoginContext(config.quorumServerLoginContext);
quorumPeer.setQuorumLearnerLoginContext(config.quorumLearnerLoginContext);
}
quorumPeer.setQuorumCnxnThreadsSize(config.quorumCnxnThreadsSize);
quorumPeer.initialize();
if(config.jvmPauseMonitorToRun) {
quorumPeer.setJvmPauseMonitor(new JvmPauseMonitor(config));
}
quorumPeer.start();
quorumPeer.join();
} catch (InterruptedException e) {
// warn, but generally this is ok
LOG.warn("Quorum Peer interrupted", e);
} finally {
if (metricsProvider != null) {
try {
metricsProvider.stop();
} catch (Throwable error) {
LOG.warn("Error while stopping metrics", error);
}
}
}
}
// @VisibleForTesting
protected QuorumPeer getQuorumPeer() throws SaslException {
return new QuorumPeer();
}
}
|
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2018 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package frc.robot.vision;
import frc.robot.RobotGameState;
import frc.robot.RobotGameStateManager;
import frc.robot.RobotGameState.RobotAction;
/**
* This class holds all the targets in the field and their angles. It serves to
* find a specific target according to estimated angles.
*/
public class TargetBank {
/**
* Contains all the targets and their angles.
*/
public enum AlignmentTarget {
RIGHT_CARGOSHIP(90.0), LEFT_CARGOSHIP(-90.0), LEFT_ROCKET_CARGO(90), RIGHT_ROCKET_CARGO(-90),
CLOSE_LEFT_ROCKET(28.75), FAR_LEFT_ROCKET(151.25), CLOSE_RIGHT_ROCKET(-28.75), FAR_RIGHT_ROCKET(-151.25),
CARGO_SHIP_FRONT(0), FEEDER(180);
private final double absoluteAngle;
AlignmentTarget(double absoluteAngle) {
this.absoluteAngle = absoluteAngle;
}
/**
* @return the angle for the specific target.
*/
public double getAbsoluteAngle() {
return absoluteAngle;
}
}
/**
* @param estimatedAngle the estimated angle from the robot to the target.
* @return the angle of the target that is closest to the estimated angle.
*/
public static AlignmentTarget getAlignmentTarget(double estimatedAngle) {
if (RobotGameStateManager.currentGameState.robotAction == RobotAction.FEEDER_COLLECT) {
return AlignmentTarget.FEEDER;
} else {
switch (RobotGameStateManager.nextGameState.fieldObjective) {
case CARGOSHIP:
if (RobotGameStateManager.nextGameState.cargoShipFace == RobotGameState.CargoShipFace.FRONT) {
return AlignmentTarget.CARGO_SHIP_FRONT;
} else {
if (estimatedAngle > 0) {
return AlignmentTarget.RIGHT_CARGOSHIP;
} else {
return AlignmentTarget.LEFT_CARGOSHIP;
}
}
case ROCKET:
default:
if (RobotGameStateManager.nextGameState.gamePiece == RobotGameState.GamePiece.CARGO) { // Cargo Game Piece
if (estimatedAngle > 0) {
return AlignmentTarget.LEFT_ROCKET_CARGO;
} else {
return AlignmentTarget.RIGHT_ROCKET_CARGO;
}
} else { // Hatch Panel Game Piece
if (RobotGameStateManager.nextGameState.rocketSide == RobotGameState.RocketSide.RIGHT) { // Right
// Rocket
if (estimatedAngle > -90 && estimatedAngle < 90) {
return AlignmentTarget.CLOSE_RIGHT_ROCKET;
} else {
return AlignmentTarget.FAR_RIGHT_ROCKET;
}
} else { // Left Rocket
if (estimatedAngle > -90 && estimatedAngle < 90) {
return AlignmentTarget.CLOSE_LEFT_ROCKET;
} else {
return AlignmentTarget.FAR_LEFT_ROCKET;
}
}
}
}
}
}
}
|
package org.squiddev.plethora.api;
import dan200.computercraft.api.peripheral.IPeripheral;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import org.squiddev.plethora.api.method.ICostHandler;
import org.squiddev.plethora.api.module.IModuleHandler;
import org.squiddev.plethora.api.vehicle.IVehicleUpgradeHandler;
import java.util.UUID;
/**
* Various constants for working with Plethora
*/
public final class Constants {
/**
* IMC command for blacklisting a tile entity or package (must have a trailing '.').
*
* Blacklisted tile entities will not be wrapped as peripherals. This should be done before the postInit stage.
*
* Parameters: class name or package prefix.
*/
public static final String IMC_BLACKLIST_PERIPHERAL = "blacklistPeripheral";
/**
* IMC command for blacklisting specific mod integration.
*
* This should be done before the postInit stage.
*
* Parameters: Mod or API ID.
*/
public static final String IMC_BLACKLIST_MOD = "blacklistMod";
/**
* UUID for Plethora's fake player
*/
public static final UUID FAKEPLAYER_UUID = UUID.fromString("ebcda071-3ef5-4f4a-849d-c078264010c4");
/**
* Capability for cost handlers.
*
* Provide this capability for custom cost handling.
*
* @see org.squiddev.plethora.api.method.IMethodRegistry#getCostHandler(ICapabilityProvider, net.minecraft.util.EnumFacing)
* @see ICostHandler
*/
@CapabilityInject(ICostHandler.class)
public static Capability<ICostHandler> COST_HANDLER_CAPABILITY = null;
/**
* Capability for modules.
*
* Provide this capability for an item to be a module
*
* @see IModuleHandler
*/
@CapabilityInject(IModuleHandler.class)
public static Capability<IModuleHandler> MODULE_HANDLER_CAPABILITY = null;
/**
* Capability for peripherals.
*
* Provide this capability for an object to be a peripheral. We register a peripheral provider which checks
* for this capability.
*
* @see IPeripheral
*/
@CapabilityInject(IPeripheral.class)
public static Capability<IPeripheral> PERIPHERAL_CAPABILITY = null;
/**
* Capability for peripheral handlers.
*
* Provide this capability for an object to be a peripheral with additional handling.
* We do not register a peripheral provider, nor do we automatically convert {@link IPeripheral}s
* to {@link IPeripheralHandler}s: you should provide both.
*
* @see IPeripheralHandler
*/
@CapabilityInject(IPeripheralHandler.class)
public static Capability<IPeripheralHandler> PERIPHERAL_HANDLER_CAPABILITY = null;
/**
* Capability for vehicle upgrades;
*
* Provide this capability for an ItemStack to be an upgrade for a vehicle computer.
*
* @see IVehicleUpgradeHandler
*/
@CapabilityInject(IVehicleUpgradeHandler.class)
public static Capability<IVehicleUpgradeHandler> VEHICLE_UPGRADE_HANDLER_CAPABILITY = null;
private Constants() {
}
}
|
/**
* Copyright (c) 2016-present, RxJava Contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License.
*/
package io.reactivex.rxjava3.internal.operators.observable;
import java.util.ArrayDeque;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import io.reactivex.rxjava3.core.*;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.exceptions.Exceptions;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.internal.disposables.DisposableHelper;
import io.reactivex.rxjava3.internal.fuseable.*;
import io.reactivex.rxjava3.internal.observers.*;
import io.reactivex.rxjava3.internal.queue.SpscLinkedArrayQueue;
import io.reactivex.rxjava3.internal.util.*;
public final class ObservableConcatMapEager<T, R> extends AbstractObservableWithUpstream<T, R> {
final Function<? super T, ? extends ObservableSource<? extends R>> mapper;
final ErrorMode errorMode;
final int maxConcurrency;
final int prefetch;
public ObservableConcatMapEager(ObservableSource<T> source,
Function<? super T, ? extends ObservableSource<? extends R>> mapper,
ErrorMode errorMode,
int maxConcurrency, int prefetch) {
super(source);
this.mapper = mapper;
this.errorMode = errorMode;
this.maxConcurrency = maxConcurrency;
this.prefetch = prefetch;
}
@Override
protected void subscribeActual(Observer<? super R> observer) {
source.subscribe(new ConcatMapEagerMainObserver<>(observer, mapper, maxConcurrency, prefetch, errorMode));
}
static final class ConcatMapEagerMainObserver<T, R>
extends AtomicInteger
implements Observer<T>, Disposable, InnerQueuedObserverSupport<R> {
private static final long serialVersionUID = 8080567949447303262L;
final Observer<? super R> downstream;
final Function<? super T, ? extends ObservableSource<? extends R>> mapper;
final int maxConcurrency;
final int prefetch;
final ErrorMode errorMode;
final AtomicThrowable errors;
final ArrayDeque<InnerQueuedObserver<R>> observers;
SimpleQueue<T> queue;
Disposable upstream;
volatile boolean done;
int sourceMode;
volatile boolean cancelled;
InnerQueuedObserver<R> current;
int activeCount;
ConcatMapEagerMainObserver(Observer<? super R> actual,
Function<? super T, ? extends ObservableSource<? extends R>> mapper,
int maxConcurrency, int prefetch, ErrorMode errorMode) {
this.downstream = actual;
this.mapper = mapper;
this.maxConcurrency = maxConcurrency;
this.prefetch = prefetch;
this.errorMode = errorMode;
this.errors = new AtomicThrowable();
this.observers = new ArrayDeque<>();
}
@SuppressWarnings("unchecked")
@Override
public void onSubscribe(Disposable d) {
if (DisposableHelper.validate(this.upstream, d)) {
this.upstream = d;
if (d instanceof QueueDisposable) {
QueueDisposable<T> qd = (QueueDisposable<T>) d;
int m = qd.requestFusion(QueueDisposable.ANY);
if (m == QueueDisposable.SYNC) {
sourceMode = m;
queue = qd;
done = true;
downstream.onSubscribe(this);
drain();
return;
}
if (m == QueueDisposable.ASYNC) {
sourceMode = m;
queue = qd;
downstream.onSubscribe(this);
return;
}
}
queue = new SpscLinkedArrayQueue<>(prefetch);
downstream.onSubscribe(this);
}
}
@Override
public void onNext(T value) {
if (sourceMode == QueueDisposable.NONE) {
queue.offer(value);
}
drain();
}
@Override
public void onError(Throwable e) {
if (errors.tryAddThrowableOrReport(e)) {
done = true;
drain();
}
}
@Override
public void onComplete() {
done = true;
drain();
}
@Override
public void dispose() {
if (cancelled) {
return;
}
cancelled = true;
upstream.dispose();
errors.tryTerminateAndReport();
drainAndDispose();
}
void drainAndDispose() {
if (getAndIncrement() == 0) {
do {
queue.clear();
disposeAll();
} while (decrementAndGet() != 0);
}
}
@Override
public boolean isDisposed() {
return cancelled;
}
void disposeAll() {
InnerQueuedObserver<R> inner = current;
if (inner != null) {
inner.dispose();
}
for (;;) {
inner = observers.poll();
if (inner == null) {
return;
}
inner.dispose();
}
}
@Override
public void innerNext(InnerQueuedObserver<R> inner, R value) {
inner.queue().offer(value);
drain();
}
@Override
public void innerError(InnerQueuedObserver<R> inner, Throwable e) {
if (errors.tryAddThrowableOrReport(e)) {
if (errorMode == ErrorMode.IMMEDIATE) {
upstream.dispose();
}
inner.setDone();
drain();
}
}
@Override
public void innerComplete(InnerQueuedObserver<R> inner) {
inner.setDone();
drain();
}
@Override
public void drain() {
if (getAndIncrement() != 0) {
return;
}
int missed = 1;
SimpleQueue<T> q = queue;
ArrayDeque<InnerQueuedObserver<R>> observers = this.observers;
Observer<? super R> a = this.downstream;
ErrorMode errorMode = this.errorMode;
outer:
for (;;) {
int ac = activeCount;
while (ac != maxConcurrency) {
if (cancelled) {
q.clear();
disposeAll();
return;
}
if (errorMode == ErrorMode.IMMEDIATE) {
Throwable ex = errors.get();
if (ex != null) {
q.clear();
disposeAll();
errors.tryTerminateConsumer(downstream);
return;
}
}
T v;
ObservableSource<? extends R> source;
try {
v = q.poll();
if (v == null) {
break;
}
source = Objects.requireNonNull(mapper.apply(v), "The mapper returned a null ObservableSource");
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
upstream.dispose();
q.clear();
disposeAll();
errors.tryAddThrowableOrReport(ex);
errors.tryTerminateConsumer(downstream);
return;
}
InnerQueuedObserver<R> inner = new InnerQueuedObserver<>(this, prefetch);
observers.offer(inner);
source.subscribe(inner);
ac++;
}
activeCount = ac;
if (cancelled) {
q.clear();
disposeAll();
return;
}
if (errorMode == ErrorMode.IMMEDIATE) {
Throwable ex = errors.get();
if (ex != null) {
q.clear();
disposeAll();
errors.tryTerminateConsumer(downstream);
return;
}
}
InnerQueuedObserver<R> active = current;
if (active == null) {
if (errorMode == ErrorMode.BOUNDARY) {
Throwable ex = errors.get();
if (ex != null) {
q.clear();
disposeAll();
errors.tryTerminateConsumer(a);
return;
}
}
boolean d = done;
active = observers.poll();
boolean empty = active == null;
if (d && empty) {
Throwable ex = errors.get();
if (ex != null) {
q.clear();
disposeAll();
errors.tryTerminateConsumer(a);
} else {
a.onComplete();
}
return;
}
if (!empty) {
current = active;
}
}
if (active != null) {
SimpleQueue<R> aq = active.queue();
for (;;) {
if (cancelled) {
q.clear();
disposeAll();
return;
}
boolean d = active.isDone();
if (errorMode == ErrorMode.IMMEDIATE) {
Throwable ex = errors.get();
if (ex != null) {
q.clear();
disposeAll();
errors.tryTerminateConsumer(a);
return;
}
}
R w;
try {
w = aq.poll();
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
errors.tryAddThrowableOrReport(ex);
current = null;
activeCount--;
continue outer;
}
boolean empty = w == null;
if (d && empty) {
current = null;
activeCount--;
continue outer;
}
if (empty) {
break;
}
a.onNext(w);
}
}
missed = addAndGet(-missed);
if (missed == 0) {
break;
}
}
}
}
}
|
package cn.van.mybatis.pagination;
import cn.van.mybatis.pagination.entity.UserInfoDO;
import cn.van.mybatis.pagination.page.MybatisPageInterceptor;
import cn.van.mybatis.pagination.mapper.UserMapper;
import cn.van.mybatis.pagination.page.PageResult;
//import com.github.pagehelper.PageHelper;
//import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import java.util.List;
/**
* Copyright (C), 2015-2020, 风尘博客
* 公众号 : 风尘博客
* FileName: MybatisPaginationTest
*
* @author: Van
* Date: 2019-06-24 16:15
* Description: 分页测试
* Version: V1.0
*/
@SpringBootTest
@RunWith(SpringRunner.class)
@Slf4j
public class MybatisPaginationTest {
@Resource
private UserMapper userMapper;
/**
* PageHelper 分页
*/
// @Test
// public void pagehelperTest() {
// // 普通查询
// List<UserInfoDO> list = userMapper.findAll();
// log.info("list:{}", list);
//
// // PageHelper 插件分页查询
// // 第几页
// int currentPage = 1;
// // 每页数量
// int pageSize = 4;
// // 排序
// String orderBy = "id desc";
// PageHelper.startPage(currentPage, pageSize, orderBy);
// List<UserInfoDO> users = userMapper.findAll();
// PageInfo<UserInfoDO> pageInfo = new PageInfo<>(users);
// log.info("pageInfo:{}", pageInfo);
// }
/**
* 拦截器分页
*/
@Test
public void interceptorTest() {
// 普通查询
List<UserInfoDO> list = userMapper.findAll();
log.info("list:{}", list);
// PageHelper 插件分页查询
// 第几页
int currentPage = 1;
// 每页数量
int pageSize = 4;
// 该查询进行分页,指定第几页和每页数量
MybatisPageInterceptor.startPage(currentPage, pageSize);
List<UserInfoDO> all = userMapper.findAll();
PageResult<UserInfoDO> result = new PageResult<>(all);
log.info("result:{}", result);
}
}
|
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* 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.intellij.psi.impl.smartPointers;
import com.intellij.lang.LanguageUtil;
import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.*;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.impl.FreeThreadedFileViewProvider;
import com.intellij.psi.impl.PsiDocumentManagerBase;
import com.intellij.psi.impl.PsiManagerEx;
import com.intellij.psi.impl.source.PsiFileImpl;
import com.intellij.psi.impl.source.tree.ForeignLeafPsiElement;
import com.intellij.psi.tree.IStubFileElementType;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
public class SmartPsiElementPointerImpl<E extends PsiElement> implements SmartPointerEx<E> {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.smartPointers.SmartPsiElementPointerImpl");
private Reference<E> myElement;
private final SmartPointerElementInfo myElementInfo;
private byte myReferenceCount = 1;
@Nullable SmartPointerTracker.PointerReference pointerReference;
SmartPsiElementPointerImpl(@NotNull Project project, @NotNull E element, @Nullable PsiFile containingFile, boolean forInjected) {
this(element, createElementInfo(project, element, containingFile, forInjected));
}
SmartPsiElementPointerImpl(@NotNull E element,
@NotNull SmartPointerElementInfo elementInfo) {
ApplicationManager.getApplication().assertReadAccessAllowed();
myElementInfo = elementInfo;
cacheElement(element);
}
@Override
public boolean equals(Object obj) {
return obj instanceof SmartPsiElementPointer && pointsToTheSameElementAs(this, (SmartPsiElementPointer)obj);
}
@Override
public int hashCode() {
return myElementInfo.elementHashCode();
}
@Override
@NotNull
public Project getProject() {
return myElementInfo.getProject();
}
@Override
@Nullable
public E getElement() {
E element = getCachedElement();
if (element == null || !element.isValid()) {
element = doRestoreElement();
cacheElement(element);
}
return element;
}
@Nullable
E doRestoreElement() {
//noinspection unchecked
E element = (E)myElementInfo.restoreElement();
if (element != null && !element.isValid()) {
return null;
}
return element;
}
void cacheElement(@Nullable E element) {
myElement = element == null ? null :
PsiManagerEx.getInstanceEx(getProject()).isBatchFilesProcessingMode() ? new WeakReference<>(element) :
new SoftReference<>(element);
}
@Override
public E getCachedElement() {
return com.intellij.reference.SoftReference.dereference(myElement);
}
@Override
public PsiFile getContainingFile() {
PsiFile file = getElementInfo().restoreFile();
if (file != null) {
return file;
}
final Document doc = myElementInfo.getDocumentToSynchronize();
if (doc == null) {
final E resolved = getElement();
return resolved == null ? null : resolved.getContainingFile();
}
return PsiDocumentManager.getInstance(getProject()).getPsiFile(doc);
}
@Override
public VirtualFile getVirtualFile() {
return myElementInfo.getVirtualFile();
}
@Override
public Segment getRange() {
return myElementInfo.getRange();
}
@Nullable
@Override
public Segment getPsiRange() {
return myElementInfo.getPsiRange();
}
@NotNull
private static <E extends PsiElement> SmartPointerElementInfo createElementInfo(@NotNull Project project,
@NotNull E element,
PsiFile containingFile, boolean forInjected) {
SmartPointerElementInfo elementInfo = doCreateElementInfo(project, element, containingFile, forInjected);
if (ApplicationManager.getApplication().isUnitTestMode()) {
PsiElement restored = elementInfo.restoreElement();
if (!element.equals(restored)) {
// likely cause: PSI having isPhysical==true, but which can't be restored by containing file and range. To fix, make isPhysical return false
LOG.error("Cannot restore " + element + " of " + element.getClass() + " from " + elementInfo + "; restored=" + restored + " in " + element.getProject());
}
}
return elementInfo;
}
@NotNull
private static <E extends PsiElement> SmartPointerElementInfo doCreateElementInfo(@NotNull Project project,
@NotNull E element,
PsiFile containingFile, boolean forInjected) {
if (element instanceof PsiDirectory) {
return new DirElementInfo((PsiDirectory)element);
}
if (element instanceof PsiCompiledElement || containingFile == null || !containingFile.isPhysical() || !element.isPhysical()) {
if (element instanceof StubBasedPsiElement && element instanceof PsiCompiledElement) {
if (element instanceof PsiFile) {
return new FileElementInfo((PsiFile)element);
}
PsiAnchor.StubIndexReference stubReference = PsiAnchor.createStubReference(element, containingFile);
if (stubReference != null) {
return new ClsElementInfo(stubReference);
}
}
return new HardElementInfo(project, element);
}
FileViewProvider viewProvider = containingFile.getViewProvider();
if (viewProvider instanceof FreeThreadedFileViewProvider) {
PsiLanguageInjectionHost hostContext = InjectedLanguageManager.getInstance(containingFile.getProject()).getInjectionHost(containingFile);
TextRange elementRange = element.getTextRange();
if (hostContext != null && elementRange != null) {
SmartPsiElementPointer<PsiLanguageInjectionHost> hostPointer = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(hostContext);
return new InjectedSelfElementInfo(project, element, elementRange, containingFile, hostPointer);
}
}
if (element instanceof PsiFile) {
return new FileElementInfo((PsiFile)element);
}
Document document = FileDocumentManager.getInstance().getCachedDocument(viewProvider.getVirtualFile());
if (document != null &&
((PsiDocumentManagerBase)PsiDocumentManager.getInstance(project)).getSynchronizer().isDocumentAffectedByTransactions(document)) {
LOG.error("Smart pointers shouldn't be created during PSI changes");
}
SmartPointerElementInfo info = createAnchorInfo(element, containingFile);
if (info != null) {
return info;
}
TextRange elementRange = element.getTextRange();
if (elementRange == null) {
return new HardElementInfo(project, element);
}
if (elementRange.isEmpty() && PsiTreeUtil.findChildOfType(element, ForeignLeafPsiElement.class) != null) {
// PSI built on C-style macro expansions. It has empty ranges, no text, but complicated structure. It can't be reliably
// restored by just one offset in a file, so hold it on a hard reference
return new HardElementInfo(project, element);
}
ProperTextRange proper = ProperTextRange.create(elementRange);
return new SelfElementInfo(project, proper, Identikit.fromPsi(element, LanguageUtil.getRootLanguage(element)), containingFile, forInjected);
}
@Nullable
private static SmartPointerElementInfo createAnchorInfo(@NotNull PsiElement element, @NotNull PsiFile containingFile) {
if (element instanceof StubBasedPsiElement && containingFile instanceof PsiFileImpl) {
IStubFileElementType stubType = ((PsiFileImpl)containingFile).getElementTypeForStubBuilder();
if (stubType != null && stubType.shouldBuildStubFor(containingFile.getViewProvider().getVirtualFile())) {
StubBasedPsiElement stubPsi = (StubBasedPsiElement)element;
int stubId = PsiAnchor.calcStubIndex(stubPsi);
if (stubId != -1) {
return new AnchorElementInfo(element, (PsiFileImpl)containingFile, stubId, stubPsi.getElementType());
}
}
}
Pair<Identikit.ByAnchor, PsiElement> pair = Identikit.withAnchor(element, LanguageUtil.getRootLanguage(containingFile));
if (pair != null) {
return new AnchorElementInfo(pair.second, containingFile, pair.first);
}
return null;
}
@NotNull
SmartPointerElementInfo getElementInfo() {
return myElementInfo;
}
static boolean pointsToTheSameElementAs(@NotNull SmartPsiElementPointer pointer1, @NotNull SmartPsiElementPointer pointer2) {
if (pointer1 == pointer2) return true;
if (pointer1 instanceof SmartPsiElementPointerImpl && pointer2 instanceof SmartPsiElementPointerImpl) {
SmartPsiElementPointerImpl impl1 = (SmartPsiElementPointerImpl)pointer1;
SmartPsiElementPointerImpl impl2 = (SmartPsiElementPointerImpl)pointer2;
SmartPointerElementInfo elementInfo1 = impl1.getElementInfo();
SmartPointerElementInfo elementInfo2 = impl2.getElementInfo();
if (!elementInfo1.pointsToTheSameElementAs(elementInfo2)) return false;
PsiElement cachedElement1 = impl1.getCachedElement();
PsiElement cachedElement2 = impl2.getCachedElement();
return cachedElement1 == null || cachedElement2 == null || Comparing.equal(cachedElement1, cachedElement2);
}
return Comparing.equal(pointer1.getElement(), pointer2.getElement());
}
public synchronized int incrementAndGetReferenceCount(int delta) {
if (myReferenceCount == Byte.MAX_VALUE) return Byte.MAX_VALUE; // saturated
if (myReferenceCount == 0) return -1; // disposed, not to be reused again
return myReferenceCount += delta;
}
@Override
public String toString() {
return myElementInfo.toString();
}
}
|
/*
* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.ui;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.ui.deployment.beans.BreadCrumbItem;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Locale;
public class BreadCrumbGenerator {
private static Log log = LogFactory.getLog(BreadCrumbGenerator.class);
/**
* Generates breadcrumb html content.
* Please do not add line breaks to places where HTML content is written.
* It makes debugging difficult.
* @param request
* @param currentPageHeader
* @return String
*/
public HashMap<String,String> getBreadCrumbContent(HttpServletRequest request
,BreadCrumbItem currentBreadcrumbItem
,String jspFilePath
,boolean topPage
,boolean removeLastItem){
String breadcrumbCookieString = "";
//int lastIndexofSlash = jspFilePath.lastIndexOf(System.getProperty("file.separator"));
//int lastIndexofSlash = jspFilePath.lastIndexOf('/');
StringBuffer content = new StringBuffer();
StringBuffer cookieContent = new StringBuffer();
HashMap<String,String> breadcrumbContents = new HashMap<String,String>();
HashMap<String, BreadCrumbItem> breadcrumbs =
(HashMap<String, BreadCrumbItem>) request.getSession().getAttribute("breadcrumbs");
String menuId = request.getParameter("item");
String region = request.getParameter("region");
String ordinalStr = request.getParameter("ordinal");
if(topPage){
//some wizards redirect to index page of the component after doing some operations.
//Hence a map of region & menuId for component/index page is maintained & retrieved
//by passing index page (eg: ../service-mgt/index.jsp)
//This logic should run only for pages marked as toppage=true
if(menuId == null && region == null){
HashMap<String, String> indexPageBreadcrumbParamMap =
(HashMap<String, String>) request.getSession().getAttribute("index-page-breadcrumb-param-map");
//eg: indexPageBreadcrumbParamMap contains ../service-mgt/index.jsp : region1,services_list_menu pattern
if(indexPageBreadcrumbParamMap != null && !(indexPageBreadcrumbParamMap.isEmpty())){
String params = indexPageBreadcrumbParamMap.get(jspFilePath);
if(params != null){
region = params.substring(0, params.indexOf(','));
menuId = params.substring(params.indexOf(',')+1);
}
}
}
}
if (menuId != null && region != null) {
String key = region.trim() + "-" + menuId.trim();
HashMap<String, String> breadcrumbMap =
(HashMap<String, String>) request.getSession().getAttribute(region + "menu-id-breadcrumb-map");
String breadCrumb = "";
if (breadcrumbMap != null && !(breadcrumbMap.isEmpty())) {
breadCrumb = breadcrumbMap.get(key);
}
if (breadCrumb != null) {
content.append("<table cellspacing=\"0\"><tr>");
Locale locale = CarbonUIUtil.getLocaleFromSession(request);
String homeText = CarbonUIUtil.geti18nString("component.home", "org.wso2.carbon.i18n.Resources", locale);
content.append("<td class=\"breadcrumb-link\"><a href=\"" + CarbonUIUtil.getHomePage() + "\">"+homeText+"</a></td>");
cookieContent.append(breadCrumb);
cookieContent.append("#");
generateBreadcrumbForMenuPath(content, breadcrumbs, breadCrumb,true);
}
}else{
HashMap<String,List<BreadCrumbItem>> links = (HashMap<String,List<BreadCrumbItem>>) request
.getSession().getAttribute("page-breadcrumbs");
//call came within a page. Retrieve the breadcrumb cookie
Cookie[] cookies = request.getCookies();
for (int a = 0; a < cookies.length; a++) {
Cookie cookie = cookies[a];
if("current-breadcrumb".equals(cookie.getName())){
breadcrumbCookieString = cookie.getValue();
//bringing back the ,
breadcrumbCookieString = breadcrumbCookieString.replace("%2C", ",");
//bringing back the #
breadcrumbCookieString = breadcrumbCookieString.replace("%23", "#");
if(log.isDebugEnabled()){
log.debug("cookie :"+cookie.getName()+" : "+breadcrumbCookieString);
}
}
}
if(links != null){
if(log.isDebugEnabled()){
log.debug("size of page-breadcrumbs is : "+links.size());
}
content.append("<table cellspacing=\"0\"><tr>");
Locale locale = CarbonUIUtil.getLocaleFromSession(request);
String homeText = CarbonUIUtil.geti18nString("component.home", "org.wso2.carbon.i18n.Resources", locale);
content.append("<td class=\"breadcrumb-link\"><a href=\"" + CarbonUIUtil.getHomePage() + "\">"+homeText+"</a></td>");
String menuBreadcrumbs = "";
if(breadcrumbCookieString.indexOf('#') > -1){
menuBreadcrumbs = breadcrumbCookieString.substring(0, breadcrumbCookieString.indexOf('#'));
}
cookieContent.append(menuBreadcrumbs);
cookieContent.append("#");
generateBreadcrumbForMenuPath(content, breadcrumbs,
menuBreadcrumbs,false);
int clickedBreadcrumbLocation = 0;
if (ordinalStr != null) {
//only clicking on already made page breadcrumb link will send this via request parameter
try {
clickedBreadcrumbLocation = Integer.parseInt(ordinalStr);
} catch (NumberFormatException e) {
// Do nothing
log.warn("Found String for breadcrumb ordinal");
}
}
String pageBreadcrumbs = "";
if(breadcrumbCookieString.indexOf('#') > -1){
pageBreadcrumbs = breadcrumbCookieString.substring(breadcrumbCookieString.indexOf('#')+1);
}
StringTokenizer st2 = new StringTokenizer(pageBreadcrumbs,"*");
String[] tokens = new String[st2.countTokens()];
int count = 0;
String previousToken = "";
while(st2.hasMoreTokens()){
String currentToken = st2.nextToken();
//To avoid page refresh create breadcrumbs
if(! currentToken.equals(previousToken)){
previousToken = currentToken;
tokens[count] = currentToken;
count++;
}
}
//jspSubContext should be the same across all the breadcrumbs
//(cookie is updated everytime a page is loaded)
List<BreadCrumbItem> breadcrumbItems = null;
// if(tokens != null && tokens.length > 0){
//String token = tokens[0];
//String jspSubContext = token.substring(0, token.indexOf('+'));
//breadcrumbItems = links.get("../"+jspSubContext);
// }
LinkedList<String> tokenJSPFileOrder = new LinkedList<String>();
LinkedList<String> jspFileSubContextOrder = new LinkedList<String>();
HashMap<String,String> jspFileSubContextMap = new HashMap<String,String>();
for(int a = 0;a < tokens.length;a++){
String token = tokens[a];
if(token != null){
String jspFileName = token.substring(token.indexOf('+')+1);
String jspSubContext = token.substring(0, token.indexOf('+'));
jspFileSubContextMap.put(jspFileName, jspSubContext);
tokenJSPFileOrder.add(jspFileName);
jspFileSubContextOrder.add(jspSubContext+"^"+jspFileName);
}
}
if(clickedBreadcrumbLocation > 0){
int tokenCount = tokenJSPFileOrder.size();
while (tokenCount > clickedBreadcrumbLocation) {
String lastItem = tokenJSPFileOrder.getLast();
if(log.isDebugEnabled()){
log.debug("Removing breacrumbItem : "+ lastItem);
}
tokenJSPFileOrder.removeLast();
jspFileSubContextOrder.removeLast();
tokenCount = tokenJSPFileOrder.size();
}
}
boolean lastBreadcrumbItemAvailable = false;
if(clickedBreadcrumbLocation == 0){
String tmp = getSubContextFromUri(currentBreadcrumbItem.getLink())+"+"+currentBreadcrumbItem.getId();
if(! previousToken.equals(tmp)){ //To prevent page refresh
lastBreadcrumbItemAvailable = true;
}
}
if(tokenJSPFileOrder != null){
//found breadcrumb items for given sub context
for(int i = 0;i < jspFileSubContextOrder.size(); i++){
String token = tokenJSPFileOrder.get(i);
//String jspFileName = token.substring(token.indexOf('+')+1);
//String jspSubContext = jspFileSubContextMap.get(jspFileName);
String fileContextToken = jspFileSubContextOrder.get(i);
String jspFileName = fileContextToken.substring(fileContextToken.indexOf('^')+1);
String jspSubContext = fileContextToken.substring(0,fileContextToken.indexOf('^'));
if(jspSubContext != null){
breadcrumbItems = links.get("../"+jspSubContext);
}
if(breadcrumbItems != null){
int bcSize = breadcrumbItems.size();
for (int a = 0; a < bcSize ; a++) {
BreadCrumbItem tmp = breadcrumbItems.get(a);
if(tmp.getId().equals(jspFileName)){
if(tmp.getLink().startsWith("#")){
content.append("<td class=\"breadcrumb-link\"> > "+tmp.getConvertedText()+"</td>");
}else{
//if((a+1) == bcSize){
//if((a+1) == bcSize && clickedBreadcrumbLocation > 0){
if((((a+1) == bcSize) && !(lastBreadcrumbItemAvailable))
|| removeLastItem){
content.append("<td class=\"breadcrumb-link\"> > "+tmp.getConvertedText()+"</td>");
}else{
content.append("<td class=\"breadcrumb-link\"> > <a href=\""+appendOrdinal(tmp.getLink(),i+1)+"\">"+tmp.getConvertedText()+"</a></td>");
}
}
cookieContent.append(getSubContextFromUri(tmp.getLink())+"+"+token+"*");
}
}
}
}
}
//add last breadcrumb item
if(lastBreadcrumbItemAvailable && !(removeLastItem)){
String tmp = getSubContextFromUri(currentBreadcrumbItem.getLink())+"+"+currentBreadcrumbItem.getId();
cookieContent.append(tmp);
cookieContent.append("*");
content.append("<td class=\"breadcrumb-link\"> > "+currentBreadcrumbItem.getConvertedText()+"</td>");
}
content.append("</tr></table>");
}
}
breadcrumbContents.put("html-content", content.toString());
String finalCookieContent = cookieContent.toString();
if(removeLastItem && breadcrumbCookieString != null &&
breadcrumbCookieString.trim().length() > 0){
finalCookieContent = breadcrumbCookieString;
}
breadcrumbContents.put("cookie-content", finalCookieContent);
return breadcrumbContents;
}
/**
*
* @param uri
* @return
*/
private static String getSubContextFromUri(String uri){
//eg: uri = ../service-mgt/service_info.jsp?serviceName=HelloService&ordinal=1
if(uri != null){
int jspExtensionLocation = uri.indexOf(".jsp");
String tmp = uri.substring(0, jspExtensionLocation);
tmp = tmp.replace("../", "");
int firstSlashLocation = tmp.indexOf('/');
return tmp.substring(0, firstSlashLocation);
}else{
return "";
}
}
/**
*
* @param url
* @param ordinal
* @return
*/
private static String appendOrdinal(String url, int ordinal) {
if(url != null){
if (url.indexOf('?') > -1) {
return url + "&ordinal=" + ordinal;
} else {
return url + "?ordinal=" + ordinal;
}
}else{
return "#";
}
}
/**
* Generates breadcrumb for menu navigation path
* @param content
* @param breadcrumbs
* @param breadCrumb
*/
private void generateBreadcrumbForMenuPath(StringBuffer content,
HashMap<String, BreadCrumbItem> breadcrumbs, String breadCrumb,boolean clickFromMenu) {
StringTokenizer st = new StringTokenizer(breadCrumb, ",");
int tokenCount = st.countTokens();
int count = 0;
while (st.hasMoreTokens()) {
count++;
String token = st.nextToken();
BreadCrumbItem breadcrumbItem = (BreadCrumbItem) breadcrumbs.get(token);
if (breadcrumbItem != null) {
//if (count == tokenCount) {
// content.append("<td class=\"breadcrumb-current-page\"><a href=\""+breadcrumbItem.getLink()+"\">"+breadcrumbItem.getConvertedText()+"</a></td>");
//} else {
if (breadcrumbItem.getLink().startsWith("#")) {
content.append("<td class=\"breadcrumb-link\">"+" > "+breadcrumbItem.getConvertedText()+"</td>");
} else {
if(count == tokenCount && (clickFromMenu)){//if last breadcrumb item, do not put the link
content.append("<td class=\"breadcrumb-link\"> > "+breadcrumbItem.getConvertedText()+"</td>");
}else{
content.append("<td class=\"breadcrumb-link\"> > <a href=\""+breadcrumbItem.getLink()+"\">"+breadcrumbItem.getConvertedText()+"</a></td>");
}
}
//}
}
}
}
}
|
package com.github.manevolent.ts3j.util;
import Punisher.NaCl.Internal.Ed25519Ref10.GroupElementP2;
import Punisher.NaCl.Internal.Ed25519Ref10.GroupElementP3;
import Punisher.NaCl.Internal.Ed25519Ref10.GroupOperations;
import Punisher.NaCl.Internal.Ed25519Ref10.ScalarOperations;
import Punisher.NaCl.Internal.Sha512;
import com.github.manevolent.ts3j.identity.*;
import com.github.manevolent.ts3j.license.License;
import org.bouncycastle.asn1.*;
import org.bouncycastle.crypto.KeyGenerationParameters;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.signers.DSADigestSigner;
import org.bouncycastle.crypto.signers.ECDSASigner;
import org.bouncycastle.jce.ECNamedCurveTable;
import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec;
import org.bouncycastle.math.ec.ECPoint;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.charset.*;
import java.security.*;
import java.util.*;
public final class Ts3Crypt {
static {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
}
public static byte[] hash128(byte[] data, int offs, int len) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA1");
digest.update(data, offs, len);
return digest.digest();
} catch (GeneralSecurityException ex) {
throw new RuntimeException(ex);
}
}
public static byte[] hash128(byte[] data) {
try {
return MessageDigest.getInstance("SHA1").digest(data);
} catch (GeneralSecurityException ex) {
throw new RuntimeException(ex);
}
}
public static byte[] hash256(byte[] data) {
try {
return MessageDigest.getInstance("SHA256").digest(data);
} catch (GeneralSecurityException ex) {
throw new RuntimeException(ex);
}
}
public static byte[] hash512(byte[] data) {
try {
return MessageDigest.getInstance("SHA512").digest(data);
} catch (GeneralSecurityException ex) {
throw new RuntimeException(ex);
}
}
public static Ts3Crypt.SecureChannelParameters cryptoInit(byte[] alpha, byte[] beta, byte[] omega,
LocalIdentity identity)
throws IOException {
if (beta.length != 10 && beta.length != 54)
throw new IOException("Invalid beta size: " + beta.length + " != (10,54)");
// getSharedSecret
byte[] sharedKey = getSharedSecret(omega, identity);
// Splamy's setSharedSecret
byte[] ivStruct = new byte[10 + beta.length];
//XorBinary(sharedKey, alpha, alpha.Length, ivStruct);
xor(sharedKey, 0, alpha, 0, alpha.length, ivStruct, 0);
//XorBinary(sharedKey.Slice(10), beta, beta.Length, ivStruct.AsSpan(10));
xor(sharedKey, 10, beta, 0, beta.length, ivStruct, 10);
byte[] buffer2 = hash128(ivStruct, 0, ivStruct.length);
byte[] fakeSignature = new byte[8];
System.arraycopy(buffer2, 0, fakeSignature, 0, 8);
return new SecureChannelParameters(fakeSignature, ivStruct);
}
public static byte[] getSharedSecret(byte[] omega, LocalIdentity identity) {
ECPoint publicKeyPoint = Ts3Crypt.decodePublicKey(omega);
ECPoint p = publicKeyPoint.multiply(identity.getPrivateKey()).normalize();
byte[] keyArr = p.getAffineXCoord().toBigInteger().toByteArray();
byte[] sharedSecret;
if (keyArr.length == 32)
sharedSecret = Ts3Crypt.hash128(keyArr);
else if (keyArr.length > 32)
sharedSecret = Ts3Crypt.hash128(keyArr, keyArr.length - 32, 32);
else {
byte[] keyArrExt = new byte[32];
System.arraycopy(keyArr, 0, keyArrExt, 32 - keyArr.length, keyArr.length);
sharedSecret = Ts3Crypt.hash128(keyArrExt);
}
return sharedSecret;
}
public static Ts3Crypt.SecureChannelParameters cryptoInit2(byte[] license, byte[] alpha,
byte[] beta, byte[] privateKey) {
// 3.2.2.2 Parsing the license
List<License> licenses = License.readLicenses(ByteBuffer.wrap(license));
byte[] key = License.deriveKey(licenses);
byte[] sharedSecret = Ts3Crypt.generateSharedSecret2(key, privateKey);
Ts3Crypt.SecureChannelParameters parameters =
Ts3Crypt.getSecureParameters(alpha, beta, sharedSecret);
return parameters;
}
public static void xor(byte[] a, int aoffs, byte[] b, int boffs, int len, byte[] outBuf, int outOffs)
{
if (a.length < len || b.length < len || outBuf.length < len)
throw new ArrayIndexOutOfBoundsException();
for (int i = 0; i < len; i++)
outBuf[i + outOffs] = (byte)(a[i + aoffs] ^ b[i + boffs]);
}
public static byte[] generateClientEkProof(byte[] key, byte[] beta,
LocalIdentity identity) {
return generateClientEkProof(key, beta, identity.getPrivateKey());
}
public static byte[] generateClientEkProof(byte[] key, byte[] beta,
BigInteger privateKey) {
// generate proof for clientek
byte[] data = new byte[86];
System.arraycopy(key, 0, data, 0, 32);
System.arraycopy(beta, 0, data, 32, 54);
return createSignature(privateKey, data);
}
public static boolean verifyClientEkProof(byte[] key, byte[] beta, byte[] signature, ECPoint publicKey) {
// generate proof for clientek
byte[] data = new byte[86];
System.arraycopy(key, 0, data, 0, 32);
System.arraycopy(beta, 0, data, 32, 54);
return verifySignature(publicKey, data, signature);
}
public static SecureChannelParameters getSecureParameters(byte[] alpha, byte[] beta, byte[] sharedKey) {
if (beta.length != 10 && beta.length != 54)
throw new IllegalArgumentException("invalid beta size (" + beta.length + ")");
byte[] fakeSignature = new byte[8];
byte[] ivStruct = new byte[10 + beta.length];
xor(sharedKey, 0, alpha, 0, alpha.length, ivStruct, 0);
xor(sharedKey, 10, beta, 0, beta.length, ivStruct, 10);
byte[] buffer = hash128(ivStruct);
System.arraycopy(buffer, 0, fakeSignature, 0, 8);
return new SecureChannelParameters(fakeSignature, ivStruct);
}
public static byte[] generateSharedSecret2(byte[] publicKey, byte[] privateKey) {
byte[] privateKeyCopy = new byte[32];
System.arraycopy(privateKey, 0, privateKeyCopy, 0, 32);
privateKeyCopy[31] &= 0x7F;
GroupElementP3 pub1 = new GroupElementP3();
GroupOperations.ge_frombytes_negate_vartime(pub1, publicKey, 0);
GroupElementP2 mul = new GroupElementP2();
GroupOperations.ge_scalarmult_vartime(mul, privateKeyCopy, pub1);
byte[] sharedTmp = new byte[32];
GroupOperations.ge_tobytes(sharedTmp, 0, mul);
sharedTmp[31] ^= 0x80;
try {
return Sha512.Hash(sharedTmp);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static ECDomainParameters getDomainParameters() {
ECNamedCurveParameterSpec ecp = ECNamedCurveTable.getParameterSpec("prime256v1");
return new ECDomainParameters(ecp.getCurve(), ecp.getG(), ecp.getN(), ecp.getH(), ecp.getSeed());
}
public static boolean verifySignature(ECPoint publicKey, byte[] data, byte[] signature) {
DSADigestSigner signer = new DSADigestSigner(new ECDSASigner(), new SHA256Digest());
ECPublicKeyParameters signingKey = new ECPublicKeyParameters(publicKey, getDomainParameters());
signer.init(false, signingKey);
signer.update(data, 0, data.length);
return signer.verifySignature(signature);
}
public static byte[] createSignature(BigInteger privateKey, byte[] data) {
DSADigestSigner signer = new DSADigestSigner(new ECDSASigner(), new SHA256Digest());
ECPrivateKeyParameters signingKey = new ECPrivateKeyParameters(privateKey, getDomainParameters());
signer.init(true, signingKey);
signer.update(data, 0, data.length);
return signer.generateSignature();
}
/**
* From http://stackoverflow.com/questions/2409618/how-do-i-decode-a-der-encoded-string-in-java
*/
private static ASN1Encodable[] readDERObject(byte[] data) throws IOException
{
ByteArrayInputStream inStream = new ByteArrayInputStream(data);
ASN1InputStream asnInputStream = new ASN1InputStream(inStream);
ASN1Object object = asnInputStream.readObject();
if (object instanceof DLSequence) {
return ((DLSequence) object).toArray();
} else {
return new ASN1Encodable[] { object };
}
}
public static ECPoint decodePublicKey(byte[] bytes) {
try {
DERSequence asnKeyData = new DERSequence(readDERObject(bytes));
BigInteger x = ((org.bouncycastle.asn1.ASN1Integer)asnKeyData.getObjectAt(2)).getValue();
BigInteger y = ((org.bouncycastle.asn1.ASN1Integer)asnKeyData.getObjectAt(3)).getValue();
return getDomainParameters().getCurve().createPoint(x, y);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static byte[] encodePublicKey(ECPoint publicKey) {
try {
byte[] dataArray = new DERSequence(new ASN1Encodable[]{
new DERBitString(new byte[]{0b0000_0000}, 7),
new DERInteger(32),
new DERInteger(publicKey.getAffineXCoord().toBigInteger()),
new DERInteger(publicKey.getAffineYCoord().toBigInteger())
}).getEncoded();
return dataArray;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static Pair<byte[], byte[]> generateKeypair() {
byte[] privateKey = new byte[32];
new SecureRandom().nextBytes(privateKey);
return generateKeypair(privateKey);
}
public static Pair<byte[], byte[]> generateKeypair(byte[] privateKey) {
ScalarOperations.sc_clamp(privateKey, 0);
GroupElementP3 A = new GroupElementP3();
GroupOperations.ge_scalarmult_base(A, privateKey, 0);
byte[] publicKey = new byte[32];
GroupOperations.ge_p3_tobytes(publicKey, 0, A);
return new Pair<>(publicKey, privateKey);
}
public static ECPoint generatePublicKeyFromPrivateKey(BigInteger privateKey) {
return ECNamedCurveTable.getParameterSpec("prime256v1").getG().multiply(privateKey).normalize();
}
public static LocalIdentity loadIdentityFromAsn(byte[] asnData) throws IOException {
ECPoint publicKey;
BigInteger privateKey = null;
DERSequence asnKeyData = new DERSequence(readDERObject(asnData));
int bitInfo = ((DERBitString)asnKeyData.getObjectAt(0)).intValue();
if (bitInfo == 0 || bitInfo == 128) {
BigInteger x = ((ASN1Integer)asnKeyData.getObjectAt(2)).getValue();
BigInteger y = ((ASN1Integer)asnKeyData.getObjectAt(3)).getValue();
publicKey = getDomainParameters().getCurve().createPoint(x, y);
if (bitInfo == 128)
privateKey = ((ASN1Integer)asnKeyData.getObjectAt(4)).getValue();
} else if (bitInfo == 192) {
privateKey = ((ASN1Integer)asnKeyData.getObjectAt(2)).getValue();
publicKey = generatePublicKeyFromPrivateKey(privateKey);
} else throw new IllegalArgumentException("invalid DER sequence");
return new LocalIdentity(publicKey, privateKey);
}
public static String hashPassword(String password) {
return Base64.getEncoder().encodeToString(hash128(password.getBytes(StandardCharsets.UTF_8)));
}
public static final class SecureChannelParameters {
private final byte[] fakeSignature;
private final byte[] ivStruct;
public SecureChannelParameters(byte[] fakeSignature, byte[] ivStruct) {
this.fakeSignature = fakeSignature;
this.ivStruct = ivStruct;
}
public byte[] getFakeSignature() {
return fakeSignature;
}
public byte[] getIvStruct() {
return ivStruct;
}
}
}
|
package com.android.github.marvelapp.marvelapp.domain.executor;
import rx.Scheduler;
public interface ThreadExecution {
Scheduler getScheduler();
}
|
/*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.internal.project;
import com.google.common.collect.Maps;
import groovy.lang.Closure;
import groovy.lang.MissingPropertyException;
import org.gradle.api.Action;
import org.gradle.api.AntBuilder;
import org.gradle.api.CircularReferenceException;
import org.gradle.api.InvalidUserDataException;
import org.gradle.api.NamedDomainObjectContainer;
import org.gradle.api.NamedDomainObjectFactory;
import org.gradle.api.PathValidation;
import org.gradle.api.Project;
import org.gradle.api.ProjectConfigurationException;
import org.gradle.api.ProjectEvaluationListener;
import org.gradle.api.Task;
import org.gradle.api.UnknownProjectException;
import org.gradle.api.artifacts.ConfigurationContainer;
import org.gradle.api.artifacts.dsl.ArtifactHandler;
import org.gradle.api.artifacts.dsl.DependencyHandler;
import org.gradle.api.artifacts.dsl.RepositoryHandler;
import org.gradle.api.component.SoftwareComponentContainer;
import org.gradle.api.file.ConfigurableFileCollection;
import org.gradle.api.file.ConfigurableFileTree;
import org.gradle.api.file.CopySpec;
import org.gradle.api.file.DeleteSpec;
import org.gradle.api.file.FileTree;
import org.gradle.api.initialization.dsl.ScriptHandler;
import org.gradle.api.internal.ClosureBackedAction;
import org.gradle.api.internal.DynamicObjectAware;
import org.gradle.api.internal.DynamicPropertyNamer;
import org.gradle.api.internal.ExtensibleDynamicObject;
import org.gradle.api.internal.FactoryNamedDomainObjectContainer;
import org.gradle.api.internal.GradleInternal;
import org.gradle.api.internal.NoConventionMapping;
import org.gradle.api.internal.ProcessOperations;
import org.gradle.api.internal.artifacts.Module;
import org.gradle.api.internal.artifacts.configurations.DependencyMetaDataProvider;
import org.gradle.api.internal.file.DefaultProjectLayout;
import org.gradle.api.internal.file.FileOperations;
import org.gradle.api.internal.file.FileResolver;
import org.gradle.api.internal.file.SourceDirectorySetFactory;
import org.gradle.api.internal.initialization.ClassLoaderScope;
import org.gradle.api.internal.initialization.ScriptHandlerFactory;
import org.gradle.api.internal.plugins.DefaultObjectConfigurationAction;
import org.gradle.api.internal.plugins.ExtensionContainerInternal;
import org.gradle.api.internal.plugins.PluginManagerInternal;
import org.gradle.api.internal.project.taskfactory.ITaskFactory;
import org.gradle.api.internal.tasks.TaskContainerInternal;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.plugins.Convention;
import org.gradle.api.plugins.ExtensionContainer;
import org.gradle.api.provider.PropertyState;
import org.gradle.api.provider.Provider;
import org.gradle.api.provider.ProviderFactory;
import org.gradle.api.resources.ResourceHandler;
import org.gradle.api.tasks.WorkResult;
import org.gradle.configuration.ScriptPluginFactory;
import org.gradle.configuration.project.ProjectConfigurationActionContainer;
import org.gradle.configuration.project.ProjectEvaluator;
import org.gradle.groovy.scripts.ScriptSource;
import org.gradle.internal.Actions;
import org.gradle.internal.Factories;
import org.gradle.internal.Factory;
import org.gradle.internal.event.ListenerBroadcast;
import org.gradle.internal.logging.LoggingManagerInternal;
import org.gradle.internal.logging.StandardOutputCapture;
import org.gradle.internal.metaobject.BeanDynamicObject;
import org.gradle.internal.metaobject.DynamicObject;
import org.gradle.internal.reflect.Instantiator;
import org.gradle.internal.resource.TextResourceLoader;
import org.gradle.internal.service.ServiceRegistry;
import org.gradle.internal.service.scopes.ServiceRegistryFactory;
import org.gradle.internal.typeconversion.TypeConverter;
import org.gradle.listener.ClosureBackedMethodInvocationDispatch;
import org.gradle.model.Model;
import org.gradle.model.RuleSource;
import org.gradle.model.dsl.internal.NonTransformedModelDslBacking;
import org.gradle.model.dsl.internal.TransformedModelDslBacking;
import org.gradle.model.internal.core.DefaultNodeInitializerRegistry;
import org.gradle.model.internal.core.Hidden;
import org.gradle.model.internal.core.ModelReference;
import org.gradle.model.internal.core.ModelRegistrations;
import org.gradle.model.internal.core.NodeInitializerRegistry;
import org.gradle.model.internal.manage.binding.StructBindingsStore;
import org.gradle.model.internal.manage.instance.ManagedProxyFactory;
import org.gradle.model.internal.manage.schema.ModelSchemaStore;
import org.gradle.model.internal.registry.ModelRegistry;
import org.gradle.model.internal.type.ModelType;
import org.gradle.normalization.InputNormalizationHandler;
import org.gradle.process.ExecResult;
import org.gradle.process.ExecSpec;
import org.gradle.process.JavaExecSpec;
import org.gradle.util.Configurable;
import org.gradle.util.ConfigureUtil;
import org.gradle.util.DeprecationLogger;
import org.gradle.util.Path;
import javax.annotation.Nullable;
import javax.inject.Inject;
import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.util.Collections.singletonMap;
import static org.gradle.util.ConfigureUtil.configureUsing;
import static org.gradle.util.GUtil.addMaps;
@NoConventionMapping
public class DefaultProject extends AbstractPluginAware implements ProjectInternal, DynamicObjectAware {
private static final ModelType<ServiceRegistry> SERVICE_REGISTRY_MODEL_TYPE = ModelType.of(ServiceRegistry.class);
private static final ModelType<File> FILE_MODEL_TYPE = ModelType.of(File.class);
private static final ModelType<ProjectIdentifier> PROJECT_IDENTIFIER_MODEL_TYPE = ModelType.of(ProjectIdentifier.class);
private static final ModelType<ExtensionContainer> EXTENSION_CONTAINER_MODEL_TYPE = ModelType.of(ExtensionContainer.class);
private static final Logger BUILD_LOGGER = Logging.getLogger(Project.class);
private final ClassLoaderScope classLoaderScope;
private final ClassLoaderScope baseClassLoaderScope;
private ServiceRegistry services;
private final ProjectInternal rootProject;
private final GradleInternal gradle;
private ProjectEvaluator projectEvaluator;
private ScriptSource buildScriptSource;
private final File projectDir;
private final File buildFile;
private final ProjectInternal parent;
private final String name;
private Object group;
private Object version;
private Object status;
private final Map<String, Project> childProjects = Maps.newTreeMap();
private List<String> defaultTasks = new ArrayList<String>();
private ProjectStateInternal state;
private FileResolver fileResolver;
private Factory<AntBuilder> antBuilderFactory;
private AntBuilder ant;
private final int depth;
private TaskContainerInternal taskContainer;
private DependencyHandler dependencyHandler;
private ConfigurationContainer configurationContainer;
private ArtifactHandler artifactHandler;
private ListenerBroadcast<ProjectEvaluationListener> evaluationListener = new ListenerBroadcast<ProjectEvaluationListener>(ProjectEvaluationListener.class);
private ExtensibleDynamicObject extensibleDynamicObject;
private String description;
private final Path path;
private Path identityPath;
public DefaultProject(String name,
@Nullable ProjectInternal parent,
File projectDir,
File buildFile,
ScriptSource buildScriptSource,
GradleInternal gradle,
ServiceRegistryFactory serviceRegistryFactory,
ClassLoaderScope selfClassLoaderScope,
ClassLoaderScope baseClassLoaderScope) {
this.classLoaderScope = selfClassLoaderScope;
this.baseClassLoaderScope = baseClassLoaderScope;
this.rootProject = parent != null ? parent.getRootProject() : this;
this.projectDir = projectDir;
this.buildFile = buildFile;
this.parent = parent;
this.name = name;
this.state = new ProjectStateInternal();
this.buildScriptSource = buildScriptSource;
this.gradle = gradle;
if (parent == null) {
path = Path.ROOT;
depth = 0;
} else {
path = parent.getProjectPath().child(name);
depth = parent.getDepth() + 1;
}
services = serviceRegistryFactory.createFor(this);
taskContainer = services.newInstance(TaskContainerInternal.class);
extensibleDynamicObject = new ExtensibleDynamicObject(this, Project.class, services.get(Instantiator.class));
if (parent != null) {
extensibleDynamicObject.setParent(parent.getInheritedScope());
}
extensibleDynamicObject.addObject(taskContainer.getTasksAsDynamicObject(), ExtensibleDynamicObject.Location.AfterConvention);
evaluationListener.add(gradle.getProjectEvaluationBroadcaster());
populateModelRegistry(services.get(ModelRegistry.class));
}
@SuppressWarnings("unused")
static class BasicServicesRules extends RuleSource {
@Hidden @Model
SourceDirectorySetFactory sourceDirectorySetFactory(ServiceRegistry serviceRegistry) {
return serviceRegistry.get(SourceDirectorySetFactory.class);
}
@Hidden @Model
ITaskFactory taskFactory(ServiceRegistry serviceRegistry) {
return serviceRegistry.get(ITaskFactory.class);
}
@Hidden @Model
Instantiator instantiator(ServiceRegistry serviceRegistry) {
return serviceRegistry.get(Instantiator.class);
}
@Hidden @Model
ModelSchemaStore schemaStore(ServiceRegistry serviceRegistry) {
return serviceRegistry.get(ModelSchemaStore.class);
}
@Hidden @Model
ManagedProxyFactory proxyFactory(ServiceRegistry serviceRegistry) {
return serviceRegistry.get(ManagedProxyFactory.class);
}
@Hidden @Model
StructBindingsStore structBindingsStore(ServiceRegistry serviceRegistry) {
return serviceRegistry.get(StructBindingsStore.class);
}
@Hidden @Model
NodeInitializerRegistry nodeInitializerRegistry(ModelSchemaStore schemaStore, StructBindingsStore structBindingsStore) {
return new DefaultNodeInitializerRegistry(schemaStore, structBindingsStore);
}
@Hidden @Model
TypeConverter typeConverter(ServiceRegistry serviceRegistry) {
return serviceRegistry.get(TypeConverter.class);
}
@Hidden @Model
FileOperations fileOperations(ServiceRegistry serviceRegistry) {
return serviceRegistry.get(FileOperations.class);
}
}
private void populateModelRegistry(ModelRegistry modelRegistry) {
registerServiceOn(modelRegistry, "serviceRegistry", SERVICE_REGISTRY_MODEL_TYPE, services, instanceDescriptorFor("serviceRegistry"));
// TODO:LPTR This ignores changes to Project.buildDir after model node has been created
registerFactoryOn(modelRegistry, "buildDir", FILE_MODEL_TYPE, new Factory<File>() {
@Override
public File create() {
return getBuildDir();
}
});
registerInstanceOn(modelRegistry, "projectIdentifier", PROJECT_IDENTIFIER_MODEL_TYPE, this);
registerInstanceOn(modelRegistry, "extensionContainer", EXTENSION_CONTAINER_MODEL_TYPE, getExtensions());
modelRegistry.getRoot().applyToSelf(BasicServicesRules.class);
}
private <T> void registerInstanceOn(ModelRegistry modelRegistry, String path, ModelType<T> type, T instance) {
registerFactoryOn(modelRegistry, path, type, Factories.constant(instance));
}
private <T> void registerFactoryOn(ModelRegistry modelRegistry, String path, ModelType<T> type, Factory<T> factory) {
modelRegistry.register(ModelRegistrations
.unmanagedInstance(ModelReference.of(path, type), factory)
.descriptor(instanceDescriptorFor(path))
.hidden(true)
.build());
}
private <T> void registerServiceOn(ModelRegistry modelRegistry, String path, ModelType<T> type, T instance, String descriptor) {
modelRegistry.register(ModelRegistrations.serviceInstance(ModelReference.of(path, type), instance)
.descriptor(descriptor)
.build()
);
}
private String instanceDescriptorFor(String path) {
return "Project.<init>." + path + "()";
}
@Override
public ProjectInternal getRootProject() {
return rootProject;
}
@Override
public GradleInternal getGradle() {
return gradle;
}
public ProjectEvaluator getProjectEvaluator() {
if (projectEvaluator == null) {
projectEvaluator = services.get(ProjectEvaluator.class);
}
return projectEvaluator;
}
public void setProjectEvaluator(ProjectEvaluator projectEvaluator) {
this.projectEvaluator = projectEvaluator;
}
@Inject
@Override
public ScriptHandler getBuildscript() {
// Decoration takes care of the implementation
throw new UnsupportedOperationException();
}
@Override
public File getBuildFile() {
return buildFile;
}
@Override
public void setScript(groovy.lang.Script buildScript) {
extensibleDynamicObject.addObject(new BeanDynamicObject(buildScript).withNoProperties().withNotImplementsMissing(),
ExtensibleDynamicObject.Location.BeforeConvention);
}
@Override
public ScriptSource getBuildScriptSource() {
return buildScriptSource;
}
@Override
public File getRootDir() {
return rootProject.getProjectDir();
}
@Override
public ProjectInternal getParent() {
return parent;
}
@Override
public ProjectIdentifier getParentIdentifier() {
return parent;
}
@Override
public DynamicObject getAsDynamicObject() {
return extensibleDynamicObject;
}
@Override
public DynamicObject getInheritedScope() {
return extensibleDynamicObject.getInheritable();
}
@Override
public String getName() {
return name;
}
@Override
public String getDescription() {
return description;
}
@Override
public void setDescription(String description) {
this.description = description;
}
@Override
public Object getGroup() {
if (group != null) {
return group;
} else if (this == rootProject) {
return "";
}
group = rootProject.getName() + (getParent() == rootProject ? "" : "." + getParent().getPath().substring(1).replace(':', '.'));
return group;
}
@Override
public void setGroup(Object group) {
this.group = group;
}
@Override
public Object getVersion() {
return version == null ? DEFAULT_VERSION : version;
}
@Override
public void setVersion(Object version) {
this.version = version;
}
@Override
public Object getStatus() {
return status == null ? DEFAULT_STATUS : status;
}
@Override
public void setStatus(Object status) {
this.status = status;
}
@Override
public Map<String, Project> getChildProjects() {
return childProjects;
}
@Override
public List<String> getDefaultTasks() {
return defaultTasks;
}
@Override
public void setDefaultTasks(List<String> defaultTasks) {
this.defaultTasks = defaultTasks;
}
@Override
public ProjectStateInternal getState() {
return state;
}
@Override
public FileResolver getFileResolver() {
if (fileResolver == null) {
fileResolver = services.get(FileResolver.class);
}
return fileResolver;
}
public void setFileResolver(FileResolver fileResolver) {
this.fileResolver = fileResolver;
}
public void setAnt(AntBuilder ant) {
this.ant = ant;
}
@Override
public ArtifactHandler getArtifacts() {
if (artifactHandler == null) {
artifactHandler = services.get(ArtifactHandler.class);
}
return artifactHandler;
}
public void setArtifactHandler(ArtifactHandler artifactHandler) {
this.artifactHandler = artifactHandler;
}
@Inject
@Override
public RepositoryHandler getRepositories() {
// Decoration takes care of the implementation
throw new UnsupportedOperationException();
}
@Override
public ConfigurationContainer getConfigurations() {
if (configurationContainer == null) {
configurationContainer = services.get(ConfigurationContainer.class);
}
return configurationContainer;
}
public void setConfigurationContainer(ConfigurationContainer configurationContainer) {
this.configurationContainer = configurationContainer;
}
@Override
public Convention getConvention() {
return extensibleDynamicObject.getConvention();
}
@Override
public String getPath() {
return path.toString();
}
@Override
public Path getIdentityPath() {
if (identityPath == null) {
if (parent == null) {
identityPath = gradle.getIdentityPath();
} else {
identityPath = parent.getIdentityPath().child(name);
}
}
return identityPath;
}
@Override
public int getDepth() {
return depth;
}
@Inject
@Override
public ProjectRegistry<ProjectInternal> getProjectRegistry() {
// Decoration takes care of the implementation
throw new UnsupportedOperationException();
}
@Override
public int depthCompare(Project otherProject) {
return new Integer(getDepth()).compareTo(otherProject.getDepth());
}
@Override
public int compareTo(Project otherProject) {
int depthCompare = depthCompare(otherProject);
if (depthCompare == 0) {
return getPath().compareTo(otherProject.getPath());
} else {
return depthCompare;
}
}
@Override
public String absoluteProjectPath(String path) {
return this.path.absolutePath(path);
}
@Override
public Path identityPath(String name) {
return getIdentityPath().child(name);
}
@Override
public Path getProjectPath() {
return path;
}
@Override
public Path getBuildPath() {
return gradle.getIdentityPath();
}
@Override
public Path projectPath(String name) {
return path.child(name);
}
@Override
public boolean isScript() {
return false;
}
@Override
public String relativeProjectPath(String path) {
return this.path.relativePath(path);
}
@Override
public ProjectInternal project(String path) {
ProjectInternal project = findProject(path);
if (project == null) {
throw new UnknownProjectException(String.format("Project with path '%s' could not be found in %s.", path, this));
}
return project;
}
@Override
public ProjectInternal findProject(String path) {
if (isNullOrEmpty(path)) {
throw new InvalidUserDataException("A path must be specified!");
}
return getProjectRegistry().getProject(absoluteProjectPath(path));
}
@Override
public Set<Project> getAllprojects() {
return new TreeSet<Project>(getProjectRegistry().getAllProjects(getPath()));
}
@Override
public Set<Project> getSubprojects() {
return new TreeSet<Project>(getProjectRegistry().getSubProjects(getPath()));
}
@Override
public void subprojects(Action<? super Project> action) {
getProjectConfigurator().subprojects(getSubprojects(), action);
}
@Override
public void allprojects(Action<? super Project> action) {
getProjectConfigurator().allprojects(getAllprojects(), action);
}
@Override
public <T> Iterable<T> configure(Iterable<T> objects, Action<? super T> configureAction) {
for (T object : objects) {
configureAction.execute(object);
}
return objects;
}
@Override
public AntBuilder getAnt() {
if (ant == null) {
ant = createAntBuilder();
}
return ant;
}
@Override
public AntBuilder createAntBuilder() {
return getAntBuilderFactory().create();
}
/**
* This method is used when scripts access the project via project.x
*/
@Override
public Project getProject() {
return this;
}
@Override
public DefaultProject evaluate() {
getProjectEvaluator().evaluate(this, state);
return this;
}
@Override
public ProjectInternal bindAllModelRules() {
try {
getModelRegistry().bindAllReferences();
} catch (Exception e) {
throw new ProjectConfigurationException(String.format("A problem occurred configuring %s.", this), e);
}
return this;
}
@Override
public TaskContainerInternal getTasks() {
return taskContainer;
}
@Override
public void defaultTasks(String... defaultTasks) {
if (defaultTasks == null) {
throw new InvalidUserDataException("Default tasks must not be null!");
}
this.defaultTasks = new ArrayList<String>();
for (String defaultTask : defaultTasks) {
if (defaultTask == null) {
throw new InvalidUserDataException("Default tasks must not be null!");
}
this.defaultTasks.add(defaultTask);
}
}
@Override
public void addChildProject(ProjectInternal childProject) {
childProjects.put(childProject.getName(), childProject);
}
@Override
public File getProjectDir() {
return projectDir;
}
@Override
public File getBuildDir() {
return getLayout().getBuildDirectory().getAsFile().get();
}
@Override
public void setBuildDir(File path) {
setBuildDir((Object) path);
}
@Override
public void setBuildDir(Object path) {
getLayout().setBuildDirectory(path);
}
@Override
public void evaluationDependsOnChildren() {
for (Project project : childProjects.values()) {
DefaultProject defaultProjectToEvaluate = (DefaultProject) project;
evaluationDependsOn(defaultProjectToEvaluate);
}
}
@Override
public Project evaluationDependsOn(String path) {
if (isNullOrEmpty(path)) {
throw new InvalidUserDataException("You must specify a project!");
}
DefaultProject projectToEvaluate = (DefaultProject) project(path);
return evaluationDependsOn(projectToEvaluate);
}
private Project evaluationDependsOn(DefaultProject projectToEvaluate) {
if (projectToEvaluate.getState().getExecuting()) {
throw new CircularReferenceException(String.format("Circular referencing during evaluation for %s.",
projectToEvaluate));
}
return projectToEvaluate.evaluate();
}
@Override
public String getDisplayName() {
StringBuilder builder = new StringBuilder();
if (parent == null && gradle.getParent() == null) {
builder.append("root project '");
builder.append(name);
builder.append('\'');
} else {
builder.append("project '");
builder.append(getIdentityPath());
builder.append("'");
}
return builder.toString();
}
@Override
public String toString() {
return getDisplayName();
}
@Override
public Map<Project, Set<Task>> getAllTasks(boolean recursive) {
final Map<Project, Set<Task>> foundTargets = new TreeMap<Project, Set<Task>>();
Action<Project> action = new Action<Project>() {
public void execute(Project project) {
foundTargets.put(project, new TreeSet<Task>(project.getTasks()));
}
};
if (recursive) {
allprojects(action);
} else {
action.execute(this);
}
return foundTargets;
}
@Override
public Set<Task> getTasksByName(final String name, boolean recursive) {
if (isNullOrEmpty(name)) {
throw new InvalidUserDataException("Name is not specified!");
}
final Set<Task> foundTasks = new HashSet<Task>();
Action<Project> action = new Action<Project>() {
public void execute(Project project) {
// Don't force evaluation of rules here, let the task container do what it needs to
((ProjectInternal) project).evaluate();
Task task = project.getTasks().findByName(name);
if (task != null) {
foundTasks.add(task);
}
}
};
if (recursive) {
allprojects(action);
} else {
action.execute(this);
}
return foundTasks;
}
@Inject
protected FileOperations getFileOperations() {
// Decoration takes care of the implementation
throw new UnsupportedOperationException();
}
@Override
@Inject
public ProviderFactory getProviders() {
// Decoration takes care of the implementation
throw new UnsupportedOperationException();
}
@Override
@Inject
public ObjectFactory getObjects() {
// Decoration takes care of the implementation
throw new UnsupportedOperationException();
}
@Override
@Inject
public DefaultProjectLayout getLayout() {
// Decoration takes care of the implementation
throw new UnsupportedOperationException();
}
@Override
public File file(Object path) {
return getFileOperations().file(path);
}
@Override
public File file(Object path, PathValidation validation) {
return getFileOperations().file(path, validation);
}
@Override
public URI uri(Object path) {
return getFileOperations().uri(path);
}
@Override
public ConfigurableFileCollection files(Object... paths) {
return getFileOperations().files(paths);
}
@Override
public ConfigurableFileCollection files(Object paths, Closure closure) {
return ConfigureUtil.configure(closure, files(paths));
}
@Override
public ConfigurableFileCollection files(Object paths, Action<? super ConfigurableFileCollection> configureAction) {
ConfigurableFileCollection files = files(paths);
configureAction.execute(files);
return files;
}
@Override
public ConfigurableFileTree fileTree(Object baseDir) {
return getFileOperations().fileTree(baseDir);
}
@Override
public ConfigurableFileTree fileTree(Object baseDir, Closure closure) {
return ConfigureUtil.configure(closure, fileTree(baseDir));
}
@Override
public ConfigurableFileTree fileTree(Object baseDir, Action<? super ConfigurableFileTree> configureAction) {
ConfigurableFileTree fileTree = fileTree(baseDir);
configureAction.execute(fileTree);
return fileTree;
}
@Override
public ConfigurableFileTree fileTree(Map<String, ?> args) {
return getFileOperations().fileTree(args);
}
@Override
public FileTree zipTree(Object zipPath) {
return getFileOperations().zipTree(zipPath);
}
@Override
public FileTree tarTree(Object tarPath) {
return getFileOperations().tarTree(tarPath);
}
@Override
public <T> Provider<T> provider(Callable<T> value) {
return getProviders().provider(value);
}
@Override
public <T> PropertyState<T> property(Class<T> clazz) {
return getProviders().property(clazz);
}
@Override
public ResourceHandler getResources() {
return getFileOperations().getResources();
}
@Override
public String relativePath(Object path) {
return getFileOperations().relativePath(path);
}
@Override
public File mkdir(Object path) {
return getFileOperations().mkdir(path);
}
@Override
public boolean delete(Object... paths) {
return getFileOperations().delete(paths);
}
@Override
public WorkResult delete(Action<? super DeleteSpec> action) {
return getFileOperations().delete(action);
}
public Factory<AntBuilder> getAntBuilderFactory() {
if (antBuilderFactory == null) {
antBuilderFactory = services.getFactory(AntBuilder.class);
}
return antBuilderFactory;
}
@Override
public DependencyHandler getDependencies() {
if (dependencyHandler == null) {
dependencyHandler = services.get(DependencyHandler.class);
}
return dependencyHandler;
}
public void setDependencyHandler(DependencyHandler dependencyHandler) {
this.dependencyHandler = dependencyHandler;
}
@Override
public ProjectEvaluationListener getProjectEvaluationBroadcaster() {
return evaluationListener.getSource();
}
@Override
public void beforeEvaluate(Action<? super Project> action) {
evaluationListener.add("beforeEvaluate", action);
}
@Override
public void afterEvaluate(Action<? super Project> action) {
evaluationListener.add("afterEvaluate", action);
}
@Override
public void beforeEvaluate(Closure closure) {
evaluationListener.add(new ClosureBackedMethodInvocationDispatch("beforeEvaluate", closure));
}
@Override
public void afterEvaluate(Closure closure) {
evaluationListener.add(new ClosureBackedMethodInvocationDispatch("afterEvaluate", closure));
}
@Override
public Logger getLogger() {
return BUILD_LOGGER;
}
@Override
public StandardOutputCapture getStandardOutputCapture() {
return getLogging();
}
@Inject
@Override
public LoggingManagerInternal getLogging() {
// Decoration takes care of the implementation
throw new UnsupportedOperationException();
}
@Inject
@Override
public SoftwareComponentContainer getComponents() {
// Decoration takes care of the implementation
throw new UnsupportedOperationException();
}
@Override
public Object property(String propertyName) throws MissingPropertyException {
return extensibleDynamicObject.getProperty(propertyName);
}
@Override
public Object findProperty(String propertyName) {
return hasProperty(propertyName) ? property(propertyName) : null;
}
@Override
public void setProperty(String name, Object value) {
extensibleDynamicObject.setProperty(name, value);
}
@Override
public boolean hasProperty(String propertyName) {
return extensibleDynamicObject.hasProperty(propertyName);
}
@Override
public Map<String, ?> getProperties() {
return DeprecationLogger.whileDisabled(new Factory<Map<String, ?>>() {
public Map<String, ?> create() {
return extensibleDynamicObject.getProperties();
}
});
}
@Override
public WorkResult copy(Closure closure) {
return copy(configureUsing(closure));
}
@Override
public WorkResult copy(Action<? super CopySpec> action) {
return getFileOperations().copy(action);
}
@Override
public WorkResult sync(Action<? super CopySpec> action) {
return getFileOperations().sync(action);
}
@Override
public CopySpec copySpec(Closure closure) {
return ConfigureUtil.configure(closure, copySpec());
}
@Override
public CopySpec copySpec(Action<? super CopySpec> action) {
return Actions.with(copySpec(), action);
}
@Override
public CopySpec copySpec() {
return getFileOperations().copySpec();
}
@Inject
protected ProcessOperations getProcessOperations() {
// Decoration takes care of the implementation
throw new UnsupportedOperationException();
}
@Override
public ExecResult javaexec(Closure closure) {
return javaexec(configureUsing(closure));
}
@Override
public ExecResult javaexec(Action<? super JavaExecSpec> action) {
return getProcessOperations().javaexec(action);
}
@Override
public ExecResult exec(Closure closure) {
return exec(configureUsing(closure));
}
@Override
public ExecResult exec(Action<? super ExecSpec> action) {
return getProcessOperations().exec(action);
}
@Override
public ServiceRegistry getServices() {
return services;
}
@Override
public ServiceRegistryFactory getServiceRegistryFactory() {
return services.get(ServiceRegistryFactory.class);
}
@Override
public Module getModule() {
return services.get(DependencyMetaDataProvider.class).getModule();
}
@Override
public AntBuilder ant(Closure configureClosure) {
return ConfigureUtil.configure(configureClosure, getAnt());
}
@Override
public AntBuilder ant(Action<? super AntBuilder> configureAction) {
AntBuilder ant = getAnt();
configureAction.execute(ant);
return ant;
}
@Override
public void subprojects(Closure configureClosure) {
getProjectConfigurator().subprojects(getSubprojects(), configureClosure);
}
@Override
public void allprojects(Closure configureClosure) {
getProjectConfigurator().allprojects(getAllprojects(), configureClosure);
}
@Override
public Project project(String path, Closure configureClosure) {
return getProjectConfigurator().project(project(path), configureClosure);
}
@Override
public Project project(String path, Action<? super Project> configureAction) {
return getProjectConfigurator().project(project(path), configureAction);
}
@Override
public Object configure(Object object, Closure configureClosure) {
return ConfigureUtil.configure(configureClosure, object);
}
@Override
public Iterable<?> configure(Iterable<?> objects, Closure configureClosure) {
for (Object object : objects) {
configure(object, configureClosure);
}
return objects;
}
@Override
public void configurations(Closure configureClosure) {
((Configurable<?>) getConfigurations()).configure(configureClosure);
}
@Override
public void repositories(Closure configureClosure) {
ConfigureUtil.configure(configureClosure, getRepositories());
}
@Override
public void dependencies(Closure configureClosure) {
ConfigureUtil.configure(configureClosure, getDependencies());
}
@Override
public void artifacts(Closure configureClosure) {
ConfigureUtil.configure(configureClosure, getArtifacts());
}
@Override
public void artifacts(Action<? super ArtifactHandler> configureAction) {
configureAction.execute(getArtifacts());
}
@Override
public void buildscript(Closure configureClosure) {
ConfigureUtil.configure(configureClosure, getBuildscript());
}
@Override
public Task task(String task) {
return taskContainer.create(task);
}
public Task task(Object task) {
return taskContainer.create(task.toString());
}
@Override
public Task task(String task, Closure configureClosure) {
return taskContainer.create(task).configure(configureClosure);
}
public Task task(Object task, Closure configureClosure) {
return task(task.toString(), configureClosure);
}
@Override
public Task task(Map options, String task) {
return taskContainer.create(addMaps(options, singletonMap(Task.TASK_NAME, task)));
}
public Task task(Map options, Object task) {
return task(options, task.toString());
}
@Override
public Task task(Map options, String task, Closure configureClosure) {
return taskContainer.create(addMaps(options, singletonMap(Task.TASK_NAME, task))).configure(configureClosure);
}
public Task task(Map options, Object task, Closure configureClosure) {
return task(options, task.toString(), configureClosure);
}
@Inject
@Override
public ProjectConfigurationActionContainer getConfigurationActions() {
// Decoration takes care of the implementation
throw new UnsupportedOperationException();
}
@Inject
@Override
public ModelRegistry getModelRegistry() {
// Decoration takes care of the implementation
throw new UnsupportedOperationException();
}
@Inject
protected ModelSchemaStore getModelSchemaStore() {
// Decoration takes care of the implementation
throw new UnsupportedOperationException();
}
@Override
protected DefaultObjectConfigurationAction createObjectConfigurationAction() {
return new DefaultObjectConfigurationAction(getFileResolver(), getScriptPluginFactory(), getScriptHandlerFactory(), getBaseClassLoaderScope(), getResourceLoader(), this);
}
@Inject
protected TextResourceLoader getResourceLoader() {
throw new UnsupportedOperationException();
}
@Inject
@Override
public PluginManagerInternal getPluginManager() {
// Decoration takes care of the implementation
throw new UnsupportedOperationException();
}
@Inject
protected ScriptPluginFactory getScriptPluginFactory() {
// Decoration takes care of the implementation
throw new UnsupportedOperationException();
}
@Inject
protected ScriptHandlerFactory getScriptHandlerFactory() {
// Decoration takes care of the implementation
throw new UnsupportedOperationException();
}
@Override
public ClassLoaderScope getClassLoaderScope() {
return classLoaderScope;
}
@Override
public ClassLoaderScope getBaseClassLoaderScope() {
return baseClassLoaderScope;
}
/**
* This is called by the task creation DSL. Need to find a cleaner way to do this...
*/
public Object passThrough(Object object) {
return object;
}
@Override
public <T> NamedDomainObjectContainer<T> container(Class<T> type) {
Instantiator instantiator = getServices().get(Instantiator.class);
return instantiator.newInstance(FactoryNamedDomainObjectContainer.class, type, instantiator, new DynamicPropertyNamer());
}
@Override
public <T> NamedDomainObjectContainer<T> container(Class<T> type, NamedDomainObjectFactory<T> factory) {
Instantiator instantiator = getServices().get(Instantiator.class);
return instantiator.newInstance(FactoryNamedDomainObjectContainer.class, type, instantiator, new DynamicPropertyNamer(), factory);
}
@Override
public <T> NamedDomainObjectContainer<T> container(Class<T> type, Closure factoryClosure) {
Instantiator instantiator = getServices().get(Instantiator.class);
return instantiator.newInstance(FactoryNamedDomainObjectContainer.class, type, instantiator, new DynamicPropertyNamer(), factoryClosure);
}
@Override
public ExtensionContainerInternal getExtensions() {
return (ExtensionContainerInternal) getConvention();
}
// Not part of the public API
public void model(Closure<?> modelRules) {
ModelRegistry modelRegistry = getModelRegistry();
if (TransformedModelDslBacking.isTransformedBlock(modelRules)) {
ClosureBackedAction.execute(new TransformedModelDslBacking(modelRegistry, this.getRootProject().getFileResolver()), modelRules);
} else {
new NonTransformedModelDslBacking(modelRegistry).configure(modelRules);
}
}
@Inject
protected DeferredProjectConfiguration getDeferredProjectConfiguration() {
// Decoration takes care of the implementation
throw new UnsupportedOperationException();
}
@Inject
protected CrossProjectConfigurator getProjectConfigurator() {
throw new UnsupportedOperationException();
}
@Override
public void addDeferredConfiguration(Runnable configuration) {
getDeferredProjectConfiguration().add(configuration);
}
@Override
public void fireDeferredConfiguration() {
getDeferredProjectConfiguration().fire();
}
@Inject
@Override
public InputNormalizationHandler getNormalization() {
throw new UnsupportedOperationException();
}
@Override
public void normalization(Action<? super InputNormalizationHandler> configuration) {
configuration.execute(getNormalization());
}
}
|
package org.openstack4j.model.network.builder;
import org.openstack4j.common.Buildable.Builder;
import org.openstack4j.model.network.NetFloatingIP;
/**
* Builder for a FloatingIP model class.
*
* @author Nathan Anderson
*/
public interface NetFloatingIPBuilder extends Builder<NetFloatingIPBuilder, NetFloatingIP> {
/**
* sets Id of floating network
*
* @param networkId the network id
* @return the floating ip builder
*/
NetFloatingIPBuilder floatingNetworkId(String networkId);
/**
* Port id.
*
* @param portId the port id
* @return the floating ip builder
*/
NetFloatingIPBuilder portId(String portId);
/**
* Value of the floating IP to use.
*/
NetFloatingIPBuilder floatingIpAddress(String address);
/**
* Fixed IP to connect to.
*/
NetFloatingIPBuilder fixedIpAddress(String address);
/**
* Textual description of the resource.
*
* @param description Maximum of 250 characters.
*/
NetFloatingIPBuilder description(String description);
}
|
/*
* 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.skywalking.oap.server.library.buffer;
import com.google.protobuf.*;
import java.io.*;
import java.nio.channels.FileLock;
import org.apache.commons.io.FileUtils;
import org.slf4j.*;
/**
* @author peng-yongsheng
*/
public class BufferStream<MESSAGE_TYPE extends GeneratedMessageV3> {
private static final Logger logger = LoggerFactory.getLogger(BufferStream.class);
private final String absolutePath;
private final boolean cleanWhenRestart;
private final int dataFileMaxSize;
private final int offsetFileMaxSize;
private final Parser<MESSAGE_TYPE> parser;
private final DataStreamReader.CallBack<MESSAGE_TYPE> callBack;
private DataStream<MESSAGE_TYPE> dataStream;
private BufferStream(String absolutePath, boolean cleanWhenRestart, int dataFileMaxSize, int offsetFileMaxSize,
Parser<MESSAGE_TYPE> parser, DataStreamReader.CallBack<MESSAGE_TYPE> callBack) {
this.absolutePath = absolutePath;
this.cleanWhenRestart = cleanWhenRestart;
this.dataFileMaxSize = dataFileMaxSize;
this.offsetFileMaxSize = offsetFileMaxSize;
this.parser = parser;
this.callBack = callBack;
}
public synchronized void initialize() throws IOException {
File directory = new File(absolutePath);
FileUtils.forceMkdir(directory);
tryLock(directory);
dataStream = new DataStream<>(directory, dataFileMaxSize, offsetFileMaxSize, parser, callBack);
if (cleanWhenRestart) {
dataStream.clean();
}
dataStream.initialize();
}
public synchronized void write(AbstractMessageLite messageLite) {
dataStream.getWriter().write(messageLite);
}
private void tryLock(File directory) {
logger.info("Try to lock buffer directory, directory is: " + absolutePath);
FileLock lock = null;
try {
lock = new FileOutputStream(new File(directory, "lock")).getChannel().tryLock();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
if (lock == null) {
throw new RuntimeException("The buffer directory is reading or writing by another thread, directory is: " + absolutePath);
}
logger.info("Lock buffer directory successfully, directory is: " + absolutePath);
}
public static class Builder<MESSAGE_TYPE extends GeneratedMessageV3> {
private final String absolutePath;
private boolean cleanWhenRestart;
private int dataFileMaxSize;
private int offsetFileMaxSize;
private Parser<MESSAGE_TYPE> parser;
private DataStreamReader.CallBack<MESSAGE_TYPE> callBack;
public Builder(String absolutePath) {
this.absolutePath = absolutePath;
}
public BufferStream<MESSAGE_TYPE> build() {
return new BufferStream<>(absolutePath, cleanWhenRestart, dataFileMaxSize, offsetFileMaxSize, parser, callBack);
}
public Builder<MESSAGE_TYPE> cleanWhenRestart(boolean cleanWhenRestart) {
this.cleanWhenRestart = cleanWhenRestart;
return this;
}
public Builder<MESSAGE_TYPE> offsetFileMaxSize(int offsetFileMaxSize) {
this.offsetFileMaxSize = offsetFileMaxSize;
return this;
}
public Builder<MESSAGE_TYPE> dataFileMaxSize(int dataFileMaxSize) {
this.dataFileMaxSize = dataFileMaxSize;
return this;
}
public Builder<MESSAGE_TYPE> parser(Parser<MESSAGE_TYPE> parser) {
this.parser = parser;
return this;
}
public Builder<MESSAGE_TYPE> callBack(DataStreamReader.CallBack<MESSAGE_TYPE> callBack) {
this.callBack = callBack;
return this;
}
}
}
|
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.springframework.amqp.remoting.testservice;
/**
* @author David Bilge
* @since 1.2
*/
public class GeneralException extends RuntimeException {
private static final long serialVersionUID = 1763252570120227426L;
public GeneralException(String message, Throwable cause) {
super(message, cause);
}
public GeneralException(String message) {
super(message);
}
}
|
package seedu.address.model.notes;
import javafx.collections.ObservableList;
/**
* Unmodifiable view of Notes
*/
public interface ReadOnlyNotes {
/**
* Returns an unmodifiable view of the all the Notes.
* This list will not contain any duplicate assessment.
*/
ObservableList<Notes> getNotesList();
}
|
package com.zimbra.qa.unittest;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import org.dom4j.DocumentException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.zimbra.common.localconfig.ConfigException;
import com.zimbra.common.localconfig.LC;
import com.zimbra.common.service.ServiceException;
import com.zimbra.cs.account.Account;
import com.zimbra.cs.account.Provisioning;
/**
* This is a shell test for Local IMAP tests that does the necessary configuration to select
* the local variant of IMAP access.
*
* Note: Currently bypasses Proxy, the tests connect directly to the embedded IMAP server's port
*
* The actual tests that are run are in {@link SharedImapTests}
*/
public class TestImapViaEmbeddedLocal extends SharedImapTests {
@Before
public void setUp() throws ServiceException, IOException, DocumentException, ConfigException {
TestUtil.setLCValue(LC.imap_always_use_remote_store, String.valueOf(false));
imapServer.setReverseProxyUpstreamImapServers(new String[] {});
super.sharedSetUp();
TestUtil.assumeTrue("local IMAP server is not enabled", imapServer.isImapServerEnabled());
}
@After
public void tearDown() throws ServiceException, DocumentException, ConfigException, IOException {
super.sharedTearDown();
}
@Override
protected int getImapPort() {
return imapServer.getImapBindPort();
}
@Test(timeout=10000)
public void testReallyUsingLocalImap() throws ServiceException {
Account uAcct = TestUtil.getAccount(USER);
assertTrue("Provisioning.canUseLocalIMAP(" + USER + ")", Provisioning.canUseLocalIMAP(uAcct));
}
}
|
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* 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.intellij.codeInsight.intention;
import com.intellij.codeInsight.intention.impl.BaseIntentionAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* @author Danila Ponomarenko
*/
public abstract class BaseElementAtCaretIntentionAction extends BaseIntentionAction {
private volatile boolean useElementToTheLeft;
@Override
public final boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
if (!checkFile(file)) return false;
useElementToTheLeft = false;
final PsiElement elementToTheRight = getElementToTheRight(editor, file);
if (elementToTheRight != null && isAvailable(project, editor, elementToTheRight)) {
return true;
}
final PsiElement elementToTheLeft = getElementToTheLeft(editor, file);
if (elementToTheLeft != null && isAvailable(project, editor, elementToTheLeft)) {
useElementToTheLeft = true;
return true;
}
return false;
}
protected boolean checkFile(@NotNull PsiFile file) {
return canModify(file);
}
/**
* Checks whether this intention is available at a caret offset in file.
* If this method returns true, a light bulb for this intention is shown.
*
* @param project the project in which the availability is checked.
* @param editor the editor in which the intention will be invoked.
* @param element the element under caret.
* @return true if the intention is available, false otherwise.
*/
public abstract boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element);
@Override
public final void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
final PsiElement element = useElementToTheLeft ? getElementToTheLeft(editor, file) : getElementToTheRight(editor,file);
if (element == null){
return;
}
invoke(project, editor, element);
}
/**
* Invokes intention action for the element under cursor.
*
* @param project the project in which the file is opened.
* @param editor the editor for the file.
* @param element the element under cursor.
* @throws IncorrectOperationException
*/
public abstract void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException;
@Nullable
protected static PsiElement getElementToTheRight(Editor editor, @NotNull PsiFile file) {
return file.findElementAt(editor.getCaretModel().getOffset());
}
@Nullable
protected static PsiElement getElementToTheLeft(Editor editor, @NotNull PsiFile file) {
return file.findElementAt(editor.getCaretModel().getOffset() - 1);
}
}
|
package com.picard.community.community.controller.interceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class AlphaInterceptor implements HandlerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(AlphaInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
logger.debug("preHandle: "+handler.toString());
return true;
}
//controller 之后执行
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
logger.debug("postHandler: "+handler.toString());
}
//templateEngine之后执行
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
logger.debug("afterCompletion: "+handler.toString());
}
}
|
package frc.robot.commands.drivetrain;
import frc.robot.subsystems.Drivetrain;
import frc.robot.subsystems.Shooter;
import harkerrobolib.commands.IndefiniteCommand;
import harkerrobolib.util.MathUtil;
import frc.robot.util.Limelight;
import edu.wpi.first.wpilibj.controller.PIDController;
import edu.wpi.first.wpilibj.geometry.Rotation2d;
import edu.wpi.first.wpilibj.kinematics.ChassisSpeeds;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import frc.robot.OI;
import frc.robot.RobotMap;
public class SwerveManual extends IndefiniteCommand {
private static final double OUTPUT_MULTIPLIER= 1;
private static final double kP=0.03;
private static final double kI=0.0;//00002;
private static final double kD=0.0;//02;
private static final double TX_SETPOINT=0;
private static final double I_ZONE = 0;
private static final double angleKP=1;
private static double pigeonAngle=Drivetrain.getInstance().getPigeon().getFusedHeading();
private PIDController pid;
public SwerveManual() {
addRequirements(Drivetrain.getInstance());
pid = new PIDController(kP, kI, kD);
pid.setIntegratorRange(-I_ZONE, I_ZONE);
}
@Override
public void execute() {
double angularVelocity = MathUtil.mapJoystickOutput(OI.getInstance().getDriverGamepad().getRightX(), OI.DEADBAND);
double translationx = MathUtil.mapJoystickOutput(OI.getInstance().getDriverGamepad().getLeftX(), OI.DEADBAND);
double translationy = MathUtil.mapJoystickOutput(OI.getInstance().getDriverGamepad().getLeftY(), OI.DEADBAND);
double chasisMagnitude=Math.sqrt(translationx*translationx + translationy*translationy);
if(chasisMagnitude<(Drivetrain.MIN_OUTPUT)){
translationx=0;
translationy=0;
if(Math.abs(angularVelocity)<(Drivetrain.MIN_OUTPUT)){
angularVelocity=0.01;}
}
if(OI.getInstance().getDriverGamepad().getButtonBumperRightState()){
angularVelocity = -pid.calculate(Limelight.getTx(), TX_SETPOINT);
}
if(OI.getInstance().getDriverGamepad().getButtonBState() || OI.getInstance().getOperatorGamepad().getButtonBState()){
Shooter.getInstance().setAutoHoodAngle();
}
angularVelocity *= Drivetrain.MAX_ANGULAR_VEL;
SmartDashboard.putNumber("limelight tx", Limelight.getTx());
SmartDashboard.putNumber("limelight ang vel", angularVelocity);
translationx *= Drivetrain.MAX_DRIVE_VEL * OUTPUT_MULTIPLIER;
translationy *= Drivetrain.MAX_DRIVE_VEL * OUTPUT_MULTIPLIER;
if (OI.getInstance().getDriverGamepad().getButtonBumperLeftState()) {
translationx *= 0.4;
translationy *= 0.4;
}
if(RobotMap.DEMO_MODE && !(OI.getInstance().getDriverGamepad().getButtonBumperLeftState() && OI.getInstance().getDriverGamepad().getButtonBumperRightState())){
translationx *= 0.3;
translationy *= 0.3;
}
// System.out.println(translationx + " " + translationy);
// double rotation =
// MathUtil.mapJoystickOutput(OI.getInstance().getDriverGamepad().getRightX(),
// OI.DEADBAND);
// if(Math.abs(MathUtil.mapJoystickOutput(OI.getInstance().getDriverGamepad().getRightX(), OI.DEADBAND))<0.05){
// angularVelocity=angleKP*(pigeonAngle - Drivetrain.getInstance().getPigeon().getFusedHeading());
// }
pigeonAngle=Drivetrain.getInstance().getPigeon().getFusedHeading();
ChassisSpeeds chassis = ChassisSpeeds.fromFieldRelativeSpeeds(translationx, translationy, -angularVelocity, new Rotation2d(Math.toRadians(Drivetrain.getInstance().getPigeon().getFusedHeading())));
Drivetrain.getInstance().setAngleAndDriveVelocity(Drivetrain.getInstance().getKinematics().toSwerveModuleStates(chassis));
}
}
|
package com.jxd.android.bookinventtory.main;
import dagger.Module;
/**
* Created by jinxiangdong on 2017/10/22.
*/
@Module
public class MainModule {
}
|
package pack.man;
import pack.*;
public class StarImporter {
DingsDa dida;
Referer ref;
Namesake ns;
}
|
package md5530bd51e982e6e7b340b73e88efe666e;
public class DatePickerRenderer_TextFieldClickHandler
extends java.lang.Object
implements
mono.android.IGCUserPeer,
android.view.View.OnClickListener
{
static final String __md_methods;
static {
__md_methods =
"n_onClick:(Landroid/view/View;)V:GetOnClick_Landroid_view_View_Handler:Android.Views.View/IOnClickListenerInvoker, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\n" +
"";
mono.android.Runtime.register ("Xamarin.Forms.Platform.Android.DatePickerRenderer/TextFieldClickHandler, Xamarin.Forms.Platform.Android, Version=1.4.0.0, Culture=neutral, PublicKeyToken=null", DatePickerRenderer_TextFieldClickHandler.class, __md_methods);
}
public DatePickerRenderer_TextFieldClickHandler () throws java.lang.Throwable
{
super ();
if (getClass () == DatePickerRenderer_TextFieldClickHandler.class)
mono.android.TypeManager.Activate ("Xamarin.Forms.Platform.Android.DatePickerRenderer/TextFieldClickHandler, Xamarin.Forms.Platform.Android, Version=1.4.0.0, Culture=neutral, PublicKeyToken=null", "", this, new java.lang.Object[] { });
}
public void onClick (android.view.View p0)
{
n_onClick (p0);
}
private native void n_onClick (android.view.View p0);
java.util.ArrayList refList;
public void monodroidAddReference (java.lang.Object obj)
{
if (refList == null)
refList = new java.util.ArrayList ();
refList.add (obj);
}
public void monodroidClearReferences ()
{
if (refList != null)
refList.clear ();
}
}
|
/**
*
*/
package com.smthit.framework.dal;
import org.beetl.sql.core.TailBean;
import com.smthit.framework.dal.bettlsql.convert.BeetlTailReformer;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
/**
* @author Bean
*
*/
public class BeetlTailReformerTest {
/**
* @param args
*/
public static void main(String[] args) {
TestPO po = new TestPO();
po.setStr("测试1");
po.setVal(1);
po.setVal2(2L);
po.set("bell_department", "技术一部");
TestVO vo = new BeetlTailReformer<TestPO, TestVO>(TestVO.class).toVO(po);
System.out.println(vo);
}
@Data
@EqualsAndHashCode(callSuper = true)
@ToString
public static class TestPO extends TailBean {
private static final long serialVersionUID = -6020275921087067503L;
private String str;
private Integer val;
private Long val2;
}
@Data
@EqualsAndHashCode(callSuper = true)
@ToString
public static class TestVO extends TailBean {
private static final long serialVersionUID = -6020275921087067503L;
private String str;
private Integer val;
private Long val2;
private String bellDepartment;
}
}
|
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.bazel.rules.java;
import static com.google.devtools.build.lib.packages.Attribute.attr;
import static com.google.devtools.build.lib.packages.BuildType.LABEL;
import static com.google.devtools.build.lib.packages.BuildType.LABEL_LIST;
import static com.google.devtools.build.lib.packages.BuildType.TRISTATE;
import static com.google.devtools.build.lib.packages.ImplicitOutputsFunction.fromFunctions;
import static com.google.devtools.build.lib.rules.java.JavaRuleClasses.CONTAINS_JAVA_PROVIDER;
import static com.google.devtools.build.lib.syntax.Type.BOOLEAN;
import static com.google.devtools.build.lib.syntax.Type.STRING;
import static com.google.devtools.build.lib.syntax.Type.STRING_LIST;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.analysis.BaseRuleClasses;
import com.google.devtools.build.lib.analysis.RuleDefinition;
import com.google.devtools.build.lib.analysis.RuleDefinitionEnvironment;
import com.google.devtools.build.lib.analysis.config.HostTransition;
import com.google.devtools.build.lib.bazel.rules.cpp.BazelCppRuleClasses.CcToolchainRequiringRule;
import com.google.devtools.build.lib.packages.Attribute;
import com.google.devtools.build.lib.packages.AttributeMap;
import com.google.devtools.build.lib.packages.ImplicitOutputsFunction;
import com.google.devtools.build.lib.packages.PredicateWithMessage;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.packages.RuleClass;
import com.google.devtools.build.lib.packages.RuleClass.Builder.RuleClassType;
import com.google.devtools.build.lib.packages.RuleClass.PackageNameConstraint;
import com.google.devtools.build.lib.packages.SkylarkProviderIdentifier;
import com.google.devtools.build.lib.packages.TriState;
import com.google.devtools.build.lib.rules.cpp.CcInfo;
import com.google.devtools.build.lib.rules.java.JavaInfo;
import com.google.devtools.build.lib.rules.java.JavaRuleClasses.IjarBaseRule;
import com.google.devtools.build.lib.rules.java.JavaRuleClasses.JavaRuntimeBaseRule;
import com.google.devtools.build.lib.rules.java.JavaSemantics;
import com.google.devtools.build.lib.syntax.Type;
import com.google.devtools.build.lib.util.FileTypeSet;
/**
* Rule class definitions for Java rules.
*/
public class BazelJavaRuleClasses {
public static final PredicateWithMessage<Rule> JAVA_PACKAGE_NAMES = new PackageNameConstraint(
PackageNameConstraint.ANY_SEGMENT, "java", "javatests");
protected static final String JUNIT_TESTRUNNER = "//tools/jdk:TestRunner";
protected static final String EXPERIMENTAL_TESTRUNNER = "//tools/jdk:ExperimentalTestRunner";
public static final ImplicitOutputsFunction JAVA_BINARY_IMPLICIT_OUTPUTS =
fromFunctions(
JavaSemantics.JAVA_BINARY_CLASS_JAR,
JavaSemantics.JAVA_BINARY_SOURCE_JAR,
JavaSemantics.JAVA_BINARY_DEPLOY_JAR,
JavaSemantics.JAVA_BINARY_DEPLOY_SOURCE_JAR);
static final ImplicitOutputsFunction JAVA_LIBRARY_IMPLICIT_OUTPUTS =
fromFunctions(
JavaSemantics.JAVA_LIBRARY_CLASS_JAR,
JavaSemantics.JAVA_LIBRARY_SOURCE_JAR);
public static final ImmutableList<SkylarkProviderIdentifier> CONTAINS_CC_LINK_PARAMS =
ImmutableList.of(SkylarkProviderIdentifier.forKey(CcInfo.PROVIDER.getKey()));
/**
* Meant to be the value of {@code mandatoryProvidersLists} in order for the rule to provide only
* a {@link JavaInfo} through an attribute.
*/
public static final ImmutableList<ImmutableList<SkylarkProviderIdentifier>>
MANDATORY_JAVA_PROVIDER_ONLY = ImmutableList.of(CONTAINS_JAVA_PROVIDER);
/**
* Common attributes for Java rules.
*/
public static final class JavaBaseRule implements RuleDefinition {
@Override
public RuleClass build(RuleClass.Builder builder, RuleDefinitionEnvironment env) {
return builder.build();
}
@Override
public Metadata getMetadata() {
return RuleDefinition.Metadata.builder()
.name("$java_base_rule")
.type(RuleClassType.ABSTRACT)
.ancestors(IjarBaseRule.class, JavaRuntimeBaseRule.class)
.build();
}
}
static final ImmutableSet<String> ALLOWED_RULES_IN_DEPS =
ImmutableSet.of(
"cc_binary", // NB: linkshared=1
"cc_library",
"genrule",
"genproto", // TODO(bazel-team): we should filter using providers instead (skylark rule).
"java_import",
"java_library",
"java_proto_library",
"java_lite_proto_library",
"proto_library",
"sh_binary",
"sh_library");
/**
* Common attributes for Java rules.
*/
public static final class JavaRule implements RuleDefinition {
@Override
public RuleClass build(RuleClass.Builder builder, RuleDefinitionEnvironment env) {
return builder
/* <!-- #BLAZE_RULE($java_rule).ATTRIBUTE(deps) -->
The list of other libraries to be linked in to the target.
See general comments about <code>deps</code> at
<a href="common-definitions.html#common-attributes">Attributes common to all build rules
</a>.
<!-- #END_BLAZE_RULE.ATTRIBUTE --> */
.override(
builder
.copy("deps")
.allowedFileTypes(JavaSemantics.JAR)
.allowedRuleClasses(ALLOWED_RULES_IN_DEPS)
.mandatoryProvidersList(
ImmutableList.of(CONTAINS_CC_LINK_PARAMS, CONTAINS_JAVA_PROVIDER))
.skipAnalysisTimeFileTypeCheck())
/* <!-- #BLAZE_RULE($java_rule).ATTRIBUTE(runtime_deps) -->
Libraries to make available to the final binary or test at runtime only.
Like ordinary <code>deps</code>, these will appear on the runtime classpath, but unlike
them, not on the compile-time classpath. Dependencies needed only at runtime should be
listed here. Dependency-analysis tools should ignore targets that appear in both
<code>runtime_deps</code> and <code>deps</code>.
<!-- #END_BLAZE_RULE.ATTRIBUTE --> */
.add(
attr("runtime_deps", LABEL_LIST)
.allowedFileTypes(JavaSemantics.JAR)
.allowedRuleClasses(ALLOWED_RULES_IN_DEPS)
.mandatoryProvidersList(MANDATORY_JAVA_PROVIDER_ONLY)
.skipAnalysisTimeFileTypeCheck())
/* <!-- #BLAZE_RULE($java_rule).ATTRIBUTE(srcs) -->
The list of source files that are processed to create the target.
This attribute is almost always required; see exceptions below.
<p>
Source files of type <code>.java</code> are compiled. In case of generated
<code>.java</code> files it is generally advisable to put the generating rule's name
here instead of the name of the file itself. This not only improves readability but
makes the rule more resilient to future changes: if the generating rule generates
different files in the future, you only need to fix one place: the <code>outs</code> of
the generating rule. You should not list the generating rule in <code>deps</code>
because it is a no-op.
</p>
<p>
Source files of type <code>.srcjar</code> are unpacked and compiled. (This is useful if
you need to generate a set of <code>.java</code> files with a genrule.)
</p>
<p>
Rules: if the rule (typically <code>genrule</code> or <code>filegroup</code>) generates
any of the files listed above, they will be used the same way as described for source
files.
</p>
<p>
This argument is almost always required, except if a
<a href="#java_binary.main_class"><code>main_class</code></a> attribute specifies a
class on the runtime classpath or you specify the <code>runtime_deps</code> argument.
</p>
<!-- #END_BLAZE_RULE.ATTRIBUTE --> */
.add(
attr("srcs", LABEL_LIST)
.orderIndependent()
.direct_compile_time_input()
.allowedFileTypes(
JavaSemantics.JAVA_SOURCE,
JavaSemantics.SOURCE_JAR,
JavaSemantics.PROPERTIES))
/* <!-- #BLAZE_RULE($java_rule).ATTRIBUTE(resources) -->
A list of data files to include in a Java jar.
<p>
If resources are specified, they will be bundled in the jar along with the usual
<code>.class</code> files produced by compilation. The location of the resources inside
of the jar file is determined by the project structure. Bazel first looks for Maven's
<a href="https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html">standard directory layout</a>,
(a "src" directory followed by a "resources" directory grandchild). If that is not
found, Bazel then looks for the topmost directory named "java" or "javatests" (so, for
example, if a resource is at <code><workspace root>/x/java/y/java/z</code>, the
path of the resource will be <code>y/java/z</code>. This heuristic cannot be overridden.
</p>
<p>
Resources may be source files or generated files.
</p>
<!-- #END_BLAZE_RULE.ATTRIBUTE --> */
.add(
attr("resources", LABEL_LIST)
.orderIndependent()
.allowedFileTypes(FileTypeSet.ANY_FILE)
.dontCheckConstraints())
/* <!-- #BLAZE_RULE($java_rule).ATTRIBUTE(resource_strip_prefix) -->
The path prefix to strip from Java resources.
<p>
If specified, this path prefix is stripped from every file in the <code>resources</code>
attribute. It is an error for a resource file not to be under this directory. If not
specified (the default), the path of resource file is determined according to the same
logic as the Java package of source files. For example, a source file at
<code>stuff/java/foo/bar/a.txt</code> will be located at <code>foo/bar/a.txt</code>.
</p>
<!-- #END_BLAZE_RULE.ATTRIBUTE --> */
.add(attr("resource_strip_prefix", STRING))
/* <!-- #BLAZE_RULE($java_rule).ATTRIBUTE(resource_jars) -->
Set of archives containing Java resources.
<p>
If specified, the contents of these jars are merged into the output jar.
</p>
<!-- #END_BLAZE_RULE.ATTRIBUTE --> */
.add(
attr("resource_jars", LABEL_LIST)
.orderIndependent()
.allowedFileTypes(JavaSemantics.JAR))
/* <!-- #BLAZE_RULE($java_rule).ATTRIBUTE(plugins) -->
Java compiler plugins to run at compile-time.
Every <code>java_plugin</code> specified in this attribute will be run whenever this rule
is built. A library may also inherit plugins from dependencies that use
<code><a href="#java_library.exported_plugins">exported_plugins</a></code>. Resources
generated by the plugin will be included in the resulting jar of this rule.
<!-- #END_BLAZE_RULE.ATTRIBUTE --> */
.add(
attr("plugins", LABEL_LIST)
.cfg(HostTransition.createFactory())
.allowedRuleClasses("java_plugin")
.legacyAllowAnyFileType())
.add(
attr(":java_plugins", LABEL_LIST)
.cfg(HostTransition.createFactory())
.allowedRuleClasses("java_plugin")
.silentRuleClassFilter()
.value(JavaSemantics.JAVA_PLUGINS))
/* <!-- #BLAZE_RULE($java_rule).ATTRIBUTE(javacopts) -->
Extra compiler options for this library.
Subject to <a href="make-variables.html">"Make variable"</a> substitution and
<a href="common-definitions.html#sh-tokenization">Bourne shell tokenization</a>.
<p>These compiler options are passed to javac after the global compiler options.</p>
<!-- #END_BLAZE_RULE.ATTRIBUTE --> */
.add(attr("javacopts", STRING_LIST))
.build();
}
@Override
public Metadata getMetadata() {
return RuleDefinition.Metadata.builder()
.name("$java_rule")
.type(RuleClassType.ABSTRACT)
.ancestors(BaseRuleClasses.RuleBase.class, JavaBaseRule.class)
.build();
}
}
/**
* Base class for rule definitions producing Java binaries.
*/
public static final class BaseJavaBinaryRule implements RuleDefinition {
@Override
public RuleClass build(RuleClass.Builder builder, final RuleDefinitionEnvironment env) {
return builder
/* <!-- #BLAZE_RULE($base_java_binary).ATTRIBUTE(classpath_resources) -->
<em class="harmful">DO NOT USE THIS OPTION UNLESS THERE IS NO OTHER WAY)</em>
<p>
A list of resources that must be located at the root of the java tree. This attribute's
only purpose is to support third-party libraries that require that their resources be
found on the classpath as exactly <code>"myconfig.xml"</code>. It is only allowed on
binaries and not libraries, due to the danger of namespace conflicts.
</p>
<!-- #END_BLAZE_RULE.ATTRIBUTE --> */
.add(attr("classpath_resources", LABEL_LIST).legacyAllowAnyFileType())
/* <!-- #BLAZE_RULE($base_java_binary).ATTRIBUTE(jvm_flags) -->
A list of flags to embed in the wrapper script generated for running this binary.
Subject to <a href="${link make-variables#location}">$(location)</a> and
<a href="make-variables.html">"Make variable"</a> substitution, and
<a href="common-definitions.html#sh-tokenization">Bourne shell tokenization</a>.
<p>The wrapper script for a Java binary includes a CLASSPATH definition
(to find all the dependent jars) and invokes the right Java interpreter.
The command line generated by the wrapper script includes the name of
the main class followed by a <code>"$@"</code> so you can pass along other
arguments after the classname. However, arguments intended for parsing
by the JVM must be specified <i>before</i> the classname on the command
line. The contents of <code>jvm_flags</code> are added to the wrapper
script before the classname is listed.</p>
<p>Note that this attribute has <em>no effect</em> on <code>*_deploy.jar</code>
outputs.</p>
<!-- #END_BLAZE_RULE.ATTRIBUTE --> */
.add(attr("jvm_flags", STRING_LIST))
/* <!-- #BLAZE_RULE($base_java_binary).ATTRIBUTE(use_testrunner) -->
Use the test runner (by default
<code>com.google.testing.junit.runner.BazelTestRunner</code>) class as the
main entry point for a Java program, and provide the test class
to the test runner as a value of <code>bazel.test_suite</code>
system property.
You can use this to override the default
behavior, which is to use test runner for
<code>java_test</code> rules,
and not use it for <code>java_binary</code> rules. It is unlikely
you will want to do this. One use is for <code>AllTest</code>
rules that are invoked by another rule (to set up a database
before running the tests, for example). The <code>AllTest</code>
rule must be declared as a <code>java_binary</code>, but should
still use the test runner as its main entry point.
The name of a test runner class can be overridden with <code>main_class</code> attribute.
<!-- #END_BLAZE_RULE.ATTRIBUTE --> */
.add(attr("use_testrunner", BOOLEAN).value(false))
/* <!-- #BLAZE_RULE($base_java_binary).ATTRIBUTE(main_class) -->
Name of class with <code>main()</code> method to use as entry point.
If a rule uses this option, it does not need a <code>srcs=[...]</code> list.
Thus, with this attribute one can make an executable from a Java library that already
contains one or more <code>main()</code> methods.
<p>
The value of this attribute is a class name, not a source file. The class must be
available at runtime: it may be compiled by this rule (from <code>srcs</code>) or
provided by direct or transitive dependencies (through <code>runtime_deps</code> or
<code>deps</code>). If the class is unavailable, the binary will fail at runtime; there
is no build-time check.
</p>
<!-- #END_BLAZE_RULE.ATTRIBUTE --> */
.add(attr("main_class", STRING))
/* <!-- #BLAZE_RULE($base_java_binary).ATTRIBUTE(create_executable) -->
Whether the binary is executable. Non-executable binaries collect transitive
runtime Java dependencies into a deploy jar, but cannot be executed directly.
No wrapper script is created if this attribute is set. It is an error to set
this to 0 if the <code>launcher</code> or <code>main_class</code> attributes
are set.
<!-- #END_BLAZE_RULE.ATTRIBUTE --> */
.add(attr("create_executable", BOOLEAN).nonconfigurable("internal").value(true))
.add(
attr("$testsupport", LABEL)
.value(
new Attribute.ComputedDefault("use_testrunner") {
@Override
public Object getDefault(AttributeMap rule) {
return rule.get("use_testrunner", Type.BOOLEAN)
? env.getToolsLabel(JUNIT_TESTRUNNER)
: null;
}
}))
.add(
attr("$experimental_testsupport", LABEL)
.value(
new Attribute.ComputedDefault("use_testrunner") {
@Override
public Object getDefault(AttributeMap rule) {
return rule.get("use_testrunner", Type.BOOLEAN)
? env.getToolsLabel(EXPERIMENTAL_TESTRUNNER)
: null;
}
}))
/* <!-- #BLAZE_RULE($base_java_binary).ATTRIBUTE(deploy_manifest_lines) -->
A list of lines to add to the <code>META-INF/manifest.mf</code> file generated for the
<code>*_deploy.jar</code> target. The contents of this attribute are <em>not</em> subject
to <a href="make-variables.html">"Make variable"</a> substitution.
<!-- #END_BLAZE_RULE.ATTRIBUTE --> */
.add(attr("deploy_manifest_lines", STRING_LIST))
/* <!-- #BLAZE_RULE($base_java_binary).ATTRIBUTE(stamp) -->
Enable link stamping.
Whether to encode build information into the binary. Possible values:
<ul>
<li><code>stamp = 1</code>: Stamp the build information into the binary. Stamped
binaries are only rebuilt when their dependencies change. Use this if there are tests
that depend on the build information.</li>
<li><code>stamp = 0</code>: Always replace build information by constant values. This
gives good build result caching.</li>
<li><code>stamp = -1</code>: Embedding of build information is controlled by the
<a href="../user-manual.html#flag--stamp">--[no]stamp</a> flag.</li>
</ul>
<!-- #END_BLAZE_RULE.ATTRIBUTE --> */
// TODO(bazel-team): describe how to access this data at runtime
.add(attr("stamp", TRISTATE).value(TriState.AUTO))
/* <!-- #BLAZE_RULE($base_java_binary).ATTRIBUTE(launcher) -->
Specify a binary that will be used to run your Java program instead of the
normal <code>bin/java</code> program included with the JDK.
The target must be a <code>cc_binary</code>. Any <code>cc_binary</code> that
implements the
<a href="http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/invocation.html">
Java Invocation API</a> can be specified as a value for this attribute.
<p>By default, Bazel will use the normal JDK launcher (bin/java or java.exe).</p>
<p>The related <a href="../user-manual.html#flag--java_launcher"><code>
--java_launcher</code></a> Bazel flag affects only those
<code>java_binary</code> and <code>java_test</code> targets that have
<i>not</i> specified a <code>launcher</code> attribute.</p>
<p>Note that your native (C++, SWIG, JNI) dependencies will be built differently
depending on whether you are using the JDK launcher or another launcher:</p>
<ul>
<li>If you are using the normal JDK launcher (the default), native dependencies are
built as a shared library named <code>{name}_nativedeps.so</code>, where
<code>{name}</code> is the <code>name</code> attribute of this java_binary rule.
Unused code is <em>not</em> removed by the linker in this configuration.</li>
<li>If you are using any other launcher, native (C++) dependencies are statically
linked into a binary named <code>{name}_nativedeps</code>, where <code>{name}</code>
is the <code>name</code> attribute of this java_binary rule. In this case,
the linker will remove any code it thinks is unused from the resulting binary,
which means any C++ code accessed only via JNI may not be linked in unless
that <code>cc_library</code> target specifies <code>alwayslink = 1</code>.</li>
</ul>
<p>When using any launcher other than the default JDK launcher, the format
of the <code>*_deploy.jar</code> output changes. See the main
<a href="#java_binary">java_binary</a> docs for details.</p>
<!-- #END_BLAZE_RULE.ATTRIBUTE --> */
.add(
attr("launcher", LABEL)
.allowedFileTypes(FileTypeSet.NO_FILE)
.allowedRuleClasses("cc_binary"))
.add(attr(":java_launcher", LABEL).value(JavaSemantics.JAVA_LAUNCHER)) // blaze flag
.add(
attr("$launcher", LABEL)
.cfg(HostTransition.createFactory())
.value(env.getToolsLabel("//tools/launcher:launcher")))
.build();
}
@Override
public Metadata getMetadata() {
return RuleDefinition.Metadata.builder()
.name("$base_java_binary")
.type(RuleClassType.ABSTRACT)
.ancestors(
JavaRule.class,
// java_binary and java_test require the crosstool C++ runtime
// libraries (libstdc++.so, libgcc_s.so).
// TODO(bazel-team): Add tests for Java+dynamic runtime.
CcToolchainRequiringRule.class)
.build();
}
}
}
|
/*
Copyright 1996-2008 Ariba, 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.
$Id: //ariba/platform/util/core/ariba/util/fieldvalue/FieldValue_Object.java#5 $
*/
package ariba.util.fieldvalue;
import ariba.util.core.Fmt;
import ariba.util.core.MultiKeyHashtable;
/**
The FieldValue_Object class extension is the default implementation of the
FieldValue interface. This default implementation is based
on java.lang.reflection primitives and will work for essentailly
all classes. Of course, certain subclasses may desire to alter
the default behavior and, as such, should subclass this class and
override the appropriate methods. For example, a Map
implementation may want to treat the fieldName as a key for get/put
rather than as the name of an instance variable. Some other subclass
may desire to mix and match the two approaches. In any case, these
special cases should be implemented in subclasses of FieldValue_Object.
*/
public class FieldValue_Object extends FieldValue
{
private static final FieldValueAccessor NotFoundAccessor = new NotFoundFieldValueAccessor();
protected final MultiKeyHashtable[] _accessorsHashtable = {
new MultiKeyHashtable(2, 8 , true),
new MultiKeyHashtable(2, 8, true),
};
/**
Creates and returns a new FieldValueAccessor (by default,
a ReflectionFieldValueAccessor) for the given target and fieldName.
No caching is done by this method. This method is designed to be
overridden by subclasses of FieldValue_Object which want to define
their own specialized accessors. Note that the target is passed
rather than its class so that accessors can be created at a finer
granularity than class. Certain meta-data driven classes require
this flexibility.
@param target the object for which the accessor will be created
@param fieldName the name of the field for which the accessor will be created
@param type the type of accessor will be created (either FieldValue.Setter
or FieldValue.Getter)
@return a new FieldValueAccessor (ReflectionFieldValueAccessor by default)
*/
public FieldValueAccessor createAccessor (Object target, String fieldName, int type)
{
FieldValueAccessor accessor = null;
if (fieldName.equals("this")) {
fieldName = "getThis";
}
if (type == Setter) {
accessor = FieldValueAccessorUtil.newReflectionSetter(target.getClass(), fieldName);
}
else {
accessor = FieldValueAccessorUtil.newReflectionGetter(target.getClass(), fieldName);
}
return accessor;
}
/**
Maintains a cache of FieldValueAccessor's for the instance by fieldName.
In general, all instances of a given class will share the same
FieldValueAccessor for a given fieldName. However, certain meta-data
driven classes may need to introspect upon the instance before returning
the proper accessor.
@param target the object for which the accessor will be looked up
@param fieldName the name of the field for the accessor
@param type the type of accessor will be created (either FieldValue.Setter
or FieldValue.Getter)
@return the cached FieldValueAccessor (ReflectionFieldValueAccessor by default)
*/
public FieldValueAccessor getAccessor (Object target, String fieldName, int type)
{
FieldValueAccessor accessor = null;
Class targetObjectClass = target.getClass();
MultiKeyHashtable accessorsHashtable = _accessorsHashtable[type];
synchronized (accessorsHashtable) {
fieldName = fieldName.intern();
accessor = (FieldValueAccessor)accessorsHashtable.get(targetObjectClass,
fieldName);
if (accessor == NotFoundAccessor) {
accessor = null;
}
else if (accessor == null) {
accessor = createAccessor(target, fieldName, type);
accessorsHashtable.put(targetObjectClass, fieldName,
(accessor != null) ? accessor : NotFoundAccessor);
}
}
return accessor;
}
/**
Sets the value on the reveiver using the fieldName indicated by
fieldPath -- only the first node of the fieldPath is considered if it is
a multi-node path.
@param target the object on which the value will be set for the field identiifed by fieldPath
@param fieldPath the fieldPath node (which contains a candidate accessor) to be
used to set the value on target.
@param value the value to set on the target
*/
public void setFieldValuePrimitive (Object target, FieldPath fieldPath, Object value)
{
FieldValueSetter setter = fieldPath._previousSetter;
boolean isAccessorApplicable = (target.getClass() == setter.forClass())
&& setter.isApplicable(target);
if (!isAccessorApplicable) {
setter = (FieldValueSetter)getAccessor(target, fieldPath._fieldName, Setter);
if (setter == null) {
String message = Fmt.S(
"Unable to locate setter method or " +
"field for: \"%s\" on target class: \"%s\"",
fieldPath._fieldName, target.getClass().getName());
throw new FieldValueException(message);
}
fieldPath._previousSetter = setter;
}
setter.setValue(target, value);
}
/**
Gets the value from the reveiver using the fieldName indicated by
fieldPath -- only the first node of the fieldPath is considered if
it is a multi-node path.
@param target the object from which to get the value of the field identified by fieldPath
@param fieldPath the fieldPath node which identifes the field to get.
@return the value obtained from the target using the fieldPath
*/
public Object getFieldValuePrimitive (Object target, FieldPath fieldPath)
{
FieldValueGetter getter = fieldPath._previousGetter;
boolean isAccessorApplicable = (target.getClass() == getter.forClass())
&& getter.isApplicable(target);
if (!isAccessorApplicable) {
getter = (FieldValueGetter)getAccessor(target, fieldPath._fieldName, Getter);
if (getter == null) {
String message = Fmt.S(
"Unable to locate getter method or " +
"field for: \"%s\" on target class: \"%s\"",
fieldPath._fieldName, target.getClass().getName());
throw new FieldValueException(message);
}
fieldPath._previousGetter = getter;
}
return getter.getValue(target);
}
/**
Recursively calls getFieldValuePrimitive() with the head of the fieldPath
list up to the last fieldPath node and then calls setFieldValuePrimitive().
Each time the recursion iterates, the receiver is the value of the
previous getFieldValuePrimitive().
@param target the object on which to start the recursion for setting
the value using the fieldPath
@param fieldPath the linked list of fieldPath nodes used to navigate from
target to the final object in the chain, upon which the value is set
@param value the value which is set on the final object in the chain
*/
public void setFieldValue (Object target,
FieldPath fieldPath, Object value)
{
FieldPath fieldPathCdr = fieldPath._nextFieldPath;
if (fieldPathCdr == null) {
setFieldValuePrimitive(target, fieldPath, value);
}
else {
Object nextTargetObject = getFieldValuePrimitive(target, fieldPath);
if (nextTargetObject != null) {
fieldPathCdr.setFieldValue(nextTargetObject, value);
}
}
}
/**
Recursively calls getFieldValuePrimitive() with the head of the fieldPath list.
Each time the recursion iterates, the receiver is the value of the previous
getFieldValuePrimitive().
@param target the first object from which to start the recursion for getting
the value identified by the fieldPath.
@param fieldPath the linked list of fieldPath nodes that identifes the value to get
@return the value obtained from the last object in the chain
*/
public Object getFieldValue (Object target, FieldPath fieldPath)
{
Object value = getFieldValuePrimitive(target, fieldPath);
FieldPath fieldPathCdr = fieldPath._nextFieldPath;
if (fieldPathCdr != null && value != null) {
value = fieldPathCdr.getFieldValue(value);
}
return value;
}
public void populateFieldInfo (Class targetClass, FieldInfo.Collection collection)
{
Class superCls = targetClass.getSuperclass();
if (superCls != null) populateFieldInfo(superCls, collection);
if (collection.includeFields()) {
FieldValueAccessorUtil.popuplateFromFields(targetClass, collection);
}
FieldValueAccessorUtil.popuplateFromMethods(targetClass, collection);
}
/*
private boolean fieldEqualsExtensionMethod (Field field, Method extensionMethod)
{
String fieldName = field.getName();
String methodName = extensionMethod.getName();
return FieldValueAccessorUtil.matchForSetter(fieldName, methodName) ||
FieldValueAccessorUtil.matchForGetter(fieldName, methodName);
}
protected void checkForCollisions (Class otherClass)
{
Method[] extensionMethods = getClass().getMethods();
Field[] otherFields = otherClass.getDeclaredFields();
for (int index = extensionMethods.length - 1; index > -1; index--) {
Method currentExtensionMethod = extensionMethods[index];
for (int otherIndex = otherFields.length - 1; otherIndex > - 1; otherIndex--) {
Field otherField = otherFields[otherIndex];
if (fieldEqualsExtensionMethod(otherField, currentExtensionMethod)) {
String message = Fmt.S(
"ClassExtension/Field collision between: " +
"%s/%s and %s/%s.",
getClass(), currentExtensionMethod, otherClass, otherField);
throw new RuntimeException(message);
}
}
}
super.checkForCollisions(otherClass);
}
*/
}
/**
A dummy/marker class used to maintain a negative cache for accessors which are not
found.
*/
class NotFoundFieldValueAccessor extends BaseAccessor
{
public NotFoundFieldValueAccessor ()
{
super(Object.class, "NotFound");
}
public Object getValue (Object target){return null;}
public void setValue (Object target, Object value){}
}
|
package com.coolweather.android;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.coolweather.android.db.City;
import com.coolweather.android.db.County;
import com.coolweather.android.db.Province;
import com.coolweather.android.util.HttpUtil;
import com.coolweather.android.util.Utility;
import org.litepal.crud.DataSupport;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
/**
* Created by lenovo on 2017/7/29.
*/
public class ChooseAreaFragment extends Fragment {
public static final int LEVEL_PROVINCE = 0;
public static final int LEVEL_CITY = 1;
public static final int LEVEL_COUNTY = 2;
private ProgressDialog progressDialog;
private TextView titleText;
private Button backButton;
public ListView listView;
private ArrayAdapter<String> adapter;
private List<String> dataList = new ArrayList<>();
/**
* 省列表
*/
private List<Province> provinceList;
/**
* 市列表
*/
private List<City> cityList;
/**
* 县列表
*/
private List<County> countyList;
/**
* 选中的省份
*/
private Province selectedProvince;
/**
* 选中的城市
*/
private City selectedCity;
/**
* 当前选中的级别
*/
private int currentLevel;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.choose_area, container, false);
titleText = view.findViewById(R.id.title_text);
backButton = view.findViewById(R.id.back_button);
listView = view.findViewById(R.id.list_view);
adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, dataList);
/*getContext()是Android 6.0 以上版本的;在我的手机中没法测试;因此选择getActivity() */
listView.setAdapter(adapter);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView.setOnItemClickListener((parent, view, position, id) -> {
if (currentLevel == LEVEL_PROVINCE) {
selectedProvince = provinceList.get(position);
queryCities();
} else if (currentLevel == LEVEL_CITY) {
selectedCity = cityList.get(position);
queryCounties();
} else if (currentLevel == LEVEL_COUNTY) {/*显示天气数据时加的*/
String weatherId = countyList.get(position).getWeatherId();
if (getActivity() instanceof MainActivity) {
Intent intent = new Intent(getActivity(), WeatherActivity.class);
intent.putExtra("weather_id", weatherId);
startActivity(intent);
getActivity().finish();
} else if (getActivity() instanceof WeatherActivity) {
WeatherActivity activity = (WeatherActivity) getActivity();
activity.drawerLayout.closeDrawers();
activity.swipeRefresh.setRefreshing(true);
activity.requestWeather(weatherId);
}
}
});
backButton.setOnClickListener(v -> {
if (currentLevel == LEVEL_COUNTY) {
queryCities();
} else if (currentLevel == LEVEL_CITY) {
queryProvinces();
}
});
queryProvinces();
}
/**
* 查询全国所有的省,优先从数据库查询,如果没有查询到再去服务器查询
*/
private void queryProvinces() {
titleText.setText("中国");
backButton.setVisibility(View.GONE);
provinceList = DataSupport.findAll(Province.class);
if (provinceList.size() > 0) {
dataList.clear();
for (Province province : provinceList) {
dataList.add(province.getProvinceName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_PROVINCE;
} else {
String address = "http://guolin.tech/api/china";
queryFromServer(address, "province");
}
}
/**
* 查询选中的省份内所有的市,优先从数据库查询,如果没有查询到再去服务器上查询
*/
private void queryCities() {
titleText.setText(selectedProvince.getProvinceName());
backButton.setVisibility(View.VISIBLE);
cityList = DataSupport.where("provinceid = ?", String.valueOf(selectedProvince.getId())).find(City.class);
if (cityList.size() > 0) {
dataList.clear();
for (City city : cityList) {
dataList.add(city.getCityName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_CITY;
} else {
int provinceCode = selectedProvince.getProvinceCode();
String address = "http://guolin.tech/api/china/" + provinceCode;
queryFromServer(address, "city");
}
}
/**
* 查询选中市内所有的县,优先从数据库查询,如果没有查询到再去服务器上查询
*/
private void queryCounties() {
titleText.setText(selectedCity.getCityName());
backButton.setVisibility(View.VISIBLE);
countyList = DataSupport.where("cityid = ?", String.valueOf(selectedCity.getId())).find(County.class);
if (countyList.size() > 0) {
dataList.clear();
for (County county : countyList) {
dataList.add(county.getCountyName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_COUNTY;
} else {
int provinceCode = selectedProvince.getProvinceCode();
int cityCode = selectedCity.getCityCode();
String address = "http://guolin.tech/api/china/" + provinceCode + "/" + cityCode;
queryFromServer(address, "county");
}
}
/**
* 根据传入的地址和类型从服务器上查询省市县数据
*/
private void queryFromServer(String address, final String type) {
showProgressDialog();
HttpUtil.sendOkHttpRequest(address, new Callback() {
@Override
public void onResponse(@SuppressWarnings("NullableProblems") Call call, @SuppressWarnings("NullableProblems") Response response) throws IOException {
String responseText = Objects.requireNonNull(response.body()).string();
boolean result = false;
if ("province".equals(type)) {
result = Utility.handleProvinceResponse(responseText);
} else if ("city".equals(type)) {
result = Utility.handleCityResponse(responseText, selectedProvince.getId());
} else if ("county".equals(type)) {
result = Utility.handleCountyResponse(responseText, selectedCity.getId());
}
if (result) {
getActivity().runOnUiThread(() -> {
closeProgressDialog();
switch (type) {
case "province":
queryProvinces();
break;
case "city":
queryCities();
break;
case "county":
queryCounties();
break;
}
});
}
}
@SuppressWarnings("NullableProblems")
@Override
public void onFailure(Call call, IOException e) {
//通过runOnUiThread()方法回到主线程处理逻辑
getActivity().runOnUiThread(() -> {
closeProgressDialog();
Toast.makeText(getActivity(), "加载失败", Toast.LENGTH_SHORT).show();
/*getContext()是Android 6.0 以上版本的;在我的手机中没法测试;因此选择getActivity() */
});
}
});
}
/**
* 显示进度对话框
*/
private void showProgressDialog() {
if (progressDialog == null) {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("正在加载...");
progressDialog.setCanceledOnTouchOutside(false);
}
progressDialog.show();
}
/**
* 关闭进度对话框
*/
private void closeProgressDialog() {
if (progressDialog != null) {
progressDialog.dismiss();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.