text
stringlengths 7
1.01M
|
|---|
package me.zhengjie.service.impl;
import lombok.RequiredArgsConstructor;
import me.zhengjie.domain.Supplier;
import me.zhengjie.domain.SupplierContact;
import me.zhengjie.domain.SupplierCusAudit;
import me.zhengjie.exception.EntityExistException;
import me.zhengjie.repository.SupplierCusAuditRepository;
import me.zhengjie.repository.SupplierRepository;
import me.zhengjie.service.SupplierCusAuditService;
import me.zhengjie.service.dto.SupplierCusAuditReplaceDto;
import me.zhengjie.utils.ValidationUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Set;
/**
* @author tmj
* @version 1.0
* @date 2021/12/1 14:07
*/
@Service
@RequiredArgsConstructor
public class SupplierCusAuditServiceImpl implements SupplierCusAuditService {
private final SupplierRepository supplierRepository;
private final SupplierCusAuditRepository cusAuditRepository;
@Override
public List<SupplierCusAudit> findBySupplierId(Long supplierId) {
return cusAuditRepository.findBySupplierId(supplierId);
}
@Override
@Transactional(rollbackFor = Exception.class)
public SupplierCusAudit create(SupplierCusAudit resources) {
SupplierCusAudit audit = cusAuditRepository.findByCustomerNameAndSupplierId(resources.getCustomerName(), resources.getSupplierId());
// 同一个供应商下的重名校验
if (audit != null) {
throw new EntityExistException(SupplierContact.class, "customerName", resources.getCustomerName());
}
return cusAuditRepository.save(resources);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(SupplierCusAudit resources) {
SupplierCusAudit audit = cusAuditRepository.findByCustomerNameAndSupplierId(resources.getCustomerName(), resources.getSupplierId());
// 同一个供应商下的重名校验
if (audit != null && !audit.getId().equals(resources.getId())) {
throw new EntityExistException(SupplierContact.class, "customerName", resources.getCustomerName());
}
cusAuditRepository.save(resources);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void replaceBindSupplierId(SupplierCusAuditReplaceDto dto) {
Supplier supplier = supplierRepository.findById(dto.getSupplierId()).orElseGet(Supplier::new);
ValidationUtil.isNull(supplier.getId(), "Supplier", "id", dto.getSupplierId());
List<SupplierCusAudit> cusAudits = cusAuditRepository.findBySupplierId(dto.getUId());
if (ValidationUtil.isNotEmpty(cusAudits)) {
cusAudits.forEach(audit -> {
audit.setSupplierId(dto.getSupplierId());
});
cusAuditRepository.saveAll(cusAudits);
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Set<Long> ids) {
cusAuditRepository.deleteAllByIdIn(ids);
}
}
|
/*
* Copyright 2009-2012 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.apache.ibatis.type;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class EnumOrdinalTypeHandler<E extends Enum<E>> extends BaseTypeHandler<E> {
private Class<E> type;
private final E[] enums;
public EnumOrdinalTypeHandler(Class<E> type) {
if (type == null) {
throw new IllegalArgumentException("Type argument cannot be null");
}
this.type = type;
this.enums = type.getEnumConstants();
if (this.enums == null) {
throw new IllegalArgumentException(type.getSimpleName() + " does not represent an enum type.");
}
}
@Override
public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
ps.setInt(i, parameter.ordinal());
}
@Override
public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
int i = rs.getInt(columnName);
if (rs.wasNull()) {
return null;
} else {
try {
return enums[i];
} catch (Exception ex) {
throw new IllegalArgumentException("Cannot convert " + i + " to " + type.getSimpleName() + " by ordinal value.", ex);
}
}
}
@Override
public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
int i = rs.getInt(columnIndex);
if (rs.wasNull()) {
return null;
} else {
try {
return enums[i];
} catch (Exception ex) {
throw new IllegalArgumentException("Cannot convert " + i + " to " + type.getSimpleName() + " by ordinal value.", ex);
}
}
}
@Override
public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
int i = cs.getInt(columnIndex);
if (cs.wasNull()) {
return null;
} else {
try {
return enums[i];
} catch (Exception ex) {
throw new IllegalArgumentException("Cannot convert " + i + " to " + type.getSimpleName() + " by ordinal value.", ex);
}
}
}
}
|
package com.ruoyi.web.controller.monitor;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.base.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.page.TableDataInfo;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.framework.web.base.BaseController;
import com.ruoyi.quartz.domain.SysJob;
import com.ruoyi.quartz.service.ISysJobService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 调度任务信息操作处理
*
* @author ruoyi
*/
@Controller
@RequestMapping("/monitor/job")
public class SysJobController extends BaseController {
private String prefix = "monitor/job";
@Autowired
private ISysJobService jobService;
@RequiresPermissions("monitor:job:view")
@GetMapping()
public String job() {
return prefix + "/job";
}
@RequiresPermissions("monitor:job:list")
@PostMapping("/list")
@ResponseBody
public TableDataInfo list(SysJob job) {
startPage();
List<SysJob> list = jobService.selectJobList(job);
return getDataTable(list);
}
@Log(title = "定时任务", businessType = BusinessType.EXPORT)
@RequiresPermissions("monitor:job:export")
@PostMapping("/export")
@ResponseBody
public AjaxResult export(SysJob job) {
List<SysJob> list = jobService.selectJobList(job);
ExcelUtil<SysJob> util = new ExcelUtil<SysJob>(SysJob.class);
return util.exportExcel(list, "定时任务");
}
@Log(title = "定时任务", businessType = BusinessType.DELETE)
@RequiresPermissions("monitor:job:remove")
@PostMapping("/remove")
@ResponseBody
public AjaxResult remove(String ids) {
try {
jobService.deleteJobByIds(ids);
return success();
} catch (Exception e) {
e.printStackTrace();
return error(e.getMessage());
}
}
@RequiresPermissions("monitor:job:detail")
@GetMapping("/detail/{jobId}")
public String detail(@PathVariable("jobId") Long jobId, ModelMap mmap) {
mmap.put("name", "job");
mmap.put("job", jobService.selectJobById(jobId));
return prefix + "/detail";
}
/**
* 任务调度状态修改
*/
@Log(title = "定时任务", businessType = BusinessType.UPDATE)
@RequiresPermissions("monitor:job:changeStatus")
@PostMapping("/changeStatus")
@ResponseBody
public AjaxResult changeStatus(SysJob job) {
job.setUpdateBy(ShiroUtils.getLoginName());
return toAjax(jobService.changeStatus(job));
}
/**
* 任务调度立即执行一次
*/
@Log(title = "定时任务", businessType = BusinessType.UPDATE)
@RequiresPermissions("monitor:job:changeStatus")
@PostMapping("/run")
@ResponseBody
public AjaxResult run(SysJob job) {
return toAjax(jobService.run(job));
}
/**
* 新增调度
*/
@GetMapping("/add")
public String add() {
return prefix + "/add";
}
/**
* 新增保存调度
*/
@Log(title = "定时任务", businessType = BusinessType.INSERT)
@RequiresPermissions("monitor:job:add")
@PostMapping("/add")
@ResponseBody
public AjaxResult addSave(SysJob job) {
job.setCreateBy(ShiroUtils.getLoginName());
return toAjax(jobService.insertJobCron(job));
}
/**
* 修改调度
*/
@GetMapping("/edit/{jobId}")
public String edit(@PathVariable("jobId") Long jobId, ModelMap mmap) {
mmap.put("job", jobService.selectJobById(jobId));
return prefix + "/edit";
}
/**
* 修改保存调度
*/
@Log(title = "定时任务", businessType = BusinessType.UPDATE)
@RequiresPermissions("monitor:job:edit")
@PostMapping("/edit")
@ResponseBody
public AjaxResult editSave(SysJob job) {
job.setUpdateBy(ShiroUtils.getLoginName());
return toAjax(jobService.updateJobCron(job));
}
/**
* 校验cron表达式是否有效
*/
@PostMapping("/checkCronExpressionIsValid")
@ResponseBody
public boolean checkCronExpressionIsValid(SysJob job) {
return jobService.checkCronExpressionIsValid(job.getCronExpression());
}
}
|
package com.jay.spring.bean.factory.xml;
import com.jay.spring.Exception.BeanDefinitionException;
import com.jay.spring.aop.config.ConfigBeanDefinitionParser;
import com.jay.spring.bean.BeanDefinition;
import com.jay.spring.bean.ConstructorArgument;
import com.jay.spring.bean.PropertyValue;
import com.jay.spring.bean.factory.config.ConfigurableBeanFactory;
import com.jay.spring.bean.factory.config.RuntimeBeanReference;
import com.jay.spring.bean.factory.config.TypedStringValue;
import com.jay.spring.bean.factory.support.BeanDefinitionRegistry;
import com.jay.spring.bean.factory.support.GenericBeanDefinition;
import com.jay.spring.context.annotation.ClassPathBeanDefinitionScanner;
import com.jay.spring.core.io.ClassPathResource;
import com.jay.spring.core.io.Resource;
import com.jay.spring.util.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.InputStream;
import java.util.Iterator;
/**
* Created by xiang.wei on 2018/6/18
*
* @author xiang.wei
*/
public class XmlBeanDefinitionReader {
private final static Logger logger = Logger.getLogger(XmlBeanDefinitionReader.class);
private static String ID_ATTRIBUTE = "id";
private static String CLASS_ATTRIBUTE = "class";
private static String SCOPE_ATTRIBUTE = "scope";
private BeanDefinitionRegistry registry;
public static final String PROPERTY_ELEMENT = "property";
public static final String REF_ATTRIBUTE = "ref";
public static final String VALUE_ATTRIBUTE = "value";
public static final String NAME_ATTRIBUTE = "name";
public static final String CONSTRUCTOR_ARG_ELEMENT = "constructor-arg";
public static final String TYPE_ATTRIBUTE = "type";
public static final String BEANS_NAMESPACE_URI = "http://www.springframework.org/schema/beans";
public static final String CONTEXT_NAMESPACE_URI = "http://www.springframework.org/schema/context";
public static final String AOP_NAMESPACE_URI = "http://www.springframework.org/schema/aop";
private static final String BASE_PACKAGE_ATTRIBUTE = "base-package";
public XmlBeanDefinitionReader(BeanDefinitionRegistry registry) {
this.registry = registry;
}
public void loadBeanDefinitions(Resource resource) {
InputStream inputStream = null;
try {
try {
//获取文件输入流
inputStream = resource.getInputStream();
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(inputStream);
// 获取根节点
Element rootElement = document.getRootElement();
Iterator<Element> iterator = rootElement.elementIterator();
while (iterator.hasNext()) {
Element element = iterator.next();
String namespaceUri = element.getNamespaceURI();
if (this.isDefaultNamespace(namespaceUri)) {
parseDefaultElement(element);//普通的bean
} else if (this.isContextNamespace(namespaceUri)) {
parseComponentElement(element);//例如<context:component-scan>
} else if (this.isAOPNamespace(namespaceUri)) {
parseAOPElement(element); //例如:<aop:config>
}
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
} catch (Exception e) {
throw new BeanDefinitionException("读取xml出错");
}
}
public void parsePropertyElement(Element beanElem, BeanDefinition bd) {
Iterator iterator = beanElem.elementIterator(PROPERTY_ELEMENT);
while (iterator.hasNext()) {
Element propElem = (Element) iterator.next();
String propertyName = propElem.attributeValue(NAME_ATTRIBUTE);
if (!StringUtils.hasLength(propertyName)) {
logger.fatal("Tag 'property' must have a 'name' attribute");
return;
}
Object val = parsePropertyValue(propElem, bd, propertyName);
PropertyValue pv = new PropertyValue(propertyName, val);
bd.getPropertyValues().add(pv);
}
}
public Object parsePropertyValue(Element ele, BeanDefinition bd, String propertyName) {
String elementName = (propertyName != null) ?
"<property> element for property '" + propertyName + "'" :
"<constructor-arg> element";
boolean hasRefAttribute = (ele.attribute(REF_ATTRIBUTE) != null);
boolean hasValueAttribute = (ele.attribute(VALUE_ATTRIBUTE) != null);
if (hasRefAttribute) {
String refName = ele.attributeValue(REF_ATTRIBUTE);
if (!StringUtils.hasText(refName)) {
logger.error(elementName + " contains empty 'ref' attribute");
}
RuntimeBeanReference ref = new RuntimeBeanReference(refName);
return ref;
} else if (hasValueAttribute) {
TypedStringValue typedStringValue = new TypedStringValue(ele.attributeValue(VALUE_ATTRIBUTE));
return typedStringValue;
} else {
throw new RuntimeException(elementName + " must specify a ref or value");
}
}
public void parseConstructorArgElements(Element beanEle, BeanDefinition beanDefinition) {
Iterator iter = beanEle.elementIterator(CONSTRUCTOR_ARG_ELEMENT);
while (iter.hasNext()) {
Element ele = (Element) iter.next();
parseConstructorArgElement(ele, beanDefinition);
}
}
public void parseConstructorArgElement(Element ele, BeanDefinition beanDefinition) {
String typeAttr = ele.attributeValue(TYPE_ATTRIBUTE);
String nameAttr = ele.attributeValue(NAME_ATTRIBUTE);
Object value = parsePropertyValue(ele, beanDefinition, null);
ConstructorArgument.ValueHolder valueHolder = new ConstructorArgument.ValueHolder(value);
if (StringUtils.hasLength(typeAttr)) {
valueHolder.setType(typeAttr);
}
if (StringUtils.hasLength(nameAttr)) {
valueHolder.setName(nameAttr);
}
beanDefinition.getConstructorArgument().addArgumentValue(valueHolder);
}
public boolean isDefaultNamespace(String namespaceUri) {
return (!StringUtils.hasLength(namespaceUri) || BEANS_NAMESPACE_URI.equals(namespaceUri));
}
public boolean isContextNamespace(String namespaceUri){
return (!StringUtils.hasLength(namespaceUri) || CONTEXT_NAMESPACE_URI.equals(namespaceUri));
}
public boolean isAOPNamespace(String namespaceUri) {
return (!StringUtils.hasLength(namespaceUri) || AOP_NAMESPACE_URI.equals(namespaceUri));
}
private void parseDefaultElement(Element element) {
String id = element.attributeValue(ID_ATTRIBUTE);
String className = element.attributeValue(CLASS_ATTRIBUTE);
BeanDefinition beanDefinition = new GenericBeanDefinition(id, className);
if (element.attribute(SCOPE_ATTRIBUTE) != null) {
beanDefinition.setScope(element.attributeValue(SCOPE_ATTRIBUTE));
}
parseConstructorArgElements(element, beanDefinition);
parsePropertyElement(element, beanDefinition);
registry.registerBeanDefinition(id, beanDefinition);
}
private void parseComponentElement(Element element) {
String basePackages = element.attributeValue(BASE_PACKAGE_ATTRIBUTE);
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(registry);
scanner.doScan(basePackages);
}
private void parseAOPElement(Element ele) {
ConfigBeanDefinitionParser parser = new ConfigBeanDefinitionParser();
parser.parse(ele, this.registry);
}
}
|
/*
This file is part of sdmx-sax.
Copyright 2015 James Stanley Gardner
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 sdmx.commonreferences;
import sdmx.commonreferences.types.ItemTypeCodelistType;
import sdmx.commonreferences.types.ItemSchemePackageTypeCodelistType;
import sdmx.common.ObsDimensionsCodeType;
/**
* <xs:complexType name="CategoryRefType">
<xs:annotation>
<xs:documentation>CategoryRefType references a category from within a category scheme. Reference fields are required for both the scheme and the item.</xs:documentation>
</xs:annotation>
<xs:complexContent>
<xs:restriction base="ItemRefBaseType">
<xs:attribute name="maintainableParentID" type="IDType" use="required">
<xs:annotation>
<xs:documentation>The maintainableParentID references the category scheme in which the category being referenced is defined.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="maintainableParentVersion" type="VersionType" use="optional" default="1.0">
<xs:annotation>
<xs:documentation>The maintainableParentVersion attribute references the version of the category scheme in which the category being referenced is defined. If not supplied, a default value of 1.0 is assumed.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="class" type="ItemTypeCodelistType" use="optional" fixed="Category"/>
<xs:attribute name="package" type="ItemSchemePackageTypeCodelistType" use="optional" fixed="categoryscheme"/>
</xs:restriction>
</xs:complexContent>
</xs:complexType>
* @author James
*/
public class CategoryRef extends ItemRefBase {
public CategoryRef(NestedNCNameID agencyId,NestedID id,IDType mainParent,Version pvers,ItemTypeCodelistType clazz,ItemSchemePackageTypeCodelistType pack) {
super(agencyId,mainParent,pvers,id,clazz,pack);
}
}
|
/*
* Copyright 2017 Marcus Portmann
*
* 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 guru.mmp.application.web.template.pages;
//~--- non-JDK imports --------------------------------------------------------
import guru.mmp.application.security.ISecurityService;
import guru.mmp.application.security.User;
import guru.mmp.application.web.WebApplicationException;
import guru.mmp.application.web.pages.WebPageSecurity;
import guru.mmp.application.web.template.TemplateSecurity;
import guru.mmp.application.web.template.components.TextFieldWithFeedback;
import org.apache.wicket.PageReference;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.validation.validator.EmailAddressValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
//~--- JDK imports ------------------------------------------------------------
/**
* The <code>UpdateUserPage</code> class implements the
* "Update User" page for the Web Application Template.
*
* @author Marcus Portmann
*/
@WebPageSecurity(TemplateSecurity.FUNCTION_CODE_USER_ADMINISTRATION)
class UpdateUserPage extends TemplateWebPage
{
/* Logger */
private static final Logger logger = LoggerFactory.getLogger(UpdateUserPage.class);
private static final long serialVersionUID = 1000000;
/* Security Service */
@Inject
private ISecurityService securityService;
/**
* Constructs a new <code>UpdateUserPage</code>.
*
* @param previousPage the previous page
* @param userModel the model for the user
*/
UpdateUserPage(PageReference previousPage, IModel<User> userModel)
{
super("Update User");
try
{
Form<User> updateForm = new Form<>("updateForm", new CompoundPropertyModel<>(userModel));
// The "username" field
TextField<String> usernameField = new TextFieldWithFeedback<>("username");
usernameField.setRequired(true);
usernameField.setEnabled(false);
updateForm.add(usernameField);
// The "firstName" field
TextField<String> firstNameField = new TextFieldWithFeedback<>("firstName");
firstNameField.setRequired(true);
updateForm.add(firstNameField);
// The "lastName" field
TextField<String> lastNameField = new TextFieldWithFeedback<>("lastName");
lastNameField.setRequired(true);
updateForm.add(lastNameField);
// The "email" field
TextField<String> emailField = new TextFieldWithFeedback<>("email");
emailField.add(EmailAddressValidator.getInstance());
emailField.setRequired(true);
updateForm.add(emailField);
// The "phoneNumber" field
TextField<String> phoneNumberField = new TextFieldWithFeedback<>("phoneNumber");
phoneNumberField.setRequired(false);
updateForm.add(phoneNumberField);
// The "mobileNumber" field
TextField<String> mobileNumberField = new TextFieldWithFeedback<>("mobileNumber");
mobileNumberField.setRequired(false);
updateForm.add(mobileNumberField);
// The "updateButton" button
Button updateButton = new Button("updateButton")
{
private static final long serialVersionUID = 1000000;
@Override
public void onSubmit()
{
try
{
User user = updateForm.getModelObject();
securityService.updateUser(user.getUserDirectoryId(), user, false, false);
setResponsePage(previousPage.getPage());
}
catch (Throwable e)
{
logger.error("Failed to update the user: " + e.getMessage(), e);
UpdateUserPage.this.error("Failed to update the user");
}
}
};
updateButton.setDefaultFormProcessing(true);
updateForm.add(updateButton);
// The "cancelButton" button
Button cancelButton = new Button("cancelButton")
{
private static final long serialVersionUID = 1000000;
@Override
public void onSubmit()
{
setResponsePage(previousPage.getPage());
}
};
cancelButton.setDefaultFormProcessing(false);
updateForm.add(cancelButton);
add(updateForm);
}
catch (Throwable e)
{
throw new WebApplicationException("Failed to initialise the UpdateUserPage", e);
}
}
}
|
package io.dekorate.issue254;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import io.dekorate.component.annotation.ComponentApplication;
@SpringBootApplication
@ComponentApplication(exposeService=true)
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
|
package com.alexandrepiveteau.wallpaper.example;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
}
|
/*
* Copyright 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.gradle.internal.execution;
import org.gradle.internal.service.scopes.EventScope;
import org.gradle.internal.service.scopes.Scopes;
@EventScope(Scopes.Build)
public interface OutputChangeListener {
/**
* Invoked when the outputs of a work item are about to change.
* This happens for example just before the task actions are executed or the outputs are loaded from the cache.
*/
void beforeOutputChange();
/**
* Like {@link #beforeOutputChange()}, only that the outputs which are about to change are known
*
* @param affectedOutputPaths The files which are affected by the change.
*/
void beforeOutputChange(Iterable<String> affectedOutputPaths);
}
|
package com.example.cuihao.zeellipse;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ToggleButton;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.android.Utils;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.MatOfPoint2f;
import org.opencv.core.RotatedRect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.core.Point;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import uk.co.senab.photoview.PhotoViewAttacher;
import static com.example.cuihao.zeellipse.JniWrapper.CppGetSobel;
import static com.example.cuihao.zeellipse.JniWrapper.CppPreprocess;
import static com.example.cuihao.zeellipse.JniWrapper.DynamicDilate;
import static com.example.cuihao.zeellipse.JniWrapper.DynamicErode;
import static com.example.cuihao.zeellipse.JniWrapper.EllipticalIntegrate;
import static com.example.cuihao.zeellipse.JniWrapper.EllipticalR;
import static com.example.cuihao.zeellipse.JniWrapper.GetRBox;
import static com.example.cuihao.zeellipse.JniWrapper.QuickFindCenter;
public class MainActivity extends AppCompatActivity {
Button buttonLoad;
TextView textViewMessage;
TextView textViewInfo;
ImageView imageViewDisplay;
PhotoViewAttacher mAttacher;
ToggleButton toggleButtonMode;
Button buttonReset;
static final double touchReactDiffPixel = 50.0;
static final int gapWidthThreshold = 10;
static final double derivative2Threshold = 1;
Mat imColor, imGray;
RotatedRect avgEllipse;
ArrayList<Integer> dResults = new ArrayList<>();
ArrayList<Point> selectPoints = new ArrayList<>();
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
@Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS: {
Log.i("Hello", "OpenCV loaded successfully");
//System.loadLibrary("libopencv_java3");
System.loadLibrary("jni_wrapper");
}
break;
default: {
super.onManagerConnected(status);
}
break;
}
}
};
private void resetImage() {
textViewInfo.setText("");
selectPoints.clear();
Bitmap bitmap = Bitmap.createBitmap(imColor.cols(), imColor.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(imColor, bitmap);
imageViewDisplay.setImageBitmap(bitmap);
float scale1 = 1.0F * imageViewDisplay.getWidth() / imColor.cols(),
scale2 = 1.0F * imageViewDisplay.getHeight() / imColor.rows();
float scale = scale1 > scale2 ? scale2 : scale1;
mAttacher.setScale(scale > mAttacher.getMinimumScale() ? scale : mAttacher.getMinimumScale());
}
private double[] secondDerivative(double[] seq) {
double[] r = new double[seq.length];
for (int i=3; i<r.length-3; i++)
r[i] = (seq[i+3] - 2*seq[i] + seq[i-3])/4.0;
return r;
}
private double findNearestEllipse(double x, double y) {
int dNearest = -1;
double d = 2*EllipticalR(new Point(x, y), avgEllipse);
for (int dRes: dResults)
if (Math.abs(dRes-d) < touchReactDiffPixel && Math.abs(dRes-d) < Math.abs(dNearest-d))
dNearest = dRes;
return dNearest;
}
private class ProcessImageTask extends AsyncTask<Uri, String, Boolean> {
protected void onPreExecute() {
buttonReset.setEnabled(false);
toggleButtonMode.setEnabled(false);
}
protected Boolean doInBackground(Uri... params) {
publishProgress(getResources().getString(R.string.process_image_task__loading));
Uri uri = params[0];
InputStream inStream;
try {
inStream = getContentResolver().openInputStream(uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
Mat sobel = new Mat(), blur = new Mat();
try {
imColor = readInputStreamIntoMat(inStream);
} catch (IOException e) {
return false;
}
publishProgress(getResources().getString(R.string.process_image_task__preprocess));
CppPreprocess(imColor.getNativeObjAddr(), (imGray = new Mat()).getNativeObjAddr());
// OpenCV use BGR colorspace as default, convert to RGB
Imgproc.cvtColor(imColor, imColor, Imgproc.COLOR_BGR2RGB);
Imgproc.GaussianBlur(imGray, blur, new Size(7, 7), 3);
Point pt = QuickFindCenter(blur);
publishProgress(getResources().getString(R.string.process_image_task__sobel));
CppGetSobel(blur.getNativeObjAddr(), sobel.getNativeObjAddr());
publishProgress(getResources().getString(R.string.process_image_task__erode_dilate));
DynamicErode(sobel, pt);
DynamicDilate(sobel, pt);
publishProgress(getResources().getString(R.string.process_image_task__find_ellipse));
avgEllipse = GetRBox(sobel);
if (avgEllipse.size.width + avgEllipse.size.height == 0) {
dResults.clear();
return true;
}
publishProgress(getResources().getString(R.string.process_image_task__integrate));
double[] seq = EllipticalIntegrate(blur, avgEllipse);
double[] de2 = secondDerivative(seq);
double sum = 0.0;
for (double i : seq) sum += i;
double val_threshold = 0.8 * sum / seq.length;
dResults.clear();
for (int i=0, j=0; j<de2.length; i=j) {
while (j<de2.length && de2[j]<-derivative2Threshold) j++;
if (j > i && (seq[i] > val_threshold || seq[j] > val_threshold)) {
int d = i + j;
if (!dResults.isEmpty()) {
int last_d = dResults.get(dResults.size() - 1);
if (d - last_d < gapWidthThreshold * 2)
dResults.set(dResults.size() - 1, (d + last_d) / 2);
else
dResults.add(d);
} else
dResults.add(d);
}
while (j<de2.length && !(de2[j]<-derivative2Threshold)) j++;
}
return true;
}
protected void onProgressUpdate(String... progress) {
textViewMessage.setText(progress[0]);
}
protected void onPostExecute(Boolean result) {
buttonReset.setEnabled(result);
toggleButtonMode.setEnabled(result);
if (result) {
Bitmap bitmap = Bitmap.createBitmap(imColor.cols(), imColor.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(imColor, bitmap);
imageViewDisplay.setImageBitmap(bitmap);
if (dResults.size() > 0)
textViewMessage.setText(R.string.process_image_task__done);
else
textViewMessage.setText(R.string.process_image_task__nothing_found);
resetImage();
} else
textViewMessage.setText(R.string.process_image_task__failed);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonLoad = (Button)findViewById(R.id.buttonLoad);
buttonReset = (Button)findViewById(R.id.buttonReset);
toggleButtonMode = (ToggleButton)findViewById(R.id.toggleButtonMode);
textViewMessage = (TextView)findViewById(R.id.textViewMessage);
textViewInfo = (TextView)findViewById(R.id.textViewInfo);
imageViewDisplay = (ImageView)findViewById(R.id.imageViewDisplay);
mAttacher = new PhotoViewAttacher(imageViewDisplay);
buttonLoad.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
});
buttonReset.setEnabled(false);
buttonReset.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
resetImage();
}
});
final PhotoViewAttacher.OnPhotoTapListener autoModeTapListener = new PhotoViewAttacher.OnPhotoTapListener() {
@Override
public void onPhotoTap(View arg0, float arg1, float arg2) {
double x = arg1 * imGray.cols(), y = arg2 * imGray.rows();
double d = findNearestEllipse(x, y);
double ratio = avgEllipse.size.width / avgEllipse.size.height;
Mat dis = imColor.clone();
Imgproc.circle(dis, avgEllipse.center, 2, new Scalar(255, 0, 0), -1);
if (d > 0) {
RotatedRect box = new RotatedRect(avgEllipse.center, new Size(d, d/ratio), avgEllipse.angle);
Imgproc.ellipse(dis, box, new Scalar(255, 0, 0), 2);
String s = getResources().getString(R.string.textview_info_output,
box.center.x, box.center.y, box.size.width / 2, box.size.height / 2);
textViewInfo.setText(s);
}
Bitmap bitmap = Bitmap.createBitmap(dis.cols(), dis.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(dis, bitmap);
imageViewDisplay.setImageBitmap(bitmap);
}
};
final PhotoViewAttacher.OnPhotoTapListener customModeTapListener = new PhotoViewAttacher.OnPhotoTapListener() {
@Override
public void onPhotoTap(View arg0, float arg1, float arg2) {
double x = arg1 * imGray.cols(), y = arg2 * imGray.rows();
boolean found = false;
for (Iterator<Point> it = selectPoints.iterator(); it.hasNext();) {
Point p = it.next();
if (Math.hypot(p.x-x, p.y-y) <= touchReactDiffPixel) {
it.remove();
found = true;
break;
}
}
if (!found) selectPoints.add(new Point(x, y));
Mat dis = imColor.clone();
for (Point pt: selectPoints) {
Imgproc.circle(dis, pt, 4, new Scalar(255, 255, 255), -1);
}
if (selectPoints.size() >= 5) {
MatOfPoint2f mop = new MatOfPoint2f();
mop.fromList(selectPoints);
RotatedRect box = Imgproc.fitEllipse(mop);
Imgproc.ellipse(dis, box, new Scalar(255, 0, 0), 2);
Imgproc.circle(dis, box.center, 2, new Scalar(255, 0, 0), -1);
String s = getResources().getString(R.string.textview_info_output,
box.center.x, box.center.y, box.size.width / 2, box.size.height / 2);
textViewInfo.setText(s);
}
Bitmap bitmap = Bitmap.createBitmap(dis.cols(), dis.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(dis, bitmap);
imageViewDisplay.setImageBitmap(bitmap);
}
};
mAttacher.setMinimumScale(0.1F);
mAttacher.setMaximumScale(8.0F);
mAttacher.setOnPhotoTapListener(autoModeTapListener);
toggleButtonMode.setEnabled(false);
toggleButtonMode.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
resetImage();
mAttacher.setOnPhotoTapListener(isChecked ? customModeTapListener : autoModeTapListener);
}
});
}
@Override
protected void onActivityResult(int reqCode, int resCode, Intent data) {
if(resCode == Activity.RESULT_OK && data != null)
new ProcessImageTask().execute(data.getData());
}
@Override
protected void onResume() {
super.onResume();
if (!OpenCVLoader.initDebug()) {
Log.d("Hello", "Internal OpenCV library not found. Using OpenCV Manager for initialization");
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_0_0, this, mLoaderCallback);
} else {
Log.d("Hello", "OpenCV library found inside package. Using it!");
mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
}
}
// from: http://stackoverflow.com/questions/29232220/android-read-image-using-opencv
private static Mat readInputStreamIntoMat(InputStream inputStream) throws IOException {
byte[] temporaryImageInMemory = readStream(inputStream);
return Imgcodecs.imdecode(new MatOfByte(temporaryImageInMemory), Imgcodecs.IMREAD_COLOR);
}
private static byte[] readStream(InputStream stream) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = stream.read(data, 0, data.length)) != -1)
buffer.write(data, 0, nRead);
buffer.flush();
byte[] temporaryImageInMemory = buffer.toByteArray();
buffer.close();
stream.close();
return temporaryImageInMemory;
}
}
|
package com.sen.review.data.structure.sort;
import java.util.Arrays;
/**
* @Author: Sen
* @Date: 2020/4/30
* @Description: 堆排序,最坏、最好、平均时间复杂度: O(n log n),是一种不稳定的排序
* 思想:
* 1.将数组构建成一个大顶堆,利用大顶堆的特性:堆顶根节点的值 >= 所有子节点的的值(注意:左子节点的值不一定 < 右子节点)
* 2.然后把对应元素与数组的最后一个元素交换位置,然后在arr.length - 1的长度数组中再构建大顶堆
* 3.一直重复直到数组有序
*/
public class HeapSort {
public static void main(String[] args) {
int[] arr = {4, 6, 8, 5, 9, -234, 345, 34, 765, 2341, 4, 7};
heapSort(arr);
System.out.println(Arrays.toString(arr));
}
/**
* 调整大顶堆
*
* @param arr 需要调整为大顶堆的数组
* @param index 堆顶根节点下标
* @param length 调整的长度
*/
private static void adjustHeap(int[] arr, int index, int length) {
// 记录堆顶值
int top = arr[index];
// 以index作为堆顶调整成大顶堆,调整后检查其子节点是否符合大顶堆
for (int i = 2 * index + 1; i < length; i = 2 * i + 1) {
/*
* 当前节点的左子节点要小于右子节点 4, 6, 8, 5, 9
* 第一轮: 4 第二轮: 4
* / \ / \
* 6 8 9 8
* / \ / \
* 5 9 5 6
* */
// 比较左、右子节点的值,将i指向最小节点
if (i + 1 < length && arr[i] < arr[i + 1]) {
// i指向比左子节点大的右子节点
i++;
}
// 判断子节点的值是否比堆顶节点大
if (top < arr[i]) {
// 子节点的值替换堆顶节点
arr[index] = arr[i];
// 堆顶指向i
index = i;
}
// 由于从最后一个左节点开始调整的当前不需要调整证明符合大顶堆
else{
break;
}
}
// 把调整前堆顶的值赋给调整后的节点
arr[index] = top;
}
/**
* 堆排序
* @param arr 待排序数组
*/
private static void heapSort(int[] arr) {
/*
* 先把数组调整成一个大顶堆
* 从最后一个左子节点开始调整堆,最后一个左子节点的下标 = arr.length / 2 - 1
* */
for (int i = arr.length / 2 - 1; i >= 0; i--) {
adjustHeap(arr, i, arr.length);
}
// 把堆顶元素和最后一个元素交换,然后以根节点为堆顶再构建成大顶堆
for (int i = arr.length - 1; i > 0; i--) {
// 交换
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
// 再原来基础上,长度-1调整成大顶堆
adjustHeap(arr, 0, i);
}
}
}
|
/*
* Copyright 2021 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.tools.opensource.classpath;
import com.google.cloud.tools.opensource.dependencies.DependencyGraph;
import org.eclipse.aether.version.InvalidVersionSpecificationException;
/**
* Algorithm to select artifacts when there are multiple versions for the same groupId and
* artifactId in a dependency graph.
*
* <p>The algorithm does not take classifier or extension into account.
*/
public interface DependencyMediation {
DependencyMediation MAVEN = new MavenDependencyMediation();
DependencyMediation GRADLE = new GradleDependencyMediation();
/**
* Returns {@link AnnotatedClassPath} after performing dependency mediation. This means that the
* returned list of class path entries has no duplicate artifacts in terms of the groupId and
* artifactId combination.
*
* @param dependencyGraph dependency graph that may have duplicate artifacts that have the same
* groupId and artifactId combination
*/
AnnotatedClassPath mediate(DependencyGraph dependencyGraph)
throws InvalidVersionSpecificationException;
}
|
// This file was generated by Mendix Studio Pro.
//
// WARNING: Code you write here will be lost the next time you deploy the project.
package communitycommons.proxies;
public class ImageDimensions
{
private final com.mendix.systemwideinterfaces.core.IMendixObject imageDimensionsMendixObject;
private final com.mendix.systemwideinterfaces.core.IContext context;
/**
* Internal name of this entity
*/
public static final java.lang.String entityName = "CommunityCommons.ImageDimensions";
/**
* Enum describing members of this entity
*/
public enum MemberNames
{
Height("Height"),
Width("Width");
private java.lang.String metaName;
MemberNames(java.lang.String s)
{
metaName = s;
}
@java.lang.Override
public java.lang.String toString()
{
return metaName;
}
}
public ImageDimensions(com.mendix.systemwideinterfaces.core.IContext context)
{
this(context, com.mendix.core.Core.instantiate(context, "CommunityCommons.ImageDimensions"));
}
protected ImageDimensions(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixObject imageDimensionsMendixObject)
{
if (imageDimensionsMendixObject == null)
throw new java.lang.IllegalArgumentException("The given object cannot be null.");
if (!com.mendix.core.Core.isSubClassOf("CommunityCommons.ImageDimensions", imageDimensionsMendixObject.getType()))
throw new java.lang.IllegalArgumentException("The given object is not a CommunityCommons.ImageDimensions");
this.imageDimensionsMendixObject = imageDimensionsMendixObject;
this.context = context;
}
/**
* @deprecated Use 'ImageDimensions.load(IContext, IMendixIdentifier)' instead.
*/
@java.lang.Deprecated
public static communitycommons.proxies.ImageDimensions initialize(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixIdentifier mendixIdentifier) throws com.mendix.core.CoreException
{
return communitycommons.proxies.ImageDimensions.load(context, mendixIdentifier);
}
/**
* Initialize a proxy using context (recommended). This context will be used for security checking when the get- and set-methods without context parameters are called.
* The get- and set-methods with context parameter should be used when for instance sudo access is necessary (IContext.createSudoClone() can be used to obtain sudo access).
*/
public static communitycommons.proxies.ImageDimensions initialize(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixObject mendixObject)
{
return new communitycommons.proxies.ImageDimensions(context, mendixObject);
}
public static communitycommons.proxies.ImageDimensions load(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixIdentifier mendixIdentifier) throws com.mendix.core.CoreException
{
com.mendix.systemwideinterfaces.core.IMendixObject mendixObject = com.mendix.core.Core.retrieveId(context, mendixIdentifier);
return communitycommons.proxies.ImageDimensions.initialize(context, mendixObject);
}
/**
* Commit the changes made on this proxy object.
*/
public final void commit() throws com.mendix.core.CoreException
{
com.mendix.core.Core.commit(context, getMendixObject());
}
/**
* Commit the changes made on this proxy object using the specified context.
*/
public final void commit(com.mendix.systemwideinterfaces.core.IContext context) throws com.mendix.core.CoreException
{
com.mendix.core.Core.commit(context, getMendixObject());
}
/**
* Delete the object.
*/
public final void delete()
{
com.mendix.core.Core.delete(context, getMendixObject());
}
/**
* Delete the object using the specified context.
*/
public final void delete(com.mendix.systemwideinterfaces.core.IContext context)
{
com.mendix.core.Core.delete(context, getMendixObject());
}
/**
* @return value of Height
*/
public final java.lang.Integer getHeight()
{
return getHeight(getContext());
}
/**
* @param context
* @return value of Height
*/
public final java.lang.Integer getHeight(com.mendix.systemwideinterfaces.core.IContext context)
{
return (java.lang.Integer) getMendixObject().getValue(context, MemberNames.Height.toString());
}
/**
* Set value of Height
* @param height
*/
public final void setHeight(java.lang.Integer height)
{
setHeight(getContext(), height);
}
/**
* Set value of Height
* @param context
* @param height
*/
public final void setHeight(com.mendix.systemwideinterfaces.core.IContext context, java.lang.Integer height)
{
getMendixObject().setValue(context, MemberNames.Height.toString(), height);
}
/**
* @return value of Width
*/
public final java.lang.Integer getWidth()
{
return getWidth(getContext());
}
/**
* @param context
* @return value of Width
*/
public final java.lang.Integer getWidth(com.mendix.systemwideinterfaces.core.IContext context)
{
return (java.lang.Integer) getMendixObject().getValue(context, MemberNames.Width.toString());
}
/**
* Set value of Width
* @param width
*/
public final void setWidth(java.lang.Integer width)
{
setWidth(getContext(), width);
}
/**
* Set value of Width
* @param context
* @param width
*/
public final void setWidth(com.mendix.systemwideinterfaces.core.IContext context, java.lang.Integer width)
{
getMendixObject().setValue(context, MemberNames.Width.toString(), width);
}
/**
* @return the IMendixObject instance of this proxy for use in the Core interface.
*/
public final com.mendix.systemwideinterfaces.core.IMendixObject getMendixObject()
{
return imageDimensionsMendixObject;
}
/**
* @return the IContext instance of this proxy, or null if no IContext instance was specified at initialization.
*/
public final com.mendix.systemwideinterfaces.core.IContext getContext()
{
return context;
}
@java.lang.Override
public boolean equals(Object obj)
{
if (obj == this)
return true;
if (obj != null && getClass().equals(obj.getClass()))
{
final communitycommons.proxies.ImageDimensions that = (communitycommons.proxies.ImageDimensions) obj;
return getMendixObject().equals(that.getMendixObject());
}
return false;
}
@java.lang.Override
public int hashCode()
{
return getMendixObject().hashCode();
}
/**
* @return String name of this class
*/
public static java.lang.String getType()
{
return "CommunityCommons.ImageDimensions";
}
/**
* @return String GUID from this object, format: ID_0000000000
* @deprecated Use getMendixObject().getId().toLong() to get a unique identifier for this object.
*/
@java.lang.Deprecated
public java.lang.String getGUID()
{
return "ID_" + getMendixObject().getId().toLong();
}
}
|
package com.jnape.palatable.winterbourne.functions.builtin.fn2;
import com.jnape.palatable.lambda.functor.builtin.Identity;
import org.junit.Test;
import static com.jnape.palatable.lambda.adt.Maybe.nothing;
import static com.jnape.palatable.lambda.functor.builtin.Identity.pureIdentity;
import static com.jnape.palatable.shoki.api.Natural.atLeastOne;
import static com.jnape.palatable.shoki.api.Natural.natural;
import static com.jnape.palatable.shoki.api.Natural.zero;
import static com.jnape.palatable.shoki.impl.StrictQueue.strictQueue;
import static com.jnape.palatable.winterbourne.StreamT.empty;
import static com.jnape.palatable.winterbourne.StreamT.streamT;
import static com.jnape.palatable.winterbourne.functions.builtin.fn1.NaturalsM.naturalsM;
import static com.jnape.palatable.winterbourne.functions.builtin.fn1.TailM.tailM;
import static com.jnape.palatable.winterbourne.functions.builtin.fn2.PrependAllM.prependAllM;
import static com.jnape.palatable.winterbourne.functions.builtin.fn2.TakeM.takeM;
import static com.jnape.palatable.winterbourne.testsupport.matchers.StreamTMatcher.streams;
import static org.junit.Assert.assertThat;
public class PrependAllMTest {
@Test
public void prependsToAllEmissions() {
assertThat(prependAllM(zero(),
takeM(atLeastOne(3),
tailM(naturalsM(pureIdentity())))),
streams(nothing(),
natural(0), natural(1),
natural(0), natural(2),
natural(0), natural(3)));
}
@Test
public void emptyRemainsEmpty() {
assertThat(prependAllM(zero(), empty(pureIdentity())), streams());
assertThat(prependAllM(zero(), streamT(new Identity<>(strictQueue(nothing(), nothing(), nothing())))),
streams(nothing(), nothing(), nothing()));
}
}
|
/*
* Copyright (c) 2002-2019 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* 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.neo4j.ogm.result.adapter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.neo4j.ogm.response.model.NodeModel;
import org.neo4j.ogm.response.model.RelationshipModel;
/**
* Adapt embedded response to a NodeModels, RelationshipModels, and objects
*
* @author Luanne Misquitta
*/
public abstract class RestModelAdapter extends BaseAdapter
implements ResultAdapter<Map<String, Object>, Map<String, Object>> {
@Override
public Map<String, Object> adapt(Map<String, Object> result) {
Map<String, Object> adaptedResults = new LinkedHashMap<>();
for (Map.Entry<String, Object> entry : result.entrySet()) {
Object value = entry.getValue();
if (value instanceof Collection) {
Collection<Object> adaptedValues = new ArrayList<>();
Collection<Object> values = (List) value;
for (Object element : values) {
adaptedValues.add(processData(element));
}
adaptedResults.put(entry.getKey(), adaptedValues);
} else {
adaptedResults.put(entry.getKey(), processData(value));
}
}
return adaptedResults;
}
private Object processData(Object element) {
if (isNode(element)) {
return buildNode(element);
}
if (isRelationship(element)) {
return buildRelationship(element);
}
return element;
}
private NodeModel buildNode(Object node) {
NodeModel nodeModel = new NodeModel(nodeId(node));
List<String> labels = labels(node);
nodeModel.setLabels(labels.toArray(new String[labels.size()]));
nodeModel.setProperties(convertArrayPropertiesToIterable(properties(node)));
return nodeModel;
}
private RelationshipModel buildRelationship(Object relationship) {
RelationshipModel relationshipModel = new RelationshipModel();
relationshipModel.setId(relationshipId(relationship));
relationshipModel.setStartNode(startNodeId(relationship));
relationshipModel.setEndNode(endNodeId(relationship));
relationshipModel.setType(relationshipType(relationship));
relationshipModel.setProperties(properties(relationship));
return relationshipModel;
}
public abstract boolean isNode(Object value);
public abstract boolean isRelationship(Object value);
public abstract long nodeId(Object node);
public abstract List<String> labels(Object node);
public abstract long relationshipId(Object relationship);
public abstract String relationshipType(Object relationship);
public abstract Long startNodeId(Object relationship);
public abstract Long endNodeId(Object relationship);
public abstract Map<String, Object> properties(Object container);
}
|
/**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.security.fx;
import java.util.Map;
import javax.time.calendar.ZonedDateTime;
import org.joda.beans.BeanBuilder;
import org.joda.beans.BeanDefinition;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.Property;
import org.joda.beans.PropertyDefinition;
import org.joda.beans.impl.direct.DirectBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;
import com.opengamma.financial.security.FinancialSecurity;
import com.opengamma.financial.security.FinancialSecurityVisitor;
import com.opengamma.id.ExternalId;
import com.opengamma.util.money.Currency;
/**
* A security for FX forwards.
*/
@BeanDefinition
public class NonDeliverableFXForwardSecurity extends FinancialSecurity {
/** Serialization version. */
private static final long serialVersionUID = 1L;
/**
* The security type.
*/
public static final String SECURITY_TYPE = "NONDELIVERABLE_FX_FORWARD";
/**
* The payer currency
*/
@PropertyDefinition(validate = "notNull")
private Currency _payCurrency;
/**
* The pay amount
*/
@PropertyDefinition
private double _payAmount;
/**
* The receiver currency
*/
@PropertyDefinition(validate = "notNull")
private Currency _receiveCurrency;
/**
* The receive amount
*/
@PropertyDefinition
private double _receiveAmount;
/**
* The forward date.
*/
@PropertyDefinition(validate = "notNull")
private ZonedDateTime _forwardDate;
/**
* The region.
*/
@PropertyDefinition(validate = "notNull")
private ExternalId _regionId;
/**
* Whether to deliver in the receive currency
*/
@PropertyDefinition
private boolean _deliverInReceiveCurrency;
NonDeliverableFXForwardSecurity() { //For builder
super();
}
public NonDeliverableFXForwardSecurity(Currency payCurrency, double payAmount, Currency receiveCurrency, double receiveAmount,
ZonedDateTime forwardDate, ExternalId region, boolean deliverInReceiveCurrency) {
super(SECURITY_TYPE);
setPayCurrency(payCurrency);
setPayAmount(payAmount);
setReceiveCurrency(receiveCurrency);
setReceiveAmount(receiveAmount);
setForwardDate(forwardDate);
setRegionId(region);
setDeliverInReceiveCurrency(deliverInReceiveCurrency);
}
//-------------------------------------------------------------------------
@Override
public final <T> T accept(FinancialSecurityVisitor<T> visitor) {
return visitor.visitNonDeliverableFXForwardSecurity(this);
}
//------------------------- AUTOGENERATED START -------------------------
///CLOVER:OFF
/**
* The meta-bean for {@code NonDeliverableFXForwardSecurity}.
* @return the meta-bean, not null
*/
public static NonDeliverableFXForwardSecurity.Meta meta() {
return NonDeliverableFXForwardSecurity.Meta.INSTANCE;
}
static {
JodaBeanUtils.registerMetaBean(NonDeliverableFXForwardSecurity.Meta.INSTANCE);
}
@Override
public NonDeliverableFXForwardSecurity.Meta metaBean() {
return NonDeliverableFXForwardSecurity.Meta.INSTANCE;
}
@Override
protected Object propertyGet(String propertyName, boolean quiet) {
switch (propertyName.hashCode()) {
case -295641895: // payCurrency
return getPayCurrency();
case -1338781920: // payAmount
return getPayAmount();
case -1228590060: // receiveCurrency
return getReceiveCurrency();
case 984267035: // receiveAmount
return getReceiveAmount();
case 1652755475: // forwardDate
return getForwardDate();
case -690339025: // regionId
return getRegionId();
case 2073187722: // deliverInReceiveCurrency
return isDeliverInReceiveCurrency();
}
return super.propertyGet(propertyName, quiet);
}
@Override
protected void propertySet(String propertyName, Object newValue, boolean quiet) {
switch (propertyName.hashCode()) {
case -295641895: // payCurrency
setPayCurrency((Currency) newValue);
return;
case -1338781920: // payAmount
setPayAmount((Double) newValue);
return;
case -1228590060: // receiveCurrency
setReceiveCurrency((Currency) newValue);
return;
case 984267035: // receiveAmount
setReceiveAmount((Double) newValue);
return;
case 1652755475: // forwardDate
setForwardDate((ZonedDateTime) newValue);
return;
case -690339025: // regionId
setRegionId((ExternalId) newValue);
return;
case 2073187722: // deliverInReceiveCurrency
setDeliverInReceiveCurrency((Boolean) newValue);
return;
}
super.propertySet(propertyName, newValue, quiet);
}
@Override
protected void validate() {
JodaBeanUtils.notNull(_payCurrency, "payCurrency");
JodaBeanUtils.notNull(_receiveCurrency, "receiveCurrency");
JodaBeanUtils.notNull(_forwardDate, "forwardDate");
JodaBeanUtils.notNull(_regionId, "regionId");
super.validate();
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj != null && obj.getClass() == this.getClass()) {
NonDeliverableFXForwardSecurity other = (NonDeliverableFXForwardSecurity) obj;
return JodaBeanUtils.equal(getPayCurrency(), other.getPayCurrency()) &&
JodaBeanUtils.equal(getPayAmount(), other.getPayAmount()) &&
JodaBeanUtils.equal(getReceiveCurrency(), other.getReceiveCurrency()) &&
JodaBeanUtils.equal(getReceiveAmount(), other.getReceiveAmount()) &&
JodaBeanUtils.equal(getForwardDate(), other.getForwardDate()) &&
JodaBeanUtils.equal(getRegionId(), other.getRegionId()) &&
JodaBeanUtils.equal(isDeliverInReceiveCurrency(), other.isDeliverInReceiveCurrency()) &&
super.equals(obj);
}
return false;
}
@Override
public int hashCode() {
int hash = 7;
hash += hash * 31 + JodaBeanUtils.hashCode(getPayCurrency());
hash += hash * 31 + JodaBeanUtils.hashCode(getPayAmount());
hash += hash * 31 + JodaBeanUtils.hashCode(getReceiveCurrency());
hash += hash * 31 + JodaBeanUtils.hashCode(getReceiveAmount());
hash += hash * 31 + JodaBeanUtils.hashCode(getForwardDate());
hash += hash * 31 + JodaBeanUtils.hashCode(getRegionId());
hash += hash * 31 + JodaBeanUtils.hashCode(isDeliverInReceiveCurrency());
return hash ^ super.hashCode();
}
//-----------------------------------------------------------------------
/**
* Gets the payer currency
* @return the value of the property, not null
*/
public Currency getPayCurrency() {
return _payCurrency;
}
/**
* Sets the payer currency
* @param payCurrency the new value of the property, not null
*/
public void setPayCurrency(Currency payCurrency) {
JodaBeanUtils.notNull(payCurrency, "payCurrency");
this._payCurrency = payCurrency;
}
/**
* Gets the the {@code payCurrency} property.
* @return the property, not null
*/
public final Property<Currency> payCurrency() {
return metaBean().payCurrency().createProperty(this);
}
//-----------------------------------------------------------------------
/**
* Gets the pay amount
* @return the value of the property
*/
public double getPayAmount() {
return _payAmount;
}
/**
* Sets the pay amount
* @param payAmount the new value of the property
*/
public void setPayAmount(double payAmount) {
this._payAmount = payAmount;
}
/**
* Gets the the {@code payAmount} property.
* @return the property, not null
*/
public final Property<Double> payAmount() {
return metaBean().payAmount().createProperty(this);
}
//-----------------------------------------------------------------------
/**
* Gets the receiver currency
* @return the value of the property, not null
*/
public Currency getReceiveCurrency() {
return _receiveCurrency;
}
/**
* Sets the receiver currency
* @param receiveCurrency the new value of the property, not null
*/
public void setReceiveCurrency(Currency receiveCurrency) {
JodaBeanUtils.notNull(receiveCurrency, "receiveCurrency");
this._receiveCurrency = receiveCurrency;
}
/**
* Gets the the {@code receiveCurrency} property.
* @return the property, not null
*/
public final Property<Currency> receiveCurrency() {
return metaBean().receiveCurrency().createProperty(this);
}
//-----------------------------------------------------------------------
/**
* Gets the receive amount
* @return the value of the property
*/
public double getReceiveAmount() {
return _receiveAmount;
}
/**
* Sets the receive amount
* @param receiveAmount the new value of the property
*/
public void setReceiveAmount(double receiveAmount) {
this._receiveAmount = receiveAmount;
}
/**
* Gets the the {@code receiveAmount} property.
* @return the property, not null
*/
public final Property<Double> receiveAmount() {
return metaBean().receiveAmount().createProperty(this);
}
//-----------------------------------------------------------------------
/**
* Gets the forward date.
* @return the value of the property, not null
*/
public ZonedDateTime getForwardDate() {
return _forwardDate;
}
/**
* Sets the forward date.
* @param forwardDate the new value of the property, not null
*/
public void setForwardDate(ZonedDateTime forwardDate) {
JodaBeanUtils.notNull(forwardDate, "forwardDate");
this._forwardDate = forwardDate;
}
/**
* Gets the the {@code forwardDate} property.
* @return the property, not null
*/
public final Property<ZonedDateTime> forwardDate() {
return metaBean().forwardDate().createProperty(this);
}
//-----------------------------------------------------------------------
/**
* Gets the region.
* @return the value of the property, not null
*/
public ExternalId getRegionId() {
return _regionId;
}
/**
* Sets the region.
* @param regionId the new value of the property, not null
*/
public void setRegionId(ExternalId regionId) {
JodaBeanUtils.notNull(regionId, "regionId");
this._regionId = regionId;
}
/**
* Gets the the {@code regionId} property.
* @return the property, not null
*/
public final Property<ExternalId> regionId() {
return metaBean().regionId().createProperty(this);
}
//-----------------------------------------------------------------------
/**
* Gets whether to deliver in the receive currency
* @return the value of the property
*/
public boolean isDeliverInReceiveCurrency() {
return _deliverInReceiveCurrency;
}
/**
* Sets whether to deliver in the receive currency
* @param deliverInReceiveCurrency the new value of the property
*/
public void setDeliverInReceiveCurrency(boolean deliverInReceiveCurrency) {
this._deliverInReceiveCurrency = deliverInReceiveCurrency;
}
/**
* Gets the the {@code deliverInReceiveCurrency} property.
* @return the property, not null
*/
public final Property<Boolean> deliverInReceiveCurrency() {
return metaBean().deliverInReceiveCurrency().createProperty(this);
}
//-----------------------------------------------------------------------
/**
* The meta-bean for {@code NonDeliverableFXForwardSecurity}.
*/
public static class Meta extends FinancialSecurity.Meta {
/**
* The singleton instance of the meta-bean.
*/
static final Meta INSTANCE = new Meta();
/**
* The meta-property for the {@code payCurrency} property.
*/
private final MetaProperty<Currency> _payCurrency = DirectMetaProperty.ofReadWrite(
this, "payCurrency", NonDeliverableFXForwardSecurity.class, Currency.class);
/**
* The meta-property for the {@code payAmount} property.
*/
private final MetaProperty<Double> _payAmount = DirectMetaProperty.ofReadWrite(
this, "payAmount", NonDeliverableFXForwardSecurity.class, Double.TYPE);
/**
* The meta-property for the {@code receiveCurrency} property.
*/
private final MetaProperty<Currency> _receiveCurrency = DirectMetaProperty.ofReadWrite(
this, "receiveCurrency", NonDeliverableFXForwardSecurity.class, Currency.class);
/**
* The meta-property for the {@code receiveAmount} property.
*/
private final MetaProperty<Double> _receiveAmount = DirectMetaProperty.ofReadWrite(
this, "receiveAmount", NonDeliverableFXForwardSecurity.class, Double.TYPE);
/**
* The meta-property for the {@code forwardDate} property.
*/
private final MetaProperty<ZonedDateTime> _forwardDate = DirectMetaProperty.ofReadWrite(
this, "forwardDate", NonDeliverableFXForwardSecurity.class, ZonedDateTime.class);
/**
* The meta-property for the {@code regionId} property.
*/
private final MetaProperty<ExternalId> _regionId = DirectMetaProperty.ofReadWrite(
this, "regionId", NonDeliverableFXForwardSecurity.class, ExternalId.class);
/**
* The meta-property for the {@code deliverInReceiveCurrency} property.
*/
private final MetaProperty<Boolean> _deliverInReceiveCurrency = DirectMetaProperty.ofReadWrite(
this, "deliverInReceiveCurrency", NonDeliverableFXForwardSecurity.class, Boolean.TYPE);
/**
* The meta-properties.
*/
private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap(
this, (DirectMetaPropertyMap) super.metaPropertyMap(),
"payCurrency",
"payAmount",
"receiveCurrency",
"receiveAmount",
"forwardDate",
"regionId",
"deliverInReceiveCurrency");
/**
* Restricted constructor.
*/
protected Meta() {
}
@Override
protected MetaProperty<?> metaPropertyGet(String propertyName) {
switch (propertyName.hashCode()) {
case -295641895: // payCurrency
return _payCurrency;
case -1338781920: // payAmount
return _payAmount;
case -1228590060: // receiveCurrency
return _receiveCurrency;
case 984267035: // receiveAmount
return _receiveAmount;
case 1652755475: // forwardDate
return _forwardDate;
case -690339025: // regionId
return _regionId;
case 2073187722: // deliverInReceiveCurrency
return _deliverInReceiveCurrency;
}
return super.metaPropertyGet(propertyName);
}
@Override
public BeanBuilder<? extends NonDeliverableFXForwardSecurity> builder() {
return new DirectBeanBuilder<NonDeliverableFXForwardSecurity>(new NonDeliverableFXForwardSecurity());
}
@Override
public Class<? extends NonDeliverableFXForwardSecurity> beanType() {
return NonDeliverableFXForwardSecurity.class;
}
@Override
public Map<String, MetaProperty<?>> metaPropertyMap() {
return _metaPropertyMap$;
}
//-----------------------------------------------------------------------
/**
* The meta-property for the {@code payCurrency} property.
* @return the meta-property, not null
*/
public final MetaProperty<Currency> payCurrency() {
return _payCurrency;
}
/**
* The meta-property for the {@code payAmount} property.
* @return the meta-property, not null
*/
public final MetaProperty<Double> payAmount() {
return _payAmount;
}
/**
* The meta-property for the {@code receiveCurrency} property.
* @return the meta-property, not null
*/
public final MetaProperty<Currency> receiveCurrency() {
return _receiveCurrency;
}
/**
* The meta-property for the {@code receiveAmount} property.
* @return the meta-property, not null
*/
public final MetaProperty<Double> receiveAmount() {
return _receiveAmount;
}
/**
* The meta-property for the {@code forwardDate} property.
* @return the meta-property, not null
*/
public final MetaProperty<ZonedDateTime> forwardDate() {
return _forwardDate;
}
/**
* The meta-property for the {@code regionId} property.
* @return the meta-property, not null
*/
public final MetaProperty<ExternalId> regionId() {
return _regionId;
}
/**
* The meta-property for the {@code deliverInReceiveCurrency} property.
* @return the meta-property, not null
*/
public final MetaProperty<Boolean> deliverInReceiveCurrency() {
return _deliverInReceiveCurrency;
}
}
///CLOVER:ON
//-------------------------- AUTOGENERATED END --------------------------
}
|
package ru.job4j.array;
/**
* Igor Khmelevskiy (igorkkhm@gmail.com)
* @version $Id$
* @since 0.1
*/
public class BubbleSort {
/**
* Метод сортировки массива пузырьком (перестановкой).
* @param array Исходный массив.
* @return Сортированный массив.
*/
public int[] sort(int[] array) {
int temp;
// внешний цикл контролирует количество проходов по всему массиву
for (int i = 0; i < array.length; i++ ) {
// внутренний цикл сдвигает более крупные числа максимально возможно вправо
for (int j = 0; j < array.length - 1; j++) {
if (array[j] > array[j+1]) {
temp = array[j + 1];
array[j + 1] = array[j];
array[j] = temp;
}
}
}
return array;
}
}
|
/*
* 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.sling.commons.log.logback.internal;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.CoreConstants;
import ch.qos.logback.core.FileAppender;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.status.Status;
import ch.qos.logback.core.util.CachingDateFormatter;
/**
* The <code>SlingConfigurationPrinter</code> is an Apache Felix Web Console
* plugin to display the currently configured log files.
*/
@SuppressWarnings("JavadocReference")
public class SlingConfigurationPrinter {
private static final CachingDateFormatter SDF = new CachingDateFormatter("yyyy-MM-dd HH:mm:ss");
private static final String MODE_ZIP = "zip";
private final LogbackManager logbackManager;
public SlingConfigurationPrinter(LogbackManager logbackManager) {
this.logbackManager = logbackManager;
}
/**
* @see org.apache.felix.webconsole.ConfigurationPrinter#printConfiguration(java.io.PrintWriter)
*/
@SuppressWarnings("UnusedDeclaration")
public void printConfiguration(PrintWriter printWriter, String mode) {
LogbackManager.LoggerStateContext ctx = logbackManager.determineLoggerState();
int numOfLines = getNumOfLines();
Tailer tailer = new Tailer(printWriter, numOfLines);
dumpLogFileSummary(printWriter, ctx.getAllAppenders());
if (!MODE_ZIP.equals(mode)) {
for (Appender<ILoggingEvent> appender : ctx.getAllAppenders()) {
if (appender instanceof FileAppender) {
final File file = new File(((FileAppender) appender).getFile());
if (file.exists()) {
printWriter.print("Log file ");
printWriter.println(file.getAbsolutePath());
printWriter.println("--------------------------------------------------");
if (numOfLines < 0) {
includeWholeFile(printWriter, file);
} else {
try {
tailer.tail(file);
} catch (IOException e) {
logbackManager.getLogConfigManager().internalFailure("Error occurred " +
"while processing log file " + file, e);
}
}
printWriter.println();
}
}
}
}
dumpLogbackStatus(logbackManager, printWriter);
}
static void includeWholeFile(PrintWriter printWriter, File file) {
FileReader fr = null;
try {
fr = new FileReader(file);
final char[] buffer = new char[512];
int len;
while ((len = fr.read(buffer)) != -1) {
printWriter.write(buffer, 0, len);
}
} catch (IOException ignore) {
// we just ignore this
} finally {
if (fr != null) {
try {
fr.close();
} catch (IOException ignored) {
}
}
}
}
private void dumpLogFileSummary(PrintWriter pw, Collection<Appender<ILoggingEvent>> appenders) {
pw.println("Summary");
pw.println("=======");
pw.println();
int counter = 0;
final String rootDir = logbackManager.getRootDir();
for (Appender<ILoggingEvent> appender : appenders) {
if (appender instanceof FileAppender) {
File file = new File(((FileAppender) appender).getFile());
final File dir = file.getParentFile();
final String baseName = file.getName();
String absolutePath = dir.getAbsolutePath();
String displayName = ((FileAppender) appender).getFile();
if (absolutePath.startsWith(rootDir)) {
displayName = baseName;
}
pw.printf("%d. %s %n", ++counter, displayName);
final File[] files = getRotatedFiles((FileAppender) appender, -1);
for (File f : files) {
pw.printf(" - %s, %s, %s %n", f.getName(), humanReadableByteCount(f.length()), getModifiedDate(f));
}
}
}
pw.println();
}
/**
* Attempts to determine all log files created even via rotation.
* if some complex rotation logic is used where rotated file get different names
* or get created in different directory then those files would not be
* included
*
* @see org.apache.felix.webconsole.AttachmentProvider#getAttachments(String)
*/
@SuppressWarnings("UnusedDeclaration")
public URL[] getAttachments(String mode) {
// we only provide urls for mode zip
if (MODE_ZIP.equals(mode)) {
final List<URL> urls = new ArrayList<URL>();
LogbackManager.LoggerStateContext ctx = logbackManager.determineLoggerState();
for (Appender<ILoggingEvent> appender : ctx.getAllAppenders()) {
if (appender instanceof FileAppender) {
final File[] files = getRotatedFiles((FileAppender) appender, getMaxOldFileCount());
for (File f : files) {
try {
urls.add(f.toURI().toURL());
} catch (MalformedURLException mue) {
// we just ignore this file then
}
}
}
}
if (urls.size() > 0) {
return urls.toArray(new URL[urls.size()]);
}
}
return null;
}
/**
* @param app appender instance
* @param maxOldFileCount -1 if all files need to be included. Otherwise max
* old files to include
* @return sorted array of files generated by passed appender
*/
private File[] getRotatedFiles(FileAppender app, int maxOldFileCount) {
final File file = new File(app.getFile());
//If RollingFileAppender then make an attempt to list files
//This might not work in all cases if complex rolling patterns
//are used in Logback
if (app instanceof RollingFileAppender) {
final File dir = file.getParentFile();
final String baseName = file.getName();
File[] result = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith(baseName);
}
});
//Sort the files in reverse
Arrays.sort(result, Collections.reverseOrder(new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
long o1t = o1.lastModified();
long o2t = o2.lastModified();
return o1t < o2t ? -1 : (o1t == o2t ? 0 : 1);
}
}));
if (maxOldFileCount > 0) {
int maxCount = Math.min(getMaxOldFileCount(), result.length);
if (maxCount < result.length) {
File[] resultCopy = new File[maxCount];
System.arraycopy(result, 0, resultCopy, 0, maxCount);
return resultCopy;
}
}
return result;
}
//Not a RollingFileAppender then just return the actual file
return new File[]{file};
}
private int getNumOfLines(){
return logbackManager.getLogConfigManager().getNumOfLines();
}
private int getMaxOldFileCount(){
return logbackManager.getLogConfigManager().getMaxOldFileCount();
}
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
private static void dumpLogbackStatus(LogbackManager logbackManager, PrintWriter pw) {
List<Status> statusList = logbackManager.getStatusManager().getCopyOfStatusList();
pw.println("Logback Status");
pw.println("--------------------------------------------------");
for (Status s : statusList) {
pw.printf("%s *%s* %s - %s %n",
SDF.format(s.getDate()),
statusLevelAsString(s),
abbreviatedOrigin(s),
s.getMessage());
if (s.getThrowable() != null) {
s.getThrowable().printStackTrace(pw);
}
}
pw.println();
}
static String abbreviatedOrigin(Status s) {
Object o = s.getOrigin();
if (o == null) {
return null;
}
String fqClassName = o.getClass().getName();
int lastIndex = fqClassName.lastIndexOf(CoreConstants.DOT);
if (lastIndex != -1) {
return fqClassName.substring(lastIndex + 1, fqClassName.length());
} else {
return fqClassName;
}
}
private static String statusLevelAsString(Status s) {
switch (s.getEffectiveLevel()) {
case Status.INFO:
return "INFO";
case Status.WARN:
return "WARN";
case Status.ERROR:
return "ERROR";
}
return null;
}
/**
* Returns a human-readable version of the file size, where the input represents
* a specific number of bytes. Based on http://stackoverflow.com/a/3758880/1035417
*/
private static String humanReadableByteCount(long bytes) {
if (bytes < 0) {
return "0";
}
int unit = 1000;
if (bytes < unit) {
return bytes + " B";
}
int exp = (int) (Math.log(bytes) / Math.log(unit));
char pre = "kMGTPE".charAt(exp - 1);
return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
}
private static String getModifiedDate(File f){
long modified = f.lastModified();
if (modified == 0){
return "UNKNOWN";
}
return SDF.format(modified);
}
}
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.engine;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.codecs.Codec;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexCommit;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.LeafReader;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.LiveIndexWriterConfig;
import org.apache.lucene.index.MergePolicy;
import org.apache.lucene.index.NumericDocValues;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.ReferenceManager;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TotalHitCountCollector;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.Version;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.cluster.ClusterModule;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.routing.AllocationId;
import org.elasticsearch.common.CheckedBiFunction;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Randomness;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.breaker.CircuitBreaker;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.compress.CompressedXContent;
import org.elasticsearch.common.lucene.Lucene;
import org.elasticsearch.common.lucene.uid.Versions;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.BigArrays;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.core.internal.io.IOUtils;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.MapperTestUtils;
import org.elasticsearch.index.VersionType;
import org.elasticsearch.index.codec.CodecService;
import org.elasticsearch.index.mapper.DocumentMapper;
import org.elasticsearch.index.mapper.IdFieldMapper;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.mapper.Mapping;
import org.elasticsearch.index.mapper.ParseContext;
import org.elasticsearch.index.mapper.ParsedDocument;
import org.elasticsearch.index.mapper.SeqNoFieldMapper;
import org.elasticsearch.index.mapper.SourceFieldMapper;
import org.elasticsearch.index.mapper.SourceToParse;
import org.elasticsearch.index.mapper.Uid;
import org.elasticsearch.index.mapper.VersionFieldMapper;
import org.elasticsearch.index.seqno.LocalCheckpointTracker;
import org.elasticsearch.index.seqno.ReplicationTracker;
import org.elasticsearch.index.seqno.RetentionLeases;
import org.elasticsearch.index.seqno.SequenceNumbers;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.store.Store;
import org.elasticsearch.index.translog.Translog;
import org.elasticsearch.index.translog.TranslogConfig;
import org.elasticsearch.indices.breaker.CircuitBreakerService;
import org.elasticsearch.indices.breaker.NoneCircuitBreakerService;
import org.elasticsearch.test.DummyShardLock;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.IndexSettingsModule;
import org.elasticsearch.threadpool.TestThreadPool;
import org.elasticsearch.threadpool.ThreadPool;
import org.junit.After;
import org.junit.Before;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.LongSupplier;
import java.util.function.Supplier;
import java.util.function.ToLongBiFunction;
import java.util.stream.Collectors;
import static java.util.Collections.emptyList;
import static java.util.Collections.shuffle;
import static org.elasticsearch.index.engine.Engine.Operation.Origin.PRIMARY;
import static org.elasticsearch.index.engine.Engine.Operation.Origin.REPLICA;
import static org.elasticsearch.index.translog.TranslogDeletionPolicies.createTranslogDeletionPolicy;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.notNullValue;
public abstract class EngineTestCase extends ESTestCase {
protected final ShardId shardId = new ShardId(new Index("index", "_na_"), 0);
protected final AllocationId allocationId = AllocationId.newInitializing();
protected static final IndexSettings INDEX_SETTINGS = IndexSettingsModule.newIndexSettings("index", Settings.EMPTY);
protected ThreadPool threadPool;
protected TranslogHandler translogHandler;
protected Store store;
protected Store storeReplica;
protected InternalEngine engine;
protected InternalEngine replicaEngine;
protected IndexSettings defaultSettings;
protected String codecName;
protected Path primaryTranslogDir;
protected Path replicaTranslogDir;
// A default primary term is used by engine instances created in this test.
protected final PrimaryTermSupplier primaryTerm = new PrimaryTermSupplier(0L);
protected static void assertVisibleCount(Engine engine, int numDocs) throws IOException {
assertVisibleCount(engine, numDocs, true);
}
protected static void assertVisibleCount(Engine engine, int numDocs, boolean refresh) throws IOException {
if (refresh) {
engine.refresh("test");
}
try (Engine.Searcher searcher = engine.acquireSearcher("test")) {
final TotalHitCountCollector collector = new TotalHitCountCollector();
searcher.searcher().search(new MatchAllDocsQuery(), collector);
assertThat(collector.getTotalHits(), equalTo(numDocs));
}
}
protected Settings indexSettings() {
// TODO randomize more settings
return Settings.builder()
.put(IndexSettings.INDEX_GC_DELETES_SETTING.getKey(), "1h") // make sure this doesn't kick in on us
.put(EngineConfig.INDEX_CODEC_SETTING.getKey(), codecName)
.put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT)
.put(IndexSettings.MAX_REFRESH_LISTENERS_PER_SHARD.getKey(),
between(10, 10 * IndexSettings.MAX_REFRESH_LISTENERS_PER_SHARD.get(Settings.EMPTY)))
.put(IndexSettings.INDEX_SOFT_DELETES_SETTING.getKey(), randomBoolean())
.put(IndexSettings.INDEX_SOFT_DELETES_RETENTION_OPERATIONS_SETTING.getKey(),
randomBoolean() ? IndexSettings.INDEX_SOFT_DELETES_RETENTION_OPERATIONS_SETTING.get(Settings.EMPTY) : between(0, 1000))
.build();
}
@Override
@Before
public void setUp() throws Exception {
super.setUp();
primaryTerm.set(randomLongBetween(1, Long.MAX_VALUE));
CodecService codecService = new CodecService(null, logger);
String name = Codec.getDefault().getName();
if (Arrays.asList(codecService.availableCodecs()).contains(name)) {
// some codecs are read only so we only take the ones that we have in the service and randomly
// selected by lucene test case.
codecName = name;
} else {
codecName = "default";
}
defaultSettings = IndexSettingsModule.newIndexSettings("test", indexSettings());
threadPool = new TestThreadPool(getClass().getName());
store = createStore();
storeReplica = createStore();
Lucene.cleanLuceneIndex(store.directory());
Lucene.cleanLuceneIndex(storeReplica.directory());
primaryTranslogDir = createTempDir("translog-primary");
translogHandler = createTranslogHandler(defaultSettings);
engine = createEngine(store, primaryTranslogDir);
LiveIndexWriterConfig currentIndexWriterConfig = engine.getCurrentIndexWriterConfig();
assertEquals(engine.config().getCodec().getName(), codecService.codec(codecName).getName());
assertEquals(currentIndexWriterConfig.getCodec().getName(), codecService.codec(codecName).getName());
if (randomBoolean()) {
engine.config().setEnableGcDeletes(false);
}
replicaTranslogDir = createTempDir("translog-replica");
replicaEngine = createEngine(storeReplica, replicaTranslogDir);
currentIndexWriterConfig = replicaEngine.getCurrentIndexWriterConfig();
assertEquals(replicaEngine.config().getCodec().getName(), codecService.codec(codecName).getName());
assertEquals(currentIndexWriterConfig.getCodec().getName(), codecService.codec(codecName).getName());
if (randomBoolean()) {
engine.config().setEnableGcDeletes(false);
}
}
public EngineConfig copy(EngineConfig config, LongSupplier globalCheckpointSupplier) {
return new EngineConfig(config.getShardId(), config.getAllocationId(), config.getThreadPool(), config.getIndexSettings(),
config.getWarmer(), config.getStore(), config.getMergePolicy(), config.getAnalyzer(), config.getSimilarity(),
new CodecService(null, logger), config.getEventListener(), config.getQueryCache(), config.getQueryCachingPolicy(),
config.getTranslogConfig(), config.getFlushMergesAfter(),
config.getExternalRefreshListener(), Collections.emptyList(), config.getIndexSort(),
config.getCircuitBreakerService(), globalCheckpointSupplier, config.retentionLeasesSupplier(),
config.getPrimaryTermSupplier(), tombstoneDocSupplier());
}
public EngineConfig copy(EngineConfig config, Analyzer analyzer) {
return new EngineConfig(config.getShardId(), config.getAllocationId(), config.getThreadPool(), config.getIndexSettings(),
config.getWarmer(), config.getStore(), config.getMergePolicy(), analyzer, config.getSimilarity(),
new CodecService(null, logger), config.getEventListener(), config.getQueryCache(), config.getQueryCachingPolicy(),
config.getTranslogConfig(), config.getFlushMergesAfter(),
config.getExternalRefreshListener(), Collections.emptyList(), config.getIndexSort(),
config.getCircuitBreakerService(), config.getGlobalCheckpointSupplier(), config.retentionLeasesSupplier(),
config.getPrimaryTermSupplier(), config.getTombstoneDocSupplier());
}
public EngineConfig copy(EngineConfig config, MergePolicy mergePolicy) {
return new EngineConfig(config.getShardId(), config.getAllocationId(), config.getThreadPool(), config.getIndexSettings(),
config.getWarmer(), config.getStore(), mergePolicy, config.getAnalyzer(), config.getSimilarity(),
new CodecService(null, logger), config.getEventListener(), config.getQueryCache(), config.getQueryCachingPolicy(),
config.getTranslogConfig(), config.getFlushMergesAfter(),
config.getExternalRefreshListener(), Collections.emptyList(), config.getIndexSort(),
config.getCircuitBreakerService(), config.getGlobalCheckpointSupplier(), config.retentionLeasesSupplier(),
config.getPrimaryTermSupplier(), config.getTombstoneDocSupplier());
}
@Override
@After
public void tearDown() throws Exception {
super.tearDown();
try {
if (engine != null && engine.isClosed.get() == false) {
engine.getTranslog().getDeletionPolicy().assertNoOpenTranslogRefs();
assertConsistentHistoryBetweenTranslogAndLuceneIndex(engine, createMapperService("test"));
assertMaxSeqNoInCommitUserData(engine);
}
if (replicaEngine != null && replicaEngine.isClosed.get() == false) {
replicaEngine.getTranslog().getDeletionPolicy().assertNoOpenTranslogRefs();
assertConsistentHistoryBetweenTranslogAndLuceneIndex(replicaEngine, createMapperService("test"));
assertMaxSeqNoInCommitUserData(replicaEngine);
}
assertThat(engine.config().getCircuitBreakerService().getBreaker(CircuitBreaker.ACCOUNTING).getUsed(), equalTo(0L));
assertThat(replicaEngine.config().getCircuitBreakerService().getBreaker(CircuitBreaker.ACCOUNTING).getUsed(), equalTo(0L));
} finally {
IOUtils.close(replicaEngine, storeReplica, engine, store, () -> terminate(threadPool));
}
}
protected static ParseContext.Document testDocumentWithTextField() {
return testDocumentWithTextField("test");
}
protected static ParseContext.Document testDocumentWithTextField(String value) {
ParseContext.Document document = testDocument();
document.add(new TextField("value", value, Field.Store.YES));
return document;
}
protected static ParseContext.Document testDocument() {
return new ParseContext.Document();
}
public static ParsedDocument createParsedDoc(String id, String routing) {
return testParsedDocument(id, routing, testDocumentWithTextField(), new BytesArray("{ \"value\" : \"test\" }"), null);
}
public static ParsedDocument createParsedDoc(String id, String routing, boolean recoverySource) {
return testParsedDocument(id, routing, testDocumentWithTextField(), new BytesArray("{ \"value\" : \"test\" }"), null,
recoverySource);
}
protected static ParsedDocument testParsedDocument(
String id, String routing, ParseContext.Document document, BytesReference source, Mapping mappingUpdate) {
return testParsedDocument(id, routing, document, source, mappingUpdate, false);
}
protected static ParsedDocument testParsedDocument(
String id, String routing, ParseContext.Document document, BytesReference source, Mapping mappingUpdate,
boolean recoverySource) {
Field uidField = new Field("_id", Uid.encodeId(id), IdFieldMapper.Defaults.FIELD_TYPE);
Field versionField = new NumericDocValuesField("_version", 0);
SeqNoFieldMapper.SequenceIDFields seqID = SeqNoFieldMapper.SequenceIDFields.emptySeqID();
document.add(uidField);
document.add(versionField);
document.add(seqID.seqNo);
document.add(seqID.seqNoDocValue);
document.add(seqID.primaryTerm);
BytesRef ref = source.toBytesRef();
if (recoverySource) {
document.add(new StoredField(SourceFieldMapper.RECOVERY_SOURCE_NAME, ref.bytes, ref.offset, ref.length));
document.add(new NumericDocValuesField(SourceFieldMapper.RECOVERY_SOURCE_NAME, 1));
} else {
document.add(new StoredField(SourceFieldMapper.NAME, ref.bytes, ref.offset, ref.length));
}
return new ParsedDocument(versionField, seqID, id, "test", routing, Arrays.asList(document), source, XContentType.JSON,
mappingUpdate);
}
public static CheckedBiFunction<String, Integer, ParsedDocument, IOException> nestedParsedDocFactory() throws Exception {
final MapperService mapperService = createMapperService("type");
final String nestedMapping = Strings.toString(XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties").startObject("nested_field").field("type", "nested").endObject().endObject()
.endObject().endObject());
final DocumentMapper nestedMapper = mapperService.documentMapperParser().parse("type", new CompressedXContent(nestedMapping));
return (docId, nestedFieldValues) -> {
final XContentBuilder source = XContentFactory.jsonBuilder().startObject().field("field", "value");
if (nestedFieldValues > 0) {
XContentBuilder nestedField = source.startObject("nested_field");
for (int i = 0; i < nestedFieldValues; i++) {
nestedField.field("field-" + i, "value-" + i);
}
source.endObject();
}
source.endObject();
return nestedMapper.parse(new SourceToParse("test", "type", docId, BytesReference.bytes(source), XContentType.JSON));
};
}
/**
* Creates a tombstone document that only includes uid, seq#, term and version fields.
*/
public static EngineConfig.TombstoneDocSupplier tombstoneDocSupplier(){
return new EngineConfig.TombstoneDocSupplier() {
@Override
public ParsedDocument newDeleteTombstoneDoc(String type, String id) {
final ParseContext.Document doc = new ParseContext.Document();
Field uidField = new Field(IdFieldMapper.NAME, Uid.encodeId(id), IdFieldMapper.Defaults.FIELD_TYPE);
doc.add(uidField);
Field versionField = new NumericDocValuesField(VersionFieldMapper.NAME, 0);
doc.add(versionField);
SeqNoFieldMapper.SequenceIDFields seqID = SeqNoFieldMapper.SequenceIDFields.emptySeqID();
doc.add(seqID.seqNo);
doc.add(seqID.seqNoDocValue);
doc.add(seqID.primaryTerm);
seqID.tombstoneField.setLongValue(1);
doc.add(seqID.tombstoneField);
return new ParsedDocument(versionField, seqID, id, type, null,
Collections.singletonList(doc), new BytesArray("{}"), XContentType.JSON, null);
}
@Override
public ParsedDocument newNoopTombstoneDoc(String reason) {
final ParseContext.Document doc = new ParseContext.Document();
SeqNoFieldMapper.SequenceIDFields seqID = SeqNoFieldMapper.SequenceIDFields.emptySeqID();
doc.add(seqID.seqNo);
doc.add(seqID.seqNoDocValue);
doc.add(seqID.primaryTerm);
seqID.tombstoneField.setLongValue(1);
doc.add(seqID.tombstoneField);
Field versionField = new NumericDocValuesField(VersionFieldMapper.NAME, 0);
doc.add(versionField);
BytesRef byteRef = new BytesRef(reason);
doc.add(new StoredField(SourceFieldMapper.NAME, byteRef.bytes, byteRef.offset, byteRef.length));
return new ParsedDocument(versionField, seqID, null, null, null,
Collections.singletonList(doc), null, XContentType.JSON, null);
}
};
}
protected Store createStore() throws IOException {
return createStore(newDirectory());
}
protected Store createStore(final Directory directory) throws IOException {
return createStore(INDEX_SETTINGS, directory);
}
protected Store createStore(final IndexSettings indexSettings, final Directory directory) throws IOException {
return new Store(shardId, indexSettings, directory, new DummyShardLock(shardId));
}
protected Translog createTranslog(LongSupplier primaryTermSupplier) throws IOException {
return createTranslog(primaryTranslogDir, primaryTermSupplier);
}
protected Translog createTranslog(Path translogPath, LongSupplier primaryTermSupplier) throws IOException {
TranslogConfig translogConfig = new TranslogConfig(shardId, translogPath, INDEX_SETTINGS, BigArrays.NON_RECYCLING_INSTANCE);
String translogUUID = Translog.createEmptyTranslog(translogPath, SequenceNumbers.NO_OPS_PERFORMED, shardId,
primaryTermSupplier.getAsLong());
return new Translog(translogConfig, translogUUID, createTranslogDeletionPolicy(INDEX_SETTINGS),
() -> SequenceNumbers.NO_OPS_PERFORMED, primaryTermSupplier);
}
protected TranslogHandler createTranslogHandler(IndexSettings indexSettings) {
return new TranslogHandler(xContentRegistry(), indexSettings);
}
protected InternalEngine createEngine(Store store, Path translogPath) throws IOException {
return createEngine(defaultSettings, store, translogPath, newMergePolicy(), null);
}
protected InternalEngine createEngine(Store store, Path translogPath, LongSupplier globalCheckpointSupplier) throws IOException {
return createEngine(defaultSettings, store, translogPath, newMergePolicy(), null, null, globalCheckpointSupplier);
}
protected InternalEngine createEngine(
Store store,
Path translogPath,
BiFunction<Long, Long, LocalCheckpointTracker> localCheckpointTrackerSupplier) throws IOException {
return createEngine(defaultSettings, store, translogPath, newMergePolicy(), null, localCheckpointTrackerSupplier, null);
}
protected InternalEngine createEngine(
Store store,
Path translogPath,
BiFunction<Long, Long, LocalCheckpointTracker> localCheckpointTrackerSupplier,
ToLongBiFunction<Engine, Engine.Operation> seqNoForOperation) throws IOException {
return createEngine(
defaultSettings, store, translogPath, newMergePolicy(), null, localCheckpointTrackerSupplier, null, seqNoForOperation);
}
protected InternalEngine createEngine(
IndexSettings indexSettings, Store store, Path translogPath, MergePolicy mergePolicy) throws IOException {
return createEngine(indexSettings, store, translogPath, mergePolicy, null);
}
protected InternalEngine createEngine(IndexSettings indexSettings, Store store, Path translogPath, MergePolicy mergePolicy,
@Nullable IndexWriterFactory indexWriterFactory) throws IOException {
return createEngine(indexSettings, store, translogPath, mergePolicy, indexWriterFactory, null, null);
}
protected InternalEngine createEngine(
IndexSettings indexSettings,
Store store,
Path translogPath,
MergePolicy mergePolicy,
@Nullable IndexWriterFactory indexWriterFactory,
@Nullable BiFunction<Long, Long, LocalCheckpointTracker> localCheckpointTrackerSupplier,
@Nullable LongSupplier globalCheckpointSupplier) throws IOException {
return createEngine(
indexSettings, store, translogPath, mergePolicy, indexWriterFactory, localCheckpointTrackerSupplier, null, null,
globalCheckpointSupplier);
}
protected InternalEngine createEngine(
IndexSettings indexSettings,
Store store,
Path translogPath,
MergePolicy mergePolicy,
@Nullable IndexWriterFactory indexWriterFactory,
@Nullable BiFunction<Long, Long, LocalCheckpointTracker> localCheckpointTrackerSupplier,
@Nullable LongSupplier globalCheckpointSupplier,
@Nullable ToLongBiFunction<Engine, Engine.Operation> seqNoForOperation) throws IOException {
return createEngine(
indexSettings,
store,
translogPath,
mergePolicy,
indexWriterFactory,
localCheckpointTrackerSupplier,
seqNoForOperation,
null,
globalCheckpointSupplier);
}
protected InternalEngine createEngine(
IndexSettings indexSettings,
Store store,
Path translogPath,
MergePolicy mergePolicy,
@Nullable IndexWriterFactory indexWriterFactory,
@Nullable BiFunction<Long, Long, LocalCheckpointTracker> localCheckpointTrackerSupplier,
@Nullable ToLongBiFunction<Engine, Engine.Operation> seqNoForOperation,
@Nullable Sort indexSort,
@Nullable LongSupplier globalCheckpointSupplier) throws IOException {
EngineConfig config = config(indexSettings, store, translogPath, mergePolicy, null, indexSort, globalCheckpointSupplier);
return createEngine(indexWriterFactory, localCheckpointTrackerSupplier, seqNoForOperation, config);
}
protected InternalEngine createEngine(EngineConfig config) throws IOException {
return createEngine(null, null, null, config);
}
protected InternalEngine createEngine(@Nullable IndexWriterFactory indexWriterFactory,
@Nullable BiFunction<Long, Long, LocalCheckpointTracker> localCheckpointTrackerSupplier,
@Nullable ToLongBiFunction<Engine, Engine.Operation> seqNoForOperation,
EngineConfig config) throws IOException {
final Store store = config.getStore();
final Directory directory = store.directory();
if (Lucene.indexExists(directory) == false) {
store.createEmpty(config.getIndexSettings().getIndexVersionCreated().luceneVersion);
final String translogUuid = Translog.createEmptyTranslog(config.getTranslogConfig().getTranslogPath(),
SequenceNumbers.NO_OPS_PERFORMED, shardId, primaryTerm.get());
store.associateIndexWithNewTranslog(translogUuid);
}
InternalEngine internalEngine = createInternalEngine(indexWriterFactory, localCheckpointTrackerSupplier, seqNoForOperation, config);
internalEngine.recoverFromTranslog(translogHandler, Long.MAX_VALUE);
return internalEngine;
}
@FunctionalInterface
public interface IndexWriterFactory {
IndexWriter createWriter(Directory directory, IndexWriterConfig iwc) throws IOException;
}
/**
* Generate a new sequence number and return it. Only works on InternalEngines
*/
public static long generateNewSeqNo(final Engine engine) {
assert engine instanceof InternalEngine : "expected InternalEngine, got: " + engine.getClass();
InternalEngine internalEngine = (InternalEngine) engine;
return internalEngine.getLocalCheckpointTracker().generateSeqNo();
}
public static InternalEngine createInternalEngine(
@Nullable final IndexWriterFactory indexWriterFactory,
@Nullable final BiFunction<Long, Long, LocalCheckpointTracker> localCheckpointTrackerSupplier,
@Nullable final ToLongBiFunction<Engine, Engine.Operation> seqNoForOperation,
final EngineConfig config) {
if (localCheckpointTrackerSupplier == null) {
return new InternalTestEngine(config) {
@Override
IndexWriter createWriter(Directory directory, IndexWriterConfig iwc) throws IOException {
return (indexWriterFactory != null) ?
indexWriterFactory.createWriter(directory, iwc) :
super.createWriter(directory, iwc);
}
@Override
protected long doGenerateSeqNoForOperation(final Operation operation) {
return seqNoForOperation != null
? seqNoForOperation.applyAsLong(this, operation)
: super.doGenerateSeqNoForOperation(operation);
}
};
} else {
return new InternalTestEngine(config, localCheckpointTrackerSupplier) {
@Override
IndexWriter createWriter(Directory directory, IndexWriterConfig iwc) throws IOException {
return (indexWriterFactory != null) ?
indexWriterFactory.createWriter(directory, iwc) :
super.createWriter(directory, iwc);
}
@Override
protected long doGenerateSeqNoForOperation(final Operation operation) {
return seqNoForOperation != null
? seqNoForOperation.applyAsLong(this, operation)
: super.doGenerateSeqNoForOperation(operation);
}
};
}
}
public EngineConfig config(IndexSettings indexSettings, Store store, Path translogPath, MergePolicy mergePolicy,
ReferenceManager.RefreshListener refreshListener) {
return config(indexSettings, store, translogPath, mergePolicy, refreshListener, null, () -> SequenceNumbers.NO_OPS_PERFORMED);
}
public EngineConfig config(IndexSettings indexSettings, Store store, Path translogPath, MergePolicy mergePolicy,
ReferenceManager.RefreshListener refreshListener, Sort indexSort, LongSupplier globalCheckpointSupplier) {
return config(
indexSettings,
store,
translogPath,
mergePolicy,
refreshListener,
indexSort,
globalCheckpointSupplier,
globalCheckpointSupplier == null ? null : () -> RetentionLeases.EMPTY);
}
public EngineConfig config(
final IndexSettings indexSettings,
final Store store,
final Path translogPath,
final MergePolicy mergePolicy,
final ReferenceManager.RefreshListener refreshListener,
final Sort indexSort,
final LongSupplier globalCheckpointSupplier,
final Supplier<RetentionLeases> retentionLeasesSupplier) {
return config(
indexSettings,
store,
translogPath,
mergePolicy,
refreshListener,
null,
indexSort,
globalCheckpointSupplier,
retentionLeasesSupplier,
new NoneCircuitBreakerService());
}
public EngineConfig config(IndexSettings indexSettings, Store store, Path translogPath, MergePolicy mergePolicy,
ReferenceManager.RefreshListener externalRefreshListener,
ReferenceManager.RefreshListener internalRefreshListener,
Sort indexSort, @Nullable LongSupplier maybeGlobalCheckpointSupplier,
CircuitBreakerService breakerService) {
return config(
indexSettings,
store,
translogPath,
mergePolicy,
externalRefreshListener,
internalRefreshListener,
indexSort,
maybeGlobalCheckpointSupplier,
maybeGlobalCheckpointSupplier == null ? null : () -> RetentionLeases.EMPTY,
breakerService);
}
public EngineConfig config(
final IndexSettings indexSettings,
final Store store,
final Path translogPath,
final MergePolicy mergePolicy,
final ReferenceManager.RefreshListener externalRefreshListener,
final ReferenceManager.RefreshListener internalRefreshListener,
final Sort indexSort,
final @Nullable LongSupplier maybeGlobalCheckpointSupplier,
final @Nullable Supplier<RetentionLeases> maybeRetentionLeasesSupplier,
final CircuitBreakerService breakerService) {
final IndexWriterConfig iwc = newIndexWriterConfig();
final TranslogConfig translogConfig = new TranslogConfig(shardId, translogPath, indexSettings, BigArrays.NON_RECYCLING_INSTANCE);
final Engine.EventListener eventListener = new Engine.EventListener() {}; // we don't need to notify anybody in this test
final List<ReferenceManager.RefreshListener> extRefreshListenerList =
externalRefreshListener == null ? emptyList() : Collections.singletonList(externalRefreshListener);
final List<ReferenceManager.RefreshListener> intRefreshListenerList =
internalRefreshListener == null ? emptyList() : Collections.singletonList(internalRefreshListener);
final LongSupplier globalCheckpointSupplier;
final Supplier<RetentionLeases> retentionLeasesSupplier;
if (maybeGlobalCheckpointSupplier == null) {
assert maybeRetentionLeasesSupplier == null;
final ReplicationTracker replicationTracker = new ReplicationTracker(
shardId,
allocationId.getId(),
indexSettings,
randomNonNegativeLong(),
SequenceNumbers.NO_OPS_PERFORMED,
update -> {},
() -> 0L,
(leases, listener) -> {});
globalCheckpointSupplier = replicationTracker;
retentionLeasesSupplier = replicationTracker::getRetentionLeases;
} else {
assert maybeRetentionLeasesSupplier != null;
globalCheckpointSupplier = maybeGlobalCheckpointSupplier;
retentionLeasesSupplier = maybeRetentionLeasesSupplier;
}
return new EngineConfig(
shardId,
allocationId.getId(),
threadPool,
indexSettings,
null,
store,
mergePolicy,
iwc.getAnalyzer(),
iwc.getSimilarity(),
new CodecService(null, logger),
eventListener,
IndexSearcher.getDefaultQueryCache(),
IndexSearcher.getDefaultQueryCachingPolicy(),
translogConfig,
TimeValue.timeValueMinutes(5),
extRefreshListenerList,
intRefreshListenerList,
indexSort,
breakerService,
globalCheckpointSupplier,
retentionLeasesSupplier,
primaryTerm,
tombstoneDocSupplier());
}
protected EngineConfig config(EngineConfig config, Store store, Path translogPath,
EngineConfig.TombstoneDocSupplier tombstoneDocSupplier) {
IndexSettings indexSettings = IndexSettingsModule.newIndexSettings("test",
Settings.builder().put(config.getIndexSettings().getSettings())
.put(IndexSettings.INDEX_SOFT_DELETES_SETTING.getKey(), true).build());
TranslogConfig translogConfig = new TranslogConfig(shardId, translogPath, indexSettings, BigArrays.NON_RECYCLING_INSTANCE);
return new EngineConfig(config.getShardId(), config.getAllocationId(), config.getThreadPool(),
indexSettings, config.getWarmer(), store, config.getMergePolicy(), config.getAnalyzer(), config.getSimilarity(),
new CodecService(null, logger), config.getEventListener(), config.getQueryCache(), config.getQueryCachingPolicy(),
translogConfig, config.getFlushMergesAfter(), config.getExternalRefreshListener(),
config.getInternalRefreshListener(), config.getIndexSort(), config.getCircuitBreakerService(),
config.getGlobalCheckpointSupplier(), config.retentionLeasesSupplier(),
config.getPrimaryTermSupplier(), tombstoneDocSupplier);
}
protected EngineConfig noOpConfig(IndexSettings indexSettings, Store store, Path translogPath) {
return noOpConfig(indexSettings, store, translogPath, null);
}
protected EngineConfig noOpConfig(IndexSettings indexSettings, Store store, Path translogPath, LongSupplier globalCheckpointSupplier) {
return config(indexSettings, store, translogPath, newMergePolicy(), null, null, globalCheckpointSupplier);
}
protected static final BytesReference B_1 = new BytesArray(new byte[]{1});
protected static final BytesReference B_2 = new BytesArray(new byte[]{2});
protected static final BytesReference B_3 = new BytesArray(new byte[]{3});
protected static final BytesArray SOURCE = bytesArray("{}");
protected static BytesArray bytesArray(String string) {
return new BytesArray(string.getBytes(Charset.defaultCharset()));
}
public static Term newUid(String id) {
return new Term("_id", Uid.encodeId(id));
}
public static Term newUid(ParsedDocument doc) {
return newUid(doc.id());
}
protected Engine.Get newGet(boolean realtime, ParsedDocument doc) {
return new Engine.Get(realtime, false, doc.type(), doc.id(), newUid(doc));
}
protected Engine.Index indexForDoc(ParsedDocument doc) {
return new Engine.Index(newUid(doc), primaryTerm.get(), doc);
}
protected Engine.Index replicaIndexForDoc(ParsedDocument doc, long version, long seqNo,
boolean isRetry) {
return new Engine.Index(newUid(doc), doc, seqNo, primaryTerm.get(), version, null, Engine.Operation.Origin.REPLICA,
System.nanoTime(), IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP, isRetry, SequenceNumbers.UNASSIGNED_SEQ_NO, 0);
}
protected Engine.Delete replicaDeleteForDoc(String id, long version, long seqNo, long startTime) {
return new Engine.Delete("test", id, newUid(id), seqNo, 1, version, null, Engine.Operation.Origin.REPLICA, startTime,
SequenceNumbers.UNASSIGNED_SEQ_NO, 0);
}
protected static void assertVisibleCount(InternalEngine engine, int numDocs) throws IOException {
assertVisibleCount(engine, numDocs, true);
}
protected static void assertVisibleCount(InternalEngine engine, int numDocs, boolean refresh) throws IOException {
if (refresh) {
engine.refresh("test");
}
try (Engine.Searcher searcher = engine.acquireSearcher("test")) {
final TotalHitCountCollector collector = new TotalHitCountCollector();
searcher.searcher().search(new MatchAllDocsQuery(), collector);
assertThat(collector.getTotalHits(), equalTo(numDocs));
}
}
public static List<Engine.Operation> generateSingleDocHistory(boolean forReplica, VersionType versionType,
long primaryTerm, int minOpCount, int maxOpCount, String docId) {
final int numOfOps = randomIntBetween(minOpCount, maxOpCount);
final List<Engine.Operation> ops = new ArrayList<>();
final Term id = newUid(docId);
final int startWithSeqNo = 0;
final String valuePrefix = (forReplica ? "r_" : "p_" ) + docId + "_";
final boolean incrementTermWhenIntroducingSeqNo = randomBoolean();
for (int i = 0; i < numOfOps; i++) {
final Engine.Operation op;
final long version;
switch (versionType) {
case INTERNAL:
version = forReplica ? i : Versions.MATCH_ANY;
break;
case EXTERNAL:
version = i;
break;
case EXTERNAL_GTE:
version = randomBoolean() ? Math.max(i - 1, 0) : i;
break;
case FORCE:
version = randomNonNegativeLong();
break;
default:
throw new UnsupportedOperationException("unknown version type: " + versionType);
}
if (randomBoolean()) {
op = new Engine.Index(id, testParsedDocument(docId, null, testDocumentWithTextField(valuePrefix + i), SOURCE, null),
forReplica && i >= startWithSeqNo ? i * 2 : SequenceNumbers.UNASSIGNED_SEQ_NO,
forReplica && i >= startWithSeqNo && incrementTermWhenIntroducingSeqNo ? primaryTerm + 1 : primaryTerm,
version,
forReplica ? null : versionType,
forReplica ? REPLICA : PRIMARY,
System.currentTimeMillis(), -1, false,
SequenceNumbers.UNASSIGNED_SEQ_NO, 0);
} else {
op = new Engine.Delete("test", docId, id,
forReplica && i >= startWithSeqNo ? i * 2 : SequenceNumbers.UNASSIGNED_SEQ_NO,
forReplica && i >= startWithSeqNo && incrementTermWhenIntroducingSeqNo ? primaryTerm + 1 : primaryTerm,
version,
forReplica ? null : versionType,
forReplica ? REPLICA : PRIMARY,
System.currentTimeMillis(), SequenceNumbers.UNASSIGNED_SEQ_NO, 0);
}
ops.add(op);
}
return ops;
}
public List<Engine.Operation> generateHistoryOnReplica(int numOps, boolean allowGapInSeqNo, boolean allowDuplicate,
boolean includeNestedDocs) throws Exception {
long seqNo = 0;
final int maxIdValue = randomInt(numOps * 2);
final List<Engine.Operation> operations = new ArrayList<>(numOps);
CheckedBiFunction<String, Integer, ParsedDocument, IOException> nestedParsedDocFactory = nestedParsedDocFactory();
for (int i = 0; i < numOps; i++) {
final String id = Integer.toString(randomInt(maxIdValue));
final Engine.Operation.TYPE opType = randomFrom(Engine.Operation.TYPE.values());
final boolean isNestedDoc = includeNestedDocs && opType == Engine.Operation.TYPE.INDEX && randomBoolean();
final int nestedValues = between(0, 3);
final long startTime = threadPool.relativeTimeInNanos();
final int copies = allowDuplicate && rarely() ? between(2, 4) : 1;
for (int copy = 0; copy < copies; copy++) {
final ParsedDocument doc = isNestedDoc ? nestedParsedDocFactory.apply(id, nestedValues) : createParsedDoc(id, null);
switch (opType) {
case INDEX:
operations.add(new Engine.Index(EngineTestCase.newUid(doc), doc, seqNo, primaryTerm.get(),
i, null, Engine.Operation.Origin.REPLICA, startTime, -1, true, SequenceNumbers.UNASSIGNED_SEQ_NO, 0));
break;
case DELETE:
operations.add(new Engine.Delete(doc.type(), doc.id(), EngineTestCase.newUid(doc), seqNo, primaryTerm.get(),
i, null, Engine.Operation.Origin.REPLICA, startTime, SequenceNumbers.UNASSIGNED_SEQ_NO, 0));
break;
case NO_OP:
operations.add(new Engine.NoOp(seqNo, primaryTerm.get(), Engine.Operation.Origin.REPLICA, startTime, "test-" + i));
break;
default:
throw new IllegalStateException("Unknown operation type [" + opType + "]");
}
}
seqNo++;
if (allowGapInSeqNo && rarely()) {
seqNo++;
}
}
Randomness.shuffle(operations);
return operations;
}
public static void assertOpsOnReplica(
final List<Engine.Operation> ops,
final InternalEngine replicaEngine,
boolean shuffleOps,
final Logger logger) throws IOException {
final Engine.Operation lastOp = ops.get(ops.size() - 1);
final String lastFieldValue;
if (lastOp instanceof Engine.Index) {
Engine.Index index = (Engine.Index) lastOp;
lastFieldValue = index.docs().get(0).get("value");
} else {
// delete
lastFieldValue = null;
}
if (shuffleOps) {
int firstOpWithSeqNo = 0;
while (firstOpWithSeqNo < ops.size() && ops.get(firstOpWithSeqNo).seqNo() < 0) {
firstOpWithSeqNo++;
}
// shuffle ops but make sure legacy ops are first
shuffle(ops.subList(0, firstOpWithSeqNo), random());
shuffle(ops.subList(firstOpWithSeqNo, ops.size()), random());
}
boolean firstOp = true;
for (Engine.Operation op : ops) {
logger.info("performing [{}], v [{}], seq# [{}], term [{}]",
op.operationType().name().charAt(0), op.version(), op.seqNo(), op.primaryTerm());
if (op instanceof Engine.Index) {
Engine.IndexResult result = replicaEngine.index((Engine.Index) op);
// replicas don't really care to about creation status of documents
// this allows to ignore the case where a document was found in the live version maps in
// a delete state and return false for the created flag in favor of code simplicity
// as deleted or not. This check is just signal regression so a decision can be made if it's
// intentional
assertThat(result.isCreated(), equalTo(firstOp));
assertThat(result.getVersion(), equalTo(op.version()));
assertThat(result.getResultType(), equalTo(Engine.Result.Type.SUCCESS));
} else {
Engine.DeleteResult result = replicaEngine.delete((Engine.Delete) op);
// Replicas don't really care to about found status of documents
// this allows to ignore the case where a document was found in the live version maps in
// a delete state and return true for the found flag in favor of code simplicity
// his check is just signal regression so a decision can be made if it's
// intentional
assertThat(result.isFound(), equalTo(firstOp == false));
assertThat(result.getVersion(), equalTo(op.version()));
assertThat(result.getResultType(), equalTo(Engine.Result.Type.SUCCESS));
}
if (randomBoolean()) {
replicaEngine.refresh("test");
}
if (randomBoolean()) {
replicaEngine.flush();
replicaEngine.refresh("test");
}
firstOp = false;
}
assertVisibleCount(replicaEngine, lastFieldValue == null ? 0 : 1);
if (lastFieldValue != null) {
try (Engine.Searcher searcher = replicaEngine.acquireSearcher("test")) {
final TotalHitCountCollector collector = new TotalHitCountCollector();
searcher.searcher().search(new TermQuery(new Term("value", lastFieldValue)), collector);
assertThat(collector.getTotalHits(), equalTo(1));
}
}
}
public static void concurrentlyApplyOps(List<Engine.Operation> ops, InternalEngine engine) throws InterruptedException {
Thread[] thread = new Thread[randomIntBetween(3, 5)];
CountDownLatch startGun = new CountDownLatch(thread.length);
AtomicInteger offset = new AtomicInteger(-1);
for (int i = 0; i < thread.length; i++) {
thread[i] = new Thread(() -> {
startGun.countDown();
try {
startGun.await();
} catch (InterruptedException e) {
throw new AssertionError(e);
}
int docOffset;
while ((docOffset = offset.incrementAndGet()) < ops.size()) {
try {
applyOperation(engine, ops.get(docOffset));
if ((docOffset + 1) % 4 == 0) {
engine.refresh("test");
}
if (rarely()) {
engine.flush();
}
} catch (IOException e) {
throw new AssertionError(e);
}
}
});
thread[i].start();
}
for (int i = 0; i < thread.length; i++) {
thread[i].join();
}
}
public static void applyOperations(Engine engine, List<Engine.Operation> operations) throws IOException {
for (Engine.Operation operation : operations) {
applyOperation(engine, operation);
if (randomInt(100) < 10) {
engine.refresh("test");
}
if (rarely()) {
engine.flush();
}
}
}
public static Engine.Result applyOperation(Engine engine, Engine.Operation operation) throws IOException {
final Engine.Result result;
switch (operation.operationType()) {
case INDEX:
result = engine.index((Engine.Index) operation);
break;
case DELETE:
result = engine.delete((Engine.Delete) operation);
break;
case NO_OP:
result = engine.noOp((Engine.NoOp) operation);
break;
default:
throw new IllegalStateException("No operation defined for [" + operation + "]");
}
return result;
}
/**
* Gets a collection of tuples of docId, sequence number, and primary term of all live documents in the provided engine.
*/
public static List<DocIdSeqNoAndSource> getDocIds(Engine engine, boolean refresh) throws IOException {
if (refresh) {
engine.refresh("test_get_doc_ids");
}
try (Engine.Searcher searcher = engine.acquireSearcher("test_get_doc_ids")) {
List<DocIdSeqNoAndSource> docs = new ArrayList<>();
for (LeafReaderContext leafContext : searcher.reader().leaves()) {
LeafReader reader = leafContext.reader();
NumericDocValues seqNoDocValues = reader.getNumericDocValues(SeqNoFieldMapper.NAME);
NumericDocValues primaryTermDocValues = reader.getNumericDocValues(SeqNoFieldMapper.PRIMARY_TERM_NAME);
NumericDocValues versionDocValues = reader.getNumericDocValues(VersionFieldMapper.NAME);
Bits liveDocs = reader.getLiveDocs();
for (int i = 0; i < reader.maxDoc(); i++) {
if (liveDocs == null || liveDocs.get(i)) {
if (primaryTermDocValues.advanceExact(i) == false) {
// We have to skip non-root docs because its _id field is not stored (indexed only).
continue;
}
final long primaryTerm = primaryTermDocValues.longValue();
Document doc = reader.document(i, Set.of(IdFieldMapper.NAME, SourceFieldMapper.NAME));
BytesRef binaryID = doc.getBinaryValue(IdFieldMapper.NAME);
String id = Uid.decodeId(Arrays.copyOfRange(binaryID.bytes, binaryID.offset, binaryID.offset + binaryID.length));
final BytesRef source = doc.getBinaryValue(SourceFieldMapper.NAME);
if (seqNoDocValues.advanceExact(i) == false) {
throw new AssertionError("seqNoDocValues not found for doc[" + i + "] id[" + id + "]");
}
final long seqNo = seqNoDocValues.longValue();
if (versionDocValues.advanceExact(i) == false) {
throw new AssertionError("versionDocValues not found for doc[" + i + "] id[" + id + "]");
}
final long version = versionDocValues.longValue();
docs.add(new DocIdSeqNoAndSource(id, source, seqNo, primaryTerm, version));
}
}
}
docs.sort(Comparator.comparingLong(DocIdSeqNoAndSource::getSeqNo)
.thenComparingLong(DocIdSeqNoAndSource::getPrimaryTerm)
.thenComparing((DocIdSeqNoAndSource::getId)));
return docs;
}
}
/**
* Reads all engine operations that have been processed by the engine from Lucene index.
* The returned operations are sorted and de-duplicated, thus each sequence number will be have at most one operation.
*/
public static List<Translog.Operation> readAllOperationsInLucene(Engine engine, MapperService mapper) throws IOException {
final List<Translog.Operation> operations = new ArrayList<>();
long maxSeqNo = Math.max(0, ((InternalEngine)engine).getLocalCheckpointTracker().getMaxSeqNo());
try (Translog.Snapshot snapshot = engine.newChangesSnapshot("test", mapper, 0, maxSeqNo, false)) {
Translog.Operation op;
while ((op = snapshot.next()) != null){
operations.add(op);
}
}
return operations;
}
/**
* Asserts the provided engine has a consistent document history between translog and Lucene index.
*/
public static void assertConsistentHistoryBetweenTranslogAndLuceneIndex(Engine engine, MapperService mapper) throws IOException {
if (mapper == null || mapper.documentMapper() == null || engine.config().getIndexSettings().isSoftDeleteEnabled() == false
|| (engine instanceof InternalEngine) == false) {
return;
}
final long maxSeqNo = ((InternalEngine) engine).getLocalCheckpointTracker().getMaxSeqNo();
if (maxSeqNo < 0) {
return; // nothing to check
}
final Map<Long, Translog.Operation> translogOps = new HashMap<>();
try (Translog.Snapshot snapshot = EngineTestCase.getTranslog(engine).newSnapshot()) {
Translog.Operation op;
while ((op = snapshot.next()) != null) {
translogOps.put(op.seqNo(), op);
}
}
final Map<Long, Translog.Operation> luceneOps = readAllOperationsInLucene(engine, mapper).stream()
.collect(Collectors.toMap(Translog.Operation::seqNo, Function.identity()));
final long globalCheckpoint = EngineTestCase.getTranslog(engine).getLastSyncedGlobalCheckpoint();
final long retainedOps = engine.config().getIndexSettings().getSoftDeleteRetentionOperations();
final long seqNoForRecovery;
try (Engine.IndexCommitRef safeCommit = engine.acquireSafeIndexCommit()) {
seqNoForRecovery = Long.parseLong(safeCommit.getIndexCommit().getUserData().get(SequenceNumbers.LOCAL_CHECKPOINT_KEY)) + 1;
}
final long minSeqNoToRetain = Math.min(seqNoForRecovery, globalCheckpoint + 1 - retainedOps);
for (Translog.Operation translogOp : translogOps.values()) {
final Translog.Operation luceneOp = luceneOps.get(translogOp.seqNo());
if (luceneOp == null) {
if (minSeqNoToRetain <= translogOp.seqNo() && translogOp.seqNo() <= maxSeqNo) {
fail("Operation not found seq# [" + translogOp.seqNo() + "], global checkpoint [" + globalCheckpoint + "], " +
"retention policy [" + retainedOps + "], maxSeqNo [" + maxSeqNo + "], translog op [" + translogOp + "]");
} else {
continue;
}
}
assertThat(luceneOp, notNullValue());
assertThat(luceneOp.toString(), luceneOp.primaryTerm(), equalTo(translogOp.primaryTerm()));
assertThat(luceneOp.opType(), equalTo(translogOp.opType()));
if (luceneOp.opType() == Translog.Operation.Type.INDEX) {
assertThat(luceneOp.getSource().source, equalTo(translogOp.getSource().source));
}
}
}
/**
* Asserts that the max_seq_no stored in the commit's user_data is never smaller than seq_no of any document in the commit.
*/
public static void assertMaxSeqNoInCommitUserData(Engine engine) throws Exception {
List<IndexCommit> commits = DirectoryReader.listCommits(engine.store.directory());
for (IndexCommit commit : commits) {
try (DirectoryReader reader = DirectoryReader.open(commit)) {
AtomicLong maxSeqNoFromDocs = new AtomicLong(SequenceNumbers.NO_OPS_PERFORMED);
Lucene.scanSeqNosInReader(reader, 0, Long.MAX_VALUE, n -> maxSeqNoFromDocs.set(Math.max(n, maxSeqNoFromDocs.get())));
assertThat(Long.parseLong(commit.getUserData().get(SequenceNumbers.MAX_SEQ_NO)),
greaterThanOrEqualTo(maxSeqNoFromDocs.get()));
}
}
}
public static MapperService createMapperService(String type) throws IOException {
IndexMetaData indexMetaData = IndexMetaData.builder("test")
.settings(Settings.builder()
.put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT)
.put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1).put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1))
.putMapping(type, "{\"properties\": {}}")
.build();
MapperService mapperService = MapperTestUtils.newMapperService(new NamedXContentRegistry(ClusterModule.getNamedXWriteables()),
createTempDir(), Settings.EMPTY, "test");
mapperService.merge(indexMetaData, MapperService.MergeReason.MAPPING_UPDATE);
return mapperService;
}
/**
* Exposes a translog associated with the given engine for testing purpose.
*/
public static Translog getTranslog(Engine engine) {
assert engine instanceof InternalEngine : "only InternalEngines have translogs, got: " + engine.getClass();
InternalEngine internalEngine = (InternalEngine) engine;
return internalEngine.getTranslog();
}
/**
* Waits for all operations up to the provided sequence number to complete in the given internal engine.
*
* @param seqNo the sequence number that the checkpoint must advance to before this method returns
* @throws InterruptedException if the thread was interrupted while blocking on the condition
*/
public static void waitForOpsToComplete(InternalEngine engine, long seqNo) throws InterruptedException {
engine.getLocalCheckpointTracker().waitForOpsToComplete(seqNo);
}
public static boolean hasSnapshottedCommits(Engine engine) {
assert engine instanceof InternalEngine : "only InternalEngines have snapshotted commits, got: " + engine.getClass();
InternalEngine internalEngine = (InternalEngine) engine;
return internalEngine.hasSnapshottedCommits();
}
public static final class PrimaryTermSupplier implements LongSupplier {
private final AtomicLong term;
PrimaryTermSupplier(long initialTerm) {
this.term = new AtomicLong(initialTerm);
}
public long get() {
return term.get();
}
public void set(long newTerm) {
this.term.set(newTerm);
}
@Override
public long getAsLong() {
return get();
}
}
}
|
/*
MIT License
Copyright (c) 2020 DanieleDeIuliis
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.salestaxes.consoleapp;
import com.salestaxes.exceptions.EmptyOrWrongInputException;
import com.salestaxes.model.Item;
import com.salestaxes.model.ItemTypeUtils;
import com.salestaxes.model.OrderItem;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;
public class InputParserUtilsTest {
@Test
public void testParseInputFromFile() throws FileNotFoundException, EmptyOrWrongInputException {
File inputTestFile = new File(
InputParserUtilsTest.class.getClassLoader().
getResource("inputParser/parseInputTest.txt").getFile());
List<OrderItem> orderedItems = InputParserUtils.parseInputFromFile(inputTestFile);
Assertions.assertEquals(1, orderedItems.size());
Item item = orderedItems.get(0).getItem();
Assertions.assertEquals("box of chocolates", item.getName());
Assertions.assertEquals(5,item.getTaxAmount());
Assertions.assertEquals(ItemTypeUtils.ItemType.FOOD, item.getType());
Assertions.assertEquals(10.50,item.getPrice());
Assertions.assertEquals(true, item.isImported());
Assertions.assertEquals(2, orderedItems.get(0).getQuantity());
}
@Test
public void testParseInputFromFileWithItemsToSkip() throws FileNotFoundException, EmptyOrWrongInputException {
File inputTestFile = new File(
InputParserUtilsTest.class.getClassLoader().
getResource("inputParser/parseInputSkipItemTest.txt").getFile());
List<OrderItem> orderedItems = InputParserUtils.parseInputFromFile(inputTestFile);
Assertions.assertEquals(1, orderedItems.size());
}
@Test
public void testParseInputFromFileNotFound(){
Assertions.assertThrows(FileNotFoundException.class, () -> {
InputParserUtils.parseInputFromFile(new File(""));
});
}
@Test
public void testParseInputFromFileEmptyInput(){
File inputTestFile = new File(
InputParserUtilsTest.class.getClassLoader().
getResource("inputParser/parseInputTestEmpty.txt").getFile());
Assertions.assertThrows(EmptyOrWrongInputException.class, () -> {
InputParserUtils.parseInputFromFile(inputTestFile);
});
}
}
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.cdi.tck.tests.full.extensions.lifecycle.atd;
import jakarta.annotation.Priority;
import jakarta.decorator.Decorator;
import jakarta.decorator.Delegate;
import jakarta.inject.Inject;
@Priority(2013)
@Decorator
public class AlphaDecorator implements Logger {
@Inject
@Delegate
Logger logger;
@Override
public String log(String msg) {
return logger.log(msg + "alpha");
}
}
|
/***********************************************************************************************************************
*
* Copyright (C) 2010-2013 by the Stratosphere project (http://stratosphere.eu)
*
* 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 eu.stratosphere.api.java.functions;
import eu.stratosphere.api.common.functions.AbstractFunction;
import eu.stratosphere.api.common.functions.GenericJoiner;
import eu.stratosphere.util.Collector;
/**
* The abstract base class for Join functions. Join functions combine two data sets by joining their
* elements on specified keys and calling this function with each pair of joining elements.
* By default, this follows strictly the semantics of an "inner join" in SQL.
* the semantics are those of an "inner join", meaning that elements are filtered out
* if their key is not contained in the other data set.
* <p>
* Per the semantics of an inner join, the function is
* <p>
* The basic syntax for using Join on two data sets is as follows:
* <pre><blockquote>
* DataSet<X> set1 = ...;
* DataSet<Y> set2 = ...;
*
* set1.join(set2).where(<key-definition>).equalTo(<key-definition>).with(new MyJoinFunction());
* </blockquote></pre>
* <p>
* {@code set1} is here considered the first input, {@code set2} the second input.
* The keys can be defined through tuple field positions or key extractors.
* See {@link eu.stratosphere.api.java.operators.Keys} for details.
* <p>
* The Join function is actually not a necessary part of a join operation. If no JoinFunction is provided,
* the result of the operation is a sequence of Tuple2, where the elements in the tuple are those that
* the JoinFunction would have been invoked with.
* <P>
* Note: You can use a {@link CoGroupFunction} to perform an outer join.
* <p>
* All functions need to be serializable, as defined in {@link java.io.Serializable}.
*
* @param <IN1> The type of the elements in the first input.
* @param <IN2> The type of the elements in the second input.
* @param <OUT> The type of the result elements.
*/
public abstract class JoinFunction<IN1, IN2, OUT> extends AbstractFunction implements GenericJoiner<IN1, IN2, OUT> {
private static final long serialVersionUID = 1L;
/**
* The user-defined method for performing transformations after a join.
* The method is called with matching pairs of elements from the inputs.
*
* @param first The element from first input.
* @param second The element from second input.
* @return The resulting element.
*
* @throws Exception This method may throw exceptions. Throwing an exception will cause the operation
* to fail and may trigger recovery.
*/
public abstract OUT join(IN1 first, IN2 second) throws Exception;
/**
* The user-defined method for performing transformations after a join, for operations that
* produce zero elements, or more than one element.
* By default, this method delegates to the method {@link #join(Object, Object)}. If this method
* is overridden, that method will no longer be called.
*
* @param first The element from first input.
* @param second The element from second input.
* @param out A collector to emit resulting element (zero, one, or many).
*
* @throws Exception This method may throw exceptions. Throwing an exception will cause the operation
* to fail and may trigger recovery.
*/
@Override
public void join(IN1 value1, IN2 value2, Collector<OUT> out) throws Exception {
out.collect(join(value1, value2));
}
}
|
import java.util.*;
public abstract class FSElement {
protected String name;
protected String owner;
protected Date created;
protected Date lastModified;
protected int size;
protected Directory parent;
public FSElement(Directory parent, String name, String owner, Date created) {
this.parent = parent;
if (parent != null) {
this.parent.appendChild(this);
}
this.created = created;
this.lastModified = created;
this.owner = owner;
this.name = name;
}
public Directory getParent() {
return this.parent;
}
public String getName() {
return this.name;
}
abstract public boolean isLeaf();
public int getDiskUtil(){
return this.size;
}
abstract public void accept (FSVisitor v);
}
|
package com.atguigu.gmall.auth.service;
import com.atguigu.core.bean.Resp;
import com.atguigu.core.utils.JwtUtils;
import com.atguigu.gmall.auth.config.JwtProperties;
import com.atguigu.gmall.auth.exception.GmallException;
import com.atguigu.gmall.auth.feign.GmallUmsClient;
import com.atguigu.gmall.ums.entity.MemberEntity;
import java.util.HashMap;
import java.util.Map;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
@Service
@EnableConfigurationProperties(JwtProperties.class)
public class AuthService {
@Autowired
private GmallUmsClient gmallUmsClient;
@Autowired
private JwtProperties jwtProperties;
public String accredit(String userName, String password) {
try {
// 1. 远程调用用户中心的数据接口,查询用户信息
Resp<MemberEntity> memberEntityResp = this.gmallUmsClient.queryUser(userName, password);
MemberEntity memberEntity = memberEntityResp.getData();
// 2. 判断用户是否存在,不存在直接返回
if (memberEntity == null) {
return null;
}
// 3. 存在,生成jwt
Map<String, Object> map = new HashMap<>();
map.put("id", memberEntity.getId());
map.put("username", memberEntity.getUsername());
return JwtUtils.generateToken(map, this.jwtProperties.getPrivateKey(), this.jwtProperties.getExpire());
} catch (Exception e) {
e.printStackTrace();
throw new GmallException("jwt认证失败!");
}
}
}
|
/*
* Copyright 2013-2016 Indiana University
*
* 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 edu.iu.fileformat;
import java.io.IOException;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
public class SingleFileInputFormat extends
FileInputFormat<String, String> {
protected boolean isSplitable(
JobContext context, Path filename) {
return false;
}
@Override
public RecordReader<String, String>
createRecordReader(InputSplit split,
TaskAttemptContext context)
throws IOException, InterruptedException {
return new SingleFileRecordReader();
}
}
|
package com.ruoyi.common.utils;
/**
* 处理并记录日志文件
*
* @author zyl
*/
public class LogUtils
{
public static String getBlock(Object msg)
{
if (msg == null)
{
msg = "";
}
return "[" + msg.toString() + "]";
}
}
|
/*
* Copyright 2014-2018 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.oauth2.config;
import be.atbash.util.CDIUtils;
import javax.enterprise.context.ApplicationScoped;
@ApplicationScoped
public class ProviderSelection {
// This will keep track of which OAuth2 provider will be used
// From JSF -> It will be set by OAuth2ServletInfo
private ThreadLocal<String> providerSelection = new ThreadLocal<>();
public String getProvider() {
String result = providerSelection.get();
if (result == null) {
UserProviderSelection userProviderSelection = CDIUtils.retrieveOptionalInstance(UserProviderSelection.class);
if (userProviderSelection != null) {
result = userProviderSelection.getSelection();
}
}
return result;
}
public void setProviderSelection(String selection) {
providerSelection.set(selection);
}
}
|
/*
* Decompiled with CFR 0.150.
*/
package us.myles.viaversion.libs.javassist.bytecode;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.Map;
import us.myles.viaversion.libs.javassist.bytecode.AttributeInfo;
import us.myles.viaversion.libs.javassist.bytecode.ByteArray;
import us.myles.viaversion.libs.javassist.bytecode.ConstPool;
public class InnerClassesAttribute
extends AttributeInfo {
public static final String tag = "InnerClasses";
InnerClassesAttribute(ConstPool cp, int n, DataInputStream in) throws IOException {
super(cp, n, in);
}
private InnerClassesAttribute(ConstPool cp, byte[] info) {
super(cp, tag, info);
}
public InnerClassesAttribute(ConstPool cp) {
super(cp, tag, new byte[2]);
ByteArray.write16bit(0, this.get(), 0);
}
public int tableLength() {
return ByteArray.readU16bit(this.get(), 0);
}
public int innerClassIndex(int nth) {
return ByteArray.readU16bit(this.get(), nth * 8 + 2);
}
public String innerClass(int nth) {
int i = this.innerClassIndex(nth);
if (i == 0) {
return null;
}
return this.constPool.getClassInfo(i);
}
public void setInnerClassIndex(int nth, int index) {
ByteArray.write16bit(index, this.get(), nth * 8 + 2);
}
public int outerClassIndex(int nth) {
return ByteArray.readU16bit(this.get(), nth * 8 + 4);
}
public String outerClass(int nth) {
int i = this.outerClassIndex(nth);
if (i == 0) {
return null;
}
return this.constPool.getClassInfo(i);
}
public void setOuterClassIndex(int nth, int index) {
ByteArray.write16bit(index, this.get(), nth * 8 + 4);
}
public int innerNameIndex(int nth) {
return ByteArray.readU16bit(this.get(), nth * 8 + 6);
}
public String innerName(int nth) {
int i = this.innerNameIndex(nth);
if (i == 0) {
return null;
}
return this.constPool.getUtf8Info(i);
}
public void setInnerNameIndex(int nth, int index) {
ByteArray.write16bit(index, this.get(), nth * 8 + 6);
}
public int accessFlags(int nth) {
return ByteArray.readU16bit(this.get(), nth * 8 + 8);
}
public void setAccessFlags(int nth, int flags) {
ByteArray.write16bit(flags, this.get(), nth * 8 + 8);
}
public int find(String name) {
int n = this.tableLength();
for (int i = 0; i < n; ++i) {
if (!name.equals(this.innerClass(i))) continue;
return i;
}
return -1;
}
public void append(String inner, String outer, String name, int flags) {
int i = this.constPool.addClassInfo(inner);
int o = this.constPool.addClassInfo(outer);
int n = this.constPool.addUtf8Info(name);
this.append(i, o, n, flags);
}
public void append(int inner, int outer, int name, int flags) {
byte[] data = this.get();
int len = data.length;
byte[] newData = new byte[len + 8];
for (int i = 2; i < len; ++i) {
newData[i] = data[i];
}
int n = ByteArray.readU16bit(data, 0);
ByteArray.write16bit(n + 1, newData, 0);
ByteArray.write16bit(inner, newData, len);
ByteArray.write16bit(outer, newData, len + 2);
ByteArray.write16bit(name, newData, len + 4);
ByteArray.write16bit(flags, newData, len + 6);
this.set(newData);
}
public int remove(int nth) {
byte[] data = this.get();
int len = data.length;
if (len < 10) {
return 0;
}
int n = ByteArray.readU16bit(data, 0);
int nthPos = 2 + nth * 8;
if (n <= nth) {
return n;
}
byte[] newData = new byte[len - 8];
ByteArray.write16bit(n - 1, newData, 0);
int i = 2;
int j = 2;
while (i < len) {
if (i == nthPos) {
i += 8;
continue;
}
newData[j++] = data[i++];
}
this.set(newData);
return n - 1;
}
@Override
public AttributeInfo copy(ConstPool newCp, Map<String, String> classnames) {
byte[] src = this.get();
byte[] dest = new byte[src.length];
ConstPool cp = this.getConstPool();
InnerClassesAttribute attr = new InnerClassesAttribute(newCp, dest);
int n = ByteArray.readU16bit(src, 0);
ByteArray.write16bit(n, dest, 0);
int j = 2;
for (int i = 0; i < n; ++i) {
int innerClass = ByteArray.readU16bit(src, j);
int outerClass = ByteArray.readU16bit(src, j + 2);
int innerName = ByteArray.readU16bit(src, j + 4);
int innerAccess = ByteArray.readU16bit(src, j + 6);
if (innerClass != 0) {
innerClass = cp.copy(innerClass, newCp, classnames);
}
ByteArray.write16bit(innerClass, dest, j);
if (outerClass != 0) {
outerClass = cp.copy(outerClass, newCp, classnames);
}
ByteArray.write16bit(outerClass, dest, j + 2);
if (innerName != 0) {
innerName = cp.copy(innerName, newCp, classnames);
}
ByteArray.write16bit(innerName, dest, j + 4);
ByteArray.write16bit(innerAccess, dest, j + 6);
j += 8;
}
return attr;
}
}
|
/*
* Copyright 2012-2017 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 ant "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.context.filtersample;
import org.springframework.stereotype.Component;
@Component
public class ExampleFilteredComponent {
}
|
package de.tub.dima.babelfish.ir.pqp.nodes.relational.scan.csv;
import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.Truffle;
import com.oracle.truffle.api.TruffleLanguage;
import com.oracle.truffle.api.TruffleRuntime;
import com.oracle.truffle.api.dsl.NodeChild;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.frame.FrameDescriptor;
import com.oracle.truffle.api.frame.FrameSlot;
import com.oracle.truffle.api.frame.FrameSlotKind;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.nodes.*;
import de.tub.dima.babelfish.ir.pqp.nodes.BFOperator;
import de.tub.dima.babelfish.ir.pqp.nodes.relational.scan.AbstractScanOperator;
import de.tub.dima.babelfish.ir.pqp.nodes.utils.ArgumentReadNode;
import de.tub.dima.babelfish.ir.pqp.objects.records.BFRecord;
import de.tub.dima.babelfish.ir.pqp.objects.records.RecordSchema;
import de.tub.dima.babelfish.storage.Buffer;
import de.tub.dima.babelfish.storage.Catalog;
import de.tub.dima.babelfish.storage.UnsafeUtils;
import de.tub.dima.babelfish.storage.layout.PhysicalCSVLayout;
import de.tub.dima.babelfish.typesytem.BFType;
import de.tub.dima.babelfish.typesytem.schema.Schema;
import de.tub.dima.babelfish.typesytem.schema.field.SchemaField;
/**
* BF scan operator for CSV data
*/
@NodeInfo(shortName = "CSVScan")
public class BFCSVScanOperator extends AbstractScanOperator {
private final FrameSlot readerSlot;
private final FrameSlot counter;
@CompilerDirectives.CompilationFinal
private Schema schema;
public BFCSVScanOperator(TruffleLanguage<?> language,
FrameDescriptor frameDescriptor,
String layout,
BFOperator child) {
super(language, frameDescriptor, layout, child);
this.readerSlot = frameDescriptor.findOrAddFrameSlot("reader", FrameSlotKind.Object);
this.counter = frameDescriptor.findOrAddFrameSlot(STATE_MANAGER_FRAME_SLOT_IDENTIFIER, FrameSlotKind.Object);
}
public RepeatingNode getScanBody(BFOperator child) {
Catalog catalog = Catalog.getInstance();
schema = ((PhysicalCSVLayout) catalog.getLayout(tableName)).schema;
return new ScanRepeatingNode(frameDescriptor, child, schema);
}
@Override
public void open(VirtualFrame frame) {
openCallNode.call(frame.getValue(counter));
}
public void execute(VirtualFrame globalFrame) {
VirtualFrame scanFrame = Truffle.getRuntime().createVirtualFrame(globalFrame.getArguments(), frameDescriptor);
scanFrame.setObject(counter, globalFrame.getValue(counter));
Buffer buffer = getBuffer(tableName);
ScanContext context = new ScanContext(buffer.getVirtualAddress().getAddress(), buffer.getVirtualAddress().getAddress() + buffer.getSize().getBytes());
if (CompilerDirectives.inInterpreter())
System.out.println(" Start scan of CSV " + tableName + " from " + context.currentAddres + " to" + context.endAddress);
scanFrame.setObject(readerSlot, context);
scanRepeatingNode.execute(scanFrame);
}
@Override
public void close(VirtualFrame frame) {
closeCallNode.call(frame.getValue(counter));
}
@CompilerDirectives.TruffleBoundary(transferToInterpreterOnException = false)
public Buffer getBuffer(String layout) {
return Catalog.getInstance().getBuffer(layout);
}
@NodeChild(type = ArgumentReadNode.class, value = "currentPosition")
@NodeChild(type = ArgumentReadNode.class, value = "endPosition")
public static abstract class SkipFieldNode extends Node {
abstract long execute(VirtualFrame frame);
boolean isSep(long endPosition, long position, long size) {
long speculatedPosition = position + size;
return UnsafeUtils.getByte(speculatedPosition) == '|';
}
long calcSize(long currentPosition) {
return skip(currentPosition, 0) - currentPosition;
}
// @Specialization(guards = {"isSep(endPosition, currentPosition, size)"}, limit = "2")
// long skipWithSize(long currentPosition, long endPosition, @Cached(value = "calcSize(currentPosition)") long size) {
// return currentPosition + size;
// }
@Specialization()
long skip(long currentPosition, long endPosition) {
while (UnsafeUtils.getByte(currentPosition) != '|') {
currentPosition++;
}
return currentPosition;
}
}
private final class ScanContext {
final long endAddress;
long currentAddres = 0;
private ScanContext(long startAddress, long endAddress) {
this.endAddress = endAddress;
this.currentAddres = startAddress;
}
}
public class ScanRepeatingNode extends Node implements RepeatingNode {
@CompilerDirectives.CompilationFinal
private final FrameSlot objectFrameSlot;
@CompilerDirectives.CompilationFinal
private final FrameDescriptor frameDescriptor;
@CompilerDirectives.CompilationFinal
private final RecordSchema loopObjectShape;
@Child
private DirectCallNode next;
@Children
private ParseCSVFieldNodesFactory.ParseFieldNode[] parseFieldNodes;
@Children
private SkipFieldNode[] skipFieldNodes;
ScanRepeatingNode(FrameDescriptor frameDescriptor, BFOperator child, Schema schema) {
TruffleRuntime runtime = Truffle.getRuntime();
this.next = runtime.createDirectCallNode(
runtime.createCallTarget(
child.getExecuteCall()));
this.frameDescriptor = frameDescriptor;
this.objectFrameSlot = frameDescriptor.findOrAddFrameSlot("object");
this.loopObjectShape = new RecordSchema();
this.parseFieldNodes = new ParseCSVFieldNodesFactory.ParseFieldNode[schema.getFields().length];
this.skipFieldNodes = new SkipFieldNode[schema.getFields().length];
for (int i = 0; i < parseFieldNodes.length; i++) {
SchemaField field = schema.getFields()[i];
parseFieldNodes[i] = ParseCSVFieldNodesFactory.createNode(field);
skipFieldNodes[i] = BFCSVScanOperatorFactory.SkipFieldNodeGen.create(new ArgumentReadNode(0), new ArgumentReadNode(1));
loopObjectShape.addField(field.getName());
}
}
@Override
public boolean executeRepeating(VirtualFrame globalFrame) {
ScanContext context = (ScanContext) globalFrame.getValue(readerSlot);
if (context.currentAddres < context.endAddress) {
BFRecord record = BFRecord.createObject(loopObjectShape);
readNext(context, record);
next.call(record, globalFrame.getValue(counter));
return true;
}
return false;
}
public long getNextFieldEndPosition(long currentPosition) {
while (UnsafeUtils.getByte(currentPosition) != '|') {
currentPosition++;
}
return currentPosition;
}
@ExplodeLoop
public void readNext(ScanContext context, BFRecord object) {
for (int i = 0; i < parseFieldNodes.length; i++) {
long fieldStartPosition = context.currentAddres;
VirtualFrame potionFrame = Truffle.getRuntime().createVirtualFrame(
new Object[]{fieldStartPosition, context.endAddress}, frameDescriptor);
long fieldEndPosition = skipFieldNodes[i].execute(potionFrame);
//if(fieldEndPosition != getNextFieldEndPosition(fieldStartPosition)){
// throw new RuntimeException("huch");
// }
//System.out.println("Parse field - " + fieldStartPosition + " - " + fieldEndPosition);
VirtualFrame localFrame = Truffle.getRuntime().createVirtualFrame(
new Object[]{fieldStartPosition, fieldEndPosition}, frameDescriptor);
BFType value = (BFType) parseFieldNodes[i].execute(localFrame);
object.setValue(i, value);
// if((char)UnsafeUtils.getByte(fieldEndPosition) != '|')
// throw new RuntimeException("huch");
context.currentAddres = fieldEndPosition + 1;
}
context.currentAddres = context.currentAddres + 1;
}
}
}
|
package seedu.address.logic.commands.commandFind;
import static java.util.Objects.requireNonNull;
import seedu.address.commons.core.Messages;
import seedu.address.logic.commands.Command;
import seedu.address.logic.commands.CommandResult;
import seedu.address.model.Model;
import seedu.address.model.modelFinance.FinanceNameContainsKeywordsPredicate;
/**
* Finds and lists all finances in address book whose name contains any of the argument keywords.
* Keyword matching is case insensitive.
*/
public class FindFinanceCommand extends Command {
public static final String COMMAND_WORD = "find-finance";
public static final String MESSAGE_USAGE =
COMMAND_WORD + ": Finds all finances whose names contain any of "
+ "the specified keywords (case-insensitive) and displays them as a list with index numbers.\n"
+ "Parameters: KEYWORD [MORE_KEYWORDS]...\n"
+ "Example: " + COMMAND_WORD + " alice bob charlie";
private final FinanceNameContainsKeywordsPredicate predicate;
public FindFinanceCommand(FinanceNameContainsKeywordsPredicate predicate) {
this.predicate = predicate;
}
@Override
public CommandResult execute(Model model) {
requireNonNull(model);
model.updateFilteredFinanceList(predicate);
model.getMainWindow().callSwitchToFinance();
return new CommandResult(
String.format(Messages.MESSAGE_FINANCES_LISTED_OVERVIEW,
model.getFilteredFinanceList().size()));
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof FindFinanceCommand // instanceof handles nulls
&& predicate.equals(((FindFinanceCommand) other).predicate)); // state check
}
}
|
/*
* Copyright (c) 2008-2016, GigaSpaces Technologies, 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 org.openspaces.core;
import com.gigaspaces.client.ChangedEntryDetails;
import com.gigaspaces.client.FailedChangedEntryDetails;
import com.gigaspaces.internal.client.FailedChangedEntryDetailsImpl;
import org.openspaces.core.exception.ExceptionTranslator;
import org.springframework.dao.InvalidDataAccessResourceUsageException;
import java.util.ArrayList;
import java.util.Collection;
/**
* Thrown when an error occurred while performing a {@link GigaSpace#change(com.gigaspaces.query.IdQuery,
* com.gigaspaces.client.ChangeSet, com.gigaspaces.client.ChangeModifiers, long)} operation.
*
* @author eitany
* @since 9.1
*/
public class ChangeException extends InvalidDataAccessResourceUsageException {
private static final long serialVersionUID = 1L;
private final Collection<ChangedEntryDetails<?>> changedEntries;
private final Collection<FailedChangedEntryDetails> translatedEntriesFailedToChange;
private final Collection<Throwable> translatedErrors;
private final int numChangedEntries;
public ChangeException(com.gigaspaces.client.ChangeException changeException, ExceptionTranslator exceptionTranslator) {
super(changeException.getMessage(), changeException);
this.numChangedEntries = changeException.getNumSuccesfullChanges();
this.changedEntries = changeException.getSuccesfullChanges();
translatedEntriesFailedToChange = new ArrayList<FailedChangedEntryDetails>(changeException.getFailedChanges().size());
for (FailedChangedEntryDetails failedChangeEntryResult : changeException.getFailedChanges()) {
translatedEntriesFailedToChange.add(new FailedChangedEntryDetailsImpl(failedChangeEntryResult.getTypeName(),
failedChangeEntryResult.getId(), failedChangeEntryResult.getVersion(), translateException(exceptionTranslator, failedChangeEntryResult.getCause())));
}
translatedErrors = new ArrayList<Throwable>(changeException.getErrors().size());
for (Throwable error : changeException.getErrors()) {
translatedErrors.add(translateException(exceptionTranslator, error));
}
}
private static Exception translateException(ExceptionTranslator exceptionTranslator,
Throwable error) {
Exception translatedException;
try {
translatedException = exceptionTranslator.translate(error);
} catch (Exception e) {
translatedException = e;
}
return translatedException;
}
/**
* Returns the successfully done changes.
*/
public Collection<ChangedEntryDetails<?>> getSuccesfullChanges() {
if (changedEntries == null)
throw new UnsupportedOperationException(" no detailed information available: operation modifier not set to return detailed change result");
return changedEntries;
}
/**
* Returns the number of successful changes.
*/
public int getNumSuccesfullChanges() {
return numChangedEntries;
}
/**
* Returns the entries that failed to change result.
*/
public Collection<FailedChangedEntryDetails> getFailedChanges() {
return translatedEntriesFailedToChange;
}
/**
* Returns the failed changes.
*/
public Collection<Throwable> getErrors() {
return translatedErrors;
}
}
|
package util;
import java.util.Optional;
/**
* Utility for reading a network port out of a command line arguments.
*
* This class is here for your convenience, it is NOT part of the framework. You can add to it as much
* as you want, or delete it.
*/
public class PortReader {
public static Optional<Integer> readPortFromArgs(String[] args) {
if (args.length == 0) {
return Optional.empty();
}
try {
return Optional.of(Integer.parseInt(args[0]));
} catch (NumberFormatException e) {
return Optional.empty();
}
}
}
|
/*
* Copyright (c) 2020 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 com.exadel.frs.system.security;
import static com.exadel.frs.enums.OrganizationRole.ADMINISTRATOR;
import static com.exadel.frs.enums.OrganizationRole.OWNER;
import static com.exadel.frs.enums.OrganizationRole.USER;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.exadel.frs.dto.ui.UserDeleteDto;
import com.exadel.frs.entity.App;
import com.exadel.frs.entity.Model;
import com.exadel.frs.entity.Organization;
import com.exadel.frs.entity.User;
import com.exadel.frs.entity.UserAppRole;
import com.exadel.frs.entity.UserAppRoleId;
import com.exadel.frs.entity.UserOrganizationRole;
import com.exadel.frs.entity.UserOrganizationRoleId;
import com.exadel.frs.enums.AppRole;
import com.exadel.frs.enums.OrganizationRole;
import com.exadel.frs.exception.AppDoesNotBelongToOrgException;
import com.exadel.frs.exception.InsufficientPrivilegesException;
import com.exadel.frs.exception.ModelDoesNotBelongToAppException;
import java.util.List;
import java.util.UUID;
import lombok.val;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
class AuthorizationManagerTest {
private static final long ORG_ID = 10001L;
private static final long APP_ID = 20001L;
private static final long MODEL_ID = 30003L;
private static final String ORG_GUID = UUID.randomUUID().toString();
private static final String APP_GUID = UUID.randomUUID().toString();
private static final long ORG_USER_ID = 1L;
private static final long ORG_ADMIN_ID = 2L;
private static final long ORG_OWNER_ID = 3L;
private static final long STRANGE_USER_ID = 4L;
private static final long ORG_USER_APP_USER_ID = 5L;
private static final long ORG_USER_APP_ADMIN_ID = 6L;
private static final long ORG_USER_APP_OWNER_ID = 7L;
private static final long ORG_ADMIN_APP_USER_ID = 8L;
private static final long ORG_ADMIN_APP_ADMIN_ID = 9L;
private static final long ORG_ADMIN_APP_OWNER_ID = 10L;
private static final long ORG_OWNER_APP_USER_ID = 11L;
private static final long ORG_OWNER_APP_ADMIN_ID = 12L;
private static final long ORG_OWNER_APP_OWNER_ID = 13L;
private final AuthorizationManager authManager;
private final Organization organization;
private final App application;
public AuthorizationManagerTest() {
authManager = new AuthorizationManager();
application = App.builder()
.id(APP_ID)
.guid(APP_GUID)
.userAppRoles(appRoles())
.build();
organization = Organization.builder()
.id(ORG_ID)
.guid(ORG_GUID)
.apps(List.of(application))
.userOrganizationRoles(orgRoles())
.build();
application.setOrganization(organization);
}
@Nested
public class TestOrganizationPrivileges {
@Test
void orgUserOrgAdminAndOrgOwnerCanReadOrg() {
authManager.verifyReadPrivilegesToOrg(ORG_USER_ID, organization);
authManager.verifyReadPrivilegesToOrg(ORG_ADMIN_ID, organization);
authManager.verifyReadPrivilegesToOrg(ORG_OWNER_ID, organization);
}
@Test
void outsideOrgUsersCannotReadOrg() {
assertThatThrownBy(() -> {
authManager.verifyReadPrivilegesToOrg(STRANGE_USER_ID, organization);
}).isInstanceOf(InsufficientPrivilegesException.class);
}
@Test
void orgAdminAndOrgOwnerCanWriteOrg() {
authManager.verifyWritePrivilegesToOrg(ORG_ADMIN_ID, organization);
authManager.verifyWritePrivilegesToOrg(ORG_OWNER_ID, organization);
}
@Test
void orgUserCannotWriteOrg() {
assertThatThrownBy(() -> {
authManager.verifyWritePrivilegesToOrg(ORG_USER_ID, organization);
}).isInstanceOf(InsufficientPrivilegesException.class);
}
@Test
void outsideOrgUsersCannotWriteOrg() {
assertThatThrownBy(() -> {
authManager.verifyWritePrivilegesToOrg(STRANGE_USER_ID, organization);
}).isInstanceOf(InsufficientPrivilegesException.class);
}
}
@Nested
public class TestAppPrivileges {
@Test
void orgUserNotInvitedToAppCannotReadApp() {
assertThatThrownBy(() -> {
authManager.verifyReadPrivilegesToApp(ORG_USER_ID, application);
}).isInstanceOf(InsufficientPrivilegesException.class);
}
@Test
void outsideOrgUsersCannotReadApp() {
assertThatThrownBy(() -> {
authManager.verifyReadPrivilegesToApp(STRANGE_USER_ID, application);
}).isInstanceOf(InsufficientPrivilegesException.class);
}
@Test
void uninvitedOrgOwnerAndOrgAdminCanReadApp() {
authManager.verifyReadPrivilegesToApp(ORG_OWNER_ID, application);
authManager.verifyReadPrivilegesToApp(ORG_ADMIN_ID, application);
}
@Test
void userWithAnyRoleToAppCanReadApp() {
authManager.verifyReadPrivilegesToApp(ORG_USER_APP_USER_ID, application);
authManager.verifyReadPrivilegesToApp(ORG_USER_APP_ADMIN_ID, application);
authManager.verifyReadPrivilegesToApp(ORG_USER_APP_OWNER_ID, application);
authManager.verifyReadPrivilegesToApp(ORG_ADMIN_APP_USER_ID, application);
authManager.verifyReadPrivilegesToApp(ORG_ADMIN_APP_ADMIN_ID, application);
authManager.verifyReadPrivilegesToApp(ORG_ADMIN_APP_OWNER_ID, application);
authManager.verifyReadPrivilegesToApp(ORG_OWNER_APP_USER_ID, application);
authManager.verifyReadPrivilegesToApp(ORG_OWNER_APP_ADMIN_ID, application);
authManager.verifyReadPrivilegesToApp(ORG_OWNER_APP_OWNER_ID, application);
}
@Test
void orgOwnerAndOrgAdminNotInvitedToAppCanWriteApp() {
assertThatCode(() -> {
authManager.verifyWritePrivilegesToApp(ORG_ADMIN_ID, application);
}).doesNotThrowAnyException();
assertThatCode(() -> {
authManager.verifyWritePrivilegesToApp(ORG_OWNER_ID, application);
}).doesNotThrowAnyException();
}
@Test
void appUserCanWriteAppIfTheyAreOrgWriters() {
assertThatCode(() -> {
authManager.verifyWritePrivilegesToApp(ORG_ADMIN_APP_USER_ID, application);
}).doesNotThrowAnyException();
assertThatCode(() -> {
authManager.verifyWritePrivilegesToApp(ORG_OWNER_APP_USER_ID, application);
}).doesNotThrowAnyException();
}
@Test
void appUserCannotWriteApp() {
assertThatThrownBy(() -> {
authManager.verifyWritePrivilegesToApp(ORG_USER_APP_USER_ID, application);
}).isInstanceOf(InsufficientPrivilegesException.class);
}
@Test
void appAdminAndAppOwnerCanWriteApp() {
authManager.verifyWritePrivilegesToApp(ORG_USER_APP_ADMIN_ID, application);
authManager.verifyWritePrivilegesToApp(ORG_USER_APP_OWNER_ID, application);
authManager.verifyWritePrivilegesToApp(ORG_ADMIN_APP_ADMIN_ID, application);
authManager.verifyWritePrivilegesToApp(ORG_ADMIN_APP_OWNER_ID, application);
authManager.verifyWritePrivilegesToApp(ORG_OWNER_APP_ADMIN_ID, application);
authManager.verifyWritePrivilegesToApp(ORG_OWNER_APP_OWNER_ID, application);
}
}
@Nested
public class TestDeleteUserPrivileges {
final Organization defaultOrg;
final User orgOwner;
final User orgAdmin;
final User orgAdmin2;
final User orgUser;
final User orgUser2;
public TestDeleteUserPrivileges() {
orgOwner = makeUser(ORG_OWNER_ID);
orgAdmin = makeUser(ORG_ADMIN_ID);
orgAdmin2 = makeUser(ORG_ADMIN_APP_ADMIN_ID);
orgUser = makeUser(ORG_USER_ID);
orgUser2 = makeUser(ORG_USER_APP_USER_ID);
val orgOwnerRole = makeRole(orgOwner, OWNER);
val orgAdminRole = makeRole(orgAdmin, ADMINISTRATOR);
val orgAdmin2Role = makeRole(orgAdmin2, ADMINISTRATOR);
val orgUserRole = makeRole(orgUser, USER);
val orgUser2Role = makeRole(orgUser2, USER);
val roles = List.of(orgOwnerRole, orgAdminRole, orgAdmin2Role, orgUserRole, orgUser2Role);
defaultOrg = Organization.builder()
.isDefault(true)
.userOrganizationRoles(roles)
.build();
}
@Test
void orgOwnerCannotBeDeleted() {
val ownerRemovalByAdmin = UserDeleteDto.builder()
.defaultOrg(defaultOrg)
.deleter(orgAdmin)
.userToDelete(orgOwner)
.build();
val ownerRemovalByItself = UserDeleteDto.builder()
.defaultOrg(defaultOrg)
.deleter(orgOwner)
.userToDelete(orgOwner)
.build();
assertThatThrownBy(() -> {
authManager.verifyCanDeleteUser(ownerRemovalByAdmin);
}).isInstanceOf(InsufficientPrivilegesException.class)
.hasMessage("Organization owner cannot be removed!");
assertThatThrownBy(() -> {
authManager.verifyCanDeleteUser(ownerRemovalByItself);
}).isInstanceOf(InsufficientPrivilegesException.class)
.hasMessage("Organization owner cannot be removed!");
}
@Test
void orgAdminCanDeleteItself() {
val adminRemovalByItself = UserDeleteDto.builder()
.defaultOrg(defaultOrg)
.deleter(orgAdmin)
.userToDelete(orgAdmin)
.build();
authManager.verifyCanDeleteUser(adminRemovalByItself);
}
@Test
void orgAdminCanDeleteOtherAdminOrUsers() {
val adminRemovalByOtherAdmin = UserDeleteDto.builder()
.defaultOrg(defaultOrg)
.deleter(orgAdmin)
.userToDelete(orgAdmin2)
.build();
val userRemovalByAdmin = UserDeleteDto.builder()
.defaultOrg(defaultOrg)
.deleter(orgAdmin)
.userToDelete(orgUser)
.build();
authManager.verifyCanDeleteUser(adminRemovalByOtherAdmin);
authManager.verifyCanDeleteUser(userRemovalByAdmin);
}
@Test
void orgUserCannotDeleteOthers() {
val adminRemovalByUser = UserDeleteDto.builder()
.defaultOrg(defaultOrg)
.deleter(orgUser)
.userToDelete(orgAdmin)
.build();
val userRemovalByOtherUser = UserDeleteDto.builder()
.defaultOrg(defaultOrg)
.deleter(orgUser)
.userToDelete(orgUser2)
.build();
assertThatThrownBy(() -> {
authManager.verifyCanDeleteUser(adminRemovalByUser);
}).isInstanceOf(InsufficientPrivilegesException.class)
.hasMessage("Action not allowed for current user");
assertThatThrownBy(() -> {
authManager.verifyCanDeleteUser(userRemovalByOtherUser);
}).isInstanceOf(InsufficientPrivilegesException.class)
.hasMessage("Action not allowed for current user");
}
@Test
void orgUserCanDeleteItself() {
val userRemovalByItself = UserDeleteDto.builder()
.defaultOrg(defaultOrg)
.deleter(orgUser)
.userToDelete(orgUser)
.build();
authManager.verifyCanDeleteUser(userRemovalByItself);
}
private User makeUser(final long orgUserId) {
return User.builder()
.id(orgUserId)
.guid(UUID.randomUUID().toString())
.build();
}
private UserOrganizationRole makeRole(final User user, OrganizationRole role) {
val roleId = UserOrganizationRoleId.builder()
.userId(user.getId())
.organizationId(ORG_ID)
.build();
return UserOrganizationRole.builder()
.id(roleId)
.user(user)
.role(role)
.build();
}
}
@Test
void verifyOrganizationHasTheApp() {
authManager.verifyOrganizationHasTheApp(ORG_GUID, application);
}
@Test
void strangeAppThrowsException() {
val otherOrg = Organization.builder()
.guid(UUID.randomUUID().toString())
.build();
val strangeApp = App.builder()
.organization(otherOrg)
.build();
assertThatThrownBy(() -> {
authManager.verifyOrganizationHasTheApp(ORG_GUID, strangeApp);
}).isInstanceOf(AppDoesNotBelongToOrgException.class);
}
@Test
void verifyAppHasModel() {
val model = Model.builder()
.id(MODEL_ID)
.app(application)
.build();
application.setModels(List.of(model));
authManager.verifyAppHasTheModel(APP_GUID, model);
}
@Test
void strangeModelThrowsException() {
val otherApp = App.builder()
.guid(UUID.randomUUID().toString())
.build();
val strangeModel = Model.builder()
.app(otherApp)
.build();
assertThatThrownBy(() -> {
authManager.verifyAppHasTheModel(APP_GUID, strangeModel);
}).isInstanceOf(ModelDoesNotBelongToAppException.class);
}
private List<UserOrganizationRole> orgRoles() {
return List.of(
makeOrgRole(ORG_USER_ID, USER),
makeOrgRole(ORG_USER_APP_USER_ID, USER),
makeOrgRole(ORG_USER_APP_ADMIN_ID, USER),
makeOrgRole(ORG_USER_APP_OWNER_ID, USER),
makeOrgRole(ORG_ADMIN_ID, ADMINISTRATOR),
makeOrgRole(ORG_ADMIN_APP_USER_ID, ADMINISTRATOR),
makeOrgRole(ORG_ADMIN_APP_ADMIN_ID, ADMINISTRATOR),
makeOrgRole(ORG_ADMIN_APP_OWNER_ID, ADMINISTRATOR),
makeOrgRole(ORG_OWNER_ID, OWNER),
makeOrgRole(ORG_OWNER_APP_USER_ID, OWNER),
makeOrgRole(ORG_OWNER_APP_ADMIN_ID, OWNER),
makeOrgRole(ORG_OWNER_APP_OWNER_ID, OWNER)
);
}
private List<UserAppRole> appRoles() {
return List.of(
makeAppRole(ORG_USER_APP_USER_ID, AppRole.USER),
makeAppRole(ORG_ADMIN_APP_USER_ID, AppRole.USER),
makeAppRole(ORG_OWNER_APP_USER_ID, AppRole.USER),
makeAppRole(ORG_USER_APP_ADMIN_ID, AppRole.ADMINISTRATOR),
makeAppRole(ORG_ADMIN_APP_ADMIN_ID, AppRole.ADMINISTRATOR),
makeAppRole(ORG_OWNER_APP_ADMIN_ID, AppRole.ADMINISTRATOR),
makeAppRole(ORG_USER_APP_OWNER_ID, AppRole.OWNER),
makeAppRole(ORG_ADMIN_APP_OWNER_ID, AppRole.OWNER),
makeAppRole(ORG_OWNER_APP_OWNER_ID, AppRole.OWNER)
);
}
private UserOrganizationRole makeOrgRole(final long userId, OrganizationRole role) {
val id = UserOrganizationRoleId.builder()
.userId(userId)
.organizationId(ORG_ID)
.build();
return UserOrganizationRole.builder()
.id(id)
.role(role)
.organization(organization)
.user(User.builder()
.id(userId)
.build()
)
.build();
}
private UserAppRole makeAppRole(final long userId, final AppRole role) {
val id = new UserAppRoleId(userId, APP_ID);
return UserAppRole.builder()
.id(id)
.app(application)
.role(role)
.user(User.builder()
.id(userId)
.build()
)
.build();
}
}
|
/*
* Copyright 2016 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.keycloak.keys;
import org.keycloak.component.ComponentModel;
import org.keycloak.component.ComponentValidationException;
import org.keycloak.crypto.Algorithm;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.provider.ConfigurationValidationHelper;
import org.keycloak.provider.ProviderConfigProperty;
import org.keycloak.provider.ProviderConfigurationBuilder;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.spec.ECGenParameterSpec;
import static org.keycloak.provider.ProviderConfigProperty.LIST_TYPE;
public abstract class AbstractEcdsaKeyProviderFactory implements KeyProviderFactory {
protected static final String ECDSA_PRIVATE_KEY_KEY = "ecdsaPrivateKey";
protected static final String ECDSA_PUBLIC_KEY_KEY = "ecdsaPublicKey";
protected static final String ECDSA_ELLIPTIC_CURVE_KEY = "ecdsaEllipticCurveKey";
// only support NIST P-256 for ES256, P-384 for ES384, P-521 for ES512
protected static ProviderConfigProperty ECDSA_ELLIPTIC_CURVE_PROPERTY = new ProviderConfigProperty(ECDSA_ELLIPTIC_CURVE_KEY, "Elliptic Curve", "Elliptic Curve used in ECDSA", LIST_TYPE,
String.valueOf(GeneratedEcdsaKeyProviderFactory.DEFAULT_ECDSA_ELLIPTIC_CURVE),
"P-256", "P-384", "P-521");
public final static ProviderConfigurationBuilder configurationBuilder() {
return ProviderConfigurationBuilder.create()
.property(Attributes.PRIORITY_PROPERTY)
.property(Attributes.ENABLED_PROPERTY)
.property(Attributes.ACTIVE_PROPERTY);
}
@Override
public void validateConfiguration(KeycloakSession session, RealmModel realm, ComponentModel model) throws ComponentValidationException {
ConfigurationValidationHelper.check(model)
.checkLong(Attributes.PRIORITY_PROPERTY, false)
.checkBoolean(Attributes.ENABLED_PROPERTY, false)
.checkBoolean(Attributes.ACTIVE_PROPERTY, false);
}
public static KeyPair generateEcdsaKeyPair(String keySpecName) {
try {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
SecureRandom randomGen = SecureRandom.getInstance("SHA1PRNG");
ECGenParameterSpec ecSpec = new ECGenParameterSpec(keySpecName);
keyGen.initialize(ecSpec, randomGen);
return keyGen.generateKeyPair();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String convertECDomainParmNistRepToSecRep(String ecInNistRep) {
// convert Elliptic Curve Domain Parameter Name in NIST to SEC which is used to generate its EC key
String ecInSecRep = null;
switch(ecInNistRep) {
case "P-256" :
ecInSecRep = "secp256r1";
break;
case "P-384" :
ecInSecRep = "secp384r1";
break;
case "P-521" :
ecInSecRep = "secp521r1";
break;
default :
// return null
}
return ecInSecRep;
}
public static String convertECDomainParmNistRepToAlgorithm(String ecInNistRep) {
switch(ecInNistRep) {
case "P-256" :
return Algorithm.ES256;
case "P-384" :
return Algorithm.ES384;
case "P-521" :
return Algorithm.ES512;
default :
return null;
}
}
public static String convertAlgorithmToECDomainParmNistRep(String algorithm) {
switch(algorithm) {
case Algorithm.ES256 :
return "P-256";
case Algorithm.ES384 :
return "P-384";
case Algorithm.ES512 :
return "P-521";
default :
return null;
}
}
}
|
/*
* Copyright 2010 Ning, Inc.
*
* Ning 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.ning.http.client.async;
import com.ning.http.client.AsyncHandler;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.HttpResponseBodyPart;
import com.ning.http.client.HttpResponseHeaders;
import com.ning.http.client.HttpResponseStatus;
import org.eclipse.jetty.continuation.Continuation;
import org.eclipse.jetty.continuation.ContinuationSupport;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
/**
* Tests default asynchronous life cycle.
*
* @author Hubert Iwaniuk
*/
public abstract class AsyncStreamLifecycleTest extends AbstractBasicTest {
private ExecutorService executorService = Executors.newFixedThreadPool(2);
@AfterClass
@Override
public void tearDownGlobal() throws Exception {
super.tearDownGlobal();
executorService.shutdownNow();
}
@Override
public AbstractHandler configureHandler() throws Exception {
return new AbstractHandler() {
public void handle(String s, Request request, HttpServletRequest req, final HttpServletResponse resp) throws IOException, ServletException {
resp.setContentType("text/plain;charset=utf-8");
resp.setStatus(200);
final Continuation continuation = ContinuationSupport.getContinuation(req);
continuation.suspend();
final PrintWriter writer = resp.getWriter();
executorService.submit(new Runnable() {
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
log.error("Failed to sleep for 100 ms.", e);
}
log.info("Delivering part1.");
writer.write("part1");
writer.flush();
}
});
executorService.submit(new Runnable() {
public void run() {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
log.error("Failed to sleep for 200 ms.", e);
}
log.info("Delivering part2.");
writer.write("part2");
writer.flush();
continuation.complete();
}
});
request.setHandled(true);
}
};
}
@Test(groups = { "standalone", "default_provider" })
public void testStream() throws IOException {
AsyncHttpClient client = getAsyncHttpClient(null);
try {
final AtomicBoolean err = new AtomicBoolean(false);
final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>();
final AtomicBoolean status = new AtomicBoolean(false);
final AtomicInteger headers = new AtomicInteger(0);
final CountDownLatch latch = new CountDownLatch(1);
client.executeRequest(client.prepareGet(getTargetUrl()).build(), new AsyncHandler<Object>() {
public void onThrowable(Throwable t) {
fail("Got throwable.", t);
err.set(true);
}
public STATE onBodyPartReceived(HttpResponseBodyPart e) throws Exception {
String s = new String(e.getBodyPartBytes());
log.info("got part: {}", s);
if (s.isEmpty()) {
// noinspection ThrowableInstanceNeverThrown
log.warn("Sampling stacktrace.", new Throwable("trace that, we should not get called for empty body."));
}
queue.put(s);
return STATE.CONTINUE;
}
public STATE onStatusReceived(HttpResponseStatus e) throws Exception {
status.set(true);
return STATE.CONTINUE;
}
public STATE onHeadersReceived(HttpResponseHeaders e) throws Exception {
if (headers.incrementAndGet() == 2) {
throw new Exception("Analyze this.");
}
return STATE.CONTINUE;
}
public Object onCompleted() throws Exception {
latch.countDown();
return null;
}
});
try {
assertTrue(latch.await(1, TimeUnit.SECONDS), "Latch failed.");
} catch (InterruptedException e) {
fail("Interrupted.", e);
}
assertFalse(err.get());
assertEquals(queue.size(), 2);
assertTrue(queue.contains("part1"));
assertTrue(queue.contains("part2"));
assertTrue(status.get());
assertEquals(headers.get(), 1);
} finally {
client.close();
}
}
}
|
package net.sunxu.website.blog.service.controller;
import net.sunxu.website.blog.service.service.StatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/article/{id}")
public class StatisticsController {
@Autowired
private StatisticsService statisticsService;
@PostMapping("/like")
@ResponseBody
public void postLike(@PathVariable("id") Long articleId, @RequestParam("like") Boolean like) {
statisticsService.likeArticle(articleId, like);
}
@GetMapping("/share")
public String shareArticle(@PathVariable("id") Long id, @RequestParam("mediaType") String mediaType) {
String redirect = statisticsService.shareArticle(id, mediaType);
return "redirect:" + redirect;
}
}
|
package com.alibaba.otter.canal.example;
import java.net.InetSocketAddress;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.otter.canal.client.CanalConnector;
import com.alibaba.otter.canal.client.CanalConnectors;
import com.alibaba.otter.canal.client.impl.SimpleCanalConnector;
import com.alibaba.otter.canal.common.utils.AddressUtils;
import com.alibaba.otter.canal.protocol.Message;
import io.netty.util.internal.StringUtil;
public class SimpleCanalClientPermanceTest {
protected final static Logger logger = LoggerFactory.getLogger(SimpleCanalClientPermanceTest.class);
public static void main(String args[]) {
String destination = "example";
if(!StringUtil.isNullOrEmpty(System.getProperty("canal.destination"))){
destination = System.getProperty("canal.destination");
logger.warn("destination:"+destination);
}
String ip = AddressUtils.getHostIp();
if(!StringUtil.isNullOrEmpty(System.getProperty("canal.ip"))){
ip = System.getProperty("canal.ip");
logger.warn("ip:"+ip);
}
int port = 11111;
if(!StringUtil.isNullOrEmpty(System.getProperty("canal.port"))){
port = Integer.valueOf(System.getProperty("canal.port"));
logger.warn("port:"+port);
}
int batchSize = 1024;
if(!StringUtil.isNullOrEmpty(System.getProperty("canal.batch.size"))){
batchSize = Integer.valueOf(System.getProperty("canal.batch.size"));
logger.warn("batchSize:"+batchSize);
}
int count = 0;
int sum = 0;
int perSum = 0;
long start = System.currentTimeMillis();
long end = 0;
final ArrayBlockingQueue<Long> queue = new ArrayBlockingQueue<Long>(100);
try {
final CanalConnector connector = CanalConnectors.newSingleConnector(new InetSocketAddress(ip, port),
destination,
"",
"");
Thread ackThread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
long batchId = queue.take();
connector.ack(batchId);
} catch (InterruptedException e) {
}
}
}
});
ackThread.start();
((SimpleCanalConnector) connector).setLazyParseEntry(true);
connector.connect();
connector.subscribe();
while (true) {
Message message = connector.getWithoutAck(batchSize, 100L, TimeUnit.MILLISECONDS);
long batchId = message.getId();
int size = message.getRawEntries().size();
sum += size;
perSum += size;
count++;
queue.add(batchId);
if (count % 10 == 0) {
end = System.currentTimeMillis();
if (end - start != 0) {
long tps = (perSum * 1000) / (end - start);
System.out.println(" total : " + sum + " , current : " + perSum + " , cost : " + (end - start)
+ " , tps : " + tps);
start = end;
perSum = 0;
}
}
}
} catch (Throwable e) {
e.printStackTrace();
}
}
}
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.http;
import com.yahoo.container.jdisc.HttpResponse;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.core5.http.NameValuePair;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Optional;
/**
* Proxies response back to client, keeps Content-Type header if it is present
*
* @author olaa
* @author freva
*/
class ProxyResponse extends HttpResponse {
private final CloseableHttpResponse clientResponse;
ProxyResponse(CloseableHttpResponse clientResponse) {
super(clientResponse.getCode());
this.clientResponse = clientResponse;
}
@Override
public String getContentType() {
return Optional.ofNullable(clientResponse.getFirstHeader("Content-Type"))
.map(NameValuePair::getValue)
.orElseGet(super::getContentType);
}
@Override
public void render(OutputStream outputStream) throws IOException {
try (clientResponse) {
clientResponse.getEntity().writeTo(outputStream);
}
}
}
|
//Deobfuscated with https://github.com/PetoPetko/Minecraft-Deobfuscator3000 using mappings "mcp_snapshot-20171003-1.12"!
/*
* Decompiled with CFR 0.150.
*
* Could not load the following classes:
* net.minecraft.block.Block
* net.minecraft.block.SoundType
* net.minecraft.block.material.Material
* net.minecraft.block.state.IBlockState
* net.minecraft.client.Minecraft
* net.minecraft.client.renderer.block.model.ModelResourceLocation
* net.minecraft.creativetab.CreativeTabs
* net.minecraft.item.Item
* net.minecraft.item.ItemBlock
* net.minecraft.util.BlockRenderLayer
* net.minecraft.util.EnumFacing
* net.minecraft.util.math.AxisAlignedBB
* net.minecraft.util.math.BlockPos
* net.minecraft.world.IBlockAccess
* net.minecraft.world.World
* net.minecraftforge.fml.common.event.FMLInitializationEvent
* net.minecraftforge.fml.common.event.FMLPreInitializationEvent
* net.minecraftforge.fml.common.registry.ForgeRegistries
* net.minecraftforge.fml.relauncher.Side
* net.minecraftforge.fml.relauncher.SideOnly
* net.minecraftforge.registries.IForgeRegistryEntry
*/
package mod.mcreator;
import net.minecraft.block.Block;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.Objects;
import java.util.Random;
public class mcreator_roadBlockBlue extends theworlditems2.ModElement {
public static Block block = new BlockCustom().setHardness(5.0f).setResistance(8.0f).setLightLevel(0.0f).setUnlocalizedName("roadblockblue").setLightOpacity(255).setCreativeTab(CreativeTabs.BUILDING_BLOCKS);
@Override
public void preInit(FMLPreInitializationEvent event) {
block.setHarvestLevel("pickaxe", 2);
block.setRegistryName("roadblockblue");
ForgeRegistries.BLOCKS.register(block);
ForgeRegistries.ITEMS.register(new ItemBlock(block).setRegistryName(Objects.requireNonNull(block.getRegistryName())));
}
@Override
public void load(FMLInitializationEvent event) {
if (event.getSide() == Side.CLIENT) {
Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register(Item.getItemFromBlock(block), 0, new ModelResourceLocation("theworlditems2:roadblockblue", "inventory"));
}
}
public static class BlockCustom
extends Block {
private final boolean red = false;
public BlockCustom() {
super(Material.ROCK);
this.setSoundType(SoundType.STONE);
}
@SideOnly(value=Side.CLIENT)
public BlockRenderLayer getBlockLayer() {
return BlockRenderLayer.SOLID;
}
public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) {
return new AxisAlignedBB(0.0, 0.0, 0.0, 1.0, 1.0, 1.0);
}
public int tickRate(World world) {
return 10;
}
public int quantityDropped(Random random) {
return 1;
}
public int getWeakPower(IBlockState state, IBlockAccess baccess, BlockPos pos, EnumFacing side) {
return this.red ? 15 : 0;
}
public int getStrongPower(IBlockState state, IBlockAccess baccess, BlockPos pos, EnumFacing side) {
return this.red ? 15 : 0;
}
}
}
|
/*
* 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 eu.fasten.vulnerabilityproducer.utils;
import com.mongodb.client.MongoDatabase;
import eu.fasten.vulnerabilityproducer.db.NitriteController;
import eu.fasten.vulnerabilityproducer.db.PatchObject;
import eu.fasten.vulnerabilityproducer.utils.Vulnerability.*;
import eu.fasten.vulnerabilityproducer.utils.connections.*;
import eu.fasten.vulnerabilityproducer.utils.patches.*;
import org.jooq.tools.json.JSONParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.UnaryOperator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* This class has the responsibility to handle references and crawl for commits.
* Those will lead to diffs that will lead to changed files.
* Those files will be considered vulnerable since they needed changes in order
*/
public class PatchFinder {
public static JSONParser jsonParser;
public static JavaHttpClient httpClient;
public String gitHubToken;
public static GitHubRanger gitHubRanger;
public static GitLabRanger gitLabRanger;
public static BitBucketRanger bitBucketRanger;
public static JIRARanger jiraRanger;
public static BugzillaRanger bugzillaRanger;
public static ExtraRanger extraRanger;
public static HashSet<String> refSet;
private final Logger logger = LoggerFactory.getLogger(PatchFinder.class.getName());
// regex utils
public static final String owner = "[a-zA-Z_0-9\\-]++";
public static final String project = "[a-zA-Z_0-9\\-\\.]++";
public static final String sha = "[a-zA-Z_0-9/]++";
// base repo cutter
UnaryOperator<String> repoCutter = ref -> {
var sb = new StringBuilder();
var repo = ref.split("/");
if (repo.length > 4) {
return sb.append("https://").append(repo[2] + "/").append(repo[3] + "/").append(repo[4]).toString();
} else {
return null;
}
};
/**
* Takes a MongoDatabase object to connect and retrieve collections from.
*/
public PatchFinder(MongoDatabase db, JavaHttpClient client, String ghToken) {
httpClient = client;
jsonParser = new JSONParser();
gitHubToken = ghToken;
gitHubRanger = new GitHubRanger(client, db, gitHubToken, jsonParser);
gitLabRanger = new GitLabRanger(client, jsonParser);
bitBucketRanger = new BitBucketRanger(client, jsonParser);
bugzillaRanger = new BugzillaRanger(client, jsonParser);
jiraRanger = new JIRARanger(client, jsonParser);
extraRanger = new ExtraRanger(client, jsonParser);
refSet = new HashSet<>();
}
/**
* Given a string of text, uses regex to find
* @param text
* @return
*/
public static List<String> findPatchLinks(String text) {
List<String> potentialPatches = new ArrayList<>();
List<Matcher> matchers = new ArrayList<>();
matchers.add(Pattern.compile("http(s)?://gitlab(\\.com|\\..*\\.org)/.*").matcher(text));
matchers.add(Pattern.compile("https://github\\.com/.*/.*/(commit|pull|issues)/[\\w]++").matcher(text));
matchers.add(Pattern.compile("https://(issues|jira)\\.[a-zA-Z_0-9\\-]++\\.org/(jira/)?browse/[a-zA-Z_0-9\\-]++").matcher(text));
matchers.add(Pattern.compile("https://(bugs|bugzilla)\\..*\\..*/show_bug\\.cgi\\?id=.*").matcher(text));
matchers.add(Pattern.compile("https://lists\\.apache\\.org/thread\\.html/.*").matcher(text));
matchers.add(Pattern.compile("http(s)?://svn\\.apache\\.org/(.*revision=.*|r[0-9]++)").matcher(text));
matchers.add(Pattern.compile("http(s)?://.*git\\..*\\.(org|com)/.*").matcher(text));
matchers.add(Pattern.compile("https://bitbucket\\.org/" + owner + "/" + project +
"/(commits|pull-requests|issues)/(" + sha + "|(\\d)++)").matcher(text));
matchers.add(Pattern.compile("http(s)?://hg\\..*\\.(net|org)/(\\w)++/" + owner + "(/\\w++)?/rev/" + sha).matcher(text));
for (Matcher matcher : matchers) {
while (matcher.find()) {
potentialPatches.add(matcher.group().split("[\t\\s\n]")[0]);
}
}
return potentialPatches;
}
/**
* Parse all the references looking for diffs.
*
* @param vulnerability to parse references and inject info.
*/
public void parseReferences(Vulnerability vulnerability, NitriteController nc) {
vulnerability.getReferences().addAll(vulnerability.getPatchLinks()); // moving patch_links to refs
var links = vulnerability.getReferences(); // processing all refs
var patchLinks = new HashSet<String>();
for (String ref : links) {
Optional<HashSet<Patch>> queryFromNC = null;
if (nc != null) queryFromNC = nc.findPatchEntry(ref);
if (queryFromNC != null && queryFromNC.isPresent()) {
var count = new AtomicInteger();
queryFromNC.get().forEach(vp -> {
vulnerability.addPatch(vp);
patchLinks.add(ref);
count.addAndGet(1);
});
logger.info("Using cached results for " + count.get()
+ " patched files in ref: " + ref + " for vulnerability " + vulnerability.getId());
} else {
var vp = parseReference(ref);
if (vp != null && vp.size() > 0) {
if (nc != null) {
var po = new PatchObject(ref, vp);
nc.insertPatch(po);
}
logger.info("Found " + vp.size() + " new patched files in ref: " + ref +
" for vulnerability " + vulnerability.getId());
vp.forEach(p -> {
if (p.getPatchUrl() != null) patchLinks.add(p.getPatchUrl());
vulnerability.addPatch(p);
});
}
}
}
vulnerability.getReferences().removeAll(patchLinks); // removing patch_links form refs
}
/**
* Gets a link that might lead to a patch and then extrapolates the information accordingly.
* @param ref - link contained in the vulnerability.
* @return - set of patches extracted from the link.
*/
public static HashSet<Patch> parseReference(String ref) {
ref = httpClient.validateAndRedirect(ref, refSet);
if (ref == null) return null;
// Prevents circular links
if (refSet.contains(ref)) {
return null;
} else {
refSet.add(ref);
}
// Case 1: GitHub commit
if (ref.matches("https://github\\.com/" + owner + "/" + project + "/commit/" + sha)) {
return gitHubRanger.parseGHCommit(ref);
}
// Case 2: GitHub Pull request
if (ref.matches("https://github\\.com/" + owner + "/" + project + "/pull/(\\d)++")) {
return gitHubRanger.parseGHPullRequest(ref);
}
// Case 3: GitHub Issues
if (ref.matches("https://github\\.com/" + owner + "/" + project + "/issues/(\\d)++")) {
return gitHubRanger.parseGHIssue(ref);
}
// Case 4: GitLab commit
if (ref.matches("https://gitlab\\.com/" + owner + "/" + project + "/-/commit/" + sha) ||
ref.matches("https://gitlab\\..*\\.org/" + owner + "/" + project + "/-/commit/" + sha)) {
return gitLabRanger.parseGLCommit(ref);
}
// Case 5: GitLab issue
if (ref.matches("https://gitlab\\.com/" + owner + "/" + project + "/-/issues/(\\d)++") ||
ref.matches("https://gitlab\\..*\\.org/" + owner + "/" + project + "/-/issues/(\\d)++")) {
return gitLabRanger.parseGLIssue(ref);
}
// Case 6: GitLab merge request
if (ref.matches("https://gitlab\\.com/" + owner + "/" + project + "/-/merge_requests/(\\d)++") ||
ref.matches("https://gitlab\\..*\\.org/" + owner + "/" + project + "/-/merge_requests/(\\d)++")) {
return gitLabRanger.parseGLMergeRequest(ref);
}
// Case 7: Git trackers
if (ref.matches("http(s)?://.*git\\..*\\.(org|com)/.*")) {
return extraRanger.parseGitTrackerCommit(ref);
}
// Case 8: SVN Apache link
if (ref.matches("http(s)?://svn\\.apache\\.org/(.*revision=.*|r[0-9]++)")) {
return extraRanger.parseApacheSVNRevision(ref);
}
// Case 9: JIRA tickets
if (ref.matches("https://(issues|jira)\\.[a-zA-Z_0-9\\-]++\\.org/(jira/)?browse/[a-zA-Z_0-9\\-]++")) {
return jiraRanger.parseJIRATicket(ref);
}
// Case 10: Bugzilla server
if (ref.matches("https://(bugs|bugzilla)\\..*\\..*/show_bug\\.cgi\\?id=" + owner)) {
return bugzillaRanger.parseBugzillaBug(ref);
}
// Case 11: Apache Mailing list
if (ref.matches("https://lists\\.apache\\.org/thread\\.html/.*")) {
return extraRanger.parseApacheMailThread(ref);
}
// Case 12: Bitbucket commit
if (ref.matches("https://bitbucket\\.org/" + owner + "/" + project + "/commits/" + sha)) {
return bitBucketRanger.parseBitBucketCommit(ref);
}
// Case 13: Bitbucket PR
if (ref.matches("https://bitbucket\\.org/" + owner + "/" + project + "/pull-requests/(\\d)++")) {
return bitBucketRanger.parseBitBucketPullRequest(ref);
}
// Case 14: Bitbucket Issue
if (ref.matches("https://bitbucket\\.org/" + owner + "/" + project + "/issues/(\\d)++")) {
return bitBucketRanger.parseBitBucketIssue(ref);
}
// Case 15: Mercurial revision
if (ref.matches("http(s)?://hg\\..*\\.(net|org)/(\\w)++/" + owner + "(/\\w++)?/rev/" + sha)) {
return extraRanger.parseMercurialRevision(ref);
}
refSet.add(ref);
return null;
}
/**
* Checks if a reference will output a valid repository link (see #88).
*/
public Boolean isRepoRefValid(String ref) {
if (ref.matches("http(s)?://github\\.com/.*/.*/.*")) return true;
if (ref.matches("http(s)?://gitlab\\.com/.*/.*/.*")) return true;
if (ref.matches("http(s)?://gitlab\\..*\\.org/.*/.*/.*")) return true;
return ref.matches("http(s)?://bitbucket\\.org/.*/.*/.*");
}
/**
* Looks in the patch links for a "repo base" url.
* For now handle GitHub links only, since they represent the majority of the base links.
* @param v _ Vulnerability Object
* @return String with the base url of the repo
*/
public String getBaseRepo(Vulnerability v) {
var mapCounts = new HashMap<String, Integer>();
v.getPatchLinks().forEach(ref -> {
if (isRepoRefValid(ref)) {
mapCounts.merge((repoCutter.apply(ref)), 1, Integer::sum);
}
});
if (mapCounts.isEmpty()) return null;
return Collections.max(mapCounts.entrySet(), Map.Entry.comparingByValue()).getKey();
}
}
|
package com.krishagni.catissueplus.core.de.domain;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import com.krishagni.catissueplus.core.de.domain.Filter.Op;
import com.krishagni.catissueplus.core.de.domain.QueryExpressionNode.LogicalOp;
import com.krishagni.catissueplus.core.de.domain.QueryExpressionNode.Parenthesis;
import com.krishagni.catissueplus.core.de.domain.SelectField.Function;
import edu.common.dynamicextensions.domain.nui.Container;
import edu.common.dynamicextensions.domain.nui.Control;
import edu.common.dynamicextensions.domain.nui.DataType;
import edu.common.dynamicextensions.domain.nui.LookupControl;
public class AqlBuilder {
private AqlBuilder() {
}
public static AqlBuilder getInstance() {
return new AqlBuilder();
}
public String getQuery(Object[] selectList, Filter[] filters, QueryExpressionNode[] queryExprNodes) {
return getQuery(selectList, filters, null, queryExprNodes);
}
public String getQuery(Object[] selectList, Filter[] filters, Filter[] conjunctionFilters, QueryExpressionNode[] queryExprNodes) {
Map<Integer, Filter> filterMap = new HashMap<Integer, Filter>();
for (Filter filter : filters) {
filterMap.put(filter.getId(), filter);
}
String selectClause = buildSelectClause(filterMap, selectList);
String whereClause = buildWhereClause(filterMap, queryExprNodes);
if (conjunctionFilters != null && conjunctionFilters.length > 0) {
whereClause = "(" + whereClause + ") and (";
for (int i = 0; i < conjunctionFilters.length; ++i) {
if (i > 0) {
whereClause += " and ";
}
whereClause += buildFilterExpr(conjunctionFilters[i]);
++i;
}
whereClause += ")";
}
return "select " + selectClause + " where " + whereClause;
}
private String buildSelectClause(Map<Integer, Filter> filterMap, Object[] selectList) {
StringBuilder select = new StringBuilder();
for (Object field : selectList) {
if (field instanceof String) {
select.append(getFieldExpr(filterMap, (String)field, true)).append(", ");
} else if (field instanceof SelectField) {
SelectField aggField = (SelectField)field;
String fieldName = aggField.getName();
if (aggField.getAggFns() == null || aggField.getAggFns().isEmpty()) {
select.append(getFieldExpr(filterMap, fieldName, true)).append(", ");
} else {
String fieldExpr = getFieldExpr(filterMap, fieldName, false);
StringBuilder fnExpr = new StringBuilder("");
for (Function fn : aggField.getAggFns()) {
if (fnExpr.length() > 0) {
fnExpr.append(", ");
}
if (fn.getName().equals("count")) {
fnExpr.append("count(distinct ");
} else {
fnExpr.append(fn.getName()).append("(");
}
fnExpr.append(fieldExpr).append(") as \"").append(fn.getDesc()).append(" \"");
}
select.append(fnExpr.toString()).append(", ");
}
}
}
int endIdx = select.length() - 2;
return select.substring(0, endIdx < 0 ? 0 : endIdx);
}
private String getFieldExpr(Map<Integer, Filter> filterMap, String fieldName, boolean includeDesc) {
if (!fieldName.startsWith("$temporal.")) {
return fieldName;
}
Integer filterId = Integer.parseInt(fieldName.substring("$temporal.".length()));
Filter filter = filterMap.get(filterId);
String expr = getLhs(filter.getExpr());
if (includeDesc) {
expr += " as \"" + filter.getDesc() + "\"";
}
return expr;
}
private String buildWhereClause(Map<Integer, Filter> filterMap, QueryExpressionNode[] queryExprNodes) {
StringBuilder whereClause = new StringBuilder();
for (QueryExpressionNode node : queryExprNodes) {
switch (node.getNodeType()) {
case FILTER:
int filterId;
if (node.getValue() instanceof Double) {
filterId = ((Double)node.getValue()).intValue();
} else {
filterId = (Integer)node.getValue();
}
Filter filter = filterMap.get(filterId);
String filterExpr = buildFilterExpr(filter);
whereClause.append(filterExpr);
break;
case OPERATOR:
LogicalOp op = null;
if (node.getValue() instanceof String) {
op = LogicalOp.valueOf((String)node.getValue());
} else if (node.getValue() instanceof LogicalOp) {
op = (LogicalOp)node.getValue();
}
whereClause.append(op.symbol());
break;
case PARENTHESIS:
Parenthesis paren = null;
if (node.getValue() instanceof String) {
paren = Parenthesis.valueOf((String)node.getValue());
} else if (node.getValue() instanceof Parenthesis) {
paren = (Parenthesis)node.getValue();
}
whereClause.append(paren.symbol());
break;
}
whereClause.append(" ");
}
return whereClause.toString();
}
private String buildFilterExpr(Filter filter) {
if (filter.getExpr() != null) {
return filter.getExpr();
}
String field = filter.getField();
String[] fieldParts = field.split("\\.");
if (fieldParts.length <= 1) {
throw new RuntimeException("Invalid field name"); // need to replace with better exception type
}
StringBuilder filterExpr = new StringBuilder();
filterExpr.append(field).append(" ").append(filter.getOp().symbol()).append(" ");
if (filter.getOp().isUnary()) {
return filterExpr.toString();
}
Container form = null;
String ctrlName = null;
Control ctrl = null;
if (fieldParts[1].equals("extensions") || fieldParts[1].equals("customFields")) {
if (fieldParts.length < 4) {
return "";
}
form = getContainer(fieldParts[2]);
ctrlName = StringUtils.join(fieldParts, ".", 3, fieldParts.length);
} else {
form = getContainer(fieldParts[0]);
ctrlName = StringUtils.join(fieldParts, ".", 1, fieldParts.length);
}
ctrl = form.getControlByUdn(ctrlName, "\\.");
DataType type = ctrl.getDataType();
if (ctrl instanceof LookupControl) {
type = ((LookupControl)ctrl).getValueType();
}
String[] values = (String[])Arrays.copyOf(filter.getValues(), filter.getValues().length);
quoteStrings(type, values);
String value = values[0];
if (filter.getOp() == Op.IN || filter.getOp() == Op.NOT_IN) {
value = "(" + join(values) + ")";
} else if (filter.getOp() == Op.BETWEEN) {
value = "(" + values[0] + ", " + values[1] + ")";
}
return filterExpr.append(value).toString();
}
private void quoteStrings(DataType type, String[] values) {
if (type != DataType.STRING && type != DataType.DATE) {
return;
}
for (int i = 0; i < values.length; ++i) {
values[i] = "\"" + values[i] + "\"";
}
}
private String join(String[] values) {
StringBuilder result = new StringBuilder();
for (String val : values) {
result.append(val).append(", ");
}
int endIdx = result.length() - 2;
return result.substring(0, endIdx < 0 ? 0 : endIdx);
}
private String getLhs(String temporalExpr) {
String[] parts = temporalExpr.split("[<=>!]|\\sany\\s*$|\\sexists\\s*$|\\snot exists\\s*$|\\sbetween\\s");
return parts[0];
}
public Container getContainer(String formName){
return Container.getContainer(formName);
}
}
|
package com.textquo.twist.common;
import com.google.appengine.api.datastore.EntityNotFoundException;
public class ObjectNotFoundException extends TwistException {
private static final long serialVersionUID = 6006726482159235720L;
public ObjectNotFoundException(String message, EntityNotFoundException e){
super(message, e);
}
}
|
/**
* Copyright (C) 2014 serv (liuyuhua69@gmail.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 xxx.yyy.framework.common.enumeration;
/**
* 状态枚举
*
* @author serv
*
*/
public enum State implements ValueEnum<Integer>{
/**
* 启用
*/
Enable(1,"sys.base.state.enable"),
/**
* 禁用
*/
Disable(2,"sys.base.state.disable");
//值
private Integer value;
//名称
private String name;
private State(Integer value,String name) {
this.value = value;
this.name = name;
}
/**
* 获取值
* @return Integer
*/
public Integer getValue() {
return value;
}
/**
* 获取名称
* @return String
*/
public String getName() {
return name;
}
}
|
package io.seata.samples.integration.order.entity;
import java.io.Serializable;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.enums.IdType;
/**
* <p>
*
* </p>
*
* @author
* @since 2019-01-13
*/
public class TOrder extends Model<TOrder> {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String orderNo;
private String userId;
private String commodityCode;
private Integer count;
private Double amount;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getOrderNo() {
return orderNo;
}
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getCommodityCode() {
return commodityCode;
}
public void setCommodityCode(String commodityCode) {
this.commodityCode = commodityCode;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public Double getAmount() {
return amount;
}
public void setAmount(Double amount) {
this.amount = amount;
}
@Override
protected Serializable pkVal() {
return this.id;
}
@Override
public String toString() {
return "TOrder{" +
", id=" + id +
", orderNo=" + orderNo +
", userId=" + userId +
", commodityCode=" + commodityCode +
", count=" + count +
", amount=" + amount +
"}";
}
}
|
/*
* Copyright 2013-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.migrationhub.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Represents a migration task in a migration tool.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/AWSMigrationHub-2017-05-31/MigrationTask" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class MigrationTask implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* A name that identifies the vendor of the migration tool being used.
* </p>
*/
private String progressUpdateStream;
/**
* <p>
* Unique identifier that references the migration task.
* </p>
*/
private String migrationTaskName;
/**
* <p>
* Task object encapsulating task information.
* </p>
*/
private Task task;
/**
* <p>
* The timestamp when the task was gathered.
* </p>
*/
private java.util.Date updateDateTime;
/** <p/> */
private java.util.List<ResourceAttribute> resourceAttributeList;
/**
* <p>
* A name that identifies the vendor of the migration tool being used.
* </p>
*
* @param progressUpdateStream
* A name that identifies the vendor of the migration tool being used.
*/
public void setProgressUpdateStream(String progressUpdateStream) {
this.progressUpdateStream = progressUpdateStream;
}
/**
* <p>
* A name that identifies the vendor of the migration tool being used.
* </p>
*
* @return A name that identifies the vendor of the migration tool being used.
*/
public String getProgressUpdateStream() {
return this.progressUpdateStream;
}
/**
* <p>
* A name that identifies the vendor of the migration tool being used.
* </p>
*
* @param progressUpdateStream
* A name that identifies the vendor of the migration tool being used.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public MigrationTask withProgressUpdateStream(String progressUpdateStream) {
setProgressUpdateStream(progressUpdateStream);
return this;
}
/**
* <p>
* Unique identifier that references the migration task.
* </p>
*
* @param migrationTaskName
* Unique identifier that references the migration task.
*/
public void setMigrationTaskName(String migrationTaskName) {
this.migrationTaskName = migrationTaskName;
}
/**
* <p>
* Unique identifier that references the migration task.
* </p>
*
* @return Unique identifier that references the migration task.
*/
public String getMigrationTaskName() {
return this.migrationTaskName;
}
/**
* <p>
* Unique identifier that references the migration task.
* </p>
*
* @param migrationTaskName
* Unique identifier that references the migration task.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public MigrationTask withMigrationTaskName(String migrationTaskName) {
setMigrationTaskName(migrationTaskName);
return this;
}
/**
* <p>
* Task object encapsulating task information.
* </p>
*
* @param task
* Task object encapsulating task information.
*/
public void setTask(Task task) {
this.task = task;
}
/**
* <p>
* Task object encapsulating task information.
* </p>
*
* @return Task object encapsulating task information.
*/
public Task getTask() {
return this.task;
}
/**
* <p>
* Task object encapsulating task information.
* </p>
*
* @param task
* Task object encapsulating task information.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public MigrationTask withTask(Task task) {
setTask(task);
return this;
}
/**
* <p>
* The timestamp when the task was gathered.
* </p>
*
* @param updateDateTime
* The timestamp when the task was gathered.
*/
public void setUpdateDateTime(java.util.Date updateDateTime) {
this.updateDateTime = updateDateTime;
}
/**
* <p>
* The timestamp when the task was gathered.
* </p>
*
* @return The timestamp when the task was gathered.
*/
public java.util.Date getUpdateDateTime() {
return this.updateDateTime;
}
/**
* <p>
* The timestamp when the task was gathered.
* </p>
*
* @param updateDateTime
* The timestamp when the task was gathered.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public MigrationTask withUpdateDateTime(java.util.Date updateDateTime) {
setUpdateDateTime(updateDateTime);
return this;
}
/**
* <p/>
*
* @return
*/
public java.util.List<ResourceAttribute> getResourceAttributeList() {
return resourceAttributeList;
}
/**
* <p/>
*
* @param resourceAttributeList
*/
public void setResourceAttributeList(java.util.Collection<ResourceAttribute> resourceAttributeList) {
if (resourceAttributeList == null) {
this.resourceAttributeList = null;
return;
}
this.resourceAttributeList = new java.util.ArrayList<ResourceAttribute>(resourceAttributeList);
}
/**
* <p/>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setResourceAttributeList(java.util.Collection)} or
* {@link #withResourceAttributeList(java.util.Collection)} if you want to override the existing values.
* </p>
*
* @param resourceAttributeList
* @return Returns a reference to this object so that method calls can be chained together.
*/
public MigrationTask withResourceAttributeList(ResourceAttribute... resourceAttributeList) {
if (this.resourceAttributeList == null) {
setResourceAttributeList(new java.util.ArrayList<ResourceAttribute>(resourceAttributeList.length));
}
for (ResourceAttribute ele : resourceAttributeList) {
this.resourceAttributeList.add(ele);
}
return this;
}
/**
* <p/>
*
* @param resourceAttributeList
* @return Returns a reference to this object so that method calls can be chained together.
*/
public MigrationTask withResourceAttributeList(java.util.Collection<ResourceAttribute> resourceAttributeList) {
setResourceAttributeList(resourceAttributeList);
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 (getProgressUpdateStream() != null)
sb.append("ProgressUpdateStream: ").append(getProgressUpdateStream()).append(",");
if (getMigrationTaskName() != null)
sb.append("MigrationTaskName: ").append(getMigrationTaskName()).append(",");
if (getTask() != null)
sb.append("Task: ").append(getTask()).append(",");
if (getUpdateDateTime() != null)
sb.append("UpdateDateTime: ").append(getUpdateDateTime()).append(",");
if (getResourceAttributeList() != null)
sb.append("ResourceAttributeList: ").append(getResourceAttributeList());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof MigrationTask == false)
return false;
MigrationTask other = (MigrationTask) obj;
if (other.getProgressUpdateStream() == null ^ this.getProgressUpdateStream() == null)
return false;
if (other.getProgressUpdateStream() != null && other.getProgressUpdateStream().equals(this.getProgressUpdateStream()) == false)
return false;
if (other.getMigrationTaskName() == null ^ this.getMigrationTaskName() == null)
return false;
if (other.getMigrationTaskName() != null && other.getMigrationTaskName().equals(this.getMigrationTaskName()) == false)
return false;
if (other.getTask() == null ^ this.getTask() == null)
return false;
if (other.getTask() != null && other.getTask().equals(this.getTask()) == false)
return false;
if (other.getUpdateDateTime() == null ^ this.getUpdateDateTime() == null)
return false;
if (other.getUpdateDateTime() != null && other.getUpdateDateTime().equals(this.getUpdateDateTime()) == false)
return false;
if (other.getResourceAttributeList() == null ^ this.getResourceAttributeList() == null)
return false;
if (other.getResourceAttributeList() != null && other.getResourceAttributeList().equals(this.getResourceAttributeList()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getProgressUpdateStream() == null) ? 0 : getProgressUpdateStream().hashCode());
hashCode = prime * hashCode + ((getMigrationTaskName() == null) ? 0 : getMigrationTaskName().hashCode());
hashCode = prime * hashCode + ((getTask() == null) ? 0 : getTask().hashCode());
hashCode = prime * hashCode + ((getUpdateDateTime() == null) ? 0 : getUpdateDateTime().hashCode());
hashCode = prime * hashCode + ((getResourceAttributeList() == null) ? 0 : getResourceAttributeList().hashCode());
return hashCode;
}
@Override
public MigrationTask clone() {
try {
return (MigrationTask) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.migrationhub.model.transform.MigrationTaskMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: POGOProtos.Rpc.proto
package POGOProtos.Rpc;
public interface GetRaidDetailsDataProtoOrBuilder extends
// @@protoc_insertion_point(interface_extends:POGOProtos.Rpc.GetRaidDetailsDataProto)
com.google.protobuf.MessageOrBuilder {
}
|
package io.verticle.oss.fireboard.client;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Status implements Serializable
{
final static long serialVersionUID = -4635841524734745733L;
/**
* event name/short summary
*
*/
private String event;
/**
* timestamp
*
*/
private String created;
/**
* the unique identity of the status event
*
*/
private String uuid;
/**
* qualifier is a dot separated alphanumeric path of any length
*
*/
private String ident;
/**
* success, warn, error
*
*/
private String status;
/**
* 0 - 6
*
*/
private String severity;
/**
* a grouping topic
*
*/
private String category;
/**
* a detailed message of the event
*
*/
private String message;
/**
* a URL to details
*
*/
private String link;
/**
* optional message properties grouped into sections
*
*/
private List<MessagePropertySection> messagePropertySection = new ArrayList<MessagePropertySection>();
/**
* Creates a new Status.
*
*/
public Status() {
super();
}
/**
* Creates a new Status.
* @param event event
* @param created timestamp
* @param uuid uuid
* @param ident identifier
* @param status status
* @param severity severity level
* @param category grouping category
* @param message detail message
* @param link back link
* @param messagePropertySection additional properties
*/
public Status(String event, String created, String uuid, String ident, String status, String severity, String category, String message, String link, List<MessagePropertySection> messagePropertySection) {
super();
this.event = event;
this.created = created;
this.uuid = uuid;
this.ident = ident;
this.status = status;
this.severity = severity;
this.category = category;
this.message = message;
this.link = link;
this.messagePropertySection = messagePropertySection;
}
/**
* Returns the event.
*
* @return
* event
*/
public String getEvent() {
return event;
}
/**
* Set the event.
*
* @param event
* the new event
*/
public void setEvent(String event) {
this.event = event;
}
/**
* Returns the created.
*
* @return
* created
*/
public String getCreated() {
return created;
}
/**
* Set the created.
*
* @param created
* the new created
*/
public void setCreated(String created) {
this.created = created;
}
/**
* Returns the uuid.
*
* @return
* uuid
*/
public String getUuid() {
return uuid;
}
/**
* Set the uuid.
*
* @param uuid
* the new uuid
*/
public void setUuid(String uuid) {
this.uuid = uuid;
}
/**
* Returns the ident.
*
* @return
* ident
*/
public String getIdent() {
return ident;
}
/**
* Set the ident.
*
* @param ident
* the new ident
*/
public void setIdent(String ident) {
this.ident = ident;
}
/**
* Returns the status.
*
* @return
* status
*/
public String getStatus() {
return status;
}
/**
* Set the status.
*
* @param status
* the new status
*/
public void setStatus(String status) {
this.status = status;
}
/**
* Returns the severity.
*
* @return
* severity
*/
public String getSeverity() {
return severity;
}
/**
* Set the severity.
*
* @param severity
* the new severity
*/
public void setSeverity(String severity) {
this.severity = severity;
}
/**
* Returns the category.
*
* @return
* category
*/
public String getCategory() {
return category;
}
/**
* Set the category.
*
* @param category
* the new category
*/
public void setCategory(String category) {
this.category = category;
}
/**
* Returns the message.
*
* @return
* message
*/
public String getMessage() {
return message;
}
/**
* Set the message.
*
* @param message
* the new message
*/
public void setMessage(String message) {
this.message = message;
}
/**
* Returns the link.
*
* @return
* link
*/
public String getLink() {
return link;
}
/**
* Set the link.
*
* @param link
* the new link
*/
public void setLink(String link) {
this.link = link;
}
/**
* Returns the messagePropertySection.
*
* @return
* messagePropertySection
*/
public List<MessagePropertySection> getMessagePropertySection() {
return messagePropertySection;
}
/**
* Set the messagePropertySection.
*
* @param messagePropertySection
* the new messagePropertySection
*/
public void setMessagePropertySection(List<MessagePropertySection> messagePropertySection) {
this.messagePropertySection = messagePropertySection;
}
}
|
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.analysis.starlark;
import static com.google.devtools.build.lib.analysis.config.transitions.ConfigurationTransition.PATCH_TRANSITION_KEY;
import static com.google.devtools.build.lib.packages.RuleClass.Builder.STARLARK_BUILD_SETTING_DEFAULT_ATTR_NAME;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Ordering;
import com.google.common.hash.Hashing;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.ArtifactRoot;
import com.google.devtools.build.lib.analysis.ActionsProvider;
import com.google.devtools.build.lib.analysis.AliasProvider;
import com.google.devtools.build.lib.analysis.BashCommandConstructor;
import com.google.devtools.build.lib.analysis.CommandHelper;
import com.google.devtools.build.lib.analysis.ConfigurationMakeVariableContext;
import com.google.devtools.build.lib.analysis.DefaultInfo;
import com.google.devtools.build.lib.analysis.FileProvider;
import com.google.devtools.build.lib.analysis.FilesToRunProvider;
import com.google.devtools.build.lib.analysis.LocationExpander;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.Runfiles;
import com.google.devtools.build.lib.analysis.RunfilesProvider;
import com.google.devtools.build.lib.analysis.ShToolchain;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration;
import com.google.devtools.build.lib.analysis.config.CoreOptions;
import com.google.devtools.build.lib.analysis.config.FragmentCollection;
import com.google.devtools.build.lib.analysis.config.HostTransition;
import com.google.devtools.build.lib.analysis.config.transitions.NoTransition;
import com.google.devtools.build.lib.analysis.platform.ConstraintValueInfo;
import com.google.devtools.build.lib.analysis.stringtemplate.ExpansionException;
import com.google.devtools.build.lib.analysis.test.InstrumentedFilesCollector;
import com.google.devtools.build.lib.analysis.test.InstrumentedFilesInfo;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.collect.nestedset.Depset;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.Order;
import com.google.devtools.build.lib.packages.Aspect;
import com.google.devtools.build.lib.packages.AspectDescriptor;
import com.google.devtools.build.lib.packages.Attribute;
import com.google.devtools.build.lib.packages.Attribute.ComputedDefault;
import com.google.devtools.build.lib.packages.BuildSetting;
import com.google.devtools.build.lib.packages.BuildType;
import com.google.devtools.build.lib.packages.ImplicitOutputsFunction;
import com.google.devtools.build.lib.packages.OutputFile;
import com.google.devtools.build.lib.packages.Package;
import com.google.devtools.build.lib.packages.Provider;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.packages.RuleClass.ConfiguredTargetFactory.RuleErrorException;
import com.google.devtools.build.lib.packages.StructImpl;
import com.google.devtools.build.lib.packages.StructProvider;
import com.google.devtools.build.lib.packages.Type;
import com.google.devtools.build.lib.packages.Type.LabelClass;
import com.google.devtools.build.lib.packages.semantics.BuildLanguageOptions;
import com.google.devtools.build.lib.shell.ShellUtils;
import com.google.devtools.build.lib.shell.ShellUtils.TokenizationException;
import com.google.devtools.build.lib.starlarkbuildapi.StarlarkRuleContextApi;
import com.google.devtools.build.lib.starlarkbuildapi.platform.ToolchainContextApi;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import net.starlark.java.eval.Dict;
import net.starlark.java.eval.EvalException;
import net.starlark.java.eval.Printer;
import net.starlark.java.eval.Sequence;
import net.starlark.java.eval.Starlark;
import net.starlark.java.eval.StarlarkList;
import net.starlark.java.eval.StarlarkSemantics;
import net.starlark.java.eval.StarlarkThread;
import net.starlark.java.eval.StarlarkValue;
import net.starlark.java.eval.Structure;
import net.starlark.java.eval.Tuple;
/**
* A Starlark API for the ruleContext.
*
* <p>"This object becomes featureless once the rule implementation function that it was created for
* has completed. To achieve this, the {@link #nullify()} should be called once the evaluation of
* the function is completed. The method both frees memory by deleting all significant fields of the
* object and makes it impossible to accidentally use this object where it's not supposed to be used
* (such attempts will result in {@link EvalException}s).
*/
public final class StarlarkRuleContext implements StarlarkRuleContextApi<ConstraintValueInfo> {
public static final String EXECUTABLE_OUTPUT_NAME = "executable";
// This field is a copy of the info from ruleContext, stored separately so it can be accessed
// after this object has been nullified.
private final String ruleLabelCanonicalName;
private final boolean isForAspect;
private final StarlarkActionFactory actionFactory;
// The fields below are intended to be final except that they can be cleared by calling
// `nullify()` when the object becomes featureless (analogous to freezing).
private RuleContext ruleContext;
private FragmentCollection fragments;
private FragmentCollection hostFragments;
@Nullable private AspectDescriptor aspectDescriptor;
/**
* This variable is used to expose the state of {@link
* RuleContext#configurationMakeVariableContext} to the user via {@code ctx.var}.
*
* <p>Computing this field causes a side-effect of initializing the Make var context with an empty
* list of additional MakeVariableSuppliers. Historically, this was fine for Starlark-defined
* rules, but became a problem when we started giving StarlarkRuleContexts to native rules (to
* sandwich them with {@code @_builtins}, for Starlarkification). The native rules would then
* compete with this default initialization for control over the Make var context.
*
* <p>To work around this, we now compute and cache the Dict of all Make vars lazily at the first
* call to {@code ctx.var}. If a native rule provides custom MakeVariableSuppliers (via {@link
* RuleContext#initConfigurationMakeVariableContext}) and also passes {@code ctx} to a
* Starlark-defined function that accesses {@code ctx.var}, then the call to {@code
* initConfigurationMakeVariableContext} must come first or else that call will throw a
* precondition exception.
*
* <p>Note that StarlarkRuleContext can (for pathological user-written rules) survive the analysis
* phase and be accessed concurrently. Nonetheless, it is still safe to initialize {@code ctx.var}
* lazily without synchronization, because {@code ctx.var} is inaccessible once {@code nullify()}
* has been called.
*/
private Dict<String, String> cachedMakeVariables = null;
private StarlarkAttributesCollection attributesCollection;
private StarlarkAttributesCollection ruleAttributesCollection;
private StructImpl splitAttributes;
private Outputs outputsObject;
/**
* Creates a new StarlarkRuleContext wrapping ruleContext.
*
* <p>{@code aspectDescriptor} is the aspect for which the context is created, or <code>
* null</code> if it is for a rule.
*/
public StarlarkRuleContext(RuleContext ruleContext, @Nullable AspectDescriptor aspectDescriptor)
throws RuleErrorException {
// Init ruleContext first, we need it to obtain the StarlarkSemantics used by
// StarlarkActionFactory (and possibly others).
this.ruleContext = Preconditions.checkNotNull(ruleContext);
this.actionFactory = new StarlarkActionFactory(this);
this.ruleLabelCanonicalName = ruleContext.getLabel().getCanonicalForm();
this.fragments = new FragmentCollection(ruleContext, NoTransition.INSTANCE);
this.hostFragments = new FragmentCollection(ruleContext, HostTransition.INSTANCE);
this.aspectDescriptor = aspectDescriptor;
this.isForAspect = aspectDescriptor != null;
Rule rule = ruleContext.getRule();
if (aspectDescriptor == null) {
Collection<Attribute> attributes =
rule.getAttributes().stream()
.filter(attribute -> !attribute.getName().equals("aspect_hints"))
.collect(Collectors.toList());
// Populate ctx.outputs.
Outputs outputs = new Outputs(this);
// These getters do some computational work to return a view, so ensure we only do it once.
ImmutableListMultimap<String, OutputFile> explicitOutMap = rule.getExplicitOutputFileMap();
ImmutableMap<String, OutputFile> implicitOutMap = rule.getStarlarkImplicitOutputFileMap();
// Add the explicit outputs -- values of attributes of type OUTPUT or OUTPUT_LIST.
// We must iterate over the attribute definitions, and not just the entries in the
// explicitOutMap, because the latter omits empty output attributes, which must still
// generate None or [] fields in the struct.
for (Attribute a : attributes) {
// Skip non-output attrs.
String attrName = a.getName();
Type<?> type = a.getType();
if (type.getLabelClass() != LabelClass.OUTPUT) {
continue;
}
// Grab all associated outputs.
ImmutableList.Builder<Artifact> artifactsBuilder = ImmutableList.builder();
for (OutputFile outputFile : explicitOutMap.get(attrName)) {
artifactsBuilder.add(ruleContext.createOutputArtifact(outputFile));
}
StarlarkList<Artifact> artifacts = StarlarkList.immutableCopyOf(artifactsBuilder.build());
// For singular output attributes, unwrap sole element or else use None for arity mismatch.
if (type == BuildType.OUTPUT) {
if (artifacts.size() == 1) {
outputs.addOutput(attrName, Iterables.getOnlyElement(artifacts));
} else {
outputs.addOutput(attrName, Starlark.NONE);
}
} else if (type == BuildType.OUTPUT_LIST) {
outputs.addOutput(attrName, artifacts);
} else {
throw new AssertionError(
String.format("Attribute %s has unexpected output type %s", attrName, type));
}
}
// Add the implicit outputs. In the case where the rule has a native-defined implicit outputs
// function, nothing is added. Note that Rule ensures that Starlark-defined implicit output
// keys don't conflict with output attribute names.
// TODO(bazel-team): Also see about requiring the key to be a valid Starlark identifier.
for (Map.Entry<String, OutputFile> e : implicitOutMap.entrySet()) {
outputs.addOutput(e.getKey(), ruleContext.createOutputArtifact(e.getValue()));
}
this.outputsObject = outputs;
// Populate ctx.attr.
StarlarkAttributesCollection.Builder builder = StarlarkAttributesCollection.builder(this);
for (Attribute attribute : attributes) {
Object value = ruleContext.attributes().get(attribute.getName(), attribute.getType());
builder.addAttribute(attribute, value);
}
this.attributesCollection = builder.build();
this.splitAttributes = buildSplitAttributeInfo(attributes, ruleContext);
this.ruleAttributesCollection = null;
} else { // ASPECT
this.outputsObject = null;
ImmutableCollection<Attribute> attributes =
ruleContext.getMainAspect().getDefinition().getAttributes().values();
StarlarkAttributesCollection.Builder aspectBuilder =
StarlarkAttributesCollection.builder(this);
for (Attribute attribute : attributes) {
Object defaultValue = attribute.getDefaultValue(rule);
if (defaultValue instanceof ComputedDefault) {
defaultValue = ((ComputedDefault) defaultValue).getDefault(ruleContext.attributes());
}
aspectBuilder.addAttribute(attribute, defaultValue);
}
this.attributesCollection = aspectBuilder.build();
this.splitAttributes = null;
StarlarkAttributesCollection.Builder ruleBuilder = StarlarkAttributesCollection.builder(this);
for (Attribute attribute : rule.getAttributes()) {
// The aspect_hints attribute is experimental. When not enabled through the
// --enable_aspect_hints flag, we don't add it to the list of attributes that the aspect
// has access to.
if (attribute.getName().equals("aspect_hints")
&& !ruleContext
.getConfiguration()
.getOptions()
.get(CoreOptions.class)
.enableAspectHints) {
continue;
}
Object value = ruleContext.attributes().get(attribute.getName(), attribute.getType());
ruleBuilder.addAttribute(attribute, value);
}
for (Aspect aspect : ruleContext.getAspects()) {
if (aspect.equals(ruleContext.getMainAspect())) {
// Aspect's own attributes are in <code>attributesCollection</code>.
continue;
}
for (Attribute attribute : aspect.getDefinition().getAttributes().values()) {
Object defaultValue = attribute.getDefaultValue(rule);
if (defaultValue instanceof ComputedDefault) {
defaultValue = ((ComputedDefault) defaultValue).getDefault(ruleContext.attributes());
}
ruleBuilder.addAttribute(attribute, defaultValue);
}
}
this.ruleAttributesCollection = ruleBuilder.build();
}
}
/**
* Represents `ctx.outputs`.
*
* <p>The value of its {@code ctx.outputs.executable} field is computed on-demand.
*
* <p>Note: There is only one {@code Outputs} object per rule context, so default (object
* identity) equals and hashCode suffice.
*/
// TODO(adonovan): add StarlarkBuiltin(name="ctx.outputs") annotation.
private static class Outputs implements Structure, StarlarkValue {
private final Map<String, Object> outputs;
private final StarlarkRuleContext context;
private boolean executableCreated = false;
Outputs(StarlarkRuleContext context) {
this.outputs = new LinkedHashMap<>();
this.context = context;
}
private void addOutput(String key, Object value) throws RuleErrorException {
Preconditions.checkState(!context.isImmutable());
// TODO(bazel-team): We should reject outputs whose key is not an identifier. Today this is
// allowed, and the resulting ctx.outputs value can be retrieved using getattr().
if (outputs.containsKey(key)
|| (context.isExecutable() && EXECUTABLE_OUTPUT_NAME.equals(key))) {
context.getRuleContext().throwWithRuleError("Multiple outputs with the same key: " + key);
}
outputs.put(key, value);
}
@Override
public boolean isImmutable() {
return context.isImmutable();
}
@Override
public ImmutableCollection<String> getFieldNames() {
// TODO(b/175954936): There's an NPE here when accessing dir(ctx.outputs) after rule
// analysis has completed. Since we can't throw EvalException here, this may require that we
// preemptively copy the fields into this object, or at least keep a "nullified" bit so we
// know to produce an empty result here.
ImmutableList.Builder<String> result = ImmutableList.builder();
if (context.isExecutable() && executableCreated) {
result.add(EXECUTABLE_OUTPUT_NAME);
}
result.addAll(outputs.keySet());
return result.build();
}
@Nullable
@Override
public Object getValue(String name) throws EvalException {
checkMutable();
if (context.isExecutable() && EXECUTABLE_OUTPUT_NAME.equals(name)) {
executableCreated = true;
// createOutputArtifact() will cache the created artifact.
return context.getRuleContext().createOutputArtifact();
}
return outputs.get(name);
}
@Nullable
@Override
public String getErrorMessageForUnknownField(String name) {
return String.format(
"No attribute '%s' in outputs. Make sure you declared a rule output with this name.",
name);
}
@Override
public void repr(Printer printer) {
if (isImmutable()) {
printer.append("ctx.outputs(for ");
printer.append(context.ruleLabelCanonicalName);
printer.append(")");
return;
}
boolean first = true;
printer.append("ctx.outputs(");
// Sort by field name to ensure deterministic output.
try {
for (String field : Ordering.natural().sortedCopy(getFieldNames())) {
if (!first) {
printer.append(", ");
}
first = false;
printer.append(field);
printer.append(" = ");
printer.repr(getValue(field));
}
printer.append(")");
} catch (EvalException e) {
throw new AssertionError("mutable ctx.outputs should not throw", e);
}
}
private void checkMutable() throws EvalException {
if (isImmutable()) {
throw Starlark.errorf(
"cannot access outputs of rule '%s' outside of its own rule implementation function",
context.ruleLabelCanonicalName);
}
}
}
public boolean isExecutable() {
return ruleContext.getRule().getRuleClassObject().isExecutableStarlark();
}
public boolean isDefaultExecutableCreated() {
return this.outputsObject.executableCreated;
}
/**
* Nullifies fields of the object when it's not supposed to be used anymore to free unused memory
* and to make sure this object is not accessed when it's not supposed to (after the corresponding
* rule implementation function has exited).
*/
public void nullify() {
ruleContext = null;
fragments = null;
hostFragments = null;
aspectDescriptor = null;
cachedMakeVariables = null;
attributesCollection = null;
ruleAttributesCollection = null;
splitAttributes = null;
outputsObject = null;
}
/** Throws an EvalException mentioning {@code attrName} if we've already been nullified. */
public void checkMutable(String attrName) throws EvalException {
if (isImmutable()) {
throw Starlark.errorf(
"cannot access field or method '%s' of rule context for '%s' outside of its own rule "
+ "implementation function",
attrName, ruleLabelCanonicalName);
}
}
@Nullable
public AspectDescriptor getAspectDescriptor() {
return aspectDescriptor;
}
public String getRuleLabelCanonicalName() {
return ruleLabelCanonicalName;
}
private static StructImpl buildSplitAttributeInfo(
Collection<Attribute> attributes, RuleContext ruleContext) {
ImmutableMap.Builder<String, Object> splitAttrInfos = ImmutableMap.builder();
for (Attribute attr : attributes) {
if (!attr.getTransitionFactory().isSplit()) {
continue;
}
Map<Optional<String>, ? extends List<? extends TransitiveInfoCollection>> splitPrereqs =
ruleContext.getSplitPrerequisites(attr.getName());
Map<Object, Object> splitPrereqsMap = new LinkedHashMap<>();
for (Map.Entry<Optional<String>, ? extends List<? extends TransitiveInfoCollection>>
splitPrereq : splitPrereqs.entrySet()) {
// Skip a split with an empty dependency list.
// TODO(jungjw): Figure out exactly which cases trigger this and see if this can be made
// more error-proof.
if (splitPrereq.getValue().isEmpty()) {
continue;
}
Object value;
if (attr.getType() == BuildType.LABEL) {
Preconditions.checkState(splitPrereq.getValue().size() == 1);
value = splitPrereq.getValue().get(0);
} else {
// BuildType.LABEL_LIST
value = StarlarkList.immutableCopyOf(splitPrereq.getValue());
}
if (splitPrereq.getKey().isPresent()
&& !splitPrereq.getKey().get().equals(PATCH_TRANSITION_KEY)) {
splitPrereqsMap.put(splitPrereq.getKey().get(), value);
} else {
// If the split transition is not in effect, then the key will be missing since there's
// nothing to key on because the dependencies aren't split and getSplitPrerequisites()
// behaves like getPrerequisites(). This also means there should be only one entry in
// the map. Use None in Starlark to represent this.
Preconditions.checkState(splitPrereqs.size() == 1);
splitPrereqsMap.put(Starlark.NONE, value);
}
}
splitAttrInfos.put(attr.getPublicName(), Dict.immutableCopyOf(splitPrereqsMap));
}
return StructProvider.STRUCT.create(
splitAttrInfos.build(),
"No attribute '%s' in split_attr."
+ "This attribute is not defined with a split configuration.");
}
@Override
public boolean isImmutable() {
return ruleContext == null;
}
@Override
public void repr(Printer printer) {
if (isForAspect) {
printer.append("<aspect context for " + ruleLabelCanonicalName + ">");
} else {
printer.append("<rule context for " + ruleLabelCanonicalName + ">");
}
}
/** Returns the wrapped ruleContext. */
public RuleContext getRuleContext() {
return ruleContext;
}
@Override
public Provider getDefaultProvider() {
return DefaultInfo.PROVIDER;
}
@Override
public StarlarkActionFactory actions() {
return actionFactory;
}
@Override
public StarlarkValue createdActions() throws EvalException {
checkMutable("created_actions");
if (ruleContext.getRule().getRuleClassObject().isStarlarkTestable()) {
return ActionsProvider.create(ruleContext.getAnalysisEnvironment().getRegisteredActions());
} else {
return Starlark.NONE;
}
}
@Override
public StructImpl getAttr() throws EvalException {
checkMutable("attr");
return attributesCollection.getAttr();
}
@Override
public StructImpl getSplitAttr() throws EvalException {
checkMutable("split_attr");
if (splitAttributes == null) {
throw new EvalException("'split_attr' is available only in rule implementations");
}
return splitAttributes;
}
/** See {@link RuleContext#getExecutablePrerequisite(String)}. */
@Override
public StructImpl getExecutable() throws EvalException {
checkMutable("executable");
return attributesCollection.getExecutable();
}
/** See {@link RuleContext#getPrerequisiteArtifact(String)}. */
@Override
public StructImpl getFile() throws EvalException {
checkMutable("file");
return attributesCollection.getFile();
}
/** See {@link RuleContext#getPrerequisiteArtifacts(String)}. */
@Override
public StructImpl getFiles() throws EvalException {
checkMutable("files");
return attributesCollection.getFiles();
}
@Override
public String getWorkspaceName() throws EvalException {
checkMutable("workspace_name");
return ruleContext.getWorkspaceName();
}
@Override
public Label getLabel() throws EvalException {
checkMutable("label");
return ruleContext.getLabel();
}
@Override
public FragmentCollection getFragments() throws EvalException {
checkMutable("fragments");
return fragments;
}
@Override
public FragmentCollection getHostFragments() throws EvalException {
checkMutable("host_fragments");
return hostFragments;
}
@Override
public BuildConfiguration getConfiguration() throws EvalException {
checkMutable("configuration");
return ruleContext.getConfiguration();
}
@Override
public BuildConfiguration getHostConfiguration() throws EvalException {
checkMutable("host_configuration");
return ruleContext.getHostConfiguration();
}
@Override
@Nullable
public Object getBuildSettingValue() throws EvalException {
if (ruleContext.getRule().getRuleClassObject().getBuildSetting() == null) {
throw Starlark.errorf(
"attempting to access 'build_setting_value' of non-build setting %s",
ruleLabelCanonicalName);
}
ImmutableMap<Label, Object> starlarkFlagSettings =
ruleContext.getConfiguration().getOptions().getStarlarkOptions();
BuildSetting buildSetting = ruleContext.getRule().getRuleClassObject().getBuildSetting();
if (starlarkFlagSettings.containsKey(ruleContext.getLabel())) {
return starlarkFlagSettings.get(ruleContext.getLabel());
} else {
Object defaultValue =
ruleContext
.attributes()
.get(STARLARK_BUILD_SETTING_DEFAULT_ATTR_NAME, buildSetting.getType());
return buildSetting.allowsMultiple() ? ImmutableList.of(defaultValue) : defaultValue;
}
}
@Override
public boolean instrumentCoverage(Object targetUnchecked) throws EvalException {
checkMutable("coverage_instrumented");
BuildConfiguration config = ruleContext.getConfiguration();
if (!config.isCodeCoverageEnabled()) {
return false;
}
if (targetUnchecked == Starlark.NONE) {
return InstrumentedFilesCollector.shouldIncludeLocalSources(
ruleContext.getConfiguration(), ruleContext.getLabel(), ruleContext.isTestTarget());
}
TransitiveInfoCollection target = (TransitiveInfoCollection) targetUnchecked;
return (target.get(InstrumentedFilesInfo.STARLARK_CONSTRUCTOR) != null)
&& InstrumentedFilesCollector.shouldIncludeLocalSources(config, target);
}
@Override
public ImmutableList<String> getFeatures() throws EvalException {
checkMutable("features");
return ImmutableList.copyOf(ruleContext.getFeatures());
}
@Override
public ImmutableList<String> getDisabledFeatures() throws EvalException {
checkMutable("disabled_features");
return ImmutableList.copyOf(ruleContext.getDisabledFeatures());
}
@Override
public ArtifactRoot getBinDirectory() throws EvalException {
checkMutable("bin_dir");
return getConfiguration().getBinDirectory(ruleContext.getRule().getRepository());
}
@Override
public ArtifactRoot getGenfilesDirectory() throws EvalException {
checkMutable("genfiles_dir");
return getConfiguration().getGenfilesDirectory(ruleContext.getRule().getRepository());
}
@Override
public Structure outputs() throws EvalException {
checkMutable("outputs");
if (outputsObject == null) {
throw new EvalException("'outputs' is not defined");
}
return outputsObject;
}
@Override
public StarlarkAttributesCollection rule() throws EvalException {
checkMutable("rule");
if (!isForAspect) {
throw new EvalException("'rule' is only available in aspect implementations");
}
return ruleAttributesCollection;
}
@Override
public ImmutableList<String> aspectIds() throws EvalException {
checkMutable("aspect_ids");
if (!isForAspect) {
throw new EvalException("'aspect_ids' is only available in aspect implementations");
}
ImmutableList.Builder<String> result = ImmutableList.builder();
for (AspectDescriptor descriptor : ruleContext.getAspectDescriptors()) {
result.add(descriptor.getDescription());
}
return result.build();
}
@Override
public Dict<String, String> var() throws EvalException {
checkMutable("var");
if (cachedMakeVariables == null) {
try {
cachedMakeVariables =
ruleContext.getConfigurationMakeVariableContext().collectMakeVariables();
} catch (ExpansionException e) {
throw Starlark.errorf("%s", e.getMessage());
}
}
return cachedMakeVariables;
}
@Override
public ToolchainContextApi toolchains() throws EvalException {
checkMutable("toolchains");
return StarlarkToolchainContext.create(ruleContext.getToolchainContext());
}
@Override
public boolean targetPlatformHasConstraint(ConstraintValueInfo constraintValue) {
return ruleContext.targetPlatformHasConstraint(constraintValue);
}
@Override
public StarlarkExecGroupCollection execGroups() {
// Create a thin wrapper around the toolchain collection, to expose the Starlark API.
return StarlarkExecGroupCollection.create(ruleContext.getToolchainContexts());
}
@Override
public String toString() {
return ruleLabelCanonicalName;
}
@Override
public Sequence<String> tokenize(String optionString) throws EvalException {
checkMutable("tokenize");
List<String> options = new ArrayList<>();
try {
ShellUtils.tokenize(options, optionString);
} catch (TokenizationException e) {
throw Starlark.errorf("%s while tokenizing '%s'", e.getMessage(), optionString);
}
return StarlarkList.immutableCopyOf(options);
}
boolean isForAspect() {
return isForAspect;
}
@Override
public Artifact newFile(Object var1, Object var2, Object fileSuffix) throws EvalException {
checkMutable("new_file");
checkDeprecated("ctx.actions.declare_file", "ctx.new_file", getStarlarkSemantics());
// Determine which of new_file's four signatures is being used. Yes, this is terrible.
// It's one major reason that this method is deprecated.
if (fileSuffix != Starlark.UNBOUND) {
// new_file(file_root, sibling_file, suffix)
ArtifactRoot root =
assertTypeForNewFile(
var1, ArtifactRoot.class, "expected first param to be of type 'root'");
Artifact siblingFile =
assertTypeForNewFile(var2, Artifact.class, "expected second param to be of type 'File'");
PathFragment original =
siblingFile.getOutputDirRelativePath(getConfiguration().isSiblingRepositoryLayout());
PathFragment fragment = original.replaceName(original.getBaseName() + fileSuffix);
return ruleContext.getDerivedArtifact(fragment, root);
} else if (var2 == Starlark.UNBOUND) {
// new_file(filename)
String filename =
assertTypeForNewFile(var1, String.class, "expected first param to be of type 'string'");
return actionFactory.declareFile(filename, Starlark.NONE);
} else {
String filename =
assertTypeForNewFile(var2, String.class, "expected second param to be of type 'string'");
if (var1 instanceof ArtifactRoot) {
// new_file(root, filename)
ArtifactRoot root = (ArtifactRoot) var1;
return ruleContext.getPackageRelativeArtifact(filename, root);
} else {
// new_file(sibling_file, filename)
Artifact siblingFile =
assertTypeForNewFile(
var1, Artifact.class, "expected first param to be of type 'File' or 'root'");
return actionFactory.declareFile(filename, siblingFile);
}
}
}
private static <T> T assertTypeForNewFile(Object obj, Class<T> type, String errorMessage)
throws EvalException {
if (type.isInstance(obj)) {
return type.cast(obj);
} else {
throw new EvalException(errorMessage);
}
}
@Override
public boolean checkPlaceholders(String template, Sequence<?> allowedPlaceholders) // <String>
throws EvalException {
checkMutable("check_placeholders");
List<String> actualPlaceHolders = new LinkedList<>();
Set<String> allowedPlaceholderSet =
ImmutableSet.copyOf(
Sequence.cast(allowedPlaceholders, String.class, "allowed_placeholders"));
ImplicitOutputsFunction.createPlaceholderSubstitutionFormatString(template, actualPlaceHolders);
for (String placeholder : actualPlaceHolders) {
if (!allowedPlaceholderSet.contains(placeholder)) {
return false;
}
}
return true;
}
@Override
public String expandMakeVariables(
String attributeName, String command, Dict<?, ?> additionalSubstitutions) // <String, String>
throws EvalException {
checkMutable("expand_make_variables");
final Map<String, String> additionalSubstitutionsMap =
Dict.cast(additionalSubstitutions, String.class, String.class, "additional_substitutions");
return expandMakeVariables(attributeName, command, additionalSubstitutionsMap);
}
private String expandMakeVariables(
String attributeName, String command, Map<String, String> additionalSubstitutionsMap) {
ConfigurationMakeVariableContext makeVariableContext =
new ConfigurationMakeVariableContext(
ruleContext,
ruleContext.getRule().getPackage(),
ruleContext.getConfiguration(),
ImmutableList.of()) {
@Override
public String lookupVariable(String variableName) throws ExpansionException {
if (additionalSubstitutionsMap.containsKey(variableName)) {
return additionalSubstitutionsMap.get(variableName);
} else {
return super.lookupVariable(variableName);
}
}
};
return ruleContext.getExpander(makeVariableContext).expand(attributeName, command);
}
FilesToRunProvider getExecutableRunfiles(Artifact executable) {
return attributesCollection.getExecutableRunfilesMap().get(executable);
}
@Override
public Artifact getStableWorkspaceStatus() throws InterruptedException, EvalException {
checkMutable("info_file");
return ruleContext.getAnalysisEnvironment().getStableWorkspaceStatusArtifact();
}
@Override
public Artifact getVolatileWorkspaceStatus() throws InterruptedException, EvalException {
checkMutable("version_file");
return ruleContext.getAnalysisEnvironment().getVolatileWorkspaceStatusArtifact();
}
@Override
public String getBuildFileRelativePath() throws EvalException {
checkMutable("build_file_path");
Package pkg = ruleContext.getRule().getPackage();
return pkg.getSourceRoot().get().relativize(pkg.getBuildFile().getPath()).getPathString();
}
@Override
public String expandLocation(String input, Sequence<?> targets, StarlarkThread thread)
throws EvalException {
checkMutable("expand_location");
try {
return LocationExpander.withExecPaths(
ruleContext,
makeLabelMap(Sequence.cast(targets, TransitiveInfoCollection.class, "targets")))
.expand(input);
} catch (IllegalStateException ise) {
throw new EvalException(ise);
}
}
@Override
public Runfiles runfiles(
Sequence<?> files,
Object transitiveFiles,
Boolean collectData,
Boolean collectDefault,
Dict<?, ?> symlinks,
Dict<?, ?> rootSymlinks)
throws EvalException {
checkMutable("runfiles");
Runfiles.Builder builder =
new Runfiles.Builder(
ruleContext.getWorkspaceName(), getConfiguration().legacyExternalRunfiles());
boolean checkConflicts = false;
if (Starlark.truth(collectData)) {
builder.addRunfiles(ruleContext, RunfilesProvider.DATA_RUNFILES);
}
if (Starlark.truth(collectDefault)) {
builder.addRunfiles(ruleContext, RunfilesProvider.DEFAULT_RUNFILES);
}
if (!files.isEmpty()) {
builder.addArtifacts(Sequence.cast(files, Artifact.class, "files"));
}
if (transitiveFiles != Starlark.NONE) {
NestedSet<Artifact> transitiveArtifacts =
Depset.cast(transitiveFiles, Artifact.class, "transitive_files");
// Runfiles uses compile order. Check that the given transitive_files depset is compatible.
if (!Order.COMPILE_ORDER.isCompatible(transitiveArtifacts.getOrder())) {
throw Starlark.errorf(
"order '%s' is invalid for transitive_files",
transitiveArtifacts.getOrder().getStarlarkName());
}
builder.addTransitiveArtifacts(transitiveArtifacts);
}
if (!symlinks.isEmpty()) {
// If Starlark code directly manipulates symlinks, activate more stringent validity checking.
checkConflicts = true;
for (Map.Entry<String, Artifact> entry :
Dict.cast(symlinks, String.class, Artifact.class, "symlinks").entrySet()) {
builder.addSymlink(PathFragment.create(entry.getKey()), entry.getValue());
}
}
if (!rootSymlinks.isEmpty()) {
checkConflicts = true;
for (Map.Entry<String, Artifact> entry :
Dict.cast(rootSymlinks, String.class, Artifact.class, "root_symlinks").entrySet()) {
builder.addRootSymlink(PathFragment.create(entry.getKey()), entry.getValue());
}
}
Runfiles runfiles = builder.build();
if (checkConflicts) {
runfiles.setConflictPolicy(Runfiles.ConflictPolicy.ERROR);
}
return runfiles;
}
@Override
public Tuple resolveCommand(
String command,
Object attributeUnchecked,
Boolean expandLocations,
Object makeVariablesUnchecked,
Sequence<?> tools,
Dict<?, ?> labelDictUnchecked,
Dict<?, ?> executionRequirementsUnchecked,
StarlarkThread thread)
throws EvalException {
checkMutable("resolve_command");
Label ruleLabel = getLabel();
Map<Label, Iterable<Artifact>> labelDict = checkLabelDict(labelDictUnchecked);
// The best way to fix this probably is to convert CommandHelper to Starlark.
CommandHelper helper =
CommandHelper.builder(ruleContext)
.addToolDependencies(Sequence.cast(tools, TransitiveInfoCollection.class, "tools"))
.addLabelMap(labelDict)
.build();
String attribute = Type.STRING.convertOptional(attributeUnchecked, "attribute", ruleLabel);
if (expandLocations) {
command =
helper.resolveCommandAndExpandLabels(command, attribute, /*allowDataInLabel=*/ false);
}
if (!Starlark.isNullOrNone(makeVariablesUnchecked)) {
Map<String, String> makeVariables =
Type.STRING_DICT.convert(makeVariablesUnchecked, "make_variables", ruleLabel);
command = expandMakeVariables(attribute, command, makeVariables);
}
// TODO(lberki): This flattens a NestedSet.
// However, we can't turn this into a Depset because it's an incompatible change to Starlark.
List<Artifact> inputs = new ArrayList<>(helper.getResolvedTools().toList());
ImmutableMap<String, String> executionRequirements =
ImmutableMap.copyOf(
Dict.noneableCast(
executionRequirementsUnchecked,
String.class,
String.class,
"execution_requirements"));
PathFragment shExecutable = ShToolchain.getPathOrError(ruleContext);
BashCommandConstructor constructor =
CommandHelper.buildBashCommandConstructor(
executionRequirements,
shExecutable,
// Hash the command-line to prevent multiple actions from the same rule invocation
// conflicting with each other.
"." + Hashing.murmur3_32().hashUnencodedChars(command).toString() + SCRIPT_SUFFIX);
List<String> argv = helper.buildCommandLine(command, inputs, constructor);
return Tuple.triple(
StarlarkList.copyOf(thread.mutability(), inputs),
StarlarkList.copyOf(thread.mutability(), argv),
helper.getToolsRunfilesSuppliers());
}
@Override
public Tuple resolveTools(Sequence<?> tools) throws EvalException {
checkMutable("resolve_tools");
CommandHelper helper =
CommandHelper.builder(ruleContext)
.addToolDependencies(Sequence.cast(tools, TransitiveInfoCollection.class, "tools"))
.build();
return Tuple.pair(
Depset.of(Artifact.TYPE, helper.getResolvedTools()), helper.getToolsRunfilesSuppliers());
}
public StarlarkSemantics getStarlarkSemantics() {
return ruleContext.getStarlarkSemantics();
}
/**
* Ensures the given {@link Map} has keys that have {@link Label} type and values that have either
* {@link Iterable} or {@link Depset} type, and raises {@link EvalException} otherwise. Returns a
* corresponding map where any sets are replaced by iterables.
*/
// TODO(bazel-team): find a better way to typecheck this argument.
private static Map<Label, Iterable<Artifact>> checkLabelDict(Map<?, ?> labelDict)
throws EvalException {
Map<Label, Iterable<Artifact>> convertedMap = new HashMap<>();
for (Map.Entry<?, ?> entry : labelDict.entrySet()) {
Object key = entry.getKey();
if (!(key instanceof Label)) {
throw Starlark.errorf("invalid key %s in 'label_dict'", Starlark.repr(key));
}
ImmutableList.Builder<Artifact> files = ImmutableList.builder();
Object val = entry.getValue();
Iterable<?> valIter;
if (val instanceof Iterable) {
valIter = (Iterable<?>) val;
} else {
throw Starlark.errorf(
"invalid value %s in 'label_dict': expected iterable, but got '%s'",
Starlark.repr(val), Starlark.type(val));
}
for (Object file : valIter) {
if (!(file instanceof Artifact)) {
throw Starlark.errorf("invalid value %s in 'label_dict'", Starlark.repr(val));
}
files.add((Artifact) file);
}
convertedMap.put((Label) key, files.build());
}
return convertedMap;
}
/** suffix of script to be used in case the command is too long to fit on a single line */
private static final String SCRIPT_SUFFIX = ".script.sh";
private static void checkDeprecated(String newApi, String oldApi, StarlarkSemantics semantics)
throws EvalException {
if (semantics.getBool(BuildLanguageOptions.INCOMPATIBLE_NEW_ACTIONS_API)) {
throw Starlark.errorf(
"Use %s instead of %s. \n"
+ "Use --incompatible_new_actions_api=false to temporarily disable this check.",
newApi, oldApi);
}
}
/**
* Builds a map: Label -> List of files from the given labels
*
* @param knownLabels List of known labels
* @return Immutable map with immutable collections as values
*/
private static ImmutableMap<Label, ImmutableCollection<Artifact>> makeLabelMap(
Iterable<TransitiveInfoCollection> knownLabels) {
ImmutableMap.Builder<Label, ImmutableCollection<Artifact>> builder = ImmutableMap.builder();
for (TransitiveInfoCollection current : knownLabels) {
builder.put(
AliasProvider.getDependencyLabel(current),
current.getProvider(FileProvider.class).getFilesToBuild().toList());
}
return builder.build();
}
}
|
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.frauddetector.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/frauddetector-2019-11-15/GetModelVersion" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetModelVersionResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* The model ID.
* </p>
*/
private String modelId;
/**
* <p>
* The model type.
* </p>
*/
private String modelType;
/**
* <p>
* The model version.
* </p>
*/
private String modelVersionNumber;
/**
* <p>
* The model version description.
* </p>
*/
private String description;
/**
* <p>
* The model version status.
* </p>
*/
private String status;
/**
* <p>
* The model ID.
* </p>
*
* @param modelId
* The model ID.
*/
public void setModelId(String modelId) {
this.modelId = modelId;
}
/**
* <p>
* The model ID.
* </p>
*
* @return The model ID.
*/
public String getModelId() {
return this.modelId;
}
/**
* <p>
* The model ID.
* </p>
*
* @param modelId
* The model ID.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetModelVersionResult withModelId(String modelId) {
setModelId(modelId);
return this;
}
/**
* <p>
* The model type.
* </p>
*
* @param modelType
* The model type.
* @see ModelTypeEnum
*/
public void setModelType(String modelType) {
this.modelType = modelType;
}
/**
* <p>
* The model type.
* </p>
*
* @return The model type.
* @see ModelTypeEnum
*/
public String getModelType() {
return this.modelType;
}
/**
* <p>
* The model type.
* </p>
*
* @param modelType
* The model type.
* @return Returns a reference to this object so that method calls can be chained together.
* @see ModelTypeEnum
*/
public GetModelVersionResult withModelType(String modelType) {
setModelType(modelType);
return this;
}
/**
* <p>
* The model type.
* </p>
*
* @param modelType
* The model type.
* @return Returns a reference to this object so that method calls can be chained together.
* @see ModelTypeEnum
*/
public GetModelVersionResult withModelType(ModelTypeEnum modelType) {
this.modelType = modelType.toString();
return this;
}
/**
* <p>
* The model version.
* </p>
*
* @param modelVersionNumber
* The model version.
*/
public void setModelVersionNumber(String modelVersionNumber) {
this.modelVersionNumber = modelVersionNumber;
}
/**
* <p>
* The model version.
* </p>
*
* @return The model version.
*/
public String getModelVersionNumber() {
return this.modelVersionNumber;
}
/**
* <p>
* The model version.
* </p>
*
* @param modelVersionNumber
* The model version.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetModelVersionResult withModelVersionNumber(String modelVersionNumber) {
setModelVersionNumber(modelVersionNumber);
return this;
}
/**
* <p>
* The model version description.
* </p>
*
* @param description
* The model version description.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* <p>
* The model version description.
* </p>
*
* @return The model version description.
*/
public String getDescription() {
return this.description;
}
/**
* <p>
* The model version description.
* </p>
*
* @param description
* The model version description.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetModelVersionResult withDescription(String description) {
setDescription(description);
return this;
}
/**
* <p>
* The model version status.
* </p>
*
* @param status
* The model version status.
*/
public void setStatus(String status) {
this.status = status;
}
/**
* <p>
* The model version status.
* </p>
*
* @return The model version status.
*/
public String getStatus() {
return this.status;
}
/**
* <p>
* The model version status.
* </p>
*
* @param status
* The model version status.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetModelVersionResult withStatus(String status) {
setStatus(status);
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 (getModelId() != null)
sb.append("ModelId: ").append(getModelId()).append(",");
if (getModelType() != null)
sb.append("ModelType: ").append(getModelType()).append(",");
if (getModelVersionNumber() != null)
sb.append("ModelVersionNumber: ").append(getModelVersionNumber()).append(",");
if (getDescription() != null)
sb.append("Description: ").append(getDescription()).append(",");
if (getStatus() != null)
sb.append("Status: ").append(getStatus());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof GetModelVersionResult == false)
return false;
GetModelVersionResult other = (GetModelVersionResult) obj;
if (other.getModelId() == null ^ this.getModelId() == null)
return false;
if (other.getModelId() != null && other.getModelId().equals(this.getModelId()) == false)
return false;
if (other.getModelType() == null ^ this.getModelType() == null)
return false;
if (other.getModelType() != null && other.getModelType().equals(this.getModelType()) == false)
return false;
if (other.getModelVersionNumber() == null ^ this.getModelVersionNumber() == null)
return false;
if (other.getModelVersionNumber() != null && other.getModelVersionNumber().equals(this.getModelVersionNumber()) == false)
return false;
if (other.getDescription() == null ^ this.getDescription() == null)
return false;
if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false)
return false;
if (other.getStatus() == null ^ this.getStatus() == null)
return false;
if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getModelId() == null) ? 0 : getModelId().hashCode());
hashCode = prime * hashCode + ((getModelType() == null) ? 0 : getModelType().hashCode());
hashCode = prime * hashCode + ((getModelVersionNumber() == null) ? 0 : getModelVersionNumber().hashCode());
hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode());
hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode());
return hashCode;
}
@Override
public GetModelVersionResult clone() {
try {
return (GetModelVersionResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
|
/*
Copyright 2006-2015 Stefano Chizzolini. http://www.pdfclown.org
Contributors:
* Stefano Chizzolini (original code developer, http://www.stefanochizzolini.it)
This file should be part of the source code distribution of "PDF Clown library"
(the Program): see the accompanying README files for more info.
This Program is free software; you can redistribute it and/or modify it under the terms
of the GNU Lesser General Public License as published by the Free Software Foundation;
either version 3 of the License, or (at your option) any later version.
This Program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY,
either expressed or implied; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the License for more details.
You should have received a copy of the GNU Lesser General Public License along with this
Program (see README files); if not, go to the GNU website (http://www.gnu.org/licenses/).
Redistribution and use, with or without modification, are permitted provided that such
redistributions retain the above copyright notice, license and disclaimer, along with
this list of conditions.
*/
package org.pdfclown.bytes;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;
import org.pdfclown.bytes.filters.Filter;
import org.pdfclown.objects.PdfDictionary;
import org.pdfclown.tokens.Encoding;
import org.pdfclown.util.ConvertUtils;
/**
Byte buffer.
@author Stefano Chizzolini (http://www.stefanochizzolini.it)
@version 0.2.0, 05/22/15
*/
public final class Buffer
implements IBuffer
{
// <class>
// <static>
// <fields>
/**
Default buffer capacity.
*/
private static final int DefaultCapacity = 1 << 8;
// </fields>
// </static>
// <dynamic>
// <fields>
/**
Inner buffer where data are stored.
*/
private byte[] data;
/**
Number of bytes actually used in the buffer.
*/
private int length;
/**
Pointer position within the buffer.
*/
private int position = 0;
private ByteOrder byteOrder = ByteOrder.BIG_ENDIAN;
private boolean dirty;
private List<IListener> listeners;
// </fields>
// <constructors>
public Buffer(
)
{this(0);}
public Buffer(
int capacity
)
{
if(capacity < 1)
{capacity = DefaultCapacity;}
this.data = new byte[capacity];
this.length = 0;
}
public Buffer(
java.io.BufferedReader dataStream
)
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try
{
char[] buffer = new char[8192]; int bufferLength;
while((bufferLength = dataStream.read(buffer, 0, buffer.length)) != -1)
{
for(int i = 0; i < bufferLength; i++)
{outputStream.write((byte)buffer[i]);}
}
}
catch(IOException e)
{throw new RuntimeException(e);}
this.data = outputStream.toByteArray();
this.length = data.length;
}
public Buffer(
InputStream dataStream
)
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try
{
byte[] buffer = new byte[8192]; int bufferLength;
while((bufferLength = dataStream.read(buffer, 0, buffer.length)) != -1)
{outputStream.write(buffer, 0, bufferLength);}
}
catch(IOException e)
{throw new RuntimeException(e);}
this.data = outputStream.toByteArray();
this.length = data.length;
}
public Buffer(
byte[] data
)
{
this.data = data;
this.length = data.length;
}
public Buffer(
byte[] data,
ByteOrder byteOrder
)
{
this.data = data;
this.length = data.length;
this.byteOrder = byteOrder;
}
public Buffer(
String data
)
{
this();
append(data);
}
// </constructors>
// <interface>
// <public>
// <IBuffer>
@Override
public void addListener(
IListener listener
)
{
if(listeners == null)
{listeners = new ArrayList<IBuffer.IListener>();}
listeners.add(listener);
}
@Override
public IBuffer append(
byte data
)
{
ensureCapacity(1);
this.data[this.length++] = data;
notifyChange();
return this;
}
@Override
public IBuffer append(
byte[] data
)
{return append(data, 0, data.length);}
@Override
public IBuffer append(
byte[] data,
int offset,
int length
)
{
ensureCapacity(length);
System.arraycopy(data, offset, this.data, this.length, length);
this.length += length;
notifyChange();
return this;
}
@Override
public IBuffer append(
String data
)
{return append(Encoding.Pdf.encode(data));}
@Override
public IBuffer append(
IInputStream data
)
{return append(data.toByteArray(), 0, (int)data.getLength());}
@Override
public void clear(
)
{setLength(0);}
@Override
public Buffer clone(
)
{
Buffer clone = new Buffer(getCapacity());
clone.append(data, 0, this.length);
return clone;
}
@Override
public void decode(
Filter filter,
PdfDictionary parameters
)
{
data = filter.decode(data, 0, length, parameters);
length = data.length;
}
@Override
public void delete(
int index,
int length
)
{
// Shift left the trailing data block to override the deleted data!
System.arraycopy(this.data, index + length, this.data, index, this.length - (index + length));
this.length -= length;
notifyChange();
}
@Override
public byte[] encode(
Filter filter,
PdfDictionary parameters
)
{return filter.encode(data, 0, length, parameters);}
@Override
public int getByte(
int index
)
{return data[index];}
@Override
public byte[] getByteArray(
int index,
int length
)
{
byte[] data = new byte[length];
System.arraycopy(this.data, index, data, 0, length);
return data;
}
@Override
public String getString(
int index,
int length
)
{return Encoding.Pdf.decode(data, index, length);}
@Override
public int getCapacity(
)
{return data.length;}
@Override
public void insert(
int index,
byte[] data
)
{insert(index, data, 0, data.length);}
@Override
public void insert(
int index,
byte[] data,
int offset,
int length
)
{
ensureCapacity(length);
// Shift right the existing data block to make room for new data!
System.arraycopy(this.data, index, this.data, index + length, this.length - index);
// Insert additional data!
System.arraycopy(data, offset, this.data, index, length);
this.length += length;
notifyChange();
}
@Override
public void insert(
int index,
String data
)
{insert(index, Encoding.Pdf.encode(data));}
@Override
public void insert(
int index,
IInputStream data
)
{insert(index, data.toByteArray());}
@Override
public boolean removeListener(
IListener listener
)
{
if(listeners == null)
return false;
return listeners.remove(listener);
}
@Override
public void replace(
int index,
byte[] data
)
{
System.arraycopy(data, 0, this.data, index, data.length);
notifyChange();
}
@Override
public void replace(
int index,
byte[] data,
int offset,
int length
)
{
System.arraycopy(data, offset, this.data, index, data.length);
notifyChange();
}
@Override
public void replace(
int index,
String data
)
{replace(index, Encoding.Pdf.encode(data));}
@Override
public void replace(
int index,
IInputStream data
)
{replace(index, data.toByteArray());}
@Override
public void setDirty(
boolean value
)
{dirty = value;}
@Override
public void setLength(
int value
)
{
length = value;
notifyChange();
}
@Override
public void writeTo(
IOutputStream stream
)
{stream.write(data, 0, length);}
// <IInputStream>
@Override
public ByteOrder getByteOrder(
)
{return byteOrder;}
@Override
public long getPosition(
)
{return position;}
/* int hashCode() uses inherited implementation. */
@Override
public boolean isDirty(
)
{return dirty;}
@Override
public void read(
byte[] data
)
{read(data, 0, data.length);}
@Override
public void read(
byte[] data,
int offset,
int length
)
{
System.arraycopy(this.data, position, data, offset, length);
position += length;
}
@Override
public byte readByte(
) throws EOFException
{
if(position >= data.length)
throw new EOFException();
return data[position++];
}
@Override
public int readInt(
) throws EOFException
{
int value = ConvertUtils.byteArrayToInt(data, position, byteOrder);
position +=4;
return value;
}
@Override
public int readInt(
int length
) throws EOFException
{
int value = ConvertUtils.byteArrayToNumber(data, position, length, byteOrder);
position += length;
return value;
}
@Override
public String readLine(
) throws EOFException
{
if(position >= data.length)
throw new EOFException();
StringBuilder buffer = new StringBuilder();
while(position < data.length)
{
int c = data[position++];
if(c == '\r'
|| c == '\n')
break;
buffer.append((char)c);
}
return buffer.toString();
}
@Override
public short readShort(
) throws EOFException
{
short value = (short)ConvertUtils.byteArrayToNumber(data, position, 2, byteOrder);
position += 2;
return value;
}
@Override
public String readString(
int length
) throws EOFException
{
String data = Encoding.Pdf.decode(this.data, position, length);
position += length;
return data;
}
@Override
public int readUnsignedByte(
) throws EOFException
{
if(position >= data.length)
throw new EOFException();
return (data[position++] & 0xFF);
}
@Override
public int readUnsignedShort(
) throws EOFException
{
//TODO: harmonize byteorder semantics with C# version!!!
try
{
if(byteOrder == ByteOrder.LITTLE_ENDIAN)
return (data[position++] & 0xFF) | (data[position++] & 0xFF) << 8;
else // ByteOrder.BIG_ENDIAN
return (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF);
}
catch(ArrayIndexOutOfBoundsException e)
{throw new EOFException();}
}
@Override
public void seek(
long position
) throws EOFException
{
if(position < 0)
{position = 0;}
else if(position > data.length)
{position = data.length;}
this.position = (int)position;
}
@Override
public void setByteOrder(
ByteOrder value
)
{byteOrder = value;}
@Override
public void skip(
long offset
) throws EOFException
{seek(position + offset);}
// <IDataWrapper>
@Override
public byte[] toByteArray(
)
{
byte[] data = new byte[this.length];
System.arraycopy(this.data, 0, data, 0, this.length);
return data;
}
// </IDataWrapper>
// <IStream>
@Override
public long getLength(
)
{return length;}
// <Closeable>
@Override
public void close(
) throws IOException
{}
// </Closeable>
// </IStream>
// </IInputStream>
// </IBuffer>
// <IOutputStream>
@Override
public void write(
byte[] data
)
{append(data);}
@Override
public void write(
byte[] data,
int offset,
int length
)
{append(data, offset, length);}
@Override
public void write(
String data
)
{append(data);}
@Override
public void write(
IInputStream data
)
{append(data);}
// </IOutputStream>
// </public>
// <protected>
@Override
protected void finalize(
) throws Throwable
{
try
{close();}
finally
{super.finalize();}
}
// </protected>
// <private>
/**
Check whether the buffer capacity has sufficient room for adding data.
*/
private void ensureCapacity(
int additionalLength
)
{
int minCapacity = this.length + additionalLength;
// Is additional data within the buffer capacity?
if(minCapacity <= this.data.length)
return;
// Additional data exceed buffer capacity.
// Reallocate the buffer!
byte[] data = new byte[
Math.max(
this.data.length << 1, // 1 order of magnitude greater than current capacity.
minCapacity // Minimum capacity required.
)
];
System.arraycopy(this.data, 0, data, 0, this.length);
this.data = data;
}
private void notifyChange(
)
{
if(dirty || listeners == null)
return;
dirty = true;
for(IListener listener : listeners)
{listener.onChange(this);}
}
// </private>
// </interface>
// </dynamic>
// </class>
}
|
/**
* Copyright (C) 2009-2014 Typesafe Inc. <http://www.typesafe.com>
*/
package docs.actor;
import akka.actor.*;
import akka.japi.pf.ReceiveBuilder;
import akka.testkit.ErrorFilter;
import akka.testkit.EventFilter;
import akka.testkit.TestEvent;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import scala.PartialFunction;
import scala.runtime.BoxedUnit;
import static docs.actor.Messages.Swap.Swap;
import static docs.actor.Messages.*;
import static akka.japi.Util.immutableSeq;
import java.util.concurrent.TimeUnit;
import akka.testkit.JavaTestKit;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
//#import-props
import akka.actor.Props;
//#import-props
//#import-actorRef
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
//#import-actorRef
//#import-identify
import akka.actor.ActorIdentity;
import akka.actor.ActorSelection;
import akka.actor.Identify;
//#import-identify
//#import-graceFulStop
import akka.pattern.AskTimeoutException;
import scala.concurrent.Await;
import scala.concurrent.duration.Duration;
import scala.concurrent.Future;
import static akka.pattern.Patterns.gracefulStop;
//#import-graceFulStop
public class ActorDocTest {
public static Config config = ConfigFactory.parseString(
"akka {\n" +
" loggers = [\"akka.testkit.TestEventListener\"]\n" +
" loglevel = \"WARNING\"\n" +
" stdout-loglevel = \"WARNING\"\n" +
"}\n"
);
static ActorSystem system = null;
@BeforeClass
public static void beforeClass() {
system = ActorSystem.create("ActorDocTest", config);
}
@AfterClass
public static void afterClass() throws Exception {
Await.ready(system.terminate(), Duration.create("5 seconds"));
}
static
//#context-actorOf
public class FirstActor extends AbstractActor {
final ActorRef child = context().actorOf(Props.create(MyActor.class), "myChild");
//#plus-some-behavior
public FirstActor() {
receive(ReceiveBuilder.
matchAny(x -> {
sender().tell(x, self());
}).build()
);
}
//#plus-some-behavior
}
//#context-actorOf
static public abstract class SomeActor extends AbstractActor {
//#receive-constructor
public SomeActor() {
receive(ReceiveBuilder.
//#and-some-behavior
match(String.class, s -> System.out.println(s.toLowerCase())).
//#and-some-behavior
build());
}
//#receive-constructor
@Override
//#receive
public abstract PartialFunction<Object, BoxedUnit> receive();
//#receive
}
static public class ActorWithArgs extends AbstractActor {
private final String args;
ActorWithArgs(String args) {
this.args = args;
receive(ReceiveBuilder.
matchAny(x -> { }).build()
);
}
}
static
//#props-factory
public class DemoActor extends AbstractActor {
/**
* Create Props for an actor of this type.
* @param magicNumber The magic number to be passed to this actor’s constructor.
* @return a Props for creating this actor, which can then be further configured
* (e.g. calling `.withDispatcher()` on it)
*/
static Props props(Integer magicNumber) {
// You need to specify the actual type of the returned actor
// since Java 8 lambdas have some runtime type information erased
return Props.create(DemoActor.class, () -> new DemoActor(magicNumber));
}
private final Integer magicNumber;
DemoActor(Integer magicNumber) {
this.magicNumber = magicNumber;
receive(ReceiveBuilder.
match(Integer.class, i -> {
sender().tell(i + magicNumber, self());
}).build()
);
}
}
//#props-factory
static
//#props-factory
public class SomeOtherActor extends AbstractActor {
// Props(new DemoActor(42)) would not be safe
ActorRef demoActor = context().actorOf(DemoActor.props(42), "demo");
// ...
//#props-factory
public SomeOtherActor() {
receive(emptyBehavior());
}
//#props-factory
}
//#props-factory
static
//#messages-in-companion
public class DemoMessagesActor extends AbstractLoggingActor {
static public class Greeting {
private final String from;
public Greeting(String from) {
this.from = from;
}
public String getGreeter() {
return from;
}
}
DemoMessagesActor() {
receive(ReceiveBuilder.
match(Greeting.class, g -> {
log().info("I was greeted by {}", g.getGreeter());
}).build()
);
};
}
//#messages-in-companion
public static class Hook extends AbstractActor {
ActorRef target = null;
public Hook() {
receive(emptyBehavior());
}
//#preStart
@Override
public void preStart() {
target = context().actorOf(Props.create(MyActor.class, "target"));
}
//#preStart
//#postStop
@Override
public void postStop() {
//#clean-up-some-resources
final String message = "stopped";
//#tell
// don’t forget to think about who is the sender (2nd argument)
target.tell(message, self());
//#tell
final Object result = "";
//#forward
target.forward(result, context());
//#forward
target = null;
//#clean-up-some-resources
}
//#postStop
// compilation test only
public void compileSelections() {
//#selection-local
// will look up this absolute path
context().actorSelection("/user/serviceA/actor");
// will look up sibling beneath same supervisor
context().actorSelection("../joe");
//#selection-local
//#selection-wildcard
// will look all children to serviceB with names starting with worker
context().actorSelection("/user/serviceB/worker*");
// will look up all siblings beneath same supervisor
context().actorSelection("../*");
//#selection-wildcard
//#selection-remote
context().actorSelection("akka.tcp://app@otherhost:1234/user/serviceB");
//#selection-remote
}
}
public static class ReplyException extends AbstractActor {
public ReplyException() {
receive(ReceiveBuilder.
matchAny(x -> {
//#reply-exception
try {
String result = operation();
sender().tell(result, self());
} catch (Exception e) {
sender().tell(new akka.actor.Status.Failure(e), self());
throw e;
}
//#reply-exception
}).build()
);
}
private String operation() {
return "Hi";
}
}
static
//#gracefulStop-actor
public class Manager extends AbstractActor {
private static enum Shutdown {
Shutdown
}
public static final Shutdown SHUTDOWN = Shutdown.Shutdown;
private ActorRef worker =
context().watch(context().actorOf(Props.create(Cruncher.class), "worker"));
public Manager() {
receive(ReceiveBuilder.
matchEquals("job", s -> {
worker.tell("crunch", self());
}).
matchEquals(SHUTDOWN, x -> {
worker.tell(PoisonPill.getInstance(), self());
context().become(shuttingDown);
}).build()
);
}
public PartialFunction<Object, BoxedUnit> shuttingDown =
ReceiveBuilder.
matchEquals("job", s -> {
sender().tell("service unavailable, shutting down", self());
}).
match(Terminated.class, t -> t.actor().equals(worker), t -> {
context().stop(self());
}).build();
}
//#gracefulStop-actor
@Test
public void usePatternsGracefulStop() throws Exception {
ActorRef actorRef = system.actorOf(Props.create(Manager.class));
//#gracefulStop
try {
Future<Boolean> stopped =
gracefulStop(actorRef, Duration.create(5, TimeUnit.SECONDS), Manager.SHUTDOWN);
Await.result(stopped, Duration.create(6, TimeUnit.SECONDS));
// the actor has been stopped
} catch (AskTimeoutException e) {
// the actor wasn't stopped within 5 seconds
}
//#gracefulStop
}
public static class Cruncher extends AbstractActor {
public Cruncher() {
receive(ReceiveBuilder.
matchEquals("crunch", s -> { }).build()
);
}
}
static
//#swapper
public class Swapper extends AbstractLoggingActor {
public Swapper() {
receive(ReceiveBuilder.
matchEquals(Swap, s -> {
log().info("Hi");
context().become(ReceiveBuilder.
matchEquals(Swap, x -> {
log().info("Ho");
context().unbecome(); // resets the latest 'become' (just for fun)
}).build(), false); // push on top instead of replace
}).build()
);
}
}
//#swapper
static
//#swapper
public class SwapperApp {
public static void main(String[] args) {
ActorSystem system = ActorSystem.create("SwapperSystem");
ActorRef swapper = system.actorOf(Props.create(Swapper.class), "swapper");
swapper.tell(Swap, ActorRef.noSender()); // logs Hi
swapper.tell(Swap, ActorRef.noSender()); // logs Ho
swapper.tell(Swap, ActorRef.noSender()); // logs Hi
swapper.tell(Swap, ActorRef.noSender()); // logs Ho
swapper.tell(Swap, ActorRef.noSender()); // logs Hi
swapper.tell(Swap, ActorRef.noSender()); // logs Ho
system.terminate();
}
}
//#swapper
@Test
public void creatingActorWithSystemActorOf() {
//#system-actorOf
// ActorSystem is a heavy object: create only one per application
final ActorSystem system = ActorSystem.create("MySystem", config);
final ActorRef myActor = system.actorOf(Props.create(MyActor.class), "myactor");
//#system-actorOf
try {
new JavaTestKit(system) {
{
myActor.tell("hello", getRef());
expectMsgEquals("hello");
}
};
} finally {
JavaTestKit.shutdownActorSystem(system);
}
}
@Test
public void creatingPropsConfig() {
//#creating-props
Props props1 = Props.create(MyActor.class);
Props props2 = Props.create(ActorWithArgs.class,
() -> new ActorWithArgs("arg")); // careful, see below
Props props3 = Props.create(ActorWithArgs.class, "arg");
//#creating-props
//#creating-props-deprecated
// NOT RECOMMENDED within another actor:
// encourages to close over enclosing class
Props props7 = Props.create(ActorWithArgs.class,
() -> new ActorWithArgs("arg"));
//#creating-props-deprecated
}
@Test(expected=IllegalArgumentException.class)
public void creatingPropsIllegal() {
//#creating-props-illegal
// This will throw an IllegalArgumentException since some runtime
// type information of the lambda is erased.
// Use Props.create(actorClass, Creator) instead.
Props props = Props.create(() -> new ActorWithArgs("arg"));
//#creating-props-illegal
}
static
//#receive-timeout
public class ReceiveTimeoutActor extends AbstractActor {
//#receive-timeout
ActorRef target = context().system().deadLetters();
//#receive-timeout
public ReceiveTimeoutActor() {
// To set an initial delay
context().setReceiveTimeout(Duration.create("10 seconds"));
receive(ReceiveBuilder.
matchEquals("Hello", s -> {
// To set in a response to a message
context().setReceiveTimeout(Duration.create("1 second"));
//#receive-timeout
target = sender();
target.tell("Hello world", self());
//#receive-timeout
}).
match(ReceiveTimeout.class, r -> {
// To turn it off
context().setReceiveTimeout(Duration.Undefined());
//#receive-timeout
target.tell("timeout", self());
//#receive-timeout
}).build()
);
}
}
//#receive-timeout
@Test
public void using_receiveTimeout() {
final ActorRef myActor = system.actorOf(Props.create(ReceiveTimeoutActor.class));
new JavaTestKit(system) {
{
myActor.tell("Hello", getRef());
expectMsgEquals("Hello world");
expectMsgEquals("timeout");
}
};
}
static
//#hot-swap-actor
public class HotSwapActor extends AbstractActor {
private PartialFunction<Object, BoxedUnit> angry;
private PartialFunction<Object, BoxedUnit> happy;
public HotSwapActor() {
angry =
ReceiveBuilder.
matchEquals("foo", s -> {
sender().tell("I am already angry?", self());
}).
matchEquals("bar", s -> {
context().become(happy);
}).build();
happy = ReceiveBuilder.
matchEquals("bar", s -> {
sender().tell("I am already happy :-)", self());
}).
matchEquals("foo", s -> {
context().become(angry);
}).build();
receive(ReceiveBuilder.
matchEquals("foo", s -> {
context().become(angry);
}).
matchEquals("bar", s -> {
context().become(happy);
}).build()
);
}
}
//#hot-swap-actor
@Test
public void using_hot_swap() {
final ActorRef actor = system.actorOf(Props.create(HotSwapActor.class), "hot");
new JavaTestKit(system) {
{
actor.tell("foo", getRef());
actor.tell("foo", getRef());
expectMsgEquals("I am already angry?");
actor.tell("bar", getRef());
actor.tell("bar", getRef());
expectMsgEquals("I am already happy :-)");
actor.tell("foo", getRef());
actor.tell("foo", getRef());
expectMsgEquals("I am already angry?");
expectNoMsg(Duration.create(1, TimeUnit.SECONDS));
}
};
}
static
//#stash
public class ActorWithProtocol extends AbstractActorWithStash {
public ActorWithProtocol() {
receive(ReceiveBuilder.
matchEquals("open", s -> {
context().become(ReceiveBuilder.
matchEquals("write", ws -> { /* do writing */ }).
matchEquals("close", cs -> {
unstashAll();
context().unbecome();
}).
matchAny(msg -> stash()).build(), false);
}).
matchAny(msg -> stash()).build()
);
}
}
//#stash
@Test
public void using_Stash() {
final ActorRef actor = system.actorOf(Props.create(ActorWithProtocol.class), "stash");
}
static
//#watch
public class WatchActor extends AbstractActor {
private final ActorRef child = context().actorOf(Props.empty(), "target");
private ActorRef lastSender = system.deadLetters();
public WatchActor() {
context().watch(child); // <-- this is the only call needed for registration
receive(ReceiveBuilder.
matchEquals("kill", s -> {
context().stop(child);
lastSender = sender();
}).
match(Terminated.class, t -> t.actor().equals(child), t -> {
lastSender.tell("finished", self());
}).build()
);
}
}
//#watch
@Test
public void using_watch() {
ActorRef actor = system.actorOf(Props.create(WatchActor.class));
new JavaTestKit(system) {
{
actor.tell("kill", getRef());
expectMsgEquals("finished");
}
};
}
static
//#identify
public class Follower extends AbstractActor {
final Integer identifyId = 1;
public Follower(){
ActorSelection selection = context().actorSelection("/user/another");
selection.tell(new Identify(identifyId), self());
receive(ReceiveBuilder.
match(ActorIdentity.class, id -> id.getRef() != null, id -> {
ActorRef ref = id.getRef();
context().watch(ref);
context().become(active(ref));
}).
match(ActorIdentity.class, id -> id.getRef() == null, id -> {
context().stop(self());
}).build()
);
}
final PartialFunction<Object, BoxedUnit> active(final ActorRef another) {
return ReceiveBuilder.
match(Terminated.class, t -> t.actor().equals(another), t -> {
context().stop(self());
}).build();
}
}
//#identify
@Test
public void using_Identify() {
ActorRef a = system.actorOf(Props.empty());
ActorRef b = system.actorOf(Props.create(Follower.class));
new JavaTestKit(system) {
{
watch(b);
system.stop(a);
assertEquals(expectMsgClass(Duration.create(2, TimeUnit.SECONDS), Terminated.class).actor(), b);
}
};
}
public static class NoReceiveActor extends AbstractActor {
}
@Test
public void noReceiveActor() {
EventFilter ex1 = new ErrorFilter(ActorInitializationException.class);
EventFilter[] ignoreExceptions = { ex1 };
try {
system.eventStream().publish(new TestEvent.Mute(immutableSeq(ignoreExceptions)));
new JavaTestKit(system) {{
final ActorRef victim = new EventFilter<ActorRef>(ActorInitializationException.class) {
protected ActorRef run() {
return system.actorOf(Props.create(NoReceiveActor.class), "victim");
}
}.message("Actor behavior has not been set with receive(...)").occurrences(1).exec();
assertEquals(true, victim.isTerminated());
}};
} finally {
system.eventStream().publish(new TestEvent.UnMute(immutableSeq(ignoreExceptions)));
}
}
public static class MultipleReceiveActor extends AbstractActor {
public MultipleReceiveActor() {
receive(ReceiveBuilder.
match(String.class, s1 -> s1.toLowerCase().equals("become"), s1 -> {
sender().tell(s1.toUpperCase(), self());
receive(ReceiveBuilder.
match(String.class, s2 -> {
sender().tell(s2.toLowerCase(), self());
}).build()
);
}).
match(String.class, s1 -> {
sender().tell(s1.toUpperCase(), self());
}).build()
);
}
}
@Test
public void multipleReceiveActor() {
EventFilter ex1 = new ErrorFilter(IllegalActorStateException.class);
EventFilter[] ignoreExceptions = { ex1 };
try {
system.eventStream().publish(new TestEvent.Mute(immutableSeq(ignoreExceptions)));
new JavaTestKit(system) {{
new EventFilter<Boolean>(IllegalActorStateException.class) {
protected Boolean run() {
ActorRef victim = system.actorOf(Props.create(MultipleReceiveActor.class), "victim2");
victim.tell("Foo", getRef());
expectMsgEquals("FOO");
victim.tell("bEcoMe", getRef());
expectMsgEquals("BECOME");
victim.tell("Foo", getRef());
// if it's upper case, then the actor was restarted
expectMsgEquals("FOO");
return true;
}
}.message("Actor behavior has already been set with receive(...), " +
"use context().become(...) to change it later").occurrences(1).exec();
}};
} finally {
system.eventStream().publish(new TestEvent.UnMute(immutableSeq(ignoreExceptions)));
}
}
}
|
/**
*
* The MIT License (MIT)
*
* Copyright (c) 2015 Miikka Andersson
*
* 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.example.avjindersinghsekhon.minimaltodo;
import android.content.Context;
import android.test.ActivityUnitTestCase;
import com.example.avjindersinghsekhon.minimaltodo.view.Main.MainActivity;
import com.example.avjindersinghsekhon.minimaltodo.view.Utility.StoreRetrieveData;
import com.example.avjindersinghsekhon.minimaltodo.view.Utility.ToDoItem;
import org.json.JSONArray;
import java.util.ArrayList;
import java.util.Date;
/**
* Test cases for StoreRetrieveData class
*/
public class TestStoreRetrieveData extends ActivityUnitTestCase<MainActivity> {
private MainActivity mMainActivity;
private ArrayList<ToDoItem> mOriginalData;
ArrayList<ToDoItem> mTestData;
public TestStoreRetrieveData() {
super(MainActivity.class);
// Create some test data
mTestData = new ArrayList<>();
for (int i = 1; i < 11; i++) {
mTestData.add(new ToDoItem(
"item" + i,
false,
new Date()));
}
}
@Override
protected void setUp() throws Exception {
super.setUp();
mMainActivity = getActivity();
mOriginalData = new ArrayList<>();
// Save the original data and wipe out the storage
StoreRetrieveData dataStorage = getDataStorage();
try {
ArrayList<ToDoItem> items = dataStorage.loadFromFile();
if (items.size() > 0) {
mOriginalData.clear();
mOriginalData.addAll(items);
items.clear();
dataStorage.saveToFile(items);
}
} catch (Exception e) {
fail("Couldn't store data: " + e.getMessage());
}
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
// Let's restore the data we might have wiped out during setUp()...
StoreRetrieveData dataStorage = getDataStorage();
dataStorage.saveToFile(mOriginalData);
}
/**
* We should have an empty data storage at hand for the starters
*/
public void testPreconditions() {
StoreRetrieveData dataStorage = getDataStorage();
ArrayList<ToDoItem> items = null;
try {
items = dataStorage.loadFromFile();
} catch (Exception e) {
fail("Couldn't read from data storage: " + e.getMessage());
}
assertEquals(0, items.size());
}
/**
* Write items to data storage and ensure those same items can be retrieved from the storage.
*/
public void testWritingToAndReadingFromTheDataStorage() {
StoreRetrieveData dataStorage = getDataStorage();
ArrayList<ToDoItem> retrievedItems = new ArrayList<>();
// Persist the test data
try {
dataStorage.saveToFile(mTestData);
} catch (Exception e) {
fail("Couldn't store data: " + e.getMessage());
}
// Read from storage
try {
retrievedItems = dataStorage.loadFromFile();
} catch (Exception e) {
fail("Couldn't read from data storage: " + e.getMessage());
}
// We should have equal amount of items than what we just stored
assertEquals(mTestData.size(), retrievedItems.size());
// The content should be same as well...
for (ToDoItem retrievedItem : retrievedItems) {
// We want to be sure every single item in data storage can also be found from
// our test data collection
boolean found = false;
for (ToDoItem testItem : mTestData) {
// Check the items are same
if (retrievedItem.getIdentifier().equals(testItem.getIdentifier()) &&
retrievedItem.getToDoText().equals(testItem.getToDoText()) &&
retrievedItem.hasReminder() == testItem.hasReminder() &&
retrievedItem.getToDoDate().equals(testItem.getToDoDate())) {
found = true;
break;
}
}
if (!found) {
fail("Content mis-match between test data and data retrieved from the storage!");
}
}
}
/**
* Ensure JSONArray conversion works as intended
*/
public void testArrayListToJsonArrayConversion() {
try {
JSONArray array = StoreRetrieveData.toJSONArray(mTestData);
assertEquals(mTestData.size(), array.length());
} catch (Exception e) {
fail("Exception thrown when converting to JSONArray: " + e.getMessage());
}
}
private StoreRetrieveData getDataStorage() {
Context context = getInstrumentation().getTargetContext();
return new StoreRetrieveData(context, MainActivity.FILENAME);
}
}
|
package id.ipaddr.android.rereso.domain.model;
import java.util.Date;
/**
* Created by iip on 3/16/17.
*/
public class Baby {
private String babyFoto;
private String name;
private ESex eSex;
private EPlaceOfBirth ePlaceOfBirth;
private String placeOfBirth;
private Date dateOfBirth;
private Date timeOfBirth;
private ETypeOfBirth eTypeOfBirth;
private int birthSequenceAt;
private EBirthHelper eBirthHelper;
private float babyWeight;
private float babyHeight;
public Baby(){}
public Baby(String babyFoto, String name, ESex eSex, EPlaceOfBirth ePlaceOfBirth, String placeOfBirth, Date dateOfBirth, Date timeOfBirth, ETypeOfBirth eTypeOfBirth, int birthSequenceAt, EBirthHelper eBirthHelper, float babyWeight, float babyHeight) {
this.babyFoto = babyFoto;
this.name = name;
this.eSex = eSex;
this.ePlaceOfBirth = ePlaceOfBirth;
this.placeOfBirth = placeOfBirth;
this.dateOfBirth = dateOfBirth;
this.timeOfBirth = timeOfBirth;
this.eTypeOfBirth = eTypeOfBirth;
this.birthSequenceAt = birthSequenceAt;
this.eBirthHelper = eBirthHelper;
this.babyWeight = babyWeight;
this.babyHeight = babyHeight;
}
public Baby(String name, ESex eSex, EPlaceOfBirth ePlaceOfBirth, String placeOfBirth, Date dateOfBirth, Date timeOfBirth, ETypeOfBirth eTypeOfBirth, int birthSequenceAt, EBirthHelper eBirthHelper, float babyWeight, float babyHeight) {
this.name = name;
this.eSex = eSex;
this.ePlaceOfBirth = ePlaceOfBirth;
this.placeOfBirth = placeOfBirth;
this.dateOfBirth = dateOfBirth;
this.timeOfBirth = timeOfBirth;
this.eTypeOfBirth = eTypeOfBirth;
this.birthSequenceAt = birthSequenceAt;
this.eBirthHelper = eBirthHelper;
this.babyWeight = babyWeight;
this.babyHeight = babyHeight;
}
public String getBabyFoto() {
return babyFoto;
}
public void setBabyFoto(String babyFoto) {
this.babyFoto = babyFoto;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ESex geteSex() {
return eSex;
}
public void seteSex(ESex eSex) {
this.eSex = eSex;
}
public EPlaceOfBirth getePlaceOfBirth() {
return ePlaceOfBirth;
}
public void setePlaceOfBirth(EPlaceOfBirth ePlaceOfBirth) {
this.ePlaceOfBirth = ePlaceOfBirth;
}
public String getPlaceOfBirth() {
return placeOfBirth;
}
public void setPlaceOfBirth(String placeOfBirth) {
this.placeOfBirth = placeOfBirth;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public Date getTimeOfBirth() {
return timeOfBirth;
}
public void setTimeOfBirth(Date timeOfBirth) {
this.timeOfBirth = timeOfBirth;
}
public ETypeOfBirth geteTypeOfBirth() {
return eTypeOfBirth;
}
public void seteTypeOfBirth(ETypeOfBirth eTypeOfBirth) {
this.eTypeOfBirth = eTypeOfBirth;
}
public int getBirthSequenceAt() {
return birthSequenceAt;
}
public void setBirthSequenceAt(int birthSequenceAt) {
this.birthSequenceAt = birthSequenceAt;
}
public EBirthHelper geteBirthHelper() {
return eBirthHelper;
}
public void seteBirthHelper(EBirthHelper eBirthHelper) {
this.eBirthHelper = eBirthHelper;
}
public float getBabyWeight() {
return babyWeight;
}
public void setBabyWeight(float babyWeight) {
this.babyWeight = babyWeight;
}
}
|
/*
*
* * Copyright (c) 2021. ForteScarlet All rights reserved.
* * Project simple-robot
* * File MiraiAvatar.kt
* *
* * You can contact the author through the following channels:
* * github https://github.com/ForteScarlet
* * gitee https://gitee.com/ForteScarlet
* * email ForteScarlet@163.com
* * QQ 1149159218
*
*/
package love.forte.test;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.WeakHashMap;
/**
* 简易的弱引用ThreadLocal.
* 构建实例的 `id` 参数用于区分不同的参数。
* @author ForteScarlet
*/
public final class ThreadLocal<T> {
private static final WeakHashMap<Thread, Map<Integer, Object>> weakMap = new WeakHashMap<>();
private final int id;
private static Map<Integer, Object> createMap() {
return new LinkedHashMap<>();
}
public ThreadLocal(int id) {
this.id = id;
}
public ThreadLocal(int id, T init) {
this.id = id;
set(init);
}
public static int weakMapSize() {
return weakMap.size();
}
private Map<Integer, Object> getMap() {
Thread t = Thread.currentThread();
Map<Integer, Object> map = weakMap.get(t);
if (map == null) {
synchronized (weakMap) {
map = weakMap.computeIfAbsent(t, k -> createMap());
}
}
return map;
}
public void set(T value) {
getMap().put(id, value);
}
@SuppressWarnings("unchecked")
public T get() {
return (T) getMap().get(id);
}
public void remove() {
Thread t = Thread.currentThread();
weakMap.remove(t);
}
}
|
/*
* 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.karaf.shell.ssh;
import java.io.ByteArrayInputStream;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.nio.file.Paths;
import java.security.KeyPair;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.karaf.shell.api.action.Action;
import org.apache.karaf.shell.api.action.Argument;
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.Option;
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.apache.karaf.shell.api.console.Session;
import org.apache.karaf.shell.api.console.Signal;
import org.apache.karaf.shell.api.console.SignalListener;
import org.apache.karaf.shell.api.console.Terminal;
import org.apache.sshd.agent.SshAgent;
import org.apache.sshd.agent.local.AgentImpl;
import org.apache.sshd.agent.local.LocalAgentFactory;
import org.apache.sshd.client.channel.ClientChannelEvent;
import org.apache.sshd.client.keyverifier.ServerKeyVerifier;
import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.auth.keyboard.UserInteraction;
import org.apache.sshd.client.channel.ChannelShell;
import org.apache.sshd.client.channel.ClientChannel;
import org.apache.sshd.client.future.ConnectFuture;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.common.SshConstants;
import org.apache.sshd.common.channel.PtyMode;
import org.apache.sshd.common.keyprovider.AbstractFileKeyPairProvider;
import org.apache.sshd.common.util.SecurityUtils;
import org.apache.sshd.common.util.buffer.Buffer;
import org.apache.sshd.common.util.io.NoCloseInputStream;
import org.apache.sshd.common.util.io.NoCloseOutputStream;
import org.jline.terminal.Attributes;
import org.jline.terminal.Attributes.ControlChar;
import org.jline.terminal.Attributes.InputFlag;
import org.jline.terminal.Attributes.LocalFlag;
import org.jline.terminal.Attributes.OutputFlag;
import org.jline.terminal.Size;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Command(scope = "ssh", name = "ssh", description = "Connects to a remote SSH server")
@Service
public class SshAction implements Action {
private final Logger log = LoggerFactory.getLogger(getClass());
@Option(name = "-l", aliases = {"--username"}, description = "The user name for remote login", required = false, multiValued = false)
private String username;
@Option(name = "-P", aliases = {"--password"}, description = "The password for remote login", required = false, multiValued = false)
private String password;
@Option(name = "-p", aliases = {"--port"}, description = "The port to use for SSH connection", required = false, multiValued = false)
private int port = 22;
@Option(name = "-k", aliases = {"--keyfile"}, description = "The private keyFile location when using key login, need have BouncyCastle registered as security provider using this flag", required = false, multiValued = false)
private String keyFile;
@Option(name = "-q", description = "Quiet Mode. Do not ask for confirmations", required = false, multiValued = false)
private boolean quiet;
@Option(name = "-r", aliases = {"--retries"}, description = "retry connection establishment (up to attempts times)", required = false, multiValued = false)
private int retries = 0;
@Argument(index = 0, name = "hostname", description = "The host name to connect to via SSH", required = true, multiValued = false)
private String hostname;
@Argument(index = 1, name = "command", description = "Optional command to execute", required = false, multiValued = true)
private List<String> command;
@Reference
private Session session;
@Override
public Object execute() throws Exception {
if (hostname.indexOf('@') >= 0) {
if (username == null) {
username = hostname.substring(0, hostname.indexOf('@'));
}
hostname = hostname.substring(hostname.indexOf('@') + 1, hostname.length());
}
System.out.println("Connecting to host " + hostname + " on port " + port);
// If not specified, assume the current user name
if (username == null) {
username = (String) this.session.get("USER");
}
// If the username was not configured via cli, then prompt the user for the values
if (username == null) {
log.debug("Prompting user for login");
if (username == null) {
username = session.readLine("Login: ", null);
}
}
SshClient client = SshClient.setUpDefaultClient();
setupAgent(username, keyFile, client);
KnownHostsManager knownHostsManager = new KnownHostsManager(new File(System.getProperty("user.home"), ".sshkaraf/known_hosts"));
ServerKeyVerifier serverKeyVerifier = new ServerKeyVerifierImpl(knownHostsManager, quiet);
client.setServerKeyVerifier(serverKeyVerifier);
log.debug("Created client: {}", client);
client.setUserInteraction(new UserInteraction() {
@Override
public void welcome(ClientSession session, String banner, String lang) {
System.out.println(banner);
}
@Override
public String[] interactive(ClientSession s, String name, String instruction, String lang, String[] prompt, boolean[] echo) {
String[] answers = new String[prompt.length];
try {
for (int i = 0; i < prompt.length; i++) {
answers[i] = session.readLine(prompt[i] + " ", echo[i] ? null : '*');
}
} catch (IOException e) {
}
return answers;
}
@Override
public boolean isInteractionAllowed(ClientSession session) {
return true;
}
@Override
public void serverVersionInfo(ClientSession session, List<String> lines) {
}
@Override
public String getUpdatedPassword(ClientSession session, String prompt, String lang) {
return null;
}
});
client.start();
try {
ClientSession sshSession = connectWithRetries(client, username, hostname, port, retries);
Object oldIgnoreInterrupts = this.session.get(Session.IGNORE_INTERRUPTS);
try {
if (password != null) {
sshSession.addPasswordIdentity(password);
}
sshSession.auth().verify();
System.out.println("Connected");
this.session.put(Session.IGNORE_INTERRUPTS, Boolean.TRUE);
StringBuilder sb = new StringBuilder();
if (command != null) {
for (String cmd : command) {
if (sb.length() > 0) {
sb.append(' ');
}
sb.append(cmd);
}
}
if (sb.length() > 0) {
ClientChannel channel = sshSession.createChannel("exec", sb.append("\n").toString());
channel.setIn(new ByteArrayInputStream(new byte[0]));
channel.setOut(new NoCloseOutputStream(System.out));
channel.setErr(new NoCloseOutputStream(System.err));
channel.open().verify();
channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), 0);
} else if (session.getTerminal() != null) {
final ChannelShell channel = sshSession.createShellChannel();
final org.jline.terminal.Terminal jlineTerminal = (org.jline.terminal.Terminal) session.get(".jline.terminal");
Attributes attributes = jlineTerminal.enterRawMode();
try {
Map<PtyMode, Integer> modes = new HashMap<>();
// Control chars
modes.put(PtyMode.VINTR, attributes.getControlChar(ControlChar.VINTR));
modes.put(PtyMode.VQUIT, attributes.getControlChar(ControlChar.VQUIT));
modes.put(PtyMode.VERASE, attributes.getControlChar(ControlChar.VERASE));
modes.put(PtyMode.VKILL, attributes.getControlChar(ControlChar.VKILL));
modes.put(PtyMode.VEOF, attributes.getControlChar(ControlChar.VEOF));
modes.put(PtyMode.VEOL, attributes.getControlChar(ControlChar.VEOL));
modes.put(PtyMode.VEOL2, attributes.getControlChar(ControlChar.VEOL2));
modes.put(PtyMode.VSTART, attributes.getControlChar(ControlChar.VSTART));
modes.put(PtyMode.VSTOP, attributes.getControlChar(ControlChar.VSTOP));
modes.put(PtyMode.VSUSP, attributes.getControlChar(ControlChar.VSUSP));
modes.put(PtyMode.VDSUSP, attributes.getControlChar(ControlChar.VDSUSP));
modes.put(PtyMode.VREPRINT, attributes.getControlChar(ControlChar.VREPRINT));
modes.put(PtyMode.VWERASE, attributes.getControlChar(ControlChar.VWERASE));
modes.put(PtyMode.VLNEXT, attributes.getControlChar(ControlChar.VLNEXT));
modes.put(PtyMode.VSTATUS, attributes.getControlChar(ControlChar.VSTATUS));
modes.put(PtyMode.VDISCARD, attributes.getControlChar(ControlChar.VDISCARD));
// Input flags
modes.put(PtyMode.IGNPAR, getFlag(attributes, InputFlag.IGNPAR));
modes.put(PtyMode.PARMRK, getFlag(attributes, InputFlag.PARMRK));
modes.put(PtyMode.INPCK, getFlag(attributes, InputFlag.INPCK));
modes.put(PtyMode.ISTRIP, getFlag(attributes, InputFlag.ISTRIP));
modes.put(PtyMode.INLCR, getFlag(attributes, InputFlag.INLCR));
modes.put(PtyMode.IGNCR, getFlag(attributes, InputFlag.IGNCR));
modes.put(PtyMode.ICRNL, getFlag(attributes, InputFlag.ICRNL));
modes.put(PtyMode.IXON, getFlag(attributes, InputFlag.IXON));
modes.put(PtyMode.IXANY, getFlag(attributes, InputFlag.IXANY));
modes.put(PtyMode.IXOFF, getFlag(attributes, InputFlag.IXOFF));
// Local flags
modes.put(PtyMode.ISIG, getFlag(attributes, LocalFlag.ISIG));
modes.put(PtyMode.ICANON, getFlag(attributes, LocalFlag.ICANON));
modes.put(PtyMode.ECHO, getFlag(attributes, LocalFlag.ECHO));
modes.put(PtyMode.ECHOE, getFlag(attributes, LocalFlag.ECHOE));
modes.put(PtyMode.ECHOK, getFlag(attributes, LocalFlag.ECHOK));
modes.put(PtyMode.ECHONL, getFlag(attributes, LocalFlag.ECHONL));
modes.put(PtyMode.NOFLSH, getFlag(attributes, LocalFlag.NOFLSH));
modes.put(PtyMode.TOSTOP, getFlag(attributes, LocalFlag.TOSTOP));
modes.put(PtyMode.IEXTEN, getFlag(attributes, LocalFlag.IEXTEN));
// Output flags
modes.put(PtyMode.OPOST, getFlag(attributes, OutputFlag.OPOST));
modes.put(PtyMode.ONLCR, getFlag(attributes, OutputFlag.ONLCR));
modes.put(PtyMode.OCRNL, getFlag(attributes, OutputFlag.OCRNL));
modes.put(PtyMode.ONOCR, getFlag(attributes, OutputFlag.ONOCR));
modes.put(PtyMode.ONLRET, getFlag(attributes, OutputFlag.ONLRET));
channel.setPtyModes(modes);
channel.setPtyColumns(getTermWidth());
channel.setPtyLines(getTermHeight());
channel.setAgentForwarding(true);
channel.setEnv("TERM", session.getTerminal().getType());
Object ctype = session.get("LC_CTYPE");
if (ctype != null) {
channel.setEnv("LC_CTYPE", ctype.toString());
}
channel.setIn(new NoCloseInputStream(System.in));
channel.setOut(new NoCloseOutputStream(System.out));
channel.setErr(new NoCloseOutputStream(System.err));
channel.open().verify();
SignalListener signalListener = signal -> {
try {
Size size = jlineTerminal.getSize();
channel.sendWindowChange(size.getColumns(), size.getRows());
} catch (IOException e) {
// Ignore
}
};
session.getTerminal().addSignalListener(signalListener, Signal.WINCH);
try {
channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), 0);
} finally {
session.getTerminal().removeSignalListener(signalListener);
}
} finally {
jlineTerminal.setAttributes(attributes);
}
} else {
throw new IllegalStateException("No terminal for interactive ssh session");
}
} finally {
session.put(Session.IGNORE_INTERRUPTS, oldIgnoreInterrupts);
sshSession.close(false);
}
} finally {
client.stop();
}
return null;
}
private static int getFlag(Attributes attributes, InputFlag flag) {
return attributes.getInputFlag(flag) ? 1 : 0;
}
private static int getFlag(Attributes attributes, OutputFlag flag) {
return attributes.getOutputFlag(flag) ? 1 : 0;
}
private static int getFlag(Attributes attributes, LocalFlag flag) {
return attributes.getLocalFlag(flag) ? 1 : 0;
}
private int getTermWidth() {
Terminal term = session.getTerminal();
return term != null ? term.getWidth() : 80;
}
private int getTermHeight() {
Terminal term = session.getTerminal();
return term != null ? term.getHeight() : 25;
}
private void setupAgent(String user, String keyFile, SshClient client) {
SshAgent agent;
URL url = getClass().getClassLoader().getResource("karaf.key");
agent = startAgent(user, url, keyFile);
client.setAgentFactory(new LocalAgentFactory(agent));
client.getProperties().put(SshAgent.SSH_AUTHSOCKET_ENV_NAME, "local");
}
private SshAgent startAgent(String user, URL privateKeyUrl, String keyFile) {
InputStream is = null;
try {
SshAgent agent = new AgentImpl();
is = privateKeyUrl.openStream();
ObjectInputStream r = new ObjectInputStream(is);
KeyPair keyPair = (KeyPair) r.readObject();
is.close();
agent.addIdentity(keyPair, user);
if (keyFile != null) {
AbstractFileKeyPairProvider fileKeyPairProvider = SecurityUtils.createFileKeyPairProvider();
fileKeyPairProvider.setPaths(Collections.singleton(Paths.get(keyFile)));
for (KeyPair key : fileKeyPairProvider.loadKeys()) {
agent.addIdentity(key, user);
}
}
return agent;
} catch (Throwable e) {
close(is);
System.err.println("Error starting ssh agent for: " + e.getMessage());
return null;
}
}
private static ClientSession connectWithRetries(SshClient client, String username, String host, int port, int maxAttempts) throws Exception, InterruptedException {
ClientSession session = null;
int retries = 0;
do {
ConnectFuture future = client.connect(username, host, port);
future.await();
try {
session = future.getSession();
} catch (Exception ex) {
if (retries++ < maxAttempts) {
Thread.sleep(2 * 1000);
System.out.println("retrying (attempt " + retries + ") ...");
} else {
throw ex;
}
}
} while (session == null);
return session;
}
private void close(Closeable is) {
if (is != null) {
try {
is.close();
} catch (IOException e1) {
// Ignore
}
}
}
}
|
/*
* Copyright 2019 Google 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.google.googlejavaformat.java;
import static com.google.common.collect.Iterables.getLast;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.stream.Collectors.joining;
import com.google.common.base.CharMatcher;
import com.google.common.base.Strings;
import com.google.common.base.Verify;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Range;
import com.google.common.collect.TreeRangeMap;
import com.google.googlejavaformat.Newlines;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.LiteralTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.util.TreePath;
import com.sun.source.util.TreePathScanner;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.parser.JavacParser;
import com.sun.tools.javac.parser.ParserFactory;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Log;
import com.sun.tools.javac.util.Options;
import com.sun.tools.javac.util.Position;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.DiagnosticListener;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardLocation;
/** Wraps string literals that exceed the column limit. */
public final class StringWrapper {
/** Reflows long string literals in the given Java source code. */
public static String wrap(String input, Formatter formatter) throws FormatterException {
return StringWrapper.wrap(formatter.maxLineLength(), input, formatter);
}
/**
* Reflows string literals in the given Java source code that extend past the given column limit.
*/
static String wrap(final int columnLimit, String input, Formatter formatter)
throws FormatterException {
if (!longLines(columnLimit, input)) {
// fast path
return input;
}
TreeRangeMap<Integer, String> replacements = getReflowReplacements(columnLimit, input);
String firstPass = formatter.formatSource(input, replacements.asMapOfRanges().keySet());
if (!firstPass.equals(input)) {
// If formatting the replacement ranges resulted in a change, recalculate the replacements on
// the updated input.
input = firstPass;
replacements = getReflowReplacements(columnLimit, input);
}
String result = applyReplacements(input, replacements);
{
// We really don't want bugs in this pass to change the behaviour of programs we're
// formatting, so check that the pretty-printed AST is the same before and after reformatting.
String expected = parse(input, /* allowStringFolding= */ true).toString();
String actual = parse(result, /* allowStringFolding= */ true).toString();
if (!expected.equals(actual)) {
throw new FormatterException(
String.format(
"Something has gone terribly wrong. Please file a bug: "
+ "https://github.com/google/google-java-format/issues/new"
+ "\n\n=== Actual: ===\n%s\n=== Expected: ===\n%s\n",
actual, expected));
}
}
return result;
}
private static TreeRangeMap<Integer, String> getReflowReplacements(
int columnLimit, final String input) throws FormatterException {
JCTree.JCCompilationUnit unit = parse(input, /* allowStringFolding= */ false);
String separator = Newlines.guessLineSeparator(input);
// Paths to string literals that extend past the column limit.
List<TreePath> toFix = new ArrayList<>();
final Position.LineMap lineMap = unit.getLineMap();
new TreePathScanner<Void, Void>() {
@Override
public Void visitLiteral(LiteralTree literalTree, Void aVoid) {
if (literalTree.getKind() != Kind.STRING_LITERAL) {
return null;
}
Tree parent = getCurrentPath().getParentPath().getLeaf();
if (parent instanceof MemberSelectTree
&& ((MemberSelectTree) parent).getExpression().equals(literalTree)) {
return null;
}
int endPosition = getEndPosition(unit, literalTree);
int lineEnd = endPosition;
while (Newlines.hasNewlineAt(input, lineEnd) == -1) {
lineEnd++;
}
if (lineMap.getColumnNumber(lineEnd) - 1 <= columnLimit) {
return null;
}
toFix.add(getCurrentPath());
return null;
}
}.scan(new TreePath(unit), null);
TreeRangeMap<Integer, String> replacements = TreeRangeMap.create();
for (TreePath path : toFix) {
// Find the outermost contiguous enclosing concatenation expression
TreePath enclosing = path;
while (enclosing.getParentPath().getLeaf().getKind() == Tree.Kind.PLUS) {
enclosing = enclosing.getParentPath();
}
// Is the literal being wrapped the first in a chain of concatenation expressions?
// i.e. `ONE + TWO + THREE`
// We need this information to handle continuation indents.
AtomicBoolean first = new AtomicBoolean(false);
// Finds the set of string literals in the concat expression that includes the one that needs
// to be wrapped.
List<Tree> flat = flatten(input, unit, path, enclosing, first);
// Zero-indexed start column
int startColumn = lineMap.getColumnNumber(getStartPosition(flat.get(0))) - 1;
// Handling leaving trailing non-string tokens at the end of the literal,
// e.g. the trailing `);` in `foo("...");`.
int end = getEndPosition(unit, getLast(flat));
int lineEnd = end;
while (Newlines.hasNewlineAt(input, lineEnd) == -1) {
lineEnd++;
}
int trailing = lineEnd - end;
// Get the original source text of the string literals, excluding `"` and `+`.
ImmutableList<String> components = stringComponents(input, unit, flat);
replacements.put(
Range.closedOpen(getStartPosition(flat.get(0)), getEndPosition(unit, getLast(flat))),
reflow(separator, columnLimit, startColumn, trailing, components, first.get()));
}
return replacements;
}
/**
* Returns the source text of the given string literal trees, excluding the leading and trailing
* double-quotes and the `+` operator.
*/
private static ImmutableList<String> stringComponents(
String input, JCTree.JCCompilationUnit unit, List<Tree> flat) {
ImmutableList.Builder<String> result = ImmutableList.builder();
StringBuilder piece = new StringBuilder();
for (Tree tree : flat) {
// adjust for leading and trailing double quotes
String text = input.substring(getStartPosition(tree) + 1, getEndPosition(unit, tree) - 1);
int start = 0;
for (int idx = 0; idx < text.length(); idx++) {
if (CharMatcher.whitespace().matches(text.charAt(idx))) {
// continue below
} else if (hasEscapedWhitespaceAt(text, idx) != -1) {
// continue below
} else if (hasEscapedNewlineAt(text, idx) != -1) {
int length;
while ((length = hasEscapedNewlineAt(text, idx)) != -1) {
idx += length;
}
} else {
continue;
}
piece.append(text, start, idx);
result.add(piece.toString());
piece = new StringBuilder();
start = idx;
}
if (piece.length() > 0) {
result.add(piece.toString());
piece = new StringBuilder();
}
if (start < text.length()) {
piece.append(text, start, text.length());
}
}
if (piece.length() > 0) {
result.add(piece.toString());
}
return result.build();
}
static int hasEscapedWhitespaceAt(String input, int idx) {
return Stream.of("\\t")
.mapToInt(x -> input.startsWith(x, idx) ? x.length() : -1)
.filter(x -> x != -1)
.findFirst()
.orElse(-1);
}
static int hasEscapedNewlineAt(String input, int idx) {
return Stream.of("\\r\\n", "\\r", "\\n")
.mapToInt(x -> input.startsWith(x, idx) ? x.length() : -1)
.filter(x -> x != -1)
.findFirst()
.orElse(-1);
}
/**
* Reflows the given source text, trying to split on word boundaries.
*
* @param separator the line separator
* @param columnLimit the number of columns to wrap at
* @param startColumn the column position of the beginning of the original text
* @param trailing extra space to leave after the last line
* @param components the text to reflow
* @param first0 true if the text includes the beginning of its enclosing concat chain, i.e. a
*/
private static String reflow(
String separator,
int columnLimit,
int startColumn,
int trailing,
ImmutableList<String> components,
boolean first0) {
// We have space between the start column and the limit to output the first line.
// Reserve two spaces for the quotes.
int width = columnLimit - startColumn - 2;
Deque<String> input = new ArrayDeque<>(components);
List<String> lines = new ArrayList<>();
boolean first = first0;
while (!input.isEmpty()) {
int length = 0;
List<String> line = new ArrayList<>();
if (input.stream().mapToInt(x -> x.length()).sum() <= width) {
width -= trailing;
}
while (!input.isEmpty() && (length <= 4 || (length + input.peekFirst().length()) < width)) {
String text = input.removeFirst();
line.add(text);
length += text.length();
if (text.endsWith("\\n") || text.endsWith("\\r")) {
break;
}
}
if (line.isEmpty()) {
line.add(input.removeFirst());
}
// add the split line to the output, and process whatever's left
lines.add(String.join("", line));
if (first) {
width -= 6; // subsequent lines have a four-space continuation indent and a `+ `
first = false;
}
}
return lines.stream()
.collect(
joining(
"\"" + separator + Strings.repeat(" ", startColumn + (first0 ? 4 : -2)) + "+ \"",
"\"",
"\""));
}
/**
* Flattens the given binary expression tree, and extracts the subset that contains the given path
* and any adjacent nodes that are also string literals.
*/
private static List<Tree> flatten(
String input,
JCTree.JCCompilationUnit unit,
TreePath path,
TreePath parent,
AtomicBoolean firstInChain) {
List<Tree> flat = new ArrayList<>();
// flatten the expression tree with a pre-order traversal
ArrayDeque<Tree> todo = new ArrayDeque<>();
todo.add(parent.getLeaf());
while (!todo.isEmpty()) {
Tree first = todo.removeFirst();
if (first.getKind() == Tree.Kind.PLUS) {
BinaryTree bt = (BinaryTree) first;
todo.addFirst(bt.getRightOperand());
todo.addFirst(bt.getLeftOperand());
} else {
flat.add(first);
}
}
int idx = flat.indexOf(path.getLeaf());
Verify.verify(idx != -1);
// walk outwards from the leaf for adjacent string literals to also reflow
int startIdx = idx;
int endIdx = idx + 1;
while (startIdx > 0
&& flat.get(startIdx - 1).getKind() == Tree.Kind.STRING_LITERAL
&& noComments(input, unit, flat.get(startIdx - 1), flat.get(startIdx))) {
startIdx--;
}
while (endIdx < flat.size()
&& flat.get(endIdx).getKind() == Tree.Kind.STRING_LITERAL
&& noComments(input, unit, flat.get(endIdx - 1), flat.get(endIdx))) {
endIdx++;
}
firstInChain.set(startIdx == 0);
return ImmutableList.copyOf(flat.subList(startIdx, endIdx));
}
private static boolean noComments(
String input, JCTree.JCCompilationUnit unit, Tree one, Tree two) {
return STRING_CONCAT_DELIMITER.matchesAllOf(
input.subSequence(getEndPosition(unit, one), getStartPosition(two)));
}
public static final CharMatcher STRING_CONCAT_DELIMITER =
CharMatcher.whitespace().or(CharMatcher.anyOf("\"+"));
private static int getEndPosition(JCTree.JCCompilationUnit unit, Tree tree) {
return ((JCTree) tree).getEndPosition(unit.endPositions);
}
private static int getStartPosition(Tree tree) {
return ((JCTree) tree).getStartPosition();
}
/** Returns true if any lines in the given Java source exceed the column limit. */
private static boolean longLines(int columnLimit, String input) {
// TODO(cushon): consider adding Newlines.lineIterable?
Iterator<String> it = Newlines.lineIterator(input);
while (it.hasNext()) {
String line = it.next();
if (line.length() > columnLimit) {
return true;
}
}
return false;
}
/** Parses the given Java source. */
private static JCTree.JCCompilationUnit parse(String source, boolean allowStringFolding)
throws FormatterException {
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
Context context = new Context();
context.put(DiagnosticListener.class, diagnostics);
Options.instance(context).put("allowStringFolding", Boolean.toString(allowStringFolding));
JCTree.JCCompilationUnit unit;
JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8);
try {
fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, ImmutableList.of());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
SimpleJavaFileObject sjfo =
new SimpleJavaFileObject(URI.create("source"), JavaFileObject.Kind.SOURCE) {
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return source;
}
};
Log.instance(context).useSource(sjfo);
ParserFactory parserFactory = ParserFactory.instance(context);
JavacParser parser =
parserFactory.newParser(
source, /*keepDocComments=*/ true, /*keepEndPos=*/ true, /*keepLineMap=*/ true);
unit = parser.parseCompilationUnit();
unit.sourcefile = sjfo;
Iterable<Diagnostic<? extends JavaFileObject>> errorDiagnostics =
Iterables.filter(diagnostics.getDiagnostics(), Formatter::errorDiagnostic);
if (!Iterables.isEmpty(errorDiagnostics)) {
// error handling is done during formatting
throw FormatterException.fromJavacDiagnostics(errorDiagnostics);
}
return unit;
}
/** Applies replacements to the given string. */
private static String applyReplacements(
String javaInput, TreeRangeMap<Integer, String> replacementMap) throws FormatterException {
// process in descending order so the replacement ranges aren't perturbed if any replacements
// differ in size from the input
Map<Range<Integer>, String> ranges = replacementMap.asDescendingMapOfRanges();
if (ranges.isEmpty()) {
return javaInput;
}
StringBuilder sb = new StringBuilder(javaInput);
for (Map.Entry<Range<Integer>, String> entry : ranges.entrySet()) {
Range<Integer> range = entry.getKey();
sb.replace(range.lowerEndpoint(), range.upperEndpoint(), entry.getValue());
}
return sb.toString();
}
private StringWrapper() {}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.dataflow.sdk.transforms;
import static com.google.cloud.dataflow.sdk.TestUtils.checkCombineFn;
import static org.junit.Assert.assertEquals;
import com.google.common.collect.Lists;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests for Max.
*/
@RunWith(JUnit4.class)
public class MaxTest {
@Test
public void testMeanGetNames() {
assertEquals("Max.Globally", Max.integersGlobally().getName());
assertEquals("Max.Globally", Max.doublesGlobally().getName());
assertEquals("Max.Globally", Max.longsGlobally().getName());
assertEquals("Max.PerKey", Max.integersPerKey().getName());
assertEquals("Max.PerKey", Max.doublesPerKey().getName());
assertEquals("Max.PerKey", Max.longsPerKey().getName());
}
@Test
public void testMaxIntegerFn() {
checkCombineFn(
new Max.MaxIntegerFn(),
Lists.newArrayList(1, 2, 3, 4),
4);
}
@Test
public void testMaxLongFn() {
checkCombineFn(
new Max.MaxLongFn(),
Lists.newArrayList(1L, 2L, 3L, 4L),
4L);
}
@Test
public void testMaxDoubleFn() {
checkCombineFn(
new Max.MaxDoubleFn(),
Lists.newArrayList(1.0, 2.0, 3.0, 4.0),
4.0);
}
}
|
//
// LoginResponse.java
// blogwt
//
// Created by William Shakour on May 11, 2015.
// Copyright © 2015 WillShex Limited. All rights reserved.
//
package com.willshex.blogwt.shared.api.user.call;
import com.google.gson.JsonObject;
import com.willshex.blogwt.shared.api.Response;
public class LoginResponse extends Response {
@Override
public JsonObject toJson () {
JsonObject object = super.toJson();
return object;
}
@Override
public void fromJson (JsonObject jsonObject) {
super.fromJson(jsonObject);
}
}
|
/**
* Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sailmi.cms.mapper;
import com.sailmi.cms.entity.Type;
import com.sailmi.cms.utils.TreeEntity;
import com.sailmi.cms.vo.TypeVO;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import java.util.List;
/**
* 内容分类 Mapper 接口
*
* @author sailmi
* @since 2020-12-16
*/
public interface TypeMapper extends BaseMapper<Type> {
/**
* 自定义分页
*
* @param page
* @param type
* @return
*/
List<TypeVO> selectTypePage(IPage page, TypeVO type);
/**
* <p>Description: 获取所有下载中心的父结构</p>
*
* @return: void
* @Author: syt
* @Date: 2020/12/24/024 11:38
*/
List<TreeEntity> downTypeTree();
/**
* <p>Description: 获取所有的</p>
*
* @return: void
* @Author: syt
* @Date: 2020/12/24/024 11:38
*/
List<TreeEntity> tree();
/**
* <p>Description: 获取有关行业分类的</p>
*
* @return: void
* @Author: syt
* @Date: 2020/12/24/024 11:38
*/
List<TreeEntity> knowledgeTree();
}
|
/*
* Copyright © 2019 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.zuora.objects;
import com.google.gson.annotations.SerializedName;
import io.cdap.cdap.api.data.schema.Schema;
import io.cdap.plugin.zuora.restobjects.annotations.ObjectDefinition;
import io.cdap.plugin.zuora.restobjects.annotations.ObjectFieldDefinition;
import io.cdap.plugin.zuora.restobjects.objects.BaseObject;
import javax.annotation.Nullable;
/**
* Object name: PUTPublicEmailTemplateRequest (PUTPublicEmailTemplateRequest)
* Related objects:
**/
@SuppressWarnings("unused")
@ObjectDefinition(
Name = "PUTPublicEmailTemplateRequest",
ObjectType = ObjectDefinition.ObjectDefinitionType.NESTED
)
public class PUTPublicEmailTemplateRequest extends BaseObject {
/**
* Name: active (active), Type: boolean
* Options (custom, update, select): false, false, false
**/
@Nullable
@SerializedName("active")
@ObjectFieldDefinition(FieldType = Schema.Type.BOOLEAN)
private Boolean active;
/**
* Name: bccEmailAddress (bccEmailAddress), Type: string
* Options (custom, update, select): false, false, false
**/
@Nullable
@SerializedName("bccEmailAddress")
@ObjectFieldDefinition(FieldType = Schema.Type.STRING)
private String bccEmailAddress;
/**
* Name: ccEmailAddress (ccEmailAddress), Type: string
* Options (custom, update, select): false, false, false
**/
@Nullable
@SerializedName("ccEmailAddress")
@ObjectFieldDefinition(FieldType = Schema.Type.STRING)
private String ccEmailAddress;
/**
* Name: ccEmailType (ccEmailType), Type: string
* Options (custom, update, select): false, false, false
**/
@Nullable
@SerializedName("ccEmailType")
@ObjectFieldDefinition(FieldType = Schema.Type.STRING)
private String ccEmailType;
/**
* Name: description (description), Type: string
* Options (custom, update, select): false, false, false
**/
@Nullable
@SerializedName("description")
@ObjectFieldDefinition(FieldType = Schema.Type.STRING)
private String description;
/**
* Name: emailBody (emailBody), Type: string
* Options (custom, update, select): false, false, false
**/
@Nullable
@SerializedName("emailBody")
@ObjectFieldDefinition(FieldType = Schema.Type.STRING)
private String emailBody;
/**
* Name: emailSubject (emailSubject), Type: string
* Options (custom, update, select): false, false, false
**/
@Nullable
@SerializedName("emailSubject")
@ObjectFieldDefinition(FieldType = Schema.Type.STRING)
private String emailSubject;
/**
* Name: encodingType (encodingType), Type: string
* Options (custom, update, select): false, false, false
**/
@Nullable
@SerializedName("encodingType")
@ObjectFieldDefinition(FieldType = Schema.Type.STRING)
private String encodingType;
/**
* Name: fromEmailAddress (fromEmailAddress), Type: string
* Options (custom, update, select): false, false, false
**/
@Nullable
@SerializedName("fromEmailAddress")
@ObjectFieldDefinition(FieldType = Schema.Type.STRING)
private String fromEmailAddress;
/**
* Name: fromEmailType (fromEmailType), Type: string
* Options (custom, update, select): false, false, false
**/
@Nullable
@SerializedName("fromEmailType")
@ObjectFieldDefinition(FieldType = Schema.Type.STRING)
private String fromEmailType;
/**
* Name: fromName (fromName), Type: string
* Options (custom, update, select): false, false, false
**/
@Nullable
@SerializedName("fromName")
@ObjectFieldDefinition(FieldType = Schema.Type.STRING)
private String fromName;
/**
* Name: isHtml (isHtml), Type: boolean
* Options (custom, update, select): false, false, false
**/
@Nullable
@SerializedName("isHtml")
@ObjectFieldDefinition(FieldType = Schema.Type.BOOLEAN)
private Boolean isHtml;
/**
* Name: name (name), Type: string
* Options (custom, update, select): false, false, false
**/
@Nullable
@SerializedName("name")
@ObjectFieldDefinition(FieldType = Schema.Type.STRING)
private String name;
/**
* Name: replyToEmailAddress (replyToEmailAddress), Type: string
* Options (custom, update, select): false, false, false
**/
@Nullable
@SerializedName("replyToEmailAddress")
@ObjectFieldDefinition(FieldType = Schema.Type.STRING)
private String replyToEmailAddress;
/**
* Name: replyToEmailType (replyToEmailType), Type: string
* Options (custom, update, select): false, false, false
**/
@Nullable
@SerializedName("replyToEmailType")
@ObjectFieldDefinition(FieldType = Schema.Type.STRING)
private String replyToEmailType;
/**
* Name: toEmailAddress (toEmailAddress), Type: string
* Options (custom, update, select): false, false, false
**/
@Nullable
@SerializedName("toEmailAddress")
@ObjectFieldDefinition(FieldType = Schema.Type.STRING)
private String toEmailAddress;
/**
* Name: toEmailType (toEmailType), Type: string
* Options (custom, update, select): false, false, false
**/
@Nullable
@SerializedName("toEmailType")
@ObjectFieldDefinition(FieldType = Schema.Type.STRING)
private String toEmailType;
@Override
public void addFields() {
addCustomField("active", active, Boolean.class);
addCustomField("bccEmailAddress", bccEmailAddress, String.class);
addCustomField("ccEmailAddress", ccEmailAddress, String.class);
addCustomField("ccEmailType", ccEmailType, String.class);
addCustomField("description", description, String.class);
addCustomField("emailBody", emailBody, String.class);
addCustomField("emailSubject", emailSubject, String.class);
addCustomField("encodingType", encodingType, String.class);
addCustomField("fromEmailAddress", fromEmailAddress, String.class);
addCustomField("fromEmailType", fromEmailType, String.class);
addCustomField("fromName", fromName, String.class);
addCustomField("isHtml", isHtml, Boolean.class);
addCustomField("name", name, String.class);
addCustomField("replyToEmailAddress", replyToEmailAddress, String.class);
addCustomField("replyToEmailType", replyToEmailType, String.class);
addCustomField("toEmailAddress", toEmailAddress, String.class);
addCustomField("toEmailType", toEmailType, String.class);
}
}
|
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.ui.repository.repositoryexplorer.model;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.repository.RepositoryDirectory;
import org.pentaho.di.repository.RepositoryElementMetaInterface;
public class UITransformation extends UIRepositoryContent {
private static final long serialVersionUID = 3826725834758429573L;
public UITransformation() {
}
public UITransformation( RepositoryElementMetaInterface rc, UIRepositoryDirectory parent, Repository rep ) {
super( rc, parent, rep );
}
@Override
public void setName( String name ) throws Exception {
super.setName( name );
renameTransformation( this.getObjectId(), getRepositoryDirectory(), name );
uiParent.fireCollectionChanged();
}
protected ObjectId renameTransformation( ObjectId objectId, RepositoryDirectory directory, String name )
throws Exception {
return rep.renameTransformation( this.getObjectId(), getRepositoryDirectory(), name );
}
public void delete() throws Exception {
rep.deleteTransformation( this.getObjectId() );
if ( uiParent.getRepositoryObjects().contains( this ) ) {
uiParent.getRepositoryObjects().remove( this );
}
}
public void move( UIRepositoryDirectory newParentDir ) throws KettleException {
if ( newParentDir != null ) {
rep.renameTransformation( obj.getObjectId(), newParentDir.getDirectory(), null );
newParentDir.refresh();
}
}
}
|
// Targeted by JavaCPP version 1.5.7: DO NOT EDIT THIS FILE
package org.bytedeco.pytorch;
import org.bytedeco.pytorch.Allocator;
import org.bytedeco.pytorch.Function;
import org.bytedeco.pytorch.Module;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.javacpp.presets.javacpp.*;
import static org.bytedeco.openblas.global.openblas_nolapack.*;
import static org.bytedeco.openblas.global.openblas.*;
import static org.bytedeco.pytorch.global.torch.*;
@Name("std::vector<c10::optional<torch::jit::Operator> >") @Properties(inherit = org.bytedeco.pytorch.presets.torch.class)
public class OperatorOptionalVector extends Pointer {
static { Loader.load(); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public OperatorOptionalVector(Pointer p) { super(p); }
public OperatorOptionalVector(OperatorOptional value) { this(1); put(0, value); }
public OperatorOptionalVector(OperatorOptional ... array) { this(array.length); put(array); }
public OperatorOptionalVector() { allocate(); }
public OperatorOptionalVector(long n) { allocate(n); }
private native void allocate();
private native void allocate(@Cast("size_t") long n);
public native @Name("operator =") @ByRef OperatorOptionalVector put(@ByRef OperatorOptionalVector x);
public boolean empty() { return size() == 0; }
public native long size();
public void clear() { resize(0); }
public native void resize(@Cast("size_t") long n);
@Index(function = "at") public native @ByRef OperatorOptional get(@Cast("size_t") long i);
public native OperatorOptionalVector put(@Cast("size_t") long i, OperatorOptional value);
public native @ByVal Iterator insert(@ByVal Iterator pos, @ByRef OperatorOptional value);
public native @ByVal Iterator erase(@ByVal Iterator pos);
public native @ByVal Iterator begin();
public native @ByVal Iterator end();
@NoOffset @Name("iterator") public static class Iterator extends Pointer {
public Iterator(Pointer p) { super(p); }
public Iterator() { }
public native @Name("operator ++") @ByRef Iterator increment();
public native @Name("operator ==") boolean equals(@ByRef Iterator it);
public native @Name("operator *") @ByRef @Const OperatorOptional get();
}
public OperatorOptional[] get() {
OperatorOptional[] array = new OperatorOptional[size() < Integer.MAX_VALUE ? (int)size() : Integer.MAX_VALUE];
for (int i = 0; i < array.length; i++) {
array[i] = get(i);
}
return array;
}
@Override public String toString() {
return java.util.Arrays.toString(get());
}
public OperatorOptional pop_back() {
long size = size();
OperatorOptional value = get(size - 1);
resize(size - 1);
return value;
}
public OperatorOptionalVector push_back(OperatorOptional value) {
long size = size();
resize(size + 1);
return put(size, value);
}
public OperatorOptionalVector put(OperatorOptional value) {
if (size() != 1) { resize(1); }
return put(0, value);
}
public OperatorOptionalVector put(OperatorOptional ... array) {
if (size() != array.length) { resize(array.length); }
for (int i = 0; i < array.length; i++) {
put(i, array[i]);
}
return this;
}
}
|
/*
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package goodman.java.awt.geom;
import goodman.java.awt.geom.*;
import goodman.java.io.Serializable;
/**
* <CODE>Arc2D</CODE> is the abstract superclass for all objects that
* store a 2D arc defined by a framing rectangle,
* start angle, angular extent (length of the arc), and a closure type
* (<CODE>OPEN</CODE>, <CODE>CHORD</CODE>, or <CODE>PIE</CODE>).
* <p>
* <a name="inscribes">
* The arc is a partial section of a full ellipse which
* inscribes the framing rectangle of its parent {@link RectangularShape}.
* </a>
* <a name="angles">
* The angles are specified relative to the non-square
* framing rectangle such that 45 degrees always falls on the line from
* the center of the ellipse to the upper right corner of the framing
* rectangle.
* As a result, if the framing rectangle is noticeably longer along one
* axis than the other, the angles to the start and end of the arc segment
* will be skewed farther along the longer axis of the frame.
* </a>
* <p>
* The actual storage representation of the coordinates is left to
* the subclass.
*
* @author Jim Graham
* @since 1.2
*/
public abstract class Arc2D extends RectangularShape {
/**
* The closure type for an open arc with no path segments
* connecting the two ends of the arc segment.
* @since 1.2
*/
public final static int OPEN = 0;
/**
* The closure type for an arc closed by drawing a straight
* line segment from the start of the arc segment to the end of the
* arc segment.
* @since 1.2
*/
public final static int CHORD = 1;
/**
* The closure type for an arc closed by drawing straight line
* segments from the start of the arc segment to the center
* of the full ellipse and from that point to the end of the arc segment.
* @since 1.2
*/
public final static int PIE = 2;
/**
* This class defines an arc specified in {@code float} precision.
* @since 1.2
*/
public static class Float extends Arc2D implements Serializable {
/**
* The X coordinate of the upper-left corner of the framing
* rectangle of the arc.
* @since 1.2
* @serial
*/
public float x;
/**
* The Y coordinate of the upper-left corner of the framing
* rectangle of the arc.
* @since 1.2
* @serial
*/
public float y;
/**
* The overall width of the full ellipse of which this arc is
* a partial section (not considering the
* angular extents).
* @since 1.2
* @serial
*/
public float width;
/**
* The overall height of the full ellipse of which this arc is
* a partial section (not considering the
* angular extents).
* @since 1.2
* @serial
*/
public float height;
/**
* The starting angle of the arc in degrees.
* @since 1.2
* @serial
*/
public float start;
/**
* The angular extent of the arc in degrees.
* @since 1.2
* @serial
*/
public float extent;
/**
* Constructs a new OPEN arc, initialized to location (0, 0),
* size (0, 0), angular extents (start = 0, extent = 0).
* @since 1.2
*/
public Float() {
super(OPEN);
}
/**
* Constructs a new arc, initialized to location (0, 0),
* size (0, 0), angular extents (start = 0, extent = 0), and
* the specified closure type.
*
* @param type The closure type for the arc:
* {@link #OPEN}, {@link #CHORD}, or {@link #PIE}.
* @since 1.2
*/
public Float(int type) {
super(type);
}
/**
* Constructs a new arc, initialized to the specified location,
* size, angular extents, and closure type.
*
* @param x The X coordinate of the upper-left corner of
* the arc's framing rectangle.
* @param y The Y coordinate of the upper-left corner of
* the arc's framing rectangle.
* @param w The overall width of the full ellipse of which
* this arc is a partial section.
* @param h The overall height of the full ellipse of which this
* arc is a partial section.
* @param start The starting angle of the arc in degrees.
* @param extent The angular extent of the arc in degrees.
* @param type The closure type for the arc:
* {@link #OPEN}, {@link #CHORD}, or {@link #PIE}.
* @since 1.2
*/
public Float(float x, float y, float w, float h,
float start, float extent, int type) {
super(type);
this.x = x;
this.y = y;
this.width = w;
this.height = h;
this.start = start;
this.extent = extent;
}
/**
* Constructs a new arc, initialized to the specified location,
* size, angular extents, and closure type.
*
* @param ellipseBounds The framing rectangle that defines the
* outer boundary of the full ellipse of which this arc is a
* partial section.
* @param start The starting angle of the arc in degrees.
* @param extent The angular extent of the arc in degrees.
* @param type The closure type for the arc:
* {@link #OPEN}, {@link #CHORD}, or {@link #PIE}.
* @since 1.2
*/
public Float(Rectangle2D ellipseBounds,
float start, float extent, int type) {
super(type);
this.x = (float) ellipseBounds.getX();
this.y = (float) ellipseBounds.getY();
this.width = (float) ellipseBounds.getWidth();
this.height = (float) ellipseBounds.getHeight();
this.start = start;
this.extent = extent;
}
/**
* {@inheritDoc}
* Note that the arc
* <a href="Arc2D.html#inscribes">partially inscribes</a>
* the framing rectangle of this {@code RectangularShape}.
*
* @since 1.2
*/
public double getX() {
return (double) x;
}
/**
* {@inheritDoc}
* Note that the arc
* <a href="Arc2D.html#inscribes">partially inscribes</a>
* the framing rectangle of this {@code RectangularShape}.
*
* @since 1.2
*/
public double getY() {
return (double) y;
}
/**
* {@inheritDoc}
* Note that the arc
* <a href="Arc2D.html#inscribes">partially inscribes</a>
* the framing rectangle of this {@code RectangularShape}.
*
* @since 1.2
*/
public double getWidth() {
return (double) width;
}
/**
* {@inheritDoc}
* Note that the arc
* <a href="Arc2D.html#inscribes">partially inscribes</a>
* the framing rectangle of this {@code RectangularShape}.
*
* @since 1.2
*/
public double getHeight() {
return (double) height;
}
/**
* {@inheritDoc}
* @since 1.2
*/
public double getAngleStart() {
return (double) start;
}
/**
* {@inheritDoc}
* @since 1.2
*/
public double getAngleExtent() {
return (double) extent;
}
/**
* {@inheritDoc}
* @since 1.2
*/
public boolean isEmpty() {
return (width <= 0.0 || height <= 0.0);
}
/**
* {@inheritDoc}
* @since 1.2
*/
public void setArc(double x, double y, double w, double h,
double angSt, double angExt, int closure) {
this.setArcType(closure);
this.x = (float) x;
this.y = (float) y;
this.width = (float) w;
this.height = (float) h;
this.start = (float) angSt;
this.extent = (float) angExt;
}
/**
* {@inheritDoc}
* @since 1.2
*/
public void setAngleStart(double angSt) {
this.start = (float) angSt;
}
/**
* {@inheritDoc}
* @since 1.2
*/
public void setAngleExtent(double angExt) {
this.extent = (float) angExt;
}
/**
* {@inheritDoc}
* @since 1.2
*/
protected Rectangle2D makeBounds(double x, double y,
double w, double h) {
return new Rectangle2D.Float((float) x, (float) y,
(float) w, (float) h);
}
/*
* JDK 1.6 serialVersionUID
*/
private static final long serialVersionUID = 9130893014586380278L;
/**
* Writes the default serializable fields to the
* <code>ObjectOutputStream</code> followed by a byte
* indicating the arc type of this <code>Arc2D</code>
* instance.
*
* @serialData
* <ol>
* <li>The default serializable fields.
* <li>
* followed by a <code>byte</code> indicating the arc type
* {@link #OPEN}, {@link #CHORD}, or {@link #PIE}.
* </ol>
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException
{
s.defaultWriteObject();
s.writeByte(getArcType());
}
/**
* Reads the default serializable fields from the
* <code>ObjectInputStream</code> followed by a byte
* indicating the arc type of this <code>Arc2D</code>
* instance.
*
* @serialData
* <ol>
* <li>The default serializable fields.
* <li>
* followed by a <code>byte</code> indicating the arc type
* {@link #OPEN}, {@link #CHORD}, or {@link #PIE}.
* </ol>
*/
private void readObject(java.io.ObjectInputStream s)
throws ClassNotFoundException, java.io.IOException
{
s.defaultReadObject();
try {
setArcType(s.readByte());
} catch (IllegalArgumentException iae) {
throw new java.io.InvalidObjectException(iae.getMessage());
}
}
}
/**
* This class defines an arc specified in {@code double} precision.
* @since 1.2
*/
public static class Double extends Arc2D implements Serializable {
/**
* The X coordinate of the upper-left corner of the framing
* rectangle of the arc.
* @since 1.2
* @serial
*/
public double x;
/**
* The Y coordinate of the upper-left corner of the framing
* rectangle of the arc.
* @since 1.2
* @serial
*/
public double y;
/**
* The overall width of the full ellipse of which this arc is
* a partial section (not considering the angular extents).
* @since 1.2
* @serial
*/
public double width;
/**
* The overall height of the full ellipse of which this arc is
* a partial section (not considering the angular extents).
* @since 1.2
* @serial
*/
public double height;
/**
* The starting angle of the arc in degrees.
* @since 1.2
* @serial
*/
public double start;
/**
* The angular extent of the arc in degrees.
* @since 1.2
* @serial
*/
public double extent;
/**
* Constructs a new OPEN arc, initialized to location (0, 0),
* size (0, 0), angular extents (start = 0, extent = 0).
* @since 1.2
*/
public Double() {
super(OPEN);
}
/**
* Constructs a new arc, initialized to location (0, 0),
* size (0, 0), angular extents (start = 0, extent = 0), and
* the specified closure type.
*
* @param type The closure type for the arc:
* {@link #OPEN}, {@link #CHORD}, or {@link #PIE}.
* @since 1.2
*/
public Double(int type) {
super(type);
}
/**
* Constructs a new arc, initialized to the specified location,
* size, angular extents, and closure type.
*
* @param x The X coordinate of the upper-left corner
* of the arc's framing rectangle.
* @param y The Y coordinate of the upper-left corner
* of the arc's framing rectangle.
* @param w The overall width of the full ellipse of which this
* arc is a partial section.
* @param h The overall height of the full ellipse of which this
* arc is a partial section.
* @param start The starting angle of the arc in degrees.
* @param extent The angular extent of the arc in degrees.
* @param type The closure type for the arc:
* {@link #OPEN}, {@link #CHORD}, or {@link #PIE}.
* @since 1.2
*/
public Double(double x, double y, double w, double h,
double start, double extent, int type) {
super(type);
this.x = x;
this.y = y;
this.width = w;
this.height = h;
this.start = start;
this.extent = extent;
}
/**
* Constructs a new arc, initialized to the specified location,
* size, angular extents, and closure type.
*
* @param ellipseBounds The framing rectangle that defines the
* outer boundary of the full ellipse of which this arc is a
* partial section.
* @param start The starting angle of the arc in degrees.
* @param extent The angular extent of the arc in degrees.
* @param type The closure type for the arc:
* {@link #OPEN}, {@link #CHORD}, or {@link #PIE}.
* @since 1.2
*/
public Double(Rectangle2D ellipseBounds,
double start, double extent, int type) {
super(type);
this.x = ellipseBounds.getX();
this.y = ellipseBounds.getY();
this.width = ellipseBounds.getWidth();
this.height = ellipseBounds.getHeight();
this.start = start;
this.extent = extent;
}
/**
* {@inheritDoc}
* Note that the arc
* <a href="Arc2D.html#inscribes">partially inscribes</a>
* the framing rectangle of this {@code RectangularShape}.
*
* @since 1.2
*/
public double getX() {
return x;
}
/**
* {@inheritDoc}
* Note that the arc
* <a href="Arc2D.html#inscribes">partially inscribes</a>
* the framing rectangle of this {@code RectangularShape}.
*
* @since 1.2
*/
public double getY() {
return y;
}
/**
* {@inheritDoc}
* Note that the arc
* <a href="Arc2D.html#inscribes">partially inscribes</a>
* the framing rectangle of this {@code RectangularShape}.
*
* @since 1.2
*/
public double getWidth() {
return width;
}
/**
* {@inheritDoc}
* Note that the arc
* <a href="Arc2D.html#inscribes">partially inscribes</a>
* the framing rectangle of this {@code RectangularShape}.
*
* @since 1.2
*/
public double getHeight() {
return height;
}
/**
* {@inheritDoc}
* @since 1.2
*/
public double getAngleStart() {
return start;
}
/**
* {@inheritDoc}
* @since 1.2
*/
public double getAngleExtent() {
return extent;
}
/**
* {@inheritDoc}
* @since 1.2
*/
public boolean isEmpty() {
return (width <= 0.0 || height <= 0.0);
}
/**
* {@inheritDoc}
* @since 1.2
*/
public void setArc(double x, double y, double w, double h,
double angSt, double angExt, int closure) {
this.setArcType(closure);
this.x = x;
this.y = y;
this.width = w;
this.height = h;
this.start = angSt;
this.extent = angExt;
}
/**
* {@inheritDoc}
* @since 1.2
*/
public void setAngleStart(double angSt) {
this.start = angSt;
}
/**
* {@inheritDoc}
* @since 1.2
*/
public void setAngleExtent(double angExt) {
this.extent = angExt;
}
/**
* {@inheritDoc}
* @since 1.2
*/
protected Rectangle2D makeBounds(double x, double y,
double w, double h) {
return new Rectangle2D.Double(x, y, w, h);
}
/*
* JDK 1.6 serialVersionUID
*/
private static final long serialVersionUID = 728264085846882001L;
/**
* Writes the default serializable fields to the
* <code>ObjectOutputStream</code> followed by a byte
* indicating the arc type of this <code>Arc2D</code>
* instance.
*
* @serialData
* <ol>
* <li>The default serializable fields.
* <li>
* followed by a <code>byte</code> indicating the arc type
* {@link #OPEN}, {@link #CHORD}, or {@link #PIE}.
* </ol>
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException
{
s.defaultWriteObject();
s.writeByte(getArcType());
}
/**
* Reads the default serializable fields from the
* <code>ObjectInputStream</code> followed by a byte
* indicating the arc type of this <code>Arc2D</code>
* instance.
*
* @serialData
* <ol>
* <li>The default serializable fields.
* <li>
* followed by a <code>byte</code> indicating the arc type
* {@link #OPEN}, {@link #CHORD}, or {@link #PIE}.
* </ol>
*/
private void readObject(java.io.ObjectInputStream s)
throws ClassNotFoundException, java.io.IOException
{
s.defaultReadObject();
try {
setArcType(s.readByte());
} catch (IllegalArgumentException iae) {
throw new java.io.InvalidObjectException(iae.getMessage());
}
}
}
private int type;
/**
* This is an abstract class that cannot be instantiated directly.
* Type-specific implementation subclasses are available for
* instantiation and provide a number of formats for storing
* the information necessary to satisfy the various accessor
* methods below.
* <p>
* This constructor creates an object with a default closure
* type of {@link #OPEN}. It is provided only to enable
* serialization of subclasses.
*
* @see java.awt.geom.Arc2D.Float
* @see java.awt.geom.Arc2D.Double
*/
protected Arc2D() {
this(OPEN);
}
/**
* This is an abstract class that cannot be instantiated directly.
* Type-specific implementation subclasses are available for
* instantiation and provide a number of formats for storing
* the information necessary to satisfy the various accessor
* methods below.
*
* @param type The closure type of this arc:
* {@link #OPEN}, {@link #CHORD}, or {@link #PIE}.
* @see java.awt.geom.Arc2D.Float
* @see java.awt.geom.Arc2D.Double
* @since 1.2
*/
protected Arc2D(int type) {
setArcType(type);
}
/**
* Returns the starting angle of the arc.
*
* @return A double value that represents the starting angle
* of the arc in degrees.
* @see #setAngleStart
* @since 1.2
*/
public abstract double getAngleStart();
/**
* Returns the angular extent of the arc.
*
* @return A double value that represents the angular extent
* of the arc in degrees.
* @see #setAngleExtent
* @since 1.2
*/
public abstract double getAngleExtent();
/**
* Returns the arc closure type of the arc: {@link #OPEN},
* {@link #CHORD}, or {@link #PIE}.
* @return One of the integer constant closure types defined
* in this class.
* @see #setArcType
* @since 1.2
*/
public int getArcType() {
return type;
}
/**
* Returns the starting point of the arc. This point is the
* intersection of the ray from the center defined by the
* starting angle and the elliptical boundary of the arc.
*
* @return A <CODE>Point2D</CODE> object representing the
* x,y coordinates of the starting point of the arc.
* @since 1.2
*/
public Point2D getStartPoint() {
double angle = Math.toRadians(-getAngleStart());
double x = getX() + (Math.cos(angle) * 0.5 + 0.5) * getWidth();
double y = getY() + (Math.sin(angle) * 0.5 + 0.5) * getHeight();
return new Point2D.Double(x, y);
}
/**
* Returns the ending point of the arc. This point is the
* intersection of the ray from the center defined by the
* starting angle plus the angular extent of the arc and the
* elliptical boundary of the arc.
*
* @return A <CODE>Point2D</CODE> object representing the
* x,y coordinates of the ending point of the arc.
* @since 1.2
*/
public Point2D getEndPoint() {
double angle = Math.toRadians(-getAngleStart() - getAngleExtent());
double x = getX() + (Math.cos(angle) * 0.5 + 0.5) * getWidth();
double y = getY() + (Math.sin(angle) * 0.5 + 0.5) * getHeight();
return new Point2D.Double(x, y);
}
/**
* Sets the location, size, angular extents, and closure type of
* this arc to the specified double values.
*
* @param x The X coordinate of the upper-left corner of the arc.
* @param y The Y coordinate of the upper-left corner of the arc.
* @param w The overall width of the full ellipse of which
* this arc is a partial section.
* @param h The overall height of the full ellipse of which
* this arc is a partial section.
* @param angSt The starting angle of the arc in degrees.
* @param angExt The angular extent of the arc in degrees.
* @param closure The closure type for the arc:
* {@link #OPEN}, {@link #CHORD}, or {@link #PIE}.
* @since 1.2
*/
public abstract void setArc(double x, double y, double w, double h,
double angSt, double angExt, int closure);
/**
* Sets the location, size, angular extents, and closure type of
* this arc to the specified values.
*
* @param loc The <CODE>Point2D</CODE> representing the coordinates of
* the upper-left corner of the arc.
* @param size The <CODE>Dimension2D</CODE> representing the width
* and height of the full ellipse of which this arc is
* a partial section.
* @param angSt The starting angle of the arc in degrees.
* @param angExt The angular extent of the arc in degrees.
* @param closure The closure type for the arc:
* {@link #OPEN}, {@link #CHORD}, or {@link #PIE}.
* @since 1.2
*/
public void setArc(Point2D loc, Dimension2D size,
double angSt, double angExt, int closure) {
setArc(loc.getX(), loc.getY(), size.getWidth(), size.getHeight(),
angSt, angExt, closure);
}
/**
* Sets the location, size, angular extents, and closure type of
* this arc to the specified values.
*
* @param rect The framing rectangle that defines the
* outer boundary of the full ellipse of which this arc is a
* partial section.
* @param angSt The starting angle of the arc in degrees.
* @param angExt The angular extent of the arc in degrees.
* @param closure The closure type for the arc:
* {@link #OPEN}, {@link #CHORD}, or {@link #PIE}.
* @since 1.2
*/
public void setArc(Rectangle2D rect, double angSt, double angExt,
int closure) {
setArc(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight(),
angSt, angExt, closure);
}
/**
* Sets this arc to be the same as the specified arc.
*
* @param a The <CODE>Arc2D</CODE> to use to set the arc's values.
* @since 1.2
*/
public void setArc(Arc2D a) {
setArc(a.getX(), a.getY(), a.getWidth(), a.getHeight(),
a.getAngleStart(), a.getAngleExtent(), a.type);
}
/**
* Sets the position, bounds, angular extents, and closure type of
* this arc to the specified values. The arc is defined by a center
* point and a radius rather than a framing rectangle for the full ellipse.
*
* @param x The X coordinate of the center of the arc.
* @param y The Y coordinate of the center of the arc.
* @param radius The radius of the arc.
* @param angSt The starting angle of the arc in degrees.
* @param angExt The angular extent of the arc in degrees.
* @param closure The closure type for the arc:
* {@link #OPEN}, {@link #CHORD}, or {@link #PIE}.
* @since 1.2
*/
public void setArcByCenter(double x, double y, double radius,
double angSt, double angExt, int closure) {
setArc(x - radius, y - radius, radius * 2.0, radius * 2.0,
angSt, angExt, closure);
}
/**
* Sets the position, bounds, and angular extents of this arc to the
* specified value. The starting angle of the arc is tangent to the
* line specified by points (p1, p2), the ending angle is tangent to
* the line specified by points (p2, p3), and the arc has the
* specified radius.
*
* @param p1 The first point that defines the arc. The starting
* angle of the arc is tangent to the line specified by points (p1, p2).
* @param p2 The second point that defines the arc. The starting
* angle of the arc is tangent to the line specified by points (p1, p2).
* The ending angle of the arc is tangent to the line specified by
* points (p2, p3).
* @param p3 The third point that defines the arc. The ending angle
* of the arc is tangent to the line specified by points (p2, p3).
* @param radius The radius of the arc.
* @since 1.2
*/
public void setArcByTangent(Point2D p1, Point2D p2, Point2D p3,
double radius) {
double ang1 = Math.atan2(p1.getY() - p2.getY(),
p1.getX() - p2.getX());
double ang2 = Math.atan2(p3.getY() - p2.getY(),
p3.getX() - p2.getX());
double diff = ang2 - ang1;
if (diff > Math.PI) {
ang2 -= Math.PI * 2.0;
} else if (diff < -Math.PI) {
ang2 += Math.PI * 2.0;
}
double bisect = (ang1 + ang2) / 2.0;
double theta = Math.abs(ang2 - bisect);
double dist = radius / Math.sin(theta);
double x = p2.getX() + dist * Math.cos(bisect);
double y = p2.getY() + dist * Math.sin(bisect);
// REMIND: This needs some work...
if (ang1 < ang2) {
ang1 -= Math.PI / 2.0;
ang2 += Math.PI / 2.0;
} else {
ang1 += Math.PI / 2.0;
ang2 -= Math.PI / 2.0;
}
ang1 = Math.toDegrees(-ang1);
ang2 = Math.toDegrees(-ang2);
diff = ang2 - ang1;
if (diff < 0) {
diff += 360;
} else {
diff -= 360;
}
setArcByCenter(x, y, radius, ang1, diff, type);
}
/**
* Sets the starting angle of this arc to the specified double
* value.
*
* @param angSt The starting angle of the arc in degrees.
* @see #getAngleStart
* @since 1.2
*/
public abstract void setAngleStart(double angSt);
/**
* Sets the angular extent of this arc to the specified double
* value.
*
* @param angExt The angular extent of the arc in degrees.
* @see #getAngleExtent
* @since 1.2
*/
public abstract void setAngleExtent(double angExt);
/**
* Sets the starting angle of this arc to the angle that the
* specified point defines relative to the center of this arc.
* The angular extent of the arc will remain the same.
*
* @param p The <CODE>Point2D</CODE> that defines the starting angle.
* @see #getAngleStart
* @since 1.2
*/
public void setAngleStart(Point2D p) {
// Bias the dx and dy by the height and width of the oval.
double dx = getHeight() * (p.getX() - getCenterX());
double dy = getWidth() * (p.getY() - getCenterY());
setAngleStart(-Math.toDegrees(Math.atan2(dy, dx)));
}
/**
* Sets the starting angle and angular extent of this arc using two
* sets of coordinates. The first set of coordinates is used to
* determine the angle of the starting point relative to the arc's
* center. The second set of coordinates is used to determine the
* angle of the end point relative to the arc's center.
* The arc will always be non-empty and extend counterclockwise
* from the first point around to the second point.
*
* @param x1 The X coordinate of the arc's starting point.
* @param y1 The Y coordinate of the arc's starting point.
* @param x2 The X coordinate of the arc's ending point.
* @param y2 The Y coordinate of the arc's ending point.
* @since 1.2
*/
public void setAngles(double x1, double y1, double x2, double y2) {
double x = getCenterX();
double y = getCenterY();
double w = getWidth();
double h = getHeight();
// Note: reversing the Y equations negates the angle to adjust
// for the upside down coordinate system.
// Also we should bias atans by the height and width of the oval.
double ang1 = Math.atan2(w * (y - y1), h * (x1 - x));
double ang2 = Math.atan2(w * (y - y2), h * (x2 - x));
ang2 -= ang1;
if (ang2 <= 0.0) {
ang2 += Math.PI * 2.0;
}
setAngleStart(Math.toDegrees(ang1));
setAngleExtent(Math.toDegrees(ang2));
}
/**
* Sets the starting angle and angular extent of this arc using
* two points. The first point is used to determine the angle of
* the starting point relative to the arc's center.
* The second point is used to determine the angle of the end point
* relative to the arc's center.
* The arc will always be non-empty and extend counterclockwise
* from the first point around to the second point.
*
* @param p1 The <CODE>Point2D</CODE> that defines the arc's
* starting point.
* @param p2 The <CODE>Point2D</CODE> that defines the arc's
* ending point.
* @since 1.2
*/
public void setAngles(Point2D p1, Point2D p2) {
setAngles(p1.getX(), p1.getY(), p2.getX(), p2.getY());
}
/**
* Sets the closure type of this arc to the specified value:
* <CODE>OPEN</CODE>, <CODE>CHORD</CODE>, or <CODE>PIE</CODE>.
*
* @param type The integer constant that represents the closure
* type of this arc: {@link #OPEN}, {@link #CHORD}, or
* {@link #PIE}.
*
* @throws IllegalArgumentException if <code>type</code> is not
* 0, 1, or 2.+
* @see #getArcType
* @since 1.2
*/
public void setArcType(int type) {
if (type < OPEN || type > PIE) {
throw new IllegalArgumentException("invalid type for Arc: "+type);
}
this.type = type;
}
/**
* {@inheritDoc}
* Note that the arc
* <a href="Arc2D.html#inscribes">partially inscribes</a>
* the framing rectangle of this {@code RectangularShape}.
*
* @since 1.2
*/
public void setFrame(double x, double y, double w, double h) {
setArc(x, y, w, h, getAngleStart(), getAngleExtent(), type);
}
/**
* Returns the high-precision framing rectangle of the arc. The framing
* rectangle contains only the part of this <code>Arc2D</code> that is
* in between the starting and ending angles and contains the pie
* wedge, if this <code>Arc2D</code> has a <code>PIE</code> closure type.
* <p>
* This method differs from the
* {@link RectangularShape#getBounds() getBounds} in that the
* <code>getBounds</code> method only returns the bounds of the
* enclosing ellipse of this <code>Arc2D</code> without considering
* the starting and ending angles of this <code>Arc2D</code>.
*
* @return the <CODE>Rectangle2D</CODE> that represents the arc's
* framing rectangle.
* @since 1.2
*/
public Rectangle2D getBounds2D() {
if (isEmpty()) {
return makeBounds(getX(), getY(), getWidth(), getHeight());
}
double x1, y1, x2, y2;
if (getArcType() == PIE) {
x1 = y1 = x2 = y2 = 0.0;
} else {
x1 = y1 = 1.0;
x2 = y2 = -1.0;
}
double angle = 0.0;
for (int i = 0; i < 6; i++) {
if (i < 4) {
// 0-3 are the four quadrants
angle += 90.0;
if (!containsAngle(angle)) {
continue;
}
} else if (i == 4) {
// 4 is start angle
angle = getAngleStart();
} else {
// 5 is end angle
angle += getAngleExtent();
}
double rads = Math.toRadians(-angle);
double xe = Math.cos(rads);
double ye = Math.sin(rads);
x1 = Math.min(x1, xe);
y1 = Math.min(y1, ye);
x2 = Math.max(x2, xe);
y2 = Math.max(y2, ye);
}
double w = getWidth();
double h = getHeight();
x2 = (x2 - x1) * 0.5 * w;
y2 = (y2 - y1) * 0.5 * h;
x1 = getX() + (x1 * 0.5 + 0.5) * w;
y1 = getY() + (y1 * 0.5 + 0.5) * h;
return makeBounds(x1, y1, x2, y2);
}
/**
* Constructs a <code>Rectangle2D</code> of the appropriate precision
* to hold the parameters calculated to be the framing rectangle
* of this arc.
*
* @param x The X coordinate of the upper-left corner of the
* framing rectangle.
* @param y The Y coordinate of the upper-left corner of the
* framing rectangle.
* @param w The width of the framing rectangle.
* @param h The height of the framing rectangle.
* @return a <code>Rectangle2D</code> that is the framing rectangle
* of this arc.
* @since 1.2
*/
protected abstract Rectangle2D makeBounds(double x, double y,
double w, double h);
/*
* Normalizes the specified angle into the range -180 to 180.
*/
static double normalizeDegrees(double angle) {
if (angle > 180.0) {
if (angle <= (180.0 + 360.0)) {
angle = angle - 360.0;
} else {
angle = Math.IEEEremainder(angle, 360.0);
// IEEEremainder can return -180 here for some input values...
if (angle == -180.0) {
angle = 180.0;
}
}
} else if (angle <= -180.0) {
if (angle > (-180.0 - 360.0)) {
angle = angle + 360.0;
} else {
angle = Math.IEEEremainder(angle, 360.0);
// IEEEremainder can return -180 here for some input values...
if (angle == -180.0) {
angle = 180.0;
}
}
}
return angle;
}
/**
* Determines whether or not the specified angle is within the
* angular extents of the arc.
*
* @param angle The angle to test.
*
* @return <CODE>true</CODE> if the arc contains the angle,
* <CODE>false</CODE> if the arc doesn't contain the angle.
* @since 1.2
*/
public boolean containsAngle(double angle) {
double angExt = getAngleExtent();
boolean backwards = (angExt < 0.0);
if (backwards) {
angExt = -angExt;
}
if (angExt >= 360.0) {
return true;
}
angle = normalizeDegrees(angle) - normalizeDegrees(getAngleStart());
if (backwards) {
angle = -angle;
}
if (angle < 0.0) {
angle += 360.0;
}
return (angle >= 0.0) && (angle < angExt);
}
/**
* Determines whether or not the specified point is inside the boundary
* of the arc.
*
* @param x The X coordinate of the point to test.
* @param y The Y coordinate of the point to test.
*
* @return <CODE>true</CODE> if the point lies within the bound of
* the arc, <CODE>false</CODE> if the point lies outside of the
* arc's bounds.
* @since 1.2
*/
public boolean contains(double x, double y) {
// Normalize the coordinates compared to the ellipse
// having a center at 0,0 and a radius of 0.5.
double ellw = getWidth();
if (ellw <= 0.0) {
return false;
}
double normx = (x - getX()) / ellw - 0.5;
double ellh = getHeight();
if (ellh <= 0.0) {
return false;
}
double normy = (y - getY()) / ellh - 0.5;
double distSq = (normx * normx + normy * normy);
if (distSq >= 0.25) {
return false;
}
double angExt = Math.abs(getAngleExtent());
if (angExt >= 360.0) {
return true;
}
boolean inarc = containsAngle(-Math.toDegrees(Math.atan2(normy,
normx)));
if (type == PIE) {
return inarc;
}
// CHORD and OPEN behave the same way
if (inarc) {
if (angExt >= 180.0) {
return true;
}
// point must be outside the "pie triangle"
} else {
if (angExt <= 180.0) {
return false;
}
// point must be inside the "pie triangle"
}
// The point is inside the pie triangle iff it is on the same
// side of the line connecting the ends of the arc as the center.
double angle = Math.toRadians(-getAngleStart());
double x1 = Math.cos(angle);
double y1 = Math.sin(angle);
angle += Math.toRadians(-getAngleExtent());
double x2 = Math.cos(angle);
double y2 = Math.sin(angle);
boolean inside = (Line2D.relativeCCW(x1, y1, x2, y2, 2*normx, 2*normy) *
Line2D.relativeCCW(x1, y1, x2, y2, 0, 0) >= 0);
return inarc ? !inside : inside;
}
/**
* Determines whether or not the interior of the arc intersects
* the interior of the specified rectangle.
*
* @param x The X coordinate of the rectangle's upper-left corner.
* @param y The Y coordinate of the rectangle's upper-left corner.
* @param w The width of the rectangle.
* @param h The height of the rectangle.
*
* @return <CODE>true</CODE> if the arc intersects the rectangle,
* <CODE>false</CODE> if the arc doesn't intersect the rectangle.
* @since 1.2
*/
public boolean intersects(double x, double y, double w, double h) {
double aw = getWidth();
double ah = getHeight();
if ( w <= 0 || h <= 0 || aw <= 0 || ah <= 0 ) {
return false;
}
double ext = getAngleExtent();
if (ext == 0) {
return false;
}
double ax = getX();
double ay = getY();
double axw = ax + aw;
double ayh = ay + ah;
double xw = x + w;
double yh = y + h;
// check bbox
if (x >= axw || y >= ayh || xw <= ax || yh <= ay) {
return false;
}
// extract necessary data
double axc = getCenterX();
double ayc = getCenterY();
Point2D sp = getStartPoint();
Point2D ep = getEndPoint();
double sx = sp.getX();
double sy = sp.getY();
double ex = ep.getX();
double ey = ep.getY();
/*
* Try to catch rectangles that intersect arc in areas
* outside of rectagle with left top corner coordinates
* (min(center x, start point x, end point x),
* min(center y, start point y, end point y))
* and rigth bottom corner coordinates
* (max(center x, start point x, end point x),
* max(center y, start point y, end point y)).
* So we'll check axis segments outside of rectangle above.
*/
if (ayc >= y && ayc <= yh) { // 0 and 180
if ((sx < xw && ex < xw && axc < xw &&
axw > x && containsAngle(0)) ||
(sx > x && ex > x && axc > x &&
ax < xw && containsAngle(180))) {
return true;
}
}
if (axc >= x && axc <= xw) { // 90 and 270
if ((sy > y && ey > y && ayc > y &&
ay < yh && containsAngle(90)) ||
(sy < yh && ey < yh && ayc < yh &&
ayh > y && containsAngle(270))) {
return true;
}
}
/*
* For PIE we should check intersection with pie slices;
* also we should do the same for arcs with extent is greater
* than 180, because we should cover case of rectangle, which
* situated between center of arc and chord, but does not
* intersect the chord.
*/
Rectangle2D rect = new Rectangle2D.Double(x, y, w, h);
if (type == PIE || Math.abs(ext) > 180) {
// for PIE: try to find intersections with pie slices
if (rect.intersectsLine(axc, ayc, sx, sy) ||
rect.intersectsLine(axc, ayc, ex, ey)) {
return true;
}
} else {
// for CHORD and OPEN: try to find intersections with chord
if (rect.intersectsLine(sx, sy, ex, ey)) {
return true;
}
}
// finally check the rectangle corners inside the arc
if (contains(x, y) || contains(x + w, y) ||
contains(x, y + h) || contains(x + w, y + h)) {
return true;
}
return false;
}
/**
* Determines whether or not the interior of the arc entirely contains
* the specified rectangle.
*
* @param x The X coordinate of the rectangle's upper-left corner.
* @param y The Y coordinate of the rectangle's upper-left corner.
* @param w The width of the rectangle.
* @param h The height of the rectangle.
*
* @return <CODE>true</CODE> if the arc contains the rectangle,
* <CODE>false</CODE> if the arc doesn't contain the rectangle.
* @since 1.2
*/
public boolean contains(double x, double y, double w, double h) {
return contains(x, y, w, h, null);
}
/**
* Determines whether or not the interior of the arc entirely contains
* the specified rectangle.
*
* @param r The <CODE>Rectangle2D</CODE> to test.
*
* @return <CODE>true</CODE> if the arc contains the rectangle,
* <CODE>false</CODE> if the arc doesn't contain the rectangle.
* @since 1.2
*/
public boolean contains(Rectangle2D r) {
return contains(r.getX(), r.getY(), r.getWidth(), r.getHeight(), r);
}
private boolean contains(double x, double y, double w, double h,
Rectangle2D origrect) {
if (!(contains(x, y) &&
contains(x + w, y) &&
contains(x, y + h) &&
contains(x + w, y + h))) {
return false;
}
// If the shape is convex then we have done all the testing
// we need. Only PIE arcs can be concave and then only if
// the angular extents are greater than 180 degrees.
if (type != PIE || Math.abs(getAngleExtent()) <= 180.0) {
return true;
}
// For a PIE shape we have an additional test for the case where
// the angular extents are greater than 180 degrees and all four
// rectangular corners are inside the shape but one of the
// rectangle edges spans across the "missing wedge" of the arc.
// We can test for this case by checking if the rectangle intersects
// either of the pie angle segments.
if (origrect == null) {
origrect = new Rectangle2D.Double(x, y, w, h);
}
double halfW = getWidth() / 2.0;
double halfH = getHeight() / 2.0;
double xc = getX() + halfW;
double yc = getY() + halfH;
double angle = Math.toRadians(-getAngleStart());
double xe = xc + halfW * Math.cos(angle);
double ye = yc + halfH * Math.sin(angle);
if (origrect.intersectsLine(xc, yc, xe, ye)) {
return false;
}
angle += Math.toRadians(-getAngleExtent());
xe = xc + halfW * Math.cos(angle);
ye = yc + halfH * Math.sin(angle);
return !origrect.intersectsLine(xc, yc, xe, ye);
}
/**
* Returns an iteration object that defines the boundary of the
* arc.
* This iterator is multithread safe.
* <code>Arc2D</code> guarantees that
* modifications to the geometry of the arc
* do not affect any iterations of that geometry that
* are already in process.
*
* @param at an optional <CODE>AffineTransform</CODE> to be applied
* to the coordinates as they are returned in the iteration, or null
* if the untransformed coordinates are desired.
*
* @return A <CODE>PathIterator</CODE> that defines the arc's boundary.
* @since 1.2
*/
public PathIterator getPathIterator(AffineTransform at) {
return new ArcIterator(this, at);
}
/**
* Returns the hashcode for this <code>Arc2D</code>.
* @return the hashcode for this <code>Arc2D</code>.
* @since 1.6
*/
public int hashCode() {
long bits = java.lang.Double.doubleToLongBits(getX());
bits += java.lang.Double.doubleToLongBits(getY()) * 37;
bits += java.lang.Double.doubleToLongBits(getWidth()) * 43;
bits += java.lang.Double.doubleToLongBits(getHeight()) * 47;
bits += java.lang.Double.doubleToLongBits(getAngleStart()) * 53;
bits += java.lang.Double.doubleToLongBits(getAngleExtent()) * 59;
bits += getArcType() * 61;
return (((int) bits) ^ ((int) (bits >> 32)));
}
/**
* Determines whether or not the specified <code>Object</code> is
* equal to this <code>Arc2D</code>. The specified
* <code>Object</code> is equal to this <code>Arc2D</code>
* if it is an instance of <code>Arc2D</code> and if its
* location, size, arc extents and type are the same as this
* <code>Arc2D</code>.
* @param obj an <code>Object</code> to be compared with this
* <code>Arc2D</code>.
* @return <code>true</code> if <code>obj</code> is an instance
* of <code>Arc2D</code> and has the same values;
* <code>false</code> otherwise.
* @since 1.6
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof Arc2D) {
Arc2D a2d = (Arc2D) obj;
return ((getX() == a2d.getX()) &&
(getY() == a2d.getY()) &&
(getWidth() == a2d.getWidth()) &&
(getHeight() == a2d.getHeight()) &&
(getAngleStart() == a2d.getAngleStart()) &&
(getAngleExtent() == a2d.getAngleExtent()) &&
(getArcType() == a2d.getArcType()));
}
return false;
}
}
|
/*
* Copyright 2017-2018 original 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 io.micronaut.inject.failures.postconstruct;
import javax.inject.Singleton;
@Singleton
public class A {
}
|
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.facebook.stetho.inspector.elements.android;
// Referenced classes of package com.facebook.stetho.inspector.elements.android:
// TextViewDescriptor
static class TextViewDescriptor$1
{
}
|
package com.bitdubai.fermat_ccp_api.layer.identity.intra_user.exceptions;
import com.bitdubai.fermat_api.FermatException;
/**
* Created by natalia on 11/11/15.
*/
public class CantDeleteIdentityException extends FermatException {
/**
* This is the constructor that every inherited FermatException must implement
*
* @param message the short description of the why this exception happened, there is a public static constant called DEFAULT_MESSAGE that can be used here
* @param cause the exception that triggered the throwing of the current exception, if there are no other exceptions to be declared here, the cause should be null
* @param context a String that provides the values of the variables that could have affected the exception
* @param possibleReason an explicative reason of why we believe this exception was most likely thrown
*/
public CantDeleteIdentityException(String message, Exception cause, String context, String possibleReason) {
super(message, cause, context, possibleReason);
}
}
|
package com.github.jnidzwetzki.bitfinex.v2.test;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import com.github.jnidzwetzki.bitfinex.v2.BitfinexApiBroker;
import com.github.jnidzwetzki.bitfinex.v2.BitfinexApiBrokerConfig;
import com.github.jnidzwetzki.bitfinex.v2.BitfinexOrderBuilder;
import com.github.jnidzwetzki.bitfinex.v2.commands.AbstractAPICommand;
import com.github.jnidzwetzki.bitfinex.v2.commands.AuthCommand;
import com.github.jnidzwetzki.bitfinex.v2.commands.CancelOrderCommand;
import com.github.jnidzwetzki.bitfinex.v2.commands.CancelOrderGroupCommand;
import com.github.jnidzwetzki.bitfinex.v2.commands.CommandException;
import com.github.jnidzwetzki.bitfinex.v2.commands.OrderCommand;
import com.github.jnidzwetzki.bitfinex.v2.commands.PingCommand;
import com.github.jnidzwetzki.bitfinex.v2.commands.SetConnectionFeaturesCommand;
import com.github.jnidzwetzki.bitfinex.v2.commands.SubscribeCandlesCommand;
import com.github.jnidzwetzki.bitfinex.v2.commands.SubscribeTickerCommand;
import com.github.jnidzwetzki.bitfinex.v2.commands.SubscribeTradesCommand;
import com.github.jnidzwetzki.bitfinex.v2.commands.SubscribeOrderbookCommand;
import com.github.jnidzwetzki.bitfinex.v2.commands.SubscribeRawOrderbookCommand;
import com.github.jnidzwetzki.bitfinex.v2.commands.UnsubscribeChannelCommand;
import com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexCurrencyPair;
import com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexOrder;
import com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexOrderType;
import com.github.jnidzwetzki.bitfinex.v2.entity.OrderBookFrequency;
import com.github.jnidzwetzki.bitfinex.v2.entity.OrderBookPrecision;
import com.github.jnidzwetzki.bitfinex.v2.entity.Timeframe;
import com.github.jnidzwetzki.bitfinex.v2.entity.OrderbookConfiguration;
import com.github.jnidzwetzki.bitfinex.v2.entity.RawOrderbookConfiguration;
import com.github.jnidzwetzki.bitfinex.v2.entity.symbol.BitfinexCandlestickSymbol;
import com.github.jnidzwetzki.bitfinex.v2.entity.symbol.BitfinexTickerSymbol;
import com.github.jnidzwetzki.bitfinex.v2.entity.symbol.BitfinexExecutedTradeSymbol;
public class CommandsTest {
/**
* Call all commands and check for excepion
* @throws CommandException
*/
@Test
public void testCommandsJSON() throws CommandException {
final BitfinexOrder order
= BitfinexOrderBuilder.create(
BitfinexCurrencyPair.of("BCH","USD"), BitfinexOrderType.EXCHANGE_STOP, 2).build();
final BitfinexCandlestickSymbol candleSymbol
= new BitfinexCandlestickSymbol(BitfinexCurrencyPair.of("BCH","USD"), Timeframe.HOUR_1);
final OrderbookConfiguration orderbookConfiguration
= new OrderbookConfiguration(BitfinexCurrencyPair.of("BCH","USD"),
OrderBookPrecision.P0, OrderBookFrequency.F0 , 50);
final RawOrderbookConfiguration rawOrderbookConfiguration
= new RawOrderbookConfiguration(BitfinexCurrencyPair.of("BAT","BTC"));
final List<AbstractAPICommand> commands = Arrays.asList(
new AuthCommand(AuthCommand.AUTH_NONCE_PRODUCER_TIMESTAMP),
new CancelOrderCommand(123),
new CancelOrderGroupCommand(1),
new OrderCommand(order),
new PingCommand(),
new SubscribeCandlesCommand(candleSymbol),
new SubscribeTickerCommand(new BitfinexTickerSymbol(BitfinexCurrencyPair.of("BCH","USD"))),
new SubscribeTradesCommand(new BitfinexExecutedTradeSymbol(BitfinexCurrencyPair.of("BAT","BTC"))),
new SubscribeOrderbookCommand(orderbookConfiguration),
new SubscribeRawOrderbookCommand(rawOrderbookConfiguration),
new UnsubscribeChannelCommand(12),
new SetConnectionFeaturesCommand(new HashSet<>()));
final BitfinexApiBroker bitfinexApiBroker = buildMockedBitfinexConnection();
for(final AbstractAPICommand command : commands) {
final String commandValue = command.getCommand(bitfinexApiBroker);
Assert.assertNotNull(commandValue);
Assert.assertTrue(commandValue.length() > 10);
}
}
/**
* Test the order command
* @throws CommandException
*/
@Test
public void testOrderCommand() throws CommandException {
final BitfinexOrder order
= BitfinexOrderBuilder.create(BitfinexCurrencyPair.of("BCH","USD"), BitfinexOrderType.EXCHANGE_STOP, 2)
.setHidden()
.setPostOnly()
.withPrice(12)
.withPriceAuxLimit(23)
.withPriceTrailing(23)
.withGroupId(4)
.build();
final OrderCommand command = new OrderCommand(order);
final BitfinexApiBroker bitfinexApiBroker = buildMockedBitfinexConnection();
final String commandValue = command.getCommand(bitfinexApiBroker);
Assert.assertNotNull(commandValue);
Assert.assertTrue(commandValue.length() > 10);
Assert.assertTrue(commandValue.contains("\"2.0\""));
}
/**
* Build the bitfinex connection
* @return
*/
private BitfinexApiBroker buildMockedBitfinexConnection() {
final BitfinexApiBroker bitfinexApiBroker = Mockito.mock(BitfinexApiBroker.class);
final BitfinexApiBrokerConfig config = Mockito.mock(BitfinexApiBrokerConfig.class);
Mockito.when(bitfinexApiBroker.getConfiguration()).thenReturn(config);
Mockito.when(bitfinexApiBroker.getConfiguration().getApiKey()).thenReturn("abc");
Mockito.when(bitfinexApiBroker.getConfiguration().getApiSecret()).thenReturn("123");
return bitfinexApiBroker;
}
}
|
package com.silvertree.ideplugin.editors;
import org.eclipse.jface.text.rules.*;
public class TagRule extends MultiLineRule {
public TagRule(IToken token) {
super("<", ">", token);
}
@Override
protected boolean sequenceDetected(ICharacterScanner scanner, char[] sequence, boolean eofAllowed) {
int c = scanner.read();
if (sequence[0] == '<') {
if (c == '?') {
// processing instruction - abort
scanner.unread();
return false;
}
if (c == '!') {
scanner.unread();
// comment - abort
return false;
}
} else if (sequence[0] == '>') {
scanner.unread();
}
return super.sequenceDetected(scanner, sequence, eofAllowed);
}
}
|
package com.builtbroken.mc.lib.helper;
import com.mojang.authlib.GameProfile;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.util.FakePlayer;
import net.minecraftforge.common.util.ForgeDirection;
import com.builtbroken.mc.imp.transform.vector.Location;
import java.util.LinkedHashMap;
import java.util.UUID;
/**
* Fake player used by machines, also includes utilities for using the fake player better.
*
* @author DarkGuardsman
*/
public class DummyPlayer extends FakePlayer
{
private static final LinkedHashMap<World, DummyPlayer> FAKE_PLAYERS = new LinkedHashMap<>();
public DummyPlayer(World world, String name, String sufix)
{
super((WorldServer) world, new GameProfile(UUID.randomUUID(), name + sufix));
}
public DummyPlayer(World world, String sufix)
{
this(world, "[RE]FakePlayer", sufix);
}
public DummyPlayer(World world)
{
this(world, "(" + world.provider.dimensionId + ")");
}
/**
* Gets the fake player for the world
*/
public static DummyPlayer get(World world)
{
if (!FAKE_PLAYERS.containsKey(world) || FAKE_PLAYERS.get(world) == null)
{
FAKE_PLAYERS.put(world, new DummyPlayer(world));
}
return FAKE_PLAYERS.get(world);
}
public static boolean useItemAt(ItemStack itemStack, Location location, ForgeDirection direction)
{
return useItemAt(itemStack, location.world, location.xi(), location.yi(), location.zi(), direction.ordinal(), 0, 0, 0);
}
public static boolean useItemAt(ItemStack itemStack, World world, int x, int y, int z, int side)
{
return useItemAt(itemStack, world, x, y, z, side, 0, 0, 0);
}
public static boolean useItemAt(ItemStack itemStack, World world, int x, int y, int z, int side, int hitX, int hitY, int hitZ)
{
return itemStack.getItem().onItemUse(itemStack, get(world), world, x, y, z, side, hitX, hitY, hitZ);
}
}
|
package java11;
import java.util.Function;
class Java11 {
void m1() {
m2((@NotNull var n) -> n * 2);
}
void m2(Function<Integer, Integer> fn) {
System.out.println(fn.apply(2));
}
}
|
package com.freedy.mall.order.dao;
import com.freedy.mall.order.entity.OrderOperateHistoryEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 订单操作历史记录
*
* @author freedy
* @email 985948228@qq.com
* @date 2021-01-30 21:39:25
*/
@Mapper
public interface OrderOperateHistoryDao extends BaseMapper<OrderOperateHistoryEntity> {
}
|
/**
* Copyright (c) 2014 All Rights Reserved by the SDL Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sdl.odata.client.api;
import com.sdl.odata.client.api.caller.EndpointCaller;
import com.sdl.odata.client.api.marshall.ODataEntityMarshaller;
import com.sdl.odata.client.api.marshall.ODataEntityUnmarshaller;
import java.net.URL;
/**
* ODataClient components provider. Provides access to some main client parts like EndpointCaller, Unmarshaller, URL.
*/
public interface ODataClientComponentsProvider {
/**
* Returns endpoint caller responsible for OData web service calls.
* @return The endpoint caller
*/
EndpointCaller getEndpointCaller();
/**
* Returns unmarshaller for unmarshalling OData string response into edm entity objects.
* @return The unmarshaller
*/
ODataEntityUnmarshaller getUnmarshaller();
/**
* Returns marshaller for marshalling OData edm entity objects into string representation.
* @return The marshaller
*/
ODataEntityMarshaller getMarshaller();
/**
* Returns OData web service url.
* @return The webservice url
*/
URL getWebServiceUrl();
}
|
/*
* Copyright 2022 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.sw.marshall;
import org.kie.workbench.common.stunner.core.graph.Edge;
import org.kie.workbench.common.stunner.core.graph.Node;
import org.kie.workbench.common.stunner.sw.definition.CompensationTransition;
import org.kie.workbench.common.stunner.sw.definition.DataConditionTransition;
import org.kie.workbench.common.stunner.sw.definition.DefaultConditionTransition;
import org.kie.workbench.common.stunner.sw.definition.End;
import org.kie.workbench.common.stunner.sw.definition.ErrorTransition;
import org.kie.workbench.common.stunner.sw.definition.EventConditionTransition;
import org.kie.workbench.common.stunner.sw.definition.StartTransition;
import org.kie.workbench.common.stunner.sw.definition.State;
import org.kie.workbench.common.stunner.sw.definition.Transition;
import org.kie.workbench.common.stunner.sw.definition.Workflow;
import org.kie.workbench.common.stunner.sw.marshall.Marshaller.EdgeMarshaller;
import org.kie.workbench.common.stunner.sw.marshall.Marshaller.EdgeUnmarshaller;
import static org.kie.workbench.common.stunner.sw.marshall.DefinitionTypeUtils.getEnd;
import static org.kie.workbench.common.stunner.sw.marshall.DefinitionTypeUtils.getTransition;
import static org.kie.workbench.common.stunner.sw.marshall.Marshaller.EDGE_START;
import static org.kie.workbench.common.stunner.sw.marshall.Marshaller.STATE_END;
import static org.kie.workbench.common.stunner.sw.marshall.MarshallerUtils.getElementDefinition;
import static org.kie.workbench.common.stunner.sw.marshall.MarshallerUtils.getStateNodeName;
import static org.kie.workbench.common.stunner.sw.marshall.MarshallerUtils.isValidString;
public interface TransitionMarshalling {
EdgeMarshaller<Object> ANY_EDGE_MARSHALLER =
(context, edge) -> edge;
EdgeUnmarshaller<Transition> TRANSITION_UNMARSHALLER =
(context, transition) -> {
String to = transition.getTo();
Edge edge = context.addEdgeToTargetName(transition, context.sourceNode, to);
return edge;
};
EdgeMarshaller<Transition> TRANSITION_MARSHALLER =
(context, edge) -> {
Node sourceNode = edge.getSourceNode();
if (null != sourceNode) {
Node targetNode = edge.getTargetNode();
if (null != targetNode) {
State sourceState = getElementDefinition(sourceNode);
Object targetDef = getElementDefinition(targetNode);
if (targetDef instanceof End) {
sourceState.transition = null;
sourceState.end = true;
} else {
sourceState.transition = getStateNodeName(targetNode);
sourceState.end = false;
}
}
}
// TODO: Update Transition.to ?
return edge;
};
EdgeUnmarshaller<CompensationTransition> COMPENSATION_TRANSITION_UNMARSHALLER =
(context, compensationTransition) -> {
String transition = getTransition(compensationTransition.transition);
Edge edge = null;
if (isValidString(transition)) {
edge = context.addEdgeToTargetName(compensationTransition, context.sourceNode, transition);
}
return edge;
};
EdgeMarshaller<CompensationTransition> COMPENSATION_TRANSITION_MARSHALLER =
(context, edge) -> {
Node sourceNode = edge.getSourceNode();
if (null != sourceNode) {
Node targetNode = edge.getTargetNode();
if (null != targetNode) {
State sourceState = getElementDefinition(sourceNode);
sourceState.transition = getStateNodeName(targetNode);
}
}
// TODO: Update CompensationTransition.name ?
// TODO: Update CompensationTransition.transition ?
return edge;
};
EdgeUnmarshaller<DataConditionTransition> DATA_CONDITION_TRANSITION_UNMARSHALLER =
(context, dataConditionTransition) -> {
boolean end = getEnd(dataConditionTransition.end);
String transition = getTransition(dataConditionTransition.transition);
Edge edge = null;
if (end) {
edge = context.addEdgeToTargetName(dataConditionTransition, context.sourceNode, STATE_END);
} else if (isValidString(transition)) {
edge = context.addEdgeToTargetName(dataConditionTransition, context.sourceNode, transition);
}
return edge;
};
EdgeMarshaller<DataConditionTransition> DATA_CONDITION_TRANSITION_MARSHALLER =
(context, edge) -> {
Node sourceNode = edge.getSourceNode();
if (null != sourceNode) {
Node targetNode = edge.getTargetNode();
if (null != targetNode) {
DataConditionTransition dataConditionTransition = getElementDefinition(edge);
Object targetDef = getElementDefinition(targetNode);
if (targetDef instanceof End) {
dataConditionTransition.transition = null;
dataConditionTransition.end = true;
} else {
dataConditionTransition.transition = getStateNodeName(targetNode);
dataConditionTransition.end = false;
}
}
}
return edge;
};
EdgeUnmarshaller<DefaultConditionTransition> DEFAULT_CONDITION_TRANSITION_UNMARSHALLER =
(context, defaultConditionTransition) -> {
boolean end = getEnd(defaultConditionTransition.end);
String transition = getTransition(defaultConditionTransition.transition);
Edge edge = null;
if (end) {
edge = context.addEdgeToTargetName(defaultConditionTransition, context.sourceNode, STATE_END);
} else if (isValidString(transition)) {
edge = context.addEdgeToTargetName(defaultConditionTransition, context.sourceNode, transition);
}
return edge;
};
EdgeMarshaller<DefaultConditionTransition> DEFAULT_CONDITION_TRANSITION_MARSHALLER =
(context, edge) -> {
Node sourceNode = edge.getSourceNode();
if (null != sourceNode) {
Node targetNode = edge.getTargetNode();
if (null != targetNode) {
DefaultConditionTransition defaultConditionTransition = getElementDefinition(edge);
Object targetDef = getElementDefinition(targetNode);
if (targetDef instanceof End) {
defaultConditionTransition.transition = null;
defaultConditionTransition.end = true;
} else {
defaultConditionTransition.transition = getStateNodeName(targetNode);
defaultConditionTransition.end = false;
}
}
}
return edge;
};
EdgeUnmarshaller<ErrorTransition> ERROR_TRANSITION_UNMARSHALLER =
(context, errorTransition) -> {
boolean end = getEnd(errorTransition.end);
String transition = getTransition(errorTransition.transition);
Edge edge = null;
if (end) {
edge = context.addEdgeToTargetName(errorTransition, context.sourceNode, STATE_END);
} else if (isValidString(transition)) {
edge = context.addEdgeToTargetName(errorTransition, context.sourceNode, transition);
}
return edge;
};
EdgeMarshaller<ErrorTransition> ERROR_TRANSITION_MARSHALLER =
(context, edge) -> {
Node sourceNode = edge.getSourceNode();
if (null != sourceNode) {
Node targetNode = edge.getTargetNode();
if (null != targetNode) {
ErrorTransition errorTransition = getElementDefinition(edge);
Object targetDef = getElementDefinition(targetNode);
if (targetDef instanceof End) {
errorTransition.transition = null;
errorTransition.end = true;
} else {
errorTransition.transition = getStateNodeName(targetNode);
errorTransition.end = false;
}
}
}
return edge;
};
EdgeUnmarshaller<EventConditionTransition> EVENT_CONDITION_TRANSITION_UNMARSHALLER =
(context, eventConditionTransition) -> {
boolean end = getEnd(eventConditionTransition.end);
String transition = getTransition(eventConditionTransition.transition);
Edge edge = null;
if (end) {
edge = context.addEdgeToTargetName(eventConditionTransition, context.sourceNode, STATE_END);
} else if (isValidString(transition)) {
edge = context.addEdgeToTargetName(eventConditionTransition, context.sourceNode, transition);
}
return edge;
};
EdgeMarshaller<EventConditionTransition> EVENT_CONDITION_TRANSITION_MARSHALLER =
(context, edge) -> {
Node sourceNode = edge.getSourceNode();
if (null != sourceNode) {
Node targetNode = edge.getTargetNode();
if (null != targetNode) {
EventConditionTransition eventConditionTransition = getElementDefinition(edge);
Object targetDef = getElementDefinition(targetNode);
if (targetDef instanceof End) {
eventConditionTransition.transition = null;
eventConditionTransition.end = true;
} else {
eventConditionTransition.transition = getStateNodeName(targetNode);
eventConditionTransition.end = false;
}
}
}
return edge;
};
EdgeUnmarshaller<StartTransition> START_TRANSITION_UNMARSHALLER =
(context, startTransition) -> {
Node sourceNode = context.sourceNode;
Edge startEdge = context.addEdge(EDGE_START, startTransition, sourceNode);
String transition = getTransition(startTransition.transition);
if (isValidString(transition)) {
String targetUUID = context.obtainUUID(transition);
context.connect(startEdge, sourceNode, targetUUID);
}
return startEdge;
};
EdgeMarshaller<StartTransition> START_TRANSITION_MARSHALLER =
(context, edge) -> {
Workflow workflow = context.getWorkflowRoot();
if (null != edge.getTargetNode()) {
Node targetNode = edge.getTargetNode();
String stateName = getStateNodeName(targetNode);
workflow.setStart(stateName);
} else {
workflow.setStart("");
}
// TODO: Update StartTransition.transition ?
return edge;
};
}
|
package com.jcloisterzone.game.phase;
import com.jcloisterzone.board.Position;
import com.jcloisterzone.board.pointer.BoardPointer;
import com.jcloisterzone.board.pointer.FeaturePointer;
import com.jcloisterzone.board.pointer.MeeplePointer;
import com.jcloisterzone.event.PointsExpression;
import com.jcloisterzone.event.ScoreEvent;
import com.jcloisterzone.event.ScoreEvent.ReceivedPoints;
import com.jcloisterzone.figure.Meeple;
import com.jcloisterzone.game.RandomGenerator;
import com.jcloisterzone.game.capability.FairyCapability;
import com.jcloisterzone.game.state.GameState;
import com.jcloisterzone.reducers.AddPoints;
import io.vavr.Tuple2;
public class FairyPhase extends Phase {
public FairyPhase(RandomGenerator random, Phase defaultNext) {
super(random, defaultNext);
}
@Override
public StepResult enter(GameState state) {
BoardPointer ptr = state.getNeutralFigures().getFairyDeployment();
if (ptr == null) {
return next(state);
}
boolean onTileRule = ptr instanceof Position;
FeaturePointer fairyFp = ptr.asFeaturePointer();
for (Tuple2<Meeple, FeaturePointer> t : state.getDeployedMeeples()) {
Meeple m = t._1;
if (!m.getPlayer().equals(state.getTurnPlayer())) continue;
if (onTileRule) {
if (!t._2.getPosition().equals(fairyFp.getPosition())) continue;
} else {
if (!t._2.equals(fairyFp)) continue;
if (!((MeeplePointer) ptr).match(m)) continue;
}
state = new AddPoints(m.getPlayer(), FairyCapability.FAIRY_POINTS_BEGINNING_OF_TURN).apply(state);
PointsExpression expr = new PointsExpression(FairyCapability.FAIRY_POINTS_BEGINNING_OF_TURN, "fairy.turn");
state = state.appendEvent(new ScoreEvent(new ReceivedPoints(expr, m.getPlayer(), fairyFp), false, false));
break;
}
return next(state);
}
}
|
package org.test.zombiedefence;
import loon.LTexture;
import loon.action.sprite.SpriteBatch;
import loon.action.sprite.SpriteBatch.SpriteEffects;
import loon.canvas.LColor;
import loon.geom.Vector2f;
import loon.utils.timer.GameTime;
public class ScreenLevelup extends Screen {
private Vector2f diplayTexturePosition;
private java.util.ArrayList<MoneyDeductionTag> moneyDeductionTagList;
public static ScrollablePane scrollablePane;
public static LTexture t2DAAGun;
public static LTexture t2DBAR;
public static LTexture t2DBarrierBroken;
public static LTexture t2DBarrierOriginal;
public static LTexture t2DBrowning;
public static LTexture t2DButtonBack;
public static LTexture t2DButtonBuy;
public static LTexture t2DButtonNext;
public static LTexture t2DCardAAGun;
public static LTexture t2DCardBAR;
public static LTexture t2DCardBrowning;
public static LTexture t2dCardColt;
public static LTexture t2DCardKarabiner98;
public static LTexture t2DCardM1Garand;
public static LTexture t2DCardNambuType14;
public static LTexture t2DCardPPSH41;
public static LTexture t2DCardSVT40;
public static LTexture t2DCardTompsonM1928;
public static LTexture t2DCardVickers;
public static LTexture t2DCardWebleyRevolver;
public static LTexture t2DCardWinchester;
public static LTexture t2DCardZhongZheng;
public static LTexture t2DColt;
public static LTexture t2DCurrentWeaponPlate;
public static LTexture t2DKarabiner98;
public static LTexture t2DM1Garand;
public static LTexture t2DNambuType14;
public static LTexture t2DPane;
public static LTexture t2DPlateTextures;
public static LTexture t2DPPSH41;
public static LTexture t2DSVT40;
public static LTexture t2DTitle;
public static LTexture t2DTompsonM1928;
public static LTexture t2DVickers;
public static LTexture t2DWebleyRevolver;
public static LTexture t2DWinchester;
public static LTexture t2DZhongZheng;
public static LTexture t2DPlateTexture;
private java.util.ArrayList<LTexture> weaponCardList;
public ScreenLevelup() {
super.screenPause = new ScreenPause(this, Help.GameScreen.LevelUp);
}
@Override
public void Draw(SpriteBatch batch) {
super.Draw(batch);
if (!super.isPaused) {
scrollablePane.Draw(batch);
for (MoneyDeductionTag tag : this.moneyDeductionTagList) {
tag.Draw(batch);
}
batch.draw(t2DTitle, 10f, 20f);
batch.draw(t2DCurrentWeaponPlate, 640f, 90f);
batch.draw(Help.currentWeapon.texture, 650f, 120f, null,
LColor.white, 0f, 0f, 0f, 0.4f, SpriteEffects.None);
batch.drawString(Screen.ariel14, Help.currentWeapon.name,
660f, 195f, LColor.white);
batch.draw(this.weaponCardList.get(scrollablePane.iSelectedItem),
230f, 90f);
if (((Weapon) scrollablePane.itemList
.get(scrollablePane.iSelectedItem)).name
.equalsIgnoreCase("Sd.Kfz 7/1")) {
batch.drawString(Screen.ariel18,
"Must've learned skill 'AAGun'",230f,
315f, LColor.white);
}
batch.draw(
scrollablePane.itemList.get(scrollablePane.iSelectedItem).texture,
this.diplayTexturePosition, null, LColor.white, 0f,
0f, 0f, 0.9f, SpriteEffects.None);
batch.drawString(
Screen.ariel14,
((Weapon) scrollablePane.itemList
.get(scrollablePane.iSelectedItem)).price + "",
555f, 398f, LColor.white);
batch.drawString(Screen.myFont, "$" + Help.money,
640f, 380f, LColor.white);
}
}
@Override
public void LoadContent() {
super.LoadContent();
ScreenGameplay.rand = new Random();
ScreenGameplay.rifleSound = new SoundEffect();
ScreenGameplay.soundThompson = new SoundEffect();
ScreenGameplay.soundNambu = new SoundEffect();
ScreenGameplay.ZhongZhengSound = new SoundEffect();
ScreenGameplay.pistolSound = new SoundEffect();
ScreenGameplay.soundWebley = new SoundEffect();
ScreenGameplay.soundWinchester = new SoundEffect();
ScreenGameplay.grenadeSound = new SoundEffect();
ScreenGameplay.soundBAR = new SoundEffect();
ScreenGameplay.reloadSound = new SoundEffect();
ScreenGameplay.soundPPSH41 = new SoundEffect();
ScreenGameplay.soundSVT40 = new SoundEffect();
ScreenGameplay.soundVickers = new SoundEffect();
ScreenGameplay.soundBrowning = new SoundEffect();
super.bgTexture = Global.Load("ScratchBG");
t2DTitle = Global.Load("TitleLevelup1");
t2DButtonBack = Global.Load("ButtonBack");
t2DButtonNext = Global.Load("ButtonNext");
t2DButtonBuy = Global.Load("ButtonBuy");
t2DPane = Global.Load("ScrollablePane");
t2DSVT40 = Global.Load("Svt40");
t2DPPSH41 = Global.Load("PPSH41");
t2DWinchester = Global.Load("Winchester");
t2DColt = Global.Load("Colt 1908");
t2DNambuType14 = Global.Load("NambuType14");
t2DWebleyRevolver = Global.Load("WebleyRevolver");
t2DKarabiner98 = Global.Load("Karabiner98");
t2DZhongZheng = Global.Load("ZhongZheng");
t2DM1Garand = Global.Load("M1Garand");
t2DBAR = Global.Load("BAR");
t2DTompsonM1928 = Global.Load("TompsonM1928");
t2DVickers = Global.Load("Vickers");
t2DBrowning = Global.Load("Browning");
t2DAAGun = Global.Load("SdKfz");
t2DCardPPSH41 = Global.Load("PPSH41Card");
t2DCardWinchester = Global.Load("WinchesterCard");
t2DCardNambuType14 = Global.Load("NambuCard");
t2DCardWebleyRevolver = Global.Load("WebleyRevolverCard");
t2DCardKarabiner98 = Global.Load("Karabiner98kCard");
t2DCardZhongZheng = Global.Load("ZhongZhengCard");
t2DCardM1Garand = Global.Load("M1GarandCard");
t2DCardBAR = Global.Load("BARCard");
t2DCardTompsonM1928 = Global.Load("ThompsonCard");
t2DCardSVT40 = Global.Load("SVT40Card");
t2DCardVickers = Global.Load("VickerCard");
t2DCardAAGun = Global.Load("SdKfz7Card");
t2dCardColt = Global.Load("ColtCard");
t2DCardBrowning = Global.Load("BrowningCard");
ScreenGameplay.t2DBunkerAA = Global.Load("BunkerAAGun");
t2DBarrierBroken = Global.Load("Barrier_Broken");
t2DPlateTexture = Global.Load("WeaponPlate");
t2DCurrentWeaponPlate = Global.Load("CurrentWeaponPlate");
super.buttonList.add(new Button(t2DButtonNext,
new Vector2f(750f, 450f), 0f, Help.ButtonID.Proceed, 15));
super.buttonList.add(new Button(t2DButtonBuy, new Vector2f(720f, 310f),
0f, Help.ButtonID.Buy, 0));
super.screenPause.LoadContent();
scrollablePane = new ScrollablePane(t2DPane, new Vector2f(50f, 90f));
this.weaponCardList = new java.util.ArrayList<LTexture>();
scrollablePane.AddItem(new Weapon(t2DNambuType14,
ScreenGameplay.soundNambu, new Vector2f(0f, 0f), "NambuType14",
7, 30, 10, 4, 0.1396263f, 0x2d));
this.weaponCardList.add(t2DCardNambuType14);
scrollablePane.AddItem(new Weapon(t2DColt, ScreenGameplay.soundNambu,
new Vector2f(0f, 0f), "Colt 1908", 7, 30, 12, 6, 0.122173f,
0x37));
this.weaponCardList.add(t2dCardColt);
scrollablePane.AddItem(new Weapon(t2DZhongZheng,
ScreenGameplay.ZhongZhengSound, new Vector2f(0f, 0f),
"ZhongZheng", 1, 0x2d, 10, 15, 0.05235988f, 80));
this.weaponCardList.add(t2DCardZhongZheng);
scrollablePane.AddItem(new Weapon(t2DKarabiner98,
ScreenGameplay.rifleSound, new Vector2f(0f, 0f),
"Karabiner98K", 1, 30, 10, 0x10, 0.05235988f, 0x5f));
this.weaponCardList.add(t2DCardKarabiner98);
scrollablePane.AddItem(new Weapon(t2DWebleyRevolver,
ScreenGameplay.soundWebley, new Vector2f(0f, 0f), "Webley", 6,
30, 15, 15, 0.1396263f, 110));
this.weaponCardList.add(t2DCardWebleyRevolver);
scrollablePane.AddItem(new Weapon(t2DWinchester,
ScreenGameplay.soundWinchester, new Vector2f(0f, 0f),
"Winchester", 2, 60, 15, 30, 0.2617994f, 140));
this.weaponCardList.add(t2DCardWinchester);
scrollablePane.AddItem(new Weapon(t2DM1Garand,
ScreenGameplay.pistolSound, new Vector2f(0f, 0f), "M1Garand",
8, 50, 9, 0x10, 0.08726647f, 0x109));
this.weaponCardList.add(t2DCardM1Garand);
scrollablePane.AddItem(new Weapon(t2DSVT40, ScreenGameplay.soundSVT40,
new Vector2f(0f, 0f), "SVT40", 10, 50, 10, 0x10, 0.08726647f,
290));
this.weaponCardList.add(t2DCardSVT40);
scrollablePane
.AddItem(new Weapon(t2DBAR, ScreenGameplay.soundBAR,
new Vector2f(0f, 0f), "BAR", 20, 80, 6, 0x12,
0.122173f, 0x18b));
this.weaponCardList.add(t2DCardBAR);
scrollablePane.AddItem(new Weapon(t2DPPSH41,
ScreenGameplay.soundPPSH41, new Vector2f(220f, 0f), "PPSH41",
30, 80, 3, 0x11, 0.1396263f, 0x221));
this.weaponCardList.add(t2DCardPPSH41);
scrollablePane.AddItem(new Weapon(t2DTompsonM1928,
ScreenGameplay.soundThompson, new Vector2f(0f, 0f),
"TompsonM1928", 30, 80, 4, 0x16, 0.122173f, 590));
this.weaponCardList.add(t2DCardTompsonM1928);
scrollablePane.AddItem(new Weapon(t2DVickers,
ScreenGameplay.soundVickers, new Vector2f(0f, 0f), "Vickers",
0x7d, 120, 4, 0x23, 0.122173f, 0x3d9));
this.weaponCardList.add(t2DCardVickers);
scrollablePane.AddItem(new Weapon(t2DBrowning,
ScreenGameplay.soundBrowning, new Vector2f(0f, 0f),
"Browning M1919", 0x7d, 120, 3, 0x2a, 0.122173f, 0x52d));
this.weaponCardList.add(t2DCardBrowning);
scrollablePane.AddItem(new Weapon(t2DAAGun, ScreenGameplay.soundNambu,
new Vector2f(0f, 0f), "Sd.Kfz 7/1", 360, 150, 1, 0x3a,
0.1570796f, 0x6d6));
this.weaponCardList.add(t2DCardAAGun);
this.moneyDeductionTagList = new java.util.ArrayList<MoneyDeductionTag>();
for (DrawableObject obj2 : scrollablePane.itemList) {
obj2.scale = new Vector2f(0.3f, 0.3f);
}
Help.currentWeapon = (Weapon) scrollablePane.itemList.get(0);
Help.AIWeapon = (Weapon) scrollablePane.itemList.get(2);
this.diplayTexturePosition = new Vector2f(240f, 100f);
}
@Override
public void Update(GameTime gameTime) {
super.Update(gameTime);
scrollablePane.Update(super.mousePositionList);
for (int i = 0; i < this.moneyDeductionTagList.size(); i++) {
this.moneyDeductionTagList.get(i).Update();
if (this.moneyDeductionTagList.get(i).isDead) {
this.moneyDeductionTagList.remove(i);
}
}
if (!super.isTranAnimFinished) {
if (super.mousePositionList.size() > 0) {
super.mousePositionList.clear();
}
return;
}
switch (super.buttonClicked.getButtonID()) {
case Proceed:
Help.currentGameState = Help.GameScreen.LevelUp2;
super.buttonClicked = null;
for (Button button2 : super.buttonList) {
button2.ButtonInitialize();
}
super.isTranAnimFinished = false;
if (super.mousePositionList.size() > 0) {
super.mousePositionList.clear();
}
return;
case Back:
Help.currentGameState = Help.GameScreen.MainMenu;
super.buttonClicked = null;
for (Button button : super.buttonList) {
button.ButtonInitialize();
}
super.isTranAnimFinished = false;
if (super.mousePositionList.size() > 0) {
super.mousePositionList.clear();
}
return;
case Buy: {
if (super.buttonClicked.isEffectTaken) {
super.isTranAnimFinished = false;
if (super.mousePositionList.size() > 0) {
super.mousePositionList.clear();
}
return;
}
Weapon weapon = (Weapon) scrollablePane.itemList
.get(scrollablePane.iSelectedItem);
if ((Help.money < weapon.price)
|| !(Help.currentWeapon.name != weapon.name)) {
super.isTranAnimFinished = false;
if (super.mousePositionList.size() > 0) {
super.mousePositionList.clear();
}
return;
}
if (weapon.name.equalsIgnoreCase("Sd.Kfz 7/1")) {
for (Button button3 : Help.currentBunker.skillsGained) {
if (button3.getButtonID() == Help.ButtonID.TagAAGun) {
Help.currentWeapon = new Weapon(weapon.texture,
weapon.firingSound, weapon.position,
weapon.name, weapon.magSize,
weapon.reloadLength, weapon.framesPerFire,
weapon.power, weapon.accuracy, weapon.price);
Help.money -= weapon.price;
int num2 = -weapon.price;
this.moneyDeductionTagList.add(new MoneyDeductionTag(
num2 + "", new Vector2f(680f, 380f)));
if (scrollablePane.iSelectedItem == (scrollablePane.itemList
.size() - 1)) {
Help.currentBunker.texture = ScreenGameplay.t2DBunkerAA;
} else {
Help.currentBunker.texture = ScreenGameplay.t2DBunkerBottom;
}
break;
}
}
} else {
Help.currentWeapon = new Weapon(weapon.texture,
weapon.firingSound, weapon.position, weapon.name,
weapon.magSize, weapon.reloadLength,
weapon.framesPerFire, weapon.power, weapon.accuracy,
weapon.price);
Help.money -= weapon.price;
int num3 = -weapon.price;
this.moneyDeductionTagList.add(new MoneyDeductionTag(num3 + "",
new Vector2f(680f, 380f)));
if (scrollablePane.iSelectedItem == (scrollablePane.itemList
.size() - 1)) {
Help.currentBunker.texture = ScreenGameplay.t2DBunkerAA;
} else {
Help.currentBunker.texture = ScreenGameplay.t2DBunkerBottom;
}
}
break;
}
default:
super.isTranAnimFinished = false;
if (super.mousePositionList.size() > 0) {
super.mousePositionList.clear();
}
return;
}
super.buttonClicked.isEffectTaken = true;
}
}
|
package com.tangjf.ttweb.enums;
/**
* 访问权限枚举类
*
* @version:v1.0
* @author: tangjf
* @date: 2017年4月26日 上午10:52:03
*
*/
public enum EnumPermissionRole {
/** 登录 */
LOGIN,
/** 前端 */
NET,
/** 管理后台 */
ADMIN;
}
|
package com.fullcontact.api.libs.fullcontact4j.http.location;
import com.fullcontact.api.libs.fullcontact4j.http.FCResponse;
import lombok.*;
import java.util.Collections;
import java.util.List;
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@Getter
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class LocationEnrichmentResponse extends FCResponse {
private List<Location> locations = Collections.emptyList();
public List<Location> getPossibleLocations() {
return locations;
}
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@Getter
@EqualsAndHashCode
@ToString
public static class Location {
private String city;
private String county;
private LocationCodeInfo state = new LocationCodeInfo();
private LocationCodeInfo country = new LocationCodeInfo();
private String continent;
private int population;
private String normalizedLocation;
}
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@Getter
@EqualsAndHashCode
@ToString
public static class LocationCodeInfo {
private String name;
private String code;
}
}
|
package com.seachangesimulations.platform.mvc.formbeans.author;
public class AuthorAddPluginFormBean {
private Long rawPluginId;
private Long customizedPluginId;
private String pluginHeading;
public Long getRawPluginId() {
return rawPluginId;
}
public void setRawPluginId(Long rawPluginId) {
this.rawPluginId = rawPluginId;
}
public Long getCustomizedPluginId() {
return customizedPluginId;
}
public void setCustomizedPluginId(Long customizedPluginId) {
this.customizedPluginId = customizedPluginId;
}
public String getPluginHeading() {
return pluginHeading;
}
public void setPluginHeading(String pluginHeading) {
this.pluginHeading = pluginHeading;
}
}
|
package bsi.lars.gui.editor.elements;
public class EMeasure3 extends Element {
private int to_measure_id;
private String description_long;
public EMeasure3(int id, String name, String description, int to_measure_id, String description_long) {
super(id, name, description);
this.to_measure_id = to_measure_id;
this.description_long = description_long;
}
public int getTo_measure_id() {
return to_measure_id;
}
public String getDescription_long() {
return description_long;
}
}
|
/*
* Integrated Rule Inference System (IRIS):
* An extensible rule inference system for datalog with extensions.
*
* Copyright (C) 2008 Semantic Technology Institute (STI) Innsbruck,
* University of Innsbruck, Technikerstrasse 21a, 6020 Innsbruck, Austria.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.deri.iris.api.terms;
import java.io.Serializable;
/**
* <p>
* An interface which defines a term. A term is a name for an object
* in the universe of discourse. There are three types of terms:
* <ul>
* <li> variables</li>
* <li> constants</li>
* <li> constructed terms (functional symbols)</li>
* </ul>
* </p>
* <p>
* By convention <code>null</code> is the smalles possible term of all types.
* So if you compare a term using the compare method you will always recieve
* a positive number.
* </p>
* <p>
* $Id: ITerm.java,v 1.15 2007-10-15 15:20:38 bazbishop237 Exp $
* </p>
* @author Darko Anicic, DERI Innsbruck
* @author Richard Pöttler (richard dot poettler at deri dot at)
*/
public interface ITerm extends Comparable<ITerm>, Serializable {
/**
* Checks whether the term is ground (a term with no variables).
*
* @return <code>true</code> if the term is ground,
* otherwise <code>false</code>.
*/
public boolean isGround();
/**
* Returns a vale of the term.
*
* @return The term value.
*/
public Object getValue();
}
|
package io.smallrye.mutiny.operators.multi.builders;
import java.util.function.Supplier;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import io.smallrye.mutiny.helpers.ParameterValidation;
import io.smallrye.mutiny.helpers.Subscriptions;
import io.smallrye.mutiny.operators.AbstractMulti;
public class DeferredMulti<T> extends AbstractMulti<T> {
private final Supplier<? extends Publisher<? extends T>> supplier;
public DeferredMulti(Supplier<? extends Publisher<? extends T>> supplier) {
this.supplier = ParameterValidation.nonNull(supplier, "supplier");
}
@Override
protected Publisher<T> publisher() {
return this;
}
@Override
public void subscribe(Subscriber<? super T> downstream) {
Publisher<? extends T> publisher;
try {
publisher = supplier.get();
if (publisher == null) {
throw new NullPointerException(ParameterValidation.SUPPLIER_PRODUCED_NULL);
}
} catch (Throwable failure) {
Subscriptions.fail(downstream, failure);
return;
}
publisher.subscribe(downstream);
}
}
|
/*
The MIT License (MIT)
Copyright (c) 2018 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.BAMRecordCodec;
import htsjdk.samtools.SAMFileHeader;
import htsjdk.samtools.SAMFileHeader.SortOrder;
import htsjdk.samtools.SAMFileWriter;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SAMRecordIterator;
import htsjdk.samtools.SAMRecordQueryNameComparator;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.util.CloseableIterator;
import htsjdk.samtools.util.CloserUtil;
import htsjdk.samtools.util.SortingCollection;
import java.io.File;
import java.io.IOException;
import java.util.Comparator;
import java.util.List;
import com.github.lindenb.jvarkit.util.picard.SAMSequenceDictionaryProgress;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParametersDelegate;
import com.github.lindenb.jvarkit.util.jcommander.Launcher;
import com.github.lindenb.jvarkit.util.jcommander.Program;
import com.github.lindenb.jvarkit.util.log.Logger;
/**
BEGIN_DOC
## Example
```bash
$ java -jar dist/sortsamrefname.jar /commun/data/packages/samtools/1.2/samtools/examples/toy.sam 2> /dev/null
@HD VN:1.4 SO:unsorted
@SQ SN:ref LN:45
@SQ SN:ref2 LN:40
@CO SortSamRefName 1c7bc5e674136947586779a2aac53e576db4a67f /commun/data/packages/samtools/1.2/samtools/examples/toy.sam
r001 83 ref 37 30 9M = 7 -39 CAGCGCCAT *
r001 163 ref 7 30 8M4I4M1D3M = 37 39 TTAGATAAAGAGGATACTG * XX:B:S,12561,2,20,112
r002 0 ref 9 30 1S2I6M1P1I1P1I4M2I * 0 0 AAAAGATAAGGGATAAA *
r003 0 ref 9 30 5H6M * 0 0 AGCTAA *
r003 16 ref 29 30 6H5M * 0 0 TAGGC *
r004 0 ref 16 30 6M14N1I5M * 0 0 ATAGCTCTCAGC *
x1 0 ref2 1 30 20M * 0 0 AGGTTTTATAAAACAAATAA ????????????????????
x2 0 ref2 2 30 21M * 0 0 GGTTTTATAAAACAAATAATT ?????????????????????
x3 0 ref2 6 30 9M4I13M * 0 0 TTATAAAACAAATAATTAAGTCTACA ??????????????????????????
x4 0 ref2 10 30 25M * 0 0 CAAATAATTAAGTCTACAGAGCAAC ?????????????????????????
x5 0 ref2 12 30 24M * 0 0 AATAATTAAGTCTACAGAGCAACT ????????????????????????
x6 0 ref2 14 30 23M * 0 0 TAATTAAGTCTACAGAGCAACTA ???????????????????????
```
END_DOC
*/
@Program(
name="sortsamrefname",
description="Sort a BAM of contig and then on name",
keywords={"sam","sort"},
biostars=154220
)
public class SortSamRefName extends Launcher
{
private static final Logger LOG = Logger.build(SortSamRefName.class).make();
@Parameter(names={"-o","--output"},description=OPT_OUPUT_FILE_OR_STDOUT)
private File outputFile = null;
@ParametersDelegate
private WritingSortingCollection writingSortingCollection=new WritingSortingCollection();
@ParametersDelegate
private WritingBamArgs writingBamArgs=new WritingBamArgs();
private static class RefNameComparator implements
Comparator<SAMRecord>
{
private final SAMRecordQueryNameComparator nameCmp=new SAMRecordQueryNameComparator();
@Override
public int compare(final SAMRecord o1, final SAMRecord o2)
{
final int refIndex1 = o1.getReferenceIndex();
final int refIndex2 = o2.getReferenceIndex();
final int cmp = refIndex1 - refIndex2;
if (cmp != 0)
{
if (refIndex1 == -1 ) return 1;
if (refIndex2 == -1 ) return -1;
return cmp;
}
return nameCmp.compare(o1, o2);
}
}
public SortSamRefName()
{
}
@Override
public int doWork(final List<String> args) {
SamReader in=null;
SAMFileWriter out=null;
SAMRecordIterator iter=null;
CloseableIterator<SAMRecord> iter2=null;
SortingCollection<SAMRecord> sorter=null;
try
{
in = openSamReader(oneFileOrNull(args));
final SAMFileHeader header= in.getFileHeader();
final BAMRecordCodec bamRecordCodec=new BAMRecordCodec(header);
final RefNameComparator refNameComparator=new RefNameComparator();
sorter =SortingCollection.newInstance(
SAMRecord.class,
bamRecordCodec,
refNameComparator,
this.writingSortingCollection.getMaxRecordsInRam(),
this.writingSortingCollection.getTmpPaths()
);
sorter.setDestructiveIteration(true);
final SAMSequenceDictionaryProgress progress=new SAMSequenceDictionaryProgress(header).logger(LOG);
iter = in.iterator();
while(iter.hasNext())
{
sorter.add( progress.watch(iter.next()));
}
in.close();in=null;
sorter.doneAdding();
final SAMFileHeader header2=header.clone();
header2.addComment(getProgramName()+" "+getVersion()+" "+getProgramCommandLine());
header2.setSortOrder(SortOrder.unsorted);
out = this.writingBamArgs.openSAMFileWriter(outputFile,header2, true);
iter2 = sorter.iterator();
while(iter2.hasNext())
{
out.addAlignment(iter2.next());
}
out.close();out=null;
sorter.cleanup();
progress.finish();
return RETURN_OK;
}
catch(final Exception err)
{
LOG.error(err);
return -1;
}
finally
{
CloserUtil.close(iter2);
CloserUtil.close(iter);
CloserUtil.close(out);
CloserUtil.close(in);
}
}
public static void main(final String[] args) throws IOException
{
new SortSamRefName().instanceMainWithExit(args);
}
}
|
/*
* Copyright 2018 ThoughtWorks, 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.thoughtworks.go.domain.config;
import com.thoughtworks.go.config.*;
import com.thoughtworks.go.domain.BaseCollection;
import com.thoughtworks.go.domain.ConfigErrors;
import org.apache.commons.lang3.StringUtils;
import java.util.*;
import static java.lang.String.format;
import static java.util.stream.Collectors.toList;
@ConfigTag("configuration")
@ConfigCollection(value = ConfigurationProperty.class)
public class Configuration extends BaseCollection<ConfigurationProperty> implements Validatable {
public static final String CONFIGURATION = "configuration";
public static final String METADATA = "metadata";
public static final String VALUE_KEY = "value";
public static final String ERRORS_KEY = "errors";
private ConfigErrors errors = new ConfigErrors();
public Configuration() {
}
public Configuration(ConfigurationProperty... configurationProperties) {
Collections.addAll(this, configurationProperties);
}
public String forDisplay(List<ConfigurationProperty> propertiesToDisplay) {
ArrayList<String> list = new ArrayList<>();
for (ConfigurationProperty property : propertiesToDisplay) {
if (!property.isSecure()) {
list.add(format("%s=%s", property.getConfigurationKey().getName().toLowerCase(), property.getConfigurationValue().getValue()));
}
}
return format("[%s]", StringUtils.join(list, ", "));
}
public void setConfigAttributes(Object attributes, SecureKeyInfoProvider secureKeyInfoProvider) {
this.clear();
Map attributesMap = (Map) attributes;
for (Object o : attributesMap.values()) {
Map configurationAttributeMap = (Map) o;
ConfigurationProperty configurationProperty = new ConfigurationProperty();
configurationProperty.setConfigAttributes(configurationAttributeMap, secureKeyInfoProvider);
this.add(configurationProperty);
}
}
public List<String> listOfConfigKeys() {
ArrayList<String> list = new ArrayList<>();
for (ConfigurationProperty configurationProperty : this) {
list.add(configurationProperty.getConfigurationKey().getName());
}
return list;
}
public void addNewConfiguration(String key, boolean isSecure) {
if (isSecure) {
add(new ConfigurationProperty(new ConfigurationKey(key), new EncryptedConfigurationValue()));
} else {
add(new ConfigurationProperty(new ConfigurationKey(key), new ConfigurationValue()));
}
}
public void addNewConfigurationWithValue(String key, String value, boolean isSecure) {
if (isSecure) {
add(new ConfigurationProperty(new ConfigurationKey(key), new EncryptedConfigurationValue(value)));
} else {
add(new ConfigurationProperty(new ConfigurationKey(key), new ConfigurationValue(value)));
}
}
public ConfigurationProperty getProperty(final String key) {
return stream().filter(item -> item.getConfigurationKey().getName().equals(key)).findFirst().orElse(null);
}
public void addErrorFor(String key, String message) {
for (ConfigurationProperty configurationProperty : this) {
if (configurationProperty.getConfigurationKey().getName().equals(key)) {
configurationProperty.addErrorAgainstConfigurationValue(message);
return;
}
}
}
public void clearEmptyConfigurations() {
List<ConfigurationProperty> propertiesToRemove = new ArrayList<>();
for (ConfigurationProperty configurationProperty : this) {
ConfigurationValue configurationValue = configurationProperty.getConfigurationValue();
EncryptedConfigurationValue encryptedValue = configurationProperty.getEncryptedConfigurationValue();
if (StringUtils.isBlank(configurationProperty.getValue()) && (configurationValue == null || configurationValue.errors().isEmpty()) && (encryptedValue == null || encryptedValue.errors().isEmpty())) {
propertiesToRemove.add(configurationProperty);
}
}
this.removeAll(propertiesToRemove);
}
public void validateUniqueness(String entity) {
HashMap<String, ConfigurationProperty> map = new HashMap<>();
for (ConfigurationProperty property : this) {
property.validateKeyUniqueness(map, entity);
}
}
public void validateTree() {
for (ConfigurationProperty property : this) {
property.validate(null);
}
}
//TODO: Move the validateUniquenessCheck from the parents to this method. Parents include SCM, PluginProfile, PluggableArtifactConfig, PackageRepository, PackageDefinition, FetchPluggableTask
@Override
public void validate(ValidationContext validationContext) {}
@Override
public ConfigErrors errors() {
return errors;
}
public boolean hasErrors() {
for (ConfigurationProperty property : this) {
if (property.hasErrors()) {
return true;
}
}
return false;
}
@Override
public void addError(String fieldName, String message) {
addErrorFor(fieldName, message);
}
public Map<String, String> getConfigurationAsMap(boolean addSecureFields) {
Map<String, String> configurationMap = new LinkedHashMap<>();
for (ConfigurationProperty currentConfiguration : this) {
if (addSecureFields || !currentConfiguration.isSecure()) {
configurationMap.put(currentConfiguration.getConfigKeyName(), currentConfiguration.getValue());
}
}
return configurationMap;
}
public Map<String, Map<String, Object>> getPropertyMetadataAndValuesAsMap() {
Map<String, Map<String, Object>> configMap = new HashMap<>();
for (ConfigurationProperty property : this) {
Map<String, Object> mapValue = new HashMap<>();
mapValue.put("isSecure", property.isSecure());
if (property.isSecure()) {
mapValue.put(VALUE_KEY, property.getEncryptedValue());
} else {
mapValue.put(VALUE_KEY, property.getConfigurationValue().getValue());
}
mapValue.put("displayValue", property.getDisplayValue());
configMap.put(property.getConfigKeyName(), mapValue);
}
return configMap;
}
public Map<String, Map<String, String>> getConfigWithErrorsAsMap() {
Map<String, Map<String, String>> configMap = new HashMap<>();
for (ConfigurationProperty property : this) {
Map<String, String> mapValue = new HashMap<>();
if (property.isSecure()) {
mapValue.put(VALUE_KEY, property.getEncryptedValue());
} else {
mapValue.put(VALUE_KEY, property.getConfigurationValue().getValue());
}
if (!property.getAllErrors().isEmpty()) {
mapValue.put(ERRORS_KEY, StringUtils.join(property.getAllErrors().stream().map(ConfigErrors::getAll).collect(toList()), ", "));
}
configMap.put(property.getConfigKeyName(), mapValue);
}
return configMap;
}
}
|
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.messaging.simp.handler;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.condition.DestinationPatternsMessageCondition;
import org.springframework.messaging.handler.condition.MessageCondition;
/**
* Encapsulates the following request mapping conditions:
* <ol>
* <li>{@link SimpMessageTypeMessageCondition}
* <li>{@link DestinationPatternsMessageCondition}
* </ol>
*
* @author Rossen Stoyanchev
* @since 4.0
*/
public class SimpMessageMappingInfo implements MessageCondition<SimpMessageMappingInfo> {
private final SimpMessageTypeMessageCondition messageTypeMessageCondition;
private final DestinationPatternsMessageCondition destinationConditions;
private int hash;
public SimpMessageMappingInfo(SimpMessageTypeMessageCondition messageTypeMessageCondition,
DestinationPatternsMessageCondition destinationConditions) {
this.messageTypeMessageCondition = messageTypeMessageCondition;
this.destinationConditions = destinationConditions;
}
public SimpMessageTypeMessageCondition getMessageTypeMessageCondition() {
return this.messageTypeMessageCondition;
}
public DestinationPatternsMessageCondition getDestinationConditions() {
return this.destinationConditions;
}
@Override
public SimpMessageMappingInfo combine(SimpMessageMappingInfo other) {
SimpMessageTypeMessageCondition typeCond =
this.getMessageTypeMessageCondition().combine(other.getMessageTypeMessageCondition());
DestinationPatternsMessageCondition destCond =
this.destinationConditions.combine(other.getDestinationConditions());
return new SimpMessageMappingInfo(typeCond, destCond);
}
@Override
public SimpMessageMappingInfo getMatchingCondition(Message<?> message) {
SimpMessageTypeMessageCondition typeCond = this.messageTypeMessageCondition.getMatchingCondition(message);
if (typeCond == null) {
return null;
}
DestinationPatternsMessageCondition destCond = this.destinationConditions.getMatchingCondition(message);
if (destCond == null) {
return null;
}
return new SimpMessageMappingInfo(typeCond, destCond);
}
@Override
public int compareTo(SimpMessageMappingInfo other, Message<?> message) {
int result = this.messageTypeMessageCondition.compareTo(other.messageTypeMessageCondition, message);
if (result != 0) {
return result;
}
result = this.destinationConditions.compareTo(other.destinationConditions, message);
if (result != 0) {
return result;
}
return 0;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj != null && obj instanceof SimpMessageMappingInfo) {
SimpMessageMappingInfo other = (SimpMessageMappingInfo) obj;
return this.destinationConditions.equals(other.destinationConditions);
}
return false;
}
@Override
public int hashCode() {
int result = hash;
if (result == 0) {
result = destinationConditions.hashCode();
result = 31 * result + messageTypeMessageCondition.hashCode();
hash = result;
}
return result;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("{");
builder.append(this.destinationConditions);
builder.append(",messageType=").append(this.messageTypeMessageCondition);
builder.append('}');
return builder.toString();
}
}
|
/**
* 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.sqoop.connector.jdbc;
import org.apache.sqoop.common.ImmutableContext;
import org.apache.sqoop.connector.jdbc.configuration.ConnectionConfiguration;
import org.apache.sqoop.connector.jdbc.configuration.ImportJobConfiguration;
import org.apache.sqoop.job.etl.Destroyer;
public class GenericJdbcImportDestroyer extends Destroyer<ConnectionConfiguration, ImportJobConfiguration> {
@Override
public void destroy(boolean success, ImmutableContext context, ConnectionConfiguration connection, ImportJobConfiguration job) {
// No explicit action at the moment
}
}
|
package com.example.simplerestapis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SimpleRestApisApplication {
public static void main(String[] args) {
SpringApplication.run(SimpleRestApisApplication.class, args);
}
}
|
package baseball;
import java.util.ArrayList;
import java.util.List;
public class BaseballGameInputValidator {
private static final int BASEBALL_GAME_NUMBER_LENGTH = 3;
private static final String BASEBALL_GAME_LENGTH_EXCEPTION_MESSAGE = "3자리 수를 입력해주세요.";
private static final String BASEBALL_GAME_DIGIT_EXCEPTION_MESSAGE = "1부터 9사이의 수를 입력해주세요.";
private static final String BASEBALL_GAME_DUPLICATE_EXCEPTION_MESSAGE = "중복되지 않은 수를 입력해주세요.";
private static final String BASEBALL_GAME_CODE_EXCEPTION_MESSAGE = "1과 2 중 하나의 수를 입력해주세요.";
public void validateNumber(String numbers) {
if (!validateLength(numbers)) {
throw new IllegalArgumentException(BASEBALL_GAME_LENGTH_EXCEPTION_MESSAGE);
}
if (!validateDigit(numbers)) {
throw new IllegalArgumentException(BASEBALL_GAME_DIGIT_EXCEPTION_MESSAGE);
}
if (!validateDuplicate(numbers)) {
throw new IllegalArgumentException(BASEBALL_GAME_DUPLICATE_EXCEPTION_MESSAGE);
}
}
private boolean validateLength(String numbers) {
return numbers.length() == BASEBALL_GAME_NUMBER_LENGTH;
}
private boolean validateDigit(String numbers) {
for (char number : numbers.toCharArray()) {
if (number < '1' || number > '9') {
return false;
}
}
return true;
}
private boolean validateDuplicate(String numbers) {
List<Character> checkDuplicate = new ArrayList<>();
for (char number : numbers.toCharArray()) {
if (checkDuplicate.contains(number)) {
return false;
}
checkDuplicate.add(number);
}
return true;
}
public void validateCode(int code) {
if (code != 1 && code != 2) {
throw new IllegalArgumentException(BASEBALL_GAME_CODE_EXCEPTION_MESSAGE);
}
}
}
|
/*
* Copyright 2014-2015 Groupon, Inc
* Copyright 2014-2015 The Billing Project, LLC
*
* The Billing Project 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.killbill.billing.plugin.coupon.model;
import java.util.UUID;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
/**
* Object used to apply a coupon to an existing account
*
* Created by maguero on 01/09/15.
*/
public class ApplyCouponRequest {
private UUID accountId;
private UUID subscriptionId;
private String couponCode;
public String getCouponCode() {
return couponCode;
}
public void setCouponCode(String couponCode) {
this.couponCode = couponCode;
}
public UUID getAccountId() {
return accountId;
}
public void setAccountId(UUID accountId) {
this.accountId = accountId;
}
public UUID getSubscriptionId() {
return subscriptionId;
}
public void setSubscriptionId(final UUID subscriptionId) {
this.subscriptionId = subscriptionId;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj.getClass() != getClass()) {
return false;
}
ApplyCouponRequest rhs = (ApplyCouponRequest) obj;
return new EqualsBuilder()
.append(this.accountId, rhs.accountId)
.append(this.subscriptionId, rhs.subscriptionId)
.append(this.couponCode, rhs.couponCode)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder()
.append(accountId)
.append(subscriptionId)
.append(couponCode)
.toHashCode();
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("accountId", accountId)
.append("subscriptionId", subscriptionId)
.append("couponCode", couponCode)
.toString();
}
}
|
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.item.recipe.crafting;
import static org.spongepowered.common.item.inventory.util.InventoryUtil.toSpongeInventory;
import com.google.common.base.Preconditions;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.util.NonNullList;
import org.spongepowered.api.item.inventory.ItemStackSnapshot;
import org.spongepowered.api.item.inventory.crafting.CraftingGridInventory;
import org.spongepowered.api.item.recipe.crafting.CraftingRecipe;
import org.spongepowered.api.world.World;
import org.spongepowered.common.item.inventory.util.ItemStackUtil;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
public abstract class AbstractSpongeCraftingRecipe implements CraftingRecipe, IRecipe {
@Override
public boolean matches(InventoryCrafting inv, net.minecraft.world.World worldIn) {
return matches(this::isValid, inv, worldIn);
}
@Override
public ItemStack getCraftingResult(InventoryCrafting inv) {
return getCraftingResult(this::getResult, inv);
}
@Override
public ItemStack getRecipeOutput() {
return getRecipeOutput(this::getExemplaryResult);
}
@Override
public NonNullList<ItemStack> getRemainingItems(InventoryCrafting inv) {
return getRemainingItems(this::getRemainingItems, inv);
}
public static boolean matches(BiFunction<CraftingGridInventory, World, Boolean> isValid, InventoryCrafting inv, net.minecraft.world.World worldIn) {
return isValid.apply(toSpongeInventory(inv), (World) worldIn);
}
public static ItemStack getCraftingResult(Function<CraftingGridInventory, ItemStackSnapshot> getResult, InventoryCrafting inv) {
ItemStackSnapshot result = getResult.apply(toSpongeInventory(inv));
Preconditions.checkNotNull(result, "The Sponge implementation returned a `null` result.");
return ItemStackUtil.fromSnapshotToNative(result);
}
public static ItemStack getRecipeOutput(Supplier<ItemStackSnapshot> getExemplaryResult) {
return ItemStackUtil.fromSnapshotToNative(getExemplaryResult.get());
}
public static NonNullList<ItemStack> getRemainingItems(Function<CraftingGridInventory, List<ItemStackSnapshot>> getRemainingItems, InventoryCrafting inv) {
List<ItemStackSnapshot> spongeResult = getRemainingItems.apply(toSpongeInventory(inv));
if (spongeResult.size() != inv.getSizeInventory()) {
throw new IllegalStateException("The number of ItemStackSnapshots returned by getRemainingItems must be equal to the size of the GridInventory.");
}
NonNullList<ItemStack> result = NonNullList.withSize(inv.getSizeInventory(), ItemStack.EMPTY);
for(int i = 0; i < spongeResult.size(); i++) {
ItemStack item = ItemStackUtil.fromSnapshotToNative(spongeResult.get(i));
result.set(i, item != null ? item : ItemStack.EMPTY);
}
return result;
}
}
|
/*
* Copyright (c) CovertJaguar, 2014 http://railcraft.info
*
* This code is the property of CovertJaguar
* and may only be used with explicit written
* permission unless otherwise specified on the
* license page at http://railcraft.info/wiki/info:license.
*/
package mods.railcraft.common.gui.slots;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.inventory.Slot;
import mods.railcraft.api.carts.bore.IBoreHead;
public class SlotBore extends Slot
{
public SlotBore(IInventory iinventory, int slotIndex, int posX, int posY)
{
super(iinventory, slotIndex, posX, posY);
}
@Override
public int getSlotStackLimit()
{
return 1;
}
@Override
public boolean isItemValid(ItemStack stack)
{
return canPlaceItem(stack);
}
public static boolean canPlaceItem(ItemStack stack)
{
return stack != null && stack.getItem() instanceof IBoreHead;
}
}
|
package com.dungeonstory.ui.test.integration.authentication;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import com.vaadin.testbench.TestBenchTestCase;
import com.vaadin.testbench.elements.FormLayoutElement;
import com.vaadin.testbench.elements.PasswordFieldElement;
import com.vaadin.testbench.elements.TextFieldElement;
/**
*
* This class knows how to create a new user.
*
*/
public class NewUserPageObject extends TestBenchTestCase {
@FindBy(id = "newUserFormSave")
private WebElement saveButton;
@FindBy(id = "newUserFormCancel")
private WebElement cancelButton;
public NewUserPageObject(WebDriver driver) {
setDriver(driver);
}
public void enterInfo(String username, String password, String name, String email) {
$(TextFieldElement.class).id("newUsername").setValue(username);
$(PasswordFieldElement.class).id("newPassword").setValue(password);
$(TextFieldElement.class).id("newName").setValue(name);
$(TextFieldElement.class).id("newEmail").setValue(email);
}
public void submit() {
saveButton.click();
}
public void cancel() {
cancelButton.click();
}
public boolean isVisible() {
return $(FormLayoutElement.class).id("newUserForm").isDisplayed();
}
}
|
/*
* IntPTI: integer error fixing by proper-type inference
* Copyright (c) 2017.
*
* Open-source component:
*
* CPAchecker
* Copyright (C) 2007-2014 Dirk Beyer
*
* Guava: Google Core Libraries for Java
* Copyright (C) 2010-2006 Google
*
*
*/
package org.sosy_lab.cpachecker.cfa.parser.eclipse;
import org.sosy_lab.common.ChildFirstPatternClassLoader;
import org.sosy_lab.common.Classes;
import org.sosy_lab.common.configuration.Configuration;
import org.sosy_lab.common.configuration.InvalidConfigurationException;
import org.sosy_lab.common.log.LogManager;
import org.sosy_lab.cpachecker.cfa.CParser;
import org.sosy_lab.cpachecker.cfa.CParser.Dialect;
import org.sosy_lab.cpachecker.cfa.Parser;
import org.sosy_lab.cpachecker.cfa.types.MachineModel;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.URLClassLoader;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.regex.Pattern;
/**
* We load the parser in its own class loader, so both all Eclipse objects
* and all Eclipse classes can be garbage collected when they are not needed anymore.
* Without this, nothing could be garbage collected because all the parser objects
* are referenced statically inside their classes.
*/
public class EclipseParsers {
private EclipseParsers() {
}
private static final Pattern OUR_CLASSES =
Pattern.compile("^(org\\.eclipse|org\\.sosy_lab\\.cpachecker\\.cfa\\.parser\\.eclipse)\\..*");
private static final String C_PARSER_CLASS =
"org.sosy_lab.cpachecker.cfa.parser.eclipse.c.EclipseCParser";
private static final String JAVA_PARSER_CLASS =
"org.sosy_lab.cpachecker.cfa.parser.eclipse.java.EclipseJavaParser";
private static WeakReference<ClassLoader> loadedClassLoader = new WeakReference<>(null);
private static WeakReference<Constructor<? extends CParser>> loadedCParser =
new WeakReference<>(null);
private static WeakReference<Constructor<? extends Parser>> loadedJavaParser =
new WeakReference<>(null);
private static final AtomicInteger loadingCount = new AtomicInteger(0);
private static ClassLoader getClassLoader(LogManager logger) {
ClassLoader classLoader = loadedClassLoader.get();
if (classLoader != null) {
return classLoader;
}
// garbage collected or first time we come here
if (loadingCount.incrementAndGet() > 1) {
logger.log(Level.INFO, "Repeated loading of Eclipse source parser");
}
classLoader = EclipseParsers.class.getClassLoader();
if (classLoader instanceof URLClassLoader) {
classLoader = new ChildFirstPatternClassLoader(OUR_CLASSES,
((URLClassLoader) classLoader).getURLs(), classLoader);
}
loadedClassLoader = new WeakReference<>(classLoader);
return classLoader;
}
public static CParser getCParser(
Configuration config,
LogManager logger,
CParser.Dialect dialect,
MachineModel machine) {
try {
Constructor<? extends CParser> parserConstructor = loadedCParser.get();
if (parserConstructor == null) {
ClassLoader classLoader = getClassLoader(logger);
@SuppressWarnings("unchecked")
Class<? extends CParser> parserClass =
(Class<? extends CParser>) classLoader.loadClass(C_PARSER_CLASS);
parserConstructor = parserClass.getConstructor(
new Class<?>[]{Configuration.class, LogManager.class, Dialect.class, MachineModel.class});
parserConstructor.setAccessible(true);
loadedCParser = new WeakReference<Constructor<? extends CParser>>(parserConstructor);
}
return parserConstructor.newInstance(config, logger, dialect, machine);
} catch (ReflectiveOperationException e) {
throw new Classes.UnexpectedCheckedException("Failed to create Eclipse CDT parser", e);
}
}
public static Parser getJavaParser(LogManager logger, Configuration config)
throws InvalidConfigurationException {
try {
Constructor<? extends Parser> parserConstructor = loadedJavaParser.get();
if (parserConstructor == null) {
ClassLoader classLoader = getClassLoader(logger);
@SuppressWarnings("unchecked")
Class<? extends CParser> parserClass =
(Class<? extends CParser>) classLoader.loadClass(JAVA_PARSER_CLASS);
parserConstructor =
parserClass.getConstructor(new Class<?>[]{LogManager.class, Configuration.class});
parserConstructor.setAccessible(true);
loadedJavaParser = new WeakReference<Constructor<? extends Parser>>(parserConstructor);
}
try {
return parserConstructor.newInstance(logger, config);
} catch (InvocationTargetException e) {
if (e.getCause() instanceof InvalidConfigurationException) {
throw (InvalidConfigurationException) e.getCause();
}
throw e;
}
} catch (ReflectiveOperationException e) {
throw new Classes.UnexpectedCheckedException("Failed to create Eclipse Java parser", e);
}
}
}
|
/*
* MIT License
*
* Copyright (c) 2017 Frederik Ar. Mikkelsen
*
* 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 fredboat.event;
import fredboat.Config;
import fredboat.audio.GuildPlayer;
import fredboat.audio.PlayerRegistry;
import fredboat.command.fun.TalkCommand;
import fredboat.command.music.control.SkipCommand;
import fredboat.command.util.HelpCommand;
import fredboat.commandmeta.CommandManager;
import fredboat.commandmeta.CommandRegistry;
import fredboat.commandmeta.abs.Command;
import fredboat.db.EntityReader;
import fredboat.feature.I18n;
import fredboat.feature.togglz.FeatureFlags;
import fredboat.util.Tuple2;
import fredboat.util.ratelimit.Ratelimiter;
import net.dv8tion.jda.core.entities.Game;
import net.dv8tion.jda.core.entities.User;
import net.dv8tion.jda.core.events.ReadyEvent;
import net.dv8tion.jda.core.events.ReconnectedEvent;
import net.dv8tion.jda.core.events.guild.GuildLeaveEvent;
import net.dv8tion.jda.core.events.guild.voice.GuildVoiceJoinEvent;
import net.dv8tion.jda.core.events.guild.voice.GuildVoiceLeaveEvent;
import net.dv8tion.jda.core.events.message.MessageDeleteEvent;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import net.dv8tion.jda.core.events.message.priv.PrivateMessageReceivedEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
public class EventListenerBoat extends AbstractEventListener {
private static final Logger log = LoggerFactory.getLogger(EventListenerBoat.class);
//first string is the users message ID, second string the id of fredboat's message that should be deleted if the
// user's message is deleted
public static Map<String, String> messagesToDeleteIfIdDeleted = new HashMap<>();
private User lastUserToReceiveHelp;
public EventListenerBoat() {
}
@Override
public void onMessageReceived(MessageReceivedEvent event) {
if (FeatureFlags.RATE_LIMITER.isActive()) {
if (Ratelimiter.getRatelimiter().isBlacklisted(event.getAuthor().getIdLong())) {
return;
}
}
if (event.getPrivateChannel() != null) {
log.info("PRIVATE" + " \t " + event.getAuthor().getName() + " \t " + event.getMessage().getRawContent());
return;
}
if (event.getAuthor().equals(event.getJDA().getSelfUser())) {
log.info(event.getGuild().getName() + " \t " + event.getAuthor().getName() + " \t " + event.getMessage().getRawContent());
return;
}
if (event.getMessage().getContent().length() < Config.CONFIG.getPrefix().length()) {
return;
}
if (event.getMessage().getContent().substring(0, Config.CONFIG.getPrefix().length()).equals(Config.CONFIG.getPrefix())) {
Command invoked = null;
log.info(event.getGuild().getName() + " \t " + event.getAuthor().getName() + " \t " + event.getMessage().getRawContent());
Matcher matcher = COMMAND_NAME_PREFIX.matcher(event.getMessage().getContent());
if(matcher.find()) {
String cmdName = matcher.group();
CommandRegistry.CommandEntry entry = CommandRegistry.getCommand(cmdName);
if(entry != null) {
invoked = entry.command;
} else {
log.info("Unknown command:", cmdName);
}
}
if (invoked == null) {
return;
}
limitOrExecuteCommand(invoked, event);
} else if (event.getMessage().getMentionedUsers().contains(event.getJDA().getSelfUser())) {
log.info(event.getGuild().getName() + " \t " + event.getAuthor().getName() + " \t " + event.getMessage().getRawContent());
CommandManager.commandsExecuted.getAndIncrement();
//regex101.com/r/9aw6ai/1/
String message = event.getMessage().getRawContent().replaceAll("<@!?[0-9]*>", "");
TalkCommand.talk(event.getMember(), event.getTextChannel(), message);
}
}
/**
* check the rate limit of user and execute the command if everything is fine
*/
private void limitOrExecuteCommand(Command invoked, MessageReceivedEvent event) {
Tuple2<Boolean, Class> ratelimiterResult = new Tuple2<>(true, null);
if (FeatureFlags.RATE_LIMITER.isActive()) {
ratelimiterResult = Ratelimiter.getRatelimiter().isAllowed(event.getMember(), invoked, 1, event.getTextChannel());
}
if (ratelimiterResult.a)
CommandManager.prefixCalled(invoked, event.getGuild(), event.getTextChannel(), event.getMember(), event.getMessage());
else {
String out = event.getMember().getAsMention() + ": " + I18n.get(event.getGuild()).getString("ratelimitedGeneralInfo");
if (ratelimiterResult.b == SkipCommand.class) { //we can compare classes with == as long as we are using the same classloader (which we are)
//add a nice reminder on how to skip more than 1 song
out += "\n" + MessageFormat.format(I18n.get(event.getGuild()).getString("ratelimitedSkipCommand"), "`" + Config.CONFIG.getPrefix() + "skip n-m`");
}
event.getTextChannel().sendMessage(out).queue();
}
}
@Override
public void onMessageDelete(MessageDeleteEvent event) {
if (messagesToDeleteIfIdDeleted.containsKey(event.getMessageId())) {
String msgId = messagesToDeleteIfIdDeleted.remove(event.getMessageId());
event.getChannel().deleteMessageById(msgId).queue();
}
}
@Override
public void onPrivateMessageReceived(PrivateMessageReceivedEvent event) {
if (FeatureFlags.RATE_LIMITER.isActive()) {
if (Ratelimiter.getRatelimiter().isBlacklisted(event.getAuthor().getIdLong())) {
return;
}
}
if (event.getAuthor() == lastUserToReceiveHelp) {
//Ignore, they just got help! Stops any bot chain reactions
return;
}
if (event.getAuthor().equals(event.getJDA().getSelfUser())) {
//Don't reply to ourselves
return;
}
event.getChannel().sendMessage(HelpCommand.getHelpDmMsg(null)).queue();
lastUserToReceiveHelp = event.getAuthor();
}
@Override
public void onReady(ReadyEvent event) {
super.onReady(event);
event.getJDA().getPresence().setGame(Game.of("Say " + Config.CONFIG.getPrefix() + "help"));
}
@Override
public void onReconnect(ReconnectedEvent event) {
event.getJDA().getPresence().setGame(Game.of("Say " + Config.CONFIG.getPrefix() + "help"));
}
/* music related */
@Override
public void onGuildVoiceLeave(GuildVoiceLeaveEvent event) {
GuildPlayer player = PlayerRegistry.getExisting(event.getGuild());
if (player == null) {
return;
}
//we got kicked from the server while in a voice channel, do nothing and return, because onGuildLeave()
// should take care of destroying stuff
if (!event.getGuild().isMember(event.getJDA().getSelfUser())) {
log.warn("onGuildVoiceLeave called for a guild where we aren't a member. This line should only ever be " +
"reached if we are getting kicked from that guild. Investigate if not.");
return;
}
if (player.getHumanUsersInVC().isEmpty()
&& player.getUserCurrentVoiceChannel(event.getGuild().getSelfMember()) == event.getChannelLeft()
&& !player.isPaused()) {
player.pause();
player.getActiveTextChannel().sendMessage(I18n.get(event.getGuild()).getString("eventUsersLeftVC")).queue();
}
}
@Override
public void onGuildVoiceJoin(GuildVoiceJoinEvent event) {
GuildPlayer player = PlayerRegistry.getExisting(event.getGuild());
if(player != null
&& player.isPaused()
&& player.getPlayingTrack() != null
&& event.getChannelJoined().getMembers().contains(event.getGuild().getSelfMember())
&& player.getHumanUsersInVC().size() == 1
&& EntityReader.getGuildConfig(event.getGuild().getId()).isAutoResume()
) {
player.getActiveTextChannel().sendMessage(I18n.get(event.getGuild()).getString("eventAutoResumed")).queue();
player.setPause(false);
}
}
@Override
public void onGuildLeave(GuildLeaveEvent event) {
PlayerRegistry.destroyPlayer(event.getGuild());
}
}
|
package net.oschina.app.improve.user.collection;
import android.content.DialogInterface;
import net.oschina.app.improve.base.BaseRecyclerFragment;
import net.oschina.app.improve.base.adapter.BaseRecyclerAdapter;
import net.oschina.app.improve.bean.Collection;
import net.oschina.app.improve.bean.News;
import net.oschina.app.improve.detail.general.BlogDetailActivity;
import net.oschina.app.improve.detail.general.EventDetailActivity;
import net.oschina.app.improve.detail.general.NewsDetailActivity;
import net.oschina.app.improve.detail.general.QuestionDetailActivity;
import net.oschina.app.improve.detail.general.SoftwareDetailActivity;
import net.oschina.app.improve.user.adapter.CollectionAdapter;
import net.oschina.app.improve.utils.CacheManager;
import net.oschina.app.improve.utils.DialogHelper;
import net.oschina.app.util.UIHelper;
import java.util.List;
/**
* Created by haibin
* on 2016/12/30.
*/
public class UserCollectionFragment extends BaseRecyclerFragment<UserCollectionContract.Presenter, Collection> implements
UserCollectionContract.View, BaseRecyclerAdapter.OnItemLongClickListener {
public static UserCollectionFragment newInstance() {
return new UserCollectionFragment();
}
@Override
protected void initData() {
if (mPresenter != null)
mPresenter.getCache(mContext);
super.initData();
mAdapter.setOnItemLongClickListener(this);
}
@Override
protected void onItemClick(Collection item, int position) {
switch (item.getType()) {
case News.TYPE_SOFTWARE:
SoftwareDetailActivity.show(mContext, item.getId(), true);
break;
case News.TYPE_QUESTION:
QuestionDetailActivity.show(mContext, item.getId(), true);
break;
case News.TYPE_BLOG:
BlogDetailActivity.show(mContext, item.getId(), true);
break;
case News.TYPE_TRANSLATE:
NewsDetailActivity.show(mContext, item.getId(), item.getType());
break;
case News.TYPE_EVENT:
EventDetailActivity.show(mContext, item.getId(), true);
break;
case News.TYPE_NEWS:
NewsDetailActivity.show(mContext, item.getId(), true);
break;
default:
UIHelper.showUrlRedirect(mContext, item.getUrl());
break;
}
}
@Override
public void onLongClick(final int position, long itemId) {
final Collection collection = mAdapter.getItem(position);
if (collection == null)
return;
DialogHelper.getConfirmDialog(mContext, "删除收藏", "是否确认删除该内容吗?", "确认", "取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mPresenter.getFavReverse(collection, position);
}
}).show();
}
@Override
public void showGetFavSuccess(int position) {
mAdapter.removeItem(position);
}
@Override
public void onRefreshSuccess(List<Collection> data) {
super.onRefreshSuccess(data);
CacheManager.saveToJson(mContext, UserCollectionPresenter.CACHE_NAME, data);
}
@Override
protected BaseRecyclerAdapter<Collection> getAdapter() {
return new CollectionAdapter(mContext);
}
}
|
package com.crowdin.utils;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.multipart.FormDataMultiPart;
import com.sun.jersey.multipart.file.FileDataBodyPart;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import org.apache.logging.log4j.LogManager;
import com.crowdin.parameters.CrowdinApiParameters;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.multipart.impl.MultiPartWriter;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
/**
*
* @author ihor <ihor.popyk@crowdin.com>
*/
public class HttpRequest {
public static final String FILE_EXTENTION_ZIP = ".zip";
public static final String REQUEST_POST_EXPANDED_UPLOAD = "upload";
public static final String REQUEST_POST_EXPANDED_DOWNLOAD = "download";
public static final String OPEN_BRACKET = "[";
public static final String CLOSE_BRACKET = "]";
/**
*
* @param url
* @param parameters
* @return String
*/
public ClientResponse get(String url, MultivaluedMap<String, String> parameters) {
Client client = new Client();
WebResource webResource = client.resource(url);
webResource = webResource.queryParams(parameters);
ClientResponse response = webResource.get(ClientResponse.class);
return response;
}
/**
*
* @param url
* @param parameters
* @param type
* @return String
*/
public ClientResponse post(String url, MultivaluedMap<String, String> parameters, String type) {
Client client = new Client();
ClientResponse clientResponse;
WebResource webResource = client.resource(url);
if (type != null && REQUEST_POST_EXPANDED_UPLOAD.equalsIgnoreCase(type)) {
clientResponse = uploadFiles(parameters, url);
} else if (type != null && REQUEST_POST_EXPANDED_DOWNLOAD.equalsIgnoreCase(type)) {
webResource = webResource.queryParams(parameters);
clientResponse = webResource.post(ClientResponse.class);
clientResponse = downloadFiles(parameters, clientResponse);
} else {
webResource = webResource.queryParams(parameters);
clientResponse = webResource.post(ClientResponse.class);
}
return clientResponse;
}
private ClientResponse uploadFiles(MultivaluedMap<String, String> parameters, String url) {
DefaultClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getClasses().add(MultiPartWriter.class);
Client client = Client.create(clientConfig);
FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
ClientResponse clientResponse = null;
WebResource webResource;
if (parameters.size() > 0) {
webResource = client.resource(url);
for (Map.Entry<String, List<String>> parameter : parameters.entrySet()) {
if (parameter.getKey().startsWith(CrowdinApiParameters.FILES)) {
File file = new File(parameter.getValue().get(0));
String crowdinPath = CrowdinApiParameters.FILES + OPEN_BRACKET + file.getName() + CLOSE_BRACKET;
for (Map.Entry<String, List<String>> title : parameters.entrySet()) {
if (title.getKey().startsWith(CrowdinApiParameters.TITLES)) {
if (parameter.getValue().get(0) != null && title.getKey() != null
&& parameter.getKey().replaceFirst(CrowdinApiParameters.FILES, "").equals(title.getKey().replaceFirst(CrowdinApiParameters.TITLES, "")) ) {
crowdinPath = CrowdinApiParameters.FILES + OPEN_BRACKET + title.getValue().get(0) + CLOSE_BRACKET;
}
}
}
formDataMultiPart.bodyPart(new FileDataBodyPart(crowdinPath, file, MediaType.APPLICATION_OCTET_STREAM_TYPE));
} else {
if (CrowdinApiParameters.FILE.equalsIgnoreCase(parameter.getKey())) {
File file = new File(parameter.getValue().get(0));
formDataMultiPart.bodyPart(new FileDataBodyPart(CrowdinApiParameters.FILE, file, MediaType.APPLICATION_OCTET_STREAM_TYPE));
} else if (CrowdinApiParameters.LOGO.equalsIgnoreCase(parameter.getKey())) {
File file = new File(parameter.getValue().get(0));
formDataMultiPart.bodyPart(new FileDataBodyPart(CrowdinApiParameters.LOGO, file, MediaType.APPLICATION_OCTET_STREAM_TYPE));
} else {
webResource = webResource.queryParam(parameter.getKey(), parameter.getValue().get(0));
}
}
}
if (formDataMultiPart.getBodyParts() != null && formDataMultiPart.getBodyParts().size() > 0) {
clientResponse = webResource.type(MediaType.MULTIPART_FORM_DATA_TYPE)
.post(ClientResponse.class, formDataMultiPart);
} else {
clientResponse = webResource.type(MediaType.MULTIPART_FORM_DATA_TYPE)
.post(ClientResponse.class);
}
}
return clientResponse;
}
private ClientResponse downloadFiles(MultivaluedMap<String, String> parameters, ClientResponse clientResponse) {
File file = new File(parameters.getFirst(CrowdinApiParameters.DESTINATION_FOLDER) + parameters.getFirst(CrowdinApiParameters.DOWNLOAD_PACKAGE) + FILE_EXTENTION_ZIP);
InputStream inputStream = clientResponse.getEntity(InputStream.class);
try {
Files.copy(inputStream, file.toPath());
} catch (IOException ex) {
}
return clientResponse;
}
}
|
/*
* GridGain Community Edition Licensing
* Copyright 2019 GridGain Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License") modified with Commons Clause
* Restriction; 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.
*
* Commons Clause Restriction
*
* The Software is provided to you by the Licensor under the License, as defined below, subject to
* the following condition.
*
* Without limiting other conditions in the License, the grant of rights under the License will not
* include, and the License does not grant to you, the right to Sell the Software.
* For purposes of the foregoing, “Sell” means practicing any or all of the rights granted to you
* under the License to provide to third parties, for a fee or other consideration (including without
* limitation fees for hosting or consulting/ support services related to the Software), a product or
* service whose value derives, entirely or substantially, from the functionality of the Software.
* Any license notice or attribution required by the License must also include this Commons Clause
* License Condition notice.
*
* For purposes of the clause above, the “Licensor” is Copyright 2019 GridGain Systems, Inc.,
* the “License” is the Apache License, Version 2.0, and the Software is the GridGain Community
* Edition software provided with this notice.
*/
package org.apache.ignite.internal.processors.cache.datastructures.partitioned;
import org.apache.ignite.cache.CacheAtomicityMode;
import static org.apache.ignite.cache.CacheAtomicityMode.ATOMIC;
/**
* Set tests.
*/
public class GridCachePartitionedAtomicSetSelfTest extends GridCachePartitionedSetSelfTest {
/** {@inheritDoc} */
@Override protected CacheAtomicityMode collectionCacheAtomicityMode() {
return ATOMIC;
}
}
|
package io.nuls.base.api.provider;
import io.nuls.core.constant.ErrorCode;
import io.nuls.core.model.StringUtils;
import java.util.List;
/**
* @Author: zhoulijun
* @Time: 2019-03-06 15:44
* @Description: 功能描述
*/
public abstract class BaseService {
/**
* 默认chainId
* 从配置文件中注入
*/
private int chainId;
protected <T> Result<T> success(T data) {
return new Result<>(data);
}
protected <T> Result<T> success(List<T> list) {
return new Result<>(list);
}
public static Result fail(ErrorCode errorCode, String message) {
return new Result(errorCode.getCode(), StringUtils.isNotBlank(message) ? message : errorCode.getMsg());
}
public static Result fail(String errorCode) {
return fail(ErrorCode.init(errorCode));
}
public static Result fail(ErrorCode errorCode) {
return fail(errorCode, errorCode.getMsg());
}
public int getChainId() {
return chainId;
}
public void setChainId(int chainId) {
this.chainId = chainId;
}
}
|
package com.nelson.powermock.answer.controller;
import com.nelson.powermock.answer.service.EmployeeService;
public class EmployeeController
{
public String getEmail(String userName) {
EmployeeService employeeService = new EmployeeService();
String email = employeeService.findEmailByUserName(userName);
return email;
}
}
|
package nl.mahmood.androidbackgroundservice;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity
{
private Intent serviceIntent;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serviceIntent = new Intent(this, MyService.class);
}
public void startService(View view)
{
startService(serviceIntent);
}
public void nextActivity(View view)
{
startActivity(new Intent(MainActivity.this, MainActivity2.class));
}
public void stopService(View view)
{
stopService(serviceIntent);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.