text
stringlengths 7
1.01M
|
|---|
package weixin.popular.bean.paymch;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import com.alibaba.fastjson.JSON;
public class MicropayPromotionDetailXmlAdapter extends XmlAdapter<String, MicropayPromotionDetail> {
@Override
public MicropayPromotionDetail unmarshal(String v) throws Exception {
return JSON.parseObject(v, MicropayPromotionDetail.class);
}
@Override
public String marshal(MicropayPromotionDetail v) throws Exception {
return "<![CDATA[" + JSON.toJSONString(v) + "]]>";
}
}
|
/*
* Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.lightsail.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateInstanceSnapshot" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateInstanceSnapshotRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The name for your new snapshot.
* </p>
*/
private String instanceSnapshotName;
/**
* <p>
* The Lightsail instance on which to base your snapshot.
* </p>
*/
private String instanceName;
/**
* <p>
* The tag keys and optional values to add to the resource during create.
* </p>
* <p>
* Use the <code>TagResource</code> action to tag a resource after it's created.
* </p>
*/
private java.util.List<Tag> tags;
/**
* <p>
* The name for your new snapshot.
* </p>
*
* @param instanceSnapshotName
* The name for your new snapshot.
*/
public void setInstanceSnapshotName(String instanceSnapshotName) {
this.instanceSnapshotName = instanceSnapshotName;
}
/**
* <p>
* The name for your new snapshot.
* </p>
*
* @return The name for your new snapshot.
*/
public String getInstanceSnapshotName() {
return this.instanceSnapshotName;
}
/**
* <p>
* The name for your new snapshot.
* </p>
*
* @param instanceSnapshotName
* The name for your new snapshot.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateInstanceSnapshotRequest withInstanceSnapshotName(String instanceSnapshotName) {
setInstanceSnapshotName(instanceSnapshotName);
return this;
}
/**
* <p>
* The Lightsail instance on which to base your snapshot.
* </p>
*
* @param instanceName
* The Lightsail instance on which to base your snapshot.
*/
public void setInstanceName(String instanceName) {
this.instanceName = instanceName;
}
/**
* <p>
* The Lightsail instance on which to base your snapshot.
* </p>
*
* @return The Lightsail instance on which to base your snapshot.
*/
public String getInstanceName() {
return this.instanceName;
}
/**
* <p>
* The Lightsail instance on which to base your snapshot.
* </p>
*
* @param instanceName
* The Lightsail instance on which to base your snapshot.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateInstanceSnapshotRequest withInstanceName(String instanceName) {
setInstanceName(instanceName);
return this;
}
/**
* <p>
* The tag keys and optional values to add to the resource during create.
* </p>
* <p>
* Use the <code>TagResource</code> action to tag a resource after it's created.
* </p>
*
* @return The tag keys and optional values to add to the resource during create.</p>
* <p>
* Use the <code>TagResource</code> action to tag a resource after it's created.
*/
public java.util.List<Tag> getTags() {
return tags;
}
/**
* <p>
* The tag keys and optional values to add to the resource during create.
* </p>
* <p>
* Use the <code>TagResource</code> action to tag a resource after it's created.
* </p>
*
* @param tags
* The tag keys and optional values to add to the resource during create.</p>
* <p>
* Use the <code>TagResource</code> action to tag a resource after it's created.
*/
public void setTags(java.util.Collection<Tag> tags) {
if (tags == null) {
this.tags = null;
return;
}
this.tags = new java.util.ArrayList<Tag>(tags);
}
/**
* <p>
* The tag keys and optional values to add to the resource during create.
* </p>
* <p>
* Use the <code>TagResource</code> action to tag a resource after it's created.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setTags(java.util.Collection)} or {@link #withTags(java.util.Collection)} if you want to override the
* existing values.
* </p>
*
* @param tags
* The tag keys and optional values to add to the resource during create.</p>
* <p>
* Use the <code>TagResource</code> action to tag a resource after it's created.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateInstanceSnapshotRequest withTags(Tag... tags) {
if (this.tags == null) {
setTags(new java.util.ArrayList<Tag>(tags.length));
}
for (Tag ele : tags) {
this.tags.add(ele);
}
return this;
}
/**
* <p>
* The tag keys and optional values to add to the resource during create.
* </p>
* <p>
* Use the <code>TagResource</code> action to tag a resource after it's created.
* </p>
*
* @param tags
* The tag keys and optional values to add to the resource during create.</p>
* <p>
* Use the <code>TagResource</code> action to tag a resource after it's created.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateInstanceSnapshotRequest withTags(java.util.Collection<Tag> tags) {
setTags(tags);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getInstanceSnapshotName() != null)
sb.append("InstanceSnapshotName: ").append(getInstanceSnapshotName()).append(",");
if (getInstanceName() != null)
sb.append("InstanceName: ").append(getInstanceName()).append(",");
if (getTags() != null)
sb.append("Tags: ").append(getTags());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof CreateInstanceSnapshotRequest == false)
return false;
CreateInstanceSnapshotRequest other = (CreateInstanceSnapshotRequest) obj;
if (other.getInstanceSnapshotName() == null ^ this.getInstanceSnapshotName() == null)
return false;
if (other.getInstanceSnapshotName() != null && other.getInstanceSnapshotName().equals(this.getInstanceSnapshotName()) == false)
return false;
if (other.getInstanceName() == null ^ this.getInstanceName() == null)
return false;
if (other.getInstanceName() != null && other.getInstanceName().equals(this.getInstanceName()) == false)
return false;
if (other.getTags() == null ^ this.getTags() == null)
return false;
if (other.getTags() != null && other.getTags().equals(this.getTags()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getInstanceSnapshotName() == null) ? 0 : getInstanceSnapshotName().hashCode());
hashCode = prime * hashCode + ((getInstanceName() == null) ? 0 : getInstanceName().hashCode());
hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode());
return hashCode;
}
@Override
public CreateInstanceSnapshotRequest clone() {
return (CreateInstanceSnapshotRequest) super.clone();
}
}
|
package com.habeebcycle.marketplace.security.jwt;
import com.habeebcycle.marketplace.security.CustomUserDetailsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);
@Autowired
private JwtTokenProvider jwtTokenProvider;
@Autowired
private CustomUserDetailsService customUserDetailsService;
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
FilterChain filterChain) throws ServletException, IOException {
try{
String jwt = getJwtFromRequest(httpServletRequest);
if(StringUtils.hasText(jwt) && jwtTokenProvider.validateToken(jwt)){
Long userId = jwtTokenProvider.getUserIdFromJWT(jwt);
UserDetails userDetails = customUserDetailsService.loadUserById(userId);
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities()
);
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
}
}catch (Exception ex){
logger.error("Could not authenticate user. ", ex);
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
private String getJwtFromRequest(HttpServletRequest httpServletRequest){
String bearerToken = httpServletRequest.getHeader("Authorization");
String tokenPrefix = "Bearer ";
if(StringUtils.hasText(bearerToken) && bearerToken.startsWith(tokenPrefix)){
return bearerToken.substring(tokenPrefix.length());
}
return null;
}
}
|
/* ========================================================================= *
* *
* The Apache Software License, Version 1.1 *
* *
* Copyright (c) 1999, 2000, 2001 The Apache Software Foundation. *
* All rights reserved. *
* *
* ========================================================================= *
* *
* Redistribution and use in source and binary forms, with or without modi- *
* fication, are permitted provided that the following conditions are met: *
* *
* 1. Redistributions of source code must retain the above copyright notice *
* notice, this list of conditions and the following disclaimer. *
* *
* 2. 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. *
* *
* 3. The end-user documentation included with the redistribution, if any, *
* must include the following acknowlegement: *
* *
* "This product includes software developed by the Apache Software *
* Foundation <http://www.apache.org/>." *
* *
* Alternately, this acknowlegement may appear in the software itself, if *
* and wherever such third-party acknowlegements normally appear. *
* *
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software *
* Foundation" must not be used to endorse or promote products derived *
* from this software without prior written permission. For written *
* permission, please contact <apache@apache.org>. *
* *
* 5. Products derived from this software may not be called "Apache" nor may *
* "Apache" appear in their names without prior written permission of the *
* Apache Software Foundation. *
* *
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR ITS 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. *
* *
* ========================================================================= *
* *
* This software consists of voluntary contributions made by many indivi- *
* duals on behalf of the Apache Software Foundation. For more information *
* on the Apache Software Foundation, please see <http://www.apache.org/>. *
* *
* ========================================================================= */
package org.apache.tester;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* Exercise basic including functionality.
*
* @author Craig R. McClanahan
* @version $Revision: 1.1 $ $Date: 2001/05/03 23:06:31 $
*/
public class Include00a extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// Prepare this response
StringBuffer sb = new StringBuffer();
response.setContentType("text/plain");
PrintWriter writer = response.getWriter();
// Write our response if an error occurred
writer.print("Include00a PASSED");
while (true) {
String message = StaticLogger.read();
if (message == null)
break;
writer.println(message);
}
StaticLogger.reset();
}
}
|
package ru.stqa.pft.addressbook.generators;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.thoughtworks.xstream.XStream;
import ru.stqa.pft.addressbook.model.GroupData;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
public class GroupDataGenerator {
@Parameter(names = "-c", description = "Group count")
public int count;
@Parameter(names = "-f", description = "Target file")
public String file;
@Parameter(names ="-d", description = "Data format")
public String format;
public static void main(String[] args) throws IOException {
GroupDataGenerator generator = new GroupDataGenerator();
JCommander jCommander = new JCommander(generator);
try{
jCommander.parse(args);
} catch (ParameterException ex){
jCommander.usage();
return;
}
generator.run();
}
private void run() throws IOException {
List<GroupData> groups = generateGroups(count);
if (format.equals("csv")) {
saveAsCsv(groups, new File(file));
} else if (format.equals("xml")) {
saveAsXml(groups, new File(file));
} else if (format.equals("json")) {
saveAsJson(groups, new File(file));
} else {
System.out.println("Unrecognised format" + format);
}
}
private void saveAsJson(List<GroupData> groups, File file) throws IOException {
Gson gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create();
String json = gson.toJson(groups);
try (Writer writer = new FileWriter(file)){
writer.write(json);
}
}
private void saveAsXml(List<GroupData> groups, File file) throws IOException {
XStream xstream = new XStream();
xstream.processAnnotations(GroupData.class);
String xml = xstream.toXML(groups);
try(Writer writer = new FileWriter(file)){
writer.write(xml);
}
}
private void saveAsCsv(List<GroupData> groups, File file) throws IOException {
System.out.println(new File(".").getAbsolutePath());
try(Writer writer = new FileWriter(file)) {
for (GroupData group : groups) {
writer.write(String.format("%s;%s;%s\n", group.getName(),
group.getHeader(), group.getFooter()));
}
}
}
private List<GroupData> generateGroups(int count){
List<GroupData> groups = new ArrayList<>();
for (int i=0; i < count; i++) {
groups.add(new GroupData().withName(String.format("test %s", i))
.withHeader(String.format("header %s", i))
.withFooter(String.format("footer %s", i)));
}
return groups;
}
}
|
package com.lambdaschool.SecretRecipes.repository;
import com.lambdaschool.SecretRecipes.models.Useremail;
import org.springframework.data.repository.CrudRepository;
/**
* The CRUD Repository connecting Useremail to the rest of the application
*/
public interface UseremailRepository
extends CrudRepository<Useremail, Long>
{
}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE190_Integer_Overflow__long_max_postinc_13.java
Label Definition File: CWE190_Integer_Overflow.label.xml
Template File: sources-sinks-13.tmpl.java
*/
/*
* @description
* CWE: 190 Integer Overflow
* BadSource: max Set data to the max value for long
* GoodSource: A hardcoded non-zero, non-min, non-max, even number
* Sinks: increment
* GoodSink: Ensure there will not be an overflow before incrementing data
* BadSink : Increment data, which can cause an overflow
* Flow Variant: 13 Control flow: if(IO.STATIC_FINAL_FIVE==5) and if(IO.STATIC_FINAL_FIVE!=5)
*
* */
package testcases.CWE190_Integer_Overflow.s06;
import testcasesupport.*;
import javax.servlet.http.*;
public class CWE190_Integer_Overflow__long_max_postinc_13 extends AbstractTestCase
{
public void bad() throws Throwable
{
long data;
if (IO.STATIC_FINAL_FIVE==5)
{
/* POTENTIAL FLAW: Use the maximum size of the data type */
data = Long.MAX_VALUE;
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run
* but ensure data is inititialized before the Sink to avoid compiler errors */
data = 0L;
}
if (IO.STATIC_FINAL_FIVE==5)
{
/* POTENTIAL FLAW: if data == Long.MAX_VALUE, this will overflow */
data++;
long result = (long)(data);
IO.writeLine("result: " + result);
}
}
/* goodG2B1() - use goodsource and badsink by changing first IO.STATIC_FINAL_FIVE==5 to IO.STATIC_FINAL_FIVE!=5 */
private void goodG2B1() throws Throwable
{
long data;
if (IO.STATIC_FINAL_FIVE!=5)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run
* but ensure data is inititialized before the Sink to avoid compiler errors */
data = 0L;
}
else
{
/* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */
data = 2;
}
if (IO.STATIC_FINAL_FIVE==5)
{
/* POTENTIAL FLAW: if data == Long.MAX_VALUE, this will overflow */
data++;
long result = (long)(data);
IO.writeLine("result: " + result);
}
}
/* goodG2B2() - use goodsource and badsink by reversing statements in first if */
private void goodG2B2() throws Throwable
{
long data;
if (IO.STATIC_FINAL_FIVE==5)
{
/* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */
data = 2;
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run
* but ensure data is inititialized before the Sink to avoid compiler errors */
data = 0L;
}
if (IO.STATIC_FINAL_FIVE==5)
{
/* POTENTIAL FLAW: if data == Long.MAX_VALUE, this will overflow */
data++;
long result = (long)(data);
IO.writeLine("result: " + result);
}
}
/* goodB2G1() - use badsource and goodsink by changing second IO.STATIC_FINAL_FIVE==5 to IO.STATIC_FINAL_FIVE!=5 */
private void goodB2G1() throws Throwable
{
long data;
if (IO.STATIC_FINAL_FIVE==5)
{
/* POTENTIAL FLAW: Use the maximum size of the data type */
data = Long.MAX_VALUE;
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run
* but ensure data is inititialized before the Sink to avoid compiler errors */
data = 0L;
}
if (IO.STATIC_FINAL_FIVE!=5)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
IO.writeLine("Benign, fixed string");
}
else
{
/* FIX: Add a check to prevent an overflow from occurring */
if (data < Long.MAX_VALUE)
{
data++;
long result = (long)(data);
IO.writeLine("result: " + result);
}
else
{
IO.writeLine("data value is too large to increment.");
}
}
}
/* goodB2G2() - use badsource and goodsink by reversing statements in second if */
private void goodB2G2() throws Throwable
{
long data;
if (IO.STATIC_FINAL_FIVE==5)
{
/* POTENTIAL FLAW: Use the maximum size of the data type */
data = Long.MAX_VALUE;
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run
* but ensure data is inititialized before the Sink to avoid compiler errors */
data = 0L;
}
if (IO.STATIC_FINAL_FIVE==5)
{
/* FIX: Add a check to prevent an overflow from occurring */
if (data < Long.MAX_VALUE)
{
data++;
long result = (long)(data);
IO.writeLine("result: " + result);
}
else
{
IO.writeLine("data value is too large to increment.");
}
}
}
public void good() throws Throwable
{
goodG2B1();
goodG2B2();
goodB2G1();
goodB2G2();
}
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
public static void main(String[] args) throws ClassNotFoundException,
InstantiationException, IllegalAccessException
{
mainFromParent(args);
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hive.common.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.IOUtils;
import org.apache.hadoop.hive.common.classification.InterfaceAudience;
import org.apache.hadoop.hive.common.classification.InterfaceStability;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.io.Files;
@InterfaceAudience.Private
@InterfaceStability.Unstable
public class HiveTestUtils {
public static final Logger LOG = LoggerFactory.getLogger(HiveTestUtils.class);
public final static String JAVA_FILE_EXT = ".java";
public final static String CLAZZ_FILE_EXT = ".class";
public final static String JAR_FILE_EXT = ".jar";
public final static String TXT_FILE_EXT = ".txt";
public static String getFileFromClasspath(String name) {
URL url = ClassLoader.getSystemResource(name);
if (url == null) {
throw new IllegalArgumentException("Could not find " + name);
}
return url.getPath();
}
private static void executeCmd(String[] cmdArr, File dir) throws IOException, InterruptedException {
final Process p1 = Runtime.getRuntime().exec(cmdArr, null, dir);
new Thread(new Runnable() {
@Override
@SuppressFBWarnings(value = "OS_OPEN_STREAM", justification = "Testing only")
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(p1.getErrorStream(), StandardCharsets.UTF_8));
String line;
try {
while ((line = input.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
LOG.error("Failed to execute the command due the exception " + e);
}
}
}).start();
p1.waitFor();
}
public static File genLocalJarForTest(String pathToClazzFile, String clazzName)
throws IOException, InterruptedException {
return genLocalJarForTest(pathToClazzFile, clazzName, new HashMap<File, String>());
}
@SuppressFBWarnings(value = "RV_RETURN_VALUE_IGNORED_BAD_PRACTICE", justification = "Testing only")
public static File genLocalJarForTest(String pathToClazzFile, String clazzName, Map<File,String>extraContent)
throws IOException, InterruptedException {
String u = pathToClazzFile;
File dir = new File(u);
File parentDir = dir.getParentFile();
File f = new File(parentDir, clazzName + JAVA_FILE_EXT);
Files.copy(dir, f);
executeCmd(new String[] { "javac", clazzName + JAVA_FILE_EXT }, parentDir);
f.delete();
File outputJar=new File(parentDir, clazzName + JAR_FILE_EXT);
ZipOutputStream zos=new ZipOutputStream(new FileOutputStream(outputJar));
String contentClassName = clazzName + CLAZZ_FILE_EXT;
zos.putNextEntry(new ZipEntry(contentClassName));
IOUtils.copy(new FileInputStream(new File(parentDir,contentClassName)), zos);
zos.closeEntry();
for (Entry<File, String> entry : extraContent.entrySet()) {
zos.putNextEntry(new ZipEntry(entry.getKey().toString()));
zos.write(entry.getValue().getBytes(StandardCharsets.UTF_8));
zos.closeEntry();
}
zos.close();
new File(parentDir, contentClassName).delete();
return outputJar;
}
}
|
/**
* 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.component.aws.lambda;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class LambdaOperationsTest {
@Test
public void supportedOperationCount() {
assertEquals(6, LambdaOperations.values().length);
}
@Test
public void valueOf() {
assertEquals(LambdaOperations.createFunction, LambdaOperations.valueOf("createFunction"));
assertEquals(LambdaOperations.getFunction, LambdaOperations.valueOf("getFunction"));
assertEquals(LambdaOperations.listFunctions, LambdaOperations.valueOf("listFunctions"));
assertEquals(LambdaOperations.invokeFunction, LambdaOperations.valueOf("invokeFunction"));
assertEquals(LambdaOperations.deleteFunction, LambdaOperations.valueOf("deleteFunction"));
assertEquals(LambdaOperations.updateFunction, LambdaOperations.valueOf("updateFunction"));
}
@Test
public void testToString() {
assertEquals(LambdaOperations.createFunction.toString(), "createFunction");
assertEquals(LambdaOperations.getFunction.toString(), "getFunction");
assertEquals(LambdaOperations.listFunctions.toString(), "listFunctions");
assertEquals(LambdaOperations.invokeFunction.toString(), "invokeFunction");
assertEquals(LambdaOperations.deleteFunction.toString(), "deleteFunction");
assertEquals(LambdaOperations.updateFunction.toString(), "updateFunction");
}
}
|
/* Copyright 2016 Sven van der Meer <vdmeer.sven@mykolab.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 de.vandermeer.skb.examples.asciiparagraph.examples;
import org.apache.commons.lang3.text.StrBuilder;
import de.svenjacobs.loremipsum.LoremIpsum;
import de.vandermeer.asciiparagraph.AP_Context;
import de.vandermeer.asciiparagraph.AsciiParagraph;
import de.vandermeer.asciithemes.a7.A7_Frames_Doc;
import de.vandermeer.skb.interfaces.StandardExampleAsCmd;
import de.vandermeer.skb.interfaces.transformers.textformat.TextAlignment;
/**
* AsciiParagraph example demonstrating frames resembling code documentation.
*
* @author Sven van der Meer <vdmeer.sven@mykolab.com>
*
*
*/
public class AP_08b_Frames_Doc implements StandardExampleAsCmd {
@Override
public void showOutput(){
// tag::example[]
AP_Context ctx = new AP_Context();
ctx.setAlignment(TextAlignment.LEFT);
ctx.setFrameTopBottomMargin(1);
ctx.setTextTopBottomMargin(0);
AsciiParagraph ap = new AsciiParagraph(ctx);
ap.addText(new LoremIpsum().getWords(9));
ctx.setFrame(A7_Frames_Doc.latexTB());
System.out.println(ap.render(20));
ctx.setFrame(A7_Frames_Doc.htmlTB());
System.out.println(ap.render(20));
ctx.setFrame(A7_Frames_Doc.bashTB());
System.out.println(ap.render(20));
ctx.setFrame(A7_Frames_Doc.bashStart2HashTB());
System.out.println(ap.render(20));
ctx.setFrame(A7_Frames_Doc.singleLine());
System.out.println(ap.render(20));
ctx.setFrame(A7_Frames_Doc.multiLine());
System.out.println(ap.render(20));
ctx.setFrame(A7_Frames_Doc.multiLineJavaDoc());
System.out.println(ap.render(20));
// end::example[]
}
@Override
public StrBuilder getSource(){
String[] source = new String[]{
"AP_Context ctx = new AP_Context();",
"ctx.setAlignment(AP_Alignment.LEFT);",
"ctx.setFrameTopBottomMargin(1);",
"ctx.setTextTopBottomMargin(0);",
"AsciiParagraph ap = new AsciiParagraph(ctx);",
"ap.addText(new LoremIpsum().getWords(9));",
"",
"ctx.setFrame(A7_Frames_Doc.latexTB());",
"System.out.println(ap.render(20));",
"",
"ctx.setFrame(A7_Frames_Doc.htmlTB());",
"System.out.println(ap.render(20));",
"",
"ctx.setFrame(A7_Frames_Doc.bashTB());",
"System.out.println(ap.render(20));",
"",
"ctx.setFrame(A7_Frames_Doc.bashStart2HashTB());",
"System.out.println(ap.render(20));",
"",
"ctx.setFrame(A7_Frames_Doc.singleLine());",
"System.out.println(ap.render(20));",
"",
"ctx.setFrame(A7_Frames_Doc.multiLine());",
"System.out.println(ap.render(20));",
"",
"ctx.setFrame(A7_Frames_Doc.multiLineJavaDoc());",
"System.out.println(ap.render(20));",
};
return new StrBuilder().appendWithSeparators(source, "\n");
}
@Override
public String getDescription() {
return "frames ressembling several documentation formats";
}
@Override
public String getID() {
return "frames-doc";
}
}
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|systest
operator|.
name|jaxrs
package|;
end_package
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|IOException
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|ws
operator|.
name|rs
operator|.
name|container
operator|.
name|ContainerRequestContext
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|ws
operator|.
name|rs
operator|.
name|container
operator|.
name|ContainerResponseContext
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|ws
operator|.
name|rs
operator|.
name|container
operator|.
name|ContainerResponseFilter
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|ws
operator|.
name|rs
operator|.
name|core
operator|.
name|Context
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|xml
operator|.
name|bind
operator|.
name|Marshaller
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|jaxrs
operator|.
name|ext
operator|.
name|MessageContext
import|;
end_import
begin_class
specifier|public
class|class
name|FormatResponseHandler
implements|implements
name|ContainerResponseFilter
block|{
annotation|@
name|Context
specifier|private
name|MessageContext
name|mc
decl_stmt|;
annotation|@
name|Override
specifier|public
name|void
name|filter
parameter_list|(
name|ContainerRequestContext
name|reqC
parameter_list|,
name|ContainerResponseContext
name|respC
parameter_list|)
throws|throws
name|IOException
block|{
if|if
condition|(
name|mc
operator|.
name|getUriInfo
argument_list|()
operator|.
name|getQueryParameters
argument_list|()
operator|.
name|containsKey
argument_list|(
literal|"_format"
argument_list|)
condition|)
block|{
name|mc
operator|.
name|put
argument_list|(
name|Marshaller
operator|.
name|JAXB_FORMATTED_OUTPUT
argument_list|,
name|Boolean
operator|.
name|TRUE
argument_list|)
expr_stmt|;
block|}
block|}
block|}
end_class
end_unit
|
package access;
public class Widget {
}
|
package com.github.skapral.poetryclub.core.config;
import com.github.skapral.config.CpSystemProperty;
/**
* poetryclub.FAKE_SYSTIME config property
*
* @author Kapralov Sergey
*/
public class Cp_FAKE_SYSTIME extends CpSystemProperty {
/**
* Ctor.
*/
public Cp_FAKE_SYSTIME() {
super("poetryclub.FAKE_SYSTIME");
}
}
|
package com.ruoyi.graduation.domain.dto;
import com.ruoyi.common.core.web.domain.BaseEntity;
// 前端查询参数
public class DetermineQuery extends BaseEntity {
private static final long serialVersionUID = 1L;
/** 用户账号 */
private String userName;
/** 用户昵称 */
private String nickName;
/** 教师id */
private Long teacherId;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public Long getTeacherId() {
return teacherId;
}
public void setTeacherId(Long teacherId) {
this.teacherId = teacherId;
}
@Override
public String toString() {
return "DetermineQuery{" +
"userName='" + userName + '\'' +
", nickName='" + nickName + '\'' +
", teacherId=" + teacherId +
'}';
}
}
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.wildfly.security.x500.cert.acme;
import static org.wildfly.security._private.ElytronMessages.acme;
import java.math.BigInteger;
import java.security.PublicKey;
import java.security.interfaces.ECPublicKey;
import java.security.interfaces.RSAPublicKey;
import javax.json.Json;
import javax.json.JsonObject;
import org.wildfly.common.codec.Base64Alphabet;
import org.wildfly.common.iteration.ByteIterator;
/**
* Useful constants and utilities related to the <a href="https://www.ietf.org/id/draft-ietf-acme-acme-14.txt">Automatic Certificate
* Management Environment (ACME)</a> protocol.
*
* @author <a href="mailto:fjuma@redhat.com">Farah Juma</a>
* @since 1.5.0
*/
public final class Acme {
public static final String ACCOUNT = "account";
public static final String ALG = "alg";
public static final String AUTHORIZATIONS = "authorizations";
public static final String CAA_IDENTITIES = "caaIdentities";
public static final String CERTIFICATE = "certificate";
public static final String CHALLENGES = "challenges";
public static final String CONTACT = "contact";
public static final String CURVE = "crv";
public static final String CSR = "csr";
public static final String DEACTIVATED = "deactivated";
public static final String DETAIL = "detail";
public static final String DNS = "dns";
public static final String EXPONENT = "e";
public static final String EXTERNAL_ACCOUNT_REQUIRED = "externalAccountRequired";
public static final String FINALIZE = "finalize";
public static final String IDENTIFIER = "identifier";
public static final String IDENTIFIERS = "identifiers";
public static final String INSTANCE = "instance";
public static final String INVALID = "invalid";
public static final String JWK = "jwk";
public static final String KEY_TYPE = "kty";
public static final String KID = "kid";
public static final String META = "meta";
public static final String MODULUS = "n";
public static final String NEW_KEY = "newKey";
public static final String NONCE = "nonce";
public static final String OLD_KEY = "oldKey";
public static final String ONLY_RETURN_EXISTING = "onlyReturnExisting";
public static final String PAYLOAD = "payload";
public static final String PENDING = "pending";
public static final String PROTECTED = "protected";
public static final String REASON = "reason";
public static final String SIGNATURE = "signature";
public static final String STATUS = "status";
public static final String SUBPROBLEMS = "subproblems";
public static final String TERMS_OF_SERVICE = "termsOfService";
public static final String TERMS_OF_SERVICE_AGREED = "termsOfServiceAgreed";
public static final String TOKEN = "token";
public static final String TITLE = "title";
public static final String TYPE = "type";
public static final String URL = "url";
public static final String VALID = "valid";
public static final String VALUE = "value";
public static final String WEBSITE = "website";
public static final String X_COORDINATE = "x";
public static final String Y_COORDINATE = "y";
public static final String GET = "GET";
public static final String HEAD = "HEAD";
public static final String POST = "POST";
public static final String ACCEPT_LANGUAGE = "Accept-Language";
public static final String CONTENT_TYPE = "Content-Type";
public static final String LOCATION = "Location";
public static final String REPLAY_NONCE = "Replay-Nonce";
public static final String RETRY_AFTER = "Retry-After";
public static final String JSON_CONTENT_TYPE = "application/json";
public static final String PROBLEM_JSON_CONTENT_TYPE = "application/problem+json";
public static final String JOSE_JSON_CONTENT_TYPE = "application/jose+json";
public static final String PEM_CERTIFICATE_CHAIN_CONTENT_TYPE = "application/pem-certificate-chain";
public static final String USER_AGENT = "User-Agent";
public static final String ERROR_TYPE_PREFIX = "urn:ietf:params:acme:error:";
public static final String BAD_NONCE = ERROR_TYPE_PREFIX + "badNonce";
public static final String USER_ACTION_REQUIRED = ERROR_TYPE_PREFIX + "userActionRequired";
public static final String RATE_LIMITED = ERROR_TYPE_PREFIX + "rateLimited";
/**
* Get the JWS "alg" header parameter value that corresponds to the given signature algorithm.
*
* @param signatureAlgorithm the signature algorithm
* @return the JWS "alg" header parameter value that corresponds to the given signature algorithm
* @throws IllegalArgumentException if the given signature algorithm is not supported
*/
static String getAlgHeaderFromSignatureAlgorithm(String signatureAlgorithm) {
switch (signatureAlgorithm) {
case "SHA256withRSA":
return "RS256";
case "SHA384withRSA":
return "RS384";
case "SHA512withRSA":
return "RS512";
case "SHA256withECDSA":
return "ES256";
case "SHA384withECDSA":
return "ES384";
case "SHA512withECDSA":
return "ES512";
default:
throw acme.unsupportedAcmeAccountSignatureAlgorithm(signatureAlgorithm);
}
}
static JsonObject getJwk(PublicKey publicKey, String algHeader) {
if (publicKey instanceof RSAPublicKey) {
RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
return Json.createObjectBuilder()
.add(EXPONENT, base64UrlEncode(rsaPublicKey.getPublicExponent().toByteArray()))
.add(KEY_TYPE, "RSA")
.add(MODULUS, base64UrlEncode(modulusToByteArray(rsaPublicKey.getModulus())))
.build();
} else if (publicKey instanceof ECPublicKey) {
ECPublicKey ecPublicKey = (ECPublicKey) publicKey;
int fieldSize = ecPublicKey.getParams().getCurve().getField().getFieldSize();
return Json.createObjectBuilder()
.add(CURVE, getCurveParameterFromAlgHeader(algHeader))
.add(KEY_TYPE, "EC")
.add(X_COORDINATE, base64UrlEncode(coordinateToByteArray(fieldSize, ecPublicKey.getW().getAffineX())))
.add(Y_COORDINATE, base64UrlEncode(coordinateToByteArray(fieldSize, ecPublicKey.getW().getAffineY())))
.build();
} else {
throw acme.unsupportedAcmeAccountPublicKeyType(publicKey.getAlgorithm());
}
}
private static byte[] modulusToByteArray(BigInteger modulus) {
// As specified in https://tools.ietf.org/html/rfc7518#section-6.3.1, the extra zero-valued octet
// needs to be omitted if present
byte[] modulusByteArray = modulus.toByteArray();
if ((modulus.bitLength() % 8 == 0) && (modulusByteArray[0] == 0) && modulusByteArray.length > 1) {
return ByteIterator.ofBytes(modulusByteArray, 1, modulusByteArray.length - 1).drain();
} else {
return modulusByteArray;
}
}
private static byte[] coordinateToByteArray(int fieldSize, BigInteger coordinate) {
byte[] coordinateByteArray = modulusToByteArray(coordinate);
int fullSize = (int) Math.ceil(fieldSize / 8d);
if (fullSize > coordinateByteArray.length) {
final byte[] fullSizeCoordinateByteArray = new byte[fullSize];
System.arraycopy(coordinateByteArray, 0, fullSizeCoordinateByteArray, fullSize - coordinateByteArray.length, coordinateByteArray.length);
return fullSizeCoordinateByteArray;
} else {
return coordinateByteArray;
}
}
private static String getCurveParameterFromAlgHeader(String algHeader) {
switch (algHeader) {
case "ES256":
return "P-256";
case "ES384":
return "P-384";
case "ES512":
return "P-521";
default:
throw acme.unableToDetermineCurveParameterFromAlgHeader(algHeader);
}
}
static String base64UrlEncode(byte[] data) {
return ByteIterator.ofBytes(data).base64Encode(BASE64_URL, false).drainToString();
}
/**
* The <a href="http://tools.ietf.org/html/rfc4648">RFC 4648</a> base64url alphabet.
*/
static final Base64Alphabet BASE64_URL = new Base64Alphabet(false) {
public int encode(final int val) {
if (val <= 25) {
return 'A' + val;
} else if (val <= 51) {
return 'a' + val - 26;
} else if (val <= 61) {
return '0' + val - 52;
} else if (val == 62) {
return '-';
} else {
assert val == 63;
return '_';
}
}
public int decode(final int codePoint) throws IllegalArgumentException {
if ('A' <= codePoint && codePoint <= 'Z') {
return codePoint - 'A';
} else if ('a' <= codePoint && codePoint <= 'z') {
return codePoint - 'a' + 26;
} else if ('0' <= codePoint && codePoint <= '9') {
return codePoint - '0' + 52;
} else if (codePoint == '-') {
return 62;
} else if (codePoint == '_') {
return 63;
} else {
return -1;
}
}
};
}
|
package com.gfacloud.did;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
public class StoreTest {
public static void storeTest(Store store) {
String label = "User1";
String content = "User1 information";
boolean ret = store.put(label, content);
assertTrue(ret);
assertTrue(store.exists(label));
String result = store.get(label);
assertNotNull(result);
assertEquals(result, content);
ArrayList<String> list = store.list();
assertNotNull(list);
assertEquals(list.size(), 1);
ret = store.remove(label);
assertTrue(ret);
assertFalse(store.exists(label));
}
}
|
package nl.endran.showcaselib.util.seperation;
public interface BaseListener {
public void onFail(String message);
}
|
/*
* Copyright (c) 2002-2018 Gargoyle Software Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gargoylesoftware.htmlunit.svg;
import com.gargoylesoftware.htmlunit.SgmlPage;
import com.gargoylesoftware.htmlunit.html.DomAttr;
import java.util.Map;
/**
* Wrapper for the SVG element {@code foreignObject}.
*
* @author Ahmed Ashour
*/
public class SvgForeignObject extends SvgElement {
/** The tag represented by this element. */
public static final String TAG_NAME = "foreignObject";
/**
* Creates a new instance.
*
* @param namespaceURI the URI that identifies an XML namespace
* @param qualifiedName the qualified name of the element type to instantiate
* @param page the page that contains this element
* @param attributes the initial attributes
*/
SvgForeignObject(final String namespaceURI, final String qualifiedName, final SgmlPage page,
final Map<String, DomAttr> attributes) {
super(namespaceURI, qualifiedName, page, attributes);
}
}
|
/*
* Copyright 2017-2019 Rudy De Busscher (https://www.atbash.be)
*
* 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 be.atbash.ee.security.octopus.keys;
import be.atbash.ee.security.octopus.keys.selector.SelectorCriteria;
import javax.enterprise.inject.Vetoed;
import java.util.List;
@Vetoed
public class CombinedKeyManager extends AbstractKeyManager implements KeyManager {
private LocalKeyManager localKeyManager = new LocalKeyManager();
private RemoteKeyManager remoteKeyManager = new RemoteKeyManager();
@Override
public List<AtbashKey> retrieveKeys(SelectorCriteria selectorCriteria) {
List<AtbashKey> atbashKeys = localKeyManager.retrieveKeys(selectorCriteria);
if (atbashKeys.isEmpty()) {
atbashKeys = remoteKeyManager.retrieveKeys(selectorCriteria);
}
return atbashKeys;
}
}
|
package com.dms.parser.datamodel.plan;
import java.sql.SQLException;
import java.util.ArrayList;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import com.dms.parser.dataio.Query;
import com.dms.utilities.database.DataSaveable;
import com.dms.utilities.database.QueryUtils;
import com.dms.utilities.database.SafeResultSet;
public class MonthPlan extends DataSaveable {
private ArrayList<Plan> dayPlans;
private int year, month;
public MonthPlan(int year, int month) {
dayPlans = new ArrayList<Plan>();
this.year = year;
this.month = month;
}
public MonthPlan() {
}
public void addPlan(Plan plan) {
dayPlans.add(plan);
}
public ArrayList<Plan> getDayPlans() {
return dayPlans;
}
public void setDayPlans(ArrayList<Plan> dayPlans) {
this.dayPlans = dayPlans;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
@Override
public String toQuery() {
return QueryUtils.querySetter(Query.PLAN.insertFormat, year, month, toJSONObject().toJSONString())+";";
}
@Override
public JSONObject toJSONObject() {
JSONObject obj = new JSONObject();
JSONArray arr = new JSONArray();
for (Plan plan : dayPlans) {
arr.add(plan.toJsonObject());
}
obj.put("Year", year);
obj.put("Month", month);
obj.put("Plans", arr);
return obj;
}
@Override
public DataSaveable fromResultSet(SafeResultSet rs) throws SQLException {
year = rs.getInt("year");
month = rs.getInt("month");
dayPlans = convertArrayList((JSONArray)((JSONObject)tryJsonParse(rs, "data")).get("Plans"));
if(dayPlans.size()==0){
vaild = false;
}
return this;
}
private ArrayList<Plan> convertArrayList(JSONArray data){
ArrayList<Plan> plans = new ArrayList<Plan>();
for(int i = 0 ; i < data.size() ; i++){
plans.add(new Plan((JSONObject)data.get(i)));
}
return plans;
}
}
|
/**
* Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
* This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
*/
package com.oracle.bmc.datasafe;
import com.oracle.bmc.datasafe.requests.*;
import com.oracle.bmc.datasafe.responses.*;
/**
* Collection of helper methods to produce {@link com.oracle.bmc.waiter.Waiter}s for different
* resources of DataSafe.
* <p>
* The default configuration used is defined by {@link com.oracle.bmc.waiter.Waiters.Waiters#DEFAULT_POLLING_WAITER}.
*/
@javax.annotation.Generated(value = "OracleSDKGenerator", comments = "API Version: 20181201")
@lombok.RequiredArgsConstructor
public class DataSafeWaiters {
private final java.util.concurrent.ExecutorService executorService;
private final DataSafe client;
/**
* Creates a new {@link com.oracle.bmc.waiter.Waiter} using the default configuration.
*
* @param request the request to send
* @param targetState the desired states to wait for. If multiple states are provided then the waiter will return once the resource reaches any of the provided states
* @return a new {@code com.oracle.bmc.waiter.Waiter} instance
*/
public com.oracle.bmc.waiter.Waiter<
GetDataSafeConfigurationRequest, GetDataSafeConfigurationResponse>
forDataSafeConfiguration(
GetDataSafeConfigurationRequest request,
com.oracle.bmc.datasafe.model.LifecycleState... targetStates) {
org.apache.commons.lang3.Validate.notEmpty(
targetStates, "At least one targetState must be provided");
org.apache.commons.lang3.Validate.noNullElements(
targetStates, "Null targetState values are not permitted");
return forDataSafeConfiguration(
com.oracle.bmc.waiter.Waiters.DEFAULT_POLLING_WAITER, request, targetStates);
}
/**
* Creates a new {@link com.oracle.bmc.waiter.Waiter} using the provided configuration.
*
* @param request the request to send
* @param targetState the desired state to wait for
* @param terminationStrategy the {@link com.oracle.bmc.waiter.TerminationStrategy} to use
* @param delayStrategy the {@link com.oracle.bmc.waiter.DelayStrategy} to use
* @return a new {@code com.oracle.bmc.waiter.Waiter} instance
*/
public com.oracle.bmc.waiter.Waiter<
GetDataSafeConfigurationRequest, GetDataSafeConfigurationResponse>
forDataSafeConfiguration(
GetDataSafeConfigurationRequest request,
com.oracle.bmc.datasafe.model.LifecycleState targetState,
com.oracle.bmc.waiter.TerminationStrategy terminationStrategy,
com.oracle.bmc.waiter.DelayStrategy delayStrategy) {
org.apache.commons.lang3.Validate.notNull(targetState, "The targetState cannot be null");
return forDataSafeConfiguration(
com.oracle.bmc.waiter.Waiters.newWaiter(terminationStrategy, delayStrategy),
request,
targetState);
}
/**
* Creates a new {@link com.oracle.bmc.waiter.Waiter} using the provided configuration.
*
* @param request the request to send
* @param terminationStrategy the {@link com.oracle.bmc.waiter.TerminationStrategy} to use
* @param delayStrategy the {@link com.oracle.bmc.waiter.DelayStrategy} to use
* @param targetStates the desired states to wait for. The waiter will return once the resource reaches any of the provided states
* @return a new {@code Waiter} instance
*/
public com.oracle.bmc.waiter.Waiter<
GetDataSafeConfigurationRequest, GetDataSafeConfigurationResponse>
forDataSafeConfiguration(
GetDataSafeConfigurationRequest request,
com.oracle.bmc.waiter.TerminationStrategy terminationStrategy,
com.oracle.bmc.waiter.DelayStrategy delayStrategy,
com.oracle.bmc.datasafe.model.LifecycleState... targetStates) {
org.apache.commons.lang3.Validate.notEmpty(
targetStates, "At least one targetState must be provided");
org.apache.commons.lang3.Validate.noNullElements(
targetStates, "Null targetState values are not permitted");
return forDataSafeConfiguration(
com.oracle.bmc.waiter.Waiters.newWaiter(terminationStrategy, delayStrategy),
request,
targetStates);
}
// Helper method to create a new Waiter for DataSafeConfiguration.
private com.oracle.bmc.waiter.Waiter<
GetDataSafeConfigurationRequest, GetDataSafeConfigurationResponse>
forDataSafeConfiguration(
com.oracle.bmc.waiter.BmcGenericWaiter waiter,
final GetDataSafeConfigurationRequest request,
final com.oracle.bmc.datasafe.model.LifecycleState... targetStates) {
final java.util.Set<com.oracle.bmc.datasafe.model.LifecycleState> targetStatesSet =
new java.util.HashSet<>(java.util.Arrays.asList(targetStates));
return new com.oracle.bmc.waiter.internal.SimpleWaiterImpl<>(
executorService,
waiter.toCallable(
com.google.common.base.Suppliers.ofInstance(request),
new com.google.common.base.Function<
GetDataSafeConfigurationRequest,
GetDataSafeConfigurationResponse>() {
@Override
public GetDataSafeConfigurationResponse apply(
GetDataSafeConfigurationRequest request) {
return client.getDataSafeConfiguration(request);
}
},
new com.google.common.base.Predicate<GetDataSafeConfigurationResponse>() {
@Override
public boolean apply(GetDataSafeConfigurationResponse response) {
return targetStatesSet.contains(
response.getDataSafeConfiguration().getLifecycleState());
}
},
targetStatesSet.contains(
com.oracle.bmc.datasafe.model.LifecycleState.Deleted)),
request);
}
/**
* Creates a new {@link com.oracle.bmc.waiter.Waiter} using the default configuration.
*
* @param request the request to send
* @param targetState the desired states to wait for. If multiple states are provided then the waiter will return once the resource reaches any of the provided states
* @return a new {@code com.oracle.bmc.waiter.Waiter} instance
*/
public com.oracle.bmc.waiter.Waiter<
GetDataSafePrivateEndpointRequest, GetDataSafePrivateEndpointResponse>
forDataSafePrivateEndpoint(
GetDataSafePrivateEndpointRequest request,
com.oracle.bmc.datasafe.model.LifecycleState... targetStates) {
org.apache.commons.lang3.Validate.notEmpty(
targetStates, "At least one targetState must be provided");
org.apache.commons.lang3.Validate.noNullElements(
targetStates, "Null targetState values are not permitted");
return forDataSafePrivateEndpoint(
com.oracle.bmc.waiter.Waiters.DEFAULT_POLLING_WAITER, request, targetStates);
}
/**
* Creates a new {@link com.oracle.bmc.waiter.Waiter} using the provided configuration.
*
* @param request the request to send
* @param targetState the desired state to wait for
* @param terminationStrategy the {@link com.oracle.bmc.waiter.TerminationStrategy} to use
* @param delayStrategy the {@link com.oracle.bmc.waiter.DelayStrategy} to use
* @return a new {@code com.oracle.bmc.waiter.Waiter} instance
*/
public com.oracle.bmc.waiter.Waiter<
GetDataSafePrivateEndpointRequest, GetDataSafePrivateEndpointResponse>
forDataSafePrivateEndpoint(
GetDataSafePrivateEndpointRequest request,
com.oracle.bmc.datasafe.model.LifecycleState targetState,
com.oracle.bmc.waiter.TerminationStrategy terminationStrategy,
com.oracle.bmc.waiter.DelayStrategy delayStrategy) {
org.apache.commons.lang3.Validate.notNull(targetState, "The targetState cannot be null");
return forDataSafePrivateEndpoint(
com.oracle.bmc.waiter.Waiters.newWaiter(terminationStrategy, delayStrategy),
request,
targetState);
}
/**
* Creates a new {@link com.oracle.bmc.waiter.Waiter} using the provided configuration.
*
* @param request the request to send
* @param terminationStrategy the {@link com.oracle.bmc.waiter.TerminationStrategy} to use
* @param delayStrategy the {@link com.oracle.bmc.waiter.DelayStrategy} to use
* @param targetStates the desired states to wait for. The waiter will return once the resource reaches any of the provided states
* @return a new {@code Waiter} instance
*/
public com.oracle.bmc.waiter.Waiter<
GetDataSafePrivateEndpointRequest, GetDataSafePrivateEndpointResponse>
forDataSafePrivateEndpoint(
GetDataSafePrivateEndpointRequest request,
com.oracle.bmc.waiter.TerminationStrategy terminationStrategy,
com.oracle.bmc.waiter.DelayStrategy delayStrategy,
com.oracle.bmc.datasafe.model.LifecycleState... targetStates) {
org.apache.commons.lang3.Validate.notEmpty(
targetStates, "At least one targetState must be provided");
org.apache.commons.lang3.Validate.noNullElements(
targetStates, "Null targetState values are not permitted");
return forDataSafePrivateEndpoint(
com.oracle.bmc.waiter.Waiters.newWaiter(terminationStrategy, delayStrategy),
request,
targetStates);
}
// Helper method to create a new Waiter for DataSafePrivateEndpoint.
private com.oracle.bmc.waiter.Waiter<
GetDataSafePrivateEndpointRequest, GetDataSafePrivateEndpointResponse>
forDataSafePrivateEndpoint(
com.oracle.bmc.waiter.BmcGenericWaiter waiter,
final GetDataSafePrivateEndpointRequest request,
final com.oracle.bmc.datasafe.model.LifecycleState... targetStates) {
final java.util.Set<com.oracle.bmc.datasafe.model.LifecycleState> targetStatesSet =
new java.util.HashSet<>(java.util.Arrays.asList(targetStates));
return new com.oracle.bmc.waiter.internal.SimpleWaiterImpl<>(
executorService,
waiter.toCallable(
com.google.common.base.Suppliers.ofInstance(request),
new com.google.common.base.Function<
GetDataSafePrivateEndpointRequest,
GetDataSafePrivateEndpointResponse>() {
@Override
public GetDataSafePrivateEndpointResponse apply(
GetDataSafePrivateEndpointRequest request) {
return client.getDataSafePrivateEndpoint(request);
}
},
new com.google.common.base.Predicate<GetDataSafePrivateEndpointResponse>() {
@Override
public boolean apply(GetDataSafePrivateEndpointResponse response) {
return targetStatesSet.contains(
response.getDataSafePrivateEndpoint().getLifecycleState());
}
},
targetStatesSet.contains(
com.oracle.bmc.datasafe.model.LifecycleState.Deleted)),
request);
}
/**
* Creates a new {@link com.oracle.bmc.waiter.Waiter} using default configuration.
*
* @param request the request to send
* @return a new {@code Waiter} instance
*/
public com.oracle.bmc.waiter.Waiter<GetWorkRequestRequest, GetWorkRequestResponse>
forWorkRequest(GetWorkRequestRequest request) {
return forWorkRequest(com.oracle.bmc.waiter.Waiters.DEFAULT_POLLING_WAITER, request);
}
/**
* Creates a new {@link com.oracle.bmc.waiter.Waiter} using the provided configuration.
*
* @param request the request to send
* @param terminationStrategy the {@link com.oracle.bmc.waiter.TerminationStrategy} to use
* @param delayStrategy the {@linkcom.oracle.bmc.waiter. DelayStrategy} to use
* @return a new {@code com.oracle.bmc.waiter.Waiter} instance
*/
public com.oracle.bmc.waiter.Waiter<GetWorkRequestRequest, GetWorkRequestResponse>
forWorkRequest(
GetWorkRequestRequest request,
com.oracle.bmc.waiter.TerminationStrategy terminationStrategy,
com.oracle.bmc.waiter.DelayStrategy delayStrategy) {
return forWorkRequest(
com.oracle.bmc.waiter.Waiters.newWaiter(terminationStrategy, delayStrategy),
request);
}
// Helper method to create a new Waiter for WorkRequest.
private com.oracle.bmc.waiter.Waiter<GetWorkRequestRequest, GetWorkRequestResponse>
forWorkRequest(
com.oracle.bmc.waiter.BmcGenericWaiter waiter,
final GetWorkRequestRequest request) {
return new com.oracle.bmc.waiter.internal.SimpleWaiterImpl<>(
executorService,
waiter.toCallable(
com.google.common.base.Suppliers.ofInstance(request),
new com.google.common.base.Function<
GetWorkRequestRequest, GetWorkRequestResponse>() {
@Override
public GetWorkRequestResponse apply(GetWorkRequestRequest request) {
return client.getWorkRequest(request);
}
},
new com.google.common.base.Predicate<GetWorkRequestResponse>() {
@Override
public boolean apply(GetWorkRequestResponse response) {
// work requests are complete once the time finished is available
return response.getWorkRequest().getTimeFinished() != null;
}
},
false),
request);
}
}
|
package ece465.handler.single;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class hash {
private final int buffersize=8*1024;
private BufferedInputStream BuffIn;
private int count;
public String gethash(String fname){
byte[] buffer= new byte[buffersize];
MessageDigest digest = null;
try {
digest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
BuffIn = null;
try {
BuffIn = new BufferedInputStream(new FileInputStream(fname));
while ((count = BuffIn.read(buffer)) > 0) {
digest.update(buffer, 0, count);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
BuffIn.close();
} catch (IOException e) {}
}
byte[] hash = digest.digest();
StringBuilder str = new StringBuilder();
for (byte b : hash) {
str.append(String.format("%02x", b));
}
return str.toString();
}
}
|
package com.example.test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.example.pool.PoolConexionesMySQL;
import com.example.pool.PoolConexionesOracle;
public class TestPoolConexiones {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
// Pool de conexiones MySQL
try {
conn = PoolConexionesMySQL.getConexion();
System.out.println("Utilizamos el pool de conexiones de MySQL");
stmt = conn.prepareStatement("SELECT * FROM personas");
rs = stmt.executeQuery();
while (rs.next()) {
System.out.print(" " + rs.getInt(1));
System.out.print(" " + rs.getString(2));
System.out.println(" " + rs.getString(3));
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
/*// Pool de conexiones Oracle
try {
conn = PoolConexionesOracle.getConexion();
System.out.println("Utilizamos el pool de conexiones de Oracle");
stmt = conn.prepareStatement("SELECT * FROM employees WHERE employee_id in(100, 101, 102)");
rs = stmt.executeQuery();
while (rs.next()) {
System.out.print(" " + rs.getInt(1));
System.out.print(" " + rs.getString(2));
System.out.println(" " + rs.getString(3));
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}*/
}
}
// Cambiamos el mensaje comentado nuevamente otro intento
|
package com.gempukku.swccgo.logic.effects;
import com.gempukku.swccgo.common.CardCategory;
import com.gempukku.swccgo.common.CardSubtype;
import com.gempukku.swccgo.filters.Filters;
import com.gempukku.swccgo.game.PhysicalCard;
import com.gempukku.swccgo.game.SwccgGame;
import com.gempukku.swccgo.game.state.GameState;
import com.gempukku.swccgo.game.state.MoveAsReactState;
import com.gempukku.swccgo.logic.GameUtils;
import com.gempukku.swccgo.logic.actions.SubAction;
import com.gempukku.swccgo.logic.modifiers.ModifiersQuerying;
import com.gempukku.swccgo.logic.timing.AbstractSubActionEffect;
import com.gempukku.swccgo.logic.timing.Action;
import com.gempukku.swccgo.logic.timing.PassthruEffect;
import com.gempukku.swccgo.logic.timing.results.EmbarkedResult;
import com.gempukku.swccgo.logic.timing.results.EmbarkingResult;
/**
* An effect to embark on a card (or to a location).
*/
public class EmbarkEffect extends AbstractSubActionEffect {
private String _playerId;
private PhysicalCard _cardMoved;
private PhysicalCard _movedFrom;
private PhysicalCard _movedTo;
private boolean _moveAsPilot;
private boolean _moveAsVehicle;
private boolean _moveCompleted;
/**
* Creates an effect to embark on a card (or to a location).
* @param action the action performing this effect
* @param cardMoved the card to move
* @param moveTo the card to embark on
* @param moveAsPilot true if moving to pilot capacity slot, otherwise false
* @param moveAsVehicle true if moving to vehicle capacity slot, otherwise false
*/
public EmbarkEffect(Action action, PhysicalCard cardMoved, PhysicalCard moveTo, boolean moveAsPilot, boolean moveAsVehicle) {
super(action);
_playerId = action.getPerformingPlayer();
_cardMoved = cardMoved;
_movedFrom = cardMoved.getAtLocation() != null ? cardMoved.getAtLocation() : cardMoved.getAttachedTo();
_movedTo = moveTo;
_moveAsPilot = moveAsPilot;
_moveAsVehicle = moveAsVehicle;
}
@Override
public boolean isPlayableInFull(SwccgGame game) {
return true;
}
@Override
protected SubAction getSubAction(SwccgGame game) {
final GameState gameState = game.getGameState();
final ModifiersQuerying modifiersQuerying = game.getModifiersQuerying();
SubAction subAction = new SubAction(_action);
// Check if card is still in play
if (_cardMoved.getAtLocation() != null || _cardMoved.getAttachedTo() != null) {
subAction.appendEffect(
new PassthruEffect(subAction) {
@Override
protected void doPlayEffect(SwccgGame game) {
MoveAsReactState moveAsReactState = gameState.getMoveAsReactState();
if (moveAsReactState != null) {
moveAsReactState.addCardParticipatingInReact(_cardMoved);
}
}
}
);
// Emit effect result that card is beginning to move
subAction.appendEffect(
new TriggeringResultEffect(subAction,
new EmbarkingResult(_cardMoved, _playerId, _movedFrom, _movedTo)));
subAction.appendEffect(
new PassthruEffect(subAction) {
@Override
protected void doPlayEffect(SwccgGame game) {
// Check that card is in play and may still move
if (_cardMoved.getAtLocation() == null && _cardMoved.getAttachedTo() == null) {
return;
}
if (modifiersQuerying.mayNotMove(gameState, _cardMoved)) {
return;
}
if (_movedTo.getBlueprint().getCardCategory() == CardCategory.LOCATION) {
gameState.sendMessage(_cardMoved.getOwner() + " embarks " + GameUtils.getCardLink(_cardMoved) + " from " + GameUtils.getCardLink(_movedFrom) + " to " + GameUtils.getCardLink(_movedTo));
gameState.moveCardToLocation(_cardMoved, _movedTo);
}
else if (_cardMoved.getBlueprint().getCardCategory() == CardCategory.CHARACTER || _cardMoved.getBlueprint().isMovesLikeCharacter()) {
if (_moveAsPilot) {
if (_movedTo.getBlueprint().getCardSubtype()== CardSubtype.TRANSPORT)
gameState.sendMessage(_cardMoved.getOwner() + " embarks " + GameUtils.getCardLink(_cardMoved) + " from " + GameUtils.getCardLink(_movedFrom) + " to " + GameUtils.getCardLink(_movedTo) + " as driver");
else
gameState.sendMessage(_cardMoved.getOwner() + " embarks " + GameUtils.getCardLink(_cardMoved) + " from " + GameUtils.getCardLink(_movedFrom) + " to " + GameUtils.getCardLink(_movedTo) + " as pilot");
gameState.moveCardToAttachedInPilotCapacitySlot(_cardMoved, _movedTo);
}
else {
gameState.sendMessage(_cardMoved.getOwner() + " embarks " + GameUtils.getCardLink(_cardMoved) + " from " + GameUtils.getCardLink(_movedFrom) + " to " + GameUtils.getCardLink(_movedTo) + " as passenger");
gameState.moveCardToAttachedInPassengerCapacitySlot(_cardMoved, _movedTo);
}
}
else {
gameState.sendMessage(_cardMoved.getOwner() + " embarks " + GameUtils.getCardLink(_cardMoved) + " from " + GameUtils.getCardLink(_movedFrom) + " into cargo hold of " + GameUtils.getCardLink(_movedTo));
if (_moveAsVehicle)
gameState.moveCardToAttachedInVehicleCapacitySlot(_cardMoved, _movedTo);
else if (Filters.capital_starship.accepts(game, _cardMoved))
gameState.moveCardToAttachedInCapitalStarshipCapacitySlot(_cardMoved, _movedTo);
else
gameState.moveCardToAttachedInStarfighterOrTIECapacitySlot(_cardMoved, _movedTo);
}
_moveCompleted = true;
// Emit effect result
game.getActionsEnvironment().emitEffectResult(new EmbarkedResult(_cardMoved, _playerId, _movedFrom, _movedTo));
}
}
);
}
return subAction;
}
@Override
protected boolean wasActionCarriedOut() {
return _moveCompleted;
}
}
|
/**
* システム管理向けのUI層コンポーネント。
*/
package sample.controller.system;
|
package io.github.longluo.util.helpers;
import android.text.Editable;
import android.text.Html;
import android.text.style.BulletSpan;
import android.text.style.LeadingMarginSpan;
import org.xml.sax.XMLReader;
import java.util.ArrayList;
import java.util.List;
/**
* Handle tags that the Html class doesn't understand
* Tweaked from source at http://stackoverflow.com/questions/4044509/android-how-to-use-the-html-taghandler
*/
public class WPHtmlTagHandler implements Html.TagHandler {
private static final int SPAN_INDENT_WIDTH = 15;
private int mListItemCount = 0;
private List<String> mListParents = new ArrayList<>();
@Override
public void handleTag(final boolean opening, final String tag, Editable output,
final XMLReader xmlReader) {
if (tag != null) {
switch (tag) {
case "WPUL":
if (opening) {
mListParents.add("ul");
} else {
mListParents.remove("ul");
}
break;
case "WPOL":
if (opening) {
mListParents.add("ol");
} else {
mListParents.remove("ol");
}
break;
case "WPLI":
if (!opening) {
handleListTag(output);
}
break;
case "dd":
if (opening) {
mListParents.add("dd");
} else {
mListParents.remove("dd");
}
break;
}
}
}
private void handleListTag(Editable output) {
int size = mListParents.size();
if (size > 0 && output != null) {
if ("ul".equals(mListParents.get(size - 1))) {
output.append("\n");
String[] split = output.toString().split("\n");
int start = 0;
if (split.length != 1) {
int lastIndex = split.length - 1;
start = output.length() - split[lastIndex].length() - 1;
}
output.setSpan(new BulletSpan(SPAN_INDENT_WIDTH * mListParents.size()), start, output.length(), 0);
} else if ("ol".equals(mListParents.get(size - 1))) {
mListItemCount++;
output.append("\n");
String[] split = output.toString().split("\n");
int start = 0;
if (split.length != 1) {
int lastIndex = split.length - 1;
start = output.length() - split[lastIndex].length() - 1;
}
output.insert(start, mListItemCount + ". ");
output.setSpan(new LeadingMarginSpan.Standard(SPAN_INDENT_WIDTH * mListParents.size()), start,
output.length(), 0);
}
}
}
}
|
package io.opensaber.views;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* OpenSABER value type helper
* This class helps write and read the values in their original types,
* which otherwise would be treated as plain strings.
*/
public class ValueType {
/**
* Writes into the database in the original value type that was passed
* @param entryVal
* @return
*/
public static Object getValue(JsonNode entryVal) {
Object result = null;
if (!entryVal.isValueNode()) {
// If it is not a value node, simply return input
result = entryVal;
return result;
}
if (entryVal.isBoolean()) {
result = entryVal.asBoolean();
} else if (entryVal.isTextual()) {
result = entryVal.textValue();
} else if (entryVal.isIntegralNumber() ||
entryVal.isLong() ||
entryVal.isBigInteger()) {
// Any number
result = entryVal.asLong();
} else if ((!entryVal.isIntegralNumber() && entryVal.isNumber()) ||
entryVal.isFloat() ||
entryVal.isBigDecimal()) {
// Decimal number
result = entryVal.asDouble();
}
return result;
}
/**
* Sets the contentNode to the corresponding value.
* This is needed to appropriately identify the value types - long, double, string
* @param contentNode - the node where the given fieldname value must be set
* @param fieldName - the fieldname
* @param readVal - the value type
*/
public static void setValue(ObjectNode contentNode, String fieldName, Object readVal) {
if (readVal instanceof Boolean) {
contentNode.put(fieldName, (Boolean) readVal);
} else if (readVal instanceof Long) {
contentNode.put(fieldName, (Long) readVal);
} else if (readVal instanceof Integer) {
contentNode.put(fieldName, (Integer) readVal);
} else if (readVal instanceof Double) {
contentNode.put(fieldName, (Double) readVal);
} else if (readVal instanceof String) {
contentNode.put(fieldName, (String) readVal);
} else if (readVal instanceof JsonNode) {
contentNode.set(fieldName, (JsonNode) readVal);
}
}
}
|
package com.commerce.cart;
import com.commerce.campaign.Campaign;
import com.commerce.category.Category;
import com.commerce.coupon.Coupon;
import com.commerce.shared.DiscountType;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
public class ShoppingCartTest {
Category foodCategory = new Category("Food");
Category fruitCategory = new Category("Fruit", foodCategory);
Category vegetableCategory = new Category("Vegetable", foodCategory);
Category bakeryCategory = new Category("Bakery");
ShoppingCart cart = new ShoppingCart();
@Test
public void shouldCreateShoppingCart(){
ShoppingCart shoppingCart = new ShoppingCart();
}
@Test
public void testAddItem() throws Exception {
Product apple = new Product("Apple", 100.0, foodCategory);
cart.addItem(apple, 10);
int itemCount = cart.getItemCount();
Assert.assertEquals(1, itemCount);
}
@Test
public void testZeroCampaignDiscount() throws Exception {
Campaign campaign = new Campaign(foodCategory, 15.0, 5, DiscountType.Rate);
Campaign campaignSecond = new Campaign(foodCategory, 55.0, 10, DiscountType.Amount);
cart.applyDiscounts(campaign, campaignSecond);
double campaignDiscount = cart.getCampaignDiscount();
Assert.assertEquals(0, campaignDiscount, 0.1);
}
@Test
public void testNoCouponDiscount() {
double couponDiscount = cart.getCouponDiscount();
Assert.assertEquals(0, couponDiscount, 0.1);
}
@Test
public void testLineItemSubTotal() throws Exception {
Product apple = new Product("Apple", 100.0, foodCategory);
LineItem lineItem = new LineItem(apple, 3);
Campaign campaign = new Campaign(foodCategory, 15.0, 5, DiscountType.Rate);
lineItem.setCampaignDiscount(campaign, 35.23);
lineItem.setCouponDiscount(12.23);
double subTotal = lineItem.getSubTotal();
Assert.assertEquals(252.54, subTotal, 0.1);
}
@Test
public void testCampaignDiscountWithDifferentCategorySingleLevel() throws Exception {
Campaign fruitCampaign = new Campaign(fruitCategory, 15.0, 5, DiscountType.Rate);
Campaign bakeryCampaign = new Campaign(bakeryCategory, 55.0, 10, DiscountType.Rate);
Product apple = new Product("Apple", 100.0, fruitCategory);
Product onion = new Product("Cake", 200.0, bakeryCategory);
cart.addItem(apple, 5); // 500 75
cart.addItem(onion, 10); // 2000 1100
cart.applyDiscounts(fruitCampaign, bakeryCampaign);
double campaignDiscount = cart.getCampaignDiscount();
Assert.assertEquals(1175, campaignDiscount, 0.1);
}
@Test
public void testCampaignDiscountWithSameCategorySingleLevel() throws Exception {
Category fruitCategory = new Category("Fruit");
Campaign fruitCampaign = new Campaign(fruitCategory, 15.0, 5, DiscountType.Rate);
Product apple = new Product("Apple", 100.0, fruitCategory);
Product mango = new Product("Mango", 200.0, fruitCategory);
cart.addItem(apple, 5); // 500 75
cart.addItem(mango, 10); // 2000 300
cart.applyDiscounts(fruitCampaign);
double campaignDiscount = cart.getCampaignDiscount();
Assert.assertEquals(375, campaignDiscount, 0.1);
}
@Test
public void testCampaignDiscountWithParentCategory() throws Exception {
Campaign fruitCampaign = new Campaign(fruitCategory, 15.0, 5, DiscountType.Rate);
Campaign vegetableCampaign = new Campaign(vegetableCategory, 25.0, 10, DiscountType.Rate);
Campaign foodCampaign = new Campaign(foodCategory, 700d, 15, DiscountType.Amount);
Product apple = new Product("Apple", 100.0, fruitCategory);
Product onion = new Product("Onion", 200.0, vegetableCategory);
cart.addItem(apple, 5); // 500 75
cart.addItem(onion, 10); // 2000 1100
cart.applyDiscounts(fruitCampaign, vegetableCampaign, foodCampaign);
double campaignDiscount = cart.getCampaignDiscount();
Assert.assertEquals(700, campaignDiscount, 0.1);
}
@Test
public void testCouponDiscount() throws Exception {
Product apple = new Product("Apple", 100.0, fruitCategory);
Product mango = new Product("Mango", 150.0, fruitCategory);
Product onion = new Product("Onion", 40.0, vegetableCategory);
Campaign fruitCampaign = new Campaign(fruitCategory, 20d, 15, DiscountType.Rate);
Coupon coupon = new Coupon(2000.0, 10.0, DiscountType.Rate);
cart.addItem(apple, 5);
cart.addItem(mango, 15);
cart.addItem(onion, 10);
cart.applyDiscounts(fruitCampaign); // 3150 - 2600
cart.applyCoupon(coupon);
double couponDiscount = cart.getCouponDiscount();
Assert.assertEquals(260, couponDiscount, 0.001);
}
@Test
public void testApplyCouponWithLowerAmount() throws Exception {
Product apple = new Product("Apple", 100.0, fruitCategory);
Coupon coupon = new Coupon(2000.0, 10.0, DiscountType.Rate);
cart.addItem(apple, 10);
cart.applyCoupon(coupon);
double couponDiscount = cart.getCouponDiscount();
Assert.assertEquals(0, couponDiscount, 0.001);
}
@Test
public void testGetTotalAmountAfterDiscountsApplied() throws Exception {
Product apple = new Product("Apple", 100.0, fruitCategory);
Product mango = new Product("Mango", 150.0, fruitCategory);
Product onion = new Product("Onion", 40.0, vegetableCategory);
Campaign fruitCampaign = new Campaign(fruitCategory, 20d, 15, DiscountType.Rate);
Coupon coupon = new Coupon(2000.0, 10.0, DiscountType.Rate);
cart.addItem(apple, 5);
cart.addItem(mango, 15);
cart.addItem(onion, 10);
cart.applyDiscounts(fruitCampaign); // 3150 - 2600
cart.applyCoupon(coupon);// 260
double totalAmountAfterDiscount = cart.getTotalAmountAfterDiscount();
Assert.assertEquals(2340, totalAmountAfterDiscount, 0.001);
}
@Test
public void shouldPrintWithoutError() throws Exception {
testCouponDiscount();
cart.print();
}
}
|
package dev.codesoapbox.dummy4j.definitions.providers;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.util.Arrays.asList;
import static org.junit.jupiter.api.Assertions.assertEquals;
class MapMergerTest {
private MapMerger mapMerger;
@BeforeEach
void setUp() {
mapMerger = new MapMerger();
}
@Test
void shouldNotMutateOriginalMaps() {
List<Map<String, Object>> maps = advancedMapList();
mapMerger.merge(maps);
assertEquals(advancedMapList(), maps);
}
private List<Map<String, Object>> advancedMapList() {
return asList(
simpleMap("pl", "root1", "val1"),
simpleMap("en", "root1", "val1"),
simpleMap("en", "root1", "val2"),
simpleMap("en", "root2", asList("val1", "val2")),
simpleMap("en", "root2", "val3")
);
}
/**
* {
* val1: {
* val2: val3
* }
* }
*/
private Map<String, Object> simpleMap(String key1, String key2, Object val2) {
Map<String, Object> mapRoot = new HashMap<>();
Map<String, Object> mapSub = new HashMap<>();
mapRoot.put(key1, mapSub);
mapSub.put(key2, val2);
return mapRoot;
}
@Test
void shouldMerge() {
Map<String, Object> yamlMap1 = simpleMap("en", "root1", "val1");
Map<String, Object> yamlMap2 = simpleMap("en", "root2", "val2");
Map<String, Object> expectedMap = new HashMap<>();
Map<String, Object> expectedSubMap = new HashMap<>();
expectedSubMap.put("root1", "val1");
expectedSubMap.put("root2", "val2");
expectedMap.put("en", expectedSubMap);
Map<String, Object> result = mapMerger.merge(asList(yamlMap1, yamlMap2));
assertEquals(expectedMap, result);
}
@Test
void shouldMergeDeep() {
Map<String, Object> yamlMap1 = new HashMap<>();
Map<String, Object> yamlMapRoot1 = new HashMap<>();
HashMap<Object, Object> yamlSubMap1 = new HashMap<>();
yamlSubMap1.put("sub1", "val1");
yamlMapRoot1.put("root1", yamlSubMap1);
yamlMap1.put("en", yamlMapRoot1);
Map<String, Object> yamlMap2 = new HashMap<>();
Map<String, Object> yamlMapRoot2 = new HashMap<>();
HashMap<Object, Object> yamlSubMap2 = new HashMap<>();
yamlSubMap2.put("sub2", "val2");
yamlMapRoot2.put("root1", yamlSubMap2);
yamlMapRoot2.put("root2", "val3");
yamlMap2.put("en", yamlMapRoot2);
Map<String, Object> expectedMap = new HashMap<>();
Map<String, Object> expectedRootMap = new HashMap<>();
Map<String, Object> expectedSubMap1 = new HashMap<>();
expectedSubMap1.put("sub1", "val1");
expectedSubMap1.put("sub2", "val2");
expectedRootMap.put("root1", expectedSubMap1);
expectedRootMap.put("root2", "val3");
expectedMap.put("en", expectedRootMap);
Map<String, Object> result = mapMerger.merge(asList(yamlMap1, yamlMap2));
assertEquals(expectedMap, result);
}
@Test
void shouldNotMergeDifferentLocales() {
Map<String, Object> yamlMap1 = simpleMap("en", "root1", "val1");
Map<String, Object> yamlMap2 = simpleMap("pl", "root1", "val1");
Map<String, Object> expectedMap = new HashMap<>();
Map<String, Object> expectedRootMap = new HashMap<>();
expectedRootMap.put("root1", "val1");
expectedMap.put("en", expectedRootMap);
expectedMap.put("pl", expectedRootMap);
Map<String, Object> result = mapMerger.merge(asList(yamlMap1, yamlMap2));
assertEquals(expectedMap, result);
}
@Test
void shouldMergeTwoLists() {
Map<String, Object> yamlMap1 = simpleMap("en", "root1", asList("val1", "val2"));
Map<String, Object> yamlMap2 = simpleMap("en", "root1", asList("val3", "val4"));
Map<String, Object> expectedMap = simpleMap("en", "root1", asList("val1", "val2", "val3", "val4"));
Map<String, Object> result = mapMerger.merge(asList(yamlMap1, yamlMap2));
assertEquals(expectedMap, result);
}
@Test
void shouldMergeTwoSingleElements() {
Map<String, Object> yamlMap1 = simpleMap("en", "root1", "val1");
Map<String, Object> yamlMap2 = simpleMap("en", "root1", "val2");
Map<String, Object> expectedMap = simpleMap("en", "root1", asList("val1", "val2"));
Map<String, Object> result = mapMerger.merge(asList(yamlMap1, yamlMap2));
assertEquals(expectedMap, result);
}
@Test
void shouldMergeListAndSingleElement() {
Map<String, Object> yamlMap1 = simpleMap("en", "root1", asList("val1", "val2"));
Map<String, Object> yamlMap2 = simpleMap("en", "root1", "val3");
Map<String, Object> expectedMap = simpleMap("en", "root1", asList("val1", "val2", "val3"));
Map<String, Object> result = mapMerger.merge(asList(yamlMap1, yamlMap2));
assertEquals(expectedMap, result);
}
@Test
void shouldMergeSingleElementAndList() {
Map<String, Object> yamlMap1 = simpleMap("en", "root1", "val1");
Map<String, Object> yamlMap2 = simpleMap("en", "root1", asList("val2", "val3"));
Map<String, Object> expectedMap = simpleMap("en", "root1", asList("val1", "val2", "val3"));
Map<String, Object> result = mapMerger.merge(asList(yamlMap1, yamlMap2));
assertEquals(expectedMap, result);
}
}
|
import net.runelite.mapping.Export;
import net.runelite.mapping.Implements;
import net.runelite.mapping.ObfuscatedName;
@ObfuscatedName("ap")
@Implements("VorbisMapping")
public class VorbisMapping {
@ObfuscatedName("i")
@Export("submaps")
int submaps;
@ObfuscatedName("w")
@Export("mappingMux")
int mappingMux;
@ObfuscatedName("s")
@Export("submapFloor")
int[] submapFloor;
@ObfuscatedName("a")
@Export("submapResidue")
int[] submapResidue;
VorbisMapping() {
VorbisSample.readBits(16); // L: 12
this.submaps = VorbisSample.readBit() != 0 ? VorbisSample.readBits(4) + 1 : 1; // L: 13
if (VorbisSample.readBit() != 0) { // L: 14
VorbisSample.readBits(8); // L: 15
}
VorbisSample.readBits(2); // L: 18
if (this.submaps > 1) { // L: 19
this.mappingMux = VorbisSample.readBits(4); // L: 20
}
this.submapFloor = new int[this.submaps]; // L: 22
this.submapResidue = new int[this.submaps]; // L: 23
for (int var1 = 0; var1 < this.submaps; ++var1) { // L: 24
VorbisSample.readBits(8); // L: 25
this.submapFloor[var1] = VorbisSample.readBits(8); // L: 26
this.submapResidue[var1] = VorbisSample.readBits(8); // L: 27
}
} // L: 29
}
|
package com.packtpublishing.tddjava.ch04ship;
import java.util.List;
public class Planet {
private final Point max;
public Point getMax() {
return max;
}
private List<Point> obstacles;
public List<Point> getObstacles() {
return obstacles;
}
public void setObstacles(List<Point> obstacles) {
this.obstacles = obstacles;
}
public Planet(Point max) {
this.max = max;
}
public Planet(Point max, List<Point> obstacles) {
this.max = max;
this.obstacles = obstacles;
}
}
|
/*
* Copyright (c) 2017, GoMint, BlackyPaw and geNAZt
*
* This code is licensed under the BSD license found in the
* LICENSE file in the root directory of this source tree.
*/
package io.gomint.server.network;
import io.gomint.server.network.packet.Packet;
import io.gomint.server.network.packet.PacketAdventureSettings;
import io.gomint.server.network.packet.PacketAnimate;
import io.gomint.server.network.packet.PacketBatch;
import io.gomint.server.network.packet.PacketBlockPickRequest;
import io.gomint.server.network.packet.PacketBookEdit;
import io.gomint.server.network.packet.PacketBossBar;
import io.gomint.server.network.packet.PacketClientCacheBlobStatus;
import io.gomint.server.network.packet.PacketClientCacheStatus;
import io.gomint.server.network.packet.PacketCommandRequest;
import io.gomint.server.network.packet.PacketContainerClose;
import io.gomint.server.network.packet.PacketCraftingEvent;
import io.gomint.server.network.packet.PacketDisconnect;
import io.gomint.server.network.packet.PacketEmoteList;
import io.gomint.server.network.packet.PacketEncryptionResponse;
import io.gomint.server.network.packet.PacketEntityEvent;
import io.gomint.server.network.packet.PacketEntityFall;
import io.gomint.server.network.packet.PacketEntityMetadata;
import io.gomint.server.network.packet.PacketHotbar;
import io.gomint.server.network.packet.PacketInteract;
import io.gomint.server.network.packet.PacketInventoryTransaction;
import io.gomint.server.network.packet.PacketLogin;
import io.gomint.server.network.packet.PacketMobEquipment;
import io.gomint.server.network.packet.PacketModalResponse;
import io.gomint.server.network.packet.PacketMovePlayer;
import io.gomint.server.network.packet.PacketPlayState;
import io.gomint.server.network.packet.PacketPlayerAction;
import io.gomint.server.network.packet.PacketRequestChunkRadius;
import io.gomint.server.network.packet.PacketResourcePackResponse;
import io.gomint.server.network.packet.PacketResourcePacksInfo;
import io.gomint.server.network.packet.PacketRespawnPosition;
import io.gomint.server.network.packet.PacketServerSettingsRequest;
import io.gomint.server.network.packet.PacketConfirmChunkRadius;
import io.gomint.server.network.packet.PacketSetLocalPlayerAsInitialized;
import io.gomint.server.network.packet.PacketText;
import io.gomint.server.network.packet.PacketTickSync;
import io.gomint.server.network.packet.PacketTileEntityData;
import io.gomint.server.network.packet.PacketViolationWarning;
import io.gomint.server.network.packet.PacketWorldSoundEvent;
/**
* @author BlackyPaw
* @version 1.0
*/
public final class Protocol {
// CHECKSTYLE:OFF
// MC:PE Protocol ID
public static final int MINECRAFT_PE_BETA_PROTOCOL_VERSION = -1;
public static final int MINECRAFT_PE_NEXT_STABLE_PROTOCOL_VERSION = -1;
public static final int MINECRAFT_PE_PROTOCOL_VERSION = 419;
public static final String MINECRAFT_PE_NETWORK_VERSION = "1.16.100";
// ========================================= PACKET IDS ========================================= //
public static final byte BATCH_MAGIC = (byte) 0xfe;
public static final int PACKET_LOGIN = 0x01;
public static final int PACKET_PLAY_STATE = 0x02;
public static final int PACKET_ENCRYPTION_REQUEST = 0x03;
public static final int PACKET_ENCRYPTION_RESPONSE = 0x04;
public static final int PACKET_DISCONNECT = 0x05;
public static final int PACKET_RESOURCEPACK_INFO = 0x06;
public static final int PACKET_RESOURCEPACK_STACK = 0x07;
public static final int PACKET_RESOURCEPACK_RESPONSE = 0x08;
public static final int PACKET_TEXT = 0x09;
public static final int PACKET_WORLD_TIME = 0x0a;
public static final int PACKET_START_GAME = 0x0b;
public static final int PACKET_SPAWN_PLAYER = 0x0c;
public static final int PACKET_SPAWN_ENTITY = 0x0d;
public static final int PACKET_DESPAWN_ENTITY = 0x0e;
public static final int PACKET_ADD_ITEM_ENTITY = 0x0f;
public static final int PACKET_PICKUP_ITEM_ENTITY = 0x11;
public static final int PACKET_ENTITY_MOVEMENT = 0x12;
public static final int PACKET_MOVE_PLAYER = 0x13;
public static final int PACKET_RIDER_JUMP = 0x14;
public static final int PACKET_UPDATE_BLOCK = 0x15;
public static final int PACKET_ADD_PAINTING = 0x16;
public static final int PACKET_TICK_SYNC = 0x17;
public static final int PACKET_WORLD_SOUND_EVENT_V1 = 0x18;
public static final int PACKET_WORLD_EVENT = 0x19;
public static final int PACKET_BLOCK_EVENT = 0x1A;
public static final int PACKET_ENTITY_EVENT = 0x1B;
public static final int PACKET_MOB_EFFECT = 0x1C;
public static final int PACKET_UPDATE_ATTRIBUTES = 0x1D;
public static final int PACKET_INVENTORY_TRANSACTION = 0x1E;
public static final int PACKET_MOB_EQUIPMENT = 0x1F;
public static final int PACKET_MOB_ARMOR_EQUIPMENT = 0x20;
public static final int PACKET_INTERACT = 0x21;
public static final int PACKET_BLOCK_PICK_REQUEST = 0x22;
public static final int PACKET_ENTITY_PICK_REQUEST = 0x23;
public static final int PACKET_PLAYER_ACTION = 0x24;
public static final int PACKET_ENTITY_FALL = 0x25;
public static final int PACKET_HURT_ARMOR = 0x26;
public static final int PACKET_ENTITY_METADATA = 0x27;
public static final int PACKET_ENTITY_MOTION = 0x28;
public static final int PACKET_SET_ENTITY_LINK = 0x29;
public static final int PACKET_SET_HEALTH = 0x2A;
public static final int PACKET_SET_SPAWN_POSITION = 0x2B;
public static final int PACKET_ANIMATE = 0x2C;
public static final int PACKET_RESPAWN_POSITION = 0x2D;
public static final int PACKET_CONTAINER_OPEN = 0x2E;
public static final int PACKET_CONTAINER_CLOSE = 0x2F;
public static final int PACKET_HOTBAR = 0x30;
public static final int PACKET_INVENTORY_CONTENT_PACKET = 0x31;
public static final int PACKET_INVENTORY_SET_SLOT = 0x32;
public static final int PACKET_SET_CONTAINER_DATA = 0x33;
public static final int PACKET_CRAFTING_RECIPES = 0x34;
public static final int PACKET_CRAFTING_EVENT = 0x35;
public static final int PACKET_GUI_DATA_PICK_ITEM = 0x36;
public static final int PACKET_ADVENTURE_SETTINGS = 0x37;
public static final int PACKET_TILE_ENTITY_DATA = 0x38;
public static final int PACKET_PLAYER_INPUT = 0x39;
public static final int PACKET_WORLD_CHUNK = 0x3A;
public static final int PACKET_SET_COMMANDS_ENABLED = 0x3B;
public static final int PACKET_SET_DIFFICULTY = 0x3C;
public static final int PACKET_CHANGE_DIMENSION = 0x3D;
public static final int PACKET_SET_GAMEMODE = 0x3E;
public static final int PACKET_PLAYER_LIST = 0x3F;
public static final int PACKET_SIMPLE_EVENT = 0x40;
public static final int PACKET_EVENT = 0x41;
public static final int PACKET_SPAWN_EXPERIENCE_ORB = 0x42;
public static final int PACKET_CLIENTBOUND_MAP_ITEM_DATA = 0x43;
public static final int PACKET_MAP_INFO_REQUEST = 0x44;
public static final int PACKET_REQUEST_CHUNK_RADIUS = 0x45;
public static final int PACKET_CONFIRM_CHUNK_RADIUS = 0x46;
public static final int PACKET_ITEM_FRAME_DROP_ITEM = 0x47;
public static final int PACKET_GAME_RULES_CHANGED = 0x48;
public static final int PACKET_CAMERA = 0x49;
public static final int PACKET_BOSS_BAR = 0x4a;
public static final int PACKET_SHOW_CREDITS = 0x4b;
public static final int PACKET_AVAILABLE_COMMANDS = 0x4c;
public static final int PACKET_COMMAND_REQUEST = 0x4d;
public static final int PACKET_COMMAND_BLOCK_UPDATE = 0x4e;
public static final int PACKET_COMMAND_OUTPUT = 0x4f;
public static final int PACKET_UPDATE_TRADE = 0x50;
public static final int PACKET_UPDATE_EQUIPMENT = 0x51;
public static final int PACKET_RESOURCE_PACK_DATA_INFO = 0x52;
public static final int PACKET_RESOURCE_PACK_CHUNK_DATA = 0x53;
public static final int PACKET_RESOURCE_PACK_CHUNK_REQUEST = 0x54;
public static final int PACKET_TRANSFER = 0x55;
public static final int PACKET_PLAY_SOUND = 0x56;
public static final int PACKET_STOP_SOUND = 0x57;
public static final int PACKET_SET_TITLE = 0x58;
public static final int PACKET_ADD_BEHAVIOR_TREE = 0x59;
public static final int PACKET_STRUCTURE_BLOCK_UPDATE = 0x5a;
public static final int PACKET_SHOW_STORE_OFFER = 0x5b;
public static final int PACKET_PURCHASE_RECEIPT = 0x5c;
public static final int PACKET_PLAYER_SKIN = 0x5d;
public static final int PACKET_SUB_CLIENT_LOGIN = 0x5e;
public static final int PACKET_AUTOMATION_CLIENT_CONNECT = 0x5f;
public static final int PACKET_SET_LAST_HURT_BY = 0x60;
public static final int PACKET_BOOK_EDIT = 0x61;
public static final int PACKET_NPC_REQUEST = 0x62;
public static final int PACKET_PHOTO_TRANSFER = 0x63;
public static final int PACKET_MODAL_REQUEST = 0x64;
public static final int PACKET_MODAL_RESPONSE = 0x65;
public static final int PACKET_SERVER_SETTINGS_REQUEST = 0x66;
public static final int PACKET_SERVER_SETTINGS_RESPONSE = 0x67;
public static final int PACKET_SHOW_PROFILE = 0x68;
public static final int PACKET_SET_DEFAULT_GAME_TYPE = 0x69;
public static final int PACKET_REMOVE_OBJECTIVE = 0x6a;
public static final int PACKET_SET_OBJECTIVE = 0x6b;
public static final int PACKET_SET_SCORE = 0x6c;
public static final int PACKET_LAB_TABLE = 0x6d;
public static final int PACKET_UPDATE_BLOCK_SYNCHED = 0x6e;
public static final int PACKET_ENTITY_RELATIVE_MOVEMENT = 0x6f;
public static final int PACKET_SET_SCOREBOARD_IDENTITY = 0x70;
public static final int PACKET_SET_LOCAL_PLAYER_INITIALIZED = 0x71;
public static final int PACKET_UPDATE_SOFT_ENUM = 0x72;
public static final int PACKET_NETWORK_STACK_LATENCY = 0x73;
public static final int PACKET_SCRIPT_CUSTOM_EVENT = 0x75;
public static final int PACKET_SPAWN_PARTICLE_EFFECT = 0x76;
public static final int PACKET_AVAILABLE_ENTITY_IDENTIFIERS = 0x77;
public static final int PACKET_WORLD_SOUND_EVENT_V2 = 0x78;
public static final int PACKET_NETWORK_CHUNK_PUBLISHER_UPDATE = 0x79;
public static final int PACKET_BIOME_DEFINITION_LIST = 0x7a;
public static final int PACKET_WORLD_SOUND_EVENT = 0x7b;
public static final int PACKET_WORLD_EVENT_GENERIC = 0x7c;
public static final int PACKET_LECTERN_UPDATE = 0x7d;
public static final int PACKET_VIDEO_STREAM_CONNECT = 0x7e;
public static final int PACKET_ADD_ENTITY = 0x7f;
public static final int PACKET_REMOVE_ENTITY = 0x80;
public static final int PACKET_CLIENT_CACHE_STATUS = 0x81;
public static final int PACKET_ON_SCREEN_TEXTURE_ANIMATION = 0x82;
public static final int PACKET_MAP_CREATE_LOCKED_COPY = 0x83;
public static final int PACKET_STRUCTURE_TEMPLATE_DATA_REQUEST = 0x84;
public static final int PACKET_STRUCTURE_TEMPLATE_DATA_RESPONSE = 0x85;
public static final int PACKET_UPDATE_BLOCK_PROPERTIES = 0x86;
public static final int PACKET_CLIENT_CACHE_BLOB_STATUS = 0x87;
public static final int PACKET_CLIENT_CACHE_MISS_RESPONSE = 0x88;
public static final int PACKET_EDUCATION_SETTINGS = 0x89;
public static final int PACKET_EMOTE = 0x8a;
public static final int PACKET_MULTIPLAYER_SETTINGS = 0x8b;
public static final int PACKET_SETTINGS_COMMAND = 0x8c;
public static final int PACKET_ANVIL_DAMAGE = 0x8d;
public static final int PACKET_COMPLETED_USING_ITEM = 0x8e;
public static final int PACKET_NETWORK_SETTINGS = 0x8f;
public static final int PACKET_PLAYER_AUTH_INPUT = 0x90;
public static final int PACKET_CREATIVE_CONTENT = 0x91;
public static final int PACKET_PLAYER_ENCHANT_OPTIONS = 0x92;
public static final int PACKET_ITEM_STACK_REQUEST = 0x93;
public static final int PACKET_ITEM_STACK_RESPONSE = 0x94;
public static final int PACKET_PLAYER_ARMOR_DAMAGE = 0x95;
public static final int PACKET_CODE_BUILDER = 0x96;
public static final int PACKET_UPDATE_PLAYER_GAME_TYPE = 0x97;
public static final int PACKET_EMOTE_LIST = 0x98;
public static final int PACKET_POS_TRACKING_SERVER_BROADCAST = 0x99;
public static final int PACKET_POS_TRACKING_CLIENT_REQUEST = 0x9a;
public static final int PACKET_DEBUG_INFO = 0x9b;
public static final int PACKET_VIOLATION_WARNING = 0x9c;
public static final int PACKET_ITEM_COMPONENT = 0xA2;
// CHECKSTYLE:ON
// ========================================= PACKET METHODS ========================================= //
private Protocol() {
throw new AssertionError("Cannot instantiate Protocol!");
}
/**
* Creates a new packet instance given the packet ID found inside the first int of any
* packet's data.
*
* @param id The ID of the the packet to create
* @return The created packet or null if it could not be created
*/
public static Packet createPacket(int id) {
switch (id) {
case PACKET_EMOTE_LIST:
return new PacketEmoteList();
case PACKET_CLIENT_CACHE_BLOB_STATUS:
return new PacketClientCacheBlobStatus();
case PACKET_VIOLATION_WARNING:
return new PacketViolationWarning();
case PACKET_TILE_ENTITY_DATA:
return new PacketTileEntityData();
case PACKET_SET_LOCAL_PLAYER_INITIALIZED:
return new PacketSetLocalPlayerAsInitialized();
case PACKET_BOOK_EDIT:
return new PacketBookEdit();
case PACKET_ENTITY_FALL:
return new PacketEntityFall();
case PACKET_BOSS_BAR:
return new PacketBossBar();
case PACKET_SERVER_SETTINGS_REQUEST:
return new PacketServerSettingsRequest();
case PACKET_MOB_EQUIPMENT:
return new PacketMobEquipment();
case PACKET_MODAL_RESPONSE:
return new PacketModalResponse();
case PACKET_ENTITY_EVENT:
return new PacketEntityEvent();
case PACKET_COMMAND_REQUEST:
return new PacketCommandRequest();
case PACKET_TEXT:
return new PacketText();
case PACKET_HOTBAR:
return new PacketHotbar();
case PACKET_LOGIN:
return new PacketLogin();
case PACKET_PLAY_STATE:
return new PacketPlayState();
case PACKET_ENCRYPTION_RESPONSE:
return new PacketEncryptionResponse();
case PACKET_DISCONNECT:
return new PacketDisconnect();
case PACKET_INVENTORY_TRANSACTION:
return new PacketInventoryTransaction();
case PACKET_RESOURCEPACK_INFO:
return new PacketResourcePacksInfo();
case PACKET_RESOURCEPACK_RESPONSE:
return new PacketResourcePackResponse();
case PACKET_WORLD_SOUND_EVENT:
return new PacketWorldSoundEvent();
case PACKET_MOVE_PLAYER:
return new PacketMovePlayer();
case PACKET_PLAYER_ACTION:
return new PacketPlayerAction();
case PACKET_ANIMATE:
return new PacketAnimate();
case PACKET_CONTAINER_CLOSE:
return new PacketContainerClose();
case PACKET_CRAFTING_EVENT:
return new PacketCraftingEvent();
case PACKET_ADVENTURE_SETTINGS:
return new PacketAdventureSettings();
case PACKET_INTERACT:
return new PacketInteract();
case PACKET_BLOCK_PICK_REQUEST:
return new PacketBlockPickRequest();
case PACKET_ENTITY_METADATA:
return new PacketEntityMetadata();
case PACKET_CONFIRM_CHUNK_RADIUS:
return new PacketConfirmChunkRadius();
case PACKET_CLIENT_CACHE_STATUS:
return new PacketClientCacheStatus();
case PACKET_TICK_SYNC:
return new PacketTickSync();
case PACKET_REQUEST_CHUNK_RADIUS:
return new PacketRequestChunkRadius();
case PACKET_RESPAWN_POSITION:
return new PacketRespawnPosition();
default:
// LOGGER.warn( "Unknown client side packetId: {}", Integer.toHexString( id & 0xFF ) );
return null;
}
}
}
|
package com.tokenbank.view;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import com.tokenbank.R;
import java.util.ArrayList;
import java.util.List;
public class HotView extends ViewGroup implements OnClickListener {
/**
* 最大行数
*/
private int maxLines = 3;
private OnClickListener l;
private List<Rect> rects = new ArrayList<Rect>();
public HotView(Context context) {
this(context, null);
}
public HotView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public HotView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setMaxLines(int maxLines) {
this.maxLines = maxLines;
}
public void setOnItemClickListener(OnClickListener l) {
this.l = l;
}
public void setData(List<String> hots) {
removeAllViews();
if (hots != null && hots.size() > 0) {
for (int i = 0; i < hots.size(); i++) {
TextView tv = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.hot_item_view, this, false);
tv.setOnClickListener(this);
try {
tv.setText(hots.get(i));
tv.setTag(i);
// GradientDrawable gd = (GradientDrawable) tv.getBackground();
// gd.setColor(Color.parseColor(olb.getColor()));
} catch (Exception e) {
e.printStackTrace();
}
addView(tv);
}
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int width = getPaddingLeft();
int height = getPaddingTop();
// 行宽,行高
int lineWidth = getPaddingLeft();
int lineHeight = getPaddingTop();
// 行数
int lines = 1;
int count = getChildCount();
rects.clear();
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
measureChild(child, widthMeasureSpec, heightMeasureSpec);
MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;
Rect rect = new Rect();
// 换行
if (lineWidth + childWidth > widthSize - getPaddingLeft() - getPaddingRight()) {
width = Math.max(width, lineWidth);
lineWidth = getPaddingLeft() + childWidth;
height += lineHeight;
lineHeight = childHeight;
lines++;
} else { // 未换行
lineWidth += childWidth;
lineHeight = Math.max(childHeight, lineHeight);
}
rect.top = height + lp.topMargin;
rect.bottom = height + lineHeight - lp.bottomMargin;
rect.right = lineWidth - lp.rightMargin;
rect.left = lineWidth - childWidth + lp.leftMargin;
if (lines > maxLines) {
break;
} else {
rects.add(rect);
}
// 最后 一个
if (i == count - 1) {
width = Math.max(lineWidth, width);
height += lineHeight;
}
}
height += getPaddingBottom();
width += getPaddingRight();
setMeasuredDimension(widthMode == MeasureSpec.EXACTLY ? widthSize : width, heightMode == MeasureSpec.EXACTLY ? heightSize : height);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
for (int i = 0; i < getChildCount(); i++) {
if (i < rects.size()) {
Rect loc = rects.get(i);
if (loc != null) {
View child = getChildAt(i);
child.layout(loc.left, loc.top, loc.right, loc.bottom);
}
}
}
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new MarginLayoutParams(getContext(), attrs);
}
@Override
public void onClick(View v) {
if (l != null) {
l.onClick(v);
}
}
}
|
package org.gradle.test.performance.mediummonolithicjavaproject.p381;
import org.junit.Test;
import static org.junit.Assert.*;
public class Test7634 {
Production7634 objectUnderTest = new Production7634();
@Test
public void testProperty0() {
Production7631 value = new Production7631();
objectUnderTest.setProperty0(value);
assertEquals(value, objectUnderTest.getProperty0());
}
@Test
public void testProperty1() {
Production7632 value = new Production7632();
objectUnderTest.setProperty1(value);
assertEquals(value, objectUnderTest.getProperty1());
}
@Test
public void testProperty2() {
Production7633 value = new Production7633();
objectUnderTest.setProperty2(value);
assertEquals(value, objectUnderTest.getProperty2());
}
@Test
public void testProperty3() {
String value = "value";
objectUnderTest.setProperty3(value);
assertEquals(value, objectUnderTest.getProperty3());
}
@Test
public void testProperty4() {
String value = "value";
objectUnderTest.setProperty4(value);
assertEquals(value, objectUnderTest.getProperty4());
}
@Test
public void testProperty5() {
String value = "value";
objectUnderTest.setProperty5(value);
assertEquals(value, objectUnderTest.getProperty5());
}
@Test
public void testProperty6() {
String value = "value";
objectUnderTest.setProperty6(value);
assertEquals(value, objectUnderTest.getProperty6());
}
@Test
public void testProperty7() {
String value = "value";
objectUnderTest.setProperty7(value);
assertEquals(value, objectUnderTest.getProperty7());
}
@Test
public void testProperty8() {
String value = "value";
objectUnderTest.setProperty8(value);
assertEquals(value, objectUnderTest.getProperty8());
}
@Test
public void testProperty9() {
String value = "value";
objectUnderTest.setProperty9(value);
assertEquals(value, objectUnderTest.getProperty9());
}
}
|
/*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.stunner.core.client.components.toolbox.actions;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PreDestroy;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import org.jboss.errai.ioc.client.api.ManagedInstance;
import org.kie.workbench.common.stunner.core.lookup.domain.CommonDomainLookups;
@ApplicationScoped
public class ToolboxDomainLookups {
private final ManagedInstance<CommonDomainLookups> domainLookupInstances;
private final Map<String, CommonDomainLookups> domainLookups;
// CDI proxy.
protected ToolboxDomainLookups() {
this(null);
}
@Inject
public ToolboxDomainLookups(final ManagedInstance<CommonDomainLookups> domainLookupInstances) {
this.domainLookupInstances = domainLookupInstances;
this.domainLookups = new HashMap<>(4);
}
public CommonDomainLookups get(final String definitionSetId) {
CommonDomainLookups lookup = domainLookups.get(definitionSetId);
if (null == lookup) {
lookup = domainLookupInstances.get();
lookup.setDomain(definitionSetId);
domainLookups.put(definitionSetId, lookup);
}
return lookup;
}
@PreDestroy
public void destroy() {
domainLookups.clear();
domainLookupInstances.destroyAll();
}
}
|
/*
* This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file
* at the root of this project for more details.
*/
package io.github.nucleuspowered.nucleus.modules.nickname.events;
import io.github.nucleuspowered.nucleus.api.module.nickname.event.NucleusChangeNicknameEvent;
import org.spongepowered.api.entity.living.player.User;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.impl.AbstractEvent;
import org.spongepowered.api.text.Text;
import java.util.Optional;
import javax.annotation.Nullable;
public class ChangeNicknameEventPre extends AbstractEvent implements NucleusChangeNicknameEvent.Pre {
private final Cause cause;
private final User target;
@Nullable private final Text previousNickname;
@Nullable private final Text newNickname;
private boolean cancel = false;
public ChangeNicknameEventPre(Cause cause, @Nullable Text previousNickname, @Nullable Text newNickname, User target) {
this.cause = cause;
this.previousNickname = previousNickname;
this.newNickname = newNickname;
this.target = target;
}
@Override public User getUser() {
return this.target;
}
@Override
public Optional<Text> getPreviousNickname() {
return Optional.ofNullable(this.previousNickname);
}
@Override public Optional<Text> getNickname() {
return Optional.ofNullable(this.newNickname);
}
@Override
public boolean isCancelled() {
return this.cancel;
}
@Override
public void setCancelled(boolean cancel) {
this.cancel = cancel;
}
@Override
public Cause getCause() {
return this.cause;
}
}
|
package org.wakeup;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Generated by wakeup generator 'http://wakeup.org.in'
* Application
*/
@Controller
@SpringBootApplication
public class Application {
@RequestMapping("/")
public String index() { return "index.html"; }
public static void main(String[] args) {
SpringApplication app=new SpringApplication(Application.class);
app.run(args);
}
}
|
/*
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.kinesisanalytics.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.kinesisanalytics.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* DeleteApplicationInputProcessingConfigurationRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DeleteApplicationInputProcessingConfigurationRequestProtocolMarshaller implements
Marshaller<Request<DeleteApplicationInputProcessingConfigurationRequest>, DeleteApplicationInputProcessingConfigurationRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/")
.httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true)
.operationIdentifier("KinesisAnalytics_20150814.DeleteApplicationInputProcessingConfiguration").serviceName("AmazonKinesisAnalytics").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public DeleteApplicationInputProcessingConfigurationRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<DeleteApplicationInputProcessingConfigurationRequest> marshall(
DeleteApplicationInputProcessingConfigurationRequest deleteApplicationInputProcessingConfigurationRequest) {
if (deleteApplicationInputProcessingConfigurationRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<DeleteApplicationInputProcessingConfigurationRequest> protocolMarshaller = protocolFactory
.createProtocolMarshaller(SDK_OPERATION_BINDING, deleteApplicationInputProcessingConfigurationRequest);
protocolMarshaller.startMarshalling();
DeleteApplicationInputProcessingConfigurationRequestMarshaller.getInstance().marshall(deleteApplicationInputProcessingConfigurationRequest,
protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
/*
* BinUtils - access various binary formats from Java
*
* (C) Copyright 2017 - JaWi - j.w.janssen@lxtreme.nl
*
* Licensed under Apache License v2.
*/
package nl.lxtreme.binutils.hex.util;
import java.io.IOException;
import java.io.Reader;
/**
* Provides some convenience utilities to work with strings of hex digits.
*/
public final class HexUtils {
// CONSTRUCTORS
/**
* Creates a new HexUtils instance.
*/
private HexUtils() {
// NO-op
}
// METHODS
/**
* Parses the hex-byte in the given character sequence at the given offset.
*
* @param aInput the characters to parse as hex-bytes.
* @return a byte value.
* @throws IllegalArgumentException in case the given char sequence was <code>null</code>, in case
* the given input did not yield a hex-byte, or the requested offset
* is outside the boundaries of the given char sequence.
*/
public static byte parseHexByte(char[] aInput) throws IllegalArgumentException {
if (aInput == null) {
throw new IllegalArgumentException("Input cannot be null!");
}
if (aInput.length < 2) {
throw new IllegalArgumentException("Input should be at least two characters!");
}
return (byte) ((parseHex(aInput[0]) << 4) | (parseHex(aInput[1])));
}
/**
* Reads two characters from the given reader and parses them as a single
* hex-value byte.
*
* @param aReader
* @return
* @throws IllegalArgumentException
* @throws IOException
*/
public static byte readHexByte(Reader aReader) throws IllegalArgumentException, IOException {
return (byte) readHexNumber(aReader, 1);
}
/**
* Reads a number of characters from the given reader and parses them as a
* hex-value.
*
* @param aReader the reader to read the data from;
* @param aByteCount the number of bytes to read (= 2 * amount of actual characters
* read).
* @return the parsed number.
* @throws IllegalArgumentException in case the given reader was <code>null</code> or the given byte
* count was <= 0.
* @throws IOException in case of I/O problems.
*/
public static int readHexNumber(Reader aReader, int aByteCount) throws IllegalArgumentException, IOException {
if (aReader == null) {
throw new IllegalArgumentException("Input cannot be null!");
}
if (aByteCount <= 0) {
throw new IllegalArgumentException("Byte count cannot be less or equal to zero!");
}
int result = 0;
int nibbleCount = 2 * aByteCount;
while (nibbleCount-- > 0) {
int hexdigit = parseHex(aReader.read());
result = (result << 4) | hexdigit;
}
return result;
}
/**
* Reads four characters from the given reader and parses them as a single
* hex-value word.
*
* @param aReader
* @return
* @throws IllegalArgumentException
* @throws IOException
*/
public static int readHexWord(Reader aReader) throws IllegalArgumentException, IOException {
return (readHexNumber(aReader, 2) & 0xFFFF);
}
private static int parseHex(int c) {
int v = Character.digit(c, 16);
if (v < 0) {
throw new IllegalArgumentException("Unexpected character: " + c);
}
return v;
}
}
|
/*
* Copyright 2020-Present Okta, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.okta.sdk.impl.resource.identity.provider;
import com.okta.sdk.client.Client;
import com.okta.sdk.resource.identity.provider.IdentityProvider;
import com.okta.sdk.resource.identity.provider.IdentityProviderCredentials;
import com.okta.sdk.resource.identity.provider.IdentityProviderCredentialsClient;
import com.okta.sdk.resource.identity.provider.Protocol;
import com.okta.sdk.resource.identity.provider.Provisioning;
import com.okta.sdk.resource.identity.provider.ProvisioningConditions;
import com.okta.sdk.resource.identity.provider.ProvisioningDeprovisionedCondition;
import com.okta.sdk.resource.identity.provider.ProvisioningGroups;
import com.okta.sdk.resource.identity.provider.ProvisioningSuspendedCondition;
import com.okta.sdk.resource.policy.IdentityProviderPolicy;
import com.okta.sdk.resource.policy.PolicyAccountLink;
import com.okta.sdk.resource.policy.PolicySubject;
import com.okta.sdk.resource.policy.PolicyUserNameTemplate;
public class FacebookIdentityProviderBuilder extends DefaultIdentityProviderBuilder {
@Override
public IdentityProvider buildAndCreate(Client client) {
IdentityProvider createdIdp = client.createIdentityProvider(client.instantiate(IdentityProvider.class)
.setType(IdentityProvider.TypeValues.FACEBOOK)
.setName(name)
.setProtocol(client.instantiate(Protocol.class)
.setType(Protocol.TypeEnum.OAUTH2)
.setScopes(scopes)
.setCredentials(client.instantiate(IdentityProviderCredentials.class)
.setClient(client.instantiate(IdentityProviderCredentialsClient.class)
.setClientId(clientId)
.setClientSecret(clientSecret))))
.setPolicy(client.instantiate(IdentityProviderPolicy.class)
.setProvisioning(client.instantiate(Provisioning.class)
.setAction(Provisioning.ActionEnum.AUTO)
.setProfileMaster(isProfileMaster)
.setGroups(client.instantiate(ProvisioningGroups.class)
.setAction(ProvisioningGroups.ActionEnum.NONE))
.setConditions(client.instantiate(ProvisioningConditions.class)
.setDeprovisioned(client.instantiate(ProvisioningDeprovisionedCondition.class)
.setAction(ProvisioningDeprovisionedCondition.ActionEnum.NONE))
.setSuspended(client.instantiate(ProvisioningSuspendedCondition.class)
.setAction(ProvisioningSuspendedCondition.ActionEnum.NONE))))
.setAccountLink(client.instantiate(PolicyAccountLink.class)
.setFilter(null)
.setAction(PolicyAccountLink.ActionEnum.AUTO))
.setSubject(client.instantiate(PolicySubject.class)
.setUserNameTemplate(client.instantiate(PolicyUserNameTemplate.class)
.setTemplate(userName))
.setMatchType(matchType))
.setMaxClockSkew(maxClockSkew)));
return createdIdp;
}
}
|
package com.github.xerragnaroek.jikai.commands.guild;
import com.github.xerragnaroek.jikai.core.Core;
import com.github.xerragnaroek.jikai.user.JikaiUserManager;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
public class ForceRegisterCommand implements GuildCommand {
@Override
public String getName() {
return "register";
}
@Override
public void executeCommand(GuildMessageReceivedEvent event, String[] arguments) {
long id = event.getAuthor().getIdLong();
if (!JikaiUserManager.getInstance().isKnownJikaiUser(id)) {
JikaiUserManager.getInstance().registerNewUser(id, Core.JM.get(event.getGuild().getIdLong()));
}
}
@Override
public boolean isJikaiUserOnly() {
return false;
}
@Override
public String getLocaleKey() {
return "com_g_register";
}
}
|
/*
* ******************************************************************************
* * Copyright (c) 2021 Deeplearning4j Contributors
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available 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.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.deeplearning4j.arbiter.ui.data;
import lombok.Data;
import org.deeplearning4j.arbiter.optimize.runner.CandidateStatus;
import org.deeplearning4j.core.storage.Persistable;
/**
* A {@link Persistable} implemention for model results - i.e., results for
* each model
*
* @author Alex BLack
*/
@Data
public class ModelInfoPersistable extends BaseJavaPersistable {
private String workerId;
private Integer modelIdx;
private Double score;
private CandidateStatus status;
private long lastUpdateTime;
private long numParameters;
private int numLayers;
//From candidate generator - this + model hyperparam space means we can work out specific hyperparam
// settings for this model
private double[] paramSpaceValues;
private int totalNumUpdates;
//Values for score vs. iteration chart
private int[] iter;
private float[] scoreVsIter;
private String modelConfigJson;
private String exceptionStackTrace;
public ModelInfoPersistable(String sessionId, String workerId, long timeStamp){
super(sessionId, timeStamp);
this.workerId = workerId;
}
private ModelInfoPersistable(Builder builder){
super(builder);
this.workerId = builder.workerId;
this.modelIdx = builder.modelIdx;
this.score = builder.score;
this.status = builder.status;
this.iter = builder.iter;
this.scoreVsIter = builder.scoreVsIter;
this.lastUpdateTime = builder.lastUpdateTime;
this.numParameters = builder.numParameters;
this.numLayers = builder.numLayers;
this.paramSpaceValues = builder.paramSpaceValues;
this.modelConfigJson = builder.modelConfigJson;
this.totalNumUpdates = builder.totalNumUpdates;
this.exceptionStackTrace = builder.exceptionStackTrace;
}
public ModelInfoPersistable(){
//No-arg costructor for Pesistable encoding/decoding
}
@Override
public String getWorkerID() {
return workerId;
}
public static class Builder extends BaseJavaPersistable.Builder<Builder> {
private String workerId;
private Integer modelIdx;
private Double score;
private CandidateStatus status;
private long lastUpdateTime;
private long numParameters;
private int numLayers;
private int totalNumUpdates;
private double[] paramSpaceValues;
private int[] iter;
private float[] scoreVsIter;
private String modelConfigJson;
private String exceptionStackTrace;
public Builder workerId(String workerId){
this.workerId = workerId;
return this;
}
public Builder modelIdx(Integer idx){
this.modelIdx = idx;
return this;
}
public Builder score(Double score){
this.score = score;
return this;
}
public Builder status(CandidateStatus status){
this.status = status;
return this;
}
public Builder scoreVsIter(int[] iter, float[] scoreVsIter){
this.iter = iter;
this.scoreVsIter = scoreVsIter;
return this;
}
public Builder lastUpdateTime(long lastUpdateTime){
this.lastUpdateTime = lastUpdateTime;
return this;
}
public Builder numParameters(long numParameters){
this.numParameters = numParameters;
return this;
}
public Builder numLayers(int numLayers){
this.numLayers = numLayers;
return this;
}
public Builder totalNumUpdates(int totalNumUpdates){
this.totalNumUpdates = totalNumUpdates;
return this;
}
public Builder paramSpaceValues(double[] paramSpaceValues){
this.paramSpaceValues = paramSpaceValues;
return this;
}
public Builder modelConfigJson(String modelConfigJson){
this.modelConfigJson = modelConfigJson;
return this;
}
public Builder exceptionStackTrace(String exceptionStackTrace){
this.exceptionStackTrace = exceptionStackTrace;
return this;
}
public ModelInfoPersistable build(){
return new ModelInfoPersistable(this);
}
}
}
|
package org.bcos.web3j.abi.datatypes.generated;
import java.math.BigInteger;
import org.bcos.web3j.abi.datatypes.Fixed;
/**
* <p>Auto generated code.<br>
* <strong>Do not modifiy!</strong><br>
* Please use {@link org.bcos.web3j.codegen.AbiTypesGenerator} to update.</p>
*/
public class Fixed80x96 extends Fixed {
public static final Fixed80x96 DEFAULT = new Fixed80x96(BigInteger.ZERO);
public Fixed80x96(BigInteger value) {
super(80, 96, value);
}
public Fixed80x96(int mBitSize, int nBitSize, BigInteger m, BigInteger n) {
super(80, 96, m, n);
}
}
|
package main.java.core;
import java.time.LocalDate;
import main.java.model.BizDayInterface;
import main.java.services.CorporateHolidayService;
import main.java.services.HolidayValidatorService;
import main.java.services.WeekendValidatorService;
public class BusinessDayCalculator implements BizDayInterface {
private CorporateHolidayService corporateHolidayService;
private HolidayValidatorService holidayValidatorService;
private WeekendValidatorService weekendValidatorService;
public BusinessDayCalculator()
{
this.setCorporateHolidayService(new CorporateHolidayService());
this.setHolidayValidatorService(new HolidayValidatorService());
this.setWeekendValidatorService(new WeekendValidatorService());
}
public CorporateHolidayService getCorporateHolidayService()
{
return corporateHolidayService;
}
public void setCorporateHolidayService(CorporateHolidayService corporateHolidayService)
{
this.corporateHolidayService = corporateHolidayService;
}
public HolidayValidatorService getHolidayValidatorService()
{
return holidayValidatorService;
}
public void setHolidayValidatorService(HolidayValidatorService holidayValidatorService)
{
this.holidayValidatorService = holidayValidatorService;
}
public WeekendValidatorService getWeekendValidatorService()
{
return weekendValidatorService;
}
public void setWeekendValidatorService(WeekendValidatorService weekendValidatorService)
{
this.weekendValidatorService = weekendValidatorService;
}
@Override
public boolean isBizDay(LocalDate date)
{
if (date == null)
{
return false;
}
return !(getWeekendValidatorService().isWeekend(date) || getHolidayValidatorService().isHoliday(date)
|| getCorporateHolidayService().isCorporateHoliday(date));
}
@Override
public LocalDate nextBizDay()
{
return nextBizDay(LocalDate.now());
}
@Override
public LocalDate nextBizDay(LocalDate date)
{
if (date == null)
{
return null;
}
LocalDate date2 = LocalDate.of(date.getYear(), date.getMonth(), date.getDayOfMonth()).plusDays(1L);
while (!isBizDay(date2))
{
date2 = date2.plusDays(1L);
}
return date2;
}
@Override
public int bizDayDiff(LocalDate date1, LocalDate date2)
{
if (date1 == null || date2 == null)
{
return 0;
}
LocalDate earlierDate = (date1.isBefore(date2) ? date1 : date2);
LocalDate laterDate = (earlierDate.isEqual(date1) ? date2 : date1);
int counter = 0;
while(earlierDate.isBefore(laterDate))
{
if (isBizDay(earlierDate))
{
counter++;
}
earlierDate = earlierDate.plusDays(1L);
}
return counter;
}
@Override
public int bizDayUntil(LocalDate date)
{
if (date == null)
{
return 0;
}
LocalDate now = LocalDate.now();
return (now.compareTo(date) < 0) ? 0 : bizDayDiff(now, date);
}
}
|
package cn.huanzi.qch.baseadmin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
@EnableAsync//开启异步调用
@SpringBootApplication
public class BaseAdminApplication {
public static void main(String[] args) {
SpringApplication.run(BaseAdminApplication.class, args);
}
/**
* 解决不能注入session注册表问题
*/
@Bean
SessionRegistry sessionRegistry() {
return new SessionRegistryImpl();
}
}
|
package me.monaparty.api;
import lombok.Getter;
import lombok.ToString;
@Getter
@ToString
public class GetTrrigersResult {
private Long tx_index;
private String tx_hash;
private Long block_index;
private String source;
private String target_hash;
private String payload;
private String status;
public Long getTxIndex() {
return tx_index;
}
public String getTxHash() {
return tx_hash;
}
public Long getBlockIndex() {
return block_index;
}
public String getTargetHash() {
return target_hash;
}
}
|
/*
* Farsi Knowledge Graph Project
* Iran University of Science and Technology (Year 2017)
* Developed by Majid Asgari.
*/
package ir.ac.iust.dml.kg.raw.services.web.rest.data;
import ir.ac.iust.dml.kg.raw.rulebased.RuleAndPredicate;
import java.util.List;
public class RuleTestData {
private List<RuleAndPredicate> rules;
private String text;
public List<RuleAndPredicate> getRules() {
return rules;
}
public void setRules(List<RuleAndPredicate> rules) {
this.rules = rules;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
|
package org.hl7.davinci.atr.server.dao;
import java.util.Date;
import java.util.List;
import org.hl7.davinci.atr.server.model.DafCondition;
import org.hl7.davinci.atr.server.util.SearchParameterMap;
import org.hl7.fhir.r4.model.Condition;
public interface ConditionDao {
DafCondition getConditionById(int id);
DafCondition getConditionByVersionId(int theId, String versionId);
List<DafCondition> search(SearchParameterMap theMap);
DafCondition creatCondition(Condition theCondition);
DafCondition updateConditionById(int theId, Condition theCondition);
List<DafCondition> getConditionForBulkData(Date start, Date end);
List<DafCondition> getConditionForPatientsBulkData(String id, Date start, Date end);
}
|
package daw.itinerary;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@Test
public void contextLoads() {
}
}
|
/*
* Copyright 2019 IIT Software GmbH
*
* IIT Software GmbH 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.swiftmq.jms.smqp.v610;
/**
* SMQP-Protocol Version 610, Class: XAResPrepareReply
* Automatically generated, don't change!
* Generation Date: Mon Jul 17 17:50:11 CEST 2006
* (c) 2006, IIT GmbH, Bremen/Germany, All Rights Reserved
**/
import com.swiftmq.tools.requestreply.ReplyNE;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
public class XAResPrepareReply extends ReplyNE {
private int errorCode;
public XAResPrepareReply(int errorCode) {
this.errorCode = errorCode;
}
protected XAResPrepareReply() {
}
public int getErrorCode() {
return errorCode;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
public int getDumpId() {
return SMQPFactory.DID_XARESPREPARE_REP;
}
public void writeContent(DataOutput out) throws IOException {
super.writeContent(out);
SMQPUtil.write(errorCode, out);
}
public void readContent(DataInput in) throws IOException {
super.readContent(in);
errorCode = SMQPUtil.read(errorCode, in);
}
public String toString() {
StringBuffer _b = new StringBuffer("[v610/XAResPrepareReply, ");
_b.append(super.toString());
_b.append(", ");
_b.append("errorCode=");
_b.append(errorCode);
_b.append("]");
return _b.toString();
}
}
|
package tech.ecoa.osets.eclipse.plugin.editors.parts.cimpl.model;
import org.eclipse.draw2d.ColorConstants;
import org.eclipse.swt.graphics.Color;
public class DynamicTriggerInstanceTerminalNode extends Node {
public static final int DEF_HEIGHT = 30;
public static final int DEF_WIDTH = 75;
public static final Color DEF_COLOR = ColorConstants.white;
public static final Color FONT_COLOR = ColorConstants.black;
private String name;
private String type;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
|
package seedu.foodiebot.logic.commands;
import static java.util.Objects.requireNonNull;
import java.util.Objects;
/** Represents the result of a command execution. */
public class CommandResult {
public final String commandName;
private final String feedbackToUser;
/** Help information should be shown to the user. */
private final boolean showHelp;
/** The application should exit. */
private final boolean exit;
private final boolean isLocationSpecified;
/** Constructs a {@code CommandResult} with the specified fields. */
public CommandResult(String commandName, String feedbackToUser, boolean showHelp, boolean exit) {
this.commandName = commandName;
this.feedbackToUser = requireNonNull(feedbackToUser);
this.showHelp = showHelp;
this.exit = exit;
this.isLocationSpecified = false;
}
/** Constructs a {@code CommandResult} with the specified fields. */
public CommandResult(String commandName, String feedbackToUser, boolean showHelp, boolean exit,
boolean isLocationSpecified) {
this.commandName = commandName;
this.feedbackToUser = requireNonNull(feedbackToUser);
this.showHelp = showHelp;
this.exit = exit;
this.isLocationSpecified = isLocationSpecified;
}
/**
* Constructs a {@code CommandResult} with the specified {@code feedbackToUser}, and other
* fields set to their default value.
*/
public CommandResult(String commandName, String feedbackToUser) {
this(commandName, feedbackToUser,
false, false);
}
public String getFeedbackToUser() {
return feedbackToUser;
}
public boolean isShowHelp() {
return showHelp;
}
public boolean isExit() {
return exit;
}
public boolean isLocationSpecified() {
return isLocationSpecified;
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
// instanceof handles nulls
if (!(other instanceof CommandResult)) {
return false;
}
CommandResult otherCommandResult = (CommandResult) other;
return commandName.equals(otherCommandResult.commandName)
&& feedbackToUser.equals(otherCommandResult.feedbackToUser)
&& showHelp == otherCommandResult.showHelp
&& exit == otherCommandResult.exit;
}
@Override
public int hashCode() {
return Objects.hash(feedbackToUser, showHelp, exit);
}
}
|
/*
Copyright 2020 Donavie Ordonez, Dennis Tye, Kenneth Doan
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.
*/
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.util.*;
public class SendEmail {
public static void send(String toEmail, String msg) {
final String username = "[REDACTED]";
final String password = "[REDACTED]";
String destEmail = toEmail.length() == 0 ? "" : toEmail;
Properties prop = new Properties();
prop.put("mail.smtp.host", "smtp.gmail.com");
prop.put("mail.smtp.ssl.trust", "smtp.gmail.com");
prop.put("mail.smtp.port", "587");
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(prop,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}
);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(
Message.RecipientType.TO, InternetAddress.parse(destEmail));
message.setSubject("Enneagram Quiz Results");
message.setText("Here are the results of your enneagram quiz:\n\n" + msg
+ "\n\n\n\n===============================================\n"
+ "If you have not requested for these results, please ignore this email and block this address.");
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
|
/*
* Copyright 2001-2005 Stephen Colebourne
*
* 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.joda.time.chrono;
import org.joda.time.Chronology;
import org.joda.time.DateTimeConstants;
/**
* Abstract implementation of a calendar system based around fixed length months.
* <p>
* As the month length is fixed various calculations can be optimised.
* This implementation assumes any additional days after twelve
* months fall into a thirteenth month.
* <p>
* BasicFixedMonthChronology is thread-safe and immutable, and all
* subclasses must be as well.
*
* @author Brian S O'Neill
* @author Stephen Colebourne
* @since 1.2, refactored from CopticChronology
*/
abstract class BasicFixedMonthChronology extends BasicChronology {
/** Serialization lock */
private static final long serialVersionUID = 261387371998L;
/** The length of the month. */
static final int MONTH_LENGTH = 30;
/** The typical millis per year. */
static final long MILLIS_PER_YEAR =
(long) (365.25 * DateTimeConstants.MILLIS_PER_DAY);
/** The length of the month in millis. */
static final long MILLIS_PER_MONTH = ((long) MONTH_LENGTH) * DateTimeConstants.MILLIS_PER_DAY;
//-----------------------------------------------------------------------
/**
* Restricted constructor.
*
* @param base the base chronology
* @param param the init parameter
* @param minDaysInFirstWeek the minimum days in the first week
*/
BasicFixedMonthChronology(Chronology base, Object param, int minDaysInFirstWeek) {
super(base, param, minDaysInFirstWeek);
}
//-----------------------------------------------------------------------
long setYear(long instant, int year) {
// optimsed implementation of set, due to fixed months
int thisYear = getYear(instant);
int dayOfYear = getDayOfYear(instant, thisYear);
int millisOfDay = getMillisOfDay(instant);
if (dayOfYear > 365) {
// Current year is leap, and day is leap.
if (!isLeapYear(year)) {
// Moving to a non-leap year, leap day doesn't exist.
dayOfYear--;
}
}
instant = getYearMonthDayMillis(year, 1, dayOfYear);
instant += millisOfDay;
return instant;
}
//-----------------------------------------------------------------------
long getYearDifference(long minuendInstant, long subtrahendInstant) {
// optimsed implementation of getDifference, due to fixed months
int minuendYear = getYear(minuendInstant);
int subtrahendYear = getYear(subtrahendInstant);
// Inlined remainder method to avoid duplicate calls to get.
long minuendRem = minuendInstant - getYearMillis(minuendYear);
long subtrahendRem = subtrahendInstant - getYearMillis(subtrahendYear);
int difference = minuendYear - subtrahendYear;
if (minuendRem < subtrahendRem) {
difference--;
}
return difference;
}
//-----------------------------------------------------------------------
long getTotalMillisByYearMonth(int year, int month) {
return ((month - 1) * MILLIS_PER_MONTH);
}
//-----------------------------------------------------------------------
int getDayOfMonth(long millis) {
// optimised for fixed months
return (getDayOfYear(millis) - 1) % MONTH_LENGTH + 1;
}
//-----------------------------------------------------------------------
boolean isLeapYear(int year) {
return (year & 3) == 3;
}
//-----------------------------------------------------------------------
int getDaysInYearMonth(int year, int month) {
return (month != 13) ? MONTH_LENGTH : (isLeapYear(year) ? 6 : 5);
}
//-----------------------------------------------------------------------
int getDaysInMonthMax() {
return MONTH_LENGTH;
}
//-----------------------------------------------------------------------
int getDaysInMonthMax(int month) {
return (month != 13 ? MONTH_LENGTH : 6);
}
//-----------------------------------------------------------------------
int getMonthOfYear(long millis) {
return (getDayOfYear(millis) - 1) / MONTH_LENGTH + 1;
}
//-----------------------------------------------------------------------
int getMonthOfYear(long millis, int year) {
long monthZeroBased = (millis - getYearMillis(year)) / MILLIS_PER_MONTH;
return ((int) monthZeroBased) + 1;
}
//-----------------------------------------------------------------------
int getMaxMonth() {
return 13;
}
//-----------------------------------------------------------------------
long getAverageMillisPerYear() {
return MILLIS_PER_YEAR;
}
//-----------------------------------------------------------------------
long getAverageMillisPerYearDividedByTwo() {
return MILLIS_PER_YEAR / 2;
}
//-----------------------------------------------------------------------
long getAverageMillisPerMonth() {
return MILLIS_PER_MONTH;
}
}
|
/*
* MIT License
*
* Copyright (c) 2022 MASES s.r.l.
*
* 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.
*/
/**************************************************************************************
* <auto-generated>
* This code was generated from a template using JCOReflector
*
* Manual changes to this file may cause unexpected behavior in your application.
* Manual changes to this file will be overwritten if the code is regenerated.
* </auto-generated>
*************************************************************************************/
package autofac.core;
import org.mases.jcobridge.*;
import org.mases.jcobridge.netreflection.*;
// Import section
import autofac.core.Service;
import autofac.core.IComponentRegistration;
import autofac.core.IComponentRegistrationImplementation;
/**
* The base .NET class managing Autofac.Core.IComponentRegistryServices, Autofac, Version=6.0.0.0, Culture=neutral, PublicKeyToken=17863af14b0044da.
* <p>
*
* See: <a href="https://docs.microsoft.com/en-us/dotnet/api/Autofac.Core.IComponentRegistryServices" target="_top">https://docs.microsoft.com/en-us/dotnet/api/Autofac.Core.IComponentRegistryServices</a>
*/
public interface IComponentRegistryServices extends IJCOBridgeReflected {
/**
* Fully assembly qualified name: Autofac, Version=6.0.0.0, Culture=neutral, PublicKeyToken=17863af14b0044da
*/
public static final String assemblyFullName = "Autofac, Version=6.0.0.0, Culture=neutral, PublicKeyToken=17863af14b0044da";
/**
* Assembly name: Autofac
*/
public static final String assemblyShortName = "Autofac";
/**
* Qualified class name: Autofac.Core.IComponentRegistryServices
*/
public static final String className = "Autofac.Core.IComponentRegistryServices";
/**
* Try to cast the {@link IJCOBridgeReflected} instance into {@link IComponentRegistryServices}, a cast assert is made to check if types are compatible.
* @param from {@link IJCOBridgeReflected} instance to be casted
* @return {@link IComponentRegistryServices} instance
* @throws java.lang.Throwable in case of error during cast operation
*/
public static IComponentRegistryServices ToIComponentRegistryServices(IJCOBridgeReflected from) throws Throwable {
JCOBridge bridge = JCOBridgeInstance.getInstance("Autofac, Version=6.0.0.0, Culture=neutral, PublicKeyToken=17863af14b0044da");
JCType classType = bridge.GetType(className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName));
NetType.AssertCast(classType, from);
return new IComponentRegistryServicesImplementation(from.getJCOInstance());
}
/**
* Returns the reflected Assembly name
*
* @return A {@link String} representing the Fullname of reflected Assembly
*/
public String getJCOAssemblyName();
/**
* Returns the reflected Class name
*
* @return A {@link String} representing the Fullname of reflected Class
*/
public String getJCOClassName();
/**
* Returns the reflected Class name used to build the object
*
* @return A {@link String} representing the name used to allocated the object
* in CLR context
*/
public String getJCOObjectName();
/**
* Returns the instantiated class
*
* @return An {@link java.lang.Object} representing the instance of the instantiated Class
*/
public java.lang.Object getJCOInstance();
/**
* Returns the instantiated class Type
*
* @return A {@link JCType} representing the Type of the instantiated Class
*/
public JCType getJCOType();
// Methods section
public boolean IsRegistered(Service service) throws Throwable;
public boolean TryGetRegistration(Service service, JCORefOut<IComponentRegistration> registration) throws Throwable;
// Properties section
// Instance Events section
}
|
package com.dipasquale.ai.rl.neat.speciation.core;
import java.io.Serial;
public final class PopulationExtinctionException extends RuntimeException {
@Serial
private static final long serialVersionUID = 44568232965014397L;
public PopulationExtinctionException(final String message) {
super(message);
}
public PopulationExtinctionException(final String message, final Throwable cause) {
super(message, cause);
}
}
|
package com.orangeSoft.market.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.orangeSoft.market.entity.DataDictionary;
import org.springframework.stereotype.Repository;
/**
* <p>
* Mapper 接口
* </p>
*
* @since 2021-03-13
*/
@Repository
public interface DataDictionaryMapper extends BaseMapper<DataDictionary> {
}
|
// Copyright 2000-2018 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.scopes;
import com.intellij.ide.util.scopeChooser.ScopeChooserConfigurable;
import com.intellij.ide.util.scopeChooser.ScopeConfigurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.ui.MasterDetailsStateService;
import com.intellij.packageDependencies.DependencyValidationManager;
import com.intellij.psi.search.scope.packageSet.NamedScope;
import com.intellij.psi.search.scope.packageSet.PatternPackageSet;
import com.intellij.testFramework.LightJavaCodeInsightTestCase;
public class ScopeConfigurableTest extends LightJavaCodeInsightTestCase {
public void testModified() throws ConfigurationException {
DependencyValidationManager manager = DependencyValidationManager.getInstance(getProject());
final ScopeChooserConfigurable.ScopeChooserConfigurableState state = new ScopeChooserConfigurable.ScopeChooserConfigurableState();
NamedScope utilScope = new NamedScope("util", new PatternPackageSet( "java.util.*", PatternPackageSet.SCOPE_LIBRARY, null));
manager.addScope(utilScope);
state.myOrder.add(utilScope.getScopeId());
NamedScope xScope = new NamedScope("xxx", new PatternPackageSet("*..*", PatternPackageSet.SCOPE_ANY, null));
manager.addScope(xScope);
state.myOrder.add(xScope.getScopeId());
try {
ScopeChooserConfigurable configurable = new ScopeChooserConfigurable(getProject());
MasterDetailsStateService.getInstance(getProject()).setComponentState(ScopeChooserConfigurable.SCOPE_CHOOSER_CONFIGURABLE_UI_KEY, state);
configurable.reset();
assertFalse(configurable.isModified());
configurable.apply();
assertFalse(configurable.isModified());
configurable.disposeUIResources();
}
finally {
manager.removeAllSets();
}
}
public void testScopeConfigurablesModified() throws ConfigurationException {
DependencyValidationManager manager = DependencyValidationManager.getInstance(getProject());
NamedScope utilscope = new NamedScope("util", new PatternPackageSet("java.util.*", PatternPackageSet.SCOPE_LIBRARY, null));
manager.addScope(utilscope);
try {
for (NamedScope scope : manager.getScopes()) {
LOG.debug("scope = " + scope);
ScopeConfigurable configurable = new ScopeConfigurable(scope, true, getProject(), null);
configurable.reset();
assertFalse("Configurable " + configurable + " is modified immediately after creation", configurable.isModified());
assertTrue(!configurable.isModified());
configurable.apply();
configurable.disposeUIResources();
}
}
finally {
manager.removeAllSets();
}
}
}
|
package com.firebase.ui.auth.util.ui;
import android.content.Context;
import android.net.Uri;
import android.support.annotation.ColorInt;
import android.support.annotation.Nullable;
import android.support.annotation.RestrictTo;
import android.support.annotation.StringRes;
import android.support.customtabs.CustomTabsIntent;
import android.support.v4.content.ContextCompat;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.TypedValue;
import android.view.View;
import android.widget.TextView;
import com.firebase.ui.auth.R;
import com.firebase.ui.auth.data.model.FlowParameters;
import java.lang.ref.WeakReference;
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public class PreambleHandler {
private static final String BTN_TARGET = "%BTN%";
private static final String TOS_TARGET = "%TOS%";
private static final String PP_TARGET = "%PP%";
private static final int NO_BUTTON = -1;
private final Context mContext;
private final FlowParameters mFlowParameters;
private final int mButtonText;
private final ForegroundColorSpan mLinkSpan;
private SpannableStringBuilder mBuilder;
private PreambleHandler(Context context, FlowParameters parameters, @StringRes int buttonText) {
mContext = context;
mFlowParameters = parameters;
mButtonText = buttonText;
mLinkSpan = new ForegroundColorSpan(ContextCompat.getColor(mContext,
R.color.fui_linkColor));
}
public static void setup(Context context,
FlowParameters parameters,
@StringRes int textViewText,
TextView textView) {
setup(context, parameters, NO_BUTTON, textViewText, textView);
}
public static void setup(Context context,
FlowParameters parameters,
@StringRes int buttonText,
@StringRes int textViewText,
TextView textView) {
PreambleHandler handler = new PreambleHandler(context, parameters, buttonText);
handler.initPreamble(textViewText);
handler.setPreamble(textView);
}
private void setPreamble(TextView textView) {
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(mBuilder);
}
private void initPreamble(@StringRes int textViewText) {
String withTargets = getPreambleStringWithTargets(textViewText, mButtonText != NO_BUTTON);
if (withTargets == null) {
return;
}
mBuilder = new SpannableStringBuilder(withTargets);
replaceTarget(BTN_TARGET, mButtonText);
replaceUrlTarget(TOS_TARGET, R.string.fui_terms_of_service, mFlowParameters.termsOfServiceUrl);
replaceUrlTarget(PP_TARGET, R.string.fui_privacy_policy, mFlowParameters.privacyPolicyUrl);
}
private void replaceTarget(String target, @StringRes int replacementRes) {
int targetIndex = mBuilder.toString().indexOf(target);
if (targetIndex != -1) {
String replacement = mContext.getString(replacementRes);
mBuilder.replace(targetIndex, targetIndex + target.length(), replacement);
}
}
private void replaceUrlTarget(String target, @StringRes int replacementRes, String url) {
int targetIndex = mBuilder.toString().indexOf(target);
if (targetIndex != -1) {
String replacement = mContext.getString(replacementRes);
mBuilder.replace(targetIndex, targetIndex + target.length(), replacement);
int end = targetIndex + replacement.length();
mBuilder.setSpan(mLinkSpan, targetIndex, end, 0);
mBuilder.setSpan(new CustomTabsSpan(mContext, url), targetIndex, end, 0);
}
}
@Nullable
private String getPreambleStringWithTargets(@StringRes int textViewText, boolean hasButton) {
boolean termsOfServiceUrlProvided = !TextUtils.isEmpty(mFlowParameters.termsOfServiceUrl);
boolean privacyPolicyUrlProvided = !TextUtils.isEmpty(mFlowParameters.privacyPolicyUrl);
if (termsOfServiceUrlProvided && privacyPolicyUrlProvided) {
Object[] targets = hasButton ?
new Object[]{BTN_TARGET, TOS_TARGET, PP_TARGET}
: new Object[]{TOS_TARGET, PP_TARGET};
return mContext.getString(textViewText, targets);
}
return null;
}
private static final class CustomTabsSpan extends ClickableSpan {
private final WeakReference<Context> mContext;
private final String mUrl;
private final CustomTabsIntent mCustomTabsIntent;
public CustomTabsSpan(Context context, String url) {
mContext = new WeakReference<>(context);
mUrl = url;
// Getting default color
TypedValue typedValue = new TypedValue();
context.getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
@ColorInt int color = typedValue.data;
mCustomTabsIntent = new CustomTabsIntent.Builder()
.setToolbarColor(color)
.setShowTitle(true)
.build();
}
@Override
public void onClick(View widget) {
Context context = mContext.get();
if (context != null) {
mCustomTabsIntent.launchUrl(context, Uri.parse(mUrl));
}
}
}
}
|
/*
* Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.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.orientechnologies.orient.test.database.auto;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.testng.Assert;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
@Test(groups = "sql-select")
public class SQLSelectGroupByTest extends DocumentDBBaseTest {
@Parameters(value = "url")
public SQLSelectGroupByTest(@Optional String url) {
super(url);
}
@Test
public void queryGroupByBasic() {
List<ODocument> result = database.command(new OSQLSynchQuery<ODocument>("select location from Account group by location"))
.execute();
Assert.assertTrue(result.size() > 1);
Set<Object> set = new HashSet<Object>();
for (ODocument d : result)
set.add(d.field("location"));
Assert.assertEquals(result.size(), set.size());
}
@Test
public void queryGroupByCount() {
List<ODocument> result = database.command(new OSQLSynchQuery<ODocument>("select count(*) from Account group by location"))
.execute();
Assert.assertTrue(result.size() > 1);
}
@Test
public void queryGroupByAndOrderBy() {
List<ODocument> result = database.command(
new OSQLSynchQuery<ODocument>("select location from Account group by location order by location")).execute();
Assert.assertTrue(result.size() > 1);
String last = null;
for (ODocument d : result) {
if (last != null)
Assert.assertTrue(last.compareTo((String) d.field("location")) < 0);
last = d.field("location");
}
result = database.command(
new OSQLSynchQuery<ODocument>("select location from Account group by location order by location desc")).execute();
Assert.assertTrue(result.size() > 1);
last = null;
for (ODocument d : result) {
if (last != null)
Assert.assertTrue(last.compareTo((String) d.field("location")) > 0);
last = d.field("location");
}
}
}
|
package org.pdxfinder.graph.repositories;
import org.pdxfinder.graph.dao.CurrentTreatment;
import org.springframework.data.neo4j.repository.Neo4jRepository;
import org.springframework.stereotype.Repository;
/*
* Created by csaba on 25/07/2018.
*/
@Repository
public interface CurrentTreatmentRepository extends Neo4jRepository<CurrentTreatment, Long>{
CurrentTreatment findByName(String name);
}
|
package red.jackf.chesttracker.gui;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.screen.ingame.CreativeInventoryScreen;
import net.minecraft.client.gui.screen.ingame.HandledScreen;
import net.minecraft.client.gui.screen.recipebook.RecipeBookProvider;
import net.minecraft.client.gui.screen.recipebook.RecipeBookWidget;
import red.jackf.chesttracker.mixins.AccessorHandledScreen;
import red.jackf.chesttracker.resource.ButtonPositionManager;
import java.util.Map;
@Environment(EnvType.CLIENT)
public abstract class ButtonPositions {
public static int getX(HandledScreen<?> screen, int buttonIndex) {
Map<String, ButtonPositionManager.ButtonPosition> overrides = ButtonPositionManager.getOverrides();
String className = screen.getClass().getSimpleName();
if (overrides.containsKey(className)) {
ButtonPositionManager.ButtonPosition position = overrides.get(className);
int x = MinecraftClient.getInstance().getWindow().getScaledWidth();
if (position.horizontalAlignment == ButtonPositionManager.HorizontalAlignment.LEFT) {
x -= ((AccessorHandledScreen) screen).getBackgroundWidth();
} else {
x += ((AccessorHandledScreen) screen).getBackgroundWidth();
}
if (doRecipeAdjust(screen)) {
x += 77 * 2;
}
return (x / 2) + position.horizontalOffset;
}
int x = (MinecraftClient.getInstance().getWindow().getScaledWidth() + ((AccessorHandledScreen) screen).getBackgroundWidth()) / 2;
if (doRecipeAdjust(screen))
x += 77;
return x - 14 - (11 * buttonIndex);
}
public static int getY(HandledScreen<?> screen, int buttonIndex) {
Map<String, ButtonPositionManager.ButtonPosition> overrides = ButtonPositionManager.getOverrides();
String className = screen.getClass().getSimpleName();
if (overrides.containsKey(className)) {
ButtonPositionManager.ButtonPosition position = overrides.get(className);
int y = MinecraftClient.getInstance().getWindow().getScaledHeight();
if (position.verticalAlignment == ButtonPositionManager.VerticalAlignment.TOP) {
y -= ((AccessorHandledScreen) screen).getBackgroundHeight();
} else {
y += ((AccessorHandledScreen) screen).getBackgroundHeight();
}
return (y / 2) + position.verticalOffset;
}
int y = (MinecraftClient.getInstance().getWindow().getScaledHeight() - ((AccessorHandledScreen) screen).getBackgroundHeight()) / 2;
if (!(screen instanceof CreativeInventoryScreen)) {
y -= 15;
}
return y + 5;
}
protected static boolean doRecipeAdjust(Screen screen) {
if (screen instanceof RecipeBookProvider) {
RecipeBookWidget widget = ((RecipeBookProvider) screen).getRecipeBookWidget();
return widget.isOpen();
}
return false;
}
}
|
package org.innovateuk.ifs.application.documentation;
import org.innovateuk.ifs.BaseControllerMockMVCTest;
import org.innovateuk.ifs.application.controller.ApplicationAssessmentSummaryController;
import org.innovateuk.ifs.application.resource.ApplicationAssessmentSummaryResource;
import org.innovateuk.ifs.application.resource.ApplicationAssessorResource;
import org.innovateuk.ifs.application.resource.ApplicationAvailableAssessorPageResource;
import org.innovateuk.ifs.application.resource.ApplicationAvailableAssessorResource.Sort;
import org.innovateuk.ifs.application.transactional.ApplicationAssessmentSummaryService;
import org.junit.Test;
import org.mockito.Mock;
import java.util.Collections;
import java.util.List;
import static java.util.Arrays.asList;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess;
import static org.innovateuk.ifs.documentation.ApplicationAssessmentSummaryResourceDocs.applicationAssessmentSummaryFields;
import static org.innovateuk.ifs.documentation.ApplicationAssessmentSummaryResourceDocs.applicationAssessmentSummaryResourceBuilder;
import static org.innovateuk.ifs.documentation.ApplicationAssessorResourceDocs.applicationAssessorFields;
import static org.innovateuk.ifs.documentation.ApplicationAssessorResourceDocs.applicationAssessorResourceBuilder;
import static org.innovateuk.ifs.documentation.PageResourceDocs.pageResourceFields;
import static org.mockito.Mockito.*;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
import static org.springframework.restdocs.request.RequestDocumentation.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
public class ApplicationAssessmentSummaryControllerDocumentation extends BaseControllerMockMVCTest<ApplicationAssessmentSummaryController> {
@Mock
private ApplicationAssessmentSummaryService applicationAssessmentSummaryServiceMock;
@Override
protected ApplicationAssessmentSummaryController supplyControllerUnderTest() {
return new ApplicationAssessmentSummaryController();
}
@Test
public void getAssessors() throws Exception {
Long applicationId = 1L;
List<ApplicationAssessorResource> applicationAssessorResources = applicationAssessorResourceBuilder.build(2);
when(applicationAssessmentSummaryServiceMock.getAssignedAssessors(applicationId)).thenReturn(serviceSuccess(applicationAssessorResources));
mockMvc.perform(get("/application-assessment-summary/{id}/assigned-assessors", applicationId)
.header("IFS_AUTH_TOKEN", "123abc"))
.andExpect(status().isOk())
.andDo(document("applicationassessmentsummary/{method-name}",
pathParameters(
parameterWithName("id").description("Id of the application")
),
responseFields(fieldWithPath("[]").description("List of assessors participating on the competition of the application"))
.andWithPrefix("[].", applicationAssessorFields)
));
verify(applicationAssessmentSummaryServiceMock, only()).getAssignedAssessors(applicationId);
}
@Test
public void getApplicationAssessmentSummary() throws Exception {
Long applicationId = 1L;
ApplicationAssessmentSummaryResource applicationAssessmentSummaryResource = applicationAssessmentSummaryResourceBuilder.build();
when(applicationAssessmentSummaryServiceMock.getApplicationAssessmentSummary(applicationId)).thenReturn(serviceSuccess(applicationAssessmentSummaryResource));
mockMvc.perform(get("/application-assessment-summary/{id}", applicationId)
.header("IFS_AUTH_TOKEN", "123abc"))
.andExpect(status().isOk())
.andDo(document("applicationassessmentsummary/{method-name}",
pathParameters(
parameterWithName("id").description("Id of the application")
),
responseFields(applicationAssessmentSummaryFields)
));
verify(applicationAssessmentSummaryServiceMock, only()).getApplicationAssessmentSummary(applicationId);
}
@Test
public void getAvailableAssessors() throws Exception {
long applicationId = 1L;
int pageIndex = 1;
int pageSize = 1;
String assessorNameFilter = "assessorNameFilter";
Sort sort = Sort.ASSESSOR;
ApplicationAvailableAssessorPageResource page = new ApplicationAvailableAssessorPageResource(1L, 1, Collections.emptyList(),1 ,1);
when(applicationAssessmentSummaryServiceMock.getAvailableAssessors(applicationId, pageIndex, pageSize, assessorNameFilter, sort)).thenReturn(serviceSuccess(page));
mockMvc.perform(get("/application-assessment-summary/{applicationId}/available-assessors?page={page}&size={size}&assessorNameFilter={assessorNameFilter}&sort={sort}", applicationId, pageIndex, pageSize, assessorNameFilter, sort)
.header("IFS_AUTH_TOKEN", "123abc"))
.andExpect(status().isOk())
.andDo(document("applicationassessmentsummary/{method-name}",
pathParameters(
parameterWithName("applicationId").description("Id of the application")
),
requestParameters(
parameterWithName("page").description("Index of the page to get"),
parameterWithName("size").description("Size of the page"),
parameterWithName("assessorNameFilter").description("Assessor name filter"),
parameterWithName("sort").description("Sort order")
),
responseFields(
pageResourceFields
)
));
verify(applicationAssessmentSummaryServiceMock, only()).getAvailableAssessors(applicationId, pageIndex, pageSize, assessorNameFilter, sort);
}
@Test
public void getAvailableAssessorsIds() throws Exception {
long applicationId = 1L;
String assessorNameFilter = "assessorNameFilter";
when(applicationAssessmentSummaryServiceMock.getAvailableAssessorIds(applicationId, assessorNameFilter)).thenReturn(serviceSuccess(asList(1L, 2L)));
mockMvc.perform(get("/application-assessment-summary/{applicationId}/available-assessors-ids?assessorNameFilter={assessorNameFilter}", applicationId, assessorNameFilter)
.header("IFS_AUTH_TOKEN", "123abc"))
.andExpect(status().isOk())
.andDo(document("applicationassessmentsummary/{method-name}",
pathParameters(
parameterWithName("applicationId").description("Id of the application")
),
requestParameters(
parameterWithName("assessorNameFilter").description("Assessor name filter")
),
responseFields(
fieldWithPath("[]").description("ids")
)
));
verify(applicationAssessmentSummaryServiceMock, only()).getAvailableAssessorIds(applicationId, assessorNameFilter);
}
}
|
/*
The MIT License (MIT)
Copyright (c) 2016 Pierre Lindenbaum
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.github.lindenb.jvarkit.tools.misc;
import htsjdk.samtools.util.CloserUtil;
import htsjdk.variant.variantcontext.VariantContext;
import htsjdk.variant.variantcontext.VariantContextBuilder;
import htsjdk.variant.variantcontext.writer.VariantContextWriter;
import htsjdk.variant.vcf.VCFHeader;
import htsjdk.variant.vcf.VCFHeaderLine;
import htsjdk.variant.vcf.VCFHeaderLineCount;
import htsjdk.variant.vcf.VCFHeaderLineType;
import htsjdk.variant.vcf.VCFInfoHeaderLine;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
import com.beust.jcommander.Parameter;
import com.github.lindenb.jvarkit.util.jcommander.Launcher;
import com.github.lindenb.jvarkit.util.jcommander.Program;
import com.github.lindenb.jvarkit.util.log.Logger;
import com.github.lindenb.jvarkit.util.picard.SAMSequenceDictionaryProgress;
import com.github.lindenb.jvarkit.util.tabix.AbstractTabixObjectReader;
import com.github.lindenb.jvarkit.util.vcf.VcfIterator;
/**
BEGIN_DOC
## Building the Tabix File for regulomeDB:
```bash
(for S in 1 2 3 4 5 6 ; do curl -s "http://regulome.stanford.edu/downloads/RegulomeDB.dbSNP132.Category${S}.txt.gz" | gunzip -c | cut -f 1,2,5 | sed -e 's/^chrX/23/' -e 's/^chr//' | awk -F ' ' '{printf("%s\t%d\t%s\t%s\n",$1,int($2)-1,$2,$3);}' | uniq ; done)| LC_ALL=C sort -t ' ' -k1,1n -k2,2n -k3,3n | sed 's/^23/X/' | bgzip -c > regulomeDB.bed.gz && tabix -p bed -f regulomeDB.bed.gz
```
## Example
```bash
$ curl -kLs "https://raw.githubusercontent.com/arq5x/gemini/master/test/ALL.wgs.phase1_release_v3.20101123.snps_indels_sv.sites.snippet.snpEff.vcf" |\
java -jar dist/vcfstripannot.jar -k '*' |\
java -jar dist/vcfregulomedb.jar -b regulomeDB.bed.gz -x 10 |\
grep -i REGU | head
##INFO=<ID=REGULOMEDB,Number=.,Type=String,Description="Format: Position|Distance|Rank">
##VcfRegulomeDBCmdLine=-b regulomeDB.bed.gz -x 10
##VcfRegulomeDBVersion=235a18b083ea15c4ad94060de512f1edc74cec42
1 10583 rs58108140 G A 100 PASS REGULOMEDB=10582|0|5
1 13327 rs144762171 G C 100 PASS REGULOMEDB=13326|0|6
1 13980 rs151276478 T C 100 PASS REGULOMEDB=13971|8|6,13979|0|6,13980|1|6
1 46402 . C CTGT 31 PASS REGULOMEDB=46402|1|6
1 55164 rs3091274 C A 100 PASS REGULOMEDB=55163|0|6
1 55299 rs10399749 C T 100 PASS REGULOMEDB=55298|0|6
1 55313 rs182462964 A T 100 PASS REGULOMEDB=55321|9|6
1 55326 rs3107975 T C 100 PASS REGULOMEDB=55321|4|6,55325|0|6
1 55330 rs185215913 G A 100 PASS REGULOMEDB=55321|8|6,55325|4|6
```
Those SNPs can be seen at:
* http://regulome.stanford.edu/snp/chr1/10582
* http://regulome.stanford.edu/snp/chr1/13326
* http://regulome.stanford.edu/snp/chr1/13971
* http://regulome.stanford.edu/snp/chr1/46402
* etc...
END_DOC
*/
@Program(name="vcfregulomedb",description="Annotate a VCF with the Regulome data (http://regulome.stanford.edu/")
public class VcfRegulomeDB extends Launcher
{
private static final Logger LOG = Logger.build(VcfRegulomeDB.class).make();
@Parameter(names={"-o","--output"},description=OPT_OUPUT_FILE_OR_STDOUT)
private File outputFile = null;
@Parameter(names="-b",description=" bed indexed with tabix. Format: chrom(tab)start(tab)end(tab)rank",required=true)
private String bedFile=null;
@Parameter(names="-T",description="tag in vcf INFO.")
private String infoTag="REGULOMEDB";
@Parameter(names="-x",description="(int) base pairs. look.for data around the variation +/- 'x' ")
private int extend=5;
@Parameter(names="-r",description="if defined, only accept the rank matching the regular expression ")
private String acceptRegexStr=null;
private Pattern acceptRegex=null;
private RegDataTabixFileReader regDataTabixFileReader=null;
private static class RegData
{
@SuppressWarnings("unused")
String chrom;
int chromSart;
@SuppressWarnings("unused")
int chromEnd;
String rank;
RegData(String tokens[])
{
this.chrom=tokens[0];
this.chromSart=Integer.parseInt(tokens[1]);
this.chromEnd=Integer.parseInt(tokens[2]);
this.rank=tokens[3];
}
}
private static class RegDataTabixFileReader
extends AbstractTabixObjectReader<RegData>
{
RegDataTabixFileReader(String uri) throws IOException
{
super(uri);
}
@Override
protected Iterator<RegData> iterator(Iterator<String> delegate) {
return new MyIterator(delegate);
}
private class MyIterator
extends AbstractMyIterator
{
private Pattern tab=Pattern.compile("[\t]");
MyIterator(Iterator<String> delegate)
{
super(delegate);
}
@Override
public RegData next() {
return new RegData(this.tab.split(delegate.next(),5));
}
}
}
private VcfRegulomeDB()
{
}
@Override
protected int doVcfToVcf(String inputName, VcfIterator in,
VariantContextWriter out)
{
VCFHeader header=in.getHeader();
SAMSequenceDictionaryProgress progress=new SAMSequenceDictionaryProgress(header.getSequenceDictionary());
header.addMetaDataLine(new VCFHeaderLine(getClass().getSimpleName()+"CmdLine",String.valueOf(getProgramCommandLine())));
header.addMetaDataLine(new VCFHeaderLine(getClass().getSimpleName()+"Version",String.valueOf(getVersion())));
header.addMetaDataLine(new VCFInfoHeaderLine(
this.infoTag,
VCFHeaderLineCount.UNBOUNDED,
VCFHeaderLineType.String,
"Format: Position|Distance|Rank"
));
out.writeHeader(header);
while(in.hasNext())
{
List<String> regDataList=new ArrayList<String>();
VariantContext ctx=in.next();
progress.watch(ctx.getContig(),ctx.getStart());
int start=Math.max(0,ctx.getStart()-this.extend);
int end=ctx.getEnd()+this.extend;
for(Iterator<RegData> iter=this.regDataTabixFileReader.iterator(ctx.getContig(), start, end);
iter.hasNext();
)
{
RegData curr=iter.next();
if(this.acceptRegex!=null &&
!this.acceptRegex.matcher(curr.rank).matches()
)
{
continue;
}
String str=
String.valueOf(curr.chromSart)+"|"+
String.valueOf(Math.abs(curr.chromSart-(ctx.getStart()-1)))+"|"+
curr.rank;
regDataList.add(str);
}
if(regDataList.isEmpty())
{
out.add(ctx);
continue;
}
VariantContextBuilder vcb=new VariantContextBuilder(ctx);
vcb.attribute(this.infoTag, regDataList.toArray());
out.add(vcb.make());
}
progress.finish();
return 0;
}
@Override
public int doWork(List<String> args)
{
if(bedFile==null)
{
LOG.error("Bed file indexed with tabix is missing");
return -1;
}
try
{
if(this.acceptRegexStr!=null)
{
this.acceptRegex=Pattern.compile(this.acceptRegexStr);
}
LOG.info("Opening "+bedFile);
this.regDataTabixFileReader=new RegDataTabixFileReader(bedFile);
return doVcfToVcf(args, outputFile);
}
catch(Exception err)
{
LOG.error(err);
return -1;
}
finally
{
CloserUtil.close(this.regDataTabixFileReader);
}
}
public static void main(String[] args)
{
new VcfRegulomeDB().instanceMainWithExit(args);
}
}
|
package net.minecraft.util;
import net.minecraft.entity.Entity;
public class MovingObjectPosition
{
private BlockPos blockPos;
/** What type of ray trace hit was this? 0 = block, 1 = entity */
public MovingObjectType typeOfHit;
public EnumFacing sideHit;
/** The vector position of the hit */
public Vec3 hitVec;
/** The hit entity */
public Entity entityHit;
public MovingObjectPosition(Vec3 hitVecIn, EnumFacing facing, BlockPos blockPosIn)
{
this(MovingObjectType.BLOCK, hitVecIn, facing, blockPosIn);
}
public MovingObjectPosition(Vec3 p_i45552_1_, EnumFacing facing)
{
this(MovingObjectType.BLOCK, p_i45552_1_, facing, BlockPos.ORIGIN);
}
public MovingObjectPosition(Entity p_i2304_1_)
{
this(p_i2304_1_, new Vec3(p_i2304_1_.posX, p_i2304_1_.posY, p_i2304_1_.posZ));
}
public MovingObjectPosition(MovingObjectType typeOfHitIn, Vec3 hitVecIn, EnumFacing sideHitIn, BlockPos blockPosIn)
{
this.typeOfHit = typeOfHitIn;
this.blockPos = blockPosIn;
this.sideHit = sideHitIn;
this.hitVec = new Vec3(hitVecIn.xCoord, hitVecIn.yCoord, hitVecIn.zCoord);
}
public MovingObjectPosition(Entity entityHitIn, Vec3 hitVecIn)
{
this.typeOfHit = MovingObjectType.ENTITY;
this.entityHit = entityHitIn;
this.hitVec = hitVecIn;
}
public BlockPos getBlockPos()
{
return this.blockPos;
}
public String toString()
{
return "HitResult{type=" + this.typeOfHit + ", blockpos=" + this.blockPos + ", f=" + this.sideHit + ", pos=" + this.hitVec + ", entity=" + this.entityHit + '}';
}
public static enum MovingObjectType
{
MISS,
BLOCK,
ENTITY;
}
}
|
/*
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Thahzan Mohomed
*
* 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 de.blackcraze.grb.util.wagu;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Thedath Oudarya
*/
public final class Table {
private Board board;
@SuppressWarnings("unused")
private final int tableWidth;
private List<String> headersList;
private List<List<String>> rowsList;
private List<Integer> colWidthsList;
private List<Integer> colAlignsList;
private int headerHeight;
private int rowHeight;
private int gridMode;
private Block initialTableBlock;
public final static int GRID_NON = 13;
public final static int GRID_FULL = 14;
public final static int GRID_COLUMN = 15;
public Table(Board board, int tableWidth, List<String> headersList,
List<List<String>> rowsList) {
this.board = board;
if (tableWidth <= 0) {
throw new RuntimeException(
"Board width must be large than zero. " + tableWidth + " given.");
} else {
this.tableWidth = tableWidth;
}
if (headersList.size() <= 0) {
throw new RuntimeException(
"Header size must be large than zero. " + headersList.size() + " found.");
} else {
this.headersList = headersList;
}
for (int i = 0; i < rowsList.size(); i++) {
List<String> row = rowsList.get(i);
if (row.size() != headersList.size()) {
throw new RuntimeException("Size(" + row.size() + ") of the row(" + i
+ ") and header size(" + headersList.size() + ") are not equal.");
}
}
this.rowsList = rowsList;
this.colWidthsList = new ArrayList<>();
int avgWidthOfCol = (tableWidth - (gridMode == GRID_NON ? 0 : headersList.size() + 1))
/ headersList.size();
int availableForExtend = (tableWidth - (gridMode == GRID_NON ? 0 : headersList.size() + 1))
% headersList.size();
for (int i = 0; i < headersList.size(); i++, availableForExtend--) {
int finalWidth = avgWidthOfCol + (availableForExtend > 0 ? 1 : 0);
this.colWidthsList.add(finalWidth);
}
this.colAlignsList = new ArrayList<>();
List<String> firstRow = rowsList.get(0);
for (String cell : firstRow) {
int alignMode;
try {
Long.parseLong(cell);
alignMode = Block.DATA_MIDDLE_RIGHT;
} catch (NumberFormatException e0) {
try {
Integer.parseInt(cell);
alignMode = Block.DATA_MIDDLE_RIGHT;
} catch (NumberFormatException e1) {
try {
Double.parseDouble(cell);
alignMode = Block.DATA_MIDDLE_RIGHT;
} catch (NumberFormatException e2) {
alignMode = Block.DATA_MIDDLE_LEFT;
}
}
}
this.colAlignsList.add(alignMode);
}
headerHeight = 1;
rowHeight = 1;
gridMode = GRID_COLUMN;
}
public Table(Board board, int tableWidth, List<String> headersList, List<List<String>> rowsList,
List<Integer> colWidthsList) {
this(board, tableWidth, headersList, rowsList);
if (colWidthsList.size() != headersList.size()) {
throw new RuntimeException("Column width count(" + colWidthsList.size()
+ ") and header size(" + headersList.size() + ") are not equal.");
} else {
this.colWidthsList = colWidthsList;
}
}
public Table(Board board, int tableWidth, List<String> headersList, List<List<String>> rowsList,
List<Integer> colWidthsList, List<Integer> colAlignsList) {
this(board, tableWidth, headersList, rowsList, colWidthsList);
if (colAlignsList.size() != headersList.size()) {
throw new RuntimeException("Column align count(" + colAlignsList.size()
+ ") and header size(" + headersList.size() + ") are not equal.");
} else {
this.colAlignsList = colAlignsList;
}
}
public List<String> getHeadersList() {
return headersList;
}
public Table setHeadersList(List<String> headersList) {
this.headersList = headersList;
return this;
}
public List<List<String>> getRowsList() {
return rowsList;
}
public Table setRowsList(List<List<String>> rowsList) {
this.rowsList = rowsList;
return this;
}
public List<Integer> getColWidthsList() {
return colWidthsList;
}
public Table setColWidthsList(List<Integer> colWidthsList) {
if (colWidthsList.size() != headersList.size()) {
throw new RuntimeException("Column width count(" + colWidthsList.size()
+ ") and header size(" + headersList.size() + ") are not equal.");
} else {
this.colWidthsList = colWidthsList;
}
return this;
}
public List<Integer> getColAlignsList() {
return colAlignsList;
}
public Table setColAlignsList(List<Integer> colAlignsList) {
if (colAlignsList.size() != headersList.size()) {
throw new RuntimeException("Column align count(" + colAlignsList.size()
+ ") and header size(" + headersList.size() + ") are not equal.");
} else {
this.colAlignsList = colAlignsList;
}
return this;
}
public int getHeaderHeight() {
return headerHeight;
}
public Table setHeaderHeight(int headerHeight) {
this.headerHeight = headerHeight;
return this;
}
public int getRowHeight() {
return rowHeight;
}
public Table setRowHeight(int rowHeight) {
this.rowHeight = rowHeight;
return this;
}
public int getGridMode() {
return gridMode;
}
public Table setGridMode(int gridMode) {
if (gridMode == GRID_NON || gridMode == GRID_FULL || gridMode == GRID_COLUMN) {
this.gridMode = gridMode;
} else {
throw new RuntimeException("Invalid grid mode. " + gridMode + " given.");
}
return this;
}
public Block tableToBlocks() {
for (int i = 0; i < headersList.size(); i++) {
String headerValue = headersList.get(i);
int columnWidth = colWidthsList.get(i);
Block block = new Block(board, columnWidth, headerHeight, headerValue);
if (getGridMode() == GRID_NON) {
block.allowGrid(false);
} else {
block.allowGrid(true);
}
int alignIndex = colAlignsList.get(i);
block.setDataAlign(alignIndex);
if (initialTableBlock == null) {
initialTableBlock = block;
} else {
initialTableBlock.getMostRightBlock().setRightBlock(block);
}
}
if (getGridMode() != GRID_COLUMN) {
for (int i = 0; i < rowsList.size(); i++) {
List<String> row = rowsList.get(i);
Block rowStartingBlock = initialTableBlock.getMostBelowBlock();
for (int j = 0; j < row.size(); j++) {
String rowValue = row.get(j);
int columnWidth = colWidthsList.get(j);
Block block = new Block(board, columnWidth, rowHeight, rowValue);
if (getGridMode() == GRID_NON) {
block.allowGrid(false);
} else {
block.allowGrid(true);
}
int alignIndex = colAlignsList.get(j);
block.setDataAlign(alignIndex);
if (rowStartingBlock.getBelowBlock() == null) {
rowStartingBlock.setBelowBlock(block);
} else {
rowStartingBlock.getBelowBlock().getMostRightBlock().setRightBlock(block);
}
}
}
} else {
for (int i = 0; i < headersList.size(); i++) {
String columnData = "";
for (int j = 0; j < rowsList.size(); j++) {
String rowData = rowsList.get(j).get(i);
columnData = columnData.concat(rowData).concat("\n");
}
Block block = new Block(board, colWidthsList.get(i), rowsList.size(), columnData);
int alignIndex = colAlignsList.get(i);
block.setDataAlign(alignIndex);
if (initialTableBlock.getBelowBlock() == null) {
initialTableBlock.setBelowBlock(block);
} else {
initialTableBlock.getBelowBlock().getMostRightBlock().setRightBlock(block);
}
}
}
return initialTableBlock;
}
public Table invalidate() {
initialTableBlock = null;
return this;
}
}
|
package org.iubbo.proxy.service.impl;
import org.iubbo.proxy.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.concurrent.TimeUnit;
/**
* @author idea
* @date 2019/7/18
* @version V1.0
*/
@Service
public class RedisServiceImpl implements RedisService {
@Autowired
private StringRedisTemplate template;
@Autowired
private RedisTemplate<Object, Object> redisTemplate;
@Override
public String getString(String key) {
ValueOperations<String, String> operations = template.opsForValue();
String value = operations.get(key);
return value;
}
@Override
public void setString(String key, String value) {
if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) {
return;
}
ValueOperations<String, String> operations = template.opsForValue();
operations.set(key, value);
}
@Override
public void setString(String key, String value, Long time, TimeUnit timeUnit) {
if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) {
return;
}
ValueOperations<String, String> operations = template.opsForValue();
operations.set(key, value, time, timeUnit);
}
@Override
public Integer getInt(String key) {
if (StringUtils.isEmpty(key)) {
return null;
}
ValueOperations<String, String> operations = template.opsForValue();
String val = operations.get(key);
if (val!=null && val!="" ) {
return Integer.valueOf(val);
} else {
return null;
}
}
@Override
public <T> T getObject(String key, Class<T> clazz) {
if (StringUtils.isEmpty(key)) {
return null;
}
ValueOperations<Object, Object> valueOperations = redisTemplate.opsForValue();
Object object = valueOperations.get(key);
return (T) object;
}
@Override
public void del(String key) {
redisTemplate.delete(key);
}
@Override
public void setObject(String key, Object obj) {
if (StringUtils.isEmpty(key)) {
return;
}
ValueOperations<Object, Object> valueOperations = redisTemplate.opsForValue();
valueOperations.set(key, obj);
}
@Override
public void setObject(String key, Object obj, Long time, TimeUnit timeUnit) {
if (StringUtils.isEmpty(key)) {
return;
}
ValueOperations<Object, Object> valueOperations = redisTemplate.opsForValue();
valueOperations.set(key, obj, time, timeUnit);
}
@Override
public void rpush(String queueName, Object value) {
redisTemplate.opsForList().rightPush(queueName,value);
}
@Override
public Object rpop(String queueName) {
return redisTemplate.opsForList().rightPop(queueName);
}
@Override
public void lpush(String queueName, Object value) {
redisTemplate.opsForList().leftPush(queueName,value);
}
@Override
public Object lpop(String queueName) {
return redisTemplate.opsForList().leftPop(queueName);
}
@Override
public void setInt(String key, Integer value) {
if (StringUtils.isEmpty(key) && value != null) {
return;
}
ValueOperations<String, String> operations = template.opsForValue();
operations.set(key, String.valueOf(value));
}
@Override
public void setInt(String key, Integer value, Long time, TimeUnit timeUnit) {
if (StringUtils.isEmpty(key) && value != null) {
return;
}
ValueOperations<String, String> operations = template.opsForValue();
operations.set(key, String.valueOf(value), time, timeUnit);
}
}
|
/*******************************************************************************
* Copyright 2014 IBM
*
* 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.ibm.hrl.proton.epa.simple.operators;
import java.util.ArrayList;
import com.ibm.hrl.proton.epa.simple.abstractOperators.AbstractStandardOperator;
import com.ibm.hrl.proton.epa.state.OperatorData;
import com.ibm.hrl.proton.runtime.epa.IState;
import com.ibm.hrl.proton.runtime.epa.functions.IAbsenceProcessingFunction;
public class AbsenceOperator extends AbstractStandardOperator implements
IAbsenceProcessingFunction {
/*@Override
public MatchingSets match() {
// TODO Auto-generated method stub
return null;
}*/
@Override
/*
* This function is invoked from compose() and returns whether there was a match
* (the internal MatchingSet variable is updated with the result); in Absence we do not generate
* a matching set but only boolean indication regarding the match (empty internal state - true,
* otherwise - false).
*/
protected boolean process(int opNum) {
IState internalState = getInternalState();
OperatorData data = (OperatorData)internalState;
// currently the entire processing (call hierarchy) does not work with empty
// matching set, which is the case with the Absence pattern; should be special treatment
// another alternative is to push dummy event into matching set to support all places
// and this event would be ignored by derivation (trivial "empty" derivation for
// the Absence pattern is enforced by metadata)
// put a dummy matching set into matching sets
matchingSets.addMatchingSet(new ArrayList());
;
if (!data.isEmpty()) {
matchingSets.setPatternDetected(false);
}
return data.isEmpty();
}
/*@Override
public boolean addInstancetoState(IEventInstance eventInstance,Set<Operand> filteringResults) {
return false;
}
@Override
protected boolean checkOverride(IEventInstance eventInstance,
Operand operand) {
return false;
}
@Override
protected void addInstanceByPolicy(IEventInstance candidate,Operand operand)
{
addCandidateFirst(candidate, operand);
}*/
@Override
protected boolean operatorCompose() {
// TODO What this function should return for absence...
return false;
}
@Override
public boolean determineTerminationInstantiation() {
return true;
}
}
|
/*
* Copyright 2013 NGDATA nv
*
* 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.ngdata.hbaseindexer.indexer;
import static org.apache.zookeeper.ZooKeeper.States.CONNECTED;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.List;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.io.Resources;
import com.ngdata.hbaseindexer.HBaseIndexerConfiguration;
import com.ngdata.hbaseindexer.Main;
import com.ngdata.hbaseindexer.model.api.IndexerDefinition;
import com.ngdata.hbaseindexer.model.api.IndexerDefinition.IncrementalIndexingState;
import com.ngdata.hbaseindexer.model.api.IndexerDefinitionBuilder;
import com.ngdata.hbaseindexer.model.api.IndexerNotFoundException;
import com.ngdata.hbaseindexer.model.api.WriteableIndexerModel;
import com.ngdata.hbaseindexer.util.net.NetUtils;
import com.ngdata.hbaseindexer.util.solr.SolrTestingUtility;
import com.ngdata.sep.impl.SepReplicationSource;
import com.ngdata.sep.impl.SepTestUtil;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.replication.ReplicationAdmin;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.CloudSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Integration tests.
*
* <p>Hint: use "mvn -Dit.test=IndexerIT#methodname integration-test" to run individual tests.</p>
*/
public class IndexerIT {
private static boolean firstTest = true;
private static Configuration conf;
private static HBaseTestingUtility hbaseTestUtil;
private static SolrTestingUtility solrTestingUtility;
private static CloudSolrServer collection1;
private static CloudSolrServer collection2;
private Main main;
private int oldMasterEventCount;
private int oldSupervisorEventCount;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
// Note on the use of @BeforeClass:
// Ideally, we would tear up and down everything with each test. Unfortunately, due to connection
// leaks in HBase (CDH4.2), we can't do this. For example, ReplicationPeer.zkw isn't closed, and
// while we can work around that particular one by deleting replication peers first, there are
// still other issues that I haven't tracked down completely.
// On the plus side, since stuff keeps running between tests, they should run a bit faster.
// We'll use the same conf object for hbase master/rs, hbase-indexer, and hbase client
conf = HBaseIndexerConfiguration.create();
// The following are the standard settings that for hbase regionserver when using the SEP (see SEP docs)
conf.setBoolean(HConstants.REPLICATION_ENABLE_KEY, true);
conf.setLong("replication.source.sleepforretries", 50);
conf.set("replication.replicationsource.implementation", SepReplicationSource.class.getName());
hbaseTestUtil = new HBaseTestingUtility(conf);
hbaseTestUtil.startMiniZKCluster(1);
hbaseTestUtil.startMiniCluster(1);
int zkClientPort = hbaseTestUtil.getZkCluster().getClientPort();
conf.set("hbaseindexer.zookeeper.connectstring", "localhost:" + zkClientPort);
solrTestingUtility = new SolrTestingUtility(zkClientPort, NetUtils.getFreePort());
solrTestingUtility.start();
solrTestingUtility.uploadConfig("config1",
Resources.toByteArray(Resources.getResource(IndexerIT.class, "schema.xml")),
Resources.toByteArray(Resources.getResource(IndexerIT.class, "solrconfig.xml")));
solrTestingUtility.createCore("collection1_core1", "collection1", "config1", 1);
solrTestingUtility.createCore("collection2_core1", "collection2", "config1", 1);
collection1 = new CloudSolrServer(solrTestingUtility.getZkConnectString());
collection1.setDefaultCollection("collection1");
collection2 = new CloudSolrServer(solrTestingUtility.getZkConnectString());
collection2.setDefaultCollection("collection2");
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
if (collection1 != null) {
collection1.shutdown();
}
if (collection2 != null) {
collection2.shutdown();
}
// Stop Solr first, as it depends on ZooKeeper
if (solrTestingUtility != null) {
solrTestingUtility.stop();
}
if (hbaseTestUtil != null) {
hbaseTestUtil.shutdownMiniCluster();
}
}
@Before
public void setUpBeforeTest() throws Exception {
if (!firstTest) {
// Delete /ngdata from zookeeper
System.out.println(">>> Deleting /ngdata node from ZooKeeper");
cleanZooKeeper("localhost:" + hbaseTestUtil.getZkCluster().getClientPort(), "/ngdata");
// Delete all hbase tables
System.out.println(">>> Deleting all HBase tables");
HBaseAdmin admin = new HBaseAdmin(conf);
for (HTableDescriptor table : admin.listTables()) {
admin.disableTable(table.getName());
admin.deleteTable(table.getName());
}
admin.close();
// Delete all replication peers
System.out.println(">>> Deleting all replication peers from HBase");
ReplicationAdmin replAdmin = new ReplicationAdmin(conf);
for (String peerId : replAdmin.listPeers().keySet()) {
replAdmin.removePeer(peerId);
}
replAdmin.close();
SepTestUtil.waitOnAllReplicationPeersStopped();
// Clear Solr indexes
System.out.println(">>> Clearing Solr indexes");
collection1.deleteByQuery("*:*");
collection1.commit();
collection2.deleteByQuery("*:*");
collection2.commit();
} else {
firstTest = false;
}
main = new Main();
main.startServices(conf);
}
@After
public void tearDownAfterTest() throws Exception {
if (main != null) {
main.stopServices();
}
}
@Test
public void testBasicScenario() throws Exception {
// Create a table in HBase
createTable("table1", "family1");
// Add an indexer
WriteableIndexerModel indexerModel = main.getIndexerModel();
IndexerDefinition indexerDef = new IndexerDefinitionBuilder()
.name("indexer1")
.configuration("<indexer table='table1'><field name='field1_s' value='family1:qualifier1'/></indexer>".getBytes())
.connectionType("solr")
.connectionParams(ImmutableMap.of("solr.zk", solrTestingUtility.getZkConnectString(),
"solr.collection", "collection1"))
.build();
indexerModel.addIndexer(indexerDef);
// Ingest
HTable table = new HTable(conf, "table1");
Put put = new Put(b("row1"));
put.add(b("family1"), b("qualifier1"), b("value1"));
table.put(put);
// Commit Solr index and check data is present
waitForSolrDocumentCount(1);
// Delete
Delete delete = new Delete(b("row1"));
table.delete(delete);
table.delete(delete);
waitForSolrDocumentCount(0);
table.close();
}
@Test
public void testIndexerDefinitionChangesPickedUp() throws Exception {
createTable("table1", "family1");
WriteableIndexerModel indexerModel = main.getIndexerModel();
IndexerDefinition indexerDef = new IndexerDefinitionBuilder()
.name("indexer1")
.configuration("<indexer table='table1'><field name='field1_s' value='family1:qualifier1'/></indexer>".getBytes())
.connectionType("solr")
.connectionParams(ImmutableMap.of("solr.zk", solrTestingUtility.getZkConnectString(),
"solr.collection", "collection1"))
.build();
indexerModel.addIndexer(indexerDef);
HTable table = new HTable(conf, "table1");
Put put = new Put(b("row1"));
put.add(b("family1"), b("qualifier1"), b("value1"));
table.put(put);
// Also put a value which should not be processed by the current config
put = new Put(b("row2"));
put.add(b("family1"), b("qualifier2"), b("value1"));
table.put(put);
SepTestUtil.waitOnReplicationPeerReady(peerId("indexer1"));
SepTestUtil.waitOnReplication(conf, 60000L);
collection1.commit();
QueryResponse response = collection1.query(new SolrQuery("*:*"));
assertEquals(1, response.getResults().size());
// update indexer model
markEventCounts();
String lock = indexerModel.lockIndexer("indexer1");
indexerDef = new IndexerDefinitionBuilder()
.startFrom(indexerModel.getFreshIndexer("indexer1"))
.configuration(("<indexer table='table1'>" +
"<field name='field1_s' value='family1:qualifier1'/>" +
"<field name='field2_s' value='family1:qualifier2'/>" +
"</indexer>").getBytes())
.build();
indexerModel.updateIndexer(indexerDef, lock);
indexerModel.unlockIndexer(lock);
waitOnEventsProcessed(1);
put = new Put(b("row3"));
put.add(b("family1"), b("qualifier2"), b("value1"));
table.put(put);
SepTestUtil.waitOnReplication(conf, 60000L);
collection1.commit();
response = collection1.query(new SolrQuery("*:*"));
assertEquals(2, response.getResults().size());
table.close();
}
@Test
public void testTwoTablesTwoIndexers() throws Exception {
createTable("table1", "family1");
createTable("table2", "family1");
assertEquals(0, collection1.query(new SolrQuery("*:*")).getResults().size());
assertEquals(0, collection2.query(new SolrQuery("*:*")).getResults().size());
WriteableIndexerModel indexerModel = main.getIndexerModel();
IndexerDefinition indexerDef = new IndexerDefinitionBuilder()
.name("indexer1")
.configuration(("<indexer table='table1'>" +
"<field name='field1_s' value='family1:qualifier1'/>" +
"</indexer>").getBytes())
.connectionType("solr")
.connectionParams(ImmutableMap.of("solr.zk", solrTestingUtility.getZkConnectString(),
"solr.collection", "collection1"))
.build();
indexerModel.addIndexer(indexerDef);
indexerDef = new IndexerDefinitionBuilder()
.name("indexer2")
.configuration(("<indexer table='table2'>" +
"<field name='field1_s' value='family1:qualifier1'/>" +
"</indexer>").getBytes())
.connectionType("solr")
.connectionParams(ImmutableMap.of("solr.zk", solrTestingUtility.getZkConnectString(),
"solr.collection", "collection2"))
.build();
indexerModel.addIndexer(indexerDef);
HTable table1 = new HTable(conf, "table1");
HTable table2 = new HTable(conf, "table2");
Put put = new Put(b("row1"));
put.add(b("family1"), b("qualifier1"), b("value1"));
table1.put(put);
put = new Put(b("row2"));
put.add(b("family1"), b("qualifier1"), b("value1"));
table2.put(put);
SepTestUtil.waitOnReplicationPeerReady(peerId("indexer1"));
SepTestUtil.waitOnReplicationPeerReady(peerId("indexer2"));
SepTestUtil.waitOnReplication(conf, 60000L);
collection1.commit();
collection2.commit();
assertEquals(1, collection1.query(new SolrQuery("*:*")).getResults().size());
assertEquals(1, collection2.query(new SolrQuery("*:*")).getResults().size());
table1.close();
table2.close();
}
@Test
public void testIndexerIncrementalIndexingStates() throws Exception {
createTable("table1", "family1");
// First create an index in the default incremental indexing state (SUBSCRIBE_AND_CONSUME)
markEventCounts();
WriteableIndexerModel indexerModel = main.getIndexerModel();
IndexerDefinition indexerDef = new IndexerDefinitionBuilder()
.name("indexer1")
.configuration(("<indexer table='table1'>" +
"<field name='field1_s' value='family1:qualifier1'/>" +
"</indexer>").getBytes())
.connectionType("solr")
.connectionParams(ImmutableMap.of("solr.zk", solrTestingUtility.getZkConnectString(),
"solr.collection", "collection1"))
.build();
indexerModel.addIndexer(indexerDef);
// wait for 2 events because: first the indexer is added (= first event), then IndexerMaster
// updates it to assign subscription (= second event), and only then IndexerSupervisor will start the indexer
waitOnEventsProcessed(2);
// Make sure the SEP and indexer processes were started
assertEquals(1, main.getIndexerSupervisor().getRunningIndexers().size());
SepTestUtil.waitOnReplicationPeerReady(peerId("indexer1"));
// Now change to DO_NOT_SUBSCRIBE_STATE
markEventCounts();
String lock = indexerModel.lockIndexer("indexer1");
indexerDef = new IndexerDefinitionBuilder()
.startFrom(indexerModel.getFreshIndexer("indexer1"))
.incrementalIndexingState(IncrementalIndexingState.DO_NOT_SUBSCRIBE)
.build();
indexerModel.updateIndexer(indexerDef, lock);
indexerModel.unlockIndexer(lock);
waitOnEventsProcessed(1);
// Verify master removed the SEP subscription and unassigned the subscription ID
SepTestUtil.waitOnReplicationPeerStopped(peerId("indexer1"));
assertNull(indexerModel.getFreshIndexer("indexer1").getSubscriptionId());
// Verify supervisor stopped the indexer
assertEquals(0, main.getIndexerSupervisor().getRunningIndexers().size());
// Change to SUBSCRIBE_DO_NOT_CONSUME
markEventCounts();
lock = indexerModel.lockIndexer("indexer1");
indexerDef = new IndexerDefinitionBuilder()
.startFrom(indexerModel.getFreshIndexer("indexer1"))
.incrementalIndexingState(IncrementalIndexingState.SUBSCRIBE_DO_NOT_CONSUME)
.build();
indexerModel.updateIndexer(indexerDef, lock);
indexerModel.unlockIndexer(lock);
waitOnEventsProcessed(1);
// Verify master registered the SEP subscription and assigned the subscription ID
SepTestUtil.waitOnReplicationPeerReady(peerId("indexer1"));
assertNotNull(indexerModel.getFreshIndexer("indexer1").getSubscriptionId());
// Verify supervisor didn't start the indexer (because in state "do no consume")
assertEquals(0, main.getIndexerSupervisor().getRunningIndexers().size());
// Change again to default SUBSCRIBE_AND_CONSUME
markEventCounts();
lock = indexerModel.lockIndexer("indexer1");
indexerDef = new IndexerDefinitionBuilder()
.startFrom(indexerModel.getFreshIndexer("indexer1"))
.incrementalIndexingState(IncrementalIndexingState.SUBSCRIBE_AND_CONSUME)
.build();
indexerModel.updateIndexer(indexerDef, lock);
indexerModel.unlockIndexer(lock);
waitOnEventsProcessed(1);
// Verify supervisor started the indexer
assertEquals(1, main.getIndexerSupervisor().getRunningIndexers().size());
}
@Test
public void testDeleteIndexer() throws Exception {
createTable("table1", "family1");
// Create an index
markEventCounts();
WriteableIndexerModel indexerModel = main.getIndexerModel();
IndexerDefinition indexerDef = new IndexerDefinitionBuilder()
.name("indexer1")
.configuration(("<indexer table='table1'>" +
"<field name='field1_s' value='family1:qualifier1'/>" +
"</indexer>").getBytes())
.connectionType("solr")
.connectionParams(ImmutableMap.of("solr.zk", solrTestingUtility.getZkConnectString(),
"solr.collection", "collection1"))
.build();
indexerModel.addIndexer(indexerDef);
waitOnEventsProcessed(2);
// Make sure the SEP and indexer processes were started
assertEquals(1, main.getIndexerSupervisor().getRunningIndexers().size());
SepTestUtil.waitOnReplicationPeerReady(peerId("indexer1"));
// Now request to delete the indexer, this is done by changing the lifecycle state to DELETE_REQUESTED
markEventCounts();
String lock = indexerModel.lockIndexer("indexer1");
indexerDef = new IndexerDefinitionBuilder()
.startFrom(indexerModel.getFreshIndexer("indexer1"))
.lifecycleState(IndexerDefinition.LifecycleState.DELETE_REQUESTED)
.build();
indexerModel.updateIndexer(indexerDef, lock);
indexerModel.unlockIndexer(lock);
waitOnEventsProcessed(1);
// Check index was removed
try {
indexerModel.getFreshIndexer("indexer1");
fail("expected an IndexerNotFoundException");
} catch (IndexerNotFoundException e) {
// expected
}
// Verify master removed the SEP subscription
SepTestUtil.waitOnReplicationPeerStopped(peerId("indexer1"));
// Verify supervisor stopped the indexer
assertEquals(0, main.getIndexerSupervisor().getRunningIndexers().size());
}
/**
* When adding a new replication peer (= SEP consumer), HBase replication will deliver events starting
* from the beginning of the current hlog file. These events might already be quite a while in there (if
* there hasn't been much activity), which would lead to the surprising effect of these being indexed.
* Therefore, the SEP has the concept of a subscriptionTimestamp, and events older than that ts are
* ignored.
*/
@Test
public void testSubscriptionTimestamp() throws Exception {
createTable("table1", "family1");
HTable table = new HTable(conf, "table1");
for (int i = 0; i < 10; i++) {
Put put = new Put(b("row" + i));
put.add(b("family1"), b("qualifier1"), b("value1"));
table.put(put);
}
// Ensure that the index is added on a different timestamp than the last put
Thread.sleep(5);
WriteableIndexerModel indexerModel = main.getIndexerModel();
IndexerDefinition indexerDef = new IndexerDefinitionBuilder()
.name("indexer1")
.configuration(("<indexer table='table1'>" +
"<field name='field1_s' value='family1:qualifier1'/>" +
"</indexer>").getBytes())
.connectionType("solr")
.connectionParams(ImmutableMap.of("solr.zk", solrTestingUtility.getZkConnectString(),
"solr.collection", "collection1"))
.build();
indexerModel.addIndexer(indexerDef);
SepTestUtil.waitOnReplicationPeerReady(peerId("indexer1"));
SepTestUtil.waitOnReplication(conf, 60000L);
// Check that records created before the indexer was added are not indexed
collection1.commit();
SolrDocumentList results = collection1.query(new SolrQuery("*:*")).getResults();
assertEquals("Got results " + results + " while expecting none", 0, results.size());
// But newly added rows should be indexed
for (int i = 0; i < 10; i++) {
Put put = new Put(b("row_b_" + i));
put.add(b("family1"), b("qualifier1"), b("value1"));
table.put(put);
}
SepTestUtil.waitOnReplication(conf, 60000L);
collection1.commit();
assertEquals(10, collection1.query(new SolrQuery("*:*")).getResults().size());
table.close();
}
@Test
public void testCustomKeyFormatter() throws Exception {
createTable("table1", "family1");
HTable table = new HTable(conf, "table1");
StringBuilder indexerConf = new StringBuilder();
indexerConf.append("<indexer table='table1'");
indexerConf.append(" unique-key-formatter='com.ngdata.hbaseindexer.uniquekey.HexUniqueKeyFormatter'>");
indexerConf.append(" <field name='field1_s' value='family1:field1' type='string'/>");
indexerConf.append("</indexer>");
createIndexer1(indexerConf.toString());
SepTestUtil.waitOnReplicationPeerReady(peerId("indexer1"));
Put put = new Put(new byte[] { 0, 0, 0, 0 });
put.add(b("family1"), b("field1"), b("value1"));
table.put(put);
SepTestUtil.waitOnReplication(conf, 60000L);
collection1.commit();
QueryResponse response = collection1.query(new SolrQuery("*:*"));
assertEquals(1, response.getResults().size());
SolrDocument doc = response.getResults().get(0);
assertEquals("00000000", doc.getFirstValue("id").toString());
table.close();
}
@Test
public void testDefaultKeyFormatter() throws Exception {
createTable("table1", "family1");
HTable table = new HTable(conf, "table1");
StringBuilder indexerConf = new StringBuilder();
indexerConf.append("<indexer table='table1'>");
indexerConf.append(" <field name='field1_s' value='family1:field1' type='string'/>");
indexerConf.append("</indexer>");
createIndexer1(indexerConf.toString());
SepTestUtil.waitOnReplicationPeerReady(peerId("indexer1"));
Put put = new Put(new byte[] { 0, 0, 0, 0 });
put.add(b("family1"), b("field1"), b("value1"));
table.put(put);
SepTestUtil.waitOnReplication(conf, 60000L);
collection1.commit();
QueryResponse response = collection1.query(new SolrQuery("*:*"));
assertEquals(1, response.getResults().size());
SolrDocument doc = response.getResults().get(0);
assertEquals("#0;#0;#0;#0;", doc.getFirstValue("id").toString());
table.close();
}
@Test
public void testSomeDataTypesIncludingCustomValueMapper() throws Exception {
createTable("table1", "family1");
HTable table = new HTable(conf, "table1");
StringBuilder indexerConf = new StringBuilder();
indexerConf.append("<indexer table='table1'>");
indexerConf.append(" <field name='field1_s' value='family1:field1' type='string'/>");
indexerConf.append(" <field name='field2_s' value='family1:field2' type='int'/>");
indexerConf.append(" <field name='field3_ss' value='family1:field3' type='com.ngdata.hbaseindexer.indexer.CsvByteArrayValueMapper'>");
indexerConf.append(" <param name='defaults' value='default1,default2'/>");
indexerConf.append(" </field>");
indexerConf.append("</indexer>");
createIndexer1(indexerConf.toString());
SepTestUtil.waitOnReplicationPeerReady(peerId("indexer1"));
Put put = new Put(Bytes.toBytes("cry baby"));
put.add(b("family1"), b("field1"), b("value1"));
put.add(b("family1"), b("field2"), Bytes.toBytes(836));
put.add(b("family1"), b("field3"), b("blue,green,black,orange"));
table.put(put);
SepTestUtil.waitOnReplication(conf, 60000L);
collection1.commit();
QueryResponse response = collection1.query(new SolrQuery("*:*"));
assertEquals(1, response.getResults().size());
SolrDocument doc = response.getResults().get(0);
assertEquals("value1", doc.getFirstValue("field1_s"));
assertEquals(836, Integer.parseInt(doc.getFirstValue("field2_s").toString()));
assertEquals(6, doc.getFieldValues("field3_ss").size());
assertTrue(doc.getFieldValues("field3_ss").contains("orange"));
assertTrue(doc.getFieldValues("field3_ss").contains("default1"));
table.close();
}
@Test
public void testColumnMappingAndRowAndFamilySolrFields() throws Exception {
createTable("table1", "family1");
HTable table = new HTable(conf, "table1");
StringBuilder indexerConf = new StringBuilder();
indexerConf.append("<indexer table='table1'");
indexerConf.append(" unique-key-field='id'");
indexerConf.append(" row-field='row_s'");
indexerConf.append(" column-family-field='family_s'");
indexerConf.append(" mapping-type='column'>");
// one cell can map to a solr doc with multiple fields
indexerConf.append(" <field name='cell_s' value='family1:*' type='string'/>");
indexerConf.append(" <field name='cell_qualifier_s' value='family1:*' source='qualifier' type='string'/>");
indexerConf.append("</indexer>");
createIndexer1(indexerConf.toString());
SepTestUtil.waitOnReplicationPeerReady(peerId("indexer1"));
Put put = new Put(Bytes.toBytes("the row"));
put.add(b("family1"), b("col1"), b("value1"));
table.put(put);
put = new Put(Bytes.toBytes("the row"));
put.add(b("family1"), b("col2"), b("value2"));
table.put(put);
// 2 columns added in one call should still be mapped individually
put = new Put(Bytes.toBytes("the row"));
put.add(b("family1"), b("col3"), b("value3"));
put.add(b("family1"), b("col4"), b("value4"));
table.put(put);
SepTestUtil.waitOnReplication(conf, 60000L);
collection1.commit();
QueryResponse response = collection1.query(new SolrQuery("*:*"));
assertEquals(4, response.getResults().size());
response = collection1.query(new SolrQuery("+row_s:\"the row\""));
assertEquals(4, response.getResults().size());
response = collection1.query(new SolrQuery("+row_s:\"the row\" +family_s:family1"));
assertEquals(4, response.getResults().size());
for (String col : Lists.newArrayList("col1", "col2", "col3", "col4")) {
response = collection1.query(new SolrQuery("+cell_qualifier_s:" + col));
assertEquals(1, response.getResults().size());
}
response = collection1.query(new SolrQuery("+cell_s:value1"));
assertEquals(1, response.getResults().size());
table.close();
}
private void createIndexer1(String indexerConf) throws Exception {
WriteableIndexerModel indexerModel = main.getIndexerModel();
IndexerDefinition indexerDef = new IndexerDefinitionBuilder()
.name("indexer1")
.configuration(indexerConf.toString().getBytes())
.connectionType("solr")
.connectionParams(ImmutableMap.of("solr.zk", solrTestingUtility.getZkConnectString(),
"solr.collection", "collection1"))
.build();
indexerModel.addIndexer(indexerDef);
}
private void cleanZooKeeper(String zkConnectString, String rootToDelete) throws Exception {
int sessionTimeout = 10000;
ZooKeeper zk = new ZooKeeper(zkConnectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getState() == Watcher.Event.KeeperState.Disconnected) {
System.err.println("ZooKeeper Disconnected.");
} else if (event.getState() == Event.KeeperState.Expired) {
System.err.println("ZooKeeper session expired.");
}
}
});
long waitUntil = System.currentTimeMillis() + sessionTimeout;
while (zk.getState() != CONNECTED && waitUntil > System.currentTimeMillis()) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
break;
}
}
if (zk.getState() != CONNECTED) {
throw new RuntimeException("Failed to connect to ZK within " + sessionTimeout + "ms.");
}
if (zk.exists(rootToDelete, false) != null) {
List<String> paths = new ArrayList<String>();
collectChildren(rootToDelete, zk, paths);
paths.add(rootToDelete);
for (String path : paths) {
zk.delete(path, -1, null, null);
}
// The above deletes are async, wait for them to be finished
long startWait = System.currentTimeMillis();
while (zk.exists(rootToDelete, null) != null) {
Thread.sleep(5);
if (System.currentTimeMillis() - startWait > 120000) {
throw new RuntimeException("State was not cleared in ZK within the expected timeout");
}
}
}
zk.close();
}
private void collectChildren(String path, ZooKeeper zk, List<String> paths) throws InterruptedException, KeeperException {
List<String> children = zk.getChildren(path, false);
for (String child : children) {
String childPath = path + "/" + child;
collectChildren(childPath, zk, paths);
paths.add(childPath);
}
}
/**
* Creates a table wit one family, with replication enabled.
*/
private void createTable(String tableName, String familyName) throws Exception {
HTableDescriptor tableDescriptor = new HTableDescriptor(tableName);
HColumnDescriptor familyDescriptor = new HColumnDescriptor(familyName);
familyDescriptor.setScope(HConstants.REPLICATION_SCOPE_GLOBAL);
tableDescriptor.addFamily(familyDescriptor);
HBaseAdmin hbaseAdmin = new HBaseAdmin(conf);
hbaseAdmin.createTable(tableDescriptor);
hbaseAdmin.close();
}
private void waitForSolrDocumentCount(int count) throws Exception {
long waitUntil = System.currentTimeMillis() + 60000L;
int resultSize = 0;
while (resultSize != count) {
collection1.commit();
QueryResponse response = collection1.query(new SolrQuery("*:*"));
resultSize = response.getResults().size();
if (System.currentTimeMillis() > waitUntil) {
fail("Document not indexed in Solr within timeout");
} else {
System.out.println("Waiting on document to be available in Solr...");
}
Thread.sleep(20);
}
}
private void markEventCounts() {
oldMasterEventCount = main.getIndexerMaster().getEventCount();
oldSupervisorEventCount = main.getIndexerSupervisor().getEventCount();
}
private void waitOnEventsProcessed(int expectedEvents) throws InterruptedException {
waitOnEventCountChange(oldMasterEventCount, expectedEvents, new EventConsumer() {
@Override
public String getName() {
return "IndexerMaster";
}
@Override
public int getEventCount() {
return main.getIndexerMaster().getEventCount();
}
});
waitOnEventCountChange(oldSupervisorEventCount, expectedEvents, new EventConsumer() {
@Override
public String getName() {
return "IndexerSupervisor";
}
@Override
public int getEventCount() {
return main.getIndexerSupervisor().getEventCount();
}
});
}
private void waitOnEventCountChange(int oldEventCount, int minExpectedEvents, EventConsumer consumer)
throws InterruptedException {
long waitUntil = System.currentTimeMillis() + 60000L;
long lastNotification = System.currentTimeMillis();
while (consumer.getEventCount() < oldEventCount + minExpectedEvents) {
if (System.currentTimeMillis() > waitUntil) {
throw new RuntimeException("Did not reach expected number of events processed by " + consumer.getName()
+ ", current " + consumer.getEventCount()
+ ", expected: " + (oldEventCount + minExpectedEvents));
}
if (System.currentTimeMillis() > lastNotification + 1000) {
System.out.println("Waiting on change in number of events processed by " + consumer.getName());
lastNotification = System.currentTimeMillis();
}
Thread.sleep(20);
}
}
private static interface EventConsumer {
String getName();
int getEventCount();
}
private static byte[] b(String string) {
return Bytes.toBytes(string);
}
private String peerId(String indexerName) {
return "Indexer_" + indexerName;
}
}
|
/*
* 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.model.v20140515;
import java.util.List;
import com.aliyuncs.AcsResponse;
import com.aliyuncs.slb.transform.v20140515.DescribeRulesResponseUnmarshaller;
import com.aliyuncs.transform.UnmarshallerContext;
/**
* @author auto create
* @version
*/
public class DescribeRulesResponse extends AcsResponse {
private String requestId;
private List<Rule> rules;
public String getRequestId() {
return this.requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public List<Rule> getRules() {
return this.rules;
}
public void setRules(List<Rule> rules) {
this.rules = rules;
}
public static class Rule {
private String ruleId;
private String ruleName;
private String domain;
private String url;
private String vServerGroupId;
public String getRuleId() {
return this.ruleId;
}
public void setRuleId(String ruleId) {
this.ruleId = ruleId;
}
public String getRuleName() {
return this.ruleName;
}
public void setRuleName(String ruleName) {
this.ruleName = ruleName;
}
public String getDomain() {
return this.domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
public String getVServerGroupId() {
return this.vServerGroupId;
}
public void setVServerGroupId(String vServerGroupId) {
this.vServerGroupId = vServerGroupId;
}
}
@Override
public DescribeRulesResponse getInstance(UnmarshallerContext context) {
return DescribeRulesResponseUnmarshaller.unmarshall(this, context);
}
}
|
/**
* Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.analytics.timeseries;
import java.util.Set;
import com.google.common.collect.Iterables;
import com.opengamma.analytics.financial.timeseries.util.TimeSeriesRelativeWeightedDifferenceOperator;
import com.opengamma.analytics.financial.timeseries.util.TimeSeriesWeightedVolatilityOperator;
import com.opengamma.engine.value.ValueProperties;
import com.opengamma.engine.value.ValuePropertyNames;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.timeseries.date.localdate.LocalDateDoubleTimeSeries;
/**
*
*/
public class VolatilityWeightedFXReturnSeriesFunction extends FXReturnSeriesFunction {
private static final TimeSeriesRelativeWeightedDifferenceOperator RELATIVE_WEIGHTED_DIFFERENCE = new TimeSeriesRelativeWeightedDifferenceOperator();
@Override
protected ValueProperties getResultProperties() {
final ValueProperties properties = super.getResultProperties().copy()
.withoutAny(ValuePropertyNames.RETURN_CALCULATOR)
.with(ValuePropertyNames.RETURN_CALCULATOR, RELATIVE_RETURNS)
.get();
return VolatilityWeightingFunctionUtils.addVolatilityWeightingProperties(properties);
}
@Override
protected String getSpotSeriesStart(final ValueProperties constraints) {
final Set<String> lambdas = constraints.getValues(VolatilityWeightingFunctionUtils.VOLATILITY_WEIGHTING_LAMBDA_PROPERTY);
if (lambdas == null || lambdas.size() != 1) {
return null;
}
final Set<String> startDates = constraints.getValues(HistoricalTimeSeriesFunctionUtils.START_DATE_PROPERTY);
if (startDates == null || startDates.size() != 1) {
return null;
}
final String startDate = Iterables.getOnlyElement(startDates);
final Set<String> volWeightingStartDates = constraints.getValues(VolatilityWeightingFunctionUtils.VOLATILITY_WEIGHTING_START_DATE_PROPERTY);
if (volWeightingStartDates == null || volWeightingStartDates.size() != 1) {
// NOTE jonathan 2013-04-29 -- should start a day earlier so the result after weighting starts at the startDate,
// but need to know previous date with data
return startDate;
}
return Iterables.getOnlyElement(volWeightingStartDates);
}
@Override
protected LocalDateDoubleTimeSeries getReturnSeries(final LocalDateDoubleTimeSeries spotSeries, final ValueRequirement desiredValue) {
final double lambda = Double.parseDouble(desiredValue.getConstraint(VolatilityWeightingFunctionUtils.VOLATILITY_WEIGHTING_LAMBDA_PROPERTY));
final TimeSeriesWeightedVolatilityOperator weightedVolOp = TimeSeriesWeightedVolatilityOperator.relative(lambda);
final LocalDateDoubleTimeSeries weightedVolSeries = (LocalDateDoubleTimeSeries) weightedVolOp.evaluate(spotSeries);
return (LocalDateDoubleTimeSeries) RELATIVE_WEIGHTED_DIFFERENCE.evaluate(spotSeries, weightedVolSeries);
}
}
|
/*******************************************************************************
* Copyright (c) 2010 xored software, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* xored software, Inc. - initial API and Implementation (Alex Panchenko)
*******************************************************************************/
package org.eclipse.dltk.core;
/**
* @since 3.0
*/
public interface INamespace {
/**
* Returns the parts of this namespace
*
* @return
*/
String[] getStrings();
/**
* Returns the qualified name of this namespace. This consists of the simple
* names, separated by <code>'$'</code>. This is a handle-only method.
*
* @return the qualified name of this namespace
*/
String getQualifiedName();
/**
* Returns the qualified name of this namespace. This consists of the simple
* names, separated by <code>separator</code>. This is a handle-only method.
*
* @param separator
* the specified enclosing type separator
* @return the qualified name of this package
*
*/
String getQualifiedName(String separator);
boolean isRoot();
}
|
package com.binance.api.examples;
import com.binance.api.HttpUtils;
import com.binance.api.client.BinanceApiClientFactory;
import com.binance.api.client.BinanceApiWebSocketClient;
import com.binance.api.client.domain.market.CandlestickInterval;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import org.asynchttpclient.AsyncHttpClient;
import java.io.IOException;
/**
* Market data stream endpoints examples.
*
* It illustrates how to create a stream to obtain updates on market data such as executed trades.
*/
public class MarketDataStreamExample {
public static void main(String[] args) throws InterruptedException, IOException {
final EventLoopGroup eventLoopGroup = new NioEventLoopGroup(2);
final AsyncHttpClient asyncHttpClient = HttpUtils.newAsyncHttpClient(eventLoopGroup, 65536);
BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(asyncHttpClient);
BinanceApiWebSocketClient client = factory.newWebSocketClient();
// Listen for aggregated trade events for ETH/BTC
client.onAggTradeEvent("ethbtc", response -> System.out.println(response));
// Listen for changes in the order book in ETH/BTC
client.onDepthEvent("ethbtc", response -> System.out.println(response));
// Obtain 1m candlesticks in real-time for ETH/BTC
client.onCandlestickEvent("ethbtc", CandlestickInterval.ONE_MINUTE, response -> System.out.println(response));
}
}
|
package l2f.gameserver.skills;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import l2f.commons.crypt.CryptUtil;
import l2f.gameserver.model.Skill;
import l2f.gameserver.skills.effects.EffectTemplate;
import l2f.gameserver.stats.StatTemplate;
import l2f.gameserver.stats.Stats;
import l2f.gameserver.stats.conditions.Condition;
import l2f.gameserver.stats.conditions.ConditionFirstEffectSuccess;
import l2f.gameserver.stats.conditions.ConditionGameTime;
import l2f.gameserver.stats.conditions.ConditionGameTime.CheckGameTime;
import l2f.gameserver.stats.conditions.ConditionHasSkill;
import l2f.gameserver.stats.conditions.ConditionLogicAnd;
import l2f.gameserver.stats.conditions.ConditionLogicNot;
import l2f.gameserver.stats.conditions.ConditionLogicOr;
import l2f.gameserver.stats.conditions.ConditionPlayerAgathion;
import l2f.gameserver.stats.conditions.ConditionPlayerClassId;
import l2f.gameserver.stats.conditions.ConditionPlayerCubic;
import l2f.gameserver.stats.conditions.ConditionPlayerHasBuff;
import l2f.gameserver.stats.conditions.ConditionPlayerHasBuffId;
import l2f.gameserver.stats.conditions.ConditionPlayerInstanceZone;
import l2f.gameserver.stats.conditions.ConditionPlayerMaxLevel;
import l2f.gameserver.stats.conditions.ConditionPlayerMaxPK;
import l2f.gameserver.stats.conditions.ConditionPlayerMinLevel;
import l2f.gameserver.stats.conditions.ConditionPlayerMinMaxDamage;
import l2f.gameserver.stats.conditions.ConditionPlayerOlympiad;
import l2f.gameserver.stats.conditions.ConditionPlayerPercentCp;
import l2f.gameserver.stats.conditions.ConditionPlayerPercentHp;
import l2f.gameserver.stats.conditions.ConditionPlayerPercentMp;
import l2f.gameserver.stats.conditions.ConditionPlayerRace;
import l2f.gameserver.stats.conditions.ConditionPlayerRiding;
import l2f.gameserver.stats.conditions.ConditionPlayerRiding.CheckPlayerRiding;
import l2f.gameserver.stats.conditions.ConditionPlayerState;
import l2f.gameserver.stats.conditions.ConditionPlayerState.CheckPlayerState;
import l2f.gameserver.stats.conditions.ConditionPlayerSummonSiegeGolem;
import l2f.gameserver.stats.conditions.ConditionSlotItemId;
import l2f.gameserver.stats.conditions.ConditionTargetActiveSkillId;
import l2f.gameserver.stats.conditions.ConditionTargetAggro;
import l2f.gameserver.stats.conditions.ConditionTargetCastleDoor;
import l2f.gameserver.stats.conditions.ConditionTargetClan;
import l2f.gameserver.stats.conditions.ConditionTargetDirection;
import l2f.gameserver.stats.conditions.ConditionTargetForbiddenClassId;
import l2f.gameserver.stats.conditions.ConditionTargetHasBuff;
import l2f.gameserver.stats.conditions.ConditionTargetHasBuffId;
import l2f.gameserver.stats.conditions.ConditionTargetHasForbiddenSkill;
import l2f.gameserver.stats.conditions.ConditionTargetMob;
import l2f.gameserver.stats.conditions.ConditionTargetMobId;
import l2f.gameserver.stats.conditions.ConditionTargetNpcClass;
import l2f.gameserver.stats.conditions.ConditionTargetPercentCp;
import l2f.gameserver.stats.conditions.ConditionTargetPercentHp;
import l2f.gameserver.stats.conditions.ConditionTargetPercentMp;
import l2f.gameserver.stats.conditions.ConditionTargetPlayable;
import l2f.gameserver.stats.conditions.ConditionTargetPlayer;
import l2f.gameserver.stats.conditions.ConditionTargetPlayerRace;
import l2f.gameserver.stats.conditions.ConditionTargetRace;
import l2f.gameserver.stats.conditions.ConditionTargetSummon;
import l2f.gameserver.stats.conditions.ConditionUsingArmor;
import l2f.gameserver.stats.conditions.ConditionUsingItemType;
import l2f.gameserver.stats.conditions.ConditionUsingSkill;
import l2f.gameserver.stats.conditions.ConditionZoneType;
import l2f.gameserver.stats.funcs.FuncTemplate;
import l2f.gameserver.stats.triggers.TriggerInfo;
import l2f.gameserver.stats.triggers.TriggerType;
import l2f.gameserver.templates.StatsSet;
import l2f.gameserver.templates.item.ArmorTemplate.ArmorType;
import l2f.gameserver.templates.item.WeaponTemplate.WeaponType;
import l2f.gameserver.utils.PositionUtils;
abstract class DocumentBase
{
private static final Logger _log = LoggerFactory.getLogger(DocumentBase.class);
private final File file;
protected Map<String, Object[]> tables;
DocumentBase(File file)
{
this.file = file;
tables = new HashMap<String, Object[]>();
}
Document parse()
{
Document doc;
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setIgnoringComments(true);
FileInputStream stream = new FileInputStream(file);
InputStream output;
if ((byte)stream.read() == 0x00)
{
byte[] bytes = new byte[0];
output = new ByteArrayInputStream(bytes);
output = CryptUtil.decrypt(stream, output);
}
else
output = new FileInputStream(file);
doc = factory.newDocumentBuilder().parse(output);
}
catch (FileNotFoundException e)
{
_log.error("Didn't find " + file, e);
return null;
}
catch (IOException | ParserConfigurationException | SAXException e)
{
_log.error("Error loading file " + file, e);
return null;
}
try
{
parseDocument(doc);
}
catch (RuntimeException e)
{
_log.error("Error in file " + file, e);
return null;
}
return doc;
}
protected abstract void parseDocument(Document doc);
protected abstract Object getTableValue(String name);
protected abstract Object getTableValue(String name, int idx);
protected void resetTable()
{
tables = new HashMap<String, Object[]>();
}
protected void setTable(String name, Object[] table)
{
tables.put(name, table);
}
protected void parseTemplate(Node n, StatTemplate template)
{
n = n.getFirstChild();
if (n == null)
return;
for (; n != null; n = n.getNextSibling())
{
String nodeName = n.getNodeName();
if ("add".equalsIgnoreCase(nodeName))
attachFunc(n, template, "Add");
else if ("sub".equalsIgnoreCase(nodeName))
attachFunc(n, template, "Sub");
else if ("mul".equalsIgnoreCase(nodeName))
attachFunc(n, template, "Mul");
else if ("div".equalsIgnoreCase(nodeName))
attachFunc(n, template, "Div");
else if ("set".equalsIgnoreCase(nodeName))
attachFunc(n, template, "Set");
else if ("enchant".equalsIgnoreCase(nodeName))
attachFunc(n, template, "Enchant");
else if ("effect".equalsIgnoreCase(nodeName))
{
if (template instanceof EffectTemplate)
throw new RuntimeException("Nested effects");
attachEffect(n, template);
}
else if (template instanceof EffectTemplate)
if ("def".equalsIgnoreCase(nodeName))
parseBeanSet(n, ((EffectTemplate) template).getParam(), ((Skill) ((EffectTemplate) template).getParam().getObject("object")).getLevel());
else
{
Condition cond = parseCondition(n);
if (cond != null)
((EffectTemplate) template).attachCond(cond);
}
}
}
protected void parseTrigger(Node n, StatTemplate template)
{
for (n = n.getFirstChild(); n != null; n = n.getNextSibling())
{
if ("trigger".equalsIgnoreCase(n.getNodeName()))
{
NamedNodeMap map = n.getAttributes();
int id = parseNumber(map.getNamedItem("id").getNodeValue()).intValue();
int level = parseNumber(map.getNamedItem("level").getNodeValue()).intValue();
TriggerType t = TriggerType.valueOf(map.getNamedItem("type").getNodeValue());
double chance = parseNumber(map.getNamedItem("chance").getNodeValue()).doubleValue();
TriggerInfo trigger = new TriggerInfo(id, level, t, chance);
for (Node n2 = n.getFirstChild(); n2 != null; n2 = n2.getNextSibling())
{
Condition condition = parseCondition(n.getFirstChild());
if (condition != null)
trigger.addCondition(condition);
}
template.addTrigger(trigger);
}
}
}
protected void attachFunc(Node n, StatTemplate template, String name)
{
Stats stat = Stats.valueOfXml(n.getAttributes().getNamedItem("stat").getNodeValue());
String order = n.getAttributes().getNamedItem("order").getNodeValue();
int ord = parseNumber(order).intValue();
Condition applyCond = parseCondition(n.getFirstChild());
double val = 0;
if (n.getAttributes().getNamedItem("val") != null)
val = parseNumber(n.getAttributes().getNamedItem("val").getNodeValue()).doubleValue();
template.attachFunc(new FuncTemplate(applyCond, name, stat, ord, val));
}
protected void attachEffect(Node n, Object template)
{
NamedNodeMap attrs = n.getAttributes();
StatsSet set = new StatsSet();
set.set("name", attrs.getNamedItem("name").getNodeValue());
set.set("object", template);
if (attrs.getNamedItem("count") != null)
set.set("count", parseNumber(attrs.getNamedItem("count").getNodeValue()).intValue());
if (attrs.getNamedItem("time") != null)
set.set("time", parseNumber(attrs.getNamedItem("time").getNodeValue()).intValue());
set.set("value", attrs.getNamedItem("val") != null ? parseNumber(attrs.getNamedItem("val").getNodeValue()).doubleValue() : 0.);
set.set("abnormal", AbnormalEffect.NULL);
set.set("abnormal2", AbnormalEffect.NULL);
set.set("abnormal3", AbnormalEffect.NULL);
if (attrs.getNamedItem("abnormal") != null)
{
AbnormalEffect ae = AbnormalEffect.getByName(attrs.getNamedItem("abnormal").getNodeValue());
if (ae.isSpecial())
set.set("abnormal2", ae);
if (ae.isEvent())
set.set("abnormal3", ae);
else
set.set("abnormal", ae);
}
if (attrs.getNamedItem("stackType") != null)
set.set("stackType", attrs.getNamedItem("stackType").getNodeValue());
if (attrs.getNamedItem("stackType2") != null)
set.set("stackType2", attrs.getNamedItem("stackType2").getNodeValue());
if (attrs.getNamedItem("stackOrder") != null)
set.set("stackOrder", parseNumber(attrs.getNamedItem("stackOrder").getNodeValue()).intValue());
if (attrs.getNamedItem("applyOnCaster") != null)
set.set("applyOnCaster", Boolean.valueOf(attrs.getNamedItem("applyOnCaster").getNodeValue()));
if (attrs.getNamedItem("applyOnSummon") != null)
set.set("applyOnSummon", Boolean.valueOf(attrs.getNamedItem("applyOnSummon").getNodeValue()));
if (attrs.getNamedItem("displayId") != null)
set.set("displayId", parseNumber(attrs.getNamedItem("displayId").getNodeValue()).intValue());
if (attrs.getNamedItem("displayLevel") != null)
set.set("displayLevel", parseNumber(attrs.getNamedItem("displayLevel").getNodeValue()).intValue());
if (attrs.getNamedItem("chance") != null)
set.set("chance", parseNumber(attrs.getNamedItem("chance").getNodeValue()).intValue());
if (attrs.getNamedItem("cancelOnAction") != null)
set.set("cancelOnAction", Boolean.valueOf(attrs.getNamedItem("cancelOnAction").getNodeValue()));
if (attrs.getNamedItem("isOffensive") != null)
set.set("isOffensive", Boolean.valueOf(attrs.getNamedItem("isOffensive").getNodeValue()));
if (attrs.getNamedItem("isReflectable") != null)
set.set("isReflectable", Boolean.valueOf(attrs.getNamedItem("isReflectable").getNodeValue()));
EffectTemplate lt = new EffectTemplate(set);
parseTemplate(n, lt);
for (Node n1 = n.getFirstChild(); n1 != null; n1 = n1.getNextSibling())
{
if ("triggers".equalsIgnoreCase(n1.getNodeName()))
parseTrigger(n1, lt);
}
if (template instanceof Skill)
((Skill) template).attach(lt);
}
protected Condition parseCondition(Node n)
{
while (n != null && n.getNodeType() != Node.ELEMENT_NODE)
n = n.getNextSibling();
if (n == null)
return null;
if ("and".equalsIgnoreCase(n.getNodeName()))
return parseLogicAnd(n);
if ("or".equalsIgnoreCase(n.getNodeName()))
return parseLogicOr(n);
if ("not".equalsIgnoreCase(n.getNodeName()))
return parseLogicNot(n);
if ("player".equalsIgnoreCase(n.getNodeName()))
return parsePlayerCondition(n);
if ("target".equalsIgnoreCase(n.getNodeName()))
return parseTargetCondition(n);
if ("has".equalsIgnoreCase(n.getNodeName()))
return parseHasCondition(n);
if ("using".equalsIgnoreCase(n.getNodeName()))
return parseUsingCondition(n);
if ("game".equalsIgnoreCase(n.getNodeName()))
return parseGameCondition(n);
if ("zone".equalsIgnoreCase(n.getNodeName()))
return parseZoneCondition(n);
return null;
}
protected Condition parseLogicAnd(Node n)
{
ConditionLogicAnd cond = new ConditionLogicAnd();
for (n = n.getFirstChild(); n != null; n = n.getNextSibling())
if (n.getNodeType() == Node.ELEMENT_NODE)
cond.add(parseCondition(n));
if (cond._conditions == null || cond._conditions.length == 0)
_log.error("Empty <and> condition in " + file);
return cond;
}
protected Condition parseLogicOr(Node n)
{
ConditionLogicOr cond = new ConditionLogicOr();
for (n = n.getFirstChild(); n != null; n = n.getNextSibling())
if (n.getNodeType() == Node.ELEMENT_NODE)
cond.add(parseCondition(n));
if (cond._conditions == null || cond._conditions.length == 0)
_log.error("Empty <or> condition in " + file);
return cond;
}
protected Condition parseLogicNot(Node n)
{
for (n = n.getFirstChild(); n != null; n = n.getNextSibling())
if (n.getNodeType() == Node.ELEMENT_NODE)
return new ConditionLogicNot(parseCondition(n));
_log.error("Empty <not> condition in " + file);
return null;
}
protected Condition parsePlayerCondition(Node n)
{
Condition cond = null;
NamedNodeMap attrs = n.getAttributes();
for (int i = 0; i < attrs.getLength(); i++)
{
Node a = attrs.item(i);
String nodeName = a.getNodeName();
if ("race".equalsIgnoreCase(nodeName))
cond = joinAnd(cond, new ConditionPlayerRace(a.getNodeValue()));
else if ("minLevel".equalsIgnoreCase(nodeName))
{
int lvl = parseNumber(a.getNodeValue()).intValue();
cond = joinAnd(cond, new ConditionPlayerMinLevel(lvl));
}
else if ("summon_siege_golem".equalsIgnoreCase(nodeName))
{
cond = joinAnd(cond, new ConditionPlayerSummonSiegeGolem());
}
else if ("maxLevel".equalsIgnoreCase(nodeName))
{
int lvl = parseNumber(a.getNodeValue()).intValue();
cond = joinAnd(cond, new ConditionPlayerMaxLevel(lvl));
}
else if ("maxPK".equalsIgnoreCase(nodeName))
{
int pk = parseNumber(a.getNodeValue()).intValue();
cond = joinAnd(cond, new ConditionPlayerMaxPK(pk));
}
else if ("resting".equalsIgnoreCase(nodeName))
{
boolean val = Boolean.valueOf(a.getNodeValue());
cond = joinAnd(cond, new ConditionPlayerState(CheckPlayerState.RESTING, val));
}
else if ("moving".equalsIgnoreCase(nodeName))
{
boolean val = Boolean.valueOf(a.getNodeValue());
cond = joinAnd(cond, new ConditionPlayerState(CheckPlayerState.MOVING, val));
}
else if ("running".equalsIgnoreCase(nodeName))
{
boolean val = Boolean.valueOf(a.getNodeValue());
cond = joinAnd(cond, new ConditionPlayerState(CheckPlayerState.RUNNING, val));
}
else if ("standing".equalsIgnoreCase(nodeName))
{
boolean val = Boolean.valueOf(a.getNodeValue());
cond = joinAnd(cond, new ConditionPlayerState(CheckPlayerState.STANDING, val));
}
else if ("flying".equalsIgnoreCase(a.getNodeName()))
{
boolean val = Boolean.valueOf(a.getNodeValue());
cond = joinAnd(cond, new ConditionPlayerState(CheckPlayerState.FLYING, val));
}
else if ("flyingTransform".equalsIgnoreCase(a.getNodeName()))
{
boolean val = Boolean.valueOf(a.getNodeValue());
cond = joinAnd(cond, new ConditionPlayerState(CheckPlayerState.FLYING_TRANSFORM, val));
}
else if ("olympiad".equalsIgnoreCase(a.getNodeName()))
{
boolean val = Boolean.valueOf(a.getNodeValue());
cond = joinAnd(cond, new ConditionPlayerOlympiad(val));
}
else if ("active_skill_id".equalsIgnoreCase(a.getNodeName()))
{
int skill_id = parseNumber(a.getNodeValue()).intValue();
cond = joinAnd(cond, new ConditionTargetActiveSkillId(skill_id));
}
else if ("percentHP".equalsIgnoreCase(nodeName))
{
int percentHP = parseNumber(a.getNodeValue()).intValue();
cond = joinAnd(cond, new ConditionPlayerPercentHp(percentHP));
}
else if ("percentMP".equalsIgnoreCase(nodeName))
{
int percentMP = parseNumber(a.getNodeValue()).intValue();
cond = joinAnd(cond, new ConditionPlayerPercentMp(percentMP));
}
else if ("percentCP".equalsIgnoreCase(nodeName))
{
int percentCP = parseNumber(a.getNodeValue()).intValue();
cond = joinAnd(cond, new ConditionPlayerPercentCp(percentCP));
}
else if ("agathion".equalsIgnoreCase(nodeName))
{
int agathionId = parseNumber(a.getNodeValue()).intValue();
cond = joinAnd(cond, new ConditionPlayerAgathion(agathionId));
}
else if ("cubic".equalsIgnoreCase(nodeName))
{
int cubicId = parseNumber(a.getNodeValue()).intValue();
cond = joinAnd(cond, new ConditionPlayerCubic(cubicId));
}
else if ("instance_zone".equalsIgnoreCase(nodeName))
{
int id = parseNumber(a.getNodeValue()).intValue();
cond = joinAnd(cond, new ConditionPlayerInstanceZone(id));
}
else if ("riding".equalsIgnoreCase(nodeName))
{
String riding = a.getNodeValue();
if ("strider".equalsIgnoreCase(riding))
cond = joinAnd(cond, new ConditionPlayerRiding(CheckPlayerRiding.STRIDER));
else if ("wyvern".equalsIgnoreCase(riding))
cond = joinAnd(cond, new ConditionPlayerRiding(CheckPlayerRiding.WYVERN));
else if ("none".equalsIgnoreCase(riding))
cond = joinAnd(cond, new ConditionPlayerRiding(CheckPlayerRiding.NONE));
}
else if ("classId".equalsIgnoreCase(nodeName))
cond = joinAnd(cond, new ConditionPlayerClassId(a.getNodeValue().split(",")));
else if ("hasBuffId".equalsIgnoreCase(nodeName))
{
StringTokenizer st = new StringTokenizer(a.getNodeValue(), ";");
int id = Integer.parseInt(st.nextToken().trim());
int level = -1;
if (st.hasMoreTokens())
level = Integer.parseInt(st.nextToken().trim());
cond = joinAnd(cond, new ConditionPlayerHasBuffId(id, level));
}
else if ("hasBuff".equalsIgnoreCase(nodeName))
{
StringTokenizer st = new StringTokenizer(a.getNodeValue(), ";");
EffectType et = Enum.valueOf(EffectType.class, st.nextToken().trim());
int level = -1;
if (st.hasMoreTokens())
level = Integer.parseInt(st.nextToken().trim());
cond = joinAnd(cond, new ConditionPlayerHasBuff(et, level));
}
else if ("damage".equalsIgnoreCase(nodeName))
{
String[] st = a.getNodeValue().split(";");
cond = joinAnd(cond, new ConditionPlayerMinMaxDamage(Double.parseDouble(st[0]), Double.parseDouble(st[1])));
}
}
if (cond == null)
_log.error("Unrecognized <player> condition in " + file);
return cond;
}
protected Condition parseTargetCondition(Node n)
{
Condition cond = null;
NamedNodeMap attrs = n.getAttributes();
for (int i = 0; i < attrs.getLength(); i++)
{
Node a = attrs.item(i);
String nodeName = a.getNodeName();
String nodeValue = a.getNodeValue();
if ("aggro".equalsIgnoreCase(nodeName))
cond = joinAnd(cond, new ConditionTargetAggro(Boolean.valueOf(nodeValue)));
else if ("pvp".equalsIgnoreCase(nodeName))
cond = joinAnd(cond, new ConditionTargetPlayable(Boolean.valueOf(nodeValue)));
else if ("player".equalsIgnoreCase(nodeName))
cond = joinAnd(cond, new ConditionTargetPlayer(Boolean.valueOf(nodeValue)));
else if ("summon".equalsIgnoreCase(nodeName))
cond = joinAnd(cond, new ConditionTargetSummon(Boolean.valueOf(nodeValue)));
else if ("mob".equalsIgnoreCase(nodeName))
cond = joinAnd(cond, new ConditionTargetMob(Boolean.valueOf(nodeValue)));
else if ("mobId".equalsIgnoreCase(nodeName))
cond = joinAnd(cond, new ConditionTargetMobId(Integer.parseInt(nodeValue)));
else if ("race".equalsIgnoreCase(nodeName))
cond = joinAnd(cond, new ConditionTargetRace(nodeValue));
else if ("npc_class".equalsIgnoreCase(nodeName))
cond = joinAnd(cond, new ConditionTargetNpcClass(nodeValue));
else if ("playerRace".equalsIgnoreCase(nodeName))
cond = joinAnd(cond, new ConditionTargetPlayerRace(nodeValue));
else if ("forbiddenClassIds".equalsIgnoreCase(nodeName))
cond = joinAnd(cond, new ConditionTargetForbiddenClassId(nodeValue.split(";")));
else if ("playerSameClan".equalsIgnoreCase(nodeName))
cond = joinAnd(cond, new ConditionTargetClan(nodeValue));
else if ("castledoor".equalsIgnoreCase(nodeName))
cond = joinAnd(cond, new ConditionTargetCastleDoor(Boolean.valueOf(nodeValue)));
else if ("direction".equalsIgnoreCase(nodeName))
cond = joinAnd(cond, new ConditionTargetDirection(PositionUtils.TargetDirection.valueOf(nodeValue.toUpperCase())));
else if ("percentHP".equalsIgnoreCase(nodeName))
cond = joinAnd(cond, new ConditionTargetPercentHp(parseNumber(a.getNodeValue()).intValue()));
else if ("percentMP".equalsIgnoreCase(nodeName))
cond = joinAnd(cond, new ConditionTargetPercentMp(parseNumber(a.getNodeValue()).intValue()));
else if ("percentCP".equalsIgnoreCase(nodeName))
cond = joinAnd(cond, new ConditionTargetPercentCp(parseNumber(a.getNodeValue()).intValue()));
else if ("hasBuffId".equalsIgnoreCase(nodeName))
{
StringTokenizer st = new StringTokenizer(nodeValue, ";");
int id = Integer.parseInt(st.nextToken().trim());
int level = -1;
if (st.hasMoreTokens())
level = Integer.parseInt(st.nextToken().trim());
cond = joinAnd(cond, new ConditionTargetHasBuffId(id, level));
}
else if ("hasBuff".equalsIgnoreCase(nodeName))
{
StringTokenizer st = new StringTokenizer(nodeValue, ";");
EffectType et = Enum.valueOf(EffectType.class, st.nextToken().trim());
int level = -1;
if (st.hasMoreTokens())
level = Integer.parseInt(st.nextToken().trim());
cond = joinAnd(cond, new ConditionTargetHasBuff(et, level));
}
else if ("hasForbiddenSkill".equalsIgnoreCase(nodeName))
cond = joinAnd(cond, new ConditionTargetHasForbiddenSkill(parseNumber(a.getNodeValue()).intValue()));
}
if (cond == null)
_log.error("Unrecognized <target> condition in " + file);
return cond;
}
protected Condition parseUsingCondition(Node n)
{
Condition cond = null;
NamedNodeMap attrs = n.getAttributes();
for (int i = 0; i < attrs.getLength(); i++)
{
Node a = attrs.item(i);
String nodeName = a.getNodeName();
String nodeValue = a.getNodeValue();
if ("kind".equalsIgnoreCase(nodeName) || "weapon".equalsIgnoreCase(nodeName))
{
long mask = 0;
StringTokenizer st = new StringTokenizer(nodeValue, ",");
tokens: while(st.hasMoreTokens())
{
String item = st.nextToken().trim();
for (WeaponType wt : WeaponType.VALUES)
if (wt.toString().equalsIgnoreCase(item))
{
mask |= wt.mask();
continue tokens;
}
for (ArmorType at : ArmorType.VALUES)
if (at.toString().equalsIgnoreCase(item))
{
mask |= at.mask();
continue tokens;
}
_log.error("Invalid item kind: \"" + item + "\" in " + file);
}
if (mask != 0)
cond = joinAnd(cond, new ConditionUsingItemType(mask));
}
else if ("armor".equalsIgnoreCase(nodeName))
{
ArmorType armor = ArmorType.valueOf(nodeValue.toUpperCase());
cond = joinAnd(cond, new ConditionUsingArmor(armor));
}
else if ("skill".equalsIgnoreCase(nodeName))
cond = joinAnd(cond, new ConditionUsingSkill(Integer.parseInt(nodeValue)));
else if ("slotitem".equalsIgnoreCase(nodeName))
{
StringTokenizer st = new StringTokenizer(nodeValue, ";");
int id = Integer.parseInt(st.nextToken().trim());
int slot = Integer.parseInt(st.nextToken().trim());
int enchant = 0;
if (st.hasMoreTokens())
enchant = Integer.parseInt(st.nextToken().trim());
cond = joinAnd(cond, new ConditionSlotItemId(slot, id, enchant));
}
}
if (cond == null)
_log.error("Unrecognized <using> condition in " + file);
return cond;
}
protected Condition parseHasCondition(Node n)
{
Condition cond = null;
NamedNodeMap attrs = n.getAttributes();
for (int i = 0; i < attrs.getLength(); i++)
{
Node a = attrs.item(i);
String nodeName = a.getNodeName();
String nodeValue = a.getNodeValue();
if ("skill".equalsIgnoreCase(nodeName))
{
StringTokenizer st = new StringTokenizer(nodeValue, ";");
Integer id = parseNumber(st.nextToken().trim()).intValue();
int level = parseNumber(st.nextToken().trim()).shortValue();
cond = joinAnd(cond, new ConditionHasSkill(id, level));
}
else if ("success".equalsIgnoreCase(nodeName))
cond = joinAnd(cond, new ConditionFirstEffectSuccess(Boolean.valueOf(nodeValue)));
}
if (cond == null)
_log.error("Unrecognized <has> condition in " + file);
return cond;
}
protected Condition parseGameCondition(Node n)
{
Condition cond = null;
NamedNodeMap attrs = n.getAttributes();
for (int i = 0; i < attrs.getLength(); i++)
{
Node a = attrs.item(i);
if ("night".equalsIgnoreCase(a.getNodeName()))
{
boolean val = Boolean.valueOf(a.getNodeValue());
cond = joinAnd(cond, new ConditionGameTime(CheckGameTime.NIGHT, val));
}
}
if (cond == null)
_log.error("Unrecognized <game> condition in " + file);
return cond;
}
protected Condition parseZoneCondition(Node n)
{
Condition cond = null;
NamedNodeMap attrs = n.getAttributes();
for (int i = 0; i < attrs.getLength(); i++)
{
Node a = attrs.item(i);
if ("type".equalsIgnoreCase(a.getNodeName()))
cond = joinAnd(cond, new ConditionZoneType(a.getNodeValue()));
}
if (cond == null)
_log.error("Unrecognized <zone> condition in " + file);
return cond;
}
protected Object[] parseTable(Node n)
{
NamedNodeMap attrs = n.getAttributes();
String name = attrs.getNamedItem("name").getNodeValue();
if (name.charAt(0) != '#')
throw new IllegalArgumentException("Table name must start with #");
StringTokenizer data = new StringTokenizer(n.getFirstChild().getNodeValue());
List<String> array = new ArrayList<String>();
while (data.hasMoreTokens())
array.add(data.nextToken());
Object[] res = array.toArray(new Object[array.size()]);
setTable(name, res);
return res;
}
protected void parseBeanSet(Node n, StatsSet set, int level)
{
try
{
String name = n.getAttributes().getNamedItem("name").getNodeValue().trim();
String value = n.getAttributes().getNamedItem("val").getNodeValue().trim();
char ch = value.length() == 0 ? ' ' : value.charAt(0);
if (value.contains("#") && ch != '#')
for (String str : value.split("[;: ]+"))
if (str.charAt(0) == '#')
value = value.replace(str, String.valueOf(getTableValue(str, level)));
if (ch == '#')
{
Object tableVal = getTableValue(value, level);
Number parsedVal = parseNumber(tableVal.toString());
set.set(name, parsedVal == null ? tableVal : String.valueOf(parsedVal));
}
else if ((Character.isDigit(ch) || ch == '-') && !value.contains(" ") && !value.contains(";"))
set.set(name, String.valueOf(parseNumber(value)));
else
set.set(name, value);
}
catch (DOMException e)
{
_log.warn(n.getAttributes().getNamedItem("name") + " " + set.get("skill_id"), e);
}
}
protected Number parseNumber(String value)
{
if (value.charAt(0) == '#')
value = getTableValue(value).toString();
try
{
if (value.equalsIgnoreCase("max"))
return Double.POSITIVE_INFINITY;
if (value.equalsIgnoreCase("min"))
return Double.NEGATIVE_INFINITY;
if (value.indexOf('.') == -1)
{
int radix = 10;
if (value.length() > 2 && value.substring(0, 2).equalsIgnoreCase("0x"))
{
value = value.substring(2);
radix = 16;
}
return Integer.valueOf(value, radix);
}
return Double.valueOf(value);
}
catch (NumberFormatException e)
{
return null;
}
}
protected Condition joinAnd(Condition cond, Condition c)
{
if (cond == null)
return c;
if (cond instanceof ConditionLogicAnd)
{
((ConditionLogicAnd) cond).add(c);
return cond;
}
ConditionLogicAnd and = new ConditionLogicAnd();
and.add(cond);
and.add(c);
return and;
}
}
|
/*
* Copyright 2016-2018 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.jboss.galleon;
/**
*
* @author Alexey Loubyansky
*/
public class ArtifactException extends ProvisioningException {
private static final long serialVersionUID = 1L;
public ArtifactException(String message) {
super(message);
}
public ArtifactException(String message, Throwable cause) {
super(message, cause);
}
}
|
package factory_method;
public class Audi implements Car
{
@Override
public void carCreator()
{
System.out.println("Audi markasında araç oluşturuldu");
}
}
|
package io.netx.net;
import io.netx.concurrent.ChannelFuture;
import java.io.IOException;
import java.net.SocketAddress;
public interface ChannelOutboundHandler extends ChannelHandler {
void bind(ChannelHandlerContext ctx, SocketAddress localAddress) throws Exception;
void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress) throws Exception;
void close(ChannelHandlerContext ctx) throws Exception;
void read(ChannelHandlerContext ctx) throws Exception;
void write(ChannelHandlerContext ctx, Object msg) throws IOException;
ChannelFuture<Void> closeAsyc(ChannelHandlerContext ctx, ChannelFuture<Void> future) throws Exception;
}
|
package cn.gaohank.idea.java.base_11_utils;
import org.junit.Test;
import java.util.Date;
import static org.junit.Assert.assertEquals;
public class Utils01TimeTest {
private final static Utils01Time utils01Time = new Utils01Time();
@Test
public void getCurrentTimeMillis() {
System.out.println(utils01Time.getCurrentTimeMillis());
}
@Test
public void getUnixTimestamp() throws Exception {
// 2011/11/11 11:11:11 转换成unix时间戳是:1320981071000 单位是ms
assertEquals(1320981071000L, utils01Time.getUnixTimestamp(
utils01Time.getParseDate("2011-11-11 11:11:11", "yyyy-MM-dd HH:mm:ss")
));
}
@Test
public void getFormatDate() {
// 2011/11/11 11:11:11 转换成unix时间戳是:1320981071000 单位是ms
assertEquals("20111111", utils01Time.getFormatDate(new Date(1320981071000L), "yyyyMMdd"));
}
@Test
public void getParseDate() throws Exception {
String dateStr = "2018-10-10 10:10:10";
Date parseDate = utils01Time.getParseDate(dateStr, "yyyy-MM-dd HH:mm:ss");
assertEquals("20181010", utils01Time.getFormatDate(parseDate, "yyyyMMdd"));
}
}
|
package com.iwc.shop.modules.sys.utils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.iwc.shop.common.config.Global;
import com.iwc.shop.common.utils.*;
import com.iwc.shop.modules.sys.dao.LogDao;
import com.iwc.shop.modules.sys.dao.MenuDao;
import com.iwc.shop.modules.sys.entity.Log;
import com.iwc.shop.modules.sys.entity.Menu;
import com.iwc.shop.modules.sys.entity.Sms;
import com.iwc.shop.modules.sys.entity.User;
import com.iwc.shop.modules.sys.service.SmsService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 短信工具类
* @author Tony Wong
* @version 2014-11-7
*/
public class SmsUtils {
/**
* 日志对象
*/
private static Logger logger = LoggerFactory.getLogger("SmsUtils");
private static SmsService smsService = SpringContextHolder.getBean(SmsService.class);
/**
* 发送用户注册的手机验证码, 过期时间为30分钟
* @return
*/
public static boolean sendRegisterCode(String mobile) {
if (ValidateUtils.isMobile(mobile)) {
String code = RamdomUtils.genRegisterCode();
String msg = "验证码为 " + code + ",恭喜,您正在注册月光茶人,请填写验证码并完成注册。(月光茶人客服绝不会索取此验证码,请勿告知他人)";
try {
SmsClient smsClient = new SmsClient();
String result = smsClient.sendSms(mobile, msg, "", "");
logger.debug("发送手机({})验证码返回结果: {}", mobile, result);
Date date = new Date();
date.setTime(date.getTime() + 1800000);
Sms sms = new Sms();
sms.setMobile(mobile);
sms.setType(Sms.TYPE_REGISTER);
sms.setMsg(msg);
sms.setExpiredDate(date);
sms.setSyncReturnResult(result);
sms.setCode(code);
smsService.save(sms);
return true;
} catch (Exception e) {
logger.debug("发送手机({})验证码失败, Exception: ", mobile, e.getMessage());
return false;
}
} else {
return false;
}
}
/**
* 发送重置密码的手机验证码, 过期时间为30分钟
* @return
*/
public static boolean sendForgetPasswordCode(String mobile) {
if (ValidateUtils.isMobile(mobile)) {
String code = RamdomUtils.genRegisterCode();
String msg = "验证码为 " + code + ",您正在重置密码,请填写验证码。(月光茶人客服绝不会索取此验证码,请勿告知他人)";
try {
SmsClient smsClient = new SmsClient();
String result = smsClient.sendSms(mobile, msg, "", "");
logger.debug("发送手机({})验证码返回结果: {}", mobile, result);
Date date = new Date();
date.setTime(date.getTime() + 1800000);
Sms sms = new Sms();
sms.setMobile(mobile);
sms.setType(Sms.TYPE_FORGET_PASSWORD);
sms.setMsg(msg);
sms.setExpiredDate(date);
sms.setSyncReturnResult(result);
sms.setCode(code);
smsService.save(sms);
return true;
} catch (Exception e) {
logger.debug("发送手机({})验证码失败, Exception: ", mobile, e.getMessage());
return false;
}
} else {
return false;
}
}
}
|
/*******************************************************************************
* Copyright 2019 ClilyStudio.
* 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.github.clilystudio.leetcode.question.medium;
/// -----------------------------------------------------------------------------
/// [152] 乘积最大子序列
///
/// https://leetcode-cn.com/problems/maximum-product-subarray/description/
///
/// 给定一个整数数组 nums ,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。
///
/// 示例 1:
///
/// 输入: [2,3,-2,4]
/// 输出: 6
/// 解释: 子数组 [2,3] 有最大乘积 6。
///
/// 示例 2:
///
/// 输入: [-2,0,-1]
/// 输出: 0
/// 解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。
/// -----------------------------------------------------------------------------
public class Q0152 {
public int maxProduct(int[] nums) {
// TODO
return 0;
}
}
|
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 4.0.2
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package org.pjsip.pjsua2;
public class OnTransportStateParam {
private transient long swigCPtr;
protected transient boolean swigCMemOwn;
protected OnTransportStateParam(long cPtr, boolean cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
swigCPtr = cPtr;
}
protected static long getCPtr(OnTransportStateParam obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@SuppressWarnings("deprecation")
protected void finalize() {
delete();
}
public synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
pjsua2JNI.delete_OnTransportStateParam(swigCPtr);
}
swigCPtr = 0;
}
}
public void setHnd(SWIGTYPE_p_void value) {
pjsua2JNI.OnTransportStateParam_hnd_set(swigCPtr, this, SWIGTYPE_p_void.getCPtr(value));
}
public SWIGTYPE_p_void getHnd() {
long cPtr = pjsua2JNI.OnTransportStateParam_hnd_get(swigCPtr, this);
return (cPtr == 0) ? null : new SWIGTYPE_p_void(cPtr, false);
}
public void setType(String value) {
pjsua2JNI.OnTransportStateParam_type_set(swigCPtr, this, value);
}
public String getType() {
return pjsua2JNI.OnTransportStateParam_type_get(swigCPtr, this);
}
public void setState(int value) {
pjsua2JNI.OnTransportStateParam_state_set(swigCPtr, this, value);
}
public int getState() {
return pjsua2JNI.OnTransportStateParam_state_get(swigCPtr, this);
}
public void setLastError(int value) {
pjsua2JNI.OnTransportStateParam_lastError_set(swigCPtr, this, value);
}
public int getLastError() {
return pjsua2JNI.OnTransportStateParam_lastError_get(swigCPtr, this);
}
public void setTlsInfo(TlsInfo value) {
pjsua2JNI.OnTransportStateParam_tlsInfo_set(swigCPtr, this, TlsInfo.getCPtr(value), value);
}
public TlsInfo getTlsInfo() {
long cPtr = pjsua2JNI.OnTransportStateParam_tlsInfo_get(swigCPtr, this);
return (cPtr == 0) ? null : new TlsInfo(cPtr, false);
}
public OnTransportStateParam() {
this(pjsua2JNI.new_OnTransportStateParam(), true);
}
}
|
package ru.korovko.clinic.validation;
import ru.korovko.clinic.validation.impl.PasswordValidationImpl;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Constraint(validatedBy = PasswordValidationImpl.class)
public @interface PasswordValidation {
String message() default "Password must contain at least 8 symbols, included digits, upper and lower case letters";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
|
/**********************************************************************************
*
* $Id$
*
***********************************************************************************
*
* Copyright (c) 2005, 2006, 2007, 2008 The Sakai Foundation, The MIT Corporation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ECL-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.sakaiproject.tool.gradebook.jsf;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import lombok.extern.slf4j.Slf4j;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.service.gradebook.shared.GradebookService;
import org.sakaiproject.tool.gradebook.AbstractGradeRecord;
import org.sakaiproject.tool.gradebook.GradebookAssignment;
import org.sakaiproject.tool.gradebook.AssignmentGradeRecord;
import org.sakaiproject.tool.gradebook.CourseGradeRecord;
import org.sakaiproject.tool.gradebook.GradableObject;
import org.sakaiproject.tool.gradebook.Gradebook;
/**
* This formatting-only converver consolidates the rather complex formatting
* logic for assignment and assignment grade points. If the points are null,
* they should be displayed in a special way. If the points belong to an
* assignment which doesn't count toward the final grade, they should be
* displayed in a special way with a tooltip "title" attribute.
*/
@Slf4j
public class AssignmentPointsConverter extends PointsConverter {
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (log.isDebugEnabled()) log.debug("getAsString(" + context + ", " + component + ", " + value + ")");
String formattedScore;
boolean notCounted = false;
Object workingValue = value;
boolean percentage = false;
if (value != null) {
if (value instanceof GradebookAssignment) {
GradebookAssignment assignment = (GradebookAssignment)value;
workingValue = assignment.getPointsPossible();
notCounted = assignment.isNotCounted();
// if weighting enabled, item is not counted if not assigned
// a category
if (!notCounted && assignment.getGradebook().getCategory_type() == GradebookService.CATEGORY_TYPE_WEIGHTED_CATEGORY) {
notCounted = assignment.getCategory() == null;
}
} else if (value instanceof AssignmentGradeRecord) {
Gradebook gradebook = ((GradableObject)((AbstractGradeRecord)value).getGradableObject()).getGradebook();
int gradeType = gradebook.getGrade_type();
AssignmentGradeRecord agr = (AssignmentGradeRecord)value;
if (agr.isUserAbleToView()) {
if(gradeType == GradebookService.GRADE_TYPE_POINTS ){
//if grade by points and no category weighting
workingValue = ((AbstractGradeRecord)value).getPointsEarned();
} else if (gradeType == GradebookService.GRADE_TYPE_LETTER) {
workingValue = agr.getLetterEarned();
} else {
//display percentage
percentage = true;
workingValue = agr.getPercentEarned();
}
} else {
workingValue = " ";
}
GradebookAssignment assignment = agr.getAssignment();
notCounted = assignment.isNotCounted();
// if weighting enabled, item is only counted if assigned
// a category
if (!notCounted && assignment.getGradebook().getCategory_type() == GradebookService.CATEGORY_TYPE_WEIGHTED_CATEGORY) {
notCounted = assignment.getCategory() == null;
}
} else if (value instanceof CourseGradeRecord) {
// display percentage
percentage = true;
workingValue = ((AbstractGradeRecord)value).getGradeAsPercentage();
if(ServerConfigurationService.getBoolean("gradebook.roster.showCourseGradePoints", false)){
Gradebook gradebook = ((GradableObject)((AbstractGradeRecord)value).getGradableObject()).getGradebook();
int gradeType = gradebook.getGrade_type();
if(gradeType == GradebookService.GRADE_TYPE_POINTS && gradebook.getCategory_type() != GradebookService.CATEGORY_TYPE_WEIGHTED_CATEGORY){
percentage = false;
workingValue = super.getAsString(context, component, ((CourseGradeRecord)value).getPointsEarned())
+ "/" + super.getAsString(context, component, ((CourseGradeRecord)value).getTotalPointsPossible());
}
}
}
}
formattedScore = super.getAsString(context, component, workingValue);
if (notCounted) {
formattedScore = FacesUtil.getLocalizedString("score_not_counted",
new String[] {formattedScore, FacesUtil.getLocalizedString("score_not_counted_tooltip")});
}
if(percentage && workingValue != null){
formattedScore += "%";
}
if(value != null && value instanceof AssignmentGradeRecord){
AssignmentGradeRecord agr = (AssignmentGradeRecord)value;
if(agr.getDroppedFromGrade()) {
formattedScore = "<strike>" + formattedScore + "</strike>";
}
}
if(value != null && value instanceof CourseGradeRecord && !ServerConfigurationService.getBoolean("gradebook.roster.showCourseGradePoints", false)){
if(((CourseGradeRecord) value).getEnteredGrade() != null){
formattedScore = "<span style='color: red'>" + formattedScore + "</span>";
}
}
return formattedScore;
}
}
|
package com.iramml.uberclone.riderapp.Activities;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.iramml.uberclone.riderapp.Common.Common;
import com.iramml.uberclone.riderapp.Fragments.BottomSheetRiderFragment;
import com.iramml.uberclone.riderapp.Helper.CustomInfoWindow;
import com.iramml.uberclone.riderapp.Interfaces.IFCMService;
import com.iramml.uberclone.riderapp.Interfaces.locationListener;
import com.iramml.uberclone.riderapp.Messages.Errors;
import com.iramml.uberclone.riderapp.Messages.Message;
import com.iramml.uberclone.riderapp.Model.User;
import com.iramml.uberclone.riderapp.Model.Token;
import com.iramml.uberclone.riderapp.R;
import com.iramml.uberclone.riderapp.Util.Location;
import com.facebook.AccessToken;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginManager;
import com.firebase.geofire.GeoFire;
import com.firebase.geofire.GeoLocation;
import com.firebase.geofire.GeoQuery;
import com.firebase.geofire.GeoQueryEventListener;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.OptionalPendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.AutocompleteFilter;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlaceAutocompleteFragment;
import com.google.android.gms.location.places.ui.PlaceSelectionListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MapStyleOptions;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.google.maps.android.SphericalUtil;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.squareup.picasso.Picasso;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import de.hdodenhof.circleimageview.CircleImageView;
import dmax.dialog.SpotsDialog;
public class Home extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
GoogleMap.OnInfoWindowClickListener {
Toolbar toolbar;
Location location=null;
private GoogleMap mMap;
Marker riderMarket, destinationMarker;
GoogleSignInAccount account;
DatabaseReference drivers;
GeoFire geoFire;
private GoogleApiClient mGoogleApiClient;
Double currentLat;
Double currentLng;
private static final int REQUEST_CODE_PERMISSION=100;
private static final int PLAY_SERVICES_REQUEST_CODE=2001;
SupportMapFragment mapFragment;
ImageView imgExpandable;
Button btnRequestPickup;
BottomSheetRiderFragment bottomSheetRiderFragment;
int radius=1; // km
int distance=1;
private static final int LIMIT=3;
IFCMService ifcmService;
DatabaseReference driversAvailable;
PlaceAutocompleteFragment placeLocation, placeDestination;
AutocompleteFilter typeFilter;
String mPlaceLocation, mPlaceDestination;
CircleImageView imgUser;
TextView txRiderName, tvStars;
FirebaseStorage storage;
StorageReference storageReference;
ImageView carUberX, carUberBlack;
boolean isUberX=false;
//Gooogle
private GoogleApiClient googleApiClient;
//Facebook
AccessToken accessToken = AccessToken.getCurrentAccessToken();
boolean isLoggedInFacebook = accessToken != null && !accessToken.isExpired();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
verifyGoogleAccount();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
storage=FirebaseStorage.getInstance();
storageReference=storage.getReference();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ifcmService=Common.getFCMService();
location=new Location(this, new locationListener() {
@Override
public void locationResponse(LocationResult response) {
// Add a icon_marker in Sydney and move the camera
currentLat=response.getLastLocation().getLatitude();
currentLng=response.getLastLocation().getLongitude();
Common.currenLocation=new LatLng(response.getLastLocation().getLatitude(), response.getLastLocation().getLongitude());
if(mPlaceLocation==null) {
displayLocation();
driversAvailable = FirebaseDatabase.getInstance().getReference(Common.driver_tbl);
driversAvailable.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
loadAllAvailableDriver(new LatLng(currentLat, currentLng));
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
});
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
carUberX=findViewById(R.id.selectedUberX);
carUberBlack=findViewById(R.id.selectedUberBlack);
carUberX.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isToggle=!isUberX;
isUberX=true;
if(isToggle) {
carUberX.setImageResource(R.drawable.car_cui_select);
carUberBlack.setImageResource(R.drawable.car_vip);
}
mMap.clear();
loadAllAvailableDriver(new LatLng(currentLat, currentLng));
}
});
carUberBlack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isToggle=isUberX;
isUberX=false;
if(isToggle) {
carUberX.setImageResource(R.drawable.car_cui);
carUberBlack.setImageResource(R.drawable.car_vip_select);
}
mMap.clear();
loadAllAvailableDriver(new LatLng(currentLat, currentLng));
}
});
btnRequestPickup=findViewById(R.id.btnPickupRequest);
btnRequestPickup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (currentLat!=null && currentLng!=null) {
if (!Common.driverFound)
requestPickup(Common.userID);
else
Common.sendRequestToDriver(Common.driverID, ifcmService, getApplicationContext(), Common.currenLocation);
}
}
});
placeDestination=(PlaceAutocompleteFragment)getFragmentManager().findFragmentById(R.id.placeDestination);
placeLocation=(PlaceAutocompleteFragment)getFragmentManager().findFragmentById(R.id.placeLocation);
typeFilter=new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_ADDRESS)
.setTypeFilter(3)
.build();
placeLocation.setOnPlaceSelectedListener(new PlaceSelectionListener() {
@Override
public void onPlaceSelected(Place place) {
mPlaceLocation=place.getAddress().toString();
mMap.clear();
riderMarket=mMap.addMarker(new MarkerOptions().position(place.getLatLng())
.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_marker))
.title("Pickup Here"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(place.getLatLng(), 15.0f));
}
@Override
public void onError(Status status) {
}
});
placeDestination.setOnPlaceSelectedListener(new PlaceSelectionListener() {
@Override
public void onPlaceSelected(Place place) {
mPlaceDestination=place.getAddress().toString();
mMap.addMarker(new MarkerOptions().position(place.getLatLng())
.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_destination_marker))
.title("Destination"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(place.getLatLng(), 15.0f));
BottomSheetRiderFragment mBottomSheet=BottomSheetRiderFragment.newInstance(mPlaceLocation, mPlaceDestination, false);
mBottomSheet.show(getSupportFragmentManager(), mBottomSheet.getTag());
}
@Override
public void onError(Status status) {
}
});
setUpLocation();
updateFirebaseToken();
}
public void initDrawer(){
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View navigationHeaderView=navigationView.getHeaderView(0);
TextView tvName=(TextView)navigationHeaderView.findViewById(R.id.tvRiderName);
TextView tvStars=(TextView)findViewById(R.id.tvStars);
CircleImageView imageAvatar=(CircleImageView) navigationHeaderView.findViewById(R.id.imgAvatar);
tvName.setText(Common.currentUser.getName());
if(Common.currentUser.getRates()!=null &&
!TextUtils.isEmpty(Common.currentUser.getRates()))
tvStars.setText(Common.currentUser.getRates());
if(isLoggedInFacebook)
Picasso.get().load("https://graph.facebook.com/" + Common.userID + "/picture?width=500&height=500").into(imageAvatar);
else if(account!=null)
Picasso.get().load(account.getPhotoUrl()).into(imageAvatar);
if(Common.currentUser.getAvatarUrl()!=null &&
!TextUtils.isEmpty(Common.currentUser.getAvatarUrl()))
Picasso.get().load(Common.currentUser.getAvatarUrl()).into(imageAvatar);
}
private void loadUser(){
FirebaseDatabase.getInstance().getReference(Common.user_rider_tbl)
.child(Common.userID)
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Common.currentUser=dataSnapshot.getValue(User.class);
initDrawer();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void verifyGoogleAccount() {
GoogleSignInOptions gso=new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
mGoogleApiClient=new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
OptionalPendingResult<GoogleSignInResult> opr=Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (opr.isDone()){
GoogleSignInResult result= opr.get();
handleSignInResult(result);
}else {
opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
@Override
public void onResult(@NonNull GoogleSignInResult googleSignInResult) {
handleSignInResult(googleSignInResult);
}
});
}
}
private void updateFirebaseToken() {
FirebaseDatabase db=FirebaseDatabase.getInstance();
final DatabaseReference tokens=db.getReference(Common.token_tbl);
final Token token=new Token(FirebaseInstanceId.getInstance().getToken());
if(FirebaseAuth.getInstance().getUid()!=null) tokens.child(FirebaseAuth.getInstance().getUid()).setValue(token);
else if(account!=null) tokens.child(account.getId()).setValue(token);
else{
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
String id = object.optString("id");
tokens.child(id).setValue(token);
}
});
request.executeAsync();
}
}
private void requestPickup(String uid) {
DatabaseReference dbRequest=FirebaseDatabase.getInstance().getReference(Common.pickup_request_tbl);
GeoFire mGeofire=new GeoFire(dbRequest);
mGeofire.setLocation(uid, new GeoLocation(Common.currenLocation.latitude, Common.currenLocation.longitude),
new GeoFire.CompletionListener() {
@Override
public void onComplete(String key, DatabaseError error) {
}
});
if (riderMarket.isVisible())riderMarket.remove();
riderMarket=mMap.addMarker(new MarkerOptions().title(getResources().getString(R.string.pickup_here)).snippet("").position(new LatLng(Common.currenLocation.latitude, Common.currenLocation.longitude))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
riderMarket.showInfoWindow();
btnRequestPickup.setText(getResources().getString(R.string.getting_uber));
findDriver();
}
private void findDriver() {
DatabaseReference driverLocation;
if(isUberX)
driverLocation=FirebaseDatabase.getInstance().getReference(Common.driver_tbl).child("UberX");
else
driverLocation=FirebaseDatabase.getInstance().getReference(Common.driver_tbl).child("Uber Black");
GeoFire geoFire=new GeoFire(driverLocation);
GeoQuery geoQuery=geoFire.queryAtLocation(new GeoLocation(Common.currenLocation.latitude, Common.currenLocation.longitude), radius);
geoQuery.removeAllListeners();
geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
@Override
public void onKeyEntered(String key, GeoLocation location) {
if (!Common.driverFound){
Common.driverFound=true;
Common.driverID=key;
btnRequestPickup.setText(getApplicationContext().getResources().getString(R.string.call_driver));
}
}
@Override
public void onKeyExited(String key) {
}
@Override
public void onKeyMoved(String key, GeoLocation location) {
}
@Override
public void onGeoQueryReady() {
if (!Common.driverFound && radius<LIMIT){
radius++;
findDriver();
}else{
if(!Common.driverFound) {
Toast.makeText(Home.this, "No available any driver near you", Toast.LENGTH_SHORT).show();
btnRequestPickup.setText("REQUEST PICKUP");
}
}
}
@Override
public void onGeoQueryError(DatabaseError error) {
}
});
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
switch (id){
case R.id.nav_trip_history:
showTripHistory();
break;
case R.id.nav_updateInformation:
showDialogUpdateInfo();
break;
case R.id.nav_signOut:
signOut();
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void showTripHistory() {
Intent intent=new Intent(Home.this, TripHistory.class);
startActivity(intent);
}
private void showDialogUpdateInfo() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Home.this);
alertDialog.setTitle("UPDATE INFORMATION");
LayoutInflater inflater = this.getLayoutInflater();
View layout_pwd = inflater.inflate(R.layout.layout_update_information, null);
final MaterialEditText etName = (MaterialEditText) layout_pwd.findViewById(R.id.etName);
final MaterialEditText etPhone = (MaterialEditText) layout_pwd.findViewById(R.id.etPhone);
final ImageView image_upload = (ImageView) layout_pwd.findViewById(R.id.imageUpload);
image_upload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
chooseImage();
}
});
alertDialog.setView(layout_pwd);
alertDialog.setPositiveButton("UPDATE", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
final android.app.AlertDialog waitingDialog = new SpotsDialog(Home.this);
waitingDialog.show();
String name = etName.getText().toString();
String phone = etPhone.getText().toString();
Map<String, Object> updateInfo = new HashMap<>();
if(!TextUtils.isEmpty(name))
updateInfo.put("name", name);
if(!TextUtils.isEmpty(phone))
updateInfo.put("phone",phone);
DatabaseReference driverInformation = FirebaseDatabase.getInstance().getReference(Common.user_rider_tbl);
driverInformation.child(Common.userID)
.updateChildren(updateInfo)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
waitingDialog.dismiss();
if(task.isSuccessful())
Toast.makeText(Home.this,"Information Updated!",Toast.LENGTH_SHORT).show();
else
Toast.makeText(Home.this,"Information Update Failed!",Toast.LENGTH_SHORT).show();
}
});
}
});
alertDialog.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
alertDialog.show();
}
private void chooseImage() {
Dexter.withActivity(this)
.withPermissions(Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
@Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
if(report.areAllPermissionsGranted()){
Intent intent=new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, Common.PICK_IMAGE_REQUEST);
}else{
Toast.makeText(getApplicationContext(), "Permission denied", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==Common.PICK_IMAGE_REQUEST && resultCode==RESULT_OK && data!=null && data.getData()!=null){
Uri saveUri=data.getData();
if(saveUri!=null){
final ProgressDialog progressDialog=new ProgressDialog(this);
progressDialog.setMessage("Uploading...");
progressDialog.show();
String imageName=UUID.randomUUID().toString();
final StorageReference imageFolder=storageReference.child("images/"+imageName);
imageFolder.putFile(saveUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(Home.this, "Uploaded!", Toast.LENGTH_SHORT).show();
imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
Map<String, Object> avatarUpdate=new HashMap<>();
avatarUpdate.put("avatarUrl", uri.toString());
DatabaseReference driverInformations=FirebaseDatabase.getInstance().getReference(Common.user_rider_tbl);
driverInformations.child(Common.userID).updateChildren(avatarUpdate)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful())
Toast.makeText(Home.this, "Uploaded!", Toast.LENGTH_SHORT).show();
else
Toast.makeText(Home.this, "Uploaded error!", Toast.LENGTH_SHORT).show();
}
});
}
});
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress=(100.0*taskSnapshot.getBytesTransferred())/taskSnapshot.getTotalByteCount();
progressDialog.setMessage("Uploaded "+progress+"%");
}
});
}
}
}
private void signOut() {
if(account!=null) {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(@NonNull Status status) {
if (status.isSuccess()) {
Intent intent = new Intent(Home.this, Login.class);
startActivity(intent);
finish();
} else {
Toast.makeText(Home.this, "Could not log out", Toast.LENGTH_SHORT).show();
}
}
});
}else if(isLoggedInFacebook){
LoginManager.getInstance().logOut();
Intent intent = new Intent(Home.this, Login.class);
startActivity(intent);
finish();
}else{
FirebaseAuth.getInstance().signOut();
Intent intent=new Intent(Home.this, Login.class);
startActivity(intent);
finish();
}
}
private void handleSignInResult(GoogleSignInResult result) {
if (result.isSuccess()) {
account = result.getSignInAccount();
Common.userID=account.getId();
loadUser();
}else if(isLoggedInFacebook){
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
String id=object.optString("id");
Common.userID=id;
loadUser();
}
});
request.executeAsync();
}else{
Common.userID=FirebaseAuth.getInstance().getCurrentUser().getUid();
loadUser();
}
}
private void setUpLocation() {
if(ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{
android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.ACCESS_FINE_LOCATION
}, REQUEST_CODE_PERMISSION);
}else{
if (checkPlayServices()){
buildGoogleApiClient();
displayLocation();
}
}
}
private void buildGoogleApiClient() {
mGoogleApiClient=new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
private boolean checkPlayServices() {
int resultCode= GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode!= ConnectionResult.SUCCESS){
if(GooglePlayServicesUtil.isUserRecoverableError(resultCode))
GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_REQUEST_CODE).show();
else {
Message.messageError(this, Errors.NOT_SUPPORT);
finish();
}
return false;
}
return true;
}
private void displayLocation(){
if (currentLat!=null && currentLng!=null){
LatLng center=new LatLng(currentLat, currentLng);
LatLng northSide=SphericalUtil.computeOffset(center, 100000, 0);
LatLng southSide=SphericalUtil.computeOffset(center, 100000, 180);
LatLngBounds bounds=LatLngBounds.builder()
.include(northSide)
.include(southSide)
.build();
placeLocation.setBoundsBias(bounds);
placeLocation.setFilter(typeFilter);
placeDestination.setBoundsBias(bounds);
placeDestination.setFilter(typeFilter);
//presence system
driversAvailable = FirebaseDatabase.getInstance().getReference(Common.driver_tbl);
driversAvailable.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//if have change from drivers table, we will reload all drivers available
loadAllAvailableDriver(new LatLng(currentLat, currentLng));
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
loadAllAvailableDriver(new LatLng(currentLat, currentLng));
}else{
Message.messageError(this, Errors.WITHOUT_LOCATION);
}
}
private void loadAllAvailableDriver(final LatLng location) {
mMap.clear();
riderMarket = mMap.addMarker(new MarkerOptions().position(location)
.title(getResources().getString(R.string.you))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_marker)));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(location, 15.0f));
DatabaseReference driverLocation;
if(isUberX)
driverLocation=FirebaseDatabase.getInstance().getReference(Common.driver_tbl).child("UberX");
else
driverLocation=FirebaseDatabase.getInstance().getReference(Common.driver_tbl).child("Uber Black");
GeoFire geoFire=new GeoFire(driverLocation);
GeoQuery geoQuery=geoFire.queryAtLocation(new GeoLocation(location.latitude, location.longitude), distance);
geoQuery.removeAllListeners();
geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
@Override
public void onKeyEntered(String key, final GeoLocation location) {
FirebaseDatabase.getInstance().getReference(Common.user_driver_tbl).child(key).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
User driver=dataSnapshot.getValue(User.class);
String name;
String phone;
if(driver.getName()!=null) name=driver.getName();
else name="not available";
if (driver.getPhone()!=null)phone="Phone: "+driver.getPhone();
else phone="Phone: none";
mMap.addMarker(new MarkerOptions().position(new LatLng(location.latitude, location.longitude)).flat(true)
.title(name).snippet("Driver ID: "+dataSnapshot.getKey()).icon(BitmapDescriptorFactory.fromResource(R.drawable.car)));
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
@Override
public void onKeyExited(String key) {
}
@Override
public void onKeyMoved(String key, GeoLocation location) {
}
@Override
public void onGeoQueryReady() {
if (distance<=LIMIT){
distance++;
loadAllAvailableDriver(location);
}
}
@Override
public void onGeoQueryError(DatabaseError error) {
}
});
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setZoomGesturesEnabled(true);
mMap.setInfoWindowAdapter(new CustomInfoWindow(this));
googleMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(this, R.raw.uber_style_map));
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
if(destinationMarker!=null)
destinationMarker.remove();
destinationMarker=mMap.addMarker(new MarkerOptions().position(latLng)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_destination_marker))
.title("Destination"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15.0f));
BottomSheetRiderFragment mBottomSheet=BottomSheetRiderFragment.newInstance(String.format("%f,%f", currentLat, currentLng),
String.format("%f,%f",latLng.latitude, latLng.longitude), true);
mBottomSheet.show(getSupportFragmentManager(), mBottomSheet.getTag());
}
});
mMap.setOnInfoWindowClickListener(this);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case REQUEST_CODE_PERMISSION:
if (grantResults.length>0 && grantResults[0]== PackageManager.PERMISSION_GRANTED){
location.onRequestPermissionResult(requestCode, permissions, grantResults);
if (checkPlayServices()){
buildGoogleApiClient();
displayLocation();
}
}
break;
case PLAY_SERVICES_REQUEST_CODE:
break;
}
}
@Override
protected void onStop() {
super.onStop();
location.stopUpdateLocation();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
displayLocation();
location.inicializeLocation();
}
@Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onInfoWindowClick(Marker marker) {
if(!marker.getTitle().equals("You")){
Intent intent=new Intent(Home.this, CallDriver.class);
String ID= marker.getSnippet().replace("Driver ID: ", "");
intent.putExtra("driverID", ID);
intent.putExtra("lat", currentLat);
intent.putExtra("lng", currentLng);
startActivity(intent);
}
}
}
|
package com.feng.project.product.production.service;
import com.feng.common.utils.StringUtils;
import com.feng.project.product.production.dao.IProductionDao;
import com.feng.project.product.production.domain.Production;
import com.feng.project.product.production.domain.ProductionSimple;
import com.feng.project.purchase.vendor.domain.Vendor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.feng.common.utils.security.ShiroUtils;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("productionService")
public class ProductionServiceImpl implements IProductionService {
@Autowired
private IProductionDao productionDao;
@Override
public List<Production> selectAllProduction(Production production) {
return productionDao.selectProductionAll(production);
}
public List<Production> selectProductionList(Production production)
{
return productionDao.selectProductionList(production);
}
@Override
public Production selectProductionById(Long id) {
return productionDao.selectByPrimaryKey(id);
}
@Override
public int deleteProductionById(Long id) {
if(productionDao.checkItemCodeIsUsed(id) == 0) {
return productionDao.deleteByPrimaryKey(id);
}else {
return -100;
}
}
@Override
public int saveProduction(Production production) {
Long productionId = production.getProductionId();
int count = 0;
if (StringUtils.isNotNull(productionId))
{
production.setUpdateBy(ShiroUtils.getLoginName());
// 修改供应商信息
count = productionDao.updateByPrimaryKeySelective(production);
}
else
{
production.setCreateBy(ShiroUtils.getLoginName());
// 新增供应商信息
count = productionDao.insertSelective(production);
}
return count;
}
@Override
public int batchDeleteProduction(Long[] ids) {
return productionDao.batchDeleteProduction(ids);
}
@Override
public List<ProductionSimple> selectProductionSimpleList(String searchStr, String type) {
if("code".equalsIgnoreCase(type)) {
return productionDao.selectProductionSimpleByCode(searchStr);
}
if("name".equalsIgnoreCase(type)) {
return productionDao.selectProductionSimpleByName(searchStr);
}
return null;
}
@Override
public String checkItemCodeUnique(String itemCode) {
int count = productionDao.checkItemCodeUnique(itemCode);
if(count>0){
return "1";
}
return "0";
}
}
|
/*
* Copyright 2002-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 org.springframework.expression.spel.ast;
import org.springframework.asm.MethodVisitor;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.Operation;
import org.springframework.expression.TypedValue;
import org.springframework.expression.spel.CodeFlow;
import org.springframework.expression.spel.ExpressionState;
import org.springframework.util.Assert;
import org.springframework.util.NumberUtils;
import java.math.BigDecimal;
import java.math.BigInteger;
/**
* Implements the modulus operator.
*
* @author Andy Clement
* @author Juergen Hoeller
* @author Giovanni Dall'Oglio Risso
* @since 3.0
*/
public class OpModulus extends Operator {
public OpModulus(int startPos, int endPos, SpelNodeImpl... operands) {
super("%", startPos, endPos, operands);
}
@Override
public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
Object leftOperand = getLeftOperand().getValueInternal(state).getValue();
Object rightOperand = getRightOperand().getValueInternal(state).getValue();
if (leftOperand instanceof Number && rightOperand instanceof Number) {
Number leftNumber = (Number) leftOperand;
Number rightNumber = (Number) rightOperand;
if (leftNumber instanceof BigDecimal || rightNumber instanceof BigDecimal) {
BigDecimal leftBigDecimal = NumberUtils.convertNumberToTargetClass(leftNumber, BigDecimal.class);
BigDecimal rightBigDecimal = NumberUtils.convertNumberToTargetClass(rightNumber, BigDecimal.class);
return new TypedValue(leftBigDecimal.remainder(rightBigDecimal));
} else if (leftNumber instanceof Double || rightNumber instanceof Double) {
this.exitTypeDescriptor = "D";
return new TypedValue(leftNumber.doubleValue() % rightNumber.doubleValue());
} else if (leftNumber instanceof Float || rightNumber instanceof Float) {
this.exitTypeDescriptor = "F";
return new TypedValue(leftNumber.floatValue() % rightNumber.floatValue());
} else if (leftNumber instanceof BigInteger || rightNumber instanceof BigInteger) {
BigInteger leftBigInteger = NumberUtils.convertNumberToTargetClass(leftNumber, BigInteger.class);
BigInteger rightBigInteger = NumberUtils.convertNumberToTargetClass(rightNumber, BigInteger.class);
return new TypedValue(leftBigInteger.remainder(rightBigInteger));
} else if (leftNumber instanceof Long || rightNumber instanceof Long) {
this.exitTypeDescriptor = "J";
return new TypedValue(leftNumber.longValue() % rightNumber.longValue());
} else if (CodeFlow.isIntegerForNumericOp(leftNumber) || CodeFlow.isIntegerForNumericOp(rightNumber)) {
this.exitTypeDescriptor = "I";
return new TypedValue(leftNumber.intValue() % rightNumber.intValue());
} else {
// Unknown Number subtypes -> best guess is double division
return new TypedValue(leftNumber.doubleValue() % rightNumber.doubleValue());
}
}
return state.operate(Operation.MODULUS, leftOperand, rightOperand);
}
@Override
public boolean isCompilable() {
if (!getLeftOperand().isCompilable()) {
return false;
}
if (this.children.length > 1) {
if (!getRightOperand().isCompilable()) {
return false;
}
}
return (this.exitTypeDescriptor != null);
}
@Override
public void generateCode(MethodVisitor mv, CodeFlow cf) {
getLeftOperand().generateCode(mv, cf);
String leftDesc = getLeftOperand().exitTypeDescriptor;
String exitDesc = this.exitTypeDescriptor;
Assert.state(exitDesc != null, "No exit type descriptor");
char targetDesc = exitDesc.charAt(0);
CodeFlow.insertNumericUnboxOrPrimitiveTypeCoercion(mv, leftDesc, targetDesc);
if (this.children.length > 1) {
cf.enterCompilationScope();
getRightOperand().generateCode(mv, cf);
String rightDesc = getRightOperand().exitTypeDescriptor;
cf.exitCompilationScope();
CodeFlow.insertNumericUnboxOrPrimitiveTypeCoercion(mv, rightDesc, targetDesc);
switch (targetDesc) {
case 'I':
mv.visitInsn(IREM);
break;
case 'J':
mv.visitInsn(LREM);
break;
case 'F':
mv.visitInsn(FREM);
break;
case 'D':
mv.visitInsn(DREM);
break;
default:
throw new IllegalStateException(
"Unrecognized exit type descriptor: '" + this.exitTypeDescriptor + "'");
}
}
cf.pushDescriptor(this.exitTypeDescriptor);
}
}
|
package info.smart_tools.smartactors.checkpoint.recover_strategies.chain_choice;
import info.smart_tools.smartactors.base.exception.invalid_argument_exception.InvalidArgumentException;
import info.smart_tools.smartactors.checkpoint.interfaces.exceptions.RecoverStrategyExecutionException;
import info.smart_tools.smartactors.checkpoint.interfaces.exceptions.RecoverStrategyInitializationException;
import info.smart_tools.smartactors.iobject.ifield_name.IFieldName;
import info.smart_tools.smartactors.iobject.iobject.IObject;
import info.smart_tools.smartactors.iobject.iobject.exception.ChangeValueException;
import info.smart_tools.smartactors.iobject.iobject.exception.ReadValueException;
import info.smart_tools.smartactors.ioc.iioccontainer.exception.ResolutionException;
import info.smart_tools.smartactors.ioc.ioc.IOC;
import info.smart_tools.smartactors.ioc.named_keys_storage.Keys;
/**
* Strategy that sends message to the same chain every time.
*
* <pre>
* {
* "strategy": "single chain recover strategy",
* "chain": "recoveryChain" // Name of the chain where the message will be sent
* }
* </pre>
*/
public class SingleChainRecoverStrategy implements IRecoveryChainChoiceStrategy {
private final IFieldName chainFieldName;
/**
* The constructor.
*
* @throws ResolutionException if error occurs resolving any dependencies
*/
public SingleChainRecoverStrategy()
throws ResolutionException {
chainFieldName = IOC.resolve(Keys.getOrAdd("info.smart_tools.smartactors.iobject.ifield_name.IFieldName"), "chain");
}
@Override
public void init(final IObject state, final IObject args) throws RecoverStrategyInitializationException {
try {
String chainName = (String) args.getValue(chainFieldName);
if (null == chainName) {
throw new RecoverStrategyInitializationException("Chain name should be defined.", null);
}
state.setValue(chainFieldName, chainName);
} catch (ReadValueException | ChangeValueException | InvalidArgumentException e) {
throw new RecoverStrategyInitializationException("Error occurred initializing strategy.", e);
}
}
@Override
public Object chooseRecoveryChain(final IObject state) throws RecoverStrategyExecutionException {
try {
return IOC.resolve(Keys.getOrAdd("chain_id_from_map_name"), state.getValue(chainFieldName));
} catch (ResolutionException | ReadValueException | InvalidArgumentException e) {
throw new RecoverStrategyExecutionException("Error occurred resolving chain identifier.", e);
}
}
}
|
/*
* MIT License
*
* Copyright (c) 2017-2018 nuls.io
*
* 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 io.nuls.tools.core.annotation;
import java.lang.annotation.*;
/**
* 该注解用来标识类型,当类型上标记了本注解,系统会在初始化阶段实例化该对象,并且对需要自动装载的属性进行赋值
* 该注解标识的类型生成的对象不使用动态代理的方式实例化,不会被默认拦截器拦截
* This annotation is used to identify the type, and when the annotation is marked on the type,
* the system instantiates the object in the initialization phase and assigns the attributes that need to be automatically loaded.
* The type generated by the annotation identifier is not instantiated using a dynamic proxy and is not intercepted by the default interceptor.
*
* @author: Niels Wang
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Component {
/**
* bean名称,可以为空,默认为空
* the bean name, it can be empty and the default is empty.
*
* @return 对象名称/bean name
*/
String value() default "";
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.lucene.queryparser.xml;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.queryparser.xml.builders.*;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.spans.SpanQuery;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.InputStream;
import java.util.Locale;
/**
* Assembles a QueryBuilder which uses only core Lucene Query objects
*/
public class CoreParser implements QueryBuilder, SpanQueryBuilder {
protected String defaultField;
protected Analyzer analyzer;
protected QueryParser parser;
protected QueryBuilderFactory queryFactory;
final protected SpanQueryBuilderFactory spanFactory;
/**
* Construct an XML parser that uses a single instance QueryParser for handling
* UserQuery tags - all parse operations are synchronised on this parser
*
* @param parser A QueryParser which will be synchronized on during parse calls.
*/
public CoreParser(Analyzer analyzer, QueryParser parser) {
this(null, analyzer, parser);
}
/**
* Constructs an XML parser that creates a QueryParser for each UserQuery request.
*
* @param defaultField The default field name used by QueryParsers constructed for UserQuery tags
*/
public CoreParser(String defaultField, Analyzer analyzer) {
this(defaultField, analyzer, null);
}
protected CoreParser(String defaultField, Analyzer analyzer, QueryParser parser) {
this.defaultField = defaultField;
this.analyzer = analyzer;
this.parser = parser;
queryFactory = new QueryBuilderFactory();
spanFactory = new SpanQueryBuilderFactory();
queryFactory.addBuilder("TermQuery", new TermQueryBuilder());
queryFactory.addBuilder("TermsQuery", new TermsQueryBuilder(analyzer));
queryFactory.addBuilder("MatchAllDocsQuery", new MatchAllDocsQueryBuilder());
queryFactory.addBuilder("BooleanQuery", new BooleanQueryBuilder(queryFactory));
queryFactory.addBuilder("LegacyNumericRangeQuery", new LegacyNumericRangeQueryBuilder());
queryFactory.addBuilder("PointRangeQuery", new PointRangeQueryBuilder());
queryFactory.addBuilder("RangeQuery", new RangeQueryBuilder());
queryFactory.addBuilder("DisjunctionMaxQuery", new DisjunctionMaxQueryBuilder(queryFactory));
if (parser != null) {
queryFactory.addBuilder("UserQuery", new UserInputQueryBuilder(parser));
} else {
queryFactory.addBuilder("UserQuery", new UserInputQueryBuilder(defaultField, analyzer));
}
queryFactory.addBuilder("ConstantScoreQuery", new ConstantScoreQueryBuilder(queryFactory));
SpanNearBuilder snb = new SpanNearBuilder(spanFactory);
spanFactory.addBuilder("SpanNear", snb);
queryFactory.addBuilder("SpanNear", snb);
BoostingTermBuilder btb = new BoostingTermBuilder();
spanFactory.addBuilder("BoostingTermQuery", btb);
queryFactory.addBuilder("BoostingTermQuery", btb);
SpanTermBuilder snt = new SpanTermBuilder();
spanFactory.addBuilder("SpanTerm", snt);
queryFactory.addBuilder("SpanTerm", snt);
SpanOrBuilder sot = new SpanOrBuilder(spanFactory);
spanFactory.addBuilder("SpanOr", sot);
queryFactory.addBuilder("SpanOr", sot);
SpanOrTermsBuilder sots = new SpanOrTermsBuilder(analyzer);
spanFactory.addBuilder("SpanOrTerms", sots);
queryFactory.addBuilder("SpanOrTerms", sots);
SpanFirstBuilder sft = new SpanFirstBuilder(spanFactory);
spanFactory.addBuilder("SpanFirst", sft);
queryFactory.addBuilder("SpanFirst", sft);
SpanNotBuilder snot = new SpanNotBuilder(spanFactory);
spanFactory.addBuilder("SpanNot", snot);
queryFactory.addBuilder("SpanNot", snot);
}
/**
* Parses the given stream as XML file and returns a {@link Query}.
* By default this disallows external entities for security reasons.
*/
public Query parse(InputStream xmlStream) throws ParserException {
return getQuery(parseXML(xmlStream).getDocumentElement());
}
// for test use
SpanQuery parseAsSpanQuery(InputStream xmlStream) throws ParserException {
return getSpanQuery(parseXML(xmlStream).getDocumentElement());
}
public void addQueryBuilder(String nodeName, QueryBuilder builder) {
queryFactory.addBuilder(nodeName, builder);
}
public void addSpanBuilder(String nodeName, SpanQueryBuilder builder) {
spanFactory.addBuilder(nodeName, builder);
}
public void addSpanQueryBuilder(String nodeName, SpanQueryBuilder builder) {
queryFactory.addBuilder(nodeName, builder);
spanFactory.addBuilder(nodeName, builder);
}
/**
* Returns a SAX {@link EntityResolver} to be used by {@link DocumentBuilder}.
* By default this returns {@link #DISALLOW_EXTERNAL_ENTITY_RESOLVER}, which disallows the
* expansion of external entities (for security reasons). To restore legacy behavior,
* override this method to return {@code null}.
*/
protected EntityResolver getEntityResolver() {
return DISALLOW_EXTERNAL_ENTITY_RESOLVER;
}
/**
* Subclass and override to return a SAX {@link ErrorHandler} to be used by {@link DocumentBuilder}.
* By default this returns {@code null} so no error handler is used.
* This method can be used to redirect XML parse errors/warnings to a custom logger.
*/
protected ErrorHandler getErrorHandler() {
return null;
}
private Document parseXML(InputStream pXmlFile) throws ParserException {
final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
try {
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
} catch (ParserConfigurationException e) {
// ignore since all implementations are required to support the
// {@link javax.xml.XMLConstants#FEATURE_SECURE_PROCESSING} feature
}
final DocumentBuilder db;
try {
db = dbf.newDocumentBuilder();
} catch (Exception se) {
throw new ParserException("XML Parser configuration error.", se);
}
try {
db.setEntityResolver(getEntityResolver());
db.setErrorHandler(getErrorHandler());
return db.parse(pXmlFile);
} catch (Exception se) {
throw new ParserException("Error parsing XML stream: " + se, se);
}
}
public Query getQuery(Element e) throws ParserException {
return queryFactory.getQuery(e);
}
@Override
public SpanQuery getSpanQuery(Element e) throws ParserException {
return spanFactory.getSpanQuery(e);
}
public static final EntityResolver DISALLOW_EXTERNAL_ENTITY_RESOLVER = (String publicId, String systemId) -> {
throw new SAXException(String.format(Locale.ENGLISH,
"External Entity resolving unsupported: publicId=\"%s\" systemId=\"%s\"",
publicId, systemId));
};
}
|
/*
* Copyright 2012-2018 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.samples.petclinic;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* PetClinic Spring Boot Application.
*
* @author Dave Syer
*
*/
@SpringBootApplication
public class PetClinicApplication {
public static void main(String[] args) {
SpringApplication.run(PetClinicApplication.class, args);
}
}
|
/*
* Licensed to Crate.io GmbH ("Crate") under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership. Crate 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.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial agreement.
*/
package io.crate.execution.engine.collect.files;
import io.crate.analyze.CopyFromParserProperties;
import org.junit.Before;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.net.URI;
import java.net.URISyntaxException;
import static io.crate.execution.dsl.phases.FileUriCollectPhase.InputFormat.CSV;
import static io.crate.execution.dsl.phases.FileUriCollectPhase.InputFormat.JSON;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
public class LineProcessorTest {
private LineProcessor subjectUnderTest;
private URI uri;
private BufferedReader bufferedReader;
@Before
public void setup() {
subjectUnderTest = new LineProcessor(CopyFromParserProperties.DEFAULT);
}
@Test
public void readFirstLine_givenFileExtensionIsCsv_AndDefaultJSONFileFormat_thenReadsLine() throws URISyntaxException, IOException {
uri = new URI ("file.csv");
Reader reader = new StringReader("some/string");
bufferedReader = new BufferedReader(reader);
subjectUnderTest.readFirstLine(uri, JSON, bufferedReader);
assertThat(bufferedReader.readLine(), is(nullValue()));
}
@Test
public void readFirstLine_givenFileFormatIsCsv_thenReadsLine() throws URISyntaxException, IOException {
uri = new URI ("file.any");
Reader reader = new StringReader("some/string");
bufferedReader = new BufferedReader(reader);
subjectUnderTest.readFirstLine(uri, CSV, bufferedReader);
assertThat(bufferedReader.readLine(), is(nullValue()));
}
@Test
public void readFirstLine_givenFileExtensionIsJson__AndDefaultJSONFileFormat_thenDoesNotReadLine() throws URISyntaxException, IOException {
uri = new URI ("file.json");
Reader reader = new StringReader("some/string");
bufferedReader = new BufferedReader(reader);
subjectUnderTest.readFirstLine(uri, JSON, bufferedReader);
assertThat(bufferedReader.readLine(), is("some/string"));
}
@Test
public void readFirstLine_givenFileFormatIsJson_thenDoesNotReadLine() throws URISyntaxException, IOException {
uri = new URI ("file.any");
Reader reader = new StringReader("some/string");
bufferedReader = new BufferedReader(reader);
subjectUnderTest.readFirstLine(uri, JSON, bufferedReader);
assertThat(bufferedReader.readLine(), is("some/string"));
}
}
|
package org.hibernate.validator.referenceguide.chapter08;
public class Car {
}
|
/**
* Copyright 2014 XCL-Charts
*
* 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.
*
* @Project XCL-Charts
* @Description Android图表基类库演示
* @author XiongChuanLiang<br/>(xcl_168@aliyun.com)
* @license http://www.apache.org/licenses/ Apache v2 License
* @version 1.7
*/
package com.mygame.pure.view;
import java.util.List;
import org.xclcharts.common.DensityUtil;
import org.xclcharts.renderer.XChart;
import org.xclcharts.view.ChartView;
import android.content.Context;
import android.util.AttributeSet;
/**
* @ClassName DemoView
* @Description 各个例子view的view基类
* @author XiongChuanLiang<br/>(xcl_168@aliyun.com)
*/
public class DemoView extends ChartView{
public DemoView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public DemoView(Context context, AttributeSet attrs){
super(context, attrs);
}
public DemoView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public List<XChart> bindChart() {
// TODO Auto-generated method stub
return null;
}
//Demo中bar chart所使用的默认偏移值。
//偏移出来的空间用于显示tick,axistitle....
protected int[] getBarLnDefaultSpadding()
{
int [] ltrb = new int[4];
ltrb[0] = DensityUtil.dip2px(getContext(), 40); //left
ltrb[1] = DensityUtil.dip2px(getContext(), 60); //top
ltrb[2] = DensityUtil.dip2px(getContext(), 20); //right
ltrb[3] = DensityUtil.dip2px(getContext(), 40); //bottom
return ltrb;
}
protected int[] getPieDefaultSpadding()
{
int [] ltrb = new int[4];
ltrb[0] = DensityUtil.dip2px(getContext(), 20); //left
ltrb[1] = DensityUtil.dip2px(getContext(), 65); //top
ltrb[2] = DensityUtil.dip2px(getContext(), 20); //right
ltrb[3] = DensityUtil.dip2px(getContext(), 20); //bottom
return ltrb;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
}
|
package easy.data.tests;
import static easy.data.sig.PrimSig.*;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Before;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import easy.data.sig.*;
import java.util.ArrayList;
public class ISigTests {
ArrayList<String> al1;
ArrayList<Integer> al2;
//ArrayList<Thread> al3; cannot get reflection info about arraylist component type
String[] as1;
int[] as2;
Thread[] as3;
ListSig ls1;
ListSig ls2;
CompSig<C1> cs1; // C1: int * string
CompSig<C1> cs2; // C1: int * int
CompSig<C1> cs3; // C1: int
CompSig<C2> cs4; // C2: int * int
static ISigVisitor<Integer> intVisitor = new ISigVisitor<Integer>() {
public Integer defaultVisit(ISig s) { return 0; }
public <C> Integer visit(PrimSig s) { return 1; }
public Integer visit(CompSig<?> s) { return 2; }
public Integer visit(ListSig s) { return 3; }
};
@SuppressWarnings("unused")
private static class C1 {
C1(int x, String y) {}
C1(int x, int y) {}
C1(Double s) {}
}
private static class C2 {}
@Rule
public ExpectedException exception = ExpectedException.none();
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
al1 = new ArrayList<String>();
al2 = new ArrayList<Integer>();
//al3 = new ArrayList<Thread>();
as1 = new String[] {};
as2 = new int[] {};
as3 = new Thread[] {};
ls1 = new ListSig(STRING_SIG);
ls2 = new ListSig(INT_SIG);
cs1 = new CompSig<C1>(C1.class);
cs2 = new CompSig<C1>(C1.class);
cs3 = new CompSig<C1>(C1.class);
cs4 = new CompSig<C2>(C2.class);
cs1.addField(INT_SIG, "xf");
cs1.addField(STRING_SIG, "yf");
cs2.addField(INT_SIG, "xf");
cs2.addField(INT_SIG, "yf");
cs3.addField(INT_SIG, "xf");
cs4.addField(INT_SIG, "xf");
cs4.addField(INT_SIG, "yf");
}
@After
public void tearDown() throws Exception {
}
@Test
public void testApply() {
assertSame(BOOLEAN_SIG.apply(intVisitor), 1);
assertSame(cs1.apply(intVisitor), 2);
assertSame(ls1.apply(intVisitor), 3);
}
@Test
public void testUnifyWithPrimSig() throws SignatureUnificationException {
assertEquals(BOOLEAN_SIG.unifyWith(Boolean.class), BOOLEAN_SIG);
assertEquals(BOOLEAN_SIG.unifyWith(boolean.class), BOOLEAN_SIG);
assertEquals(BYTE_SIG.unifyWith(Byte.class), BYTE_SIG);
assertEquals(BYTE_SIG.unifyWith(byte.class), BYTE_SIG);
assertEquals(CHAR_SIG.unifyWith(Character.class), CHAR_SIG);
assertEquals(CHAR_SIG.unifyWith(char.class), CHAR_SIG);
assertEquals(DOUBLE_SIG.unifyWith(double.class), DOUBLE_SIG);
assertEquals(STRING_SIG.unifyWith(String.class), STRING_SIG);
assertEquals(WILDCARD_SIG.unifyWith(byte.class), BYTE_SIG);
assertEquals(WILDCARD_SIG.unifyWith(String.class), STRING_SIG);
assertEquals(WILDCARD_SIG.unifyWith(Boolean.class), BOOLEAN_SIG);
assertEquals(WILDCARD_SIG.unifyWith(Double.class), DOUBLE_SIG);
assertEquals(WILDCARD_SIG.unifyWith(int.class), INT_SIG);
assertEquals(BOOLEAN_SIG.unifyWith(String.class), STRING_SIG);
assertEquals(BYTE_SIG.unifyWith(String.class), STRING_SIG);
assertEquals(INT_SIG.unifyWith(String.class), STRING_SIG);
assertEquals(DOUBLE_SIG.unifyWith(String.class), STRING_SIG);
}
@Test
public void testUnifyFailBoolean() throws SignatureUnificationException {
exception.expect(SignatureUnificationException.class);
exception.expectMessage("<boolean> cannot be unified with java.lang.Double");
BOOLEAN_SIG.unifyWith(Double.class);
}
@Test
public void testUnifyFailByte() throws SignatureUnificationException {
exception.expect(SignatureUnificationException.class);
BYTE_SIG.unifyWith(int.class);
}
@Test
public void testUnifyFailNonprim() throws SignatureUnificationException {
exception.expect(SignatureUnificationException.class);
exception.expectMessage("java.lang.Thread is not a primitive class");
WILDCARD_SIG.unifyWith(Thread.class);
}
@Test
public void testUnifyWithArrayList() throws SignatureUnificationException {
assertEquals(ls1.unifyWith(al1.getClass()), ls1);
assertEquals(ls1.unifyWith(as1.getClass()), ls1);
assertEquals(ls2.unifyWith(al2.getClass()), ls2);
assertEquals(ls2.unifyWith(as2.getClass()), ls2);
}
@Test
public void testUnifyWithArrayFail1() throws SignatureUnificationException {
exception.expect(SignatureUnificationException.class);
ls1.unifyWith(as2.getClass());
}
@Test
public void testUnifyWithArrayFail2() throws SignatureUnificationException {
exception.expect(SignatureUnificationException.class);
ls1.unifyWith(as3.getClass());
}
@Test
public void testUnifyWithComp() throws SignatureUnificationException {
assertEquals(cs1.unifyWith(C1.class), cs1);
assertEquals(cs2.unifyWith(C1.class), cs2);
}
@Test
public void testUnifyWithCompFail1() throws SignatureUnificationException {
exception.expect(SignatureUnificationException.class);
cs3.unifyWith(C1.class);
}
@Test
public void testUnifyWithCompFail2() throws SignatureUnificationException {
exception.expect(SignatureUnificationException.class);
cs4.unifyWith(C1.class);
}
@Test
public void testUnifyWithCompFail3() throws SignatureUnificationException {
exception.expect(SignatureUnificationException.class);
cs2.unifyWith(C2.class);
}
}
|
package org.jruby.runtime;
import java.io.EOFException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Array;
import java.net.PortUnreachableException;
import java.nio.channels.ClosedChannelException;
import java.nio.charset.Charset;
import java.nio.file.AccessDeniedException;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileSystemLoopException;
import java.nio.file.NoSuchFileException;
import java.nio.file.NotDirectoryException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Pattern;
import jnr.constants.platform.Errno;
import org.jruby.*;
import org.jruby.ast.ArgsNode;
import org.jruby.ast.ArgumentNode;
import org.jruby.ast.MultipleAsgnNode;
import org.jruby.ast.Node;
import org.jruby.ast.UnnamedRestArgNode;
import org.jruby.ast.types.INameNode;
import org.jruby.ast.RequiredKeywordArgumentValueNode;
import org.jruby.common.IRubyWarnings.ID;
import org.jruby.exceptions.RaiseException;
import org.jruby.exceptions.Unrescuable;
import org.jruby.internal.runtime.methods.*;
import org.jruby.ir.IRScope;
import org.jruby.ir.IRScopeType;
import org.jruby.ir.Interp;
import org.jruby.ir.JIT;
import org.jruby.ir.operands.UndefinedValue;
import org.jruby.ir.runtime.IRRuntimeHelpers;
import org.jruby.javasupport.JavaClass;
import org.jruby.javasupport.JavaUtil;
import org.jruby.javasupport.proxy.InternalJavaProxy;
import org.jruby.parser.StaticScope;
import org.jruby.runtime.JavaSites.HelpersSites;
import org.jruby.runtime.backtrace.BacktraceData;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.callsite.CacheEntry;
import org.jruby.runtime.invokedynamic.MethodNames;
import org.jruby.util.ArraySupport;
import org.jruby.util.ByteList;
import org.jruby.util.MurmurHash;
import org.jruby.util.TypeConverter;
import org.jcodings.Encoding;
import org.jcodings.specific.ASCIIEncoding;
import org.jcodings.specific.USASCIIEncoding;
import org.jcodings.specific.UTF8Encoding;
import org.jcodings.unicode.UnicodeEncoding;
import static org.jruby.RubyBasicObject.getMetaClass;
import static org.jruby.runtime.Visibility.PRIVATE;
import static org.jruby.runtime.Visibility.PROTECTED;
import static org.jruby.runtime.invokedynamic.MethodNames.EQL;
import static org.jruby.util.CodegenUtils.sig;
import static org.jruby.util.RubyStringBuilder.str;
import static org.jruby.util.RubyStringBuilder.ids;
import static org.jruby.util.RubyStringBuilder.types;
import static org.jruby.util.StringSupport.EMPTY_STRING_ARRAY;
import org.jruby.util.io.EncodingUtils;
/**
* Helper methods which are called by the compiler. Note: These will show no consumers, but
* generated code does call these so don't remove them thinking they are dead code.
*
*/
public class Helpers {
public static final Pattern SEMICOLON_PATTERN = Pattern.compile(";");
public static RubyClass getSingletonClass(Ruby runtime, IRubyObject receiver) {
if (receiver instanceof RubyFixnum || receiver instanceof RubySymbol) {
throw runtime.newTypeError("can't define singleton");
} else {
return receiver.getSingletonClass();
}
}
@Deprecated // no longer used - only been used by interface implementation
public static IRubyObject invokeMethodMissing(IRubyObject receiver, String name, IRubyObject[] args) {
ThreadContext context = receiver.getRuntime().getCurrentContext();
// store call information so method_missing impl can use it
context.setLastCallStatusAndVisibility(CallType.FUNCTIONAL, Visibility.PUBLIC);
if (name.equals("method_missing")) {
return RubyKernel.method_missing(context, receiver, args, Block.NULL_BLOCK);
}
IRubyObject[] newArgs = prepareMethodMissingArgs(args, context, name);
return invoke(context, receiver, "method_missing", newArgs, Block.NULL_BLOCK);
}
public static IRubyObject callMethodMissing(ThreadContext context, IRubyObject self, RubyClass klass, Visibility visibility, String name, CallType callType, IRubyObject[] args, Block block) {
return selectMethodMissing(context, klass, visibility, name, callType).call(context, self, klass, name, args, block);
}
public static IRubyObject callMethodMissing(ThreadContext context, IRubyObject receiver, Visibility visibility, String name, CallType callType, IRubyObject[] args, Block block) {
final RubyClass klass = getMetaClass(receiver);
return selectMethodMissing(context, klass, visibility, name, callType).call(context, receiver, klass, name, args, block);
}
public static IRubyObject callMethodMissing(ThreadContext context, IRubyObject self, RubyClass klass, Visibility visibility, String name, CallType callType, IRubyObject arg0, Block block) {
return selectMethodMissing(context, klass, visibility, name, callType).call(context, self, klass, name, arg0, block);
}
public static IRubyObject callMethodMissing(ThreadContext context, IRubyObject receiver, Visibility visibility, String name, CallType callType, IRubyObject arg0, Block block) {
final RubyClass klass = getMetaClass(receiver);
return selectMethodMissing(context, klass, visibility, name, callType).call(context, receiver, klass, name, arg0, block);
}
public static IRubyObject callMethodMissing(ThreadContext context, IRubyObject self, RubyClass klass, Visibility visibility, String name, CallType callType, IRubyObject arg0, IRubyObject arg1, Block block) {
return selectMethodMissing(context, klass, visibility, name, callType).call(context, self, klass, name, arg0, arg1, block);
}
public static IRubyObject callMethodMissing(ThreadContext context, IRubyObject receiver, Visibility visibility, String name, CallType callType, IRubyObject arg0, IRubyObject arg1, Block block) {
final RubyClass klass = getMetaClass(receiver);
return selectMethodMissing(context, klass, visibility, name, callType).call(context, receiver, klass, name, arg0, arg1, block);
}
public static IRubyObject callMethodMissing(ThreadContext context, IRubyObject self, RubyClass klass, Visibility visibility, String name, CallType callType, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, Block block) {
return selectMethodMissing(context, klass, visibility, name, callType).call(context, self, klass, name, arg0, arg1, arg2, block);
}
public static IRubyObject callMethodMissing(ThreadContext context, IRubyObject receiver, Visibility visibility, String name, CallType callType, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, Block block) {
final RubyClass klass = getMetaClass(receiver);
return selectMethodMissing(context, klass, visibility, name, callType).call(context, receiver, klass, name, arg0, arg1, arg2, block);
}
public static IRubyObject callMethodMissing(ThreadContext context, IRubyObject self, RubyClass klass, Visibility visibility, String name, CallType callType, Block block) {
return selectMethodMissing(context, klass, visibility, name, callType).call(context, self, klass, name, block);
}
public static IRubyObject callMethodMissing(ThreadContext context, IRubyObject receiver, Visibility visibility, String name, CallType callType, Block block) {
final RubyClass klass = getMetaClass(receiver);
return selectMethodMissing(context, klass, visibility, name, callType).call(context, receiver, klass, name, block);
}
public static DynamicMethod selectMethodMissing(ThreadContext context, IRubyObject receiver, Visibility visibility, String name, CallType callType) {
Ruby runtime = context.runtime;
if (name.equals("method_missing")) {
return selectInternalMM(runtime, visibility, callType);
}
CacheEntry entry = receiver.getMetaClass().searchWithCache("method_missing");
DynamicMethod methodMissing = entry.method;
if (methodMissing.isUndefined() || methodMissing.equals(runtime.getDefaultMethodMissing())) {
return selectInternalMM(runtime, visibility, callType);
}
return new MethodMissingMethod(entry, visibility, callType);
}
public static DynamicMethod selectMethodMissing(ThreadContext context, RubyClass selfClass, Visibility visibility, String name, CallType callType) {
final Ruby runtime = context.runtime;
if (name.equals("method_missing")) {
return selectInternalMM(runtime, visibility, callType);
}
CacheEntry entry = selfClass.searchWithCache("method_missing");
DynamicMethod methodMissing = entry.method;
if (methodMissing.isUndefined() || methodMissing.equals(runtime.getDefaultMethodMissing())) {
return selectInternalMM(runtime, visibility, callType);
}
return new MethodMissingMethod(entry, visibility, callType);
}
public static DynamicMethod selectMethodMissing(RubyClass selfClass, Visibility visibility, String name, CallType callType) {
Ruby runtime = selfClass.getClassRuntime();
if (name.equals("method_missing")) {
return selectInternalMM(runtime, visibility, callType);
}
CacheEntry entry = selfClass.searchWithCache("method_missing");
DynamicMethod methodMissing = entry.method;
if (methodMissing.isUndefined() || methodMissing.equals(runtime.getDefaultMethodMissing())) {
return selectInternalMM(runtime, visibility, callType);
}
return new MethodMissingMethod(entry, visibility, callType);
}
public static final Map<String, String> map(String... keyValues) {
HashMap<String, String> map = new HashMap<>(keyValues.length / 2 + 1, 1);
for (int i = 0; i < keyValues.length;) {
map.put(keyValues[i++], keyValues[i++]);
}
return map;
}
public static boolean additionOverflowed(long original, long other, long result) {
return (~(original ^ other) & (original ^ result) & RubyFixnum.SIGN_BIT) != 0;
}
public static boolean subtractionOverflowed(long original, long other, long result) {
return (~(original ^ ~other) & (original ^ result) & RubyFixnum.SIGN_BIT) != 0;
}
/**
* This method attempts to produce an Errno value for the given exception.
*
* Many low-level operations wrapped by the JDK will raise IOException or subclasses of it when there's a system-
* level error. In most cases, the only way to determine the cause of the IOException is by inspecting its contents,
* usually by checking the error message string. This is obviously fragile and breaks on platforms localized to
* languages other than English, so we also try as much as possible to detect the cause of the error by its actual
* type (if it is indeed a specialized subtype of IOException).
*
* @param t the exception to convert to an {@link Errno}
* @return the resulting {@link Errno} value, or null if none could be determined.
*/
public static Errno errnoFromException(Throwable t) {
// FIXME: Error-message scrapingis gross and turns out to be fragile if the host system is localized jruby/jruby#5415
// Try specific exception types by rethrowing and catching.
try {
throw t;
} catch (FileNotFoundException fnfe) {
return Errno.ENOENT;
} catch (EOFException eofe) {
return Errno.EPIPE;
} catch (AtomicMoveNotSupportedException amnse) {
return Errno.EXDEV;
} catch (ClosedChannelException cce) {
return Errno.EBADF;
} catch (PortUnreachableException pue) {
return Errno.ECONNREFUSED;
} catch (FileAlreadyExistsException faee) {
return Errno.EEXIST;
} catch (FileSystemLoopException fsle) {
return Errno.ELOOP;
} catch (NoSuchFileException nsfe) {
return Errno.ENOENT;
} catch (NotDirectoryException nde) {
return Errno.ENOTDIR;
} catch (AccessDeniedException ade) {
return Errno.EACCES;
} catch (DirectoryNotEmptyException dnee) {
switch (dnee.getMessage()) {
case "File exists":
return Errno.EEXIST;
case "Directory not empty":
return Errno.ENOTEMPTY;
}
} catch (Throwable t2) {
// fall through
}
final String errorMessage = t.getMessage();
if (errorMessage != null) {
// All errors to sysread should be SystemCallErrors, but on a closed stream
// Ruby returns an IOError. Java throws same exception for all errors so
// we resort to this hack...
switch (errorMessage) {
case "Bad file descriptor":
return Errno.EBADF;
case "File not open":
return null;
case "An established connection was aborted by the software in your host machine":
case "connection was aborted": // Windows
return Errno.ECONNABORTED;
case "Broken pipe":
return Errno.EPIPE;
case "Connection reset by peer":
case "An existing connection was forcibly closed by the remote host":
return Errno.ECONNRESET;
case "Too many levels of symbolic links":
return Errno.ELOOP;
case "Too many open files":
return Errno.EMFILE;
case "Too many open files in system":
return Errno.ENFILE;
case "Network is unreachable":
return Errno.ENETUNREACH;
case "Address already in use":
return Errno.EADDRINUSE;
case "No space left on device":
return Errno.ENOSPC;
case "Message too large": // Alpine Linux
case "Message too long":
return Errno.EMSGSIZE;
case "Is a directory":
return Errno.EISDIR;
case "Operation timed out":
return Errno.ETIMEDOUT;
case "No route to host":
return Errno.EHOSTUNREACH;
case "permission denied":
case "Permission denied":
return Errno.EACCES;
case "Protocol family unavailable":
return Errno.EADDRNOTAVAIL;
}
}
return null;
}
/**
* Java does not give us enough information for specific error conditions
* so we are reduced to divining them through string matches...
*
* TODO: Should ECONNABORTED get thrown earlier in the descriptor itself or is it ok to handle this late?
* TODO: Should we include this into Errno code somewhere do we can use this from other places as well?
*/
public static RaiseException newIOErrorFromException(Ruby runtime, IOException ex) {
Errno errno = errnoFromException(ex);
if (errno == null) throw runtime.newIOError(ex.getLocalizedMessage());
throw runtime.newErrnoFromErrno(errno, ex.getLocalizedMessage());
}
public static RubyModule getNthScopeModule(StaticScope scope, int depth) {
int n = depth;
while (n > 0) {
scope = scope.getEnclosingScope();
if (scope.getScopeType() != null) {
n--;
}
}
return scope.getModule();
}
public static RubyArray viewArgsArray(ThreadContext context, RubyArray rubyArray, int preArgsCount, int postArgsCount) {
int n = rubyArray.getLength();
if (preArgsCount + postArgsCount >= n) {
return RubyArray.newEmptyArray(context.runtime);
}
return (RubyArray)rubyArray.subseq(context.runtime.getArray(), preArgsCount, n - preArgsCount - postArgsCount, true);
}
public static Class[] getStaticMethodParams(Class target, int args) {
switch (args) {
case 0:
return new Class[] {target, ThreadContext.class, IRubyObject.class, Block.class};
case 1:
return new Class[] {target, ThreadContext.class, IRubyObject.class, IRubyObject.class, Block.class};
case 2:
return new Class[] {target, ThreadContext.class, IRubyObject.class, IRubyObject.class, IRubyObject.class, Block.class};
case 3:
return new Class[] {target, ThreadContext.class, IRubyObject.class, IRubyObject.class, IRubyObject.class, IRubyObject.class, Block.class};
case 4:
return new Class[] {target, ThreadContext.class, IRubyObject.class, IRubyObject[].class, Block.class};
default:
throw new RuntimeException("unsupported arity: " + args);
}
}
public static String getStaticMethodSignature(String classname, int args) {
switch (args) {
case 0:
return sig(IRubyObject.class, "L" + classname + ";", ThreadContext.class, IRubyObject.class, Block.class);
case 1:
return sig(IRubyObject.class, "L" + classname + ";", ThreadContext.class, IRubyObject.class, IRubyObject.class, Block.class);
case 2:
return sig(IRubyObject.class, "L" + classname + ";", ThreadContext.class, IRubyObject.class, IRubyObject.class, IRubyObject.class, Block.class);
case 3:
return sig(IRubyObject.class, "L" + classname + ";", ThreadContext.class, IRubyObject.class, IRubyObject.class, IRubyObject.class, IRubyObject.class, Block.class);
case 4:
return sig(IRubyObject.class, "L" + classname + ";", ThreadContext.class, IRubyObject.class, IRubyObject[].class, Block.class);
default:
throw new RuntimeException("unsupported arity: " + args);
}
}
private static class MethodMissingMethod extends DynamicMethod {
private final CacheEntry entry;
private final CallType lastCallStatus;
private final Visibility lastVisibility;
public MethodMissingMethod(CacheEntry entry, Visibility lastVisibility, CallType lastCallStatus) {
super(entry.method.getImplementationClass(), lastVisibility, entry.method.getName());
this.entry = entry;
this.lastCallStatus = lastCallStatus;
this.lastVisibility = lastVisibility;
}
@Override
public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args, Block block) {
context.setLastCallStatusAndVisibility(lastCallStatus, lastVisibility);
return this.entry.method.call(context, self, entry.sourceModule, "method_missing", prepareMethodMissingArgs(args, context, name), block);
}
@Override
public DynamicMethod dup() {
return this;
}
}
private static DynamicMethod selectInternalMM(Ruby runtime, Visibility visibility, CallType callType) {
if (visibility == Visibility.PRIVATE) {
return runtime.getPrivateMethodMissing();
} else if (visibility == Visibility.PROTECTED) {
return runtime.getProtectedMethodMissing();
} else if (callType == CallType.VARIABLE) {
return runtime.getVariableMethodMissing();
} else if (callType == CallType.SUPER) {
return runtime.getSuperMethodMissing();
} else {
return runtime.getNormalMethodMissing();
}
}
private static IRubyObject[] prepareMethodMissingArgs(IRubyObject[] args, ThreadContext context, String name) {
return ArraySupport.newCopy(context.runtime.newSymbol(name), args);
}
public static IRubyObject invoke(ThreadContext context, IRubyObject self, String name, Block block) {
return self.getMetaClass().finvoke(context, self, name, block);
}
public static IRubyObject invoke(ThreadContext context, IRubyObject self, String name, IRubyObject arg0, Block block) {
return self.getMetaClass().finvoke(context, self, name, arg0, block);
}
public static IRubyObject invoke(ThreadContext context, IRubyObject self, String name, IRubyObject arg0, IRubyObject arg1, Block block) {
return self.getMetaClass().finvoke(context, self, name, arg0, arg1, block);
}
public static IRubyObject invoke(ThreadContext context, IRubyObject self, String name, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, Block block) {
return self.getMetaClass().finvoke(context, self, name, arg0, arg1, arg2, block);
}
public static IRubyObject invoke(ThreadContext context, IRubyObject self, String name, IRubyObject[] args, Block block) {
return self.getMetaClass().finvoke(context, self, name, args, block);
}
public static IRubyObject invoke(ThreadContext context, IRubyObject self, String name) {
return self.getMetaClass().finvoke(context, self, name);
}
public static IRubyObject invoke(ThreadContext context, IRubyObject self, String name, IRubyObject arg0) {
return self.getMetaClass().finvoke(context, self, name, arg0);
}
public static IRubyObject invoke(ThreadContext context, IRubyObject self, String name, IRubyObject arg0, IRubyObject arg1) {
return self.getMetaClass().finvoke(context, self, name, arg0, arg1);
}
public static IRubyObject invoke(ThreadContext context, IRubyObject self, String name, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2) {
return self.getMetaClass().finvoke(context, self, name, arg0, arg1, arg2);
}
public static IRubyObject invoke(ThreadContext context, IRubyObject self, String name, IRubyObject... args) {
return self.getMetaClass().finvoke(context, self, name, args);
}
public static IRubyObject invokeAs(ThreadContext context, RubyClass asClass, IRubyObject self, String name, IRubyObject[] args, Block block) {
return asClass.finvoke(context, self, name, args, block);
}
public static IRubyObject invokeAs(ThreadContext context, RubyClass asClass, IRubyObject self, String name, Block block) {
return asClass.finvoke(context, self, name, block);
}
public static IRubyObject invokeAs(ThreadContext context, RubyClass asClass, IRubyObject self, String name, IRubyObject arg0, Block block) {
return asClass.finvoke(context, self, name, arg0, block);
}
public static IRubyObject invokeAs(ThreadContext context, RubyClass asClass, IRubyObject self, String name, IRubyObject arg0, IRubyObject arg1, Block block) {
return asClass.finvoke(context, self, name, arg0, arg1, block);
}
public static IRubyObject invokeAs(ThreadContext context, RubyClass asClass, IRubyObject self, String name, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, Block block) {
return asClass.finvoke(context, self, name, arg0, arg1, arg2, block);
}
/**
* MRI: rb_funcallv_public
*/
public static IRubyObject invokePublic(ThreadContext context, IRubyObject self, String name, IRubyObject arg) {
return getMetaClass(self).invokePublic(context, self, name, arg);
}
// MRI: rb_check_funcall
public static IRubyObject invokeChecked(ThreadContext context, IRubyObject self, String name) {
return getMetaClass(self).finvokeChecked(context, self, name);
}
// MRI: rb_check_funcall
public static IRubyObject invokeChecked(ThreadContext context, IRubyObject self, JavaSites.CheckedSites sites) {
return getMetaClass(self).finvokeChecked(context, self, sites);
}
// MRI: rb_check_funcall
public static IRubyObject invokeChecked(ThreadContext context, IRubyObject self, String name, IRubyObject... args) {
return getMetaClass(self).finvokeChecked(context, self, name, args);
}
// MRI: rb_check_funcall
public static IRubyObject invokeChecked(ThreadContext context, IRubyObject self, JavaSites.CheckedSites sites, IRubyObject arg0) {
return getMetaClass(self).finvokeChecked(context, self, sites, arg0);
}
// MRI: rb_check_funcall
public static IRubyObject invokeChecked(ThreadContext context, IRubyObject self, JavaSites.CheckedSites sites, IRubyObject... args) {
return getMetaClass(self).finvokeChecked(context, self, sites, args);
}
/**
* The protocol for super method invocation is a bit complicated
* in Ruby. In real terms it involves first finding the real
* implementation class (the super class), getting the name of the
* method to call from the frame, and then invoke that on the
* super class with the current self as the actual object
* invoking.
*/
public static IRubyObject invokeSuper(ThreadContext context, IRubyObject self, IRubyObject[] args, Block block) {
return invokeSuper(context, self, context.getFrameKlazz(), context.getFrameName(), args, block);
}
public static IRubyObject invokeSuper(ThreadContext context, IRubyObject self, RubyModule klass, String name, IRubyObject[] args, Block block) {
checkSuperDisabledOrOutOfMethod(context, klass, name);
RubyClass selfClass = getMetaClass(self);
RubyClass superClass = klass.getSuperClass();
CacheEntry entry = superClass != null ? superClass.searchWithCache(name) : CacheEntry.NULL_CACHE;
DynamicMethod method = entry.method;
if (method.isUndefined()) {
return callMethodMissing(context, self, selfClass, method.getVisibility(), name, CallType.SUPER, args, block);
}
return method.call(context, self, entry.sourceModule, name, args, block);
}
public static IRubyObject invokeSuper(ThreadContext context, IRubyObject self, RubyModule klass, String name, IRubyObject arg0, Block block) {
checkSuperDisabledOrOutOfMethod(context, klass, name);
RubyClass selfClass = getMetaClass(self);
RubyClass superClass = klass.getSuperClass();
CacheEntry entry = superClass != null ? superClass.searchWithCache(name) : CacheEntry.NULL_CACHE;
DynamicMethod method = entry.method;
if (method.isUndefined()) {
return callMethodMissing(context, self, selfClass, method.getVisibility(), name, CallType.SUPER, arg0, block);
}
return method.call(context, self, entry.sourceModule, name, arg0, block);
}
public static IRubyObject invokeSuper(ThreadContext context, IRubyObject self, Block block) {
checkSuperDisabledOrOutOfMethod(context);
RubyModule klazz = context.getFrameKlazz();
String name = context.getFrameName();
RubyClass selfClass = getMetaClass(self);
RubyClass superClass = klazz.getSuperClass();
CacheEntry entry = superClass != null ? superClass.searchWithCache(name) : CacheEntry.NULL_CACHE;
DynamicMethod method = entry.method;
if (method.isUndefined()) {
return callMethodMissing(context, self, selfClass, method.getVisibility(), name, CallType.SUPER, block);
}
return method.call(context, self, entry.sourceModule, name, block);
}
public static IRubyObject invokeSuper(ThreadContext context, IRubyObject self, IRubyObject arg0, Block block) {
checkSuperDisabledOrOutOfMethod(context);
RubyModule klazz = context.getFrameKlazz();
String name = context.getFrameName();
RubyClass selfClass = getMetaClass(self);
RubyClass superClass = klazz.getSuperClass();
CacheEntry entry = superClass != null ? superClass.searchWithCache(name) : CacheEntry.NULL_CACHE;
DynamicMethod method = entry.method;
if (method.isUndefined()) {
return callMethodMissing(context, self, selfClass, method.getVisibility(), name, CallType.SUPER, arg0, block);
}
return method.call(context, self, entry.sourceModule, name, arg0, block);
}
public static IRubyObject invokeSuper(ThreadContext context, IRubyObject self, IRubyObject arg0, IRubyObject arg1, Block block) {
checkSuperDisabledOrOutOfMethod(context);
RubyModule klazz = context.getFrameKlazz();
String name = context.getFrameName();
RubyClass selfClass = getMetaClass(self);
RubyClass superClass = klazz.getSuperClass();
CacheEntry entry = superClass != null ? superClass.searchWithCache(name) : CacheEntry.NULL_CACHE;
DynamicMethod method = entry.method;
if (method.isUndefined()) {
return callMethodMissing(context, self, selfClass, method.getVisibility(), name, CallType.SUPER, arg0, arg1, block);
}
return method.call(context, self, entry.sourceModule, name, arg0, arg1, block);
}
public static IRubyObject invokeSuper(ThreadContext context, IRubyObject self, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, Block block) {
checkSuperDisabledOrOutOfMethod(context);
RubyModule klazz = context.getFrameKlazz();
String name = context.getFrameName();
RubyClass selfClass = getMetaClass(self);
RubyClass superClass = klazz.getSuperClass();
CacheEntry entry = superClass != null ? superClass.searchWithCache(name) : CacheEntry.NULL_CACHE;
DynamicMethod method = entry.method;
if (method.isUndefined()) {
return callMethodMissing(context, self, selfClass, method.getVisibility(), name, CallType.SUPER, arg0, arg1, arg2, block);
}
return method.call(context, self, entry.sourceModule, name, arg0, arg1, arg2, block);
}
@Deprecated
public static RubyArray ensureRubyArray(IRubyObject value) {
return ensureRubyArray(value.getRuntime(), value);
}
public static RubyArray ensureRubyArray(Ruby runtime, IRubyObject value) {
return value instanceof RubyArray ? (RubyArray)value : RubyArray.newArray(runtime, value);
}
@Deprecated // not used
public static IRubyObject nullToNil(IRubyObject value, ThreadContext context) {
return value != null ? value : context.nil;
}
@Deprecated // not used
public static IRubyObject nullToNil(IRubyObject value, Ruby runtime) {
return value != null ? value : runtime.getNil();
}
/**
* @see Ruby#getNullToNilHandle()
*/
public static IRubyObject nullToNil(IRubyObject value, IRubyObject nil) {
return value != null ? value : nil;
}
public static void handleArgumentSizes(ThreadContext context, Ruby runtime, int given, int required, int opt, int rest) {
if (opt == 0) {
if (rest < 0) {
// no opt, no rest, exact match
if (given != required) {
throw runtime.newArgumentError(given, required);
}
} else {
// only rest, must be at least required
if (given < required) {
throw runtime.newArgumentError(given, required);
}
}
} else {
if (rest < 0) {
// opt but no rest, must be at least required and no more than required + opt
if (given < required) {
throw runtime.newArgumentError(given, required);
} else if (given > (required + opt)) {
throw runtime.newArgumentError(given, required + opt);
}
} else {
// opt and rest, must be at least required
if (given < required) {
throw runtime.newArgumentError(given, required);
}
}
}
}
public static String getLocalJumpTypeOrRethrow(RaiseException re) {
RubyException exception = re.getException();
Ruby runtime = exception.getRuntime();
if (runtime.getLocalJumpError().isInstance(exception)) {
RubyLocalJumpError jumpError = (RubyLocalJumpError)re.getException();
IRubyObject reason = jumpError.reason();
return reason.asJavaString();
}
throw re;
}
public static IRubyObject unwrapLocalJumpErrorValue(RaiseException re) {
return ((RubyLocalJumpError)re.getException()).exit_value();
}
public static Block getBlockFromBlockPassBody(Ruby runtime, IRubyObject proc, Block currentBlock) {
// No block from a nil proc
if (proc.isNil()) return Block.NULL_BLOCK;
// If not already a proc then we should try and make it one.
if (!(proc instanceof RubyProc)) {
proc = coerceProc(proc, runtime);
}
return getBlockFromProc(currentBlock, proc);
}
private static IRubyObject coerceProc(IRubyObject maybeProc, Ruby runtime) throws RaiseException {
IRubyObject proc = TypeConverter.convertToType(maybeProc, runtime.getProc(), "to_proc", false);
if (!(proc instanceof RubyProc)) {
throw runtime.newTypeError(str(runtime, "wrong argument type ", types(runtime, maybeProc.getMetaClass()), " (expected Proc)"));
}
return proc;
}
private static Block getBlockFromProc(Block currentBlock, IRubyObject proc) {
// TODO: Add safety check for taintedness
if (currentBlock != null && currentBlock.isGiven()) {
RubyProc procObject = currentBlock.getProcObject();
// The current block is already associated with proc. No need to create a new one
if (procObject != null && procObject == proc) {
return currentBlock;
}
}
return ((RubyProc) proc).getBlock();
}
public static Block getBlockFromBlockPassBody(IRubyObject proc, Block currentBlock) {
return getBlockFromBlockPassBody(proc.getRuntime(), proc, currentBlock);
}
public static IRubyObject backref(ThreadContext context) {
return RubyRegexp.getBackRef(context);
}
public static IRubyObject backrefLastMatch(ThreadContext context) {
IRubyObject backref = context.getBackRef();
return RubyRegexp.last_match(backref);
}
public static IRubyObject backrefMatchPre(ThreadContext context) {
IRubyObject backref = context.getBackRef();
return RubyRegexp.match_pre(backref);
}
public static IRubyObject backrefMatchPost(ThreadContext context) {
IRubyObject backref = context.getBackRef();
return RubyRegexp.match_post(backref);
}
public static IRubyObject backrefMatchLast(ThreadContext context) {
IRubyObject backref = context.getBackRef();
return RubyRegexp.match_last(backref);
}
public static IRubyObject[] appendToObjectArray(IRubyObject[] array, IRubyObject add) {
return ArraySupport.newCopy(array, add);
}
public static IRubyObject breakLocalJumpError(Ruby runtime, IRubyObject value) {
throw runtime.newLocalJumpError(RubyLocalJumpError.Reason.BREAK, value, "unexpected break");
}
public static IRubyObject[] concatObjectArrays(IRubyObject[] array, IRubyObject[] add) {
return toArray(array, add);
}
public static IRubyObject[] toArray(IRubyObject[] array, IRubyObject... rest) {
final int len = array.length;
IRubyObject[] newArray = new IRubyObject[len + rest.length];
ArraySupport.copy(array, newArray, 0, len);
ArraySupport.copy(rest, newArray, len, rest.length);
return newArray;
}
public static IRubyObject[] toArray(IRubyObject obj, IRubyObject... rest) {
return ArraySupport.newCopy(obj, rest);
}
public static IRubyObject[] toArray(IRubyObject obj0, IRubyObject obj1, IRubyObject... rest) {
IRubyObject[] newArray = new IRubyObject[2 + rest.length];
newArray[0] = obj0;
newArray[1] = obj1;
ArraySupport.copy(rest, newArray, 2, rest.length);
return newArray;
}
public static IRubyObject[] toArray(IRubyObject obj0, IRubyObject obj1, IRubyObject obj2, IRubyObject... rest) {
IRubyObject[] newArray = new IRubyObject[3 + rest.length];
newArray[0] = obj0;
newArray[1] = obj1;
newArray[2] = obj2;
ArraySupport.copy(rest, newArray, 3, rest.length);
return newArray;
}
public static IRubyObject isExceptionHandled(RubyException currentException, IRubyObject[] exceptions, ThreadContext context) {
for (int i = 0; i < exceptions.length; i++) {
IRubyObject result = isExceptionHandled(currentException, exceptions[i], context);
if (result.isTrue()) return result;
}
return context.fals;
}
public static IRubyObject isExceptionHandled(RubyException currentException, IRubyObject exception, ThreadContext context) {
return isExceptionHandled((IRubyObject) currentException, exception, context);
}
public static IRubyObject isExceptionHandled(IRubyObject currentException, IRubyObject exception, ThreadContext context) {
Ruby runtime = context.runtime;
if (!runtime.getModule().isInstance(exception)) {
throw runtime.newTypeError("class or module required for rescue clause");
}
IRubyObject result = invoke(context, exception, "===", currentException);
if (result.isTrue()) return result;
return runtime.getFalse();
}
public static IRubyObject isExceptionHandled(RubyException currentException, IRubyObject exception0, IRubyObject exception1, ThreadContext context) {
IRubyObject result = isExceptionHandled(currentException, exception0, context);
if (result.isTrue()) return result;
return isExceptionHandled(currentException, exception1, context);
}
public static IRubyObject isExceptionHandled(RubyException currentException, IRubyObject exception0, IRubyObject exception1, IRubyObject exception2, ThreadContext context) {
IRubyObject result = isExceptionHandled(currentException, exception0, context);
if (result.isTrue()) return result;
return isExceptionHandled(currentException, exception1, exception2, context);
}
public static boolean checkJavaException(final IRubyObject wrappedEx, final Throwable ex, IRubyObject catchable, ThreadContext context) {
final Ruby runtime = context.runtime;
if (
// rescue exception needs to catch Java exceptions
runtime.getException() == catchable ||
// rescue Object needs to catch Java exceptions
runtime.getObject() == catchable ||
// rescue StandardError needs to catch Java exceptions
runtime.getStandardError() == catchable) {
if (ex instanceof RaiseException) {
return isExceptionHandled(((RaiseException) ex).getException(), catchable, context).isTrue();
}
// let Ruby exceptions decide if they handle it
return isExceptionHandled(wrappedEx, catchable, context).isTrue();
}
if (runtime.getNativeException() == catchable) {
// NativeException catches Java exceptions, lazily creating the wrapper
return true;
}
if (catchable instanceof RubyClass && JavaClass.isProxyType(context, (RubyClass) catchable)) {
if ( ex instanceof InternalJavaProxy ) { // Ruby sub-class of a Java exception type
final IRubyObject target = ((InternalJavaProxy) ex).___getInvocationHandler().getOrig();
if ( target != null ) return ((RubyClass) catchable).isInstance(target);
}
return ((RubyClass) catchable).isInstance(wrappedEx);
}
if (catchable instanceof RubyModule) {
IRubyObject result = invoke(context, catchable, "===", wrappedEx);
return result.isTrue();
}
return false;
}
public static boolean checkJavaException(final Throwable ex, IRubyObject catchable, ThreadContext context) {
return checkJavaException(wrapJavaException(context.runtime, ex), ex, catchable, context);
}
// wrapJavaException(runtime, ex)
public static IRubyObject wrapJavaException(final Ruby runtime, final Throwable ex) {
return JavaUtil.convertJavaToUsableRubyObject(runtime, ex);
}
@Deprecated // due deprecated checkJavaException
public static IRubyObject isJavaExceptionHandled(Throwable currentThrowable, IRubyObject[] throwables, ThreadContext context) {
if (currentThrowable instanceof Unrescuable) {
throwException(currentThrowable);
}
if (currentThrowable instanceof RaiseException) {
return isExceptionHandled(((RaiseException) currentThrowable).getException(), throwables, context);
} else {
if (throwables.length == 0) {
// no rescue means StandardError, which rescues Java exceptions
return context.tru;
} else {
for (int i = 0; i < throwables.length; i++) {
if (checkJavaException(currentThrowable, throwables[i], context)) {
return context.tru;
}
}
}
return context.fals;
}
}
@Deprecated // due deprecated checkJavaException
public static IRubyObject isJavaExceptionHandled(Throwable currentThrowable, IRubyObject throwable, ThreadContext context) {
if (currentThrowable instanceof Unrescuable) {
throwException(currentThrowable);
}
if (currentThrowable instanceof RaiseException) {
return isExceptionHandled(((RaiseException) currentThrowable).getException(), throwable, context);
} else {
if (checkJavaException(currentThrowable, throwable, context)) {
return context.tru;
}
return context.fals;
}
}
@Deprecated // due deprecated checkJavaException
public static IRubyObject isJavaExceptionHandled(Throwable currentThrowable, IRubyObject throwable0, IRubyObject throwable1, ThreadContext context) {
if (currentThrowable instanceof Unrescuable) {
throwException(currentThrowable);
}
if (currentThrowable instanceof RaiseException) {
return isExceptionHandled(((RaiseException)currentThrowable).getException(), throwable0, throwable1, context);
} else {
if (checkJavaException(currentThrowable, throwable0, context)) {
return context.tru;
}
if (checkJavaException(currentThrowable, throwable1, context)) {
return context.tru;
}
return context.fals;
}
}
@Deprecated // due deprecated checkJavaException
public static IRubyObject isJavaExceptionHandled(Throwable currentThrowable, IRubyObject throwable0, IRubyObject throwable1, IRubyObject throwable2, ThreadContext context) {
if (currentThrowable instanceof Unrescuable) {
throwException(currentThrowable);
}
if (currentThrowable instanceof RaiseException) {
return isExceptionHandled(((RaiseException)currentThrowable).getException(), throwable0, throwable1, throwable2, context);
} else {
if (checkJavaException(currentThrowable, throwable0, context)) {
return context.tru;
}
if (checkJavaException(currentThrowable, throwable1, context)) {
return context.tru;
}
if (checkJavaException(currentThrowable, throwable2, context)) {
return context.tru;
}
return context.fals;
}
}
@Deprecated
public static void storeExceptionInErrorInfo(Throwable currentThrowable, ThreadContext context) {
IRubyObject exception;
if (currentThrowable instanceof RaiseException) {
exception = ((RaiseException)currentThrowable).getException();
} else {
exception = JavaUtil.convertJavaToUsableRubyObject(context.runtime, currentThrowable);
}
context.setErrorInfo(exception);
}
public static void clearErrorInfo(ThreadContext context) {
context.setErrorInfo(context.nil);
}
public static void checkSuperDisabledOrOutOfMethod(ThreadContext context) {
checkSuperDisabledOrOutOfMethod(context, context.getFrameKlazz(), context.getFrameName());
}
public static void checkSuperDisabledOrOutOfMethod(ThreadContext context, RubyModule klass, String name) {
if (klass == null) {
if (name != null) {
Ruby runtime = context.runtime;
throw runtime.newNameError(str(runtime, "superclass method '", ids(runtime, name), "' disabled"), name);
}
}
if (name == null) {
throw context.runtime.newNoMethodError("super called outside of method", null, context.nil);
}
}
public static RubyModule findImplementerIfNecessary(RubyModule clazz, RubyModule implementationClass) {
if (implementationClass.needsImplementer()) {
// modules are included with a shim class; we must find that shim to handle super() appropriately
return clazz.findImplementer(implementationClass);
} else {
// method is directly in a class, so just ensure we don't use any prepends
return implementationClass.getMethodLocation();
}
}
public static RubyArray createSubarray(RubyArray input, int start) {
return (RubyArray)input.subseqLight(start, input.size() - start);
}
public static RubyArray createSubarray(RubyArray input, int start, int post) {
return (RubyArray)input.subseqLight(start, input.size() - post - start);
}
public static RubyArray createSubarray(IRubyObject[] input, Ruby runtime, int start) {
if (start >= input.length) {
return RubyArray.newEmptyArray(runtime);
} else {
return RubyArray.newArrayMayCopy(runtime, input, start);
}
}
public static RubyArray createSubarray(IRubyObject[] input, Ruby runtime, int start, int exclude) {
int length = input.length - exclude - start;
if (length <= 0) {
return RubyArray.newEmptyArray(runtime);
} else {
return RubyArray.newArrayMayCopy(runtime, input, start, length);
}
}
public static IRubyObject elementOrNull(IRubyObject[] input, int element) {
if (element >= input.length) {
return null;
} else {
return input[element];
}
}
public static IRubyObject optElementOrNull(IRubyObject[] input, int element, int postCount) {
if (element + postCount >= input.length) {
return null;
} else {
return input[element];
}
}
public static IRubyObject elementOrNil(IRubyObject[] input, int element, IRubyObject nil) {
if (element >= input.length) {
return nil;
} else {
return input[element];
}
}
public static IRubyObject setConstantInModule(ThreadContext context, String name, IRubyObject value, IRubyObject module) {
if (!(module instanceof RubyModule)) {
throw context.runtime.newTypeError(str(context.runtime, ids(context.runtime, module), " is not a class/module"));
}
((RubyModule) module).setConstant(name, value);
return value;
}
public static final int MAX_SPECIFIC_ARITY_OBJECT_ARRAY = 10;
public static IRubyObject[] anewarrayIRubyObjects(int size) {
return new IRubyObject[size];
}
public static IRubyObject[] aastoreIRubyObjects(IRubyObject[] ary, IRubyObject one, int start) {
ary[start] = one;
return ary;
}
public static IRubyObject[] aastoreIRubyObjects(IRubyObject[] ary, IRubyObject one, IRubyObject two, int start) {
ary[start] = one;
ary[start+1] = two;
return ary;
}
public static IRubyObject[] aastoreIRubyObjects(IRubyObject[] ary, IRubyObject one, IRubyObject two, IRubyObject three, int start) {
ary[start] = one;
ary[start+1] = two;
ary[start+2] = three;
return ary;
}
public static IRubyObject[] aastoreIRubyObjects(IRubyObject[] ary, IRubyObject one, IRubyObject two, IRubyObject three, IRubyObject four, int start) {
ary[start] = one;
ary[start+1] = two;
ary[start+2] = three;
ary[start+3] = four;
return ary;
}
public static IRubyObject[] aastoreIRubyObjects(IRubyObject[] ary, IRubyObject one, IRubyObject two, IRubyObject three, IRubyObject four, IRubyObject five, int start) {
ary[start] = one;
ary[start+1] = two;
ary[start+2] = three;
ary[start+3] = four;
ary[start+4] = five;
return ary;
}
public static IRubyObject[] aastoreIRubyObjects(IRubyObject[] ary, IRubyObject one, IRubyObject two, IRubyObject three, IRubyObject four, IRubyObject five, IRubyObject six, int start) {
ary[start] = one;
ary[start+1] = two;
ary[start+2] = three;
ary[start+3] = four;
ary[start+4] = five;
ary[start+5] = six;
return ary;
}
public static IRubyObject[] aastoreIRubyObjects(IRubyObject[] ary, IRubyObject one, IRubyObject two, IRubyObject three, IRubyObject four, IRubyObject five, IRubyObject six, IRubyObject seven, int start) {
ary[start] = one;
ary[start+1] = two;
ary[start+2] = three;
ary[start+3] = four;
ary[start+4] = five;
ary[start+5] = six;
ary[start+6] = seven;
return ary;
}
public static IRubyObject[] aastoreIRubyObjects(IRubyObject[] ary, IRubyObject one, IRubyObject two, IRubyObject three, IRubyObject four, IRubyObject five, IRubyObject six, IRubyObject seven, IRubyObject eight, int start) {
ary[start] = one;
ary[start+1] = two;
ary[start+2] = three;
ary[start+3] = four;
ary[start+4] = five;
ary[start+5] = six;
ary[start+6] = seven;
ary[start+7] = eight;
return ary;
}
public static IRubyObject[] aastoreIRubyObjects(IRubyObject[] ary, IRubyObject one, IRubyObject two, IRubyObject three, IRubyObject four, IRubyObject five, IRubyObject six, IRubyObject seven, IRubyObject eight, IRubyObject nine, int start) {
ary[start] = one;
ary[start+1] = two;
ary[start+2] = three;
ary[start+3] = four;
ary[start+4] = five;
ary[start+5] = six;
ary[start+6] = seven;
ary[start+7] = eight;
ary[start+8] = nine;
return ary;
}
public static IRubyObject[] aastoreIRubyObjects(IRubyObject[] ary, IRubyObject one, IRubyObject two, IRubyObject three, IRubyObject four, IRubyObject five, IRubyObject six, IRubyObject seven, IRubyObject eight, IRubyObject nine, IRubyObject ten, int start) {
ary[start] = one;
ary[start+1] = two;
ary[start+2] = three;
ary[start+3] = four;
ary[start+4] = five;
ary[start+5] = six;
ary[start+6] = seven;
ary[start+7] = eight;
ary[start+8] = nine;
ary[start+9] = ten;
return ary;
}
public static IRubyObject[] constructObjectArray(IRubyObject one) {
return new IRubyObject[] {one};
}
public static IRubyObject[] constructObjectArray(IRubyObject one, IRubyObject two) {
return new IRubyObject[] {one, two};
}
public static IRubyObject[] constructObjectArray(IRubyObject one, IRubyObject two, IRubyObject three) {
return new IRubyObject[] {one, two, three};
}
public static IRubyObject[] constructObjectArray(IRubyObject one, IRubyObject two, IRubyObject three, IRubyObject four) {
return new IRubyObject[] {one, two, three, four};
}
public static IRubyObject[] constructObjectArray(IRubyObject one, IRubyObject two, IRubyObject three, IRubyObject four, IRubyObject five) {
return new IRubyObject[] {one, two, three, four, five};
}
public static IRubyObject[] constructObjectArray(IRubyObject one, IRubyObject two, IRubyObject three, IRubyObject four, IRubyObject five, IRubyObject six) {
return new IRubyObject[] {one, two, three, four, five, six};
}
public static IRubyObject[] constructObjectArray(IRubyObject one, IRubyObject two, IRubyObject three, IRubyObject four, IRubyObject five, IRubyObject six, IRubyObject seven) {
return new IRubyObject[] {one, two, three, four, five, six, seven};
}
public static IRubyObject[] constructObjectArray(IRubyObject one, IRubyObject two, IRubyObject three, IRubyObject four, IRubyObject five, IRubyObject six, IRubyObject seven, IRubyObject eight) {
return new IRubyObject[] {one, two, three, four, five, six, seven, eight};
}
public static IRubyObject[] constructObjectArray(IRubyObject one, IRubyObject two, IRubyObject three, IRubyObject four, IRubyObject five, IRubyObject six, IRubyObject seven, IRubyObject eight, IRubyObject nine) {
return new IRubyObject[] {one, two, three, four, five, six, seven, eight, nine};
}
public static IRubyObject[] constructObjectArray(IRubyObject one, IRubyObject two, IRubyObject three, IRubyObject four, IRubyObject five, IRubyObject six, IRubyObject seven, IRubyObject eight, IRubyObject nine, IRubyObject ten) {
return new IRubyObject[] {one, two, three, four, five, six, seven, eight, nine, ten};
}
public static RubyArray constructRubyArray(Ruby runtime, IRubyObject one) {
return RubyArray.newArrayLight(runtime, one);
}
public static RubyArray constructRubyArray(Ruby runtime, IRubyObject one, IRubyObject two) {
return RubyArray.newArrayLight(runtime, one, two);
}
public static RubyArray constructRubyArray(Ruby runtime, IRubyObject one, IRubyObject two, IRubyObject three) {
return RubyArray.newArrayLight(runtime, one, two, three);
}
public static RubyArray constructRubyArray(Ruby runtime, IRubyObject one, IRubyObject two, IRubyObject three, IRubyObject four) {
return RubyArray.newArrayLight(runtime, one, two, three, four);
}
public static RubyArray constructRubyArray(Ruby runtime, IRubyObject one, IRubyObject two, IRubyObject three, IRubyObject four, IRubyObject five) {
return RubyArray.newArrayLight(runtime, one, two, three, four, five);
}
public static RubyArray constructRubyArray(Ruby runtime, IRubyObject one, IRubyObject two, IRubyObject three, IRubyObject four, IRubyObject five, IRubyObject six) {
return RubyArray.newArrayLight(runtime, one, two, three, four, five, six);
}
public static RubyArray constructRubyArray(Ruby runtime, IRubyObject one, IRubyObject two, IRubyObject three, IRubyObject four, IRubyObject five, IRubyObject six, IRubyObject seven) {
return RubyArray.newArrayLight(runtime, one, two, three, four, five, six, seven);
}
public static RubyArray constructRubyArray(Ruby runtime, IRubyObject one, IRubyObject two, IRubyObject three, IRubyObject four, IRubyObject five, IRubyObject six, IRubyObject seven, IRubyObject eight) {
return RubyArray.newArrayLight(runtime, one, two, three, four, five, six, seven, eight);
}
public static RubyArray constructRubyArray(Ruby runtime, IRubyObject one, IRubyObject two, IRubyObject three, IRubyObject four, IRubyObject five, IRubyObject six, IRubyObject seven, IRubyObject eight, IRubyObject nine) {
return RubyArray.newArrayLight(runtime, one, two, three, four, five, six, seven, eight, nine);
}
public static RubyArray constructRubyArray(Ruby runtime, IRubyObject one, IRubyObject two, IRubyObject three, IRubyObject four, IRubyObject five, IRubyObject six, IRubyObject seven, IRubyObject eight, IRubyObject nine, IRubyObject ten) {
return RubyArray.newArrayLight(runtime, one, two, three, four, five, six, seven, eight, nine, ten);
}
public static String[] constructStringArray(String one) {
return new String[] {one};
}
public static String[] constructStringArray(String one, String two) {
return new String[] {one, two};
}
public static String[] constructStringArray(String one, String two, String three) {
return new String[] {one, two, three};
}
public static String[] constructStringArray(String one, String two, String three, String four) {
return new String[] {one, two, three, four};
}
public static String[] constructStringArray(String one, String two, String three, String four, String five) {
return new String[] {one, two, three, four, five};
}
public static String[] constructStringArray(String one, String two, String three, String four, String five, String six) {
return new String[] {one, two, three, four, five, six};
}
public static String[] constructStringArray(String one, String two, String three, String four, String five, String six, String seven) {
return new String[] {one, two, three, four, five, six, seven};
}
public static String[] constructStringArray(String one, String two, String three, String four, String five, String six, String seven, String eight) {
return new String[] {one, two, three, four, five, six, seven, eight};
}
public static String[] constructStringArray(String one, String two, String three, String four, String five, String six, String seven, String eight, String nine) {
return new String[] {one, two, three, four, five, six, seven, eight, nine};
}
public static String[] constructStringArray(String one, String two, String three, String four, String five, String six, String seven, String eight, String nine, String ten) {
return new String[] {one, two, three, four, five, six, seven, eight, nine, ten};
}
public static final int MAX_SPECIFIC_ARITY_HASH = 5;
public static RubyHash constructHash(Ruby runtime,
IRubyObject key1, IRubyObject value1, boolean prepareString1) {
RubyHash hash = RubyHash.newHash(runtime);
hash.fastASet(runtime, key1, value1, prepareString1);
return hash;
}
public static RubyHash constructHash(Ruby runtime,
IRubyObject key1, IRubyObject value1, boolean prepareString1,
IRubyObject key2, IRubyObject value2, boolean prepareString2) {
RubyHash hash = RubyHash.newHash(runtime);
hash.fastASet(runtime, key1, value1, prepareString1);
hash.fastASet(runtime, key2, value2, prepareString2);
return hash;
}
public static RubyHash constructHash(Ruby runtime,
IRubyObject key1, IRubyObject value1, boolean prepareString1,
IRubyObject key2, IRubyObject value2, boolean prepareString2,
IRubyObject key3, IRubyObject value3, boolean prepareString3) {
RubyHash hash = RubyHash.newHash(runtime);
hash.fastASet(runtime, key1, value1, prepareString1);
hash.fastASet(runtime, key2, value2, prepareString2);
hash.fastASet(runtime, key3, value3, prepareString3);
return hash;
}
public static RubyHash constructHash(Ruby runtime,
IRubyObject key1, IRubyObject value1, boolean prepareString1,
IRubyObject key2, IRubyObject value2, boolean prepareString2,
IRubyObject key3, IRubyObject value3, boolean prepareString3,
IRubyObject key4, IRubyObject value4, boolean prepareString4) {
RubyHash hash = RubyHash.newHash(runtime);
hash.fastASet(runtime, key1, value1, prepareString1);
hash.fastASet(runtime, key2, value2, prepareString2);
hash.fastASet(runtime, key3, value3, prepareString3);
hash.fastASet(runtime, key4, value4, prepareString4);
return hash;
}
public static RubyHash constructHash(Ruby runtime,
IRubyObject key1, IRubyObject value1, boolean prepareString1,
IRubyObject key2, IRubyObject value2, boolean prepareString2,
IRubyObject key3, IRubyObject value3, boolean prepareString3,
IRubyObject key4, IRubyObject value4, boolean prepareString4,
IRubyObject key5, IRubyObject value5, boolean prepareString5) {
RubyHash hash = RubyHash.newHash(runtime);
hash.fastASet(runtime, key1, value1, prepareString1);
hash.fastASet(runtime, key2, value2, prepareString2);
hash.fastASet(runtime, key3, value3, prepareString3);
hash.fastASet(runtime, key4, value4, prepareString4);
hash.fastASet(runtime, key5, value5, prepareString5);
return hash;
}
public static RubyHash constructSmallHash(Ruby runtime,
IRubyObject key1, IRubyObject value1, boolean prepareString1) {
RubyHash hash = RubyHash.newSmallHash(runtime);
hash.fastASetSmall(runtime, key1, value1, prepareString1);
return hash;
}
public static RubyHash constructSmallHash(Ruby runtime,
IRubyObject key1, IRubyObject value1, boolean prepareString1,
IRubyObject key2, IRubyObject value2, boolean prepareString2) {
RubyHash hash = RubyHash.newSmallHash(runtime);
hash.fastASetSmall(runtime, key1, value1, prepareString1);
hash.fastASetSmall(runtime, key2, value2, prepareString2);
return hash;
}
public static RubyHash constructSmallHash(Ruby runtime,
IRubyObject key1, IRubyObject value1, boolean prepareString1,
IRubyObject key2, IRubyObject value2, boolean prepareString2,
IRubyObject key3, IRubyObject value3, boolean prepareString3) {
RubyHash hash = RubyHash.newSmallHash(runtime);
hash.fastASetSmall(runtime, key1, value1, prepareString1);
hash.fastASetSmall(runtime, key2, value2, prepareString2);
hash.fastASetSmall(runtime, key3, value3, prepareString3);
return hash;
}
public static RubyHash constructSmallHash(Ruby runtime,
IRubyObject key1, IRubyObject value1, boolean prepareString1,
IRubyObject key2, IRubyObject value2, boolean prepareString2,
IRubyObject key3, IRubyObject value3, boolean prepareString3,
IRubyObject key4, IRubyObject value4, boolean prepareString4) {
RubyHash hash = RubyHash.newSmallHash(runtime);
hash.fastASetSmall(runtime, key1, value1, prepareString1);
hash.fastASetSmall(runtime, key2, value2, prepareString2);
hash.fastASetSmall(runtime, key3, value3, prepareString3);
hash.fastASetSmall(runtime, key4, value4, prepareString4);
return hash;
}
public static RubyHash constructSmallHash(Ruby runtime,
IRubyObject key1, IRubyObject value1, boolean prepareString1,
IRubyObject key2, IRubyObject value2, boolean prepareString2,
IRubyObject key3, IRubyObject value3, boolean prepareString3,
IRubyObject key4, IRubyObject value4, boolean prepareString4,
IRubyObject key5, IRubyObject value5, boolean prepareString5) {
RubyHash hash = RubyHash.newSmallHash(runtime);
hash.fastASetSmall(runtime, key1, value1, prepareString1);
hash.fastASetSmall(runtime, key2, value2, prepareString2);
hash.fastASetSmall(runtime, key3, value3, prepareString3);
hash.fastASetSmall(runtime, key4, value4, prepareString4);
hash.fastASetSmall(runtime, key5, value5, prepareString5);
return hash;
}
public static IRubyObject negate(IRubyObject value, Ruby runtime) {
if (value.isTrue()) return runtime.getFalse();
return runtime.getTrue();
}
@Deprecated // no-longer used + confusing argument order
public static IRubyObject stringOrNil(ByteList value, ThreadContext context) {
if (value == null) return context.nil;
return RubyString.newStringShared(context.runtime, value);
}
@SuppressWarnings("deprecation")
public static StaticScope preLoad(ThreadContext context, String[] varNames) {
StaticScope staticScope = context.runtime.getStaticScopeFactory().newLocalScope(null, varNames);
preLoadCommon(context, staticScope, false);
return staticScope;
}
public static void preLoadCommon(ThreadContext context, StaticScope staticScope, boolean wrap) {
RubyModule objectClass = context.runtime.getObject();
if (wrap) {
objectClass = RubyModule.newModule(context.runtime);
}
staticScope.setModule(objectClass);
DynamicScope scope = DynamicScope.newDynamicScope(staticScope);
// Each root node has a top-level scope that we need to push
context.preScopedBody(scope);
context.preNodeEval(context.runtime.getTopSelf());
}
public static void postLoad(ThreadContext context) {
context.postNodeEval();
context.postScopedBody();
}
@Deprecated // not-used
public static void registerEndBlock(Block block, Ruby runtime) {
runtime.pushExitBlock(runtime.newProc(Block.Type.LAMBDA, block));
}
@Deprecated // not-used
public static IRubyObject match3(RubyRegexp regexp, IRubyObject value, ThreadContext context) {
if (value instanceof RubyString) {
return regexp.op_match(context, value);
} else {
return value.callMethod(context, "=~", regexp);
}
}
public static IRubyObject getErrorInfo(Ruby runtime) {
return runtime.getGlobalVariables().get("$!");
}
public static void setErrorInfo(Ruby runtime, IRubyObject error) {
runtime.getGlobalVariables().set("$!", error);
}
public static IRubyObject setLastLine(Ruby runtime, ThreadContext context, IRubyObject value) {
return context.setLastLine(value);
}
public static IRubyObject getLastLine(Ruby runtime, ThreadContext context) {
return context.getLastLine();
}
public static IRubyObject setBackref(Ruby runtime, ThreadContext context, IRubyObject value) {
if (!value.isNil() && !(value instanceof RubyMatchData)) throw runtime.newTypeError(value, runtime.getMatchData());
return context.setBackRef(value);
}
public static IRubyObject getBackref(Ruby runtime, ThreadContext context) {
return backref(context); // backref(context) method otherwise not used
}
public static RubyArray arrayValue(IRubyObject value) {
Ruby runtime = value.getRuntime();
return arrayValue(runtime.getCurrentContext(), runtime, value);
}
public static RubyArray arrayValue(ThreadContext context, Ruby runtime, IRubyObject value) {
IRubyObject tmp = value.checkArrayType();
if (tmp.isNil()) {
if (value.respondsTo("to_a")) {
IRubyObject avalue = value.callMethod(context, "to_a");
if (!(avalue instanceof RubyArray)) {
if (avalue.isNil()) {
return runtime.newArray(value);
} else {
throw runtime.newTypeError("`to_a' did not return Array");
}
}
return (RubyArray)avalue;
} else {
CacheEntry entry = value.getMetaClass().searchWithCache("method_missing");
DynamicMethod methodMissing = entry.method;
if (methodMissing.isUndefined() || runtime.isDefaultMethodMissing(methodMissing)) {
return runtime.newArray(value);
} else {
IRubyObject avalue = methodMissing.call(context, value, entry.sourceModule, "to_a", new IRubyObject[] {runtime.newSymbol("to_a")}, Block.NULL_BLOCK);
if (!(avalue instanceof RubyArray)) {
if (avalue.isNil()) {
return runtime.newArray(value);
} else {
throw runtime.newTypeError("`to_a' did not return Array");
}
}
return (RubyArray)avalue;
}
}
}
RubyArray arr = (RubyArray) tmp;
return arr.aryDup();
}
// mri: rb_Array
@Deprecated
public static RubyArray asArray(ThreadContext context, IRubyObject value) {
return TypeConverter.rb_Array(context, value);
}
@Deprecated // not used
public static IRubyObject aryToAry(IRubyObject value) {
return aryToAry(value.getRuntime().getCurrentContext(), value);
}
public static IRubyObject aryToAry(ThreadContext context, IRubyObject value) {
if (value instanceof RubyArray) return value;
if (value.respondsTo("to_ary")) {
return TypeConverter.convertToType(context, value, context.runtime.getArray(), "to_ary", false);
}
return context.runtime.newArray(value);
}
public static IRubyObject aryOrToAry(ThreadContext context, IRubyObject value) {
if (value instanceof RubyArray) return value;
if (value.respondsTo("to_ary")) {
return TypeConverter.convertToType(context, value, context.runtime.getArray(), "to_ary", false);
}
return context.nil;
}
@Deprecated // not used
public static IRubyObject aValueSplat(IRubyObject value) {
if (!(value instanceof RubyArray) || ((RubyArray) value).length().getLongValue() == 0) {
return value.getRuntime().getNil();
}
RubyArray array = (RubyArray) value;
return array.getLength() == 1 ? array.first() : array;
}
@Deprecated // not used
public static IRubyObject aValueSplat19(IRubyObject value) {
if (!(value instanceof RubyArray)) {
return value.getRuntime().getNil();
}
return (RubyArray) value;
}
@Deprecated // not used
public static RubyArray splatValue(IRubyObject value) {
if (value.isNil()) {
return value.getRuntime().newArray(value);
}
return arrayValue(value);
}
@Deprecated // not used
public static RubyArray splatValue19(IRubyObject value) {
if (value.isNil()) {
return value.getRuntime().newEmptyArray();
}
return arrayValue(value);
}
@Deprecated // not used
public static IRubyObject unsplatValue19(IRubyObject argsResult) {
if (argsResult instanceof RubyArray) {
RubyArray array = (RubyArray) argsResult;
if (array.size() == 1) {
IRubyObject newResult = array.eltInternal(0);
if (!((newResult instanceof RubyArray) && ((RubyArray) newResult).size() == 0)) {
argsResult = newResult;
}
}
}
return argsResult;
}
@Deprecated // no longer used
public static IRubyObject[] splatToArguments(IRubyObject value) {
if (value.isNil()) {
return value.getRuntime().getSingleNilArray();
}
IRubyObject tmp = value.checkArrayType();
if (tmp.isNil()) {
return convertSplatToJavaArray(value.getRuntime(), value);
}
return ((RubyArray)tmp).toJavaArrayMaybeUnsafe();
}
private static IRubyObject[] convertSplatToJavaArray(Ruby runtime, IRubyObject value) {
// Object#to_a is obsolete. We match Ruby's hack until to_a goes away. Then we can
// remove this hack too.
RubyClass metaClass = value.getMetaClass();
CacheEntry entry = metaClass.searchWithCache("to_a");
DynamicMethod method = entry.method;
if (method.isUndefined() || method.isImplementedBy(runtime.getKernel())) {
return new IRubyObject[] {value};
}
IRubyObject avalue = method.call(runtime.getCurrentContext(), value, entry.sourceModule, "to_a");
if (!(avalue instanceof RubyArray)) {
if (avalue.isNil()) {
return new IRubyObject[] {value};
} else {
throw runtime.newTypeError("`to_a' did not return Array");
}
}
return ((RubyArray)avalue).toJavaArray();
}
@SuppressWarnings("deprecation") @Deprecated // no longer used
public static IRubyObject[] argsCatToArguments(IRubyObject[] args, IRubyObject cat) {
IRubyObject[] ary = splatToArguments(cat);
if (ary.length > 0) {
IRubyObject[] newArgs = new IRubyObject[args.length + ary.length];
System.arraycopy(args, 0, newArgs, 0, args.length);
System.arraycopy(ary, 0, newArgs, args.length, ary.length);
return newArgs;
}
return args;
}
@Deprecated
public static RubySymbol addInstanceMethod(RubyModule containingClass, String name, DynamicMethod method, Visibility visibility, ThreadContext context, Ruby runtime) {
return addInstanceMethod(containingClass, runtime.fastNewSymbol(name), method, visibility, context, runtime);
}
public static RubySymbol addInstanceMethod(RubyModule containingClass, RubySymbol symbol, DynamicMethod method, Visibility visibility, ThreadContext context, Ruby runtime) {
containingClass.addMethod(symbol.idString(), method);
if (!containingClass.isRefinement()) callNormalMethodHook(containingClass, context, symbol);
if (visibility == Visibility.MODULE_FUNCTION) addModuleMethod(containingClass, method, context, symbol);
return symbol;
}
private static void addModuleMethod(RubyModule containingClass, DynamicMethod method, ThreadContext context, RubySymbol sym) {
DynamicMethod singletonMethod = method.dup();
singletonMethod.setImplementationClass(containingClass.getSingletonClass());
singletonMethod.setVisibility(Visibility.PUBLIC);
containingClass.getSingletonClass().addMethod(sym.idString(), singletonMethod);
containingClass.callMethod(context, "singleton_method_added", sym);
}
private static void callNormalMethodHook(RubyModule containingClass, ThreadContext context, RubySymbol name) {
// 'class << state.self' and 'class << obj' uses defn as opposed to defs
if (containingClass.isSingleton()) {
callSingletonMethodHook(((MetaClass) containingClass).getAttached(), context, name);
} else {
containingClass.callMethod(context, "method_added", name);
}
}
private static void callSingletonMethodHook(RubyBasicObject receiver, ThreadContext context, RubySymbol name) {
receiver.callMethod(context, "singleton_method_added", name);
}
@SuppressWarnings("deprecation")
static String encodeScope(StaticScope scope) {
StringBuilder namesBuilder = new StringBuilder(scope.getType().name()); // 0
namesBuilder.append(','); // 1
boolean first = true;
for (String name : scope.getVariables()) {
if (!first) namesBuilder.append(';');
first = false;
namesBuilder.append(name);
}
namesBuilder.append(',').append(scope.getSignature().encode()); // 2
namesBuilder.append(',').append(scope.getScopeType()); // 3
return namesBuilder.toString();
}
@SuppressWarnings("deprecation")
static StaticScope decodeScope(ThreadContext context, StaticScope parent, String scopeString) {
String[][] decodedScope = decodeScopeDescriptor(scopeString);
String scopeTypeName = decodedScope[0][0];
String[] names = decodedScope[1];
StaticScope scope = null;
switch (StaticScope.Type.valueOf(scopeTypeName)) {
case BLOCK:
scope = context.runtime.getStaticScopeFactory().newBlockScope(parent, names);
break;
case EVAL:
scope = context.runtime.getStaticScopeFactory().newEvalScope(parent, names);
break;
case LOCAL:
scope = context.runtime.getStaticScopeFactory().newLocalScope(parent, names);
break;
}
setAritiesFromDecodedScope(scope, decodedScope[0][2]);
scope.setScopeType(IRScopeType.valueOf(decodedScope[0][3]));
return scope;
}
private static String[][] decodeScopeDescriptor(String scopeString) {
String[] scopeElements = scopeString.split(",");
String[] scopeNames = scopeElements[1].length() == 0 ? EMPTY_STRING_ARRAY : getScopeNames(scopeElements[1]);
return new String[][] {scopeElements, scopeNames};
}
private static void setAritiesFromDecodedScope(StaticScope scope, String encodedSignature) {
scope.setSignature(Signature.decode(Long.parseLong(encodedSignature)));
}
public static StaticScope decodeScopeAndDetermineModule(ThreadContext context, StaticScope parent, String scopeString) {
StaticScope scope = decodeScope(context, parent, scopeString);
scope.determineModule();
return scope;
}
public static Visibility performNormalMethodChecksAndDetermineVisibility(Ruby runtime, RubyModule clazz,
RubySymbol symbol, Visibility visibility) throws RaiseException {
String name = symbol.asJavaString(); // We just assume simple ascii string since that is all we are examining.
if (clazz == runtime.getDummy()) {
throw runtime.newTypeError("no class/module to add method");
}
if (clazz == runtime.getObject() && "initialize".equals(name)) {
runtime.getWarnings().warn(ID.REDEFINING_DANGEROUS, "redefining Object#initialize may cause infinite loop");
}
if ("__id__".equals(name) || "__send__".equals(name)) {
runtime.getWarnings().warn(ID.REDEFINING_DANGEROUS, str(runtime, "redefining `", ids(runtime, symbol), "' may cause serious problem"));
}
if ("initialize".equals(name) || "initialize_copy".equals(name) || name.equals("initialize_dup") || name.equals("initialize_clone") || name.equals("respond_to_missing?") || visibility == Visibility.MODULE_FUNCTION) {
visibility = Visibility.PRIVATE;
}
return visibility;
}
public static RubyClass performSingletonMethodChecks(Ruby runtime, IRubyObject receiver, String name) throws RaiseException {
if (receiver instanceof RubyFixnum || receiver instanceof RubySymbol) {
throw runtime.newTypeError(str(runtime, "can't define singleton method \"", ids(runtime, name), "\" for ", types(runtime, receiver.getMetaClass())));
}
if (receiver.isFrozen()) {
throw runtime.newFrozenError("object");
}
RubyClass rubyClass = receiver.getSingletonClass();
return rubyClass;
}
@Deprecated // not used
public static IRubyObject arrayEntryOrNil(RubyArray array, int index) {
if (index < array.getLength()) {
return array.eltInternal(index);
} else {
return array.getRuntime().getNil();
}
}
@Deprecated // not used
public static IRubyObject arrayEntryOrNilZero(RubyArray array) {
if (0 < array.getLength()) {
return array.eltInternal(0);
} else {
return array.getRuntime().getNil();
}
}
@Deprecated // not used
public static IRubyObject arrayEntryOrNilOne(RubyArray array) {
if (1 < array.getLength()) {
return array.eltInternal(1);
} else {
return array.getRuntime().getNil();
}
}
@Deprecated // not used
public static IRubyObject arrayEntryOrNilTwo(RubyArray array) {
if (2 < array.getLength()) {
return array.eltInternal(2);
} else {
return array.getRuntime().getNil();
}
}
@Deprecated // not used
public static IRubyObject arrayPostOrNil(RubyArray array, int pre, int post, int index) {
if (pre + post < array.getLength()) {
return array.eltInternal(array.getLength() - post + index);
} else if (pre + index < array.getLength()) {
return array.eltInternal(pre + index);
} else {
return array.getRuntime().getNil();
}
}
@Deprecated // not used
public static IRubyObject arrayPostOrNilZero(RubyArray array, int pre, int post) {
if (pre + post < array.getLength()) {
return array.eltInternal(array.getLength() - post + 0);
} else if (pre + 0 < array.getLength()) {
return array.eltInternal(pre + 0);
} else {
return array.getRuntime().getNil();
}
}
@Deprecated // not used
public static IRubyObject arrayPostOrNilOne(RubyArray array, int pre, int post) {
if (pre + post < array.getLength()) {
return array.eltInternal(array.getLength() - post + 1);
} else if (pre + 1 < array.getLength()) {
return array.eltInternal(pre + 1);
} else {
return array.getRuntime().getNil();
}
}
@Deprecated // not used
public static IRubyObject arrayPostOrNilTwo(RubyArray array, int pre, int post) {
if (pre + post < array.getLength()) {
return array.eltInternal(array.getLength() - post + 2);
} else if (pre + 2 < array.getLength()) {
return array.eltInternal(pre + 2);
} else {
return array.getRuntime().getNil();
}
}
@Deprecated // not used
public static RubyArray subarrayOrEmpty(RubyArray array, Ruby runtime, int index) {
if (index < array.getLength()) {
return createSubarray(array, index);
} else {
return RubyArray.newEmptyArray(runtime);
}
}
@Deprecated // not used
public static RubyArray subarrayOrEmpty(RubyArray array, Ruby runtime, int index, int post) {
if (index + post < array.getLength()) {
return createSubarray(array, index, post);
} else {
return RubyArray.newEmptyArray(runtime);
}
}
public static RubyModule checkIsModule(IRubyObject maybeModule) {
if (maybeModule instanceof RubyModule) return (RubyModule)maybeModule;
Ruby runtime = maybeModule.getRuntime();
throw runtime.newTypeError(str(runtime, ids(runtime, maybeModule), " is not a class/module"));
}
public static IRubyObject getGlobalVariable(Ruby runtime, String name) {
return runtime.getGlobalVariables().get(name);
}
public static IRubyObject setGlobalVariable(IRubyObject value, Ruby runtime, String name) {
return runtime.getGlobalVariables().set(name, value);
}
public static IRubyObject getInstanceVariable(IRubyObject self, Ruby runtime, String internedName) {
IRubyObject result = self.getInstanceVariables().getInstanceVariable(internedName);
if (result != null) return result;
if (runtime.isVerbose()) warnAboutUninitializedIvar(runtime, internedName);
return runtime.getNil();
}
public static IRubyObject getInstanceVariableNoWarn(IRubyObject self, ThreadContext context, String internedName) {
IRubyObject result = self.getInstanceVariables().getInstanceVariable(internedName);
if (result != null) return result;
return context.nil;
}
private static void warnAboutUninitializedIvar(Ruby runtime, String id) {
runtime.getWarnings().warning(ID.IVAR_NOT_INITIALIZED, str(runtime, "instance variable ", ids(runtime, id), " not initialized"));
}
public static IRubyObject setInstanceVariable(IRubyObject value, IRubyObject self, String name) {
return self.getInstanceVariables().setInstanceVariable(name, value);
}
public static RubyProc newLiteralLambda(ThreadContext context, Block block, IRubyObject self) {
return RubyProc.newProc(context.runtime, block, Block.Type.LAMBDA);
}
public static void fillNil(final IRubyObject[] arr, int from, int to, Ruby runtime) {
if (arr.length == 0) return;
IRubyObject nils[] = runtime.getNilPrefilledArray();
int i;
// NOTE: seems that Arrays.fill(arr, runtime.getNil()) won't do better ... on Java 8
// Object[] array doesn't get the same optimizations as e.g. byte[] int[]
for (i = from; i + Ruby.NIL_PREFILLED_ARRAY_SIZE < to; i += Ruby.NIL_PREFILLED_ARRAY_SIZE) {
System.arraycopy(nils, 0, arr, i, Ruby.NIL_PREFILLED_ARRAY_SIZE);
}
ArraySupport.copy(nils, arr, i, to - i);
}
public static void fillNil(IRubyObject[] arr, Ruby runtime) {
fillNil(arr, 0, arr.length, runtime);
}
public static Block getBlock(ThreadContext context, IRubyObject self, Node node) {
throw new RuntimeException("Should not be called");
}
public static Block getBlock(Ruby runtime, ThreadContext context, IRubyObject self, Node node, Block aBlock) {
throw new RuntimeException("Should not be called");
}
/**
* Equivalent to rb_equal in MRI
*
* @param context
* @param a
* @param b
* @return
*/
public static RubyBoolean rbEqual(ThreadContext context, IRubyObject a, IRubyObject b) {
Ruby runtime = context.runtime;
if (a == b) return runtime.getTrue();
IRubyObject res = sites(context).op_equal.call(context, a, a, b);
return runtime.newBoolean(res.isTrue());
}
/**
* Equivalent to rb_equal in MRI
*
* @param context
* @param a
* @param b
* @return
*/
public static RubyBoolean rbEqual(ThreadContext context, IRubyObject a, IRubyObject b, CallSite equal) {
Ruby runtime = context.runtime;
if (a == b) return runtime.getTrue();
IRubyObject res = equal.call(context, a, a, b);
return runtime.newBoolean(res.isTrue());
}
/**
* Equivalent to rb_eql in MRI
*
* @param context
* @param a
* @param b
* @return
*/
public static RubyBoolean rbEql(ThreadContext context, IRubyObject a, IRubyObject b) {
Ruby runtime = context.runtime;
if (a == b) return runtime.getTrue();
IRubyObject res = invokedynamic(context, a, EQL, b);
return runtime.newBoolean(res.isTrue());
}
/**
* Used by the compiler to simplify arg checking in variable-arity paths
*
* @param context thread context
* @param args arguments array
* @param min minimum required
* @param max maximum allowed
*/
public static void checkArgumentCount(ThreadContext context, IRubyObject[] args, int min, int max) {
checkArgumentCount(context, args.length, min, max);
}
/**
* Used by the compiler to simplify arg checking in variable-arity paths
*
* @param context thread context
* @param args arguments array
* @param req required number
*/
public static void checkArgumentCount(ThreadContext context, IRubyObject[] args, int req) {
checkArgumentCount(context, args.length, req, req);
}
public static void checkArgumentCount(ThreadContext context, int length, int min, int max) {
int expected = 0;
if (length < min) {
expected = min;
} else if (max > -1 && length > max) {
expected = max;
} else {
return;
}
throw context.runtime.newArgumentError(length, expected);
}
public static boolean isModuleAndHasConstant(IRubyObject left, String name) {
return left instanceof RubyModule && ((RubyModule) left).getConstantFromNoConstMissing(name, false) != null;
}
@JIT @Interp
public static IRubyObject getDefinedConstantOrBoundMethod(IRubyObject left, String name, IRubyObject definedConstantMessage, IRubyObject definedMethodMessage) {
if (isModuleAndHasConstant(left, name)) return definedConstantMessage;
if (left.getMetaClass().isMethodBound(name, true)) return definedMethodMessage;
return null;
}
public static RubyModule getSuperClassForDefined(Ruby runtime, RubyModule klazz) {
RubyModule superklazz = klazz.getSuperClass();
if (superklazz == null && klazz.isModule()) superklazz = runtime.getObject();
return superklazz;
}
public static String[] getScopeNames(String scopeNames) {
StringTokenizer toker = new StringTokenizer(scopeNames, ";");
ArrayList list = new ArrayList(10);
while (toker.hasMoreTokens()) {
list.add(toker.nextToken().intern());
}
return (String[])list.toArray(new String[list.size()]);
}
public static RubyClass metaclass(IRubyObject object) {
return object instanceof RubyBasicObject ?
((RubyBasicObject)object).getMetaClass() :
object.getMetaClass();
}
public static String rawBytesToString(byte[] bytes) {
// stuff bytes into chars
char[] chars = new char[bytes.length];
for (int i = 0; i < bytes.length; i++) chars[i] = (char)bytes[i];
return new String(chars);
}
public static byte[] stringToRawBytes(String string) {
char[] chars = string.toCharArray();
byte[] bytes = new byte[chars.length];
for (int i = 0; i < chars.length; i++) bytes[i] = (byte)chars[i];
return bytes;
}
public static String encodeCaptureOffsets(int[] scopeOffsets) {
char[] encoded = new char[scopeOffsets.length * 2];
for (int i = 0; i < scopeOffsets.length; i++) {
int offDepth = scopeOffsets[i];
char off = (char)(offDepth & 0xFFFF);
char depth = (char)(offDepth >> 16);
encoded[2 * i] = off;
encoded[2 * i + 1] = depth;
}
return new String(encoded);
}
public static int[] decodeCaptureOffsets(String encoded) {
char[] chars = encoded.toCharArray();
int[] scopeOffsets = new int[chars.length / 2];
for (int i = 0; i < scopeOffsets.length; i++) {
char off = chars[2 * i];
char depth = chars[2 * i + 1];
scopeOffsets[i] = (((int)depth) << 16) | (int)off;
}
return scopeOffsets;
}
@Deprecated // not-used
public static IRubyObject match2AndUpdateScope(IRubyObject receiver, ThreadContext context, IRubyObject value, String scopeOffsets) {
IRubyObject match = ((RubyRegexp)receiver).op_match(context, value);
updateScopeWithCaptures(context, decodeCaptureOffsets(scopeOffsets), match);
return match;
}
public static void updateScopeWithCaptures(ThreadContext context, int[] scopeOffsets, IRubyObject result) {
Ruby runtime = context.runtime;
if (result.isNil()) { // match2 directly calls match so we know we can count on result
IRubyObject nil = runtime.getNil();
for (int i = 0; i < scopeOffsets.length; i++) {
// SSS FIXME: This is not doing the offset/depth extraction as in the else case
context.getCurrentScope().setValue(nil, scopeOffsets[i], 0);
}
} else {
RubyMatchData matchData = (RubyMatchData)context.getBackRef();
// FIXME: Mass assignment is possible since we know they are all locals in the same
// scope that are also contiguous
IRubyObject[] namedValues = matchData.getNamedBackrefValues(runtime);
for (int i = 0; i < scopeOffsets.length; i++) {
context.getCurrentScope().setValue(namedValues[i], scopeOffsets[i] & 0xffff, scopeOffsets[i] >> 16);
}
}
}
@Deprecated
public static RubyArray argsPush(ThreadContext context, RubyArray first, IRubyObject second) {
return ((RubyArray)first.dup()).append(second);
}
@JIT
public static RubyArray argsPush(IRubyObject first, IRubyObject second) {
return ((RubyArray)first.dup()).append(second);
}
public static RubyArray argsCat(ThreadContext context, IRubyObject first, IRubyObject second) {
IRubyObject secondArgs = IRRuntimeHelpers.irSplat(context, second);
return ((RubyArray) Helpers.ensureRubyArray(context.runtime, first).dup()).concat(secondArgs);
}
@Deprecated
public static RubyArray argsCat(IRubyObject first, IRubyObject second) {
return argsCat(first.getRuntime().getCurrentContext(), first, second);
}
/** Use an ArgsNode (used for blocks) to generate ArgumentDescriptors */
public static ArgumentDescriptor[] argsNodeToArgumentDescriptors(ArgsNode argsNode) {
ArrayList<ArgumentDescriptor> descs = new ArrayList<>();
Node[] args = argsNode.getArgs();
int preCount = argsNode.getPreCount();
if (preCount > 0) {
for (int i = 0; i < preCount; i++) {
if (args[i] instanceof MultipleAsgnNode) {
descs.add(new ArgumentDescriptor(ArgumentType.anonreq));
} else {
descs.add(new ArgumentDescriptor(ArgumentType.req, ((ArgumentNode) args[i]).getName()));
}
}
}
int optCount = argsNode.getOptionalArgsCount();
if (optCount > 0) {
int optIndex = argsNode.getOptArgIndex();
for (int i = 0; i < optCount; i++) {
Node optNode = args[optIndex + i];
if (optNode instanceof INameNode) {
descs.add(new ArgumentDescriptor(ArgumentType.opt, ((INameNode) optNode).getName()));
} else {
descs.add(new ArgumentDescriptor(ArgumentType.anonopt));
}
}
}
ArgumentNode restArg = argsNode.getRestArgNode();
if (restArg != null) {
if (restArg instanceof UnnamedRestArgNode) {
if (((UnnamedRestArgNode) restArg).isStar()) descs.add(new ArgumentDescriptor(ArgumentType.anonrest));
} else {
descs.add(new ArgumentDescriptor(ArgumentType.rest, restArg.getName()));
}
}
int postCount = argsNode.getPostCount();
if (postCount > 0) {
int postIndex = argsNode.getPostIndex();
for (int i = 0; i < postCount; i++) {
Node postNode = args[postIndex + i];
if (postNode instanceof MultipleAsgnNode) {
descs.add(new ArgumentDescriptor(ArgumentType.anonreq));
} else {
descs.add(new ArgumentDescriptor(ArgumentType.req, ((ArgumentNode)postNode).getName()));
}
}
}
int keywordsCount = argsNode.getKeywordCount();
if (keywordsCount > 0) {
int keywordsIndex = argsNode.getKeywordsIndex();
for (int i = 0; i < keywordsCount; i++) {
Node keyWordNode = args[keywordsIndex + i];
for (Node asgnNode : keyWordNode.childNodes()) {
ArgumentType type = isRequiredKeywordArgumentValueNode(asgnNode) ? ArgumentType.keyreq : ArgumentType.key;
descs.add(new ArgumentDescriptor(type, ((INameNode) asgnNode).getName()));
}
}
}
if (argsNode.getKeyRest() != null) {
RubySymbol argName = argsNode.getKeyRest().getName();
// FIXME: Should a argName of "" really get saved that way here?
ArgumentType type = argName == null || argName.getBytes().length() == 0 ? ArgumentType.anonkeyrest : ArgumentType.keyrest;
descs.add(new ArgumentDescriptor(type, argName));
}
if (argsNode.getBlock() != null) descs.add(new ArgumentDescriptor(ArgumentType.block, argsNode.getBlock().getName()));
return descs.toArray(new ArgumentDescriptor[descs.size()]);
}
/**
* Convert a parameter list from prefix format to ArgumentDescriptor format. This source is expected to come
* from a native path. Therefore we will be assuming parameterList is UTF-8.
*/
public static ArgumentDescriptor[] parameterListToArgumentDescriptors(Ruby runtime, String[] parameterList, boolean isLambda) {
ArgumentDescriptor[] parms = new ArgumentDescriptor[parameterList.length];
for (int i = 0; i < parameterList.length; i++) {
String param = parameterList[i];
if (param.equals("NONE")) break;
if (param.equals("nil")) param = "n"; // make length 1 so we don't look for a name
ArgumentType type = ArgumentType.valueOf(param.charAt(0));
// for lambdas, we call required args optional
if (type == ArgumentType.req && !isLambda) type = ArgumentType.opt;
// 'R', 'o', 'n' forms can get here without a name
if (param.length() > 1) {
parms[i] = new ArgumentDescriptor(type, runtime.newSymbol(param.substring(1)));
} else {
parms[i] = new ArgumentDescriptor(type.anonymousForm());
}
}
return parms;
}
/** Convert a parameter list from ArgumentDescriptor format to "Array of Array" format */
public static RubyArray argumentDescriptorsToParameters(Ruby runtime, ArgumentDescriptor[] argsDesc, boolean isLambda) {
if (argsDesc == null) Thread.dumpStack();
final RubyArray params = RubyArray.newBlankArray(runtime, argsDesc.length);
for (int i = 0; i < argsDesc.length; i++) {
ArgumentDescriptor param = argsDesc[i];
params.store(i, param.toArrayForm(runtime, isLambda));
}
return params;
}
public static ArgumentDescriptor[] methodToArgumentDescriptors(DynamicMethod method) {
method = method.getRealMethod();
if (method instanceof MethodArgs2) {
return parameterListToArgumentDescriptors(method.getImplementationClass().getRuntime(), ((MethodArgs2) method).getParameterList(), true);
} else if (method instanceof IRMethodArgs) {
return ((IRMethodArgs) method).getArgumentDescriptors();
} else {
return new ArgumentDescriptor[]{new ArgumentDescriptor(ArgumentType.anonrest)};
}
}
public static IRubyObject methodToParameters(Ruby runtime, AbstractRubyMethod recv) {
DynamicMethod method = recv.getMethod().getRealMethod();
return argumentDescriptorsToParameters(runtime, methodToArgumentDescriptors(method), true);
}
public static IRubyObject getDefinedCall(ThreadContext context, IRubyObject self, IRubyObject receiver, String name, IRubyObject definedMessage) {
RubyClass metaClass = receiver.getMetaClass();
DynamicMethod method = metaClass.searchMethod(name);
Visibility visibility = method.getVisibility();
if (visibility != Visibility.PRIVATE &&
(visibility != Visibility.PROTECTED || metaClass.getRealClass().isInstance(self)) && !method.isUndefined()) {
return definedMessage;
}
if (receiver.callMethod(context, "respond_to_missing?",
new IRubyObject[]{context.runtime.newSymbol(name), context.fals}).isTrue()) {
return definedMessage;
}
return null;
}
public static IRubyObject invokedynamic(ThreadContext context, IRubyObject self, MethodNames method) {
RubyClass metaclass = self.getMetaClass();
String name = method.realName();
CacheEntry entry = getMethodCached(context, metaclass, method.ordinal(), name);
return entry.method.call(context, self, entry.sourceModule, name);
}
public static IRubyObject invokedynamic(ThreadContext context, IRubyObject self, MethodNames method, IRubyObject arg0) {
RubyClass metaclass = self.getMetaClass();
String name = method.realName();
CacheEntry entry = getMethodCached(context, metaclass, method.ordinal(), name);
return entry.method.call(context, self, entry.sourceModule, name, arg0);
}
private static CacheEntry getMethodCached(ThreadContext context, RubyClass metaclass, int index, String name) {
if (metaclass.getClassIndex() == ClassIndex.NO_INDEX) return metaclass.searchWithCache(name);
return context.runtimeCache.getMethodEntry(context, metaclass, metaclass.getClassIndex().ordinal() * (index + 1), name);
}
@Deprecated // not used
public static IRubyObject lastElement(IRubyObject[] ary) {
return ary[ary.length - 1];
}
@Deprecated // not used
public static RubyString appendAsString(RubyString target, IRubyObject other) {
return target.append(other.asString());
}
// . Array given to rest should pass itself
// . Array with rest + other args should extract array
// . Array with multiple values and NO rest should extract args if there are more than one argument
static IRubyObject[] restructureBlockArgs(ThreadContext context,
IRubyObject value, Signature signature, Block.Type type, boolean needsSplat) {
if (!type.checkArity && signature == Signature.NO_ARGUMENTS) return IRubyObject.NULL_ARRAY;
if (value == null) return IRubyObject.NULL_ARRAY;
if (needsSplat) {
IRubyObject ary = Helpers.aryToAry(context, value);
if (ary instanceof RubyArray) return ((RubyArray) ary).toJavaArrayMaybeUnsafe();
}
return new IRubyObject[] { value };
}
@Deprecated // not used
public static RubyString appendByteList(RubyString target, ByteList source) {
target.getByteList().append(source);
return target;
}
@JIT
public static boolean BNE(ThreadContext context, IRubyObject value1, IRubyObject value2) {
boolean eql = value2 == context.nil || value2 == UndefinedValue.UNDEFINED ?
value1 == value2 : value1.op_equal(context, value2).isTrue();
return !eql;
}
public static void irCheckArgsArrayArity(ThreadContext context, RubyArray args, int required, int opt, boolean rest) {
int numArgs = args.size();
if (numArgs < required || (!rest && numArgs > (required + opt))) {
Arity.raiseArgumentError(context.runtime, numArgs, required, required + opt);
}
}
@Deprecated
public static IRubyObject invokedynamic(ThreadContext context, IRubyObject self, int index) {
return invokedynamic(context, self, MethodNames.values()[index]);
}
@Deprecated
public static IRubyObject invokedynamic(ThreadContext context, IRubyObject self, int index, IRubyObject arg0) {
return invokedynamic(context, self, MethodNames.values()[index], arg0);
}
public static void throwException(final Throwable e) {
Helpers.<RuntimeException>throwsUnchecked(e);
}
@SuppressWarnings("unchecked")
private static <T extends Throwable> void throwsUnchecked(final Throwable e) throws T {
throw (T) e;
}
/**
* Decode the given value to a Java string using the following rules:
*
* * If the string is all US-ASCII characters, it will be decoded as US-ASCII.
* * If the string is a unicode encoding, it will be decoded as such.
* * If the string is any other encoding, it will be encoded as raw bytes
* using ISO-8859-1.
*
* This allows non-unicode, non-US-ASCII encodings to be represented in the
* symbol table as their raw versions, but properly decodes unicode-
* encoded strings.
*
* @param value the value to decode
* @return the resulting symbol string
*/
public static String symbolBytesToString(ByteList value) {
Encoding encoding = value.getEncoding();
if (encoding == USASCIIEncoding.INSTANCE || encoding == ASCIIEncoding.INSTANCE) {
return value.toString(); // raw
} else if (encoding instanceof UnicodeEncoding) {
return new String(value.getUnsafeBytes(), value.getBegin(), value.getRealSize(), EncodingUtils.charsetForEncoding(value.getEncoding()));
} else {
return value.toString(); // raw
}
}
/**
* Decode a given ByteList to a Java string.
*
* @param runtime the current runtime
* @param value the bytelist
* @return a Java String representation of the ByteList
*/
public static String decodeByteList(Ruby runtime, ByteList value) {
byte[] unsafeBytes = value.getUnsafeBytes();
int begin = value.getBegin();
int length = value.length();
Encoding encoding = value.getEncoding();
if (encoding == UTF8Encoding.INSTANCE) {
return RubyEncoding.decodeUTF8(unsafeBytes, begin, length);
}
Charset charset = runtime.getEncodingService().charsetForEncoding(encoding);
if (charset == null) {
// No JDK Charset available for this encoding; convert to UTF-16 ourselves.
Encoding utf16 = EncodingUtils.getUTF16ForPlatform();
return EncodingUtils.strConvEnc(runtime.getCurrentContext(), value, value.getEncoding(), utf16).toString();
}
return RubyEncoding.decode(unsafeBytes, begin, length, charset);
}
/**
* Convert a ByteList into a Java String by using its Encoding's Charset. If
* the Charset is not available, fall back on other logic.
*
* @param bytes the bytelist to decode
* @return the decoded string
*/
public static String byteListToString(final ByteList bytes) {
final Encoding encoding = bytes.getEncoding();
if (encoding == UTF8Encoding.INSTANCE || encoding == USASCIIEncoding.INSTANCE) {
return RubyEncoding.decodeUTF8(bytes.getUnsafeBytes(), bytes.getBegin(), bytes.getRealSize());
}
final Charset charset = EncodingUtils.charsetForEncoding(encoding);
if ( charset != null ) {
return new String(bytes.getUnsafeBytes(), bytes.getBegin(), bytes.getRealSize(), charset);
}
return bytes.toString();
}
public static IRubyObject rewriteStackTraceAndThrow(ThreadContext context, Throwable t) {
Ruby runtime = context.runtime;
StackTraceElement[] javaTrace = t.getStackTrace();
BacktraceData backtraceData = runtime.getInstanceConfig().getTraceType().getIntegratedBacktrace(context, javaTrace);
t.setStackTrace(RaiseException.javaTraceFromRubyTrace(backtraceData.getBacktrace(runtime)));
throwException(t);
return null; // not reached
}
@Deprecated // un-used
public static void rewriteStackTrace(final Ruby runtime, final Throwable e) {
final StackTraceElement[] javaTrace = e.getStackTrace();
BacktraceData backtraceData = runtime.getInstanceConfig().getTraceType().getIntegratedBacktrace(runtime.getCurrentContext(), javaTrace);
e.setStackTrace(RaiseException.javaTraceFromRubyTrace(backtraceData.getBacktrace(runtime)));
}
public static <T> T[] arrayOf(T... values) {
return values;
}
public static <T> T[] arrayOf(Class<T> t, int size, T fill) {
T[] ary = (T[])Array.newInstance(t, size);
Arrays.fill(ary, fill);
return ary;
}
public static int memchr(boolean[] ary, int start, int len, boolean find) {
for (int i = 0; i < len; i++) {
if (ary[i + start] == find) return i + start;
}
return -1;
}
public static boolean isRequiredKeywordArgumentValueNode(Node asgnNode) {
return asgnNode.childNodes().get(0) instanceof RequiredKeywordArgumentValueNode;
}
// MRI: rb_hash_start
public static long hashStart(Ruby runtime, long value) {
long hash = value +
(runtime.isSiphashEnabled() ?
runtime.getHashSeedK1() :
runtime.getHashSeedK0());
return hash;
}
public static long hashEnd(long value) {
value = murmur_step(value, 10);
value = murmur_step(value, 17);
return value;
}
// MRI: rb_hash
public static RubyFixnum safeHash(final ThreadContext context, IRubyObject obj) {
Ruby runtime = context.runtime;
IRubyObject hval = context.safeRecurse(sites(context).recursive_hash, runtime, obj, "hash", true);
while (!(hval instanceof RubyFixnum)) {
if (hval instanceof RubyBignum) {
// This is different from MRI because we don't have rb_integer_pack
return ((RubyBignum) hval).hash();
}
hval = hval.convertToInteger();
}
return (RubyFixnum) hval;
}
public static long murmurCombine(long h, long i)
{
long v = 0;
h += i;
v = murmur1(v + h);
v = murmur1(v + (h >>> 4*8));
return v;
}
public static long murmur(long h, long k, int r)
{
long m = MurmurHash.MURMUR2_MAGIC;
h += k;
h *= m;
h ^= h >> r;
return h;
}
public static long murmur_finish(long h)
{
h = murmur(h, 0, 10);
h = murmur(h, 0, 17);
return h;
}
public static long murmur_step(long h, long k) {
return murmur((h), (k), 16);
}
public static long murmur1(long h) {
return murmur_step(h, 16);
}
private static HelpersSites sites(ThreadContext context) {
return context.sites.Helpers;
}
@Deprecated
public static String encodeParameterList(List<String[]> args) {
if (args.size() == 0) return "NONE";
StringBuilder builder = new StringBuilder();
boolean added = false;
for (String[] desc : args) {
if (added) builder.append(';');
builder.append(desc[0]).append(desc[1]);
added = true;
}
return builder.toString();
}
public static byte[] subseq(byte[] ary, int start, int len) {
byte[] newAry = new byte[len];
System.arraycopy(ary, start, newAry, 0, len);
return newAry;
}
/**
*
* We have respondTo logic in RubyModule and we have a special callsite for respond_to?.
* This method is just so we can share that logic.
*/
public static boolean respondsToMethod(DynamicMethod method, boolean checkVisibility) {
if (method.isUndefined() || method.isNotImplemented()) return false;
return !(checkVisibility &&
(method.getVisibility() == PRIVATE || method.getVisibility() == PROTECTED));
}
public static StaticScope getStaticScope(IRScope scope) {
return scope.getStaticScope();
}
/**
* This method is deprecated because it depends on having a Ruby frame pushed for checking method visibility,
* and there's no way to enforce that. Most users of this method probably don't need to check visibility.
*
* See https://github.com/jruby/jruby/issues/4134
*
* @deprecated Use finvoke if you do not want visibility-checking or invokeFrom if you do.
*/
public static IRubyObject invoke(ThreadContext context, IRubyObject self, String name, IRubyObject[] args, CallType callType, Block block) {
return self.getMetaClass().invoke(context, self, name, args, callType, block);
}
/**
* This method is deprecated because it depends on having a Ruby frame pushed for checking method visibility,
* and there's no way to enforce that. Most users of this method probably don't need to check visibility.
*
* See https://github.com/jruby/jruby/issues/4134
*
* @deprecated Use finvoke if you do not want visibility-checking or invokeFrom if you do.
*/
public static IRubyObject invoke(ThreadContext context, IRubyObject self, String name, IRubyObject arg, CallType callType, Block block) {
return self.getMetaClass().invoke(context, self, name, arg, callType, block);
}
/**
* This method is deprecated because it depends on having a Ruby frame pushed for checking method visibility,
* and there's no way to enforce that. Most users of this method probably don't need to check visibility.
*
* See https://github.com/jruby/jruby/issues/4134
*
* @deprecated Use finvoke if you do not want visibility-checking or invokeFrom if you do.
*/
public static IRubyObject invoke(ThreadContext context, IRubyObject self, String name, CallType callType) {
return Helpers.invoke(context, self, name, IRubyObject.NULL_ARRAY, callType, Block.NULL_BLOCK);
}
@Deprecated
public static IRubyObject invokeFrom(ThreadContext context, IRubyObject caller, IRubyObject self, String name, IRubyObject[] args, CallType callType, Block block) {
return self.getMetaClass().invokeFrom(context, callType, caller, self, name, args, block);
}
@Deprecated
public static IRubyObject invokeFrom(ThreadContext context, IRubyObject caller, IRubyObject self, String name, IRubyObject arg, CallType callType, Block block) {
return self.getMetaClass().invokeFrom(context, callType, caller, self, name, arg, block);
}
@Deprecated
public static IRubyObject invokeFrom(ThreadContext context, IRubyObject caller, IRubyObject self, String name, CallType callType) {
return self.getMetaClass().invokeFrom(context, callType, caller, self, name, IRubyObject.NULL_ARRAY, Block.NULL_BLOCK);
}
}
|
// Copyright 2000-2017 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.psi.impl;
import com.intellij.lang.*;
import com.intellij.lang.java.lexer.JavaLexer;
import com.intellij.lang.java.parser.JavaParser;
import com.intellij.lang.java.parser.JavaParserUtil;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.project.Project;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.codeStyle.JavaCodeStyleSettingsFacade;
import com.intellij.psi.impl.light.*;
import com.intellij.psi.impl.source.*;
import com.intellij.psi.impl.source.codeStyle.CodeEditUtil;
import com.intellij.psi.impl.source.tree.FileElement;
import com.intellij.psi.impl.source.tree.TreeElement;
import com.intellij.psi.javadoc.PsiDocTag;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.ConcurrencyUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
public class PsiElementFactoryImpl extends PsiJavaParserFacadeImpl implements PsiElementFactory {
private final ConcurrentMap<LanguageLevel, PsiClass> myArrayClasses = ContainerUtil.newConcurrentMap();
private final ConcurrentMap<GlobalSearchScope, PsiClassType> myCachedObjectType = ContainerUtil.createConcurrentSoftMap();
public PsiElementFactoryImpl(final PsiManagerEx manager) {
super(manager);
manager.registerRunnableToRunOnChange(myCachedObjectType::clear);
}
@NotNull
@Override
public PsiClass getArrayClass(@NotNull LanguageLevel languageLevel) {
return myArrayClasses.computeIfAbsent(languageLevel, this::createArrayClass);
}
private PsiClass createArrayClass(LanguageLevel level) {
String text = level.isAtLeast(LanguageLevel.JDK_1_5) ?
"public class __Array__<T> {\n public final int length;\n public T[] clone() {}\n}" :
"public class __Array__{\n public final int length;\n public Object clone() {}\n}";
PsiClass psiClass = ((PsiExtensibleClass)createClassFromText(text, null)).getOwnInnerClasses().get(0);
ensureNonWritable(psiClass);
PsiFile file = psiClass.getContainingFile();
file.clearCaches();
PsiUtil.FILE_LANGUAGE_LEVEL_KEY.set(file, level);
return psiClass;
}
private static void ensureNonWritable(PsiClass arrayClass) {
try {
arrayClass.getContainingFile().getViewProvider().getVirtualFile().setWritable(false);
}
catch (IOException ignored) {}
}
@NotNull
@Override
public PsiClassType getArrayClassType(@NotNull final PsiType componentType, @NotNull final LanguageLevel languageLevel) {
final PsiClass arrayClass = getArrayClass(languageLevel);
final PsiTypeParameter[] typeParameters = arrayClass.getTypeParameters();
PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
if (typeParameters.length == 1) {
substitutor = substitutor.put(typeParameters[0], componentType);
}
return createType(arrayClass, substitutor);
}
@NotNull
@Override
public PsiClassType createType(@NotNull PsiClass resolve, @NotNull PsiSubstitutor substitutor) {
return new PsiImmediateClassType(resolve, substitutor);
}
@NotNull
@Override
public PsiClassType createType(@NotNull PsiClass resolve, @NotNull PsiSubstitutor substitutor, @Nullable LanguageLevel languageLevel) {
return new PsiImmediateClassType(resolve, substitutor, languageLevel);
}
@NotNull
@Override
public PsiClassType createType(@NotNull PsiClass resolve,
@NotNull PsiSubstitutor substitutor,
@Nullable LanguageLevel languageLevel,
@NotNull PsiAnnotation[] annotations) {
return new PsiImmediateClassType(resolve, substitutor, languageLevel, annotations);
}
@NotNull
@Override
public PsiClass createClass(@NotNull final String name) throws IncorrectOperationException {
return createClassInner("class", name);
}
@NotNull
@Override
public PsiClass createInterface(@NotNull final String name) throws IncorrectOperationException {
return createClassInner("interface", name);
}
@NotNull
@Override
public PsiClass createEnum(@NotNull final String name) throws IncorrectOperationException {
return createClassInner("enum", name);
}
@NotNull
@Override
public PsiClass createAnnotationType(@NotNull @NonNls String name) throws IncorrectOperationException {
return createClassInner("@interface", name);
}
private PsiClass createClassInner(@NonNls final String type, @NonNls String name) {
PsiUtil.checkIsIdentifier(myManager, name);
final PsiJavaFile aFile = createDummyJavaFile("public " + type + " " + name + " { }");
final PsiClass[] classes = aFile.getClasses();
if (classes.length != 1) {
throw new IncorrectOperationException("Incorrect " + type + " name \"" + name + "\".");
}
return classes[0];
}
@NotNull
@Override
public PsiTypeElement createTypeElement(@NotNull final PsiType psiType) {
final LightTypeElement element = new LightTypeElement(myManager, psiType);
CodeEditUtil.setNodeGenerated(element.getNode(), true);
return element;
}
@NotNull
@Override
public PsiJavaCodeReferenceElement createReferenceElementByType(@NotNull final PsiClassType type) {
if (type instanceof PsiClassReferenceType) {
return ((PsiClassReferenceType)type).getReference();
}
return new LightClassTypeReference(myManager, type);
}
@NotNull
@Override
public PsiTypeParameterList createTypeParameterList() {
final PsiTypeParameterList parameterList = createMethodFromText("void foo()", null).getTypeParameterList();
assert parameterList != null;
return parameterList;
}
@NotNull
@Override
public PsiTypeParameter createTypeParameter(String name, PsiClassType[] superTypes) {
@NonNls StringBuilder builder = new StringBuilder();
builder.append("public <").append(name);
if (superTypes.length > 1 ||
superTypes.length == 1 && !superTypes[0].equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) {
builder.append(" extends ");
for (PsiClassType type : superTypes) {
if (type.equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) continue;
builder.append(type.getCanonicalText(true)).append('&');
}
builder.delete(builder.length() - 1, builder.length());
}
builder.append("> void foo(){}");
try {
return createMethodFromText(builder.toString(), null).getTypeParameters()[0];
}
catch (RuntimeException e) {
throw new IncorrectOperationException("type parameter text: " + builder.toString());
}
}
@NotNull
@Override
public PsiField createField(@NotNull final String name, @NotNull final PsiType type) throws IncorrectOperationException {
PsiUtil.checkIsIdentifier(myManager, name);
if (PsiType.NULL.equals(type)) {
throw new IncorrectOperationException("Cannot create field with type \"null\".");
}
@NonNls final String text = "class _Dummy_ { private " + GenericsUtil.getVariableTypeByExpressionType(type).getCanonicalText(true) + " " + name + "; }";
final PsiJavaFile aFile = createDummyJavaFile(text);
final PsiClass[] classes = aFile.getClasses();
if (classes.length < 1) {
throw new IncorrectOperationException("Class was not created " + text);
}
final PsiClass psiClass = classes[0];
final PsiField[] fields = psiClass.getFields();
if (fields.length < 1) {
throw new IncorrectOperationException("Field was not created " + text);
}
PsiField field = fields[0];
field = (PsiField)JavaCodeStyleManager.getInstance(myManager.getProject()).shortenClassReferences(field);
return (PsiField)CodeStyleManager.getInstance(myManager.getProject()).reformat(field);
}
@NotNull
@Override
public PsiMethod createMethod(@NotNull final String name, final PsiType returnType) throws IncorrectOperationException {
PsiUtil.checkIsIdentifier(myManager, name);
if (PsiType.NULL.equals(returnType)) {
throw new IncorrectOperationException("Cannot create method with type \"null\".");
}
final String canonicalText = GenericsUtil.getVariableTypeByExpressionType(returnType).getCanonicalText(true);
final PsiJavaFile aFile = createDummyJavaFile("class _Dummy_ { public " + canonicalText + " " + name + "() {\n} }");
final PsiClass[] classes = aFile.getClasses();
if (classes.length < 1) {
throw new IncorrectOperationException("Class was not created. Method name: " + name + "; return type: " + canonicalText);
}
final PsiMethod[] methods = classes[0].getMethods();
if (methods.length < 1) {
throw new IncorrectOperationException("Method was not created. Method name: " + name + "; return type: " + canonicalText);
}
PsiMethod method = methods[0];
method = (PsiMethod)JavaCodeStyleManager.getInstance(myManager.getProject()).shortenClassReferences(method);
return (PsiMethod)CodeStyleManager.getInstance(myManager.getProject()).reformat(method);
}
@NotNull
@Override
public PsiMethod createMethod(@NotNull @NonNls String name, PsiType returnType, PsiElement context) throws IncorrectOperationException {
return createMethodFromText("public " + GenericsUtil.getVariableTypeByExpressionType(returnType).getCanonicalText(true) + " " + name + "() {}", context);
}
@NotNull
@Override
public PsiMethod createConstructor() {
return createConstructor("_Dummy_");
}
@NotNull
@Override
public PsiMethod createConstructor(@NotNull @NonNls final String name) {
final PsiJavaFile aFile = createDummyJavaFile("class " + name + " { public " + name + "() {} }");
final PsiMethod method = aFile.getClasses()[0].getMethods()[0];
return (PsiMethod)CodeStyleManager.getInstance(myManager.getProject()).reformat(method);
}
@Override
public PsiMethod createConstructor(@NotNull @NonNls String name, PsiElement context) {
return createMethodFromText(name + "() {}", context);
}
@NotNull
@Override
public PsiClassInitializer createClassInitializer() throws IncorrectOperationException {
final PsiJavaFile aFile = createDummyJavaFile("class _Dummy_ { {} }");
final PsiClassInitializer classInitializer = aFile.getClasses()[0].getInitializers()[0];
return (PsiClassInitializer)CodeStyleManager.getInstance(myManager.getProject()).reformat(classInitializer);
}
@NotNull
@Override
public PsiParameter createParameter(@NotNull final String name, @NotNull final PsiType type) throws IncorrectOperationException {
PsiUtil.checkIsIdentifier(myManager, name);
if (PsiType.NULL.equals(type)) {
throw new IncorrectOperationException("Cannot create parameter with type \"null\".");
}
final String text = type.getCanonicalText(true) + " " + name;
PsiParameter parameter = createParameterFromText(text, null);
final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(myManager.getProject());
PsiUtil.setModifierProperty(parameter, PsiModifier.FINAL,
JavaCodeStyleSettingsFacade.getInstance(myManager.getProject()).isGenerateFinalParameters());
GeneratedMarkerVisitor.markGenerated(parameter);
parameter = (PsiParameter)JavaCodeStyleManager.getInstance(myManager.getProject()).shortenClassReferences(parameter);
return (PsiParameter)codeStyleManager.reformat(parameter);
}
@Override
public PsiParameter createParameter(@NotNull @NonNls String name, PsiType type, PsiElement context) throws IncorrectOperationException {
final PsiMethod psiMethod = createMethodFromText("void f(" + type.getCanonicalText(true) + " " + name + ") {}", context);
final PsiParameter[] parameters = psiMethod.getParameterList().getParameters();
return parameters[0];
}
@NotNull
@Override
public PsiCodeBlock createCodeBlock() {
final PsiCodeBlock block = createCodeBlockFromText("{}", null);
return (PsiCodeBlock)CodeStyleManager.getInstance(myManager.getProject()).reformat(block);
}
@NotNull
@Override
public PsiClassType createType(@NotNull final PsiClass aClass) {
return new PsiImmediateClassType(aClass, aClass instanceof PsiTypeParameter ? PsiSubstitutor.EMPTY : createRawSubstitutor(aClass));
}
@NotNull
@Override
public PsiClassType createType(@NotNull final PsiJavaCodeReferenceElement classReference) {
return new PsiClassReferenceType(classReference, null);
}
@NotNull
@Override
public PsiClassType createType(@NotNull final PsiClass aClass, final PsiType parameter) {
final PsiTypeParameter[] typeParameters = aClass.getTypeParameters();
assert typeParameters.length == 1 : aClass;
return createType(aClass, PsiSubstitutor.EMPTY.put(typeParameters[0], parameter));
}
@NotNull
@Override
public PsiClassType createType(@NotNull final PsiClass aClass, final PsiType... parameters) {
return createType(aClass, PsiSubstitutor.EMPTY.putAll(aClass, parameters));
}
@NotNull
@Override
public PsiSubstitutor createRawSubstitutor(@NotNull final PsiTypeParameterListOwner owner) {
Map<PsiTypeParameter, PsiType> substitutorMap = null;
for (PsiTypeParameter parameter : PsiUtil.typeParametersIterable(owner)) {
if (substitutorMap == null) substitutorMap = new HashMap<>();
substitutorMap.put(parameter, null);
}
return PsiSubstitutorImpl.createSubstitutor(substitutorMap);
}
@NotNull
@Override
public PsiSubstitutor createRawSubstitutor(@NotNull final PsiSubstitutor baseSubstitutor, @NotNull final PsiTypeParameter[] typeParameters) {
Map<PsiTypeParameter, PsiType> substitutorMap = null;
for (PsiTypeParameter parameter : typeParameters) {
if (substitutorMap == null) substitutorMap = new HashMap<>();
substitutorMap.put(parameter, null);
}
return PsiSubstitutorImpl.createSubstitutor(substitutorMap).putAll(baseSubstitutor);
}
@NotNull
@Override
public PsiElement createDummyHolder(@NotNull final String text, @NotNull final IElementType type, @Nullable final PsiElement context) {
final DummyHolder result = DummyHolderFactory.createHolder(myManager, context);
final FileElement holder = result.getTreeElement();
final Language language = type.getLanguage();
final ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(language);
assert parserDefinition != null : "No parser definition for language " + language;
final Project project = myManager.getProject();
final Lexer lexer = parserDefinition.createLexer(project);
final PsiBuilder builder = PsiBuilderFactory.getInstance().createBuilder(project, holder, lexer, language, text);
final ASTNode node = parserDefinition.createParser(project).parse(type, builder);
holder.rawAddChildren((TreeElement)node);
final PsiElement psi = node.getPsi();
assert psi != null : text;
return psi;
}
@NotNull
@Override
public PsiSubstitutor createSubstitutor(@NotNull final Map<PsiTypeParameter, PsiType> map) {
return PsiSubstitutorImpl.createSubstitutor(map);
}
@Nullable
@Override
public PsiPrimitiveType createPrimitiveType(@NotNull final String text) {
return PsiJavaParserFacadeImpl.getPrimitiveType(text);
}
@NotNull
@Override
public PsiClassType createTypeByFQClassName(@NotNull final String qName) {
return createTypeByFQClassName(qName, GlobalSearchScope.allScope(myManager.getProject()));
}
@NotNull
@Override
public PsiClassType createTypeByFQClassName(@NotNull final String qName, @NotNull final GlobalSearchScope resolveScope) {
if (CommonClassNames.JAVA_LANG_OBJECT.equals(qName)) {
PsiClassType cachedObjectType = myCachedObjectType.get(resolveScope);
if (cachedObjectType != null) {
return cachedObjectType;
}
PsiClass aClass = JavaPsiFacade.getInstance(myManager.getProject()).findClass(CommonClassNames.JAVA_LANG_OBJECT, resolveScope);
if (aClass != null) {
cachedObjectType = new PsiImmediateClassType(aClass, PsiSubstitutor.EMPTY);
cachedObjectType = ConcurrencyUtil.cacheOrGet(myCachedObjectType, resolveScope, cachedObjectType);
return cachedObjectType;
}
}
return new PsiClassReferenceType(createReferenceElementByFQClassName(qName, resolveScope), null);
}
@NotNull
@Override
public PsiJavaCodeReferenceElement createClassReferenceElement(@NotNull final PsiClass aClass) {
final String text;
if (aClass instanceof PsiAnonymousClass) {
text = ((PsiAnonymousClass)aClass).getBaseClassType().getPresentableText();
}
else {
text = aClass.getName();
}
if (text == null) {
throw new IncorrectOperationException("Invalid class: " + aClass);
}
return new LightClassReference(myManager, text, aClass);
}
@NotNull
@Override
public PsiJavaCodeReferenceElement createReferenceElementByFQClassName(@NotNull final String qName,
@NotNull final GlobalSearchScope resolveScope) {
final String shortName = PsiNameHelper.getShortClassName(qName);
return new LightClassReference(myManager, shortName, qName, resolveScope);
}
@NotNull
@Override
public PsiJavaCodeReferenceElement createFQClassNameReferenceElement(@NotNull final String qName,
@NotNull final GlobalSearchScope resolveScope) {
return new LightClassReference(myManager, qName, qName, resolveScope);
}
@NotNull
@Override
public PsiJavaCodeReferenceElement createPackageReferenceElement(@NotNull final PsiPackage aPackage) throws IncorrectOperationException {
if (aPackage.getQualifiedName().isEmpty()) {
throw new IncorrectOperationException("Cannot create reference to default package.");
}
return new LightPackageReference(myManager, aPackage);
}
@NotNull
@Override
public PsiPackageStatement createPackageStatement(@NotNull final String name) throws IncorrectOperationException {
final PsiJavaFile aFile = createDummyJavaFile("package " + name + ";");
final PsiPackageStatement stmt = aFile.getPackageStatement();
if (stmt == null) {
throw new IncorrectOperationException("Incorrect package name: " + name);
}
return stmt;
}
@NotNull
@Override
public PsiImportStaticStatement createImportStaticStatement(@NotNull final PsiClass aClass,
@NotNull final String memberName) throws IncorrectOperationException {
if (aClass instanceof PsiAnonymousClass) {
throw new IncorrectOperationException("Cannot create import statement for anonymous class.");
}
else if (aClass.getParent() instanceof PsiDeclarationStatement) {
throw new IncorrectOperationException("Cannot create import statement for local class.");
}
final PsiJavaFile aFile = createDummyJavaFile("import static " + aClass.getQualifiedName() + "." + memberName + ";");
final PsiImportStatementBase statement = extractImport(aFile, true);
return (PsiImportStaticStatement)CodeStyleManager.getInstance(myManager.getProject()).reformat(statement);
}
@NotNull
@Override
public PsiParameterList createParameterList(@NotNull final String[] names, @NotNull final PsiType[] types) throws IncorrectOperationException {
@NonNls StringBuilder builder = new StringBuilder();
builder.append("void method(");
for (int i = 0; i < names.length; i++) {
if (i > 0) builder.append(", ");
builder.append(types[i].getCanonicalText(true)).append(' ').append(names[i]);
}
builder.append(");");
return createMethodFromText(builder.toString(), null).getParameterList();
}
@NotNull
@Override
public PsiReferenceList createReferenceList(@NotNull final PsiJavaCodeReferenceElement[] references) throws IncorrectOperationException {
@NonNls final StringBuilder builder = new StringBuilder();
builder.append("void method()");
if (references.length > 0){
builder.append(" throws ");
for (int i = 0; i < references.length; i++) {
if (i > 0) builder.append(", ");
builder.append(references[i].getCanonicalText());
}
}
builder.append(';');
return createMethodFromText(builder.toString(), null).getThrowsList();
}
@NotNull
@Override
public PsiJavaCodeReferenceElement createPackageReferenceElement(@NotNull final String packageName) throws IncorrectOperationException {
if (packageName.isEmpty()) {
throw new IncorrectOperationException("Cannot create reference to default package.");
}
return new LightPackageReference(myManager, packageName);
}
@NotNull
@Override
public PsiReferenceExpression createReferenceExpression(@NotNull final PsiClass aClass) throws IncorrectOperationException {
final String text;
if (aClass instanceof PsiAnonymousClass) {
text = ((PsiAnonymousClass)aClass).getBaseClassType().getPresentableText();
}
else {
text = aClass.getName();
}
return new LightClassReferenceExpression(myManager, text, aClass);
}
@NotNull
@Override
public PsiReferenceExpression createReferenceExpression(@NotNull final PsiPackage aPackage) throws IncorrectOperationException {
if (aPackage.getQualifiedName().isEmpty()) {
throw new IncorrectOperationException("Cannot create reference to default package.");
}
return new LightPackageReferenceExpression(myManager, aPackage);
}
@NotNull
@Override
public PsiIdentifier createIdentifier(@NotNull final String text) throws IncorrectOperationException {
PsiUtil.checkIsIdentifier(myManager, text);
return new LightIdentifier(myManager, text);
}
@NotNull
@Override
public PsiKeyword createKeyword(@NotNull final String text) throws IncorrectOperationException {
if (!PsiNameHelper.getInstance(myManager.getProject()).isKeyword(text)) {
throw new IncorrectOperationException("\"" + text + "\" is not a keyword.");
}
return new LightKeyword(myManager, text);
}
@NotNull
@Override
public PsiKeyword createKeyword(@NotNull @NonNls String keyword, PsiElement context) throws IncorrectOperationException {
LanguageLevel level = PsiUtil.getLanguageLevel(context);
if (!JavaLexer.isKeyword(keyword, level) && !JavaLexer.isSoftKeyword(keyword, level)) {
throw new IncorrectOperationException("\"" + keyword + "\" is not a keyword.");
}
return new LightKeyword(myManager, keyword);
}
@NotNull
@Override
public PsiImportStatement createImportStatement(@NotNull final PsiClass aClass) throws IncorrectOperationException {
if (aClass instanceof PsiAnonymousClass) {
throw new IncorrectOperationException("Cannot create import statement for anonymous class.");
}
else if (aClass.getParent() instanceof PsiDeclarationStatement) {
throw new IncorrectOperationException("Cannot create import statement for local class.");
}
final PsiJavaFile aFile = createDummyJavaFile("import " + aClass.getQualifiedName() + ";");
final PsiImportStatementBase statement = extractImport(aFile, false);
return (PsiImportStatement)CodeStyleManager.getInstance(myManager.getProject()).reformat(statement);
}
@NotNull
@Override
public PsiImportStatement createImportStatementOnDemand(@NotNull final String packageName) throws IncorrectOperationException {
if (packageName.isEmpty()) {
throw new IncorrectOperationException("Cannot create import statement for default package.");
}
if (!PsiNameHelper.getInstance(myManager.getProject()).isQualifiedName(packageName)) {
throw new IncorrectOperationException("Incorrect package name: \"" + packageName + "\".");
}
final PsiJavaFile aFile = createDummyJavaFile("import " + packageName + ".*;");
final PsiImportStatementBase statement = extractImport(aFile, false);
return (PsiImportStatement)CodeStyleManager.getInstance(myManager.getProject()).reformat(statement);
}
@NotNull
@Override
public PsiDeclarationStatement createVariableDeclarationStatement(@NonNls @NotNull String name,
@NotNull PsiType type,
@Nullable PsiExpression initializer) throws IncorrectOperationException {
return createVariableDeclarationStatement(name, type, initializer, null);
}
@NotNull
@Override
public PsiDeclarationStatement createVariableDeclarationStatement(@NonNls @NotNull String name,
@NotNull PsiType type,
@Nullable PsiExpression initializer,
@Nullable PsiElement context) throws IncorrectOperationException {
if (!isIdentifier(name)) {
throw new IncorrectOperationException("\"" + name + "\" is not an identifier.");
}
if (PsiType.NULL.equals(type)) {
throw new IncorrectOperationException("Cannot create variable with type \"null\".");
}
String text = "X " + name + (initializer != null ? " = x" : "") + ";";
PsiDeclarationStatement statement = (PsiDeclarationStatement)createStatementFromText(text, context);
PsiVariable variable = (PsiVariable)statement.getDeclaredElements()[0];
replace(variable.getTypeElement(), createTypeElement(GenericsUtil.getVariableTypeByExpressionType(type)), text);
boolean generateFinalLocals = JavaCodeStyleSettingsFacade.getInstance(myManager.getProject()).isGenerateFinalLocals();
PsiUtil.setModifierProperty(variable, PsiModifier.FINAL, generateFinalLocals);
if (initializer != null) {
replace(variable.getInitializer(), initializer, text);
}
GeneratedMarkerVisitor.markGenerated(statement);
return statement;
}
@Override
public PsiResourceVariable createResourceVariable(@NonNls @NotNull String name,
@NotNull PsiType type,
@Nullable PsiExpression initializer,
@Nullable PsiElement context) {
PsiTryStatement tryStatement = (PsiTryStatement)createStatementFromText("try (X x = null){}", context);
PsiResourceList resourceList = tryStatement.getResourceList();
assert resourceList != null;
PsiResourceVariable resourceVariable = (PsiResourceVariable)resourceList.iterator().next();
resourceVariable.getTypeElement().replace(createTypeElement(type));
PsiIdentifier nameIdentifier = resourceVariable.getNameIdentifier();
assert nameIdentifier != null;
nameIdentifier.replace(createIdentifier(name));
if (initializer != null) {
resourceVariable.setInitializer(initializer);
}
return resourceVariable;
}
private static void replace(@Nullable PsiElement original, @NotNull PsiElement replacement, @NotNull String message) {
assert original != null : message;
original.replace(replacement);
}
@NotNull
@Override
public PsiDocTag createParamTag(@NotNull final String parameterName, @NonNls final String description) throws IncorrectOperationException {
@NonNls final StringBuilder builder = new StringBuilder();
builder.append(" * @param ");
builder.append(parameterName);
builder.append(" ");
final String[] strings = description.split("\\n");
for (int i = 0; i < strings.length; i++) {
if (i > 0) builder.append("\n * ");
builder.append(strings[i]);
}
return createDocTagFromText(builder.toString());
}
@NotNull
@Override
public PsiAnnotation createAnnotationFromText(@NotNull final String annotationText, @Nullable final PsiElement context) throws IncorrectOperationException {
final PsiAnnotation psiAnnotation = super.createAnnotationFromText(annotationText, context);
GeneratedMarkerVisitor.markGenerated(psiAnnotation);
return psiAnnotation;
}
public PsiAnnotation createAnnotationFromText(@NotNull final String annotationText,
@Nullable final PsiElement context,
boolean markGenerated) throws IncorrectOperationException {
final PsiAnnotation psiAnnotation = super.createAnnotationFromText(annotationText, context);
if (markGenerated) {
GeneratedMarkerVisitor.markGenerated(psiAnnotation);
}
return psiAnnotation;
}
@NotNull
@Override
public PsiCodeBlock createCodeBlockFromText(@NotNull final String text, @Nullable final PsiElement context) throws IncorrectOperationException {
final PsiCodeBlock psiCodeBlock = super.createCodeBlockFromText(text, context);
GeneratedMarkerVisitor.markGenerated(psiCodeBlock);
return psiCodeBlock;
}
@NotNull
@Override
public PsiEnumConstant createEnumConstantFromText(@NotNull final String text, @Nullable final PsiElement context) throws IncorrectOperationException {
final PsiEnumConstant enumConstant = super.createEnumConstantFromText(text, context);
GeneratedMarkerVisitor.markGenerated(enumConstant);
return enumConstant;
}
@NotNull
@Override
public PsiExpression createExpressionFromText(@NotNull final String text, @Nullable final PsiElement context) throws IncorrectOperationException {
final PsiExpression expression = super.createExpressionFromText(text, context);
GeneratedMarkerVisitor.markGenerated(expression);
return expression;
}
@NotNull
@Override
public PsiField createFieldFromText(@NotNull final String text, @Nullable final PsiElement context) throws IncorrectOperationException {
final PsiField psiField = super.createFieldFromText(text, context);
GeneratedMarkerVisitor.markGenerated(psiField);
return psiField;
}
@NotNull
@Override
public PsiParameter createParameterFromText(@NotNull final String text, @Nullable final PsiElement context) throws IncorrectOperationException {
final PsiParameter parameter = super.createParameterFromText(text, context);
GeneratedMarkerVisitor.markGenerated(parameter);
return parameter;
}
@NotNull
@Override
public PsiStatement createStatementFromText(@NotNull final String text, @Nullable final PsiElement context) throws IncorrectOperationException {
final PsiStatement statement = super.createStatementFromText(text, context);
GeneratedMarkerVisitor.markGenerated(statement);
return statement;
}
@NotNull
@Override
public PsiType createTypeFromText(@NotNull final String text, @Nullable final PsiElement context) throws IncorrectOperationException {
return createTypeInner(text, context, true);
}
@NotNull
@Override
public PsiTypeParameter createTypeParameterFromText(@NotNull final String text,
final PsiElement context) throws IncorrectOperationException {
final PsiTypeParameter typeParameter = super.createTypeParameterFromText(text, context);
GeneratedMarkerVisitor.markGenerated(typeParameter);
return typeParameter;
}
@NotNull
@Override
public PsiMethod createMethodFromText(@NotNull final String text,
final PsiElement context,
final LanguageLevel level) throws IncorrectOperationException {
final PsiMethod method = super.createMethodFromText(text, context, level);
GeneratedMarkerVisitor.markGenerated(method);
return method;
}
private static PsiImportStatementBase extractImport(final PsiJavaFile aFile, final boolean isStatic) {
final PsiImportList importList = aFile.getImportList();
assert importList != null : aFile;
final PsiImportStatementBase[] statements = isStatic ? importList.getImportStaticStatements() : importList.getImportStatements();
assert statements.length == 1 : aFile.getText();
return statements[0];
}
private static final JavaParserUtil.ParserWrapper CATCH_SECTION =
builder -> JavaParser.INSTANCE.getStatementParser().parseCatchBlock(builder);
@NotNull
@Override
public PsiCatchSection createCatchSection(@NotNull final PsiType exceptionType,
@NotNull final String exceptionName,
@Nullable final PsiElement context) throws IncorrectOperationException {
if (!(exceptionType instanceof PsiClassType || exceptionType instanceof PsiDisjunctionType)) {
throw new IncorrectOperationException("Unexpected type:" + exceptionType);
}
@NonNls final String text = "catch (" + exceptionType.getCanonicalText(true) + " " + exceptionName + ") {}";
final DummyHolder holder = DummyHolderFactory.createHolder(myManager, new JavaDummyElement(text, CATCH_SECTION, level(context)), context);
final PsiElement element = SourceTreeToPsiMap.treeElementToPsi(holder.getTreeElement().getFirstChildNode());
if (!(element instanceof PsiCatchSection)) {
throw new IncorrectOperationException("Incorrect catch section '" + text + "'. Parsed element: " + element);
}
final Project project = myManager.getProject();
final JavaPsiImplementationHelper helper = JavaPsiImplementationHelper.getInstance(project);
helper.setupCatchBlock(exceptionName, exceptionType, context, (PsiCatchSection)element);
final CodeStyleManager styleManager = CodeStyleManager.getInstance(project);
final PsiCatchSection catchSection = (PsiCatchSection)styleManager.reformat(element);
GeneratedMarkerVisitor.markGenerated(catchSection);
return catchSection;
}
@Override
public boolean isValidClassName(@NotNull String name) {
return isIdentifier(name);
}
@Override
public boolean isValidMethodName(@NotNull String name) {
return isIdentifier(name);
}
@Override
public boolean isValidParameterName(@NotNull String name) {
return isIdentifier(name);
}
@Override
public boolean isValidFieldName(@NotNull String name) {
return isIdentifier(name);
}
@Override
public boolean isValidLocalVariableName(@NotNull String name) {
return isIdentifier(name);
}
private boolean isIdentifier(@NotNull String name) {
return PsiNameHelper.getInstance(myManager.getProject()).isIdentifier(name);
}
}
|
// Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.analysis;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.actions.ActionOwner;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.Executor;
import com.google.devtools.build.lib.analysis.actions.AbstractFileWriteAction;
import com.google.devtools.build.lib.events.EventHandler;
import com.google.devtools.build.lib.util.Fingerprint;
import com.google.devtools.build.lib.util.Pair;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
/**
* Action to create a manifest of input files for processing by a subsequent
* build step (e.g. runfiles symlinking or archive building).
*
* <p>The manifest's format is specifiable by {@link ManifestType}, in
* accordance with the needs of the calling functionality.
*
* <p>Note that this action carefully avoids building the manifest content in
* memory.
*/
public class SourceManifestAction extends AbstractFileWriteAction {
private static final String GUID = "07459553-a3d0-4d37-9d78-18ed942470f4";
/**
* Interface for defining manifest formatting and reporting specifics.
*/
@VisibleForTesting
interface ManifestWriter {
/**
* Writes a single line of manifest output.
*
* @param manifestWriter the output stream
* @param rootRelativePath path of an entry relative to the manifest's root
* @param symlink (optional) symlink that resolves the above path
*/
void writeEntry(Writer manifestWriter, PathFragment rootRelativePath,
@Nullable Artifact symlink) throws IOException;
/**
* Fulfills {@link #ActionMetadata.getMnemonic()}
*/
String getMnemonic();
/**
* Fulfills {@link #AbstractAction.getRawProgressMessage()}
*/
String getRawProgressMessage();
}
/**
* The strategy we use to write manifest entries.
*/
private final ManifestWriter manifestWriter;
/**
* The runfiles for which to create the symlink tree.
*/
private final Runfiles runfiles;
/**
* Creates a new AbstractSourceManifestAction instance using latin1 encoding
* to write the manifest file and with a specified root path for manifest entries.
*
* @param manifestWriter the strategy to use to write manifest entries
* @param owner the action owner
* @param output the file to which to write the manifest
* @param runfiles runfiles
*/
private SourceManifestAction(ManifestWriter manifestWriter, ActionOwner owner, Artifact output,
Runfiles runfiles) {
super(owner, getDependencies(runfiles), output, false);
this.manifestWriter = manifestWriter;
this.runfiles = runfiles;
}
@VisibleForTesting
public void writeOutputFile(OutputStream out, EventHandler eventHandler)
throws IOException {
writeFile(out, runfiles.getRunfilesInputs(eventHandler, getOwner().getLocation()));
}
@Override
public DeterministicWriter newDeterministicWriter(EventHandler eventHandler, Executor executor)
throws IOException {
final Pair<Map<PathFragment, Artifact>, Map<PathFragment, Artifact>> runfilesInputs =
runfiles.getRunfilesInputs(eventHandler, getOwner().getLocation());
return new DeterministicWriter() {
@Override
public void writeOutputFile(OutputStream out) throws IOException {
writeFile(out, runfilesInputs);
}
};
}
/**
* Returns the input dependencies for this action. Note we don't need to create the symlink
* target Artifacts before we write the output manifest, so this Action does not have to
* depend on them. The only necessary dependencies are pruning manifests, which must be read
* to properly prune the tree.
*/
private static Collection<Artifact> getDependencies(Runfiles runfiles) {
ImmutableList.Builder<Artifact> builder = ImmutableList.builder();
for (Runfiles.PruningManifest manifest : runfiles.getPruningManifests()) {
builder.add(manifest.getManifestFile());
}
return builder.build();
}
/**
* Sort the entries in both the normal and root manifests and write the output
* file.
*
* @param out is the message stream to write errors to.
* @param output The actual mapping of the output manifest.
* @throws IOException
*/
private void writeFile(OutputStream out,
Pair<Map<PathFragment, Artifact>, Map<PathFragment, Artifact>> output)
throws IOException {
Writer manifestFile = new BufferedWriter(new OutputStreamWriter(out, ISO_8859_1));
Comparator<Map.Entry<PathFragment, Artifact>> fragmentComparator =
new Comparator<Map.Entry<PathFragment, Artifact>>() {
@Override
public int compare(Map.Entry<PathFragment, Artifact> path1,
Map.Entry<PathFragment, Artifact> path2) {
return path1.getKey().compareTo(path2.getKey());
}
};
List<Map.Entry<PathFragment, Artifact>> sortedRootLinks =
new ArrayList<>(output.second.entrySet());
Collections.sort(sortedRootLinks, fragmentComparator);
List<Map.Entry<PathFragment, Artifact>> sortedManifest =
new ArrayList<>(output.first.entrySet());
Collections.sort(sortedManifest, fragmentComparator);
for (Map.Entry<PathFragment, Artifact> line : sortedRootLinks) {
manifestWriter.writeEntry(manifestFile, line.getKey(), line.getValue());
}
for (Map.Entry<PathFragment, Artifact> line : sortedManifest) {
manifestWriter.writeEntry(manifestFile, line.getKey(), line.getValue());
}
manifestFile.flush();
}
@Override
public String getMnemonic() {
return manifestWriter.getMnemonic();
}
@Override
protected String getRawProgressMessage() {
return manifestWriter.getRawProgressMessage() + " for " + getOwner().getLabel();
}
@Override
protected String computeKey() {
Fingerprint f = new Fingerprint();
f.addString(GUID);
Map<PathFragment, Artifact> symlinks = runfiles.getSymlinksAsMap();
f.addInt(symlinks.size());
for (Map.Entry<PathFragment, Artifact> symlink : symlinks.entrySet()) {
f.addPath(symlink.getKey());
f.addPath(symlink.getValue().getPath());
}
Map<PathFragment, Artifact> rootSymlinks = runfiles.getRootSymlinksAsMap();
f.addInt(rootSymlinks.size());
for (Map.Entry<PathFragment, Artifact> rootSymlink : rootSymlinks.entrySet()) {
f.addPath(rootSymlink.getKey());
f.addPath(rootSymlink.getValue().getPath());
}
for (Artifact artifact : runfiles.getArtifactsWithoutMiddlemen()) {
f.addPath(artifact.getRootRelativePath());
f.addPath(artifact.getPath());
}
return f.hexDigestAndReset();
}
/**
* Supported manifest writing strategies.
*/
public static enum ManifestType implements ManifestWriter {
/**
* Writes each line as:
*
* [rootRelativePath] [resolvingSymlink]
*
* <p>This strategy is suitable for creating an input manifest to a source view tree. Its
* output is a valid input to {@link com.google.devtools.build.lib.analysis.SymlinkTreeAction}.
*/
SOURCE_SYMLINKS {
@Override
public void writeEntry(Writer manifestWriter, PathFragment rootRelativePath, Artifact symlink)
throws IOException {
manifestWriter.append(rootRelativePath.getPathString());
// This trailing whitespace is REQUIRED to process the single entry line correctly.
manifestWriter.append(' ');
if (symlink != null) {
manifestWriter.append(symlink.getPath().getPathString());
}
manifestWriter.append('\n');
}
@Override
public String getMnemonic() {
return "SourceSymlinkManifest";
}
@Override
public String getRawProgressMessage() {
return "Creating source manifest";
}
},
/**
* Writes each line as:
*
* [rootRelativePath]
*
* <p>This strategy is suitable for an input into a packaging system (notably .par) that
* consumes a list of all source files but needs that list to be constant with respect to
* how the user has their client laid out on local disk.
*/
SOURCES_ONLY {
@Override
public void writeEntry(Writer manifestWriter, PathFragment rootRelativePath, Artifact symlink)
throws IOException {
manifestWriter.append(rootRelativePath.getPathString());
manifestWriter.append('\n');
manifestWriter.flush();
}
@Override
public String getMnemonic() {
return "PackagingSourcesManifest";
}
@Override
public String getRawProgressMessage() {
return "Creating file sources list";
}
}
}
/** Creates an action for the given runfiles. */
public static SourceManifestAction forRunfiles(ManifestType manifestType, ActionOwner owner,
Artifact output, Runfiles runfiles) {
return new SourceManifestAction(manifestType, owner, output, runfiles);
}
/**
* Builder class to construct {@link SourceManifestAction} instances.
*/
public static final class Builder {
private final ManifestWriter manifestWriter;
private final ActionOwner owner;
private final Artifact output;
private final Runfiles.Builder runfilesBuilder = new Runfiles.Builder();
public Builder(ManifestType manifestType, ActionOwner owner, Artifact output) {
manifestWriter = manifestType;
this.owner = owner;
this.output = output;
}
@VisibleForTesting
Builder(ManifestWriter manifestWriter, ActionOwner owner, Artifact output) {
this.manifestWriter = manifestWriter;
this.owner = owner;
this.output = output;
}
public SourceManifestAction build() {
return new SourceManifestAction(manifestWriter, owner, output, runfilesBuilder.build());
}
/**
* Adds a set of symlinks from the artifacts' root-relative paths to the
* artifacts themselves.
*/
public Builder addSymlinks(Iterable<Artifact> artifacts) {
runfilesBuilder.addArtifacts(artifacts);
return this;
}
/**
* Adds a map of symlinks.
*/
public Builder addSymlinks(Map<PathFragment, Artifact> symlinks) {
runfilesBuilder.addSymlinks(symlinks);
return this;
}
/**
* Adds a single symlink.
*/
public Builder addSymlink(PathFragment link, Artifact target) {
runfilesBuilder.addSymlink(link, target);
return this;
}
/**
* <p>Adds a mapping of Artifacts to the directory above the normal symlink
* forest base.
*/
public Builder addRootSymlinks(Map<PathFragment, Artifact> rootSymlinks) {
runfilesBuilder.addRootSymlinks(rootSymlinks);
return this;
}
/**
* Set an expander function for the symlinks.
*/
@VisibleForTesting
Builder setSymlinksExpander(
Function<Map<PathFragment, Artifact>, Map<PathFragment, Artifact>> expander) {
runfilesBuilder.setManifestExpander(expander);
return this;
}
/**
* Adds a runfiles pruning manifest.
*/
@VisibleForTesting
Builder addPruningManifest(Runfiles.PruningManifest manifest) {
runfilesBuilder.addPruningManifest(manifest);
return this;
}
}
}
|
/*
* Copyright (c) 2011-2016 The original author or authors
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.it.service;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.eventbus.MessageConsumer;
import io.vertx.core.json.JsonObject;
import io.vertx.serviceproxy.ProxyHelper;
/**
* @author <a href="http://escoffier.me">Clement Escoffier</a>
*/
public class HelloServiceImpl implements HelloService {
private final String msg;
private MessageConsumer<JsonObject> service;
public HelloServiceImpl() {
this("Hello");
}
public HelloServiceImpl(String message) {
this.msg = message;
}
public void start(Vertx vertx, String address) {
service = ProxyHelper.registerService(HelloService.class, vertx, this, address);
}
public void stop() {
ProxyHelper.unregisterService(service);
}
@Override
public void hello(JsonObject name, Handler<AsyncResult<String>> resultHandler) {
resultHandler.handle(Future.succeededFuture(msg + " " + name.getString("name")));
}
}
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.admin.monitoring;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import static com.yahoo.vespa.model.admin.monitoring.DefaultVespaMetrics.defaultVespaMetricSet;
import static java.util.Collections.singleton;
/**
* Encapsulates vespa service metrics.
*
* @author gjoranv
*/
public class VespaMetricSet {
public static final MetricSet vespaMetricSet = new MetricSet("vespa",
getVespaMetrics(),
singleton(defaultVespaMetricSet));
private static Set<Metric> getVespaMetrics() {
Set<Metric> metrics = new LinkedHashSet<>();
metrics.addAll(getSearchNodeMetrics());
metrics.addAll(getStorageMetrics());
metrics.addAll(getDocprocMetrics());
metrics.addAll(getClusterControllerMetrics());
metrics.addAll(getQrserverMetrics());
metrics.addAll(getContainerMetrics());
metrics.addAll(getConfigServerMetrics());
metrics.addAll(getSentinelMetrics());
metrics.addAll(getOtherMetrics());
return Collections.unmodifiableSet(metrics);
}
private static Set<Metric> getSentinelMetrics() {
Set<Metric> metrics = new LinkedHashSet<>();
metrics.add(new Metric("sentinel.restarts.count"));
metrics.add(new Metric("sentinel.totalRestarts.last"));
metrics.add(new Metric("sentinel.uptime.last"));
metrics.add(new Metric("sentinel.running.count"));
metrics.add(new Metric("sentinel.running.last"));
return metrics;
}
private static Set<Metric> getOtherMetrics() {
Set<Metric> metrics = new LinkedHashSet<>();
metrics.add(new Metric("slobrok.heartbeats.failed.count"));
metrics.add(new Metric("logd.processed.lines.count"));
metrics.add(new Metric("worker.connections.max"));
// Java (JRT) TLS metrics
metrics.add(new Metric("jrt.transport.tls-certificate-verification-failures"));
metrics.add(new Metric("jrt.transport.peer-authorization-failures"));
metrics.add(new Metric("jrt.transport.server.tls-connections-established"));
metrics.add(new Metric("jrt.transport.client.tls-connections-established"));
metrics.add(new Metric("jrt.transport.server.unencrypted-connections-established"));
metrics.add(new Metric("jrt.transport.client.unencrypted-connections-established"));
// C++ TLS metrics
metrics.add(new Metric("vds.server.network.tls-handshakes-failed"));
metrics.add(new Metric("vds.server.network.peer-authorization-failures"));
metrics.add(new Metric("vds.server.network.client.tls-connections-established"));
metrics.add(new Metric("vds.server.network.server.tls-connections-established"));
metrics.add(new Metric("vds.server.network.client.insecure-connections-established"));
metrics.add(new Metric("vds.server.network.server.insecure-connections-established"));
metrics.add(new Metric("vds.server.network.tls-connections-broken"));
metrics.add(new Metric("vds.server.network.failed-tls-config-reloads"));
// C++ Fnet metrics
metrics.add(new Metric("vds.server.fnet.num-connections"));
return metrics;
}
private static Set<Metric> getConfigServerMetrics() {
Set<Metric> metrics =new LinkedHashSet<>();
metrics.add(new Metric("configserver.requests.count"));
metrics.add(new Metric("configserver.failedRequests.count"));
metrics.add(new Metric("configserver.latency.max"));
metrics.add(new Metric("configserver.latency.sum"));
metrics.add(new Metric("configserver.latency.count"));
metrics.add(new Metric("configserver.latency.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("configserver.cacheConfigElems.last"));
metrics.add(new Metric("configserver.cacheChecksumElems.last"));
metrics.add(new Metric("configserver.hosts.last"));
metrics.add(new Metric("configserver.delayedResponses.count"));
metrics.add(new Metric("configserver.sessionChangeErrors.count"));
metrics.add(new Metric("configserver.zkZNodes.last"));
metrics.add(new Metric("configserver.zkAvgLatency.last"));
metrics.add(new Metric("configserver.zkMaxLatency.last"));
metrics.add(new Metric("configserver.zkConnections.last"));
metrics.add(new Metric("configserver.zkOutstandingRequests.last"));
return metrics;
}
private static Set<Metric> getContainerMetrics() {
Set<Metric> metrics = new LinkedHashSet<>();
addMetric(metrics, "jdisc.http.requests", List.of("rate", "count"));
metrics.add(new Metric("handled.requests.count"));
metrics.add(new Metric("handled.latency.max"));
metrics.add(new Metric("handled.latency.sum"));
metrics.add(new Metric("handled.latency.count"));
metrics.add(new Metric("handled.latency.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("serverRejectedRequests.rate"));
metrics.add(new Metric("serverRejectedRequests.count"));
metrics.add(new Metric("serverThreadPoolSize.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("serverThreadPoolSize.min")); // TODO: Remove in Vespa 8
metrics.add(new Metric("serverThreadPoolSize.max"));
metrics.add(new Metric("serverThreadPoolSize.rate")); // TODO: Remove in Vespa 8
metrics.add(new Metric("serverThreadPoolSize.count")); // TODO: Remove in Vespa 8
metrics.add(new Metric("serverThreadPoolSize.last"));
metrics.add(new Metric("serverActiveThreads.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("serverActiveThreads.min"));
metrics.add(new Metric("serverActiveThreads.max"));
metrics.add(new Metric("serverActiveThreads.rate")); // TODO: Remove in Vespa 8
metrics.add(new Metric("serverActiveThreads.sum"));
metrics.add(new Metric("serverActiveThreads.count"));
metrics.add(new Metric("serverActiveThreads.last"));
metrics.add(new Metric("serverNumOpenConnections.average"));
metrics.add(new Metric("serverNumOpenConnections.max"));
metrics.add(new Metric("serverNumOpenConnections.last"));
metrics.add(new Metric("serverNumConnections.average"));
metrics.add(new Metric("serverNumConnections.max"));
metrics.add(new Metric("serverNumConnections.last"));
{
List<String> suffixes = List.of("sum", "count", "last", "min", "max");
addMetric(metrics, "jdisc.thread_pool.unhandled_exceptions", suffixes);
addMetric(metrics, "jdisc.thread_pool.work_queue.capacity", suffixes);
addMetric(metrics, "jdisc.thread_pool.work_queue.size", suffixes);
}
metrics.add(new Metric("httpapi_latency.max"));
metrics.add(new Metric("httpapi_latency.sum"));
metrics.add(new Metric("httpapi_latency.count"));
metrics.add(new Metric("httpapi_latency.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("httpapi_pending.max"));
metrics.add(new Metric("httpapi_pending.sum"));
metrics.add(new Metric("httpapi_pending.count"));
metrics.add(new Metric("httpapi_pending.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("httpapi_num_operations.rate"));
metrics.add(new Metric("httpapi_num_updates.rate"));
metrics.add(new Metric("httpapi_num_removes.rate"));
metrics.add(new Metric("httpapi_num_puts.rate"));
metrics.add(new Metric("httpapi_succeeded.rate"));
metrics.add(new Metric("httpapi_failed.rate"));
metrics.add(new Metric("httpapi_parse_error.rate"));
metrics.add(new Metric("mem.heap.total.average"));
metrics.add(new Metric("mem.heap.free.average"));
metrics.add(new Metric("mem.heap.used.average"));
metrics.add(new Metric("mem.heap.used.max"));
metrics.add(new Metric("jdisc.memory_mappings.max"));
metrics.add(new Metric("jdisc.open_file_descriptors.max"));
metrics.add(new Metric("jdisc.gc.count.average"));
metrics.add(new Metric("jdisc.gc.count.max"));
metrics.add(new Metric("jdisc.gc.count.last"));
metrics.add(new Metric("jdisc.gc.ms.average"));
metrics.add(new Metric("jdisc.gc.ms.max"));
metrics.add(new Metric("jdisc.gc.ms.last"));
metrics.add(new Metric("jdisc.deactivated_containers.total.last"));
metrics.add(new Metric("jdisc.deactivated_containers.with_retained_refs.last"));
metrics.add(new Metric("athenz-tenant-cert.expiry.seconds.last"));
metrics.add(new Metric("jdisc.http.request.prematurely_closed.rate"));
metrics.add(new Metric("http.status.1xx.rate"));
metrics.add(new Metric("http.status.2xx.rate"));
metrics.add(new Metric("http.status.3xx.rate"));
metrics.add(new Metric("http.status.4xx.rate"));
metrics.add(new Metric("http.status.5xx.rate"));
metrics.add(new Metric("http.status.401.rate"));
metrics.add(new Metric("http.status.403.rate"));
metrics.add(new Metric("jdisc.http.request.uri_length.max"));
metrics.add(new Metric("jdisc.http.request.uri_length.sum"));
metrics.add(new Metric("jdisc.http.request.uri_length.count"));
metrics.add(new Metric("jdisc.http.request.uri_length.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("jdisc.http.request.content_size.max"));
metrics.add(new Metric("jdisc.http.request.content_size.sum"));
metrics.add(new Metric("jdisc.http.request.content_size.count"));
metrics.add(new Metric("jdisc.http.request.content_size.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("jdisc.http.ssl.handshake.failure.missing_client_cert.rate"));
metrics.add(new Metric("jdisc.http.ssl.handshake.failure.expired_client_cert.rate"));
metrics.add(new Metric("jdisc.http.ssl.handshake.failure.invalid_client_cert.rate"));
metrics.add(new Metric("jdisc.http.ssl.handshake.failure.incompatible_protocols.rate"));
metrics.add(new Metric("jdisc.http.ssl.handshake.failure.incompatible_ciphers.rate"));
metrics.add(new Metric("jdisc.http.ssl.handshake.failure.unknown.rate"));
metrics.add(new Metric("jdisc.http.handler.unhandled_exceptions.rate"));
addMetric(metrics, "jdisc.http.jetty.threadpool.thread.max", List.of("last"));
addMetric(metrics, "jdisc.http.jetty.threadpool.thread.reserved", List.of("last"));
addMetric(metrics, "jdisc.http.jetty.threadpool.thread.busy", List.of("sum", "count", "min", "max"));
addMetric(metrics, "jdisc.http.jetty.threadpool.thread.total", List.of("sum", "count", "min", "max"));
addMetric(metrics, "jdisc.http.jetty.threadpool.queue.size", List.of("sum", "count", "min", "max"));
addMetric(metrics, "jdisc.http.filtering.request.handled", List.of("rate"));
addMetric(metrics, "jdisc.http.filtering.request.unhandled", List.of("rate"));
addMetric(metrics, "jdisc.http.filtering.response.handled", List.of("rate"));
addMetric(metrics, "jdisc.http.filtering.response.unhandled", List.of("rate"));
addMetric(metrics, "jdisc.application.failed_component_graphs", List.of("rate"));
addMetric(metrics, "jdisc.http.filter.rule.blocked_requests", List.of("rate"));
addMetric(metrics, "jdisc.http.filter.rule.allowed_requests", List.of("rate"));
return metrics;
}
private static Set<Metric> getClusterControllerMetrics() {
Set<Metric> metrics =new LinkedHashSet<>();
metrics.add(new Metric("cluster-controller.down.count.last"));
metrics.add(new Metric("cluster-controller.initializing.count.last"));
metrics.add(new Metric("cluster-controller.maintenance.count.last"));
metrics.add(new Metric("cluster-controller.retired.count.last"));
metrics.add(new Metric("cluster-controller.stopping.count.last"));
metrics.add(new Metric("cluster-controller.up.count.last"));
metrics.add(new Metric("cluster-controller.cluster-state-change.count"));
metrics.add(new Metric("cluster-controller.is-master.last"));
metrics.add(new Metric("cluster-controller.remote-task-queue.size.last"));
// TODO(hakonhall): Update this name once persistent "count" metrics has been implemented.
// DO NOT RELY ON THIS METRIC YET.
metrics.add(new Metric("cluster-controller.node-event.count"));
metrics.add(new Metric("cluster-controller.resource_usage.nodes_above_limit.last"));
metrics.add(new Metric("cluster-controller.resource_usage.max_memory_utilization.last"));
metrics.add(new Metric("cluster-controller.resource_usage.max_disk_utilization.last"));
metrics.add(new Metric("cluster-controller.resource_usage.disk_limit.last"));
metrics.add(new Metric("cluster-controller.resource_usage.memory_limit.last"));
metrics.add(new Metric("reindexing.progress.last"));
return metrics;
}
private static Set<Metric> getDocprocMetrics() {
Set<Metric> metrics = new LinkedHashSet<>();
// per chain
metrics.add(new Metric("documents_processed.rate"));
return metrics;
}
private static Set<Metric> getQrserverMetrics() {
Set<Metric> metrics = new LinkedHashSet<>();
metrics.add(new Metric("peak_qps.max"));
metrics.add(new Metric("search_connections.max"));
metrics.add(new Metric("search_connections.sum"));
metrics.add(new Metric("search_connections.count"));
metrics.add(new Metric("search_connections.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("feed.latency.max"));
metrics.add(new Metric("feed.latency.sum"));
metrics.add(new Metric("feed.latency.count"));
metrics.add(new Metric("feed.latency.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("feed.http-requests.count"));
metrics.add(new Metric("feed.http-requests.rate"));
metrics.add(new Metric("queries.rate"));
metrics.add(new Metric("query_container_latency.max"));
metrics.add(new Metric("query_container_latency.sum"));
metrics.add(new Metric("query_container_latency.count"));
metrics.add(new Metric("query_container_latency.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("query_latency.max"));
metrics.add(new Metric("query_latency.sum"));
metrics.add(new Metric("query_latency.count"));
metrics.add(new Metric("query_latency.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("query_latency.95percentile"));
metrics.add(new Metric("query_latency.99percentile"));
metrics.add(new Metric("failed_queries.rate"));
metrics.add(new Metric("degraded_queries.rate"));
metrics.add(new Metric("hits_per_query.max"));
metrics.add(new Metric("hits_per_query.sum"));
metrics.add(new Metric("hits_per_query.count"));
metrics.add(new Metric("hits_per_query.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("hits_per_query.95percentile"));
metrics.add(new Metric("hits_per_query.99percentile"));
metrics.add(new Metric("query_hit_offset.max"));
metrics.add(new Metric("query_hit_offset.sum"));
metrics.add(new Metric("query_hit_offset.count"));
metrics.add(new Metric("documents_covered.count"));
metrics.add(new Metric("documents_total.count"));
metrics.add(new Metric("dispatch_internal.rate"));
metrics.add(new Metric("dispatch_fdispatch.rate"));
metrics.add(new Metric("totalhits_per_query.max"));
metrics.add(new Metric("totalhits_per_query.sum"));
metrics.add(new Metric("totalhits_per_query.count"));
metrics.add(new Metric("totalhits_per_query.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("totalhits_per_query.95percentile"));
metrics.add(new Metric("totalhits_per_query.99percentile"));
metrics.add(new Metric("empty_results.rate"));
metrics.add(new Metric("requestsOverQuota.rate"));
metrics.add(new Metric("requestsOverQuota.count"));
metrics.add(new Metric("relevance.at_1.sum"));
metrics.add(new Metric("relevance.at_1.count"));
metrics.add(new Metric("relevance.at_1.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("relevance.at_3.sum"));
metrics.add(new Metric("relevance.at_3.count"));
metrics.add(new Metric("relevance.at_3.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("relevance.at_10.sum"));
metrics.add(new Metric("relevance.at_10.count"));
metrics.add(new Metric("relevance.at_10.average")); // TODO: Remove in Vespa 8
// Errors from qrserver
metrics.add(new Metric("error.timeout.rate"));
metrics.add(new Metric("error.backends_oos.rate"));
metrics.add(new Metric("error.plugin_failure.rate"));
metrics.add(new Metric("error.backend_communication_error.rate"));
metrics.add(new Metric("error.empty_document_summaries.rate"));
metrics.add(new Metric("error.invalid_query_parameter.rate"));
metrics.add(new Metric("error.internal_server_error.rate"));
metrics.add(new Metric("error.misconfigured_server.rate"));
metrics.add(new Metric("error.invalid_query_transformation.rate"));
metrics.add(new Metric("error.result_with_errors.rate"));
metrics.add(new Metric("error.unspecified.rate"));
metrics.add(new Metric("error.unhandled_exception.rate"));
return metrics;
}
private static void addSearchNodeExecutorMetrics(Set<Metric> metrics, String prefix) {
metrics.add(new Metric(prefix + ".queuesize.max"));
metrics.add(new Metric(prefix + ".queuesize.sum"));
metrics.add(new Metric(prefix + ".queuesize.count"));
metrics.add(new Metric(prefix + ".maxpending.last")); // TODO: Remove in Vespa 8
metrics.add(new Metric(prefix + ".accepted.rate"));
}
private static Set<Metric> getSearchNodeMetrics() {
Set<Metric> metrics = new LinkedHashSet<>();
metrics.add(new Metric("content.proton.documentdb.documents.total.last"));
metrics.add(new Metric("content.proton.documentdb.documents.ready.last"));
metrics.add(new Metric("content.proton.documentdb.documents.active.last"));
metrics.add(new Metric("content.proton.documentdb.documents.removed.last"));
metrics.add(new Metric("content.proton.documentdb.index.docs_in_memory.last"));
metrics.add(new Metric("content.proton.documentdb.disk_usage.last"));
metrics.add(new Metric("content.proton.documentdb.memory_usage.allocated_bytes.max"));
metrics.add(new Metric("content.proton.transport.query.count.rate"));
metrics.add(new Metric("content.proton.docsum.docs.rate"));
metrics.add(new Metric("content.proton.docsum.latency.max"));
metrics.add(new Metric("content.proton.docsum.latency.sum"));
metrics.add(new Metric("content.proton.docsum.latency.count"));
metrics.add(new Metric("content.proton.docsum.latency.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("content.proton.transport.query.latency.max"));
metrics.add(new Metric("content.proton.transport.query.latency.sum"));
metrics.add(new Metric("content.proton.transport.query.latency.count"));
metrics.add(new Metric("content.proton.transport.query.latency.average")); // TODO: Remove in Vespa 8
// Search protocol
metrics.add(new Metric("content.proton.search_protocol.query.latency.max"));
metrics.add(new Metric("content.proton.search_protocol.query.latency.sum"));
metrics.add(new Metric("content.proton.search_protocol.query.latency.count"));
metrics.add(new Metric("content.proton.search_protocol.query.request_size.max"));
metrics.add(new Metric("content.proton.search_protocol.query.request_size.sum"));
metrics.add(new Metric("content.proton.search_protocol.query.request_size.count"));
metrics.add(new Metric("content.proton.search_protocol.query.reply_size.max"));
metrics.add(new Metric("content.proton.search_protocol.query.reply_size.sum"));
metrics.add(new Metric("content.proton.search_protocol.query.reply_size.count"));
metrics.add(new Metric("content.proton.search_protocol.docsum.latency.max"));
metrics.add(new Metric("content.proton.search_protocol.docsum.latency.sum"));
metrics.add(new Metric("content.proton.search_protocol.docsum.latency.count"));
metrics.add(new Metric("content.proton.search_protocol.docsum.request_size.max"));
metrics.add(new Metric("content.proton.search_protocol.docsum.request_size.sum"));
metrics.add(new Metric("content.proton.search_protocol.docsum.request_size.count"));
metrics.add(new Metric("content.proton.search_protocol.docsum.reply_size.max"));
metrics.add(new Metric("content.proton.search_protocol.docsum.reply_size.sum"));
metrics.add(new Metric("content.proton.search_protocol.docsum.reply_size.count"));
metrics.add(new Metric("content.proton.search_protocol.docsum.requested_documents.count"));
// Executors shared between all document dbs
addSearchNodeExecutorMetrics(metrics, "content.proton.executor.proton");
addSearchNodeExecutorMetrics(metrics, "content.proton.executor.flush");
addSearchNodeExecutorMetrics(metrics, "content.proton.executor.match");
addSearchNodeExecutorMetrics(metrics, "content.proton.executor.docsum");
addSearchNodeExecutorMetrics(metrics, "content.proton.executor.shared");
addSearchNodeExecutorMetrics(metrics, "content.proton.executor.warmup");
// jobs
metrics.add(new Metric("content.proton.documentdb.job.total.average"));
metrics.add(new Metric("content.proton.documentdb.job.attribute_flush.average"));
metrics.add(new Metric("content.proton.documentdb.job.memory_index_flush.average"));
metrics.add(new Metric("content.proton.documentdb.job.disk_index_fusion.average"));
metrics.add(new Metric("content.proton.documentdb.job.document_store_flush.average"));
metrics.add(new Metric("content.proton.documentdb.job.document_store_compact.average"));
metrics.add(new Metric("content.proton.documentdb.job.bucket_move.average"));
metrics.add(new Metric("content.proton.documentdb.job.lid_space_compact.average"));
metrics.add(new Metric("content.proton.documentdb.job.removed_documents_prune.average"));
// Threading service (per document db)
addSearchNodeExecutorMetrics(metrics, "content.proton.documentdb.threading_service.master");
addSearchNodeExecutorMetrics(metrics, "content.proton.documentdb.threading_service.index");
addSearchNodeExecutorMetrics(metrics, "content.proton.documentdb.threading_service.summary");
addSearchNodeExecutorMetrics(metrics, "content.proton.documentdb.threading_service.index_field_inverter");
addSearchNodeExecutorMetrics(metrics, "content.proton.documentdb.threading_service.index_field_writer");
addSearchNodeExecutorMetrics(metrics, "content.proton.documentdb.threading_service.attribute_field_writer");
// lid space
metrics.add(new Metric("content.proton.documentdb.ready.lid_space.lid_bloat_factor.average"));
metrics.add(new Metric("content.proton.documentdb.notready.lid_space.lid_bloat_factor.average"));
metrics.add(new Metric("content.proton.documentdb.removed.lid_space.lid_bloat_factor.average"));
metrics.add(new Metric("content.proton.documentdb.ready.lid_space.lid_fragmentation_factor.average"));
metrics.add(new Metric("content.proton.documentdb.notready.lid_space.lid_fragmentation_factor.average"));
metrics.add(new Metric("content.proton.documentdb.removed.lid_space.lid_fragmentation_factor.average"));
metrics.add(new Metric("content.proton.documentdb.ready.lid_space.lid_limit.last"));
metrics.add(new Metric("content.proton.documentdb.notready.lid_space.lid_limit.last"));
metrics.add(new Metric("content.proton.documentdb.removed.lid_space.lid_limit.last"));
metrics.add(new Metric("content.proton.documentdb.ready.lid_space.highest_used_lid.last"));
metrics.add(new Metric("content.proton.documentdb.notready.lid_space.highest_used_lid.last"));
metrics.add(new Metric("content.proton.documentdb.removed.lid_space.highest_used_lid.last"));
metrics.add(new Metric("content.proton.documentdb.ready.lid_space.used_lids.last"));
metrics.add(new Metric("content.proton.documentdb.notready.lid_space.used_lids.last"));
metrics.add(new Metric("content.proton.documentdb.removed.lid_space.used_lids.last"));
// bucket move
metrics.add(new Metric("content.proton.documentdb.bucket_move.buckets_pending.last"));
// resource usage
metrics.add(new Metric("content.proton.resource_usage.disk.average"));
metrics.add(new Metric("content.proton.resource_usage.disk_utilization.average"));
metrics.add(new Metric("content.proton.resource_usage.memory.average"));
metrics.add(new Metric("content.proton.resource_usage.memory_utilization.average"));
metrics.add(new Metric("content.proton.resource_usage.transient_memory.average"));
metrics.add(new Metric("content.proton.resource_usage.transient_disk.average"));
metrics.add(new Metric("content.proton.resource_usage.memory_mappings.max"));
metrics.add(new Metric("content.proton.resource_usage.open_file_descriptors.max"));
metrics.add(new Metric("content.proton.resource_usage.feeding_blocked.max"));
metrics.add(new Metric("content.proton.documentdb.attribute.resource_usage.enum_store.average"));
metrics.add(new Metric("content.proton.documentdb.attribute.resource_usage.multi_value.average"));
metrics.add(new Metric("content.proton.documentdb.attribute.resource_usage.feeding_blocked.last")); // TODO: Remove in Vespa 8
metrics.add(new Metric("content.proton.documentdb.attribute.resource_usage.feeding_blocked.max"));
// transaction log
metrics.add(new Metric("content.proton.transactionlog.entries.average"));
metrics.add(new Metric("content.proton.transactionlog.disk_usage.average"));
metrics.add(new Metric("content.proton.transactionlog.replay_time.last"));
// document store
metrics.add(new Metric("content.proton.documentdb.ready.document_store.disk_usage.average"));
metrics.add(new Metric("content.proton.documentdb.ready.document_store.disk_bloat.average"));
metrics.add(new Metric("content.proton.documentdb.ready.document_store.max_bucket_spread.average"));
metrics.add(new Metric("content.proton.documentdb.ready.document_store.memory_usage.allocated_bytes.average"));
metrics.add(new Metric("content.proton.documentdb.ready.document_store.memory_usage.used_bytes.average"));
metrics.add(new Metric("content.proton.documentdb.ready.document_store.memory_usage.dead_bytes.average"));
metrics.add(new Metric("content.proton.documentdb.ready.document_store.memory_usage.onhold_bytes.average"));
metrics.add(new Metric("content.proton.documentdb.notready.document_store.disk_usage.average"));
metrics.add(new Metric("content.proton.documentdb.notready.document_store.disk_bloat.average"));
metrics.add(new Metric("content.proton.documentdb.notready.document_store.max_bucket_spread.average"));
metrics.add(new Metric("content.proton.documentdb.notready.document_store.memory_usage.allocated_bytes.average"));
metrics.add(new Metric("content.proton.documentdb.notready.document_store.memory_usage.used_bytes.average"));
metrics.add(new Metric("content.proton.documentdb.notready.document_store.memory_usage.dead_bytes.average"));
metrics.add(new Metric("content.proton.documentdb.notready.document_store.memory_usage.onhold_bytes.average"));
metrics.add(new Metric("content.proton.documentdb.removed.document_store.disk_usage.average"));
metrics.add(new Metric("content.proton.documentdb.removed.document_store.disk_bloat.average"));
metrics.add(new Metric("content.proton.documentdb.removed.document_store.max_bucket_spread.average"));
metrics.add(new Metric("content.proton.documentdb.removed.document_store.memory_usage.allocated_bytes.average"));
metrics.add(new Metric("content.proton.documentdb.removed.document_store.memory_usage.used_bytes.average"));
metrics.add(new Metric("content.proton.documentdb.removed.document_store.memory_usage.dead_bytes.average"));
metrics.add(new Metric("content.proton.documentdb.removed.document_store.memory_usage.onhold_bytes.average"));
// document store cache
metrics.add(new Metric("content.proton.documentdb.ready.document_store.cache.memory_usage.average"));
metrics.add(new Metric("content.proton.documentdb.ready.document_store.cache.hit_rate.average"));
metrics.add(new Metric("content.proton.documentdb.ready.document_store.cache.lookups.rate"));
metrics.add(new Metric("content.proton.documentdb.ready.document_store.cache.invalidations.rate"));
metrics.add(new Metric("content.proton.documentdb.notready.document_store.cache.memory_usage.average"));
metrics.add(new Metric("content.proton.documentdb.notready.document_store.cache.hit_rate.average"));
metrics.add(new Metric("content.proton.documentdb.notready.document_store.cache.lookups.rate"));
metrics.add(new Metric("content.proton.documentdb.notready.document_store.cache.invalidations.rate"));
// attribute
metrics.add(new Metric("content.proton.documentdb.ready.attribute.memory_usage.allocated_bytes.average"));
metrics.add(new Metric("content.proton.documentdb.ready.attribute.memory_usage.used_bytes.average"));
metrics.add(new Metric("content.proton.documentdb.ready.attribute.memory_usage.dead_bytes.average"));
metrics.add(new Metric("content.proton.documentdb.ready.attribute.memory_usage.onhold_bytes.average"));
metrics.add(new Metric("content.proton.documentdb.notready.attribute.memory_usage.allocated_bytes.average"));
metrics.add(new Metric("content.proton.documentdb.notready.attribute.memory_usage.used_bytes.average"));
metrics.add(new Metric("content.proton.documentdb.notready.attribute.memory_usage.dead_bytes.average"));
metrics.add(new Metric("content.proton.documentdb.notready.attribute.memory_usage.onhold_bytes.average"));
// index
metrics.add(new Metric("content.proton.documentdb.index.memory_usage.allocated_bytes.average"));
metrics.add(new Metric("content.proton.documentdb.index.memory_usage.used_bytes.average"));
metrics.add(new Metric("content.proton.documentdb.index.memory_usage.dead_bytes.average"));
metrics.add(new Metric("content.proton.documentdb.index.memory_usage.onhold_bytes.average"));
// matching
metrics.add(new Metric("content.proton.documentdb.matching.queries.rate"));
metrics.add(new Metric("content.proton.documentdb.matching.soft_doomed_queries.rate"));
metrics.add(new Metric("content.proton.documentdb.matching.query_latency.max"));
metrics.add(new Metric("content.proton.documentdb.matching.query_latency.sum"));
metrics.add(new Metric("content.proton.documentdb.matching.query_latency.count"));
metrics.add(new Metric("content.proton.documentdb.matching.query_latency.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("content.proton.documentdb.matching.query_collateral_time.max")); // TODO: Remove in Vespa 8
metrics.add(new Metric("content.proton.documentdb.matching.query_collateral_time.sum")); // TODO: Remove in Vespa 8
metrics.add(new Metric("content.proton.documentdb.matching.query_collateral_time.count")); // TODO: Remove in Vespa 8
metrics.add(new Metric("content.proton.documentdb.matching.query_collateral_time.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("content.proton.documentdb.matching.query_setup_time.max"));
metrics.add(new Metric("content.proton.documentdb.matching.query_setup_time.sum"));
metrics.add(new Metric("content.proton.documentdb.matching.query_setup_time.count"));
metrics.add(new Metric("content.proton.documentdb.matching.docs_matched.rate")); // TODO: Consider remove in Vespa 8
metrics.add(new Metric("content.proton.documentdb.matching.docs_matched.max"));
metrics.add(new Metric("content.proton.documentdb.matching.docs_matched.sum"));
metrics.add(new Metric("content.proton.documentdb.matching.docs_matched.count"));
metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.queries.rate"));
metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.soft_doomed_queries.rate"));
metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.soft_doom_factor.min"));
metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.soft_doom_factor.max"));
metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.soft_doom_factor.sum"));
metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.soft_doom_factor.count"));
metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.query_latency.max"));
metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.query_latency.sum"));
metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.query_latency.count"));
metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.query_latency.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.query_collateral_time.max")); // TODO: Remove in Vespa 8
metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.query_collateral_time.sum")); // TODO: Remove in Vespa 8
metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.query_collateral_time.count")); // TODO: Remove in Vespa 8
metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.query_collateral_time.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.query_setup_time.max"));
metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.query_setup_time.sum"));
metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.query_setup_time.count"));
metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.rerank_time.max"));
metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.rerank_time.sum"));
metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.rerank_time.count"));
metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.rerank_time.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.docs_matched.rate")); // TODO: Consider remove in Vespa 8
metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.docs_matched.max"));
metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.docs_matched.sum"));
metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.docs_matched.count"));
metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.limited_queries.rate"));
return metrics;
}
private static Set<Metric> getStorageMetrics() {
Set<Metric> metrics = new LinkedHashSet<>();
// TODO: For the purpose of this file and likely elsewhere, all but the last aggregate specifier,
// TODO: such as 'average' and 'sum' in the metric names below are just confusing and can be mentally
// TODO: disregarded when considering metric names. Consider cleaning up for Vespa 8.
// TODO Vespa 8 all metrics with .sum in the name should have that removed.
metrics.add(new Metric("vds.datastored.alldisks.docs.average"));
metrics.add(new Metric("vds.datastored.alldisks.bytes.average"));
metrics.add(new Metric("vds.visitor.allthreads.averagevisitorlifetime.sum.max"));
metrics.add(new Metric("vds.visitor.allthreads.averagevisitorlifetime.sum.sum"));
metrics.add(new Metric("vds.visitor.allthreads.averagevisitorlifetime.sum.count"));
metrics.add(new Metric("vds.visitor.allthreads.averagevisitorlifetime.sum.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("vds.visitor.allthreads.averagequeuewait.sum.max"));
metrics.add(new Metric("vds.visitor.allthreads.averagequeuewait.sum.sum"));
metrics.add(new Metric("vds.visitor.allthreads.averagequeuewait.sum.count"));
metrics.add(new Metric("vds.visitor.allthreads.averagequeuewait.sum.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("vds.filestor.alldisks.allthreads.put.sum.count.rate"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.remove.sum.count.rate"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.get.sum.count.rate"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.update.sum.count.rate"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.createiterator.count.rate"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.visit.sum.count.rate"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.remove_location.sum.count.rate"));
metrics.add(new Metric("vds.filestor.alldisks.queuesize.max"));
metrics.add(new Metric("vds.filestor.alldisks.queuesize.sum"));
metrics.add(new Metric("vds.filestor.alldisks.queuesize.count"));
metrics.add(new Metric("vds.filestor.alldisks.queuesize.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("vds.filestor.alldisks.averagequeuewait.sum.max"));
metrics.add(new Metric("vds.filestor.alldisks.averagequeuewait.sum.sum"));
metrics.add(new Metric("vds.filestor.alldisks.averagequeuewait.sum.count"));
metrics.add(new Metric("vds.filestor.alldisks.averagequeuewait.sum.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("vds.filestor.alldisks.allthreads.mergemetadatareadlatency.max"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.mergemetadatareadlatency.sum"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.mergemetadatareadlatency.count"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.mergedatareadlatency.max"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.mergedatareadlatency.sum"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.mergedatareadlatency.count"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.mergedatawritelatency.max"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.mergedatawritelatency.sum"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.mergedatawritelatency.count"));
metrics.add(new Metric("vds.visitor.allthreads.queuesize.count.max"));
metrics.add(new Metric("vds.visitor.allthreads.queuesize.count.sum"));
metrics.add(new Metric("vds.visitor.allthreads.queuesize.count.count"));
metrics.add(new Metric("vds.visitor.allthreads.queuesize.count.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("vds.visitor.allthreads.completed.sum.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("vds.visitor.allthreads.completed.sum.rate"));
metrics.add(new Metric("vds.visitor.allthreads.created.sum.rate"));
metrics.add(new Metric("vds.visitor.allthreads.failed.sum.rate"));
metrics.add(new Metric("vds.visitor.allthreads.averagemessagesendtime.sum.max"));
metrics.add(new Metric("vds.visitor.allthreads.averagemessagesendtime.sum.sum"));
metrics.add(new Metric("vds.visitor.allthreads.averagemessagesendtime.sum.count"));
metrics.add(new Metric("vds.visitor.allthreads.averagemessagesendtime.sum.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("vds.visitor.allthreads.averageprocessingtime.sum.max"));
metrics.add(new Metric("vds.visitor.allthreads.averageprocessingtime.sum.sum"));
metrics.add(new Metric("vds.visitor.allthreads.averageprocessingtime.sum.count"));
metrics.add(new Metric("vds.visitor.allthreads.averageprocessingtime.sum.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("vds.filestor.alldisks.allthreads.put.sum.count.rate"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.put.sum.failed.rate"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.put.sum.test_and_set_failed.rate"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.put.sum.latency.max"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.put.sum.latency.sum"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.put.sum.latency.count"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.put.sum.latency.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("vds.filestor.alldisks.allthreads.put.sum.request_size.max"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.put.sum.request_size.sum"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.put.sum.request_size.count"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.remove.sum.count.rate"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.remove.sum.failed.rate"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.remove.sum.test_and_set_failed.rate"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.remove.sum.latency.max"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.remove.sum.latency.sum"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.remove.sum.latency.count"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.remove.sum.latency.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("vds.filestor.alldisks.allthreads.remove.sum.request_size.max"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.remove.sum.request_size.sum"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.remove.sum.request_size.count"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.get.sum.count.rate"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.get.sum.failed.rate"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.get.sum.latency.max"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.get.sum.latency.sum"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.get.sum.latency.count"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.get.sum.latency.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("vds.filestor.alldisks.allthreads.get.sum.request_size.max"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.get.sum.request_size.sum"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.get.sum.request_size.count"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.update.sum.count.rate"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.update.sum.failed.rate"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.update.sum.test_and_set_failed.rate"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.update.sum.latency.max"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.update.sum.latency.sum"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.update.sum.latency.count"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.update.sum.latency.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("vds.filestor.alldisks.allthreads.update.sum.request_size.max"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.update.sum.request_size.sum"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.update.sum.request_size.count"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.createiterator.latency.max"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.createiterator.latency.sum"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.createiterator.latency.count"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.createiterator.latency.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("vds.filestor.alldisks.allthreads.visit.sum.latency.max"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.visit.sum.latency.sum"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.visit.sum.latency.count"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.visit.sum.latency.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("vds.filestor.alldisks.allthreads.remove_location.sum.latency.max"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.remove_location.sum.latency.sum"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.remove_location.sum.latency.count"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.remove_location.sum.latency.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("vds.filestor.alldisks.allthreads.splitbuckets.count.rate"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.joinbuckets.count.rate"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.deletebuckets.count.rate"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.deletebuckets.failed.rate"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.deletebuckets.latency.max"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.deletebuckets.latency.sum"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.deletebuckets.latency.count"));
metrics.add(new Metric("vds.filestor.alldisks.allthreads.deletebuckets.latency.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("vds.filestor.alldisks.allthreads.setbucketstates.count.rate"));
//Distributor
metrics.add(new Metric("vds.idealstate.buckets_rechecking.average"));
metrics.add(new Metric("vds.idealstate.idealstate_diff.average"));
metrics.add(new Metric("vds.idealstate.buckets_toofewcopies.average"));
metrics.add(new Metric("vds.idealstate.buckets_toomanycopies.average"));
metrics.add(new Metric("vds.idealstate.buckets.average"));
metrics.add(new Metric("vds.idealstate.buckets_notrusted.average"));
metrics.add(new Metric("vds.idealstate.delete_bucket.done_ok.rate"));
metrics.add(new Metric("vds.idealstate.delete_bucket.done_failed.rate"));
metrics.add(new Metric("vds.idealstate.delete_bucket.pending.average"));
metrics.add(new Metric("vds.idealstate.merge_bucket.done_ok.rate"));
metrics.add(new Metric("vds.idealstate.merge_bucket.done_failed.rate"));
metrics.add(new Metric("vds.idealstate.merge_bucket.pending.average"));
metrics.add(new Metric("vds.idealstate.split_bucket.done_ok.rate"));
metrics.add(new Metric("vds.idealstate.split_bucket.done_failed.rate"));
metrics.add(new Metric("vds.idealstate.split_bucket.pending.average"));
metrics.add(new Metric("vds.idealstate.join_bucket.done_ok.rate"));
metrics.add(new Metric("vds.idealstate.join_bucket.done_failed.rate"));
metrics.add(new Metric("vds.idealstate.join_bucket.pending.average"));
metrics.add(new Metric("vds.idealstate.garbage_collection.done_ok.rate"));
metrics.add(new Metric("vds.idealstate.garbage_collection.done_failed.rate"));
metrics.add(new Metric("vds.idealstate.garbage_collection.pending.average"));
metrics.add(new Metric("vds.idealstate.garbage_collection.documents_removed.count"));
metrics.add(new Metric("vds.idealstate.garbage_collection.documents_removed.rate"));
metrics.add(new Metric("vds.distributor.puts.sum.latency.max"));
metrics.add(new Metric("vds.distributor.puts.sum.latency.sum"));
metrics.add(new Metric("vds.distributor.puts.sum.latency.count"));
metrics.add(new Metric("vds.distributor.puts.sum.latency.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("vds.distributor.puts.sum.ok.rate"));
metrics.add(new Metric("vds.distributor.puts.sum.failures.total.rate"));
metrics.add(new Metric("vds.distributor.puts.sum.failures.notfound.rate"));
metrics.add(new Metric("vds.distributor.puts.sum.failures.test_and_set_failed.rate"));
metrics.add(new Metric("vds.distributor.puts.sum.failures.concurrent_mutations.rate"));
metrics.add(new Metric("vds.distributor.removes.sum.latency.max"));
metrics.add(new Metric("vds.distributor.removes.sum.latency.sum"));
metrics.add(new Metric("vds.distributor.removes.sum.latency.count"));
metrics.add(new Metric("vds.distributor.removes.sum.latency.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("vds.distributor.removes.sum.ok.rate"));
metrics.add(new Metric("vds.distributor.removes.sum.failures.total.rate"));
metrics.add(new Metric("vds.distributor.removes.sum.failures.notfound.rate"));
metrics.add(new Metric("vds.distributor.removes.sum.failures.test_and_set_failed.rate"));
metrics.add(new Metric("vds.distributor.removes.sum.failures.concurrent_mutations.rate"));
metrics.add(new Metric("vds.distributor.updates.sum.latency.max"));
metrics.add(new Metric("vds.distributor.updates.sum.latency.sum"));
metrics.add(new Metric("vds.distributor.updates.sum.latency.count"));
metrics.add(new Metric("vds.distributor.updates.sum.latency.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("vds.distributor.updates.sum.ok.rate"));
metrics.add(new Metric("vds.distributor.updates.sum.failures.total.rate"));
metrics.add(new Metric("vds.distributor.updates.sum.failures.notfound.rate"));
metrics.add(new Metric("vds.distributor.updates.sum.failures.test_and_set_failed.rate"));
metrics.add(new Metric("vds.distributor.updates.sum.failures.concurrent_mutations.rate"));
metrics.add(new Metric("vds.distributor.updates.sum.diverging_timestamp_updates.rate"));
metrics.add(new Metric("vds.distributor.removelocations.sum.ok.rate"));
metrics.add(new Metric("vds.distributor.removelocations.sum.failures.total.rate"));
metrics.add(new Metric("vds.distributor.gets.sum.latency.max"));
metrics.add(new Metric("vds.distributor.gets.sum.latency.sum"));
metrics.add(new Metric("vds.distributor.gets.sum.latency.count"));
metrics.add(new Metric("vds.distributor.gets.sum.latency.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("vds.distributor.gets.sum.ok.rate"));
metrics.add(new Metric("vds.distributor.gets.sum.failures.total.rate"));
metrics.add(new Metric("vds.distributor.gets.sum.failures.notfound.rate"));
metrics.add(new Metric("vds.distributor.visitor.sum.latency.max"));
metrics.add(new Metric("vds.distributor.visitor.sum.latency.sum"));
metrics.add(new Metric("vds.distributor.visitor.sum.latency.count"));
metrics.add(new Metric("vds.distributor.visitor.sum.latency.average")); // TODO: Remove in Vespa 8
metrics.add(new Metric("vds.distributor.visitor.sum.ok.rate"));
metrics.add(new Metric("vds.distributor.visitor.sum.failures.total.rate"));
metrics.add(new Metric("vds.distributor.docsstored.average"));
metrics.add(new Metric("vds.distributor.bytesstored.average"));
metrics.add(new Metric("vds.bouncer.clock_skew_aborts.count"));
return metrics;
}
private static void addMetric(Set<Metric> metrics, String metricName, List<String> aggregateSuffices) {
for (String suffix : aggregateSuffices) {
metrics.add(new Metric(metricName + "." + suffix));
}
}
}
|
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* ____ _ _____ _
* / ___| _ __ _ __(_)_ __ __ |_ _| _ _ __| |__ ___
* \___ \| '_ \| '__| | '_ \ / _` || || | | | '__| '_ \ / _ \
* ___) | |_) | | | | | | | (_| || || |_| | | | |_) | (_) |
* |____/| .__/|_| |_|_| |_|\__, ||_| \__,_|_| |_.__/ \___/
* |_| |___/ https://github.com/yingzhuo/spring-turbo
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
package spring.turbo.io;
import java.io.IOException;
import java.io.InputStream;
/**
* @author 应卓
* @since 1.0.8
*/
public final class EmptyInputStream extends InputStream {
private EmptyInputStream() {
super();
}
public static EmptyInputStream getInstance() {
return SyncAvoid.INSTANCE;
}
@Override
public int read() throws IOException {
return -1;
}
// 延迟加载
private static class SyncAvoid {
private static final EmptyInputStream INSTANCE = new EmptyInputStream();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.