text
stringlengths 7
1.01M
|
|---|
package com.otaliastudios.cameraview.engine.action;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;
import android.hardware.camera2.TotalCaptureResult;
import android.os.Build;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
/**
* The holder of {@link Action}.
*
* This class should keep a list or set of currently running actions, and offers
* to them the base Camera2 objects that are needed to apply changes.
*
* This class, or an holder of it, should also forward the capture callbacks
* to all {@link Action}s. See {@link com.otaliastudios.cameraview.engine.Camera2Engine} for
* our implementation.
*/
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
public interface ActionHolder {
/**
* Adds a new action
* @param action action
*/
void addAction(@NonNull Action action);
/**
* Removes a previously added action
* @param action action
*/
void removeAction(@NonNull Action action);
/**
* Returns the {@link CameraCharacteristics} of the current
* camera device.
* @param action action
* @return characteristics
*/
@NonNull
CameraCharacteristics getCharacteristics(@NonNull Action action);
/**
* Returns the latest {@link TotalCaptureResult}. Can be used
* by actions to start querying the state before receiving their
* first frame.
* @param action action
* @return last result
*/
@NonNull
TotalCaptureResult getLastResult(@NonNull Action action);
/**
* Returns the current {@link CaptureRequest.Builder} so that
* actions can apply changes to it and later submit them.
* @param action action
* @return the builder
*/
@NonNull
CaptureRequest.Builder getBuilder(@NonNull Action action);
/**
* Applies the current builder (as per {@link #getBuilder(Action)})
* as a repeating request on the preview.
* @param source action
*/
void applyBuilder(@NonNull Action source);
/**
* Applies the given builder as a single capture request.
* Callers can catch the exception and choose what to do.
* @param source action
* @param builder builder
* @throws CameraAccessException camera exception
*/
void applyBuilder(@NonNull Action source, @NonNull CaptureRequest.Builder builder)
throws CameraAccessException;
}
|
package com.wangli.gulimall.order.controller;
import java.util.Arrays;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.wangli.gulimall.order.entity.PaymentInfoEntity;
import com.wangli.gulimall.order.service.PaymentInfoService;
import com.wangli.common.utils.PageUtils;
import com.wangli.common.utils.R;
/**
* 支付信息表
*
* @author wangli
* @email 1151723225@qq.com
* @date 2021-05-30 13:55:12
*/
@RestController
@RequestMapping("order/paymentinfo")
public class PaymentInfoController {
@Autowired
private PaymentInfoService paymentInfoService;
/**
* 列表
*/
@RequestMapping("/list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = paymentInfoService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{id}")
public R info(@PathVariable("id") Long id){
PaymentInfoEntity paymentInfo = paymentInfoService.getById(id);
return R.ok().put("paymentInfo", paymentInfo);
}
/**
* 保存
*/
@RequestMapping("/save")
public R save(@RequestBody PaymentInfoEntity paymentInfo){
paymentInfoService.save(paymentInfo);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
public R update(@RequestBody PaymentInfoEntity paymentInfo){
paymentInfoService.updateById(paymentInfo);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
public R delete(@RequestBody Long[] ids){
paymentInfoService.removeByIds(Arrays.asList(ids));
return R.ok();
}
}
|
/*
* Copyright 2006-2021 Prowide
*
* 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.prowidesoftware.swift.model.field;
import com.prowidesoftware.swift.model.Tag;
import com.prowidesoftware.Generated;
import com.prowidesoftware.deprecation.ProwideDeprecated;
import com.prowidesoftware.deprecation.TargetYear;
import java.io.Serializable;
import java.util.Locale;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Calendar;
import com.prowidesoftware.swift.model.field.DateContainer;
import com.prowidesoftware.swift.model.field.DateResolver;
import org.apache.commons.lang3.StringUtils;
import com.prowidesoftware.swift.model.field.SwiftParseUtils;
import com.prowidesoftware.swift.model.field.Field;
import com.prowidesoftware.swift.model.*;
import com.prowidesoftware.swift.utils.SwiftFormatUtils;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
* <strong>SWIFT MT Field 31R</strong>
* <p>
* Model and parser for field 31R of a SWIFT MT message.
*
* <p>Subfields (components) Data types
* <ol>
* <li><code>Calendar</code></li>
* <li><code>Calendar</code></li>
* </ol>
*
* <p>Structure definition
* <ul>
* <li>validation pattern: <code><DATE2>[/<DATE2>]</code></li>
* <li>parser pattern: <code><DATE2>[/<DATE2>]</code></li>
* <li>components pattern: <code>EE</code></li>
* </ul>
*
* <p>
* This class complies with standard release <strong>SRU2021</strong>
*/
@SuppressWarnings("unused")
@Generated
public class Field31R extends Field implements Serializable, DateContainer {
/**
* Constant identifying the SRU to which this class belongs to.
*/
public static final int SRU = 2021;
private static final long serialVersionUID = 1L;
/**
* Constant with the field name 31R
*/
public static final String NAME = "31R";
/**
* same as NAME, intended to be clear when using static imports
*/
public static final String F_31R = "31R";
public static final String PARSER_PATTERN = "<DATE2>[/<DATE2>]";
/**
* Components pattern
*
* Contains a description of the type for every component. This is <em>DEPRECATED</em>,
* use TYPES_PATTERN instead, because it distinguishes between N (number) and I (BigDecimal)
* @see #TYPES_PATTERN
*/
@Deprecated
@ProwideDeprecated(phase2=TargetYear.SRU2022)
public static final String COMPONENTS_PATTERN = "EE";
/**
* Types pattern
*
* Contains a description of the type for every component, use instead of COMPONENTS_PATTERN.
* @since 9.2.7
*/
public static final String TYPES_PATTERN = "EE";
/**
* Component number for the Date 1 subfield
*/
public static final Integer DATE_1 = 1;
/**
* Component number for the Date 2 subfield
*/
public static final Integer DATE_2 = 2;
/**
* Default constructor. Creates a new field setting all components to null.
*/
public Field31R() {
super(2);
}
/**
* Creates a new field and initializes its components with content from the parameter value.
* @param value complete field value including separators and CRLF
*/
public Field31R(final String value) {
super(value);
}
/**
* Creates a new field and initializes its components with content from the parameter tag.
* The value is parsed with {@link #parse(String)}
* @throws IllegalArgumentException if the parameter tag is null or its tagname does not match the field name
* @since 7.8
*/
public Field31R(final Tag tag) {
this();
if (tag == null) {
throw new IllegalArgumentException("tag cannot be null.");
}
if (!StringUtils.equals(tag.getName(), "31R")) {
throw new IllegalArgumentException("cannot create field 31R from tag "+tag.getName()+", tagname must match the name of the field.");
}
parse(tag.getValue());
}
/**
* Copy constructor.<br>
* Initializes the components list with a deep copy of the source components list.
* @param source a field instance to copy
* @since 7.7
*/
public static Field31R newInstance(Field31R source) {
Field31R cp = new Field31R();
cp.setComponents(new ArrayList<>(source.getComponents()));
return cp;
}
/**
* Create a Tag with this field name and the given value.
* Shorthand for <code>new Tag(NAME, value)</code>
* @see #NAME
* @since 7.5
*/
public static Tag tag(final String value) {
return new Tag(NAME, value);
}
/**
* Create a Tag with this field name and an empty string as value
* Shorthand for <code>new Tag(NAME, "")</code>
* @see #NAME
* @since 7.5
*/
public static Tag emptyTag() {
return new Tag(NAME, "");
}
/**
* Parses the parameter value into the internal components structure.
*
* <p>Used to update all components from a full new value, as an alternative
* to setting individual components. Previous component values are overwritten.
*
* @param value complete field value including separators and CRLF
* @since 7.8
*/
@Override
public void parse(final String value) {
init(2);
setComponent1(SwiftParseUtils.getTokenFirst(value, null, "/"));
setComponent2(SwiftParseUtils.getTokenSecondLast(value, "/"));
}
/**
* Serializes the fields' components into the single string value (SWIFT format)
*/
@Override
public String getValue() {
final StringBuilder result = new StringBuilder();
append(result, 1);
if (getComponent2() != null) {
result.append("/").append(getComponent2());
}
return result.toString();
}
/**
* Returns a localized suitable for showing to humans string of a field component.<br>
*
* @param component number of the component to display
* @param locale optional locale to format date and amounts, if null, the default locale is used
* @return formatted component value or null if component number is invalid or not present
* @throws IllegalArgumentException if component number is invalid for the field
* @since 7.8
*/
@Override
public String getValueDisplay(int component, Locale locale) {
if (component < 1 || component > 2) {
throw new IllegalArgumentException("invalid component number " + component + " for field 31R");
}
if (component == 1) {
//date: [YY]YYMMDD
java.text.DateFormat f = java.text.DateFormat.getDateInstance(java.text.DateFormat.DEFAULT, notNull(locale));
java.util.Calendar cal = getComponent1AsCalendar();
if (cal != null) {
return f.format(cal.getTime());
}
}
if (component == 2) {
//date: [YY]YYMMDD
java.text.DateFormat f = java.text.DateFormat.getDateInstance(java.text.DateFormat.DEFAULT, notNull(locale));
java.util.Calendar cal = getComponent2AsCalendar();
if (cal != null) {
return f.format(cal.getTime());
}
}
return null;
}
/**
* Returns the field components pattern
*
* This method is <em>DEPRECATED</em>, use <code>typesPattern()</code> instead.
* @see #typesPattern()
* @return the static value of Field31R.COMPONENTS_PATTERN
*/
@Override
@Deprecated
@ProwideDeprecated(phase2=TargetYear.SRU2022)
public final String componentsPattern() {
return COMPONENTS_PATTERN;
}
/**
* Returns the field component types pattern
*
* This method returns a letter representing the type for each component in the Field. It supersedes
* the Components Pattern because it distinguishes between N (Number) and I (BigDecimal).
* @since 9.2.7
* @see #TYPES_PATTERN
* @return the static value of Field31R.TYPES_PATTERN
*/
@Override
public final String typesPattern() {
return TYPES_PATTERN;
}
/**
* Returns the field parser pattern
* @return the static value of Field31R.PARSER_PATTERN
*/
@Override
public final String parserPattern() {
return PARSER_PATTERN;
}
/**
* Returns the field validator pattern
*/
@Override
public final String validatorPattern() {
return "<DATE2>[/<DATE2>]";
}
/**
* Given a component number it returns true if the component is optional,
* regardless of the field being mandatory in a particular message.<br>
* Being the field's value conformed by a composition of one or several
* internal component values, the field may be present in a message with
* a proper value but with some of its internal components not set.
*
* @param component component number, first component of a field is referenced as 1
* @return true if the component is optional for this field, false otherwise
*/
@Override
public boolean isOptional(int component) {
if (component == 2) {
return true;
}
return false;
}
/**
* Returns true if the field is a GENERIC FIELD as specified by the standard.
* @return true if the field is generic, false otherwise
*/
@Override
public boolean isGeneric() {
return false;
}
/**
* Returns the defined amount of components.<br>
* This is not the amount of components present in the field instance, but the total amount of components
* that this field accepts as defined.
* @since 7.7
*/
@Override
public int componentsSize() {
return 2;
}
/**
* Returns english label for components.
* <br>
* The index in the list is in sync with specific field component structure.
* @see #getComponentLabel(int)
* @since 7.8.4
*/
@Override
public List<String> getComponentLabels() {
List<String> result = new ArrayList<>();
result.add("Date 1");
result.add("Date 2");
return result;
}
/**
* Returns a mapping between component numbers and their label in camel case format.
* @since 7.10.3
*/
@Override
protected Map<Integer, String> getComponentMap() {
Map<Integer, String> result = new HashMap<>();
result.put(1, "date1");
result.put(2, "date2");
return result;
}
/**
* Gets the component 1 (Date 1).
* @return the component 1
*/
public String getComponent1() {
return getComponent(1);
}
/**
* Get the component 1 as Calendar
*
* @return the component 1 converted to Calendar or null if cannot be converted
*/
public java.util.Calendar getComponent1AsCalendar() {
return SwiftFormatUtils.getDate2(getComponent(1));
}
/**
* Gets the Date 1 (component 1).
* @return the Date 1 from component 1
*/
public String getDate1() {
return getComponent1();
}
/**
* Get the Date 1 (component 1) as Calendar
* @return the Date 1 from component 1 converted to Calendar or null if cannot be converted
*/
public java.util.Calendar getDate1AsCalendar() {
return getComponent1AsCalendar();
}
/**
* Gets the component 2 (Date 2).
* @return the component 2
*/
public String getComponent2() {
return getComponent(2);
}
/**
* Get the component 2 as Calendar
*
* @return the component 2 converted to Calendar or null if cannot be converted
*/
public java.util.Calendar getComponent2AsCalendar() {
return SwiftFormatUtils.getDate2(getComponent(2));
}
/**
* Gets the Date 2 (component 2).
* @return the Date 2 from component 2
*/
public String getDate2() {
return getComponent2();
}
/**
* Get the Date 2 (component 2) as Calendar
* @return the Date 2 from component 2 converted to Calendar or null if cannot be converted
*/
public java.util.Calendar getDate2AsCalendar() {
return getComponent2AsCalendar();
}
/**
* Set the component 1 (Date 1).
*
* @param component1 the Date 1 to set
* @return the field object to enable build pattern
*/
public Field31R setComponent1(String component1) {
setComponent(1, component1);
return this;
}
/**
* Set the component1 from a Calendar object.
*
* @param component1 the Calendar with the Date 1 content to set
* @return the field object to enable build pattern
*/
public Field31R setComponent1(java.util.Calendar component1) {
setComponent(1, SwiftFormatUtils.getDate2(component1));
return this;
}
/**
* Set the Date 1 (component 1).
*
* @param component1 the Date 1 to set
* @return the field object to enable build pattern
*/
public Field31R setDate1(String component1) {
return setComponent1(component1);
}
/**
* Set the Date 1 (component 1) from a Calendar object.
*
* @see #setComponent1(java.util.Calendar)
*
* @param component1 Calendar with the Date 1 content to set
* @return the field object to enable build pattern
*/
public Field31R setDate1(java.util.Calendar component1) {
return setComponent1(component1);
}
/**
* Set the component 2 (Date 2).
*
* @param component2 the Date 2 to set
* @return the field object to enable build pattern
*/
public Field31R setComponent2(String component2) {
setComponent(2, component2);
return this;
}
/**
* Set the component2 from a Calendar object.
*
* @param component2 the Calendar with the Date 2 content to set
* @return the field object to enable build pattern
*/
public Field31R setComponent2(java.util.Calendar component2) {
setComponent(2, SwiftFormatUtils.getDate2(component2));
return this;
}
/**
* Set the Date 2 (component 2).
*
* @param component2 the Date 2 to set
* @return the field object to enable build pattern
*/
public Field31R setDate2(String component2) {
return setComponent2(component2);
}
/**
* Set the Date 2 (component 2) from a Calendar object.
*
* @see #setComponent2(java.util.Calendar)
*
* @param component2 Calendar with the Date 2 content to set
* @return the field object to enable build pattern
*/
public Field31R setDate2(java.util.Calendar component2) {
return setComponent2(component2);
}
/**
* Returns all components that can be converted to a Calendar
*
* @return the list of converted components (a Calendar object or null)
*/
public List<Calendar> dates() {
return DateResolver.dates(this);
}
/**
* Returns the first component that can be converted to a Calendar
*
* @return the converted components (a Calendar object or null)
*/
public Calendar date() {
return DateResolver.date(this);
}
/**
* Returns the field's name composed by the field number and the letter option (if any)
* @return the static value of Field31R.NAME
*/
@Override
public String getName() {
return NAME;
}
/**
* Gets the first occurrence form the tag list or null if not found.
* @return null if not found o block is null or empty
* @param block may be null or empty
*/
public static Field31R get(final SwiftTagListBlock block) {
if (block == null || block.isEmpty()) {
return null;
}
final Tag t = block.getTagByName(NAME);
if (t == null) {
return null;
}
return new Field31R(t) ;
}
/**
* Gets the first instance of Field31R in the given message.
* @param msg may be empty or null
* @return null if not found or msg is empty or null
* @see #get(SwiftTagListBlock)
*/
public static Field31R get(final SwiftMessage msg) {
if (msg == null || msg.getBlock4() == null || msg.getBlock4().isEmpty())
return null;
return get(msg.getBlock4());
}
/**
* Gets a list of all occurrences of the field Field31R in the given message
* an empty list is returned if none found.
* @param msg may be empty or null in which case an empty list is returned
* @see #getAll(SwiftTagListBlock)
*/
public static List<Field31R> getAll(final SwiftMessage msg) {
if (msg == null || msg.getBlock4() == null || msg.getBlock4().isEmpty())
return java.util.Collections.emptyList();
return getAll(msg.getBlock4());
}
/**
* Gets a list of all occurrences of the field Field31R from the given block
* an empty list is returned if none found.
*
* @param block may be empty or null in which case an empty list is returned
*/
public static List<Field31R> getAll(final SwiftTagListBlock block) {
final List<Field31R> result = new ArrayList<>();
if (block == null || block.isEmpty()) {
return result;
}
final Tag[] arr = block.getTagsByName(NAME);
if (arr != null && arr.length > 0) {
for (final Tag f : arr) {
result.add( new Field31R(f));
}
}
return result;
}
/**
* This method deserializes the JSON data into a Field31R object.
* @param json JSON structure including tuples with label and value for all field components
* @return a new field instance with the JSON data parsed into field components or an empty field id the JSON is invalid
* @since 7.10.3
* @see Field#fromJson(String)
*/
public static Field31R fromJson(final String json) {
Field31R field = new Field31R();
JsonParser parser = new JsonParser();
JsonObject jsonObject = (JsonObject) parser.parse(json);
// **** COMPONENT 1 - Date 1
if (jsonObject.get("date1") != null) {
field.setComponent1(jsonObject.get("date1").getAsString());
}
// **** COMPONENT 2 - Date 2
if (jsonObject.get("date2") != null) {
field.setComponent2(jsonObject.get("date2").getAsString());
}
return field;
}
}
|
import java.awt.Polygon;
/*
* @author Kashif Sayeed
*/
public class SpaceCraft extends Sprite {
public SpaceCraft() {
active = true;
shape = new Polygon();
shape.addPoint(0, 35);
shape.addPoint(10, 0);
shape.addPoint(15, -25);
shape.addPoint(30, -35);
shape.addPoint(10, 0);
shape.addPoint(15, -25);
shape.addPoint(-15, -25);
shape.addPoint(-10, 0);
shape.addPoint(-30, -35);
shape.addPoint(-15, -25);
shape.addPoint(-10, 0);
shape.addPoint(0, 35);
drawShape = new Polygon();
drawShape.addPoint(0, 35);
drawShape.addPoint(10, 0);
drawShape.addPoint(15, -25);
drawShape.addPoint(30, -35);
drawShape.addPoint(10, 0);
drawShape.addPoint(15, -25);
drawShape.addPoint(-15, -25);
drawShape.addPoint(-10, 0);
drawShape.addPoint(-30, -35);
drawShape.addPoint(-15, -25);
drawShape.addPoint(-10, 0);
drawShape.addPoint(0, 35);
Xspeed = 0;
Yspeed = 0;
treasureMagnet = true;
thrust = 1;
rotation = 0.1;
powerup = 20;
}
public void accelerate() {
Yspeed += Math.sin(angle + Math.PI / 2) * thrust;
Xspeed += Math.cos(angle + Math.PI / 2) * thrust;
}
public void rotateRight() {
angle += rotation;
}
public void rotateLeft() {
angle -= rotation;
}
}
|
package com.balram.locker.main;
/**
* Created by redcarpet on 12/28/16.
*/
public class PatternLockImpl {
}
|
import java.lang.Math;
class AntiAliasedCircle extends Kernel
{
AntiAliasedCircle(int radius,double falloff)
{
// double f = radius * (1-falloff);
if (falloff >= radius)
falloff = radius - 1;
double f = radius - falloff;
width = 2*radius;
height = 2*radius;
originX = radius;
originY = radius;
double cx = (width + 1)/2.0;
double cy = (height + 1)/2.0;
alpha = new double[width * height];
for(int x=0;x<width;x++)
for(int y=0;y<height;y++)
{
double dx = x - cx;
double dy = y - cy;
double d = dx*dx + dy*dy;
if (d > radius *radius)
alpha[x+y*width] = 0;
else
if (d > f*f)
{
double t = (radius - Math.sqrt(d))/falloff;
alpha[x+y*width] = t * t * (3 - 2*t);
}
else
alpha[x+y*width] = 1;
}
}
}
|
package pt.unl.fct.miei.usmanagement.manager.dtos.mapper;
import org.mapstruct.Builder;
import org.mapstruct.Context;
import org.mapstruct.InheritInverseConfiguration;
import org.mapstruct.IterableMapping;
import org.mapstruct.Mapper;
import org.mapstruct.NullValueMappingStrategy;
import org.mapstruct.factory.Mappers;
import pt.unl.fct.miei.usmanagement.manager.dtos.kafka.NodeDTO;
import pt.unl.fct.miei.usmanagement.manager.nodes.Node;
@Mapper(builder = @Builder(disableBuilder = true))
public interface NodeMapper {
NodeMapper MAPPER = Mappers.getMapper(NodeMapper.class);
@IterableMapping(nullValueMappingStrategy = NullValueMappingStrategy.RETURN_DEFAULT)
Node toNode(NodeDTO nodeDTO, @Context CycleAvoidingMappingContext context);
@InheritInverseConfiguration
NodeDTO fromNode(Node node, @Context CycleAvoidingMappingContext context);
}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2017 abel533@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.pagehelper.dialect.helper;
import com.github.pagehelper.Page;
import com.github.pagehelper.dialect.AbstractHelperDialect;
import org.apache.ibatis.cache.CacheKey;
/**
* @author liuzh
*/
public class MySqlDialect extends AbstractHelperDialect {
@Override
public String getPageSql(String sql, Page<?> page, CacheKey pageKey) {
StringBuilder sqlBuilder = new StringBuilder(sql.length() + 14);
sqlBuilder.append(sql);
if (page.getStartRow() == 0) {
sqlBuilder.append(" LIMIT ");
sqlBuilder.append(page.getPageSize());
} else {
sqlBuilder.append(" LIMIT ");
sqlBuilder.append(page.getStartRow());
sqlBuilder.append(",");
sqlBuilder.append(page.getPageSize());
pageKey.update(page.getStartRow());
}
pageKey.update(page.getPageSize());
return sqlBuilder.toString();
}
}
|
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Main.java to edit this template
*/
package rocks.imsofa.net.simplesocket;
/**
*
* @author lendle
*/
public class Test1 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception {
// TODO code application logic here
SimpleSocket ss=new DefaultSimpleSocketImpl(8081);
SimpleSocket ss1=new DefaultSimpleSocketImpl();
ss.addMessageCallback(new MessageCallback(){
@Override
public void onMessage(String sourceIp, int sourcePort, String message) {
System.out.println(sourceIp+":"+sourcePort+":"+message);
}
});
ss.startReceivingMessage();
ss1.send("localhost", 8081, "This is a test.");
Thread.sleep(30000);
ss.stopReceivingMessage();
}
}
|
/*
* Copyright 2011 Google Inc.
* Copyright 2014 Andreas Schildbach
*
* 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.bitcoinj.core;
import com.google.common.collect.*;
import com.google.common.util.concurrent.*;
import org.bitcoinj.utils.*;
import org.bitcoinj.wallet.Wallet;
import javax.annotation.*;
import java.util.*;
import java.util.concurrent.*;
import static com.google.common.base.Preconditions.*;
// TODO: Modify the getDepthInBlocks method to require the chain height to be specified, in preparation for ceasing to touch every tx on every block.
/**
* <p>A TransactionConfidence object tracks data you can use to make a confidence decision about a transaction.
* It also contains some pre-canned rules for common scenarios: if you aren't really sure what level of confidence
* you need, these should prove useful. You can get a confidence object using {@link Transaction#getConfidence()}.
* They cannot be constructed directly.</p>
*
* <p>Confidence in a transaction can come in multiple ways:</p>
*
* <ul>
* <li>Because you created it yourself and only you have the necessary keys.</li>
* <li>Receiving it from a fully validating peer you know is trustworthy, for instance, because it's run by yourself.</li>
* <li>Receiving it from a peer on the network you randomly chose. If your network connection is not being
* intercepted, you have a pretty good chance of connecting to a node that is following the rules.</li>
* <li>Receiving it from multiple peers on the network. If your network connection is not being intercepted,
* hearing about a transaction from multiple peers indicates the network has accepted the transaction and
* thus miners likely have too (miners have the final say in whether a transaction becomes valid or not).</li>
* <li>Seeing the transaction appear appear in a block on the main chain. Your confidence increases as the transaction
* becomes further buried under work. Work can be measured either in blocks (roughly, units of time), or
* amount of work done.</li>
* </ul>
*
* <p>Alternatively, you may know that the transaction is "dead", that is, one or more of its inputs have
* been double spent and will never confirm unless there is another re-org.</p>
*
* <p>TransactionConfidence is updated via the {@link org.bitcoinj.core.TransactionConfidence#incrementDepthInBlocks()}
* method to ensure the block depth is up to date.</p>
* To make a copy that won't be changed, use {@link org.bitcoinj.core.TransactionConfidence#duplicate()}.
*/
public class TransactionConfidence {
/**
* The peers that have announced the transaction to us. Network nodes don't have stable identities, so we use
* IP address as an approximation. It's obviously vulnerable to being gamed if we allow arbitrary people to connect
* to us, so only peers we explicitly connected to should go here.
*/
private CopyOnWriteArrayList<PeerAddress> broadcastBy;
/** The time the transaction was last announced to us. */
private Date lastBroadcastedAt;
/** The Transaction that this confidence object is associated with. */
private final Sha256Hash hash;
// Lazily created listeners array.
private CopyOnWriteArrayList<ListenerRegistration<Listener>> listeners;
// The depth of the transaction on the best chain in blocks. An unconfirmed block has depth 0.
private int depth;
/** Describes the state of the transaction in general terms. Properties can be read to learn specifics. */
public enum ConfidenceType {
/** If BUILDING, then the transaction is included in the best chain and your confidence in it is increasing. */
BUILDING(1),
/**
* If PENDING, then the transaction is unconfirmed and should be included shortly, as long as it is being
* announced and is considered valid by the network. A pending transaction will be announced if the containing
* wallet has been attached to a live {@link PeerGroup} using {@link PeerGroup#addWallet(Wallet)}.
* You can estimate how likely the transaction is to be included by connecting to a bunch of nodes then measuring
* how many announce it, using {@link org.bitcoinj.core.TransactionConfidence#numBroadcastPeers()}.
* Or if you saw it from a trusted peer, you can assume it's valid and will get mined sooner or later as well.
*/
PENDING(2),
/**
* If DEAD, then it means the transaction won't confirm unless there is another re-org,
* because some other transaction is spending one of its inputs. Such transactions should be alerted to the user
* so they can take action, eg, suspending shipment of goods if they are a merchant.
* It can also mean that a coinbase transaction has been made dead from it being moved onto a side chain.
*/
DEAD(4),
/**
* If IN_CONFLICT, then it means there is another transaction (or several other transactions) spending one
* (or several) of its inputs but nor this transaction nor the other/s transaction/s are included in the best chain.
* The other/s transaction/s should be IN_CONFLICT too.
* IN_CONFLICT can be thought as an intermediary state between a) PENDING and BUILDING or b) PENDING and DEAD.
* Another common name for this situation is "double spend".
*/
IN_CONFLICT(5),
/**
* If a transaction hasn't been broadcast yet, or there's no record of it, its confidence is UNKNOWN.
*/
UNKNOWN(0);
private int value;
ConfidenceType(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
private ConfidenceType confidenceType = ConfidenceType.UNKNOWN;
private int appearedAtChainHeight = -1;
// The transaction that double spent this one, if any.
private Transaction overridingTransaction;
/**
* Information about where the transaction was first seen (network, sent direct from peer, created by ourselves).
* Useful for risk analyzing pending transactions. Probably not that useful after a tx is included in the chain,
* unless re-org double spends start happening frequently.
*/
public enum Source {
/** We don't know where the transaction came from. */
UNKNOWN,
/** We got this transaction from a network peer. */
NETWORK,
/** This transaction was created by our own wallet, so we know it's not a double spend. */
SELF
}
private Source source = Source.UNKNOWN;
public TransactionConfidence(Sha256Hash hash) {
// Assume a default number of peers for our set.
broadcastBy = new CopyOnWriteArrayList<PeerAddress>();
listeners = new CopyOnWriteArrayList<ListenerRegistration<Listener>>();
this.hash = hash;
}
/**
* <p>A confidence listener is informed when the level of {@link TransactionConfidence} is updated by something, like
* for example a {@link Wallet}. You can add listeners to update your user interface or manage your order tracking
* system when confidence levels pass a certain threshold. <b>Note that confidence can go down as well as up.</b>
* For example, this can happen if somebody is doing a double-spend attack against you. Whilst it's unlikely, your
* code should be able to handle that in order to be correct.</p>
*
* <p>During listener execution, it's safe to remove the current listener but not others.</p>
*/
public interface Listener {
/** An enum that describes why a transaction confidence listener is being invoked (i.e. the class of change). */
enum ChangeReason {
/**
* Occurs when the type returned by {@link org.bitcoinj.core.TransactionConfidence#getConfidenceType()}
* has changed. For example, if a PENDING transaction changes to BUILDING or DEAD, then this reason will
* be given. It's a high level summary.
*/
TYPE,
/**
* Occurs when a transaction that is in the best known block chain gets buried by another block. If you're
* waiting for a certain number of confirmations, this is the reason to watch out for.
*/
DEPTH,
/**
* Occurs when a pending transaction (not in the chain) was announced by another connected peers. By
* watching the number of peers that announced a transaction go up, you can see whether it's being
* accepted by the network or not. If all your peers announce, it's a pretty good bet the transaction
* is considered relayable and has thus reached the miners.
*/
SEEN_PEERS,
}
void onConfidenceChanged(TransactionConfidence confidence, ChangeReason reason);
}
// This is used to ensure that confidence objects which aren't referenced from anywhere but which have an event
// listener set on them don't become eligible for garbage collection. Otherwise the TxConfidenceTable, which only
// has weak references to these objects, would not be enough to keep the event listeners working as transactions
// propagate around the network - it cannot know directly if the API user is interested in the object, so it uses
// heap reachability as a proxy for interest.
//
// We add ourselves to this set when a listener is added and remove ourselves when the listener list is empty.
private static final Set<TransactionConfidence> pinnedConfidenceObjects = Collections.synchronizedSet(new HashSet<TransactionConfidence>());
/**
* <p>Adds an event listener that will be run when this confidence object is updated. The listener will be locked and
* is likely to be invoked on a peer thread.</p>
*
* <p>Note that this is NOT called when every block arrives. Instead it is called when the transaction
* transitions between confidence states, ie, from not being seen in the chain to being seen (not necessarily in
* the best chain). If you want to know when the transaction gets buried under another block, consider using
* a future from {@link #getDepthFuture(int)}.</p>
*/
public void addEventListener(Executor executor, Listener listener) {
checkNotNull(listener);
listeners.addIfAbsent(new ListenerRegistration<Listener>(listener, executor));
pinnedConfidenceObjects.add(this);
}
/**
* <p>Adds an event listener that will be run when this confidence object is updated. The listener will be locked and
* is likely to be invoked on a peer thread.</p>
*
* <p>Note that this is NOT called when every block arrives. Instead it is called when the transaction
* transitions between confidence states, ie, from not being seen in the chain to being seen (not necessarily in
* the best chain). If you want to know when the transaction gets buried under another block, implement a
* {@link org.bitcoinj.core.listeners.BlockChainListener}, attach it to a {@link BlockChain} and then use the getters on the
* confidence object to determine the new depth.</p>
*/
public void addEventListener(Listener listener) {
addEventListener(Threading.USER_THREAD, listener);
}
public boolean removeEventListener(Listener listener) {
checkNotNull(listener);
boolean removed = ListenerRegistration.removeFromList(listener, listeners);
if (listeners.isEmpty())
pinnedConfidenceObjects.remove(this);
return removed;
}
/**
* Returns the chain height at which the transaction appeared if confidence type is BUILDING.
* @throws IllegalStateException if the confidence type is not BUILDING.
*/
public synchronized int getAppearedAtChainHeight() {
if (getConfidenceType() != ConfidenceType.BUILDING)
throw new IllegalStateException("Confidence type is " + getConfidenceType() + ", not BUILDING");
return appearedAtChainHeight;
}
/**
* The chain height at which the transaction appeared, if it has been seen in the best chain. Automatically sets
* the current type to {@link ConfidenceType#BUILDING} and depth to one.
*/
public synchronized void setAppearedAtChainHeight(int appearedAtChainHeight) {
if (appearedAtChainHeight < 0)
throw new IllegalArgumentException("appearedAtChainHeight out of range");
this.appearedAtChainHeight = appearedAtChainHeight;
this.depth = 1;
setConfidenceType(ConfidenceType.BUILDING);
}
/**
* Returns a general statement of the level of confidence you can have in this transaction.
*/
public synchronized ConfidenceType getConfidenceType() {
return confidenceType;
}
/**
* Called by other objects in the system, like a {@link Wallet}, when new information about the confidence of a
* transaction becomes available.
*/
public synchronized void setConfidenceType(ConfidenceType confidenceType) {
if (confidenceType == this.confidenceType)
return;
this.confidenceType = confidenceType;
if (confidenceType != ConfidenceType.DEAD) {
overridingTransaction = null;
}
if (confidenceType == ConfidenceType.PENDING || confidenceType == ConfidenceType.IN_CONFLICT) {
depth = 0;
appearedAtChainHeight = -1;
}
}
/**
* Called by a {@link Peer} when a transaction is pending and announced by a peer. The more peers announce the
* transaction, the more peers have validated it (assuming your internet connection is not being intercepted).
* If confidence is currently unknown, sets it to {@link ConfidenceType#PENDING}. Does not run listeners.
*
* @param address IP address of the peer, used as a proxy for identity.
* @return true if marked, false if this address was already seen
*/
public boolean markBroadcastBy(PeerAddress address) {
lastBroadcastedAt = Utils.now();
if (!broadcastBy.addIfAbsent(address))
return false; // Duplicate.
synchronized (this) {
if (getConfidenceType() == ConfidenceType.UNKNOWN) {
this.confidenceType = ConfidenceType.PENDING;
}
}
return true;
}
/**
* Returns how many peers have been passed to {@link TransactionConfidence#markBroadcastBy}.
*/
public int numBroadcastPeers() {
return broadcastBy.size();
}
/**
* Returns a snapshot of {@link PeerAddress}es that announced the transaction.
*/
public Set<PeerAddress> getBroadcastBy() {
ListIterator<PeerAddress> iterator = broadcastBy.listIterator();
return Sets.newHashSet(iterator);
}
/** Returns true if the given address has been seen via markBroadcastBy() */
public boolean wasBroadcastBy(PeerAddress address) {
return broadcastBy.contains(address);
}
/** Return the time the transaction was last announced to us. */
public Date getLastBroadcastedAt() {
return lastBroadcastedAt;
}
/** Set the time the transaction was last announced to us. */
public void setLastBroadcastedAt(Date lastBroadcastedAt) {
this.lastBroadcastedAt = lastBroadcastedAt;
}
@Override
public synchronized String toString() {
StringBuilder builder = new StringBuilder();
int peers = numBroadcastPeers();
if (peers > 0) {
builder.append("Seen by ").append(peers).append(peers > 1 ? " peers" : " peer");
if (lastBroadcastedAt != null)
builder.append(" (most recently: ").append(Utils.dateTimeFormat(lastBroadcastedAt)).append(")");
builder.append(". ");
}
switch (getConfidenceType()) {
case UNKNOWN:
builder.append("Unknown confidence level.");
break;
case DEAD:
builder.append("Dead: overridden by double spend and will not confirm.");
break;
case PENDING:
builder.append("Pending/unconfirmed.");
break;
case IN_CONFLICT:
builder.append("In conflict.");
break;
case BUILDING:
builder.append(String.format(Locale.US, "Appeared in best chain at height %d, depth %d.",
getAppearedAtChainHeight(), getDepthInBlocks()));
break;
}
if (source != Source.UNKNOWN)
builder.append(" Source: ").append(source);
return builder.toString();
}
/**
* Called by the wallet when the tx appears on the best chain and a new block is added to the top. Updates the
* internal counter that tracks how deeply buried the block is.
*
* @return the new depth
*/
public synchronized int incrementDepthInBlocks() {
return ++this.depth;
}
/**
* <p>Depth in the chain is an approximation of how much time has elapsed since the transaction has been confirmed.
* On average there is supposed to be a new block every 10 minutes, but the actual rate may vary. Bitcoin Core
* considers a transaction impractical to reverse after 6 blocks, but as of EOY 2011 network
* security is high enough that often only one block is considered enough even for high value transactions. For low
* value transactions like songs, or other cheap items, no blocks at all may be necessary.</p>
*
* <p>If the transaction appears in the top block, the depth is one. If it's anything else (pending, dead, unknown)
* the depth is zero.</p>
*/
public synchronized int getDepthInBlocks() {
return depth;
}
/*
* Set the depth in blocks. Having one block confirmation is a depth of one.
*/
public synchronized void setDepthInBlocks(int depth) {
this.depth = depth;
}
/**
* Erases the set of broadcast/seen peers. This cannot be called whilst the confidence is PENDING. It is useful
* for saving memory and wallet space once a tx is buried so deep it doesn't seem likely to go pending again.
*/
public void clearBroadcastBy() {
checkState(getConfidenceType() != ConfidenceType.PENDING);
broadcastBy.clear();
lastBroadcastedAt = null;
}
/**
* If this transaction has been overridden by a double spend (is dead), this call returns the overriding transaction.
* Note that this call <b>can return null</b> if you have migrated an old wallet, as pre-Jan 2012 wallets did not
* store this information.
*
* @return the transaction that double spent this one
* @throws IllegalStateException if confidence type is not DEAD.
*/
public synchronized Transaction getOverridingTransaction() {
if (getConfidenceType() != ConfidenceType.DEAD)
throw new IllegalStateException("Confidence type is " + getConfidenceType() +
", not DEAD");
return overridingTransaction;
}
/**
* Called when the transaction becomes newly dead, that is, we learn that one of its inputs has already been spent
* in such a way that the double-spending transaction takes precedence over this one. It will not become valid now
* unless there is a re-org. Automatically sets the confidence type to DEAD. The overriding transaction may not
* directly double spend this one, but could also have double spent a dependency of this tx.
*/
public synchronized void setOverridingTransaction(@Nullable Transaction overridingTransaction) {
this.overridingTransaction = overridingTransaction;
setConfidenceType(ConfidenceType.DEAD);
}
/** Returns a copy of this object. Event listeners are not duplicated. */
public TransactionConfidence duplicate() {
TransactionConfidence c = new TransactionConfidence(hash);
c.broadcastBy.addAll(broadcastBy);
c.lastBroadcastedAt = lastBroadcastedAt;
synchronized (this) {
c.confidenceType = confidenceType;
c.overridingTransaction = overridingTransaction;
c.appearedAtChainHeight = appearedAtChainHeight;
}
return c;
}
/**
* Call this after adjusting the confidence, for cases where listeners should be notified. This has to be done
* explicitly rather than being done automatically because sometimes complex changes to transaction states can
* result in a series of confidence changes that are not really useful to see separately. By invoking listeners
* explicitly, more precise control is available. Note that this will run the listeners on the user code thread.
*/
public void queueListeners(final Listener.ChangeReason reason) {
for (final ListenerRegistration<Listener> registration : listeners) {
registration.executor.execute(new Runnable() {
@Override
public void run() {
registration.listener.onConfidenceChanged(TransactionConfidence.this, reason);
}
});
}
}
/**
* The source of a transaction tries to identify where it came from originally. For instance, did we download it
* from the peer to peer network, or make it ourselves, or receive it via Bluetooth, or import it from another app,
* and so on. This information is useful for {@link org.bitcoinj.wallet.CoinSelector} implementations to risk analyze
* transactions and decide when to spend them.
*/
public synchronized Source getSource() {
return source;
}
/**
* The source of a transaction tries to identify where it came from originally. For instance, did we download it
* from the peer to peer network, or make it ourselves, or receive it via Bluetooth, or import it from another app,
* and so on. This information is useful for {@link org.bitcoinj.wallet.CoinSelector} implementations to risk analyze
* transactions and decide when to spend them.
*/
public synchronized void setSource(Source source) {
this.source = source;
}
/**
* Returns a future that completes when the transaction has been confirmed by "depth" blocks. For instance setting
* depth to one will wait until it appears in a block on the best chain, and zero will wait until it has been seen
* on the network.
*/
public synchronized ListenableFuture<TransactionConfidence> getDepthFuture(final int depth, Executor executor) {
final SettableFuture<TransactionConfidence> result = SettableFuture.create();
if (getDepthInBlocks() >= depth) {
result.set(this);
}
addEventListener(executor, new Listener() {
@Override public void onConfidenceChanged(TransactionConfidence confidence, ChangeReason reason) {
if (getDepthInBlocks() >= depth) {
removeEventListener(this);
result.set(confidence);
}
}
});
return result;
}
public synchronized ListenableFuture<TransactionConfidence> getDepthFuture(final int depth) {
return getDepthFuture(depth, Threading.USER_THREAD);
}
public Sha256Hash getTransactionHash() {
return hash;
}
}
|
/*
* Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved.
*
* OpenArkCompiler is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
* FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
* -@TestCaseID: UnsafegetCharByAddressTest
* -@TestCaseName: Unsafe api: getChar(address)
* -@TestCaseType: Function Test
* -@RequirementName: VMRuntime_registerNativeAllocation接口实现
* -@Brief:
* -#step1:allocateMemory for one Field of Char
* -#step2:set value of Field from step1
* -#step3:invoke Unsafe.getChar(address) to visit this Field
* -#step4:check value of step3 correct
* -@Expect:0\n
* -@Priority: High
* -@Source: UnsafegetCharByAddressTest.java
* -@ExecuteClass: UnsafegetCharByAddressTest
* -@ExecuteArgs:
*/
import sun.misc.Unsafe;
import java.io.PrintStream;
import java.lang.reflect.Field;
public class UnsafegetCharByAddressTest {
private static int res = 99;
public static void main(String[] args) {
System.out.println(run(args, System.out));
}
private static int run(String[] args, PrintStream out) {
int result = 2/*STATUS_FAILED*/;
try {
result = UnsafegetCharByAddressTest_1();
} catch (Exception e) {
e.printStackTrace();
UnsafegetCharByAddressTest.res -= 2;
}
if (result == 3 && UnsafegetCharByAddressTest.res == 97) {
result =0;
}
return result;
}
private static int UnsafegetCharByAddressTest_1() {
Unsafe unsafe;
Field field;
long address;
char result;
try {
field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe = (Unsafe)field.get(null);
address = unsafe.allocateMemory(2);
// System.out.println(address);
char c = 'a';
unsafe.putChar(address, c);
result = unsafe.getChar(address);
// System.out.println(result);
if (result == c) {
UnsafegetCharByAddressTest.res -= 2;
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
return 40;
} catch (IllegalAccessException e) {
e.printStackTrace();
return 41;
}
return 3;
}
}
// EXEC:%maple %f %build_option -o %n.so
// EXEC:%run %n.so %n %run_option | compare %f
// ASSERT: scan-full 0\n
|
package mekanism.client.jei.machine;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import mekanism.api.annotations.NonNull;
import mekanism.api.chemical.gas.GasStack;
import mekanism.api.providers.IBlockProvider;
import mekanism.api.recipes.ItemStackGasToItemStackRecipe;
import mekanism.api.recipes.inputs.chemical.GasStackIngredient;
import mekanism.client.gui.element.bar.GuiEmptyBar;
import mekanism.client.gui.element.bar.GuiVerticalPowerBar;
import mekanism.client.gui.element.progress.GuiProgress;
import mekanism.client.gui.element.progress.ProgressType;
import mekanism.client.gui.element.slot.GuiSlot;
import mekanism.client.gui.element.slot.SlotType;
import mekanism.client.jei.BaseRecipeCategory;
import mekanism.client.jei.MekanismJEI;
import mekanism.common.inventory.container.slot.SlotOverlay;
import mekanism.common.tile.prefab.TileEntityAdvancedElectricMachine;
import mezz.jei.api.constants.VanillaTypes;
import mezz.jei.api.gui.IRecipeLayout;
import mezz.jei.api.gui.ingredient.IGuiIngredientGroup;
import mezz.jei.api.gui.ingredient.IGuiItemStackGroup;
import mezz.jei.api.helpers.IGuiHelper;
import mezz.jei.api.ingredients.IIngredients;
import net.minecraft.item.ItemStack;
public class ItemStackGasToItemStackRecipeCategory extends BaseRecipeCategory<ItemStackGasToItemStackRecipe> {
public ItemStackGasToItemStackRecipeCategory(IGuiHelper helper, IBlockProvider mekanismBlock) {
super(helper, mekanismBlock, 28, 16, 144, 54);
}
@Override
public Class<? extends ItemStackGasToItemStackRecipe> getRecipeClass() {
return ItemStackGasToItemStackRecipe.class;
}
@Override
protected void addGuiElements() {
guiElements.add(new GuiSlot(SlotType.INPUT, this, 63, 16));
guiElements.add(new GuiSlot(SlotType.POWER, this, 38, 34).with(SlotOverlay.POWER));
guiElements.add(new GuiSlot(SlotType.EXTRA, this, 63, 52));
guiElements.add(new GuiSlot(SlotType.OUTPUT, this, 116, 35));
guiElements.add(new GuiVerticalPowerBar(this, () -> 1F, 164, 15));
guiElements.add(new GuiEmptyBar(this, 68, 36, 6, 12));
guiElements.add(new GuiProgress(() -> timer.getValue() / 20D, ProgressType.BAR, this, 86, 38));
}
@Override
public void setIngredients(ItemStackGasToItemStackRecipe recipe, IIngredients ingredients) {
ingredients.setInputLists(VanillaTypes.ITEM, Collections.singletonList(recipe.getItemInput().getRepresentations()));
List<@NonNull GasStack> gasInputs = recipe.getChemicalInput().getRepresentations();
List<GasStack> scaledGases = gasInputs.stream().map(gas -> new GasStack(gas, gas.getAmount() * TileEntityAdvancedElectricMachine.BASE_TICKS_REQUIRED))
.collect(Collectors.toList());
ingredients.setInputLists(MekanismJEI.TYPE_GAS, Collections.singletonList(scaledGases));
ingredients.setOutputLists(VanillaTypes.ITEM, Collections.singletonList(recipe.getOutputDefinition()));
}
@Override
public void setRecipe(IRecipeLayout recipeLayout, ItemStackGasToItemStackRecipe recipe, IIngredients ingredients) {
IGuiItemStackGroup itemStacks = recipeLayout.getItemStacks();
itemStacks.init(0, true, 35, 0);
itemStacks.init(1, false, 88, 19);
itemStacks.init(2, false, 35, 36);
itemStacks.set(0, recipe.getItemInput().getRepresentations());
itemStacks.set(1, recipe.getOutputDefinition());
GasStackIngredient gasInput = recipe.getChemicalInput();
List<ItemStack> gasItemProviders = new ArrayList<>();
List<@NonNull GasStack> gasInputs = gasInput.getRepresentations();
List<GasStack> scaledGases = new ArrayList<>();
for (GasStack gas : gasInputs) {
gasItemProviders.addAll(MekanismJEI.GAS_STACK_HELPER.getStacksFor(gas.getType(), true));
//While we are already looping the gases ensure we scale it to get the average amount that will get used over all
scaledGases.add(new GasStack(gas, gas.getAmount() * TileEntityAdvancedElectricMachine.BASE_TICKS_REQUIRED));
}
itemStacks.set(2, gasItemProviders);
IGuiIngredientGroup<GasStack> gasStacks = recipeLayout.getIngredientsGroup(MekanismJEI.TYPE_GAS);
initChemical(gasStacks, 0, true, 41, 21, 6, 12, scaledGases, false);
}
}
|
package ru.job4j.threads;
import org.junit.Test;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;
/**
* Class <Name class>.
*
* @author Alexey Rastorguev (rastorguev00@gmail.com)
* @version 0.1
* @since 26.01.2018
*/
public class StopThredTest {
@Test
public void whenTwoThreadThenCountText() throws InterruptedException {
StopThred stopThred = new StopThred("aa bb cc ffafa ddd ddds fsfsdf dsf sf df s sdfs df df sdf sdf sdfsd fsdf sdf sd s sdfds fsdf dfsd dsfk sdfkdskfsdfsdhfsdh fsdjfjsd", 1);
stopThred.start();
stopThred.getT1().join();
assertThat(stopThred.getCountWord(), is(27));
}
}
|
package com.github.capitansissy.database;
import java.io.Serializable;
public class Inquiries implements Serializable {
public static final String GET_CURRENT_DATABASE = "SELECT DATABASE() FROM DUAL";
public static final String INITIALIZE_DEFAULT_DATABASE = "SELECT COUNT(*) FROM DUAL";
public static final String GET_TABLE_LIST_OBFUSCATED = "SELECT `%1$s`.`%2$s`.`%3$s`, `%1$s`.`%2$s`.`%4$s`, `%1$s`.`%2$s`.`%5$s`, `%1$s`.`%2$s`.`%6$s`, `%1$s`.`%2$s`.`%7$s`, `%1$s`.`%2$s`.`%8$s` FROM `%1$s`.`%2$s` WHERE `%1$s`.`%2$s`.`%9$s` = ?";
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package MySQL_Testes;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
*
* @author Samuel
*/
public class MySQL_Conection {
private static final String DRIVER = "com.mysql.jdbc.Driver"; // Driver location / local do Driver /
private static final String URL = "jdbc:mysql://localhost:3308/agendafx"; // Database URL used in the MySQL case / URL do banco de dados usado no caso MySQL /
private static final String USER = "root"; // usuario
private static final String PASS = ""; //senha
public static com.mysql.jdbc.Connection getConnection() { // method to get the connection / metodo para pegar a conexao /
try {
Class.forName(DRIVER); //pegando o Driver / getting the driver
return (com.mysql.jdbc.Connection) DriverManager.getConnection(URL, USER, PASS); // performing the Connection to the database / realizando a Conexao com o banco de dados /
} catch (ClassNotFoundException | SQLException ex) {
JOptionPane.showMessageDialog(null, "Nao foi possivel realizar conexao com o banco: " + ex); // error message if it occurs / mensagem de erro se ocorrer /
throw new RuntimeException("Nao foi possivel realizar conexao com o banco: " + ex);
}
}
public static void closeConnection(com.mysql.jdbc.Connection connection) { // method to close the connection / metodo para encerrar a conexao /
try {
if (connection != null) {
connection.close();
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Nao foi possivel encerrar conexao com o banco: " + ex); // error message if it occurs / mensagem de erro se ocorrer /
}
}
public static void closeConnection(com.mysql.jdbc.Connection connection, PreparedStatement statement ){ // method to close the connection / metodo para encerrar a conexao /
closeConnection(connection);
try {
if (statement != null) {
statement.close();
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Nao foi possivel encerrar conexao com o banco: " + ex); // error message if it occurs / mensagem de erro se ocorrer /
}
}
public static void closeConnection(com.mysql.jdbc.Connection connection, PreparedStatement statement, ResultSet result) { // method to close the connection / metodo para encerrar a conexao /
closeConnection(connection, statement);
try {
if (result != null) {
result.close();
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Nao foi possivel encerrar conexao com o banco: " + ex); // error message if it occurs / mensagem de erro se ocorrer /
}
}
}
|
/*
* 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.myfaces.spi.impl;
import org.apache.myfaces.config.DefaultFacesConfigurationMerger;
import org.apache.myfaces.shared.util.ClassUtils;
import org.apache.myfaces.spi.FacesConfigurationMerger;
import org.apache.myfaces.spi.FacesConfigurationMergerFactory;
import org.apache.myfaces.spi.ServiceProviderFinderFactory;
import javax.faces.FacesException;
import javax.faces.context.ExternalContext;
import java.lang.reflect.InvocationTargetException;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Jakob Korherr
*/
public class DefaultFacesConfigurationMergerFactory extends FacesConfigurationMergerFactory
{
public static final String FACES_CONFIGURATION_MERGER = FacesConfigurationMerger.class.getName();
public static final String FACES_CONFIGURATION_MERGER_INSTANCE_KEY = FACES_CONFIGURATION_MERGER + ".INSTANCE";
@Override
public FacesConfigurationMerger getFacesConfigurationMerger(ExternalContext externalContext)
{
// check for cached instance
FacesConfigurationMerger returnValue = (FacesConfigurationMerger)
externalContext.getApplicationMap().get(FACES_CONFIGURATION_MERGER_INSTANCE_KEY);
if (returnValue == null)
{
final ExternalContext extContext = externalContext;
try
{
if (System.getSecurityManager() != null)
{
returnValue = AccessController.doPrivileged(
new java.security.PrivilegedExceptionAction<FacesConfigurationMerger>()
{
public FacesConfigurationMerger run() throws ClassNotFoundException,
NoClassDefFoundError,
InstantiationException,
IllegalAccessException,
InvocationTargetException,
PrivilegedActionException
{
return resolveFacesConfigurationMergerFromService(extContext);
}
});
}
else
{
returnValue = resolveFacesConfigurationMergerFromService(extContext);
}
// cache the result on the ApplicationMap
externalContext.getApplicationMap().put(FACES_CONFIGURATION_MERGER_INSTANCE_KEY, returnValue);
}
catch (ClassNotFoundException e)
{
// ignore
}
catch (NoClassDefFoundError e)
{
// ignore
}
catch (InstantiationException e)
{
getLogger().log(Level.SEVERE, "", e);
}
catch (IllegalAccessException e)
{
getLogger().log(Level.SEVERE, "", e);
}
catch (InvocationTargetException e)
{
getLogger().log(Level.SEVERE, "", e);
}
catch (PrivilegedActionException e)
{
throw new FacesException(e);
}
}
return returnValue;
}
private FacesConfigurationMerger resolveFacesConfigurationMergerFromService(ExternalContext externalContext)
throws ClassNotFoundException,
NoClassDefFoundError,
InstantiationException,
IllegalAccessException,
InvocationTargetException,
PrivilegedActionException
{
// get all fitting SPI implementations (no need to cache this since it's only called once per JSF-app)
List<String> classList = ServiceProviderFinderFactory.getServiceProviderFinder(externalContext)
.getServiceProviderList(FACES_CONFIGURATION_MERGER);
// create the instance using decorator pattern
return ClassUtils.buildApplicationObject(FacesConfigurationMerger.class,
classList, new DefaultFacesConfigurationMerger());
}
private Logger getLogger()
{
return Logger.getLogger(DefaultFacesConfigurationMergerFactory.class.getName());
}
}
|
package com.Huohuo.Huohuo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.Toast;
import com.Huohuo.Huohuo.base.BaseActivity;
import com.Huohuo.Huohuo.bean.Driver;
import com.Huohuo.Huohuo.bean.OrderForm;
import com.Huohuo.Huohuo.databinding.ActivityOrderEvaluateBinding;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.GetCallback;
/**
* Created by Tony on 2017/3/11.
*/
public class OrderEvaluateActivity extends BaseActivity <ActivityOrderEvaluateBinding> implements CheckBox.OnCheckedChangeListener, RatingBar.OnRatingBarChangeListener, View.OnClickListener {
private OrderForm orderForm;
private Driver driver;
private CardView driverCard;
private EditText content;
private RatingBar ratingBar;
private CheckBox checkBox;
private Button confirm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
setContentView(R.layout.activity_order_evaluate);
showContentView();
initView();
setTitle("评价");
}
public static void start(Context context) {
Intent intent = new Intent(context, OrderEvaluateActivity.class);
context.startActivity(intent);
}
private void initView() {
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
orderForm = (OrderForm) bundle.getSerializable("orderForm");
driverCard = bindingView.driverCard.driverCard;
driverCard.setOnClickListener(this);
content = bindingView.content;
ratingBar = bindingView.ratingBar;
ratingBar.setOnRatingBarChangeListener(this);
checkBox = bindingView.CheckBox;
checkBox.setOnCheckedChangeListener(this);
confirm = bindingView.confirm;
confirm.setOnClickListener(this);
driver = orderForm.getDriver();
bindingView.driverCard.realName.setText(driver.getRealName());
bindingView.driverCard.ratingBar.setRating(Float.parseFloat("" + driver.getRating()));
bindingView.driverCard.rating.setText("" + driver.getRating());
bindingView.driverCard.message.setText("已完成" + driver.getTaskCount() + "单");
}
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
}
@Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.confirm:
final float rating = (ratingBar.getRating() + driver.getRating() * driver.getTaskCount()) / (driver.getTaskCount() + 1);
final String evaluateToDriver = content.getText().toString();
AVQuery queryDriver = new AVQuery("Driver");
queryDriver.getInBackground(driver.getObjectId(), new GetCallback() {
@Override
public void done(AVObject avObject, AVException e) {
if (e == null) {
avObject.put("rating", rating);
avObject.saveInBackground();
}
}
});
AVQuery queryOrder = new AVQuery("OrderForm");
queryOrder.getInBackground(orderForm.getObjectId(), new GetCallback() {
@Override
public void done(AVObject avObject, AVException e) {
if (e == null) {
avObject.put("evaluateToDriver", evaluateToDriver);
avObject.saveInBackground();
orderForm.setEvaluateToDriver(evaluateToDriver);
orderForm.save();
}
}
});
Toast.makeText(OrderEvaluateActivity.this, "评价完成", Toast.LENGTH_SHORT).show();
finish();
break;
case R.id.driver_card:
Intent intent = new Intent(OrderEvaluateActivity.this, DriverInfoActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("driver", driver);
intent.putExtras(bundle);
startActivity(intent);
break;
}
}
}
|
package com.example.user;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserApplicationTests {
@Test
public void contextLoads() {
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.recoveryservicesbackup.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.management.Resource;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Map;
/** The BackupResourceEncryptionConfigResource model. */
@Fluent
public final class BackupResourceEncryptionConfigResource extends Resource {
@JsonIgnore private final ClientLogger logger = new ClientLogger(BackupResourceEncryptionConfigResource.class);
/*
* BackupResourceEncryptionConfigResource properties
*/
@JsonProperty(value = "properties")
private BackupResourceEncryptionConfig properties;
/*
* Optional ETag.
*/
@JsonProperty(value = "eTag")
private String etag;
/**
* Get the properties property: BackupResourceEncryptionConfigResource properties.
*
* @return the properties value.
*/
public BackupResourceEncryptionConfig properties() {
return this.properties;
}
/**
* Set the properties property: BackupResourceEncryptionConfigResource properties.
*
* @param properties the properties value to set.
* @return the BackupResourceEncryptionConfigResource object itself.
*/
public BackupResourceEncryptionConfigResource withProperties(BackupResourceEncryptionConfig properties) {
this.properties = properties;
return this;
}
/**
* Get the etag property: Optional ETag.
*
* @return the etag value.
*/
public String etag() {
return this.etag;
}
/**
* Set the etag property: Optional ETag.
*
* @param etag the etag value to set.
* @return the BackupResourceEncryptionConfigResource object itself.
*/
public BackupResourceEncryptionConfigResource withEtag(String etag) {
this.etag = etag;
return this;
}
/** {@inheritDoc} */
@Override
public BackupResourceEncryptionConfigResource withLocation(String location) {
super.withLocation(location);
return this;
}
/** {@inheritDoc} */
@Override
public BackupResourceEncryptionConfigResource withTags(Map<String, String> tags) {
super.withTags(tags);
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (properties() != null) {
properties().validate();
}
}
}
|
package com.pkj.wow.paginationviewsample;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
}
|
package io.jexxa.tutorials.timeservice.infrastructure.drivenadapter.messaging;
import java.time.LocalTime;
import java.util.Properties;
import io.jexxa.infrastructure.drivenadapterstrategy.messaging.MessageSender;
import io.jexxa.infrastructure.drivenadapterstrategy.messaging.MessageSenderManager;
import io.jexxa.tutorials.timeservice.domainservice.ITimePublisher;
@SuppressWarnings("unused")
public class TimePublisher implements ITimePublisher
{
public static final String TIME_TOPIC = "TimeService";
private final MessageSender messageSender;
// For all driven adapter we have to provide either a static factory or a public constructor to
// enable implicit constructor injection
public TimePublisher(Properties properties)
{
//Request a default message Sender from corresponding strategy manager
this.messageSender = MessageSenderManager.getInstance().getStrategy(properties);
}
@Override
public void publish(LocalTime localTime)
{
// Send the message to the topic.
messageSender.send(localTime)
.toTopic(TIME_TOPIC)
.asJson();
}
}
|
package com.guonl.handle;
import com.guonl.enums.ResultEnum;
import com.guonl.utils.ResultUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created on 2018/1/7 0007.
* 自定义登录失败处理
*
* @author zlf
* @email i@merryyou.cn
* @since 1.0
*/
@Component(value = "merryyouAuthenticationfailureHandler")
public class MerryyouAuthenticationfailureHandler extends SimpleUrlAuthenticationFailureHandler {
@Autowired
private ObjectMapper objectMapper;
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
// super.onAuthenticationFailure(request, response, exception);
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());//服务器内部异常
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(objectMapper.writeValueAsString(ResultUtil.error(ResultEnum.CODE_ERROT.getCode(),exception.getMessage())));
}
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See License.txt in the repository root.
package com.microsoft.tfs.client.common.commands.vc;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import com.microsoft.tfs.client.common.Messages;
import com.microsoft.tfs.client.common.TFSCommonClientPlugin;
import com.microsoft.tfs.client.common.commands.TFSConnectedCommand;
import com.microsoft.tfs.client.common.repository.TFSRepository;
import com.microsoft.tfs.core.clients.versioncontrol.soapextensions.Shelveset;
import com.microsoft.tfs.util.Check;
import com.microsoft.tfs.util.LocaleUtil;
public class DeleteShelvesetsCommand extends TFSConnectedCommand {
private final TFSRepository repository;
private final Shelveset[] shelvesets;
private final List deletedShelvesets = new ArrayList();
private final List failures = new ArrayList();
public DeleteShelvesetsCommand(final TFSRepository repository, final Shelveset shelveset) {
this(repository, new Shelveset[] {
shelveset
});
}
public DeleteShelvesetsCommand(final TFSRepository repository, final Shelveset[] shelvesets) {
Check.notNull(repository, "repository"); //$NON-NLS-1$
Check.notNullOrEmpty(shelvesets, "shelvesets"); //$NON-NLS-1$
this.repository = repository;
this.shelvesets = shelvesets;
setConnection(repository.getConnection());
}
@Override
public String getName() {
if (shelvesets.length == 1) {
final String messageFormat = Messages.getString("DeleteShelvesetsCommand.DeletingShelvesetFormat"); //$NON-NLS-1$
return MessageFormat.format(messageFormat, shelvesets[0].getName());
} else {
return Messages.getString("DeleteShelvesetsCommand.DeletingShelvesets"); //$NON-NLS-1$
}
}
@Override
public String getErrorDescription() {
return (Messages.getString("DeleteShelvesetsCommand.ErrorDeletingShelveset")); //$NON-NLS-1$
}
@Override
public String getLoggingDescription() {
if (shelvesets.length == 1) {
final String messageFormat =
Messages.getString("DeleteShelvesetsCommand.DeletingShelvesetFormat", LocaleUtil.ROOT); //$NON-NLS-1$
return MessageFormat.format(messageFormat, shelvesets[0].getName());
} else {
return Messages.getString("DeleteShelvesetsCommand.DeletingShelvesets", LocaleUtil.ROOT); //$NON-NLS-1$
}
}
@Override
protected IStatus doRun(final IProgressMonitor progressMonitor) throws Exception {
String message = (shelvesets.length == 1) ? Messages.getString("DeleteShelvesetsCommand.DeletingShelveSet") //$NON-NLS-1$
: Messages.getString("DeleteShelvesetsCommand.DeletingShelvesets"); //$NON-NLS-1$
progressMonitor.beginTask(message, shelvesets.length);
for (int i = 0; i < shelvesets.length; i++) {
try {
repository.getVersionControlClient().deleteShelveset(
shelvesets[i].getName(),
shelvesets[i].getOwnerName());
deletedShelvesets.add(shelvesets[i]);
} catch (final Exception e) {
final String messageFormat =
Messages.getString("DeleteShelvesetsCommand.CouldNotDeleteShelvesetFormat"); //$NON-NLS-1$
message = MessageFormat.format(
messageFormat,
shelvesets[i].getName(),
TFSCommandExceptionHandler.getErrorMessage(e.getLocalizedMessage()));
failures.add(new Status(Status.ERROR, getPluginID(), 0, message, null));
} finally {
progressMonitor.worked(1);
}
}
if (failures.size() == 1) {
return (IStatus) failures.get(0);
} else if (failures.size() > 0) {
final String messageFormat = Messages.getString("DeleteShelvesetsCommand.CouldNotDeleteShelvesetsFormat"); //$NON-NLS-1$
message = MessageFormat.format(messageFormat, failures.size());
return new MultiStatus(
getPluginID(),
0,
(IStatus[]) failures.toArray(new IStatus[failures.size()]),
message,
null);
}
return Status.OK_STATUS;
}
public Shelveset[] getDeletedShelvesets() {
return (Shelveset[]) deletedShelvesets.toArray(new Shelveset[deletedShelvesets.size()]);
}
public String getPluginID() {
return TFSCommonClientPlugin.PLUGIN_ID;
}
}
|
/*
* 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.dtstack.flinkx.connector.kingbase.converter;
import org.apache.flink.table.data.DecimalData;
import org.apache.flink.table.data.StringData;
import org.apache.flink.table.data.TimestampData;
import org.apache.flink.table.types.logical.DecimalType;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.RowType;
import com.dtstack.flinkx.connector.jdbc.converter.JdbcRowConverter;
import com.dtstack.flinkx.converter.IDeserializationConverter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
/**
* @description:
* @program: flinkx-all
* @author: lany
* @create: 2021/05/20 17:08
*/
public class KingbaseRowConverter extends JdbcRowConverter {
private static final long serialVersionUID = 2L;
public KingbaseRowConverter(RowType rowType) {
super(rowType);
}
/**
* override reason: tinying type in KingBase is byte type, couldn't case int.
*
* @param type
*
* @return
*/
@Override
protected IDeserializationConverter createInternalConverter(LogicalType type) {
switch (type.getTypeRoot()) {
case NULL:
return val -> null;
case BOOLEAN:
case FLOAT:
case DOUBLE:
case INTERVAL_YEAR_MONTH:
case INTERVAL_DAY_TIME:
return val -> val;
case TINYINT:
return val -> ((Byte) val);
case SMALLINT:
return val -> val instanceof Integer ? ((Integer) val).shortValue() : val;
case INTEGER:
return val -> val;
case BIGINT:
return val -> val;
case DECIMAL:
final int precision = ((DecimalType) type).getPrecision();
final int scale = ((DecimalType) type).getScale();
return val ->
val instanceof BigInteger
? DecimalData.fromBigDecimal(
new BigDecimal((BigInteger) val, 0), precision, scale)
: DecimalData.fromBigDecimal((BigDecimal) val, precision, scale);
case DATE:
return val -> (int) ((Date.valueOf(String.valueOf(val))).toLocalDate().toEpochDay());
case TIME_WITHOUT_TIME_ZONE:
return val -> (int) ((Time.valueOf(String.valueOf(val))).toLocalTime().toNanoOfDay() / 1_000_000L);
case TIMESTAMP_WITH_TIME_ZONE:
case TIMESTAMP_WITHOUT_TIME_ZONE:
return val -> TimestampData.fromTimestamp((Timestamp) val);
case CHAR:
case VARCHAR:
return val -> StringData.fromString(val.toString());
case BINARY:
case VARBINARY:
return val -> (byte[]) val;
case ARRAY:
case ROW:
case MAP:
case MULTISET:
case RAW:
default:
throw new UnsupportedOperationException("Unsupported type:" + type);
}
}
}
|
/*
* Copyright (c) 2020 Logical Clocks AB
*
* 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.logicalclocks.hsfs.metadata;
import com.damnhandy.uri.template.UriTemplate;
import com.logicalclocks.hsfs.FeatureStore;
import com.logicalclocks.hsfs.FeatureStoreException;
import com.logicalclocks.hsfs.StorageConnector;
import org.apache.http.client.methods.HttpGet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public class StorageConnectorApi {
private static final String CONNECTOR_PATH = "/storageconnectors";
private static final String CONNECTOR_TYPE_PATH =
CONNECTOR_PATH + "{/connType}{/name}{?temporaryCredentials}";
private static final String ONLINE_CONNECTOR_PATH = CONNECTOR_PATH + "/onlinefeaturestore";
private static final Logger LOGGER = LoggerFactory.getLogger(StorageConnectorApi.class);
public StorageConnector getByName(FeatureStore featureStore, String name)
throws IOException, FeatureStoreException {
HopsworksClient hopsworksClient = HopsworksClient.getInstance();
String pathTemplate = HopsworksClient.PROJECT_PATH
+ FeatureStoreApi.FEATURE_STORE_PATH
+ CONNECTOR_TYPE_PATH;
String uri = UriTemplate.fromTemplate(pathTemplate)
.set("projectId", featureStore.getProjectId())
.set("fsId", featureStore.getId())
.set("name", name)
.set("temporaryCredentials", true)
.expand();
LOGGER.info("Sending metadata request: " + uri);
return hopsworksClient.handleRequest(new HttpGet(uri), StorageConnector.class);
}
public StorageConnector getOnlineStorageConnector(FeatureStore featureStore)
throws IOException, FeatureStoreException {
HopsworksClient hopsworksClient = HopsworksClient.getInstance();
String pathTemplate = HopsworksClient.PROJECT_PATH
+ FeatureStoreApi.FEATURE_STORE_PATH
+ ONLINE_CONNECTOR_PATH;
String uri = UriTemplate.fromTemplate(pathTemplate)
.set("projectId", featureStore.getProjectId())
.set("fsId", featureStore.getId())
.expand();
LOGGER.info("Sending metadata request: " + uri);
return hopsworksClient.handleRequest(new HttpGet(uri), StorageConnector.class);
}
}
|
package org.bian.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.bian.dto.CRContactCenterManagementPlanExchangeInputModelContactCenterManagementPlanExchangeActionRequest;
import javax.validation.Valid;
/**
* CRContactCenterManagementPlanExchangeInputModel
*/
public class CRContactCenterManagementPlanExchangeInputModel {
private String contactCenterManagementServicingSessionReference = null;
private String contactCenterManagementPlanInstanceReference = null;
private Object contactCenterManagementPlanExchangeActionTaskRecord = null;
private CRContactCenterManagementPlanExchangeInputModelContactCenterManagementPlanExchangeActionRequest contactCenterManagementPlanExchangeActionRequest = null;
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to the active servicing session
* @return contactCenterManagementServicingSessionReference
**/
public String getContactCenterManagementServicingSessionReference() {
return contactCenterManagementServicingSessionReference;
}
public void setContactCenterManagementServicingSessionReference(String contactCenterManagementServicingSessionReference) {
this.contactCenterManagementServicingSessionReference = contactCenterManagementServicingSessionReference;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to the Contact Center Management Plan instance
* @return contactCenterManagementPlanInstanceReference
**/
public String getContactCenterManagementPlanInstanceReference() {
return contactCenterManagementPlanInstanceReference;
}
public void setContactCenterManagementPlanInstanceReference(String contactCenterManagementPlanInstanceReference) {
this.contactCenterManagementPlanInstanceReference = contactCenterManagementPlanInstanceReference;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The exchange service call consolidated processing record
* @return contactCenterManagementPlanExchangeActionTaskRecord
**/
public Object getContactCenterManagementPlanExchangeActionTaskRecord() {
return contactCenterManagementPlanExchangeActionTaskRecord;
}
public void setContactCenterManagementPlanExchangeActionTaskRecord(Object contactCenterManagementPlanExchangeActionTaskRecord) {
this.contactCenterManagementPlanExchangeActionTaskRecord = contactCenterManagementPlanExchangeActionTaskRecord;
}
/**
* Get contactCenterManagementPlanExchangeActionRequest
* @return contactCenterManagementPlanExchangeActionRequest
**/
public CRContactCenterManagementPlanExchangeInputModelContactCenterManagementPlanExchangeActionRequest getContactCenterManagementPlanExchangeActionRequest() {
return contactCenterManagementPlanExchangeActionRequest;
}
public void setContactCenterManagementPlanExchangeActionRequest(CRContactCenterManagementPlanExchangeInputModelContactCenterManagementPlanExchangeActionRequest contactCenterManagementPlanExchangeActionRequest) {
this.contactCenterManagementPlanExchangeActionRequest = contactCenterManagementPlanExchangeActionRequest;
}
}
|
package com.github.ocraft.s2client.api.vertx;
/*-
* #%L
* ocraft-s2client-api
* %%
* Copyright (C) 2017 - 2018 Ocraft Project
* %%
* 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.
* #L%
*/
import io.reactivex.observers.DefaultObserver;
import io.vertx.reactivex.core.http.WebSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.BufferOverflowException;
class OnResponse extends DefaultObserver<byte[]> implements ConnectionHandler {
private Logger log = LoggerFactory.getLogger(OnResponse.class);
private final VertxChannel channel;
private final Runnable onConnectionLost;
OnResponse(VertxChannel channel, Runnable onConnectionLost) {
this.channel = channel;
this.onConnectionLost = onConnectionLost;
}
@Override
public void onComplete() {
log.debug("OnResponse.onComplete: connection lost.");
onConnectionLost.run();
}
@Override
public void onError(Throwable e) {
log.error("OnResponse.onError", e);
channel.error(e);
}
@Override
public void onNext(byte[] response) {
log.debug("OnResponse.onNext: received message");
try {
channel.output(response);
} catch (BufferOverflowException e) {
cancel();
onError(e);
}
}
@Override
public void onConnectionLost() {
log.error("Connection lost");
cancel();
}
@Override
public void onConnected(WebSocket webSocket) {
log.debug("Connected");
webSocket.toObservable().map(b -> b.getDelegate().getBytes()).subscribe(this);
}
}
|
package main;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import bench.chengTxn.ChengTxnConstants;
public class Logger {
private static boolean isInit = false;
private static FileWriter fwriter = null;
// local log: tid->FileWriter
private static HashMap<Long, FileWriter> local_loggers = new HashMap<Long, FileWriter>();
private static void init() {
// check if folder exists
File directory = new File(Config.get().COBRA_FD);
if (!directory.exists()) {
directory.mkdirs();
}
// create the log file
try {
fwriter = new FileWriter(Config.get().BENCHMARK_LOG_PATH, Config.get().APPEND_OTHERWISE_RECREATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
isInit = true;
}
public synchronized static void logln(String prefix, String msg) {
if (!isInit) init();
try {
fwriter.write(prefix + "[" + Thread.currentThread().getId() + "] " + msg + "\n");
// FIXME: isn't this too expansive?
fwriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public synchronized static void logDebug(String msg) {
if (Config.get().LOG_DEBUG) {
logln("[DEBUG]", msg);
}
}
public synchronized static void logInfo(String msg) {
if (Config.get().LOG_INFO) {
logln("[INFO]", msg);
}
}
public synchronized static void logError(String msg) {
if (Config.get().LOG_ERROR) {
logln("[ERROR]", msg);
}
}
// ================
// Local log functions
// ================
public synchronized static void startLogger(String name) {
long tid = Thread.currentThread().getId();
String log_name = Config.get().COBRA_FD + name;
try {
FileWriter fw = new FileWriter(log_name, Config.get().APPEND_OTHERWISE_RECREATE);
local_loggers.put(tid, fw);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
public synchronized static void localwrite(String msg) {
long tid = Thread.currentThread().getId();
assert local_loggers.containsKey(tid);
FileWriter fw = local_loggers.get(tid);
try {
fw.write(msg + "\n");
// FIXME: isn't this too expansive?
fw.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package com.example.android.quakereport.Models;
import android.content.AsyncTaskLoader;
import android.content.Context;
import com.example.android.quakereport.Utilities.QueryUtils;
import java.util.List;
public class BookLoader extends AsyncTaskLoader<List<Book>> {
/**
* Tag for log messages
*/
private static final String LOG_TAG = BookLoader.class.getName();
/**
* Query URL
*/
private String mUrl;
/**
* Constructs a new {@link BookLoader}.
*
* @param context of the activity
* @param url to load data from
*/
public BookLoader(Context context, String url) {
super(context);
this.mUrl = url;
}
@Override
protected void onStartLoading() {
forceLoad();
}
/**
* This is on a background thread.
*/
@Override
public List<Book> loadInBackground() {
if (mUrl == null) {
return null;
}
// Perform the network request, parse the response, and extract a list of books.
List<Book> books = QueryUtils.fetchBookData(mUrl);
return books;
}
}
|
package kg.ash.javavi.actions;
import kg.ash.javavi.output.OutputClassPackages;
import kg.ash.javavi.searchers.PackagesLoader;
import kg.ash.javavi.cache.Cache;
public class GetClassPackagesAction extends ActionWithTarget {
@Override
public String perform(String[] args) {
return new OutputClassPackages(Cache.getInstance().getClassPackages())
.get(parseTarget(args));
}
}
|
/*
* Weblounge: Web Content Management System
* Copyright (c) 2003 - 2011 The Weblounge Team
* http://entwinemedia.com/weblounge
*
* 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 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package ch.entwine.weblounge.taglib.content;
import ch.entwine.weblounge.common.content.page.Page;
import ch.entwine.weblounge.common.editor.EditingState;
import ch.entwine.weblounge.common.impl.request.RequestUtils;
import ch.entwine.weblounge.common.impl.security.SecurityUtils;
import ch.entwine.weblounge.common.impl.security.SystemRole;
import ch.entwine.weblounge.common.request.WebloungeRequest;
import ch.entwine.weblounge.common.request.WebloungeResponse;
import ch.entwine.weblounge.taglib.WebloungeTag;
import java.io.IOException;
import javax.servlet.http.Cookie;
import javax.servlet.jsp.JspException;
/**
* This tag inserts the code to show the workbench.
*/
public class WorkbenchTag extends WebloungeTag {
/** Serial version uid */
private static final long serialVersionUID = -498800954917968929L;
/** Path to the workbench script */
public static final String WORKBENCH_SCRIPT = "<script src=\"/%1$2s/steal/steal.js?editor,%2$2s\"></script>";
/** Development identifier for steal */
private static final String STEAL_DEVELOPMENT = "development";
/** Production identifier for steal */
private static final String STEAL_PRODUCTION = "production";
/** Default path to the workbench ui */
private static final String DEFAULT_WORKBENCH_PATH = "weblounge";
/** The workbench path */
private String workbenchPath = DEFAULT_WORKBENCH_PATH;
/**
* Sets the workbench path.
*
* @param workbenchPath
* the path to the workbench ui
*/
public void setUri(String workbenchPath) {
this.workbenchPath = workbenchPath;
}
/**
* Writes the workbench script tag to the output.
*
* @see javax.servlet.jsp.tagext.Tag#doEndTag()
*/
@Override
public int doEndTag() throws JspException {
boolean isMockRequest = RequestUtils.isMockRequest(request);
// If the user does not have editing rights, make sure the
// cookie is deleted. This is likely to be the case after the user
// has hit the logout button or after the session has expired.
boolean isEditor = SecurityUtils.userHasRole(request.getUser(), SystemRole.EDITOR);
if (!isEditor && !isMockRequest) {
// Make sure the cookie is removed on the client side
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie c : cookies) {
if (EditingState.STATE_COOKIE.equals(c.getName())) {
Cookie cookie = new Cookie(EditingState.STATE_COOKIE, null);
cookie.setMaxAge(0);
cookie.setPath("/");
response.addCookie(cookie);
}
}
}
// Make sure to remove the session flag
request.getSession().removeAttribute(EditingState.STATE_COOKIE);
return super.doEndTag();
}
if (request.getParameter(EditingState.WORKBENCH_PREVIEW_PARAM) != null) {
return super.doEndTag();
}
// Is the ?edit parameter in place?
boolean enterWorkbench = request.getParameter(EditingState.WORKBENCH_PARAM) != null;
if (enterWorkbench && !isMockRequest) {
Cookie cookie = new Cookie(EditingState.STATE_COOKIE, "true");
cookie.setPath("/");
response.addCookie(cookie);
request.getSession().setAttribute(EditingState.STATE_COOKIE, Boolean.TRUE);
writeWorkbenchScript(getRequest(), getResponse());
return super.doEndTag();
} else if (RequestUtils.isEditingState(request)) {
writeWorkbenchScript(request, response);
}
return super.doEndTag();
}
private void writeWorkbenchScript(WebloungeRequest request,
WebloungeResponse response) throws JspException {
// Determine the environment for the steal.js script
String environment = null;
switch (request.getEnvironment()) {
case Development:
environment = STEAL_DEVELOPMENT;
break;
default:
environment = STEAL_PRODUCTION;
}
Page page = (Page) request.getAttribute(WebloungeRequest.PAGE);
// Add the current path to header for the editor
response.addHeader("path", page.getPath());
try {
pageContext.getOut().write("<script> window.currentLanguage = '" + request.getLanguage().getIdentifier() + "';");
pageContext.getOut().write("window.currentPagePath = '" + page.getPath() + "';</script>");
pageContext.getOut().write(String.format(WORKBENCH_SCRIPT, workbenchPath, environment));
} catch (IOException e) {
throw new JspException(e);
}
}
}
|
/*
* IdentifierNotFoundException.java 1.0 $Revision: 243 $
*
*
* Copyright (C) 2005 Roozbeh Farahbod
*
* Last modified by $Author: rfarahbod $ on $Date: 2011-03-29 02:05:21 +0200 (Di, 29 Mrz 2011) $.
*
* Licensed under the Academic Free License version 3.0
* http://www.opensource.org/licenses/afl-3.0.php
* http://www.coreasm.org/afl-3.0.php
*
*/
package org.coreasm.engine.absstorage;
import org.coreasm.engine.EngineException;
/**
* @author Roozbeh Farahbod
*
*/
public class IdentifierNotFoundException extends EngineException {
private static final long serialVersionUID = 1L;
public IdentifierNotFoundException() {
super();
}
public IdentifierNotFoundException(String message) {
super(message);
}
public IdentifierNotFoundException(String message, Throwable cause) {
super(message, cause);
}
public IdentifierNotFoundException(Throwable cause) {
super(cause);
}
}
|
package fi.aalto.trafficsense.trafficsense.backend.rest.types;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.gson.annotations.SerializedName;
import fi.aalto.trafficsense.trafficsense.backend.uploader.DataPoint;
import fi.aalto.trafficsense.trafficsense.backend.uploader.DataQueue;
public class DataBody {
@SerializedName("dataPoints")
public final ImmutableCollection<DataPoint> mDataPoints;
@SerializedName("sequence")
public final long mSequence;
public DataBody(ImmutableCollection<DataPoint> dataPoints, long sequence) {
this.mDataPoints = dataPoints;
this.mSequence = sequence;
}
public static DataBody createSnapshot(DataQueue queue) {
ImmutableList<DataPoint> dataPoints = queue.getSnapshot();
long sequence = Iterables.getLast(dataPoints).mSequence;
return new DataBody(dataPoints, sequence);
}
}
|
import java.util.*;
public class MethodSignature{
public static void main(String[] args){
}
public String getName(String name){
return null;
}
//the return type is not part of the signature
public List<String> getName(String name){
return null;
}
// the parameter name is not part of the signature
public String getName(String s){
return null;
}
// access modifier is not part of method signature
private String getName(String name){
return null;
}
}
|
/*
* Copyright 2016 Elvis Hew
*
* 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.elvishew.xlog.internal;
import com.elvishew.xlog.flattener.DefaultFlattener;
import com.elvishew.xlog.flattener.Flattener;
import com.elvishew.xlog.flattener.Flattener2;
import com.elvishew.xlog.formatter.border.BorderFormatter;
import com.elvishew.xlog.formatter.border.DefaultBorderFormatter;
import com.elvishew.xlog.formatter.message.json.DefaultJsonFormatter;
import com.elvishew.xlog.formatter.message.json.JsonFormatter;
import com.elvishew.xlog.formatter.message.object.ObjectFormatter;
import com.elvishew.xlog.formatter.message.throwable.DefaultThrowableFormatter;
import com.elvishew.xlog.formatter.message.throwable.ThrowableFormatter;
import com.elvishew.xlog.formatter.message.xml.DefaultXmlFormatter;
import com.elvishew.xlog.formatter.message.xml.XmlFormatter;
import com.elvishew.xlog.formatter.stacktrace.DefaultStackTraceFormatter;
import com.elvishew.xlog.formatter.stacktrace.StackTraceFormatter;
import com.elvishew.xlog.formatter.thread.DefaultThreadFormatter;
import com.elvishew.xlog.formatter.thread.ThreadFormatter;
import com.elvishew.xlog.printer.Printer;
import com.elvishew.xlog.printer.file.FilePrinter;
import com.elvishew.xlog.printer.file.backup.BackupStrategy2;
import com.elvishew.xlog.internal.printer.file.backup.BackupStrategyWrapper;
import com.elvishew.xlog.printer.file.backup.FileSizeBackupStrategy;
import com.elvishew.xlog.printer.file.clean.CleanStrategy;
import com.elvishew.xlog.printer.file.clean.NeverCleanStrategy;
import com.elvishew.xlog.printer.file.naming.ChangelessFileNameGenerator;
import com.elvishew.xlog.printer.file.naming.FileNameGenerator;
import java.util.Map;
/**
* Factory for providing default implementation.
*/
public class DefaultsFactory {
private static final String DEFAULT_LOG_FILE_NAME = "log";
private static final long DEFAULT_LOG_FILE_MAX_SIZE = 1024 * 1024; // 1M bytes;
/**
* Create the default JSON formatter.
*/
public static JsonFormatter createJsonFormatter() {
return new DefaultJsonFormatter();
}
/**
* Create the default XML formatter.
*/
public static XmlFormatter createXmlFormatter() {
return new DefaultXmlFormatter();
}
/**
* Create the default throwable formatter.
*/
public static ThrowableFormatter createThrowableFormatter() {
return new DefaultThrowableFormatter();
}
/**
* Create the default thread formatter.
*/
public static ThreadFormatter createThreadFormatter() {
return new DefaultThreadFormatter();
}
/**
* Create the default stack trace formatter.
*/
public static StackTraceFormatter createStackTraceFormatter() {
return new DefaultStackTraceFormatter();
}
/**
* Create the default border formatter.
*/
public static BorderFormatter createBorderFormatter() {
return new DefaultBorderFormatter();
}
/**
* Create the default {@link Flattener}.
*/
public static Flattener createFlattener() {
return new DefaultFlattener();
}
/**
* Create the default {@link Flattener2}.
*/
public static Flattener2 createFlattener2() {
return new DefaultFlattener();
}
/**
* Create the default printer.
*/
public static Printer createPrinter() {
return Platform.get().defaultPrinter();
}
/**
* Create the default file name generator for {@link FilePrinter}.
*/
public static FileNameGenerator createFileNameGenerator() {
return new ChangelessFileNameGenerator(DEFAULT_LOG_FILE_NAME);
}
/**
* Create the default backup strategy for {@link FilePrinter}.
*/
public static BackupStrategy2 createBackupStrategy() {
return new BackupStrategyWrapper(new FileSizeBackupStrategy(DEFAULT_LOG_FILE_MAX_SIZE));
}
/**
* Create the default clean strategy for {@link FilePrinter}.
*/
public static CleanStrategy createCleanStrategy() {
return new NeverCleanStrategy();
}
/**
* Get the builtin object formatters.
*
* @return the builtin object formatters
*/
public static Map<Class<?>, ObjectFormatter<?>> builtinObjectFormatters() {
return Platform.get().builtinObjectFormatters();
}
}
|
/* Copyright (C) 2013-2018 TU Dortmund
* This file is part of LearnLib, http://www.learnlib.de/.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.learnlib.testsupport.it.learner;
import de.learnlib.api.algorithm.LearningAlgorithm;
import de.learnlib.api.oracle.EquivalenceOracle;
import de.learnlib.api.query.DefaultQuery;
import de.learnlib.examples.LearningExample;
import de.learnlib.oracle.equivalence.SimulatorEQOracle;
import net.automatalib.automata.UniversalDeterministicAutomaton;
import net.automatalib.automata.concepts.SuffixOutput;
import net.automatalib.util.automata.Automata;
import net.automatalib.words.Alphabet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.ITest;
import org.testng.annotations.Test;
final class LearnerVariantITCase<I, D, M extends UniversalDeterministicAutomaton<?, I, ?, ?, ?> & SuffixOutput<I, D>>
implements ITest {
private static final Logger LOGGER = LoggerFactory.getLogger(LearnerVariantITCase.class);
private static final long NANOS_PER_MILLISECOND = 1000000;
private static final long MILLIS_PER_SECOND = 1000;
private final LearnerVariant<? extends M, I, D> variant;
private final LearningExample<I, D, ? extends M> example;
LearnerVariantITCase(LearnerVariant<? extends M, I, D> variant, LearningExample<I, D, ? extends M> example) {
this.variant = variant;
this.example = example;
}
@Test
public void testLearning() {
LearningAlgorithm<? extends M, I, D> learner = variant.getLearner();
Alphabet<I> alphabet = example.getAlphabet();
int maxRounds = variant.getMaxRounds();
if (maxRounds < 0) {
maxRounds = example.getReferenceAutomaton().size();
}
EquivalenceOracle<? super M, I, D> eqOracle = new SimulatorEQOracle<>(example.getReferenceAutomaton());
long start = System.nanoTime();
learner.startLearning();
int roundCounter = 0;
DefaultQuery<I, D> ceQuery;
while ((ceQuery = eqOracle.findCounterExample(learner.getHypothesisModel(), alphabet)) != null) {
roundCounter++;
if (roundCounter > maxRounds) {
Assert.fail("Learning took too many rounds (> " + maxRounds + ")");
}
boolean refined = learner.refineHypothesis(ceQuery);
Assert.assertTrue(refined, "Real counterexample " + ceQuery.getInput() + " did not refine hypothesis");
}
Assert.assertNull(Automata.findSeparatingWord(example.getReferenceAutomaton(),
learner.getHypothesisModel(),
alphabet), "Final hypothesis does not match reference automaton");
long duration = (System.nanoTime() - start) / NANOS_PER_MILLISECOND;
LOGGER.info("Passed learner integration test {} ... took [{}]",
getTestName(),
String.format("%d.%03ds", duration / MILLIS_PER_SECOND, duration % MILLIS_PER_SECOND));
}
@Override
public String getTestName() {
return variant.getLearnerName() + "[" + variant.getName() + "]/" + example.getClass().getSimpleName();
}
}
|
package org.batfish.datamodel.routing_policy.expr;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import java.io.Serializable;
import java.util.List;
import org.batfish.datamodel.routing_policy.Environment;
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "class")
public abstract class AsPathListExpr implements Serializable {
private static final long serialVersionUID = 1L;
@Override
public abstract boolean equals(Object obj);
public abstract List<Long> evaluate(Environment environment);
@Override
public abstract int hashCode();
}
|
package com.github.vladislavgoltjajev.personalcode.locale.latvia;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EmptySource;
import org.junit.jupiter.params.provider.NullSource;
import org.junit.jupiter.params.provider.ValueSource;
import static org.assertj.core.api.Assertions.assertThat;
class LatvianPersonalCodeValidatorTest {
LatvianPersonalCodeValidator validator;
@BeforeEach
void setUp() {
validator = new LatvianPersonalCodeValidator();
}
@ParameterizedTest
@ValueSource(strings = {
"180565-05610",
"061193-06460",
"280638-19406",
"290212-29381",
"211244-14874",
"290156-11605",
"060287-06450",
"140761-19428",
"120768-18764",
"32073120115",
"32019028596",
"32699402624",
"32416565491",
"323691-93794",
"321412-91101",
"328926-13925",
"323106-55350"
})
void validateValidPersonalCode(String personalCode) {
assertThat(validator.isValid(personalCode)).isTrue();
}
@ParameterizedTest
@NullSource
@EmptySource
@ValueSource(strings = {
"123",
"test",
"37605030291",
"77605030291",
"60319113016",
"99999999999",
"999999-99999",
"39912310173",
"39002310001",
"50102290005",
"501022900051",
"325-442-49548",
"335442-49548",
"315442-49548",
"290213-29381",
"180565-05611"
})
void validateInvalidPersonalCode(String personalCode) {
assertThat(validator.isValid(personalCode)).isFalse();
}
@ParameterizedTest
@ValueSource(strings = {
"32073120115",
"32019028596",
"32699402624",
"32416565491",
"323691-93794",
"321412-91101",
"328926-13925",
"323106-55350"
})
void validateValidUpdatedPersonalCode(String personalCode) {
assertThat(validator.isValidUpdatedPersonalCode(personalCode)).isTrue();
}
@ParameterizedTest
@ValueSource(strings = {
"180565-05610",
"061193-06460",
"280638-19406",
"290212-29381",
"211244-14874",
"290156-11605",
"060287-06450",
"140761-19428",
"120768-18764"
})
void validateValidLegacyPersonalCode(String personalCode) {
assertThat(validator.isValidLegacyPersonalCode(personalCode)).isTrue();
}
@ParameterizedTest
@NullSource
@EmptySource
@ValueSource(strings = {
"123",
"test",
"37605030291",
"77605030291",
"60319113016",
"99999999999",
"999999-99999",
"39912310173",
"39002310001",
"50102290005",
"501022900051",
"325-442-49548",
"335442-49548",
"315442-49548",
"290213-29381",
"180565-05611",
"180565-05610",
"061193-06460",
"280638-19406",
"290212-29381",
"211244-14874",
"290156-11605",
"060287-06450",
"140761-19428",
"120768-18764"
})
void validateInvalidUpdatedPersonalCode(String personalCode) {
assertThat(validator.isValidUpdatedPersonalCode(personalCode)).isFalse();
}
@ParameterizedTest
@NullSource
@EmptySource
@ValueSource(strings = {
"123",
"test",
"37605030291",
"77605030291",
"60319113016",
"99999999999",
"999999-99999",
"39912310173",
"39002310001",
"50102290005",
"501022900051",
"325-442-49548",
"335442-49548",
"315442-49548",
"290213-29381",
"180565-05611",
"32744759186",
"322589-41469",
"329294-80588",
"32240310721"
})
void validateInvalidLegacyPersonalCode(String personalCode) {
assertThat(validator.isValidLegacyPersonalCode(personalCode)).isFalse();
}
}
|
/*
* File: PrintLogger.java
* Author: Kyle A. Roberson kylerob@uab.edu
* Assignment: kylerob-P3 - EE333 Spring 2019
* Vers: 1.1.0 02/19/2019 KAR - finalizing
* Vers: 1.0.0 02/18/2019 KAR - initial coding
*/
package p5;
/**
* An I/O class PrintLogger implements the Logger interface and conditionally
* outputs strings to stdout.
* @author Kyle A. Roberson kylerob@uab.edu
*/
public class PrintLogger implements Logger {
private int threshold = 0;
private int level = -1;
// Constructor
/**
* Create a PrintLogger with specific threshold
* @param threshold level that has to be met or exceeded for logging
* to occur
*/
public PrintLogger(int threshold) {
if (threshold >= 0) {
this.threshold = threshold;
}
}
// Commands
/**
* Prints a string to stdout if level is greater than or equal to threshold.
* The printing routine will add a newline to the logEntry.
* The Logger class defines common values for level.
* @param level value noting the type of the information
* @param logEntry text to be part of the printed log
*/
public void log(int level, String logEntry) {
if (level >= threshold) {
if (level < 0 ) {
// don't print
}
else if ( level < 10 ) {
System.out.println("DEBUG: " + logEntry);
}
else if (level < 20) {
System.out.println("INFO: " + logEntry);
}
else if (level < 50) {
System.out.println("TIMESTAMP: " + logEntry);
}
else if (level < 100) {
System.out.println("WARNING: " + logEntry);
}
else if (level < 100000) {
System.out.println("ERROR: " + logEntry);
}
else {
System.out.println("ALWAYS: " + logEntry);
}
}
}
/**
* Set a new log threshold for actual logging
* @param newThreshold level that must be met or exceeded for actual logging
* when the logger is asked to log something
*/
@Override
public void setLogThreshold(int newThreshold) {
}
/**
* Log a message if `level` is greater than or equal to logger's threshold.
* The actual logging routine will add a newline to the logEntry if
* appropriate.
* @param level message's level
* @param logEntry text to log (a newline will be added if appropriate)
*/
//@Override
//public void log(int level, String logEntry) {
//}
/**
* Closing the logging on this class. The use of this log channel is
* complete and any closing actions that are necessary should be done.
*/
@Override
public void close() {
// does nothing at this point
}
}
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.hdinsight.v2018_06_01_preview;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* The HDInsight cluster application GET response.
*/
public class ApplicationProperties {
/**
* The list of roles in the cluster.
*/
@JsonProperty(value = "computeProfile")
private ComputeProfile computeProfile;
/**
* The list of install script actions.
*/
@JsonProperty(value = "installScriptActions")
private List<RuntimeScriptAction> installScriptActions;
/**
* The list of uninstall script actions.
*/
@JsonProperty(value = "uninstallScriptActions")
private List<RuntimeScriptAction> uninstallScriptActions;
/**
* The list of application HTTPS endpoints.
*/
@JsonProperty(value = "httpsEndpoints")
private List<ApplicationGetHttpsEndpoint> httpsEndpoints;
/**
* The list of application SSH endpoints.
*/
@JsonProperty(value = "sshEndpoints")
private List<ApplicationGetEndpoint> sshEndpoints;
/**
* The provisioning state of the application.
*/
@JsonProperty(value = "provisioningState", access = JsonProperty.Access.WRITE_ONLY)
private String provisioningState;
/**
* The application type.
*/
@JsonProperty(value = "applicationType")
private String applicationType;
/**
* The application state.
*/
@JsonProperty(value = "applicationState", access = JsonProperty.Access.WRITE_ONLY)
private String applicationState;
/**
* The list of errors.
*/
@JsonProperty(value = "errors")
private List<Errors> errors;
/**
* The application create date time.
*/
@JsonProperty(value = "createdDate", access = JsonProperty.Access.WRITE_ONLY)
private String createdDate;
/**
* The marketplace identifier.
*/
@JsonProperty(value = "marketplaceIdentifier", access = JsonProperty.Access.WRITE_ONLY)
private String marketplaceIdentifier;
/**
* Get the list of roles in the cluster.
*
* @return the computeProfile value
*/
public ComputeProfile computeProfile() {
return this.computeProfile;
}
/**
* Set the list of roles in the cluster.
*
* @param computeProfile the computeProfile value to set
* @return the ApplicationProperties object itself.
*/
public ApplicationProperties withComputeProfile(ComputeProfile computeProfile) {
this.computeProfile = computeProfile;
return this;
}
/**
* Get the list of install script actions.
*
* @return the installScriptActions value
*/
public List<RuntimeScriptAction> installScriptActions() {
return this.installScriptActions;
}
/**
* Set the list of install script actions.
*
* @param installScriptActions the installScriptActions value to set
* @return the ApplicationProperties object itself.
*/
public ApplicationProperties withInstallScriptActions(List<RuntimeScriptAction> installScriptActions) {
this.installScriptActions = installScriptActions;
return this;
}
/**
* Get the list of uninstall script actions.
*
* @return the uninstallScriptActions value
*/
public List<RuntimeScriptAction> uninstallScriptActions() {
return this.uninstallScriptActions;
}
/**
* Set the list of uninstall script actions.
*
* @param uninstallScriptActions the uninstallScriptActions value to set
* @return the ApplicationProperties object itself.
*/
public ApplicationProperties withUninstallScriptActions(List<RuntimeScriptAction> uninstallScriptActions) {
this.uninstallScriptActions = uninstallScriptActions;
return this;
}
/**
* Get the list of application HTTPS endpoints.
*
* @return the httpsEndpoints value
*/
public List<ApplicationGetHttpsEndpoint> httpsEndpoints() {
return this.httpsEndpoints;
}
/**
* Set the list of application HTTPS endpoints.
*
* @param httpsEndpoints the httpsEndpoints value to set
* @return the ApplicationProperties object itself.
*/
public ApplicationProperties withHttpsEndpoints(List<ApplicationGetHttpsEndpoint> httpsEndpoints) {
this.httpsEndpoints = httpsEndpoints;
return this;
}
/**
* Get the list of application SSH endpoints.
*
* @return the sshEndpoints value
*/
public List<ApplicationGetEndpoint> sshEndpoints() {
return this.sshEndpoints;
}
/**
* Set the list of application SSH endpoints.
*
* @param sshEndpoints the sshEndpoints value to set
* @return the ApplicationProperties object itself.
*/
public ApplicationProperties withSshEndpoints(List<ApplicationGetEndpoint> sshEndpoints) {
this.sshEndpoints = sshEndpoints;
return this;
}
/**
* Get the provisioning state of the application.
*
* @return the provisioningState value
*/
public String provisioningState() {
return this.provisioningState;
}
/**
* Get the application type.
*
* @return the applicationType value
*/
public String applicationType() {
return this.applicationType;
}
/**
* Set the application type.
*
* @param applicationType the applicationType value to set
* @return the ApplicationProperties object itself.
*/
public ApplicationProperties withApplicationType(String applicationType) {
this.applicationType = applicationType;
return this;
}
/**
* Get the application state.
*
* @return the applicationState value
*/
public String applicationState() {
return this.applicationState;
}
/**
* Get the list of errors.
*
* @return the errors value
*/
public List<Errors> errors() {
return this.errors;
}
/**
* Set the list of errors.
*
* @param errors the errors value to set
* @return the ApplicationProperties object itself.
*/
public ApplicationProperties withErrors(List<Errors> errors) {
this.errors = errors;
return this;
}
/**
* Get the application create date time.
*
* @return the createdDate value
*/
public String createdDate() {
return this.createdDate;
}
/**
* Get the marketplace identifier.
*
* @return the marketplaceIdentifier value
*/
public String marketplaceIdentifier() {
return this.marketplaceIdentifier;
}
}
|
package org.batfish.datamodel.answers;
import java.util.SortedMap;
import org.batfish.common.ParseTreeSentences;
public interface ParseAnswerElement extends InitStepAnswerElement {
SortedMap<String, ParseStatus> getParseStatus();
SortedMap<String, ParseTreeSentences> getParseTrees();
void setParseStatus(SortedMap<String, ParseStatus> parseStatus);
void setParseTrees(SortedMap<String, ParseTreeSentences> parseTrees);
}
|
package DoordashPrep;
public class _0200NumberOfIslands {
public static void main(String[] args) {
System.out.println(numIslands(
new char[][] { new char[] { '1', '1', '1', '1', '0' }, new char[] { '1', '1', '0', '1', '0' },
new char[] { '1', '1', '0', '0', '0' }, new char[] { '0', '0', '0', '0', '0' } }));
System.out.println(numIslands(
new char[][] { new char[] { '1', '1', '0', '0', '0' }, new char[] { '1', '1', '0', '0', '0' },
new char[] { '0', '0', '1', '0', '0' }, new char[] { '0', '0', '0', '1', '1' } }));
}
public static int numIslands(char[][] grid) {
if (grid == null || grid.length == 0)
return 0;
int numOfIslands = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == '1') {
dfs(i, j, grid);
numOfIslands++;
}
}
}
return numOfIslands;
}
public static void dfs(int x, int y, char[][] grid) {
if (x < 0 || y < 0 || x >= grid.length || y >= grid[0].length || grid[x][y] != '1')
return;
grid[x][y] = '0';
dfs(x - 1, y, grid);
dfs(x + 1, y, grid);
dfs(x, y - 1, grid);
dfs(x, y + 1, grid);
}
}
|
package com.github.qzagarese.dockerunit.exception;
public class ConfigException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 8021806700322024225L;
public ConfigException(String message) {
super(message);
}
}
|
/*******************************************************************************
* Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.tools.workbench.test.mappingsmodel.meta;
/**
* @see MWClassTests#testMarkerInterface
*/
public interface MarkerInterface {
// leave empty so we sorta look like a "stub" interface
}
|
package org.protobeans.core.util;
public class SnowFlakeIdGenerator {
//Если под timestamp выделить 41 бит, да еще и отнимать значения, которые уже прошли, то данный алгоритм будет работать до 2080 года
//Максимальное число помещающееся в 41 бит - 2199023255551
//Кол-во миллисекунд которые уже давно прошли - 1288834974657
//Т.к. мы их отнимаем, то максимальный таймстемп = 2199023255551 + 1288834974657 = Wed Jul 10 20:30:30 MSK 2080
private static final long TIMESTAMP_BITS = 41L;
private static final long TWEPOCH = 1288834974657L;
private static final int AVAILABLE_BITS = Long.SIZE - 1;//Необходимо для работы со знаковыми числами
private static final long TIMESTAMP_SHIFT = AVAILABLE_BITS - TIMESTAMP_BITS;
private final int clientId;
private final int sequenceMax;
private final int sequenceShift;
private long lastTimestamp;
private long sequence;
private volatile long timeShiftCount;
private volatile long sequenceOverflowCount;
/**
* @param maxClients Max planned clients in your cluster
* @param clientId Client ID from 0 to (maxClients - 1)
*/
public SnowFlakeIdGenerator(long maxClients, int clientId) {
if (maxClients <= 0 || maxClients > 1024) {
throw new IllegalStateException("Too many clients");
}
int clientIdBits = Long.toBinaryString(maxClients - 1).length();
int maxClientId = -1 ^ (-1 << clientIdBits);
if (clientId < 0 || clientId > maxClientId) {
throw new IllegalStateException("Incorrect clientId. Min client id is 0. Max client id is: " + maxClientId);
}
long sequenceBits = AVAILABLE_BITS - TIMESTAMP_BITS - clientIdBits;
sequenceShift = clientIdBits;
sequenceMax = -1 ^ (-1 << sequenceBits);//максимальное число последовательности, которое может быть сгенерировано в 1 миллисекунду
this.clientId = clientId;
}
public int getSequenceMax() {
return sequenceMax;
}
public long getTimeShiftCount() {
return timeShiftCount;
}
public long getSequenceOverflowCount() {
return sequenceOverflowCount;
}
/**
* @return Signed positive long number in format 0|timestampBits|sequenceBits|clientIdBits
*
* Возвращаемое число обладает следующими свойствами:
* 1. Уникальное в пределах кластера из maxClients
* 2. Труднопредсказуемое в будущем, т.к. зависит от времени
* 3. Гарантированно возрастает в пределах одного генератора (при условии, что часы не будут переводить в момент неактивности программы)
* 4. Возрастает с определенной погрешностью в пределах кластера, т.к. невозможно обеспечить идеальную синхронизацию часов между машинами
*/
public synchronized long generateLongId() {
long timestamp = System.currentTimeMillis();
if(timestamp < lastTimestamp) {//Значит перевели часы
timeShiftCount++;
timestamp = tilNextMillis(lastTimestamp);//Ждем следующего момента
}
if (lastTimestamp == timestamp) {
sequence++;
if (sequence > sequenceMax) {
sequenceOverflowCount++;
sequence = 0;
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0;
}
lastTimestamp = timestamp;
//0|timestampBits|sequenceBits|clientIdBits
return ((timestamp - TWEPOCH) << TIMESTAMP_SHIFT) | (sequence << sequenceShift) | clientId;
}
private long tilNextMillis(long lastTs) {
long timestamp = System.currentTimeMillis();
while (timestamp <= lastTs) {
timestamp = System.currentTimeMillis();
}
return timestamp;
}
}
|
/*
* 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.calcite.util.trace;
import org.slf4j.Logger;
import java.text.DecimalFormat;
/**
* CalciteTimingTracer provides a mechanism for tracing the timing of a call
* sequence at nanosecond resolution.
*/
public class CalciteTimingTracer {
//~ Static fields/initializers ---------------------------------------------
private static final DecimalFormat DECIMAL_FORMAT =
new DecimalFormat("###,###,###,###,###");
//~ Instance fields --------------------------------------------------------
private final Logger logger;
private long lastNanoTime;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new timing tracer, publishing an initial event (at elapsed time
* 0).
*
* @param logger logger on which to log timing events; level FINE will be
* used
* @param startEvent event to trace as start of timing
*/
public CalciteTimingTracer(
Logger logger,
String startEvent) {
if (!logger.isDebugEnabled()) {
this.logger = null;
return;
} else {
this.logger = logger;
}
lastNanoTime = System.nanoTime();
logger.debug("{}: elapsed nanos=0", startEvent);
}
//~ Methods ----------------------------------------------------------------
/**
* Publishes an event with the time elapsed since the previous event.
*
* @param event event to trace
*/
public void traceTime(String event) {
if (logger == null) {
return;
}
long newNanoTime = System.nanoTime();
long elapsed = newNanoTime - lastNanoTime;
lastNanoTime = newNanoTime;
logger.debug("{}: elapsed nanos={}", event, DECIMAL_FORMAT.format(elapsed));
}
}
// End CalciteTimingTracer.java
|
/*
***** BEGIN LICENSE BLOCK *****
* Version: EPL 2.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Eclipse Public
* 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.eclipse.org/legal/epl-v20.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001-2002 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2001-2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2002 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2004 Thomas E Enebo <enebo@acm.org>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the EPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the EPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby.ast;
import java.util.List;
import org.jruby.ast.visitor.NodeVisitor;
import org.jruby.lexer.yacc.ISourcePosition;
public class OpAsgnAndNode extends Node implements BinaryOperatorNode {
private final Node firstNode;
private final Node secondNode;
public OpAsgnAndNode(ISourcePosition position, Node headNode, Node valueNode) {
super(position, headNode.containsVariableAssignment() || valueNode.containsVariableAssignment());
assert headNode != null : "headNode is not null";
assert valueNode != null : "valueNode is not null";
firstNode = headNode;
secondNode = valueNode;
}
public NodeType getNodeType() {
return NodeType.OPASGNANDNODE;
}
/**
* Accept for the visitor pattern.
* @param iVisitor the visitor
**/
public <T> T accept(NodeVisitor<T> iVisitor) {
return iVisitor.visitOpAsgnAndNode(this);
}
/**
* Gets the firstNode.
* @return Returns a Node
*/
public Node getFirstNode() {
return firstNode;
}
/**
* Gets the secondNode.
* @return Returns a Node
*/
public Node getSecondNode() {
return secondNode;
}
public List<Node> childNodes() {
return Node.createList(firstNode, secondNode);
}
}
|
/*
* Copyright 2015 Hippo B.V. (http://www.onehippo.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hippoecm.frontend.plugins.jquery.upload.single;
import java.util.Map;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.event.Broadcast;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.request.resource.JavaScriptResourceReference;
import org.apache.wicket.util.template.PackageTextTemplate;
import org.hippoecm.frontend.plugins.jquery.upload.FileUploadBehavior;
import org.hippoecm.frontend.plugins.jquery.upload.FileUploadWidgetSettings;
import org.hippoecm.frontend.widgets.UpdateFeedbackInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Create an unique instance of jquery-file-upload widget. It does not work for multiple instances jquery-file-upload
*/
public class SingleFileUploadBar extends Panel {
static private final Logger log = LoggerFactory.getLogger(SingleFileUploadBar.class);
private static final String JQUERY_FILEUPLOAD_SINGLE_JS = "jquery.fileupload-single.js";
private static final String CONFIG_JS = "fileupload-single-config.js";
public SingleFileUploadBar(final String id, final FileUploadWidgetSettings settings) {
super(id);
setOutputMarkupId(true);
AbstractDefaultAjaxBehavior refreshAjaxBehavior;
add(refreshAjaxBehavior = new AbstractDefaultAjaxBehavior() {
@Override
protected void respond(final AjaxRequestTarget target) {
log.debug("Received an ajax callback refreshing page");
target.add(SingleFileUploadBar.this.getPage());
// refresh feedback panel in EditPerspective if needed
send(SingleFileUploadBar.this, Broadcast.BUBBLE, new UpdateFeedbackInfo(target));
}
});
final AbstractDefaultAjaxBehavior onChangeAjaxBehavior;
add(onChangeAjaxBehavior = new AbstractDefaultAjaxBehavior() {
@Override
protected void respond(final AjaxRequestTarget target) {
onChange(target);
}
});
add(new FileUploadBehavior(settings) {
@Override
protected void renderScripts(final IHeaderResponse response) {
super.renderScripts(response);
response.render(JavaScriptHeaderItem.forReference(
new JavaScriptResourceReference(SingleFileUploadBar.class, JQUERY_FILEUPLOAD_SINGLE_JS)));
}
@Override
protected Map<String, Object> configureParameters(final Component component) {
final Map<String, Object> variables = super.configureParameters(component);
//the script to refresh page after sending file has been done
variables.put("callbackRefreshScript", refreshAjaxBehavior.getCallbackScript());
variables.put("callbackFileOnChangeScript", onChangeAjaxBehavior.getCallbackScript());
onConfigureParameters(variables);
return variables;
}
@Override
protected void renderWidgetConfig(final IHeaderResponse response, final Map<String, Object> variables) {
PackageTextTemplate jsTmpl = new PackageTextTemplate(SingleFileUploadBar.class, CONFIG_JS);
String s = jsTmpl.asString(variables);
// call the configuration after all DOM elements are loaded
response.render(OnDomReadyHeaderItem.forScript(s));
}
});
}
/**
* This event is called when selecting a new file
* @param target
*/
protected void onChange(final AjaxRequestTarget target) {
}
/**
* Override this method to insert more variables to the widget configuration
*
* @param variables
*/
protected void onConfigureParameters(final Map<String, Object> variables) {
}
}
|
package cn.hutool.cron.pattern;
import java.util.Date;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import cn.hutool.core.date.DateUtil;
public class CronPatternUtilTest {
@Test
public void matchedDatesTest() {
//测试每30秒执行
List<Date> matchedDates = CronPatternUtil.matchedDates("0/30 * 8-18 * * ?", DateUtil.parse("2018-10-15 14:33:22"), 5, true);
Assert.assertEquals(5, matchedDates.size());
Assert.assertEquals("2018-10-15 14:33:30", matchedDates.get(0).toString());
Assert.assertEquals("2018-10-15 14:34:00", matchedDates.get(1).toString());
Assert.assertEquals("2018-10-15 14:34:30", matchedDates.get(2).toString());
Assert.assertEquals("2018-10-15 14:35:00", matchedDates.get(3).toString());
Assert.assertEquals("2018-10-15 14:35:30", matchedDates.get(4).toString());
}
@Test
public void matchedDatesTest2() {
//测试每小时执行
List<Date> matchedDates = CronPatternUtil.matchedDates("0 0 */1 * * *", DateUtil.parse("2018-10-15 14:33:22"), 5, true);
Assert.assertEquals(5, matchedDates.size());
Assert.assertEquals("2018-10-15 15:00:00", matchedDates.get(0).toString());
Assert.assertEquals("2018-10-15 16:00:00", matchedDates.get(1).toString());
Assert.assertEquals("2018-10-15 17:00:00", matchedDates.get(2).toString());
Assert.assertEquals("2018-10-15 18:00:00", matchedDates.get(3).toString());
Assert.assertEquals("2018-10-15 19:00:00", matchedDates.get(4).toString());
}
@Test
public void matchedDatesTest3() {
//测试最后一天
List<Date> matchedDates = CronPatternUtil.matchedDates("0 0 */1 L * *", DateUtil.parse("2018-10-30 23:33:22"), 5, true);
Assert.assertEquals(5, matchedDates.size());
Assert.assertEquals("2018-10-31 00:00:00", matchedDates.get(0).toString());
Assert.assertEquals("2018-10-31 01:00:00", matchedDates.get(1).toString());
Assert.assertEquals("2018-10-31 02:00:00", matchedDates.get(2).toString());
Assert.assertEquals("2018-10-31 03:00:00", matchedDates.get(3).toString());
Assert.assertEquals("2018-10-31 04:00:00", matchedDates.get(4).toString());
}
}
|
/*
* Copyright 2007 The JA-SIG Collaborative. All rights reserved. See license
* distributed with this file and available online at
* http://www.ja-sig.org/products/cas/overview/license/
*/
package org.jasig.cas.adaptors.radius;
import java.net.InetAddress;
import java.net.UnknownHostException;
import net.jradius.client.RadiusClient;
import net.jradius.client.auth.PAPAuthenticator;
import net.jradius.client.auth.RadiusAuthenticator;
import net.jradius.dictionary.Attr_UserName;
import net.jradius.dictionary.Attr_UserPassword;
import net.jradius.exception.RadiusException;
import net.jradius.exception.UnknownAttributeException;
import net.jradius.packet.AccessAccept;
import net.jradius.packet.AccessRequest;
import net.jradius.packet.RadiusPacket;
import net.jradius.packet.attribute.AttributeFactory;
import net.jradius.packet.attribute.AttributeList;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Implementation of a RadiusServer that utilizes the JRadius packages available
* at <a href="http://jradius.sf.net">http://jradius.sf.net</a>.
*
* @author Scott Battaglia
* @version $Revision: 22327 $ $Date: 2010-11-10 00:05:10 -0500 (Wed, 10 Nov 2010) $
* @since 3.1
*/
public final class JRadiusServerImpl implements RadiusServer {
private static final Logger LOG = LoggerFactory.getLogger(JRadiusServerImpl.class);
/** Default PAP Authenticator if no other one is specified. */
private static final RadiusAuthenticator DEFAULT_RADIUS_AUTHENTICATOR = new PAPAuthenticator();
/** Default port to do authentication on. */
private static final int DEFAULT_AUTHENTICATION_PORT = 1812;
/** Default port to do accounting on. */
private static final int DEFAULT_ACCOUNTING_PORT = 1813;
/** Default socket timeout time. */
private static final int DEFAULT_SOCKET_TIMEOUT = 5;
/** Default number of retries. */
private static final int DEFAULT_NUMBER_OF_RETRIES = 3;
/** The port to do accounting on. */
private final int accountingPort;
/** The port to do authentication on. */
private final int authenticationPort;
/** The timeout for sockets. */
private final int socketTimeout;
/** The conversion from hostname to an InetAddress. */
private final InetAddress inetAddress;
/** The shared secret to send to the RADIUS server. */
private final String sharedSecret;
/** The number of retries to do per authentication request. */
private final int retries;
/** The RADIUS Authenticator to use. */
private final RadiusAuthenticator radiusAuthenticator;
/** Load the dictionary implementation. */
static {
AttributeFactory
.loadAttributeDictionary("net.jradius.dictionary.AttributeDictionaryImpl");
}
/**
* Simplest constructor to set the hostname and the shared secret. Uses
* default values for everything else.
*
* @param hostName the host name of the RADIUS server.
* @param sharedSecret the shared secret with that server.
* @throws UnknownHostException if the hostname cannot be resolved.
*/
public JRadiusServerImpl(final String hostName, final String sharedSecret)
throws UnknownHostException {
this(hostName, sharedSecret, DEFAULT_RADIUS_AUTHENTICATOR,
DEFAULT_AUTHENTICATION_PORT);
}
/**
* Constructor to set the host name, shared secret and authentication type.
*
* @param hostName the host name of the RADIUS server.
* @param sharedSecret the shared secret with that server.
* @param radiusAuthenticator the RADIUS authenticator to use.
* @throws UnknownHostException if the hostname cannot be resolved.
*/
public JRadiusServerImpl(final String hostName, final String sharedSecret,
final RadiusAuthenticator radiusAuthenticator)
throws UnknownHostException {
this(hostName, sharedSecret, radiusAuthenticator,
DEFAULT_AUTHENTICATION_PORT);
}
/**
* Constructor that aceps the host name, shared secret, authenticaion type,
* and port.
*
* @param hostName the host name of the RADIUS server.
* @param sharedSecret the shared secret with that server.
* @param radiusAuthenticator the RADIUS authenticator to use.
* @param authenticationPort the port to use to authenticate on.
* @throws UnknownHostException if the hostname cannot be resolved.
*/
public JRadiusServerImpl(final String hostName, final String sharedSecret,
final RadiusAuthenticator radiusAuthenticator,
final int authenticationPort) throws UnknownHostException {
this(hostName, sharedSecret, radiusAuthenticator, authenticationPort,
DEFAULT_ACCOUNTING_PORT);
}
/**
* Constructor that aceps the host name, shared secret, authenticaion type,
* authentication port, and accounting port.
*
* @param hostName the host name of the RADIUS server.
* @param sharedSecret the shared secret with that server.
* @param radiusAuthenticator the RADIUS authenticator to use.
* @param authenticationPort the port to use to authenticate on.
* @param accountingPort the port to use to do accounting.
* @throws UnknownHostException if the hostname cannot be resolved.
*/
public JRadiusServerImpl(final String hostName, final String sharedSecret,
final RadiusAuthenticator radiusAuthenticator,
final int authenticationPort, final int accountingPort)
throws UnknownHostException {
this(hostName, sharedSecret, radiusAuthenticator, authenticationPort,
accountingPort, DEFAULT_SOCKET_TIMEOUT, DEFAULT_NUMBER_OF_RETRIES);
}
public JRadiusServerImpl(final String hostName, final String sharedSecret,
final RadiusAuthenticator radiusAuthenticator,
final int authenticationPort, final int accountingPort,
final int socketTimeout, final int retries) throws UnknownHostException {
this.sharedSecret = sharedSecret;
this.authenticationPort = authenticationPort;
this.accountingPort = accountingPort;
this.socketTimeout = socketTimeout;
this.retries = retries;
this.radiusAuthenticator = radiusAuthenticator;
this.inetAddress = InetAddress.getByName(hostName);
}
public boolean authenticate(
final UsernamePasswordCredentials usernamePasswordCredentials) {
final RadiusClient radiusClient = getNewRadiusClient();
final AttributeList attributeList = new AttributeList();
attributeList.add(new Attr_UserName(usernamePasswordCredentials
.getUsername()));
attributeList.add(new Attr_UserPassword(usernamePasswordCredentials
.getPassword()));
final AccessRequest request = new AccessRequest(radiusClient,
attributeList);
try {
final RadiusPacket response = radiusClient.authenticate(request,
this.radiusAuthenticator, this.retries);
// accepted
if (response instanceof AccessAccept) {
LOG.debug("Authentication request suceeded for host:"
+ this.inetAddress.getCanonicalHostName()
+ " and username "
+ usernamePasswordCredentials.getUsername());
return true;
}
// rejected
LOG.debug("Authentication request failed for host:"
+ this.inetAddress.getCanonicalHostName() + " and username "
+ usernamePasswordCredentials.getUsername());
return false;
} catch (final UnknownAttributeException e) {
throw new IllegalArgumentException(
"Passed an unknown attribute to RADIUS client: "
+ e.getMessage());
} catch (final RadiusException e) {
throw new IllegalStateException(
"Received response that puts RadiusClient into illegal state: "
+ e.getMessage());
}
}
private RadiusClient getNewRadiusClient() {
return new RadiusClient(this.inetAddress, this.sharedSecret,
this.authenticationPort, this.accountingPort, this.socketTimeout);
}
}
|
package com.taotao.cloud.netty.support;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import org.springframework.core.MethodParameter;
public class HttpHeadersMethodArgumentResolver implements MethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return HttpHeaders.class.isAssignableFrom(parameter.getParameterType());
}
@Override
public Object resolveArgument(MethodParameter parameter, Channel channel, Object object)
throws Exception {
return ((FullHttpRequest) object).headers();
}
}
|
/*
* Copyright (c) 2020
* Author: xiaoweixiang
*/
package finished.程序员面试宝典.cxy0408;
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
this.val = x;
}
}
|
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University
// Copyright (c) 2011, 2012 Open Networking Foundation
// Copyright (c) 2012, 2013 Big Switch Networks, Inc.
// This library was generated by the LoxiGen Compiler.
// See the file LICENSE.txt which should have been included in the source distribution
// Automatically generated by LOXI from template of_class.java
// Do not modify
package org.projectfloodlight.openflow.protocol.ver15;
import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
import io.netty.buffer.ByteBuf;
import com.google.common.hash.PrimitiveSink;
import com.google.common.hash.Funnel;
class OFBsnTlvFreeCountVer15 implements OFBsnTlvFreeCount {
private static final Logger logger = LoggerFactory.getLogger(OFBsnTlvFreeCountVer15.class);
// version: 1.5
final static byte WIRE_VERSION = 6;
final static int LENGTH = 8;
private final static long DEFAULT_VALUE = 0x0L;
// OF message fields
private final long value;
//
// Immutable default instance
final static OFBsnTlvFreeCountVer15 DEFAULT = new OFBsnTlvFreeCountVer15(
DEFAULT_VALUE
);
// package private constructor - used by readers, builders, and factory
OFBsnTlvFreeCountVer15(long value) {
this.value = U32.normalize(value);
}
// Accessors for OF message fields
@Override
public int getType() {
return 0xd7;
}
@Override
public long getValue() {
return value;
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_15;
}
public OFBsnTlvFreeCount.Builder createBuilder() {
return new BuilderWithParent(this);
}
static class BuilderWithParent implements OFBsnTlvFreeCount.Builder {
final OFBsnTlvFreeCountVer15 parentMessage;
// OF message fields
private boolean valueSet;
private long value;
BuilderWithParent(OFBsnTlvFreeCountVer15 parentMessage) {
this.parentMessage = parentMessage;
}
@Override
public int getType() {
return 0xd7;
}
@Override
public long getValue() {
return value;
}
@Override
public OFBsnTlvFreeCount.Builder setValue(long value) {
this.value = value;
this.valueSet = true;
return this;
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_15;
}
@Override
public OFBsnTlvFreeCount build() {
long value = this.valueSet ? this.value : parentMessage.value;
//
return new OFBsnTlvFreeCountVer15(
value
);
}
}
static class Builder implements OFBsnTlvFreeCount.Builder {
// OF message fields
private boolean valueSet;
private long value;
@Override
public int getType() {
return 0xd7;
}
@Override
public long getValue() {
return value;
}
@Override
public OFBsnTlvFreeCount.Builder setValue(long value) {
this.value = value;
this.valueSet = true;
return this;
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_15;
}
//
@Override
public OFBsnTlvFreeCount build() {
long value = this.valueSet ? this.value : DEFAULT_VALUE;
return new OFBsnTlvFreeCountVer15(
value
);
}
}
final static Reader READER = new Reader();
static class Reader implements OFMessageReader<OFBsnTlvFreeCount> {
@Override
public OFBsnTlvFreeCount readFrom(ByteBuf bb) throws OFParseError {
int start = bb.readerIndex();
// fixed value property type == 0xd7
short type = bb.readShort();
if(type != (short) 0xd7)
throw new OFParseError("Wrong type: Expected=0xd7(0xd7), got="+type);
int length = U16.f(bb.readShort());
if(length != 8)
throw new OFParseError("Wrong length: Expected=8(8), got="+length);
if(bb.readableBytes() + (bb.readerIndex() - start) < length) {
// Buffer does not have all data yet
bb.readerIndex(start);
return null;
}
if(logger.isTraceEnabled())
logger.trace("readFrom - length={}", length);
long value = U32.f(bb.readInt());
OFBsnTlvFreeCountVer15 bsnTlvFreeCountVer15 = new OFBsnTlvFreeCountVer15(
value
);
if(logger.isTraceEnabled())
logger.trace("readFrom - read={}", bsnTlvFreeCountVer15);
return bsnTlvFreeCountVer15;
}
}
public void putTo(PrimitiveSink sink) {
FUNNEL.funnel(this, sink);
}
final static OFBsnTlvFreeCountVer15Funnel FUNNEL = new OFBsnTlvFreeCountVer15Funnel();
static class OFBsnTlvFreeCountVer15Funnel implements Funnel<OFBsnTlvFreeCountVer15> {
private static final long serialVersionUID = 1L;
@Override
public void funnel(OFBsnTlvFreeCountVer15 message, PrimitiveSink sink) {
// fixed value property type = 0xd7
sink.putShort((short) 0xd7);
// fixed value property length = 8
sink.putShort((short) 0x8);
sink.putLong(message.value);
}
}
public void writeTo(ByteBuf bb) {
WRITER.write(bb, this);
}
final static Writer WRITER = new Writer();
static class Writer implements OFMessageWriter<OFBsnTlvFreeCountVer15> {
@Override
public void write(ByteBuf bb, OFBsnTlvFreeCountVer15 message) {
// fixed value property type = 0xd7
bb.writeShort((short) 0xd7);
// fixed value property length = 8
bb.writeShort((short) 0x8);
bb.writeInt(U32.t(message.value));
}
}
@Override
public String toString() {
StringBuilder b = new StringBuilder("OFBsnTlvFreeCountVer15(");
b.append("value=").append(value);
b.append(")");
return b.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
OFBsnTlvFreeCountVer15 other = (OFBsnTlvFreeCountVer15) obj;
if( value != other.value)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * (int) (value ^ (value >>> 32));
return result;
}
}
|
package com.a.b.a.a.d;
import com.a.b.a.a.a.GameParatemers;
import com.a.b.a.a.b.e.class_81;
import com.a.b.a.a.c.class_138;
import com.codeforces.commons.io.FileUtil;
import com.codeforces.commons.io.http.HttpMethod;
import com.codeforces.commons.io.http.HttpRequest;
import com.codeforces.commons.io.http.HttpResponse;
import com.codeforces.commons.io.http.HttpUtil;
import com.codeforces.commons.math.NumberUtil;
import com.codeforces.commons.process.ThreadUtil;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.log4j.Logger;
// $FF: renamed from: com.a.b.a.a.d.k
public class class_101 implements class_5 {
// $FF: renamed from: a org.apache.log4j.Logger
private static final Logger field_373 = Logger.getLogger(class_101.class);
// $FF: renamed from: b java.util.concurrent.ExecutorService
private final ExecutorService field_374 = Executors.newSingleThreadExecutor();
// $FF: renamed from: c java.util.concurrent.atomic.AtomicReference
private final AtomicReference field_375 = new AtomicReference();
// $FF: renamed from: d java.lang.String
private final String field_376;
// $FF: renamed from: e com.a.b.a.a.a.b
private final GameParatemers field_377;
// $FF: renamed from: f com.a.b.a.a.b.e.d
private final class_81 field_378;
// $FF: renamed from: g int
private int field_379;
// $FF: renamed from: h boolean
private boolean field_380;
// $FF: renamed from: i java.lang.StringBuilder
private final StringBuilder field_381 = new StringBuilder(NumberUtil.toInt(67108864L));
// $FF: renamed from: j java.lang.StringBuilder
private StringBuilder field_382 = new StringBuilder();
public class_101(String var1, GameParatemers var2) {
this.field_376 = var1;
this.field_377 = var2;
this.field_378 = new class_81(var2);
this.method_624("");
}
// $FF: renamed from: a (com.a.b.a.a.c.h) void
public void method_32(final class_138 var1) throws IOException {
this.method_628();
this.field_374.execute(new Runnable() {
public void run() {
if(class_101.this.field_375.get() == null) {
try {
String var1x = class_101.this.field_378.method_485(var1);
class_101.method_632(class_101.this);
class_101.this.field_381.append(var1x).append('\n');
class_101.this.field_382.append(var1x).append('\n');
if(class_101.method_623(var1)) {
class_101.this.method_625("", false);
}
} catch (Error | RuntimeException var2) {
class_101.this.method_627(var2);
}
}
}
});
}
public void close() throws IOException {
this.field_374.shutdown();
try {
if(!this.field_374.awaitTermination(5L, TimeUnit.MINUTES)) {
this.method_627(new IOException("Can\'t write game log file in the allotted time."));
}
} catch (InterruptedException var3) {
this.method_627(new IOException("Unexpectedly interrupted while writing game log file.", var3));
}
this.method_628();
this.method_625("", true);
FileUtil.executeIoOperation(new ThreadUtil.Operation() {
// $FF: renamed from: a () java.lang.Void
public Void method_621() throws Exception {
if(class_101.this.field_380) {
class_101.this.field_380 = false;
class_101.this.method_624("");
class_101.this.method_626(class_101.this.field_381.toString(), class_101.this.field_376, "", true);
if(class_101.this.field_380) {
throw new IOException("Can\'t save complete document \'" + class_101.this.field_376 + "\'.");
}
}
return null;
}
// $FF: synthetic method
public Object run() throws Throwable {
return this.method_621();
}
}, 4, 60000L, ThreadUtil.ExecutionStrategy.Type.LINEAR);
try {
this.field_380 = false;
this.method_624("-meta");
this.method_626((new GsonBuilder()).create().toJson((Object)(new class_101.class_205(InetAddress.getLocalHost().getHostName(), new Date(), this.field_379, this.field_377.method_80(), this.field_377.method_81(), null))), this.field_376, "-meta", true);
} catch (RuntimeException var2) {
;
}
}
// $FF: renamed from: c (com.a.b.a.a.c.h) boolean
private static boolean method_623(class_138 var0) {
return (var0.getTick() + 1) % 500 == 0;
}
// $FF: renamed from: a (java.lang.String) void
private void method_624(String var1) {
String var2 = this.field_376 + var1 + "/begin";
try {
HttpResponse var3 = HttpUtil.executePostRequestAndReturnResponse(20000, var2);
if(var3.hasIoException()) {
throw var3.getIoException();
}
if(var3.getCode() != 200) {
throw new IOException(String.format("Got unexpected %s from remote storage \'%s\' while creating new document.", new Object[]{var3, var2}));
}
} catch (IOException var4) {
field_373.error("Got I/O-exception while starting document \'" + var2 + "\'.", var4);
this.field_380 = true;
}
}
// $FF: renamed from: a (java.lang.String, boolean) void
private void method_625(String var1, boolean var2) {
this.method_626(this.field_382.toString(), this.field_376, var1, var2);
this.field_382 = new StringBuilder();
}
// $FF: renamed from: a (java.lang.String, java.lang.String, java.lang.String, boolean) void
private void method_626(String var1, String var2, String var3, boolean var4) {
if(!this.field_380) {
String var5 = var2 + var3 + '/' + (var4?"end":"append");
try {
method_629(var1, var5);
} catch (IOException var7) {
field_373.error("Got I/O-exception while appending document \'" + var5 + "\'.", var7);
this.field_380 = true;
}
}
}
// $FF: renamed from: a (java.lang.Throwable) void
private void method_627(Throwable var1) {
this.field_375.compareAndSet((Object)null, var1);
}
// $FF: renamed from: a () void
private void method_628() throws IOException {
Throwable var1 = (Throwable)this.field_375.get();
if(var1 != null) {
if(var1 instanceof IOException) {
throw (IOException)var1;
} else if(var1 instanceof RuntimeException) {
throw (RuntimeException)var1;
} else if(var1 instanceof Error) {
throw (Error)var1;
} else {
throw new IllegalStateException("Got unexpected async. throwable.", var1);
}
}
}
// $FF: renamed from: a (java.lang.String, java.lang.String) void
private static void method_629(String var0, String var1) throws IOException {
HttpResponse var2 = HttpRequest.create(var1, new Object[0]).setMethod(HttpMethod.POST).setBinaryEntity(var0.getBytes(StandardCharsets.UTF_8)).setGzip(true).setTimeoutMillis(20000).executeAndReturnResponse();
if(var2.getCode() != 200) {
throw new IOException(String.format("Got unexpected %s from remote storage \'%s\' while appending document.", new Object[]{var2, var1}));
}
}
// $FF: renamed from: c (com.a.b.a.a.d.k) int
// $FF: synthetic method
static int method_632(class_101 var0) {
return ++var0.field_379;
}
private static final class class_205 {
// $FF: renamed from: a java.lang.String
private final String field_101;
// $FF: renamed from: b java.util.Date
private final Date field_102;
// $FF: renamed from: c int
private final int field_103;
// $FF: renamed from: d int
private final int field_104;
// $FF: renamed from: e int
private final int field_105;
private class_205(String var1, Date var2, int var3, int var4, int var5) {
this.field_101 = var1;
this.field_102 = var2;
this.field_103 = var3;
this.field_104 = var4;
this.field_105 = var5;
}
// $FF: synthetic method
class_205(String var1, Date var2, int var3, int var4, int var5, Object var6) {
this(var1, var2, var3, var4, var5);
}
}
}
|
package com.example.paging;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import com.example.paging.entity.Commit;
import com.example.paging.repository.CommitRepository;
@Component
public class PagingDemoData implements ApplicationRunner {
private final CommitRepository commits;
public PagingDemoData(CommitRepository commits) {
this.commits = commits;
}
@Override
public void run(ApplicationArguments args) throws Exception {
commits.save(new Commit("1f1277c", "lombokでjacocoどーすんの問題への対応を試す"));
commits.save(new Commit("2f41e23", "JSESSIONIDと異なる名前を使う例"));
commits.save(new Commit("0db79a2", "Initial commit"));
commits.save(new Commit("56a379b", "typeormを試す"));
commits.save(new Commit("6f868f0", "リスナーをorm.xmlで定義する"));
commits.save(new Commit("6da35b4", "MappedSuperclassも試す"));
commits.save(new Commit("045edf0", "ロギングなんかを修正したり"));
commits.save(new Commit("f8bfd21", "orm.xmlでオーバーライドしてVersionを無視する例"));
commits.save(new Commit("0312b17", "Hibernateでトランザクションタイムアウトを設定する例"));
commits.save(new Commit("04e6d0c", "Mavenのプロファイルを学ぶ"));
commits.save(new Commit("3c433e6", "キーの削除、タイムアウトを検知する"));
commits.save(new Commit("8618885", "multi stage buildを学ぶ"));
commits.save(new Commit("08a67bc", "build-argを学ぶ"));
commits.save(new Commit("d8e6847", "リソースの制限を試す"));
commits.save(new Commit("4a6ce8e", "JavaでAWS Lambda"));
commits.save(new Commit("9b44232", "コンテナーを使う"));
commits.save(new Commit("a590ab8", "Inherited"));
commits.save(new Commit("9fa0e0a", "System.Logger"));
commits.save(new Commit("76bff7e", "AWS Lambda カスタムランタイムの小さなデモ"));
commits.save(new Commit("6b1d9dc", "babelでReact"));
commits.save(new Commit("d318e66", "Babelを試す"));
commits.save(new Commit("77d1e61", "Update"));
commits.save(new Commit("d4079ab", "Jestでテストする"));
commits.save(new Commit("a1753d9", "webpackを試す"));
commits.save(new Commit("6d952b3", "static initializerでスローされた例外をcatchする"));
commits.save(new Commit("7e4ece3", "高階関数"));
commits.save(new Commit("1f8e3d8", "JavaっぽくDIする"));
commits.save(new Commit("438eb72", "コンパイラの警告を抑制"));
commits.save(new Commit("70c535e", "ファイル分割"));
commits.save(new Commit("8318b8a", "Makefile"));
commits.save(new Commit("1ad86d3", "Karateを試す"));
commits.save(new Commit("65d47e4", "複数のバイナリを含める"));
commits.save(new Commit("dd43c96", "相互に呼び出す"));
commits.save(new Commit("a9d04ba", "にゃーん"));
commits.save(new Commit("c08c72f", "環境変数"));
commits.save(new Commit("ea18f76", "にゃーん"));
commits.save(new Commit("5e11c25", "Dockerでrustコードをビルド、実行"));
commits.save(new Commit("93e7885", "改善(になってるかな?)"));
commits.save(new Commit("8dc7978", "Vecと所有権を理解したい"));
commits.save(new Commit("1e6b129", "ぬーん"));
commits.save(new Commit("471159a", "panic!じゃなくてResultにした"));
commits.save(new Commit("b64bcea", "いろいろ"));
commits.save(new Commit("a3dae8c", "READMEを追加"));
commits.save(new Commit("be273fb", "main関数を実装"));
commits.save(new Commit("e21d034", "ASTの評価"));
commits.save(new Commit("36765f1", "パーサー"));
commits.save(new Commit("770f1d6", "足し算の字句解析器"));
commits.save(new Commit("d21607a", "リネーム"));
commits.save(new Commit("5749862", "非同期処理の後始末"));
commits.save(new Commit("7207e61", "コードを整理した"));
}
}
|
/*
* Copyright 2010-2019 James Pether Sörling
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* $Id$
* $HeadURL$
*/
package com.hack23.cia.web.impl.ui.application.views.user.politician.pagemode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Component;
import com.hack23.cia.model.internal.application.data.committee.impl.ViewRiksdagenVoteDataBallotPoliticianSummary;
import com.hack23.cia.model.internal.application.data.politician.impl.ViewRiksdagenPolitician;
import com.hack23.cia.web.impl.ui.application.views.common.chartfactory.api.GenericChartDataManager;
import com.hack23.cia.web.impl.ui.application.views.common.labelfactory.LabelFactory;
import com.hack23.cia.web.impl.ui.application.views.common.viewnames.PoliticianPageMode;
import com.hack23.cia.web.impl.ui.application.views.common.viewnames.UserViews;
import com.hack23.cia.web.impl.ui.application.views.pageclicklistener.PageItemPropertyClickListener;
import com.vaadin.ui.Layout;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.Panel;
import com.vaadin.ui.VerticalLayout;
/**
* The Class VotesHistoryPageModContentFactoryImpl.
*/
@Component
public final class PoliticianVotesHistoryPageModContentFactoryImpl extends AbstractPoliticianPageModContentFactoryImpl {
private static final String EMBEDDED_ID_BALLOT_ID = "embeddedId.ballotId";
private static final PageItemPropertyClickListener LISTENER = new PageItemPropertyClickListener(
UserViews.BALLOT_VIEW_NAME, EMBEDDED_ID_BALLOT_ID);
private static final String[] HIDE_COLUMNS = new String[] { "embeddedId", "partyNoWinner", "partyPercentageYes",
"partyPercentageNo", "partyPercentageAbsent", "partyPercentageAbstain", "percentageYes", "percentageNo",
"percentageAbsent", "percentageAbstain", "firstName", "lastName", "party", EMBEDDED_ID_BALLOT_ID,
"ballotType" };
private static final String[] COLUMN_ORDER = new String[] { "voteDate", "rm", "label", "embeddedId.concern",
"embeddedId.issue", "vote", "won", "partyWon", "rebel", "noWinner", "approved", "partyApproved",
"totalVotes", "partyTotalVotes", "yesVotes", "partyYesVotes", "noVotes", "partyNoVotes",
"partyAbstainVotes", "abstainVotes", "partyAbsentVotes", "absentVotes", "bornYear", "partyAvgBornYear",
"avgBornYear", "gender", "partyPercentageMale", "percentageMale", "ballotType", EMBEDDED_ID_BALLOT_ID };
private static final String[] NESTED_PROPERTIES = new String[] { EMBEDDED_ID_BALLOT_ID, "embeddedId.concern",
"embeddedId.issue" };
private static final String BALLOTS = "Ballots";
/**
* The view riksdagen vote data ballot politician summary chart data
* manager.
*/
@Autowired
private GenericChartDataManager<ViewRiksdagenVoteDataBallotPoliticianSummary> viewRiksdagenVoteDataBallotPoliticianSummaryChartDataManager;
/**
* Instantiates a new politician votes history page mod content factory
* impl.
*/
public PoliticianVotesHistoryPageModContentFactoryImpl() {
super();
}
@Override
public boolean matches(final String page, final String parameters) {
return NAME.equals(page) && parameters.contains(PoliticianPageMode.VOTEHISTORY.toString());
}
@Secured({ "ROLE_ANONYMOUS", "ROLE_USER", "ROLE_ADMIN" })
@Override
public Layout createContent(final String parameters, final MenuBar menuBar, final Panel panel) {
final VerticalLayout panelContent = createPanelContent();
final String pageId = getPageId(parameters);
final ViewRiksdagenPolitician viewRiksdagenPolitician = getItem(parameters);
getPoliticianMenuItemFactory().createPoliticianMenuBar(menuBar, pageId);
LabelFactory.createHeader2Label(panelContent, PoliticianPageMode.VOTEHISTORY.toString());
getGridFactory().createBasicBeanItemNestedPropertiesGrid(panelContent,
ViewRiksdagenVoteDataBallotPoliticianSummary.class,
viewRiksdagenVoteDataBallotPoliticianSummaryChartDataManager
.findByValue(viewRiksdagenPolitician.getPersonId()),
BALLOTS, NESTED_PROPERTIES, COLUMN_ORDER, HIDE_COLUMNS, LISTENER, EMBEDDED_ID_BALLOT_ID, null);
pageCompleted(parameters, panel, pageId, viewRiksdagenPolitician);
return panelContent;
}
}
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.batch.protocol.models;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
/**
* Defines values for TaskAddStatus.
*/
public enum TaskAddStatus {
/** Enum value success. */
SUCCESS("success"),
/** Enum value clientError. */
CLIENT_ERROR("clientError"),
/** Enum value serverError. */
SERVER_ERROR("serverError"),
/** Enum value unmapped. */
UNMAPPED("unmapped");
/** The actual serialized value for a TaskAddStatus instance. */
private String value;
TaskAddStatus(String value) {
this.value = value;
}
/**
* Parses a serialized value to a TaskAddStatus instance.
*
* @param value the serialized value to parse.
* @return the parsed TaskAddStatus object, or null if unable to parse.
*/
@JsonCreator
public static TaskAddStatus fromString(String value) {
TaskAddStatus[] items = TaskAddStatus.values();
for (TaskAddStatus item : items) {
if (item.toString().equalsIgnoreCase(value)) {
return item;
}
}
return null;
}
@JsonValue
@Override
public String toString() {
return this.value;
}
}
|
package com.letv.android.client.fragment;
import android.widget.BaseAdapter;
import com.letv.android.client.commonlib.fragement.LetvBaseFragment;
import com.letv.hackdex.VerifyLoad;
import com.letv.hotfixlib.HotFix;
public abstract class MyBaseFragment extends LetvBaseFragment {
public abstract BaseAdapter getAdapter();
public abstract void onViewPageScrollChangeEvent();
public MyBaseFragment() {
if (HotFix.PREVENT_VERIFY) {
System.out.println(VerifyLoad.class);
}
}
}
|
package com.bizzan.bitrade.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
/**
* @author Jammy
* @date 2020年12月29日
*/
@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {
/**
* 缓存管理器.
*
* @param redisTemplate
* @return
*/
@Bean
public CacheManager cacheManager(RedisTemplate<?, ?> redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
// 设置缓存默认过期时间30分钟(全局的)
cacheManager.setDefaultExpiration(1800);
return cacheManager;
}
/**
* RedisTemplate配置
* @param factory
* @return
*/
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
//定义key序列化方式
//RedisSerializer<String> redisSerializer = new StringRedisSerializer();//Long类型会出现异常信息;需要我们上面的自定义key生成策略,一般没必要
//定义value的序列化方式
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// template.setKeySerializer(redisSerializer);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
|
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2016 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.trans.steps.luciddbstreamingloader;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.util.Utils;
import org.pentaho.di.core.Props;
import org.pentaho.di.core.SQLStatement;
import org.pentaho.di.core.SourceToTargetMapping;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDialogInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.di.trans.steps.luciddbstreamingloader.LucidDBStreamingLoaderMeta;
import org.pentaho.di.ui.core.database.dialog.DatabaseExplorerDialog;
import org.pentaho.di.ui.core.database.dialog.SQLEditor;
import org.pentaho.di.ui.core.dialog.EnterMappingDialog;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.gui.GUIResource;
import org.pentaho.di.ui.core.widget.ColumnInfo;
import org.pentaho.di.ui.core.widget.StyledTextComp;
import org.pentaho.di.ui.core.widget.TableView;
import org.pentaho.di.ui.core.widget.TextVar;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
import org.pentaho.di.ui.trans.steps.tableinput.SQLValuesHighlight;
/**
* Description: Dialog class for the Farrago Streaming Loader step.
*
* @author Ray Zhang
* @since Jan-05-2010
*
*/
public class LucidDBStreamingLoaderDialog extends BaseStepDialog implements StepDialogInterface {
private static Class<?> PKG = LucidDBStreamingLoaderMeta.class;
private CCombo wConnection;
private Label wlSchema;
private TextVar wSchema;
private FormData fdlSchema, fdSchema;
private Label wlTable;
private Button wbTable;
private TextVar wTable;
private FormData fdlTable, fdbTable, fdTable;
private Label wlHost;
private TextVar wHost;
private FormData fdlHost, fdHost;
private Label wlPort;
private TextVar wPort;
private FormData fdlPort, fdPort;
private Label wlOperation;
private CCombo wOperation;
private FormData fdlOperation, fdOperation;
private CTabFolder wTabFolder;
private FormData fdTabFolder;
private CTabItem wKeysTab;
private CTabItem wFieldsTab;
private CTabItem wCustomTab;
private Composite wKeysComp;
private Composite wFieldsComp;
private Composite wCustomComp;
private FormData fdKeysComp;
private FormData fdFieldsComp;
private FormData fdCustomComp;
private Label wlKeysTb;
private TableView wKeysTb;
private FormData fdlKeysTb, fdKeysTb;
private Label wlFieldsTb;
private TableView wFieldsTb;
private FormData fdlFieldsTb, fdFieldsTb;
private Label wlCustomTb;
private StyledTextComp wCustomTb;
private FormData fdlCustomTb, fdCustomTb;
private Button wGetFieldsForKeys;
private FormData fdGetFieldsForKeys;
private Button wDoMappingForKeys;
private FormData fdDoMappingForKeys;
private Button wGetFieldsForFields;
private FormData fdGetFieldsForFields;
private Button wDoMappingForFields;
private FormData fdDoMappingForFields;
public LucidDBStreamingLoaderMeta input;
private Label lAutoCreateTable;
private FormData fdlAutoCreateTable, fdbAutoCreateTable;
public LucidDBStreamingLoaderDialog( Shell parent, Object in, TransMeta transMeta, String sname ) {
super( parent, (BaseStepMeta) in, transMeta, sname );
input = (LucidDBStreamingLoaderMeta) in;
}
public String open() {
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell( parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN );
props.setLook( shell );
setShellImage( shell, input );
ModifyListener lsMod = new ModifyListener() {
public void modifyText( ModifyEvent e ) {
input.setChanged();
}
};
changed = input.hasChanged();
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout( formLayout );
shell.setText( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.Shell.Title" ) );
int middle = props.getMiddlePct();
int margin = Const.MARGIN;
// Stepname line
wlStepname = new Label( shell, SWT.RIGHT );
wlStepname.setText( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.Stepname.Label" ) );
props.setLook( wlStepname );
fdlStepname = new FormData();
fdlStepname.left = new FormAttachment( 0, 0 );
fdlStepname.right = new FormAttachment( middle, -margin );
fdlStepname.top = new FormAttachment( 0, margin );
wlStepname.setLayoutData( fdlStepname );
wStepname = new Text( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
wStepname.setText( stepname );
props.setLook( wStepname );
wStepname.addModifyListener( lsMod );
fdStepname = new FormData();
fdStepname.left = new FormAttachment( middle, 0 );
fdStepname.top = new FormAttachment( 0, margin );
fdStepname.right = new FormAttachment( 100, 0 );
wStepname.setLayoutData( fdStepname );
// Connection line
wConnection = addConnectionLine( shell, wStepname, middle, margin );
if ( input.getDatabaseMeta() == null && transMeta.nrDatabases() == 1 ) {
wConnection.select( 0 );
}
wConnection.addModifyListener( lsMod );
// Schema line...
wlSchema = new Label( shell, SWT.RIGHT );
wlSchema.setText( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.TargetSchema.Label" ) );
props.setLook( wlSchema );
fdlSchema = new FormData();
fdlSchema.left = new FormAttachment( 0, 0 );
fdlSchema.right = new FormAttachment( middle, -margin );
fdlSchema.top = new FormAttachment( wConnection, margin * 2 );
wlSchema.setLayoutData( fdlSchema );
wSchema = new TextVar( transMeta, shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wSchema );
wSchema.addModifyListener( lsMod );
fdSchema = new FormData();
fdSchema.left = new FormAttachment( middle, 0 );
fdSchema.top = new FormAttachment( wConnection, margin * 2 );
fdSchema.right = new FormAttachment( 100, 0 );
wSchema.setLayoutData( fdSchema );
// Table line...
wlTable = new Label( shell, SWT.RIGHT );
wlTable.setText( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.TargetTable.Label" ) );
props.setLook( wlTable );
fdlTable = new FormData();
fdlTable.left = new FormAttachment( 0, 0 );
fdlTable.right = new FormAttachment( middle, -margin );
fdlTable.top = new FormAttachment( wSchema, margin );
wlTable.setLayoutData( fdlTable );
wbTable = new Button( shell, SWT.PUSH | SWT.CENTER );
props.setLook( wbTable );
wbTable.setText( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.Browse.Button" ) );
fdbTable = new FormData();
fdbTable.right = new FormAttachment( 100, 0 );
fdbTable.top = new FormAttachment( wSchema, margin );
wbTable.setLayoutData( fdbTable );
wTable = new TextVar( transMeta, shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wTable );
wTable.addModifyListener( lsMod );
fdTable = new FormData();
fdTable.left = new FormAttachment( middle, 0 );
fdTable.top = new FormAttachment( wSchema, margin );
fdTable.right = new FormAttachment( wbTable, -margin );
wTable.setLayoutData( fdTable );
// Auto create table check.
lAutoCreateTable = new Label( shell, SWT.RIGHT );
props.setLook( lAutoCreateTable );
fdlAutoCreateTable = new FormData();
fdlAutoCreateTable.left = new FormAttachment( 0, 0 );
fdlAutoCreateTable.top = new FormAttachment( wTable, margin );
fdlAutoCreateTable.right = new FormAttachment( middle, -margin );
lAutoCreateTable.setLayoutData( fdlAutoCreateTable );
fdbAutoCreateTable = new FormData();
fdbAutoCreateTable.left = new FormAttachment( lAutoCreateTable, 10 );
fdbAutoCreateTable.top = new FormAttachment( wTable, margin );
// Host
wlHost = new Label( shell, SWT.RIGHT );
wlHost.setText( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.Host.Label" ) );
props.setLook( wlHost );
fdlHost = new FormData();
fdlHost.left = new FormAttachment( 0, 0 );
fdlHost.top = new FormAttachment( lAutoCreateTable, margin );
fdlHost.right = new FormAttachment( middle, -margin );
wlHost.setLayoutData( fdlHost );
wHost = new TextVar( transMeta, shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wHost );
wHost.addModifyListener( lsMod );
fdHost = new FormData();
fdHost.left = new FormAttachment( middle, 0 );
fdHost.top = new FormAttachment( lAutoCreateTable, margin );
fdHost.right = new FormAttachment( 100, 0 );
wHost.setLayoutData( fdHost );
// Port line
wlPort = new Label( shell, SWT.RIGHT );
wlPort.setText( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.Port.Label" ) );
props.setLook( wlPort );
fdlPort = new FormData();
fdlPort.left = new FormAttachment( 0, 0 );
fdlPort.top = new FormAttachment( wHost, margin );
fdlPort.right = new FormAttachment( middle, -margin );
wlPort.setLayoutData( fdlPort );
wPort = new TextVar( transMeta, shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wPort );
wPort.addModifyListener( lsMod );
fdPort = new FormData();
fdPort.left = new FormAttachment( middle, 0 );
fdPort.top = new FormAttachment( wHost, margin );
fdPort.right = new FormAttachment( 100, 0 );
wPort.setLayoutData( fdPort );
// Operation line:
wlOperation = new Label( shell, SWT.RIGHT );
wlOperation.setText( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.Operation.Label" ) );
props.setLook( wlOperation );
fdlOperation = new FormData();
fdlOperation.left = new FormAttachment( 0, 0 );
fdlOperation.top = new FormAttachment( wPort, margin );
fdlOperation.right = new FormAttachment( middle, -margin );
wlOperation.setLayoutData( fdlOperation );
wOperation = new CCombo( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wOperation );
wOperation.addModifyListener( lsMod );
fdOperation = new FormData();
fdOperation.top = new FormAttachment( wPort, margin );
fdOperation.left = new FormAttachment( middle, 0 );
fdOperation.right = new FormAttachment( 100, 0 );
wOperation.setLayoutData( fdOperation );
final String[] operations =
new String[] {
BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.Operation.CCombo.Item1" ),
BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.Operation.CCombo.Item2" ),
BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.Operation.CCombo.Item3" ),
BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.Operation.CCombo.Item4" )
};
wOperation.setItems( operations );
wOperation.addSelectionListener( new SelectionListener() {
public void widgetDefaultSelected( SelectionEvent event ) {
widgetSelected( event );
}
public void widgetSelected( SelectionEvent event ) {
CCombo mycc = (CCombo) event.widget;
// MERGE
if ( operations[0].equals( mycc.getItem( mycc.getSelectionIndex() ) ) ) {
wKeysTb.table.removeAll();
wKeysTb.table.setItemCount( 1 );
wKeysTb.setRowNums();
wFieldsTb.table.removeAll();
wFieldsTb.table.setItemCount( 1 );
wFieldsTb.setRowNums();
wCustomTb.setText( "" );
wTabFolder.setSelection( wKeysTab );
wKeysTab.getControl().setEnabled( true );
wFieldsTab.getControl().setEnabled( true );
wCustomTab.getControl().setEnabled( false );
wFieldsTb.table.getColumn( 3 ).setWidth( 80 );
// INSERT
} else if ( operations[1].equals( mycc.getItem( mycc.getSelectionIndex() ) ) ) {
wKeysTb.table.removeAll();
wKeysTb.table.setItemCount( 1 );
wKeysTb.setRowNums();
wFieldsTb.table.removeAll();
wFieldsTb.table.setItemCount( 1 );
wFieldsTb.setRowNums();
wCustomTb.setText( "" );
wTabFolder.setSelection( wFieldsTab );
wKeysTab.getControl().setEnabled( false );
wFieldsTab.getControl().setEnabled( true );
wCustomTab.getControl().setEnabled( false );
wFieldsTb.table.getColumn( 3 ).setWidth( 0 );
// UPDATE
} else if ( operations[2].equals( mycc.getItem( mycc.getSelectionIndex() ) ) ) {
wKeysTb.table.removeAll();
wKeysTb.table.setItemCount( 1 );
wKeysTb.setRowNums();
wFieldsTb.table.removeAll();
wFieldsTb.table.setItemCount( 1 );
wFieldsTb.setRowNums();
wCustomTb.setText( "" );
wTabFolder.setSelection( wKeysTab );
wKeysTab.getControl().setEnabled( true );
wFieldsTab.getControl().setEnabled( true );
wCustomTab.getControl().setEnabled( false );
// grey out update field in Field TabelView
wFieldsTb.table.getColumn( 3 ).setWidth( 80 );
// CUSTOM
} else if ( operations[3].equals( mycc.getItem( mycc.getSelectionIndex() ) ) ) {
wKeysTb.table.removeAll();
wKeysTb.table.setItemCount( 1 );
wKeysTb.setRowNums();
wFieldsTb.table.removeAll();
wFieldsTb.table.setItemCount( 1 );
wFieldsTb.setRowNums();
wCustomTb.setText( "" );
wTabFolder.setSelection( wKeysTab );
wKeysTab.getControl().setEnabled( true );
wFieldsTab.getControl().setEnabled( true );
wCustomTab.getControl().setEnabled( true );
wFieldsTb.table.getColumn( 3 ).setWidth( 80 );
}
}
} );
// TabFolder
wTabFolder = new CTabFolder( shell, SWT.BORDER );
props.setLook( wTabFolder, Props.WIDGET_STYLE_TAB );
wTabFolder.setSimple( false );
fdTabFolder = new FormData();
fdTabFolder.left = new FormAttachment( 0, 0 );
fdTabFolder.top = new FormAttachment( wlOperation, margin );
fdTabFolder.right = new FormAttachment( 100, 0 );
fdTabFolder.bottom = new FormAttachment( 100, -50 );
wTabFolder.setLayoutData( fdTabFolder );
wKeysTab = new CTabItem( wTabFolder, SWT.NONE );
wKeysTab.setText( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.KeyTab.TabTitle" ) );
FormLayout fieldsLayout = new FormLayout();
fieldsLayout.marginWidth = Const.FORM_MARGIN;
fieldsLayout.marginHeight = Const.FORM_MARGIN;
// TabItem: Keys
wKeysComp = new Composite( wTabFolder, SWT.NONE );
wKeysComp.setLayout( fieldsLayout );
props.setLook( wKeysComp );
wlKeysTb = new Label( wKeysComp, SWT.LEFT );
wlKeysTb.setText( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.KeyTab.Label" ) );
fdlKeysTb = new FormData();
fdlKeysTb.left = new FormAttachment( 0, 0 );
fdlKeysTb.top = new FormAttachment( 0, 0 );
fdlKeysTb.right = new FormAttachment( 100, 0 );
wlKeysTb.setLayoutData( fdlKeysTb );
ColumnInfo[] colinf =
new ColumnInfo[] {
new ColumnInfo(
BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.Key.Column1" ),
ColumnInfo.COLUMN_TYPE_TEXT, false ),
new ColumnInfo(
BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.Key.Column2" ),
ColumnInfo.COLUMN_TYPE_TEXT, false ), };
wKeysTb = new TableView( transMeta, wKeysComp, SWT.FULL_SELECTION | SWT.MULTI, colinf, 0, lsMod, props );
fdKeysTb = new FormData();
fdKeysTb.left = new FormAttachment( 0, 0 );
fdKeysTb.top = new FormAttachment( wlKeysTb, margin );
fdKeysTb.right = new FormAttachment( 100, 0 );
fdKeysTb.bottom = new FormAttachment( 95, -margin );
wKeysTb.setLayoutData( fdKeysTb );
fdKeysComp = new FormData();
fdKeysComp.left = new FormAttachment( 0, 0 );
fdKeysComp.top = new FormAttachment( 0, 0 );
fdKeysComp.right = new FormAttachment( 100, 0 );
fdKeysComp.bottom = new FormAttachment( 100, 0 );
wKeysComp.setLayoutData( fdKeysComp );
wGetFieldsForKeys = new Button( wKeysComp, SWT.PUSH );
wGetFieldsForKeys.setText( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.GetFields.Label" ) );
fdGetFieldsForKeys = new FormData();
fdGetFieldsForKeys.top = new FormAttachment( wKeysTb, margin );
fdGetFieldsForKeys.left = new FormAttachment( 0, margin );
wGetFieldsForKeys.setLayoutData( fdGetFieldsForKeys );
wGetFieldsForKeys.addListener( SWT.Selection, new Listener() {
public void handleEvent( Event event ) {
getFields( wKeysTab.getText() );
}
} );
wDoMappingForKeys = new Button( wKeysComp, SWT.PUSH );
wDoMappingForKeys.setText( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.EditMapping.Label" ) );
fdDoMappingForKeys = new FormData();
fdDoMappingForKeys.top = new FormAttachment( wKeysTb, margin );
fdDoMappingForKeys.left = new FormAttachment( wGetFieldsForKeys, margin );
wDoMappingForKeys.setLayoutData( fdDoMappingForKeys );
wDoMappingForKeys.addListener( SWT.Selection, new Listener() {
public void handleEvent( Event event ) {
generateMappings( wKeysTab.getText() );
}
} );
wKeysComp.layout();
wKeysTab.setControl( wKeysComp );
// TabItem: Fields
wFieldsTab = new CTabItem( wTabFolder, SWT.NONE );
wFieldsTab.setText( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.FieldsTab.TabTitle" ) );
wFieldsComp = new Composite( wTabFolder, SWT.NONE );
wFieldsComp.setLayout( fieldsLayout );
props.setLook( wFieldsComp );
wlFieldsTb = new Label( wFieldsComp, SWT.LEFT );
wlFieldsTb.setText( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.FieldTab.Label" ) );
fdlFieldsTb = new FormData();
fdlFieldsTb.left = new FormAttachment( 0, 0 );
fdlFieldsTb.top = new FormAttachment( 0, 0 );
fdlFieldsTb.right = new FormAttachment( 100, 0 );
wlFieldsTb.setLayoutData( fdlFieldsTb );
ColumnInfo[] colinf1 =
new ColumnInfo[] {
new ColumnInfo(
BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.Field.Column1" ),
ColumnInfo.COLUMN_TYPE_TEXT, false ),
new ColumnInfo(
BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.Field.Column2" ),
ColumnInfo.COLUMN_TYPE_TEXT, false ),
new ColumnInfo(
BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.Field.Column3" ),
ColumnInfo.COLUMN_TYPE_CCOMBO, new String[] { "Y", "N", }, true )
};
wFieldsTb = new TableView( transMeta, wFieldsComp, SWT.FULL_SELECTION | SWT.MULTI, colinf1, 0, lsMod, props );
fdFieldsTb = new FormData();
fdFieldsTb.left = new FormAttachment( 0, 0 );
fdFieldsTb.top = new FormAttachment( wlFieldsTb, margin );
fdFieldsTb.right = new FormAttachment( 100, 0 );
fdFieldsTb.bottom = new FormAttachment( 95, -margin );
wFieldsTb.setLayoutData( fdFieldsTb );
fdFieldsComp = new FormData();
fdFieldsComp.left = new FormAttachment( 0, 0 );
fdFieldsComp.top = new FormAttachment( 0, 0 );
fdFieldsComp.right = new FormAttachment( 100, 0 );
fdFieldsComp.bottom = new FormAttachment( 100, 0 );
wFieldsComp.setLayoutData( fdFieldsComp );
wGetFieldsForFields = new Button( wFieldsComp, SWT.PUSH );
wGetFieldsForFields.setText( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.GetFields.Label" ) );
fdGetFieldsForFields = new FormData();
fdGetFieldsForFields.top = new FormAttachment( wFieldsTb, margin );
fdGetFieldsForFields.left = new FormAttachment( 0, margin );
wGetFieldsForFields.setLayoutData( fdGetFieldsForFields );
wGetFieldsForFields.addListener( SWT.Selection, new Listener() {
public void handleEvent( Event event ) {
getFields( wFieldsTab.getText() );
}
} );
wDoMappingForFields = new Button( wFieldsComp, SWT.PUSH );
wDoMappingForFields.setText( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.EditMapping.Label" ) );
fdDoMappingForFields = new FormData();
fdDoMappingForFields.top = new FormAttachment( wFieldsTb, margin );
fdDoMappingForFields.left = new FormAttachment( wGetFieldsForFields, margin );
wDoMappingForFields.setLayoutData( fdDoMappingForFields );
wDoMappingForFields.addListener( SWT.Selection, new Listener() {
public void handleEvent( Event event ) {
generateMappings( wFieldsTab.getText() );
}
} );
wFieldsComp.layout();
wFieldsTab.setControl( wFieldsComp );
// TabItem: Custom disable Custom tab
wCustomTab = new CTabItem( wTabFolder, SWT.NONE );
wCustomTab.setText( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.CustomTab.TabTitle" ) );
wCustomComp = new Composite( wTabFolder, SWT.NONE );
wCustomComp.setLayout( fieldsLayout );
props.setLook( wCustomComp );
wlCustomTb = new Label( wCustomComp, SWT.LEFT );
wlCustomTb.setText( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.CustomTab.Label" ) );
fdlCustomTb = new FormData();
fdlCustomTb.left = new FormAttachment( 0, 0 );
fdlCustomTb.top = new FormAttachment( 0, 0 );
fdlCustomTb.right = new FormAttachment( 100, 0 );
wlCustomTb.setLayoutData( fdlCustomTb );
wCustomTb =
new StyledTextComp( transMeta, wCustomComp, SWT.MULTI
| SWT.LEFT | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL, "" );
props.setLook( wCustomTb, Props.WIDGET_STYLE_FIXED );
wCustomTb.addModifyListener( lsMod );
fdCustomTb = new FormData();
fdCustomTb.left = new FormAttachment( 0, 0 );
fdCustomTb.top = new FormAttachment( wlCustomTb, margin );
fdCustomTb.right = new FormAttachment( 100, -2 * margin );
fdCustomTb.bottom = new FormAttachment( 100, -margin );
wCustomTb.setLayoutData( fdCustomTb );
// Text Higlighting
SQLValuesHighlight lineStyler = new SQLValuesHighlight();
wCustomTb.addLineStyleListener( lineStyler );
fdCustomComp = new FormData();
fdCustomComp.left = new FormAttachment( 0, 0 );
fdCustomComp.top = new FormAttachment( 0, 0 );
fdCustomComp.right = new FormAttachment( 100, 0 );
fdCustomComp.bottom = new FormAttachment( 100, 0 );
wCustomComp.setLayoutData( fdCustomComp );
wCustomComp.layout();
wCustomTab.setControl( wCustomComp );
// THE BUTTONS
wOK = new Button( shell, SWT.PUSH );
wOK.setText( BaseMessages.getString( "System.Button.OK" ) );
wCancel = new Button( shell, SWT.PUSH );
wCancel.setText( BaseMessages.getString( "System.Button.Cancel" ) );
wSQL = new Button( shell, SWT.PUSH );
wSQL.setText( BaseMessages.getString( "System.Button.SQL" ) );
setButtonPositions( new Button[] { wOK, wSQL, wCancel, }, margin, null );
// Add listeners
lsOK = new Listener() {
public void handleEvent( Event e ) {
ok();
}
};
lsSQL = new Listener() {
public void handleEvent( Event e ) {
create();
}
};
lsCancel = new Listener() {
public void handleEvent( Event e ) {
cancel();
}
};
wOK.addListener( SWT.Selection, lsOK );
wSQL.addListener( SWT.Selection, lsSQL );
wCancel.addListener( SWT.Selection, lsCancel );
lsDef = new SelectionAdapter() {
public void widgetDefaultSelected( SelectionEvent e ) {
ok();
}
};
wStepname.addSelectionListener( lsDef );
wSchema.addSelectionListener( lsDef );
wTable.addSelectionListener( lsDef );
wPort.addSelectionListener( lsDef );
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() {
public void shellClosed( ShellEvent e ) {
cancel();
}
} );
wbTable.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent e ) {
getTableName();
}
} );
// Set the shell size, based upon previous time...
setSize();
getData();
input.setChanged( changed );
shell.open();
while ( !shell.isDisposed() ) {
if ( !display.readAndDispatch() ) {
display.sleep();
}
}
return stepname;
}
/**
* Copy information from the meta-data input to the dialog fields.
*/
public void getData() {
logDebug( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.Log.GettingKeyInfo" ) );
if ( input.getDatabaseMeta() != null ) {
wConnection.setText( input.getDatabaseMeta().getName() );
} else {
if ( transMeta.nrDatabases() == 1 ) {
wConnection.setText( transMeta.getDatabase( 0 ).getName() );
}
}
if ( input.getSchemaName() != null ) {
wSchema.setText( input.getSchemaName() );
}
if ( input.getTableName() != null ) {
wTable.setText( input.getTableName() );
}
if ( input.getHost() != null ) {
wHost.setText( "" + input.getHost() );
}
if ( input.getPort() != null ) {
wPort.setText( "" + input.getPort() );
}
if ( input.getOperation() != null ) {
wOperation.select( wOperation.indexOf( input.getOperation() ) );
if ( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.Operation.CCombo.Item2" ).equals(
input.getOperation() ) ) {
wTabFolder.setSelection( 1 );
} else {
wTabFolder.setSelection( 0 );
}
}
if ( input.getCustom_sql() != null ) {
wCustomTb.setText( input.getCustom_sql() );
}
if ( input.getFieldTableForKeys() != null ) {
int nrKeyMapping = input.getFieldTableForKeys().length;
wKeysTb.table.setItemCount( nrKeyMapping );
for ( int i = 0; i < nrKeyMapping; i++ ) {
TableItem item = wKeysTb.table.getItem( i );
if ( input.getFieldTableForKeys()[i] != null ) {
item.setText( 1, input.getFieldTableForKeys()[i] );
}
if ( input.getFieldStreamForKeys()[i] != null ) {
item.setText( 2, input.getFieldStreamForKeys()[i] );
}
}
}
wKeysTb.setRowNums();
wKeysTb.optWidth( true );
if ( input.getFieldTableForFields() != null ) {
int nrFieldMapping = input.getFieldTableForFields().length;
wFieldsTb.table.setItemCount( nrFieldMapping );
for ( int i = 0; i < nrFieldMapping; i++ ) {
TableItem item = wFieldsTb.table.getItem( i );
if ( input.getFieldTableForFields()[i] != null ) {
item.setText( 1, input.getFieldTableForFields()[i] );
}
if ( input.getFieldStreamForFields()[i] != null ) {
item.setText( 2, input.getFieldStreamForFields()[i] );
}
if ( input.getInsOrUptFlag() != null ) {
item.setText( 3, input.getInsOrUptFlag()[i] ? "Y" : "N" );
} else {
item.setText( 3, "N" );
}
}
}
wFieldsTb.setRowNums();
wFieldsTb.optWidth( true );
if ( input.getTabIsEnable().length != 0 ) {
wKeysTab.getControl().setEnabled( input.getTabIsEnable()[0] );
wFieldsTab.getControl().setEnabled( input.getTabIsEnable()[1] );
wCustomTab.getControl().setEnabled( input.getTabIsEnable()[2] );
}
int fieldWidth = wFieldsTb.table.getColumn( 3 ).getWidth();
if ( input.getOperation() != null
&& "INSERT".equalsIgnoreCase( wOperation.getItem( wOperation.getSelectionIndex() ) ) ) {
wFieldsTb.table.getColumn( 3 ).setWidth( 0 );
} else {
wFieldsTb.table.getColumn( 3 ).setWidth( fieldWidth );
}
wStepname.selectAll();
wStepname.setFocus();
}
/**
* Reads in the fields from the previous steps and from the ONE next step and opens an EnterMappingDialog with this
* information. After the user did the mapping, those information is put into the Select/Rename table.
*/
private void generateMappings( String tabName ) {
TableView myTb;
boolean flag = false;
if ( tabName.equals( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.KeyTab.TabTitle" ) ) ) {
myTb = wKeysTb;
} else if ( tabName.equals( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.FieldsTab.TabTitle" ) ) ) {
myTb = wFieldsTb;
// Hidden Update Field when select operation INSERT
if ( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.Operation.CCombo.Item2" ).equalsIgnoreCase(
wOperation.getItem( wOperation.getSelectionIndex() ) ) ) {
flag = true;
}
} else {
return;
}
// Determine the source and target fields...
//
RowMetaInterface sourceFields;
RowMetaInterface targetFields;
try {
sourceFields = transMeta.getPrevStepFields( stepMeta );
} catch ( KettleException e ) {
new ErrorDialog( shell,
BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.DoMapping.UnableToFindSourceFields.Title" ),
BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.DoMapping.UnableToFindSourceFields.Message" ), e );
return;
}
// refresh data
input.setDatabaseMeta( transMeta.findDatabase( wConnection.getText() ) );
input.setTableName( transMeta.environmentSubstitute( wTable.getText() ) );
StepMetaInterface stepMetaInterface = stepMeta.getStepMetaInterface();
try {
targetFields = stepMetaInterface.getRequiredFields( transMeta );
} catch ( KettleException e ) {
new ErrorDialog( shell,
BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.DoMapping.UnableToFindTargetFields.Title" ),
BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.DoMapping.UnableToFindTargetFields.Message" ), e );
return;
}
String[] inputNames = new String[sourceFields.size()];
for ( int i = 0; i < sourceFields.size(); i++ ) {
ValueMetaInterface value = sourceFields.getValueMeta( i );
inputNames[i] = value.getName() + EnterMappingDialog.STRING_ORIGIN_SEPARATOR + value.getOrigin() + ")";
}
// Create the existing mapping list...
//
List<SourceToTargetMapping> mappings = new ArrayList<SourceToTargetMapping>();
StringBuffer missingSourceFields = new StringBuffer();
StringBuffer missingTargetFields = new StringBuffer();
// show a confirm dialog if some missing field was found
//
if ( missingSourceFields.length() > 0 || missingTargetFields.length() > 0 ) {
String message = "";
if ( missingSourceFields.length() > 0 ) {
message +=
BaseMessages.getString(
PKG, "LucidDBStreamingLoaderDialog.DoMapping.SomeSourceFieldsNotFound", missingSourceFields
.toString() )
+ Const.CR;
}
if ( missingTargetFields.length() > 0 ) {
message +=
BaseMessages.getString(
PKG, "LucidDBStreamingLoaderDialog.DoMapping.SomeTargetFieldsNotFound", missingSourceFields
.toString() )
+ Const.CR;
}
message += Const.CR;
message +=
BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.DoMapping.SomeFieldsNotFoundContinue" )
+ Const.CR;
MessageDialog.setDefaultImage( GUIResource.getInstance().getImageSpoon() );
boolean goOn =
MessageDialog.openConfirm( shell, BaseMessages.getString(
PKG, "LucidDBStreamingLoaderDialog.DoMapping.SomeFieldsNotFoundTitle" ), message );
if ( !goOn ) {
return;
}
}
EnterMappingDialog d =
new EnterMappingDialog(
LucidDBStreamingLoaderDialog.this.shell, sourceFields.getFieldNames(), targetFields.getFieldNames(),
mappings );
mappings = d.open();
// mappings == null if the user pressed cancel
//
if ( mappings != null ) {
// Clear and re-populate!
//
myTb.table.removeAll();
myTb.table.setItemCount( mappings.size() );
for ( int i = 0; i < mappings.size(); i++ ) {
SourceToTargetMapping mapping = mappings.get( i );
TableItem item = myTb.table.getItem( i );
item.setText( 2, sourceFields.getValueMeta( mapping.getSourcePosition() ).getName() );
item.setText( 1, targetFields.getValueMeta( mapping.getTargetPosition() ).getName() );
}
myTb.setRowNums();
myTb.optWidth( true );
// Hidden Update Field when select INSERT.
int width = myTb.table.getColumn( 3 ).getWidth();
if ( flag ) {
myTb.table.getColumn( 3 ).setWidth( 0 );
} else {
myTb.table.getColumn( 3 ).setWidth( width );
}
}
}
private void cancel() {
stepname = null;
input.setChanged( changed );
dispose();
}
private void getInfo( LucidDBStreamingLoaderMeta inf ) {
inf.setDatabaseMeta( transMeta.findDatabase( wConnection.getText() ) );
inf.setSchemaName( wSchema.getText() );
inf.setTableName( wTable.getText() );
inf.setHost( wHost.getText() );
inf.setPort( wPort.getText() );
inf.setOperation( wOperation.getItem( wOperation.getSelectionIndex() ) );
int nrKeyMapping = wKeysTb.nrNonEmpty();
int nrFieldMappping = wFieldsTb.nrNonEmpty();
inf.allocate( nrKeyMapping, nrFieldMappping, 3 );
//CHECKSTYLE:Indentation:OFF
for ( int i = 0; i < nrKeyMapping; i++ ) {
TableItem item = wKeysTb.getNonEmpty( i );
inf.getFieldTableForKeys()[i] = item.getText( 1 );
inf.getFieldStreamForKeys()[i] = item.getText( 2 );
}
//CHECKSTYLE:Indentation:OFF
for ( int i = 0; i < nrFieldMappping; i++ ) {
TableItem item = wFieldsTb.getNonEmpty( i );
inf.getFieldTableForFields()[i] = item.getText( 1 );
inf.getFieldStreamForFields()[i] = item.getText( 2 );
inf.getInsOrUptFlag()[i] = "Y".equalsIgnoreCase( item.getText( 3 ) );
}
//CHECKSTYLE:Indentation:OFF
inf.getTabIsEnable()[0] = wKeysTab.getControl().getEnabled();
inf.getTabIsEnable()[1] = wFieldsTab.getControl().getEnabled();
inf.getTabIsEnable()[2] = wCustomTab.getControl().getEnabled();
if ( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.Operation.CCombo.Item4" ).equals(
inf.getOperation() ) ) {
inf.setCustom_sql( wCustomTb.getText() );
}
stepname = wStepname.getText(); // return value
}
/**
* Description: When click button called get Field, return all fields in table
*
* @param tabName
*/
private void getFields( String tabName ) {
TableView myTb;
boolean flag = false; // disable update field when select insert
// operation.
if ( tabName.equals( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.KeyTab.TabTitle" ) ) ) {
myTb = wKeysTb;
} else if ( tabName.equals( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.FieldsTab.TabTitle" ) ) ) {
myTb = wFieldsTb;
if ( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.Operation.CCombo.Item2" ).equalsIgnoreCase(
wOperation.getItem( wOperation.getSelectionIndex() ) ) ) {
flag = true;
}
} else {
return;
}
RowMetaInterface streamMeta;
try {
streamMeta = transMeta.getPrevStepFields( stepMeta );
String[] fieldNamesOfStream = streamMeta.getFieldNames();
input.setSchemaName( wSchema.getText() );
input.setTableName( wTable.getText() );
input.setDatabaseMeta( transMeta.findDatabase( wConnection.getText() ) );
StepMetaInterface stepMetaInterface = stepMeta.getStepMetaInterface();
RowMetaInterface tblMeta = null;
String[] fieldsNamesOfTbl = null;
try {
tblMeta = stepMetaInterface.getRequiredFields( transMeta );
fieldsNamesOfTbl = tblMeta.getFieldNames();
} catch ( KettleException ke ) {
// Ignore errors
}
int count = 0;
if ( fieldsNamesOfTbl == null ) {
count = fieldNamesOfStream.length;
myTb.table.setItemCount( count );
for ( int i = 0; i < count; i++ ) {
TableItem item = myTb.table.getItem( i );
item.setText( 1, fieldNamesOfStream[i] );
item.setText( 2, fieldNamesOfStream[i] );
}
} else {
count =
( ( fieldNamesOfStream.length >= fieldsNamesOfTbl.length )
? fieldNamesOfStream.length : fieldsNamesOfTbl.length );
myTb.table.setItemCount( count );
for ( int i = 0; i < count; i++ ) {
TableItem item = myTb.table.getItem( i );
if ( i < ( fieldsNamesOfTbl.length ) ) {
if ( fieldsNamesOfTbl[i] != null ) {
item.setText( 1, fieldsNamesOfTbl[i] );
}
}
if ( i < fieldNamesOfStream.length ) {
if ( fieldNamesOfStream[i] != null ) {
item.setText( 2, fieldNamesOfStream[i] );
}
}
}
}
myTb.setRowNums();
myTb.optWidth( true );
if ( flag ) {
myTb.table.getColumn( 3 ).setWidth( 0 );
System.out.println( myTb.table.getColumn( 3 ).getWidth() );
}
} catch ( KettleStepException e ) {
// Ignore errors
}
}
private void ok() {
if ( Utils.isEmpty( wStepname.getText() ) ) {
return;
}
// Get the information for the dialog into the input structure.
getInfo( input );
if ( input.getDatabaseMeta() == null ) {
MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_ERROR );
mb
.setMessage( BaseMessages
.getString( PKG, "LucidDBStreamingLoaderDialog.InvalidConnection.DialogMessage" ) );
mb.setText( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.InvalidConnection.DialogTitle" ) );
mb.open();
}
dispose();
}
private void getTableName() {
DatabaseMeta inf = null;
// New class: SelectTableDialog
int connr = wConnection.getSelectionIndex();
if ( connr >= 0 ) {
inf = transMeta.getDatabase( connr );
}
if ( inf != null ) {
logDebug( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.Log.LookingAtConnection" )
+ inf.toString() );
DatabaseExplorerDialog std = new DatabaseExplorerDialog( shell, SWT.NONE, inf, transMeta.getDatabases() );
std.setSelectedSchemaAndTable( wSchema.getText(), wTable.getText() );
if ( std.open() ) {
wSchema.setText( Const.NVL( std.getSchemaName(), "" ) );
wTable.setText( Const.NVL( std.getTableName(), "" ) );
}
} else {
MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_ERROR );
mb
.setMessage( BaseMessages
.getString( PKG, "LucidDBStreamingLoaderDialog.InvalidConnection.DialogMessage" ) );
mb.setText( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.InvalidConnection.DialogTitle" ) );
mb.open();
}
}
// Generate code for create table...
// Conversions done by Database
private void create() {
try {
LucidDBStreamingLoaderMeta info = new LucidDBStreamingLoaderMeta();
getInfo( info );
String name = stepname; // new name might not yet be linked to other steps!
StepMeta stepMeta =
new StepMeta( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.StepMeta.Title" ), name, info );
RowMetaInterface prev = transMeta.getPrevStepFields( stepname );
SQLStatement sql = info.getSQLStatements( transMeta, stepMeta, prev, repository, metaStore );
if ( !sql.hasError() ) {
if ( sql.hasSQL() ) {
SQLEditor sqledit =
new SQLEditor( transMeta, shell, SWT.NONE, info.getDatabaseMeta(), transMeta.getDbCache(), sql
.getSQL() );
sqledit.open();
} else {
MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_INFORMATION );
mb.setMessage( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.NoSQLNeeds.DialogMessage" ) );
mb.setText( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.NoSQLNeeds.DialogTitle" ) );
mb.open();
}
} else {
MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage( sql.getError() );
mb.setText( BaseMessages.getString( PKG, "LucidDBStreamingLoaderDialog.SQLError.DialogTitle" ) );
mb.open();
}
} catch ( KettleException ke ) {
new ErrorDialog( shell, BaseMessages.getString(
PKG, "LucidDBStreamingLoaderDialog.CouldNotBuildSQL.DialogTitle" ), BaseMessages.getString(
PKG, "LucidDBStreamingLoaderDialog.CouldNotBuildSQL.DialogMessage" ), ke );
}
}
}
|
package org.infinispan.persistence.spi;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import org.infinispan.commons.api.Lifecycle;
import org.infinispan.marshall.core.MarshalledEntry;
import org.reactivestreams.Publisher;
import io.reactivex.Flowable;
import net.jcip.annotations.ThreadSafe;
/**
* Allows persisting data to an external storage, as opposed to the {@link CacheLoader}.
*
* @author Mircea Markus
* @since 6.0
*/
@ThreadSafe
public interface CacheWriter<K, V> extends Lifecycle {
/**
* Used to initialize a cache loader. Typically invoked by the {@link org.infinispan.persistence.manager.PersistenceManager}
* when setting up cache loaders.
*
* @throws PersistenceException in case of an error, e.g. communicating with the external storage
*/
void init(InitializationContext ctx);
/**
* Persists the entry to the storage.
*
* @throws PersistenceException in case of an error, e.g. communicating with the external storage
* @see MarshallableEntry
*/
default void write(MarshallableEntry<? extends K, ? extends V> entry) {
write(MarshalledEntry.wrap(entry));
}
/**
* @deprecated since 10.0, use {@link #write(MarshallableEntry)} instead.
*/
@Deprecated
default void write(MarshalledEntry<? extends K, ? extends V> entry) {
// no-op
}
/**
* @return true if the entry existed in the persistent store and it was deleted.
* @throws PersistenceException in case of an error, e.g. communicating with the external storage
*/
boolean delete(Object key);
/**
* Persist all provided entries to the store in chunks, with the size of each chunk determined by the store
* implementation. If chunking is not supported by the underlying store, then entries are written to the store
* individually via {@link #write(MarshallableEntry)}.
*
* @param entries an Iterable of MarshalledEntry to be written to the store.
* @throws NullPointerException if entries is null.
* @deprecated since 10.0, use {@link #bulkUpdate(Publisher)} instead.
*/
@Deprecated
default void writeBatch(Iterable<MarshalledEntry<? extends K, ? extends V>> entries) {
entries.forEach(e -> write((MarshallableEntry<? extends K, ? extends V>) e));
}
/**
* Persist all provided entries to the store in chunks, with the size of each chunk determined by the store
* implementation. If chunking is not supported by the underlying store, then entries are written to the store
* individually via {@link #write(MarshallableEntry)}.
*
* @param publisher a {@link Publisher} of {@link MarshallableEntry} instances
* @throws NullPointerException if the publisher is null.
*/
@SuppressWarnings("unchecked")
default CompletionStage<Void> bulkUpdate(Publisher<MarshallableEntry<? extends K, ? extends V>> publisher) {
CompletableFuture<Void> future = new CompletableFuture<>();
try {
writeBatch(
Flowable.fromPublisher((Publisher) publisher)
.map(e -> MarshalledEntry.wrap((MarshallableEntry) e))
.blockingIterable()
);
future.complete(null);
} catch (Throwable t) {
future.completeExceptionally(t);
}
return future;
}
/**
* Remove all provided keys from the store in a single batch operation. If this is not supported by the
* underlying store, then keys are removed from the store individually via {@link #delete(Object)}.
*
* @param keys an Iterable of entry Keys to be removed from the store.
* @throws NullPointerException if keys is null.
*/
default void deleteBatch(Iterable<Object> keys) {
keys.forEach(this::delete);
}
/**
* @return true if the writer can be connected to, otherwise false
*/
default boolean isAvailable() {
return true;
}
}
|
/*
* Copyright (c) 2018-present, Jim Kynde Meyer
* All rights reserved.
* <p>
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.intellij.lang.jsgraphql.psi;
import com.intellij.lang.jsgraphql.GraphQLLanguage;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
public class GraphQLTokenType extends IElementType {
public GraphQLTokenType(@NotNull @NonNls String debugName) {
super(debugName, GraphQLLanguage.INSTANCE);
}
}
|
package com.synuwxy.sample.redis.common;
/**
* @author wxy
* create by 2019.08.17
* <p>
* desc:
* 默认的返回码模板
*/
public class ResultCode {
// 成功
public static String SUCCESS = "0";
// 失败
public static String ERROR = "-1";
}
|
package Model.Statements;
import Model.ADT.IMyStack;
import Model.ADT.MyStack;
import Model.PrgState;
public class ForkStmt implements IStmt{
private IStmt stmt;
public ForkStmt(IStmt stmt){this.stmt = stmt;}
@Override
public PrgState execute(PrgState state){
PrgState forkProgram = new PrgState(state.getId()*10, new MyStack<>(), state.getSymTable().clone(), state.getOut(),state.getFileTable(), state.getHeap(), this.stmt);
forkProgram.getStk().push(this.stmt);
return forkProgram;
}
@Override
public String toString() {
return "fork(" + this.stmt.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.catalina.connector;
import java.io.BufferedReader;
import java.io.IOException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import javax.servlet.AsyncContext;
import javax.servlet.DispatcherType;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import org.apache.catalina.Globals;
import org.apache.catalina.security.SecurityUtil;
import org.apache.coyote.http11.upgrade.UpgradeInbound;
import org.apache.coyote.http11.upgrade.servlet31.HttpUpgradeHandler;
import org.apache.tomcat.util.res.StringManager;
/**
* Facade class that wraps a Coyote request object.
* All methods are delegated to the wrapped request.
*
* @author Craig R. McClanahan
* @author Remy Maucherat
* @author Jean-Francois Arcand
*/
@SuppressWarnings("deprecation")
public class RequestFacade implements HttpServletRequest {
// ----------------------------------------------------------- DoPrivileged
private final class GetAttributePrivilegedAction implements PrivilegedAction<Enumeration<String>> {
@Override
public Enumeration<String> run() {
return request.getAttributeNames();
}
}
private final class GetParameterMapPrivilegedAction
implements PrivilegedAction<Map<String,String[]>> {
@Override
public Map<String,String[]> run() {
return request.getParameterMap();
}
}
private final class GetRequestDispatcherPrivilegedAction implements PrivilegedAction<RequestDispatcher> {
private final String path;
public GetRequestDispatcherPrivilegedAction(String path){
this.path = path;
}
@Override
public RequestDispatcher run() {
return request.getRequestDispatcher(path);
}
}
private final class GetParameterPrivilegedAction implements PrivilegedAction<String> {
public String name;
public GetParameterPrivilegedAction(String name){
this.name = name;
}
@Override
public String run() {
return request.getParameter(name);
}
}
private final class GetParameterNamesPrivilegedAction
implements PrivilegedAction<Enumeration<String>> {
@Override
public Enumeration<String> run() {
return request.getParameterNames();
}
}
private final class GetParameterValuePrivilegedAction
implements PrivilegedAction<String[]> {
public String name;
public GetParameterValuePrivilegedAction(String name){
this.name = name;
}
@Override
public String[] run() {
return request.getParameterValues(name);
}
}
private final class GetCookiesPrivilegedAction
implements PrivilegedAction<Cookie[]> {
@Override
public Cookie[] run() {
return request.getCookies();
}
}
private final class GetCharacterEncodingPrivilegedAction
implements PrivilegedAction<String> {
@Override
public String run() {
return request.getCharacterEncoding();
}
}
private final class GetHeadersPrivilegedAction
implements PrivilegedAction<Enumeration<String>> {
private final String name;
public GetHeadersPrivilegedAction(String name){
this.name = name;
}
@Override
public Enumeration<String> run() {
return request.getHeaders(name);
}
}
private final class GetHeaderNamesPrivilegedAction
implements PrivilegedAction<Enumeration<String>> {
@Override
public Enumeration<String> run() {
return request.getHeaderNames();
}
}
private final class GetLocalePrivilegedAction
implements PrivilegedAction<Locale> {
@Override
public Locale run() {
return request.getLocale();
}
}
private final class GetLocalesPrivilegedAction
implements PrivilegedAction<Enumeration<Locale>> {
@Override
public Enumeration<Locale> run() {
return request.getLocales();
}
}
private final class GetSessionPrivilegedAction
implements PrivilegedAction<HttpSession> {
private final boolean create;
public GetSessionPrivilegedAction(boolean create){
this.create = create;
}
@Override
public HttpSession run() {
return request.getSession(create);
}
}
// ----------------------------------------------------------- Constructors
/**
* Construct a wrapper for the specified request.
*
* @param request The request to be wrapped
*/
public RequestFacade(Request request) {
this.request = request;
}
// ----------------------------------------------------- Instance Variables
/**
* The wrapped request.
*/
protected Request request = null;
/**
* The string manager for this package.
*/
protected static final StringManager sm =
StringManager.getManager(Constants.Package);
// --------------------------------------------------------- Public Methods
/**
* Clear facade.
*/
public void clear() {
request = null;
}
/**
* Prevent cloning the facade.
*/
@Override
protected Object clone()
throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
// ------------------------------------------------- ServletRequest Methods
@Override
public Object getAttribute(String name) {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getAttribute(name);
}
@Override
public Enumeration<String> getAttributeNames() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
if (Globals.IS_SECURITY_ENABLED){
return AccessController.doPrivileged(
new GetAttributePrivilegedAction());
} else {
return request.getAttributeNames();
}
}
@Override
public String getCharacterEncoding() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
if (Globals.IS_SECURITY_ENABLED){
return AccessController.doPrivileged(
new GetCharacterEncodingPrivilegedAction());
} else {
return request.getCharacterEncoding();
}
}
@Override
public void setCharacterEncoding(String env)
throws java.io.UnsupportedEncodingException {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
request.setCharacterEncoding(env);
}
@Override
public int getContentLength() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getContentLength();
}
@Override
public String getContentType() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getContentType();
}
@Override
public ServletInputStream getInputStream() throws IOException {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getInputStream();
}
@Override
public String getParameter(String name) {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
if (Globals.IS_SECURITY_ENABLED){
return AccessController.doPrivileged(
new GetParameterPrivilegedAction(name));
} else {
return request.getParameter(name);
}
}
@Override
public Enumeration<String> getParameterNames() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
if (Globals.IS_SECURITY_ENABLED){
return AccessController.doPrivileged(
new GetParameterNamesPrivilegedAction());
} else {
return request.getParameterNames();
}
}
@Override
public String[] getParameterValues(String name) {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
String[] ret = null;
/*
* Clone the returned array only if there is a security manager
* in place, so that performance won't suffer in the non-secure case
*/
if (SecurityUtil.isPackageProtectionEnabled()){
ret = AccessController.doPrivileged(
new GetParameterValuePrivilegedAction(name));
if (ret != null) {
ret = ret.clone();
}
} else {
ret = request.getParameterValues(name);
}
return ret;
}
@Override
public Map<String,String[]> getParameterMap() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
if (Globals.IS_SECURITY_ENABLED){
return AccessController.doPrivileged(
new GetParameterMapPrivilegedAction());
} else {
return request.getParameterMap();
}
}
@Override
public String getProtocol() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getProtocol();
}
@Override
public String getScheme() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getScheme();
}
@Override
public String getServerName() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getServerName();
}
@Override
public int getServerPort() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getServerPort();
}
@Override
public BufferedReader getReader() throws IOException {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getReader();
}
@Override
public String getRemoteAddr() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getRemoteAddr();
}
@Override
public String getRemoteHost() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getRemoteHost();
}
@Override
public void setAttribute(String name, Object o) {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
request.setAttribute(name, o);
}
@Override
public void removeAttribute(String name) {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
request.removeAttribute(name);
}
@Override
public Locale getLocale() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
if (Globals.IS_SECURITY_ENABLED){
return AccessController.doPrivileged(
new GetLocalePrivilegedAction());
} else {
return request.getLocale();
}
}
@Override
public Enumeration<Locale> getLocales() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
if (Globals.IS_SECURITY_ENABLED){
return AccessController.doPrivileged(
new GetLocalesPrivilegedAction());
} else {
return request.getLocales();
}
}
@Override
public boolean isSecure() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.isSecure();
}
@Override
public RequestDispatcher getRequestDispatcher(String path) {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
if (Globals.IS_SECURITY_ENABLED){
return AccessController.doPrivileged(
new GetRequestDispatcherPrivilegedAction(path));
} else {
return request.getRequestDispatcher(path);
}
}
@Override
public String getRealPath(String path) {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getRealPath(path);
}
@Override
public String getAuthType() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getAuthType();
}
@Override
public Cookie[] getCookies() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
Cookie[] ret = null;
/*
* Clone the returned array only if there is a security manager
* in place, so that performance won't suffer in the non-secure case
*/
if (SecurityUtil.isPackageProtectionEnabled()){
ret = AccessController.doPrivileged(
new GetCookiesPrivilegedAction());
if (ret != null) {
ret = ret.clone();
}
} else {
ret = request.getCookies();
}
return ret;
}
@Override
public long getDateHeader(String name) {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getDateHeader(name);
}
@Override
public String getHeader(String name) {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getHeader(name);
}
@Override
public Enumeration<String> getHeaders(String name) {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
if (Globals.IS_SECURITY_ENABLED){
return AccessController.doPrivileged(
new GetHeadersPrivilegedAction(name));
} else {
return request.getHeaders(name);
}
}
@Override
public Enumeration<String> getHeaderNames() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
if (Globals.IS_SECURITY_ENABLED){
return AccessController.doPrivileged(
new GetHeaderNamesPrivilegedAction());
} else {
return request.getHeaderNames();
}
}
@Override
public int getIntHeader(String name) {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getIntHeader(name);
}
@Override
public String getMethod() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getMethod();
}
@Override
public String getPathInfo() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getPathInfo();
}
@Override
public String getPathTranslated() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getPathTranslated();
}
@Override
public String getContextPath() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getContextPath();
}
@Override
public String getQueryString() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getQueryString();
}
@Override
public String getRemoteUser() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getRemoteUser();
}
@Override
public boolean isUserInRole(String role) {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.isUserInRole(role);
}
@Override
public java.security.Principal getUserPrincipal() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getUserPrincipal();
}
@Override
public String getRequestedSessionId() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getRequestedSessionId();
}
@Override
public String getRequestURI() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getRequestURI();
}
@Override
public StringBuffer getRequestURL() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getRequestURL();
}
@Override
public String getServletPath() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getServletPath();
}
@Override
public HttpSession getSession(boolean create) {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
if (SecurityUtil.isPackageProtectionEnabled()){
return AccessController.
doPrivileged(new GetSessionPrivilegedAction(create));
} else {
return request.getSession(create);
}
}
@Override
public HttpSession getSession() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return getSession(true);
}
@Override
public boolean isRequestedSessionIdValid() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.isRequestedSessionIdValid();
}
@Override
public boolean isRequestedSessionIdFromCookie() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.isRequestedSessionIdFromCookie();
}
@Override
public boolean isRequestedSessionIdFromURL() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.isRequestedSessionIdFromURL();
}
@Override
public boolean isRequestedSessionIdFromUrl() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.isRequestedSessionIdFromURL();
}
@Override
public String getLocalAddr() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getLocalAddr();
}
@Override
public String getLocalName() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getLocalName();
}
@Override
public int getLocalPort() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getLocalPort();
}
@Override
public int getRemotePort() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getRemotePort();
}
@Override
public ServletContext getServletContext() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
return request.getServletContext();
}
@Override
public AsyncContext startAsync() throws IllegalStateException {
return request.startAsync();
}
@Override
public AsyncContext startAsync(ServletRequest request, ServletResponse response)
throws IllegalStateException {
return this.request.startAsync(request, response);
}
@Override
public boolean isAsyncStarted() {
return request.isAsyncStarted();
}
@Override
public boolean isAsyncSupported() {
return request.isAsyncSupported();
}
@Override
public AsyncContext getAsyncContext() {
return request.getAsyncContext();
}
@Override
public DispatcherType getDispatcherType() {
return request.getDispatcherType();
}
@Override
public boolean authenticate(HttpServletResponse response)
throws IOException, ServletException {
return request.authenticate(response);
}
@Override
public void login(String username, String password)
throws ServletException {
request.login(username, password);
}
@Override
public void logout() throws ServletException {
request.logout();
}
@Override
public Collection<Part> getParts() throws IllegalStateException,
IOException, ServletException {
return request.getParts();
}
@Override
public Part getPart(String name) throws IllegalStateException, IOException,
ServletException {
return request.getPart(name);
}
public boolean getAllowTrace() {
return request.getConnector().getAllowTrace();
}
/**
* Sets the response status to {@link
* HttpServletResponse#SC_SWITCHING_PROTOCOLS} and flushes the response.
* Protocol specific headers must have already been set before this method
* is called.
*
* @param inbound The handler for all further incoming data on the current
* connection.
*
* @throws IOException If the upgrade fails (e.g. if the response has
* already been committed.
*/
public void doUpgrade(UpgradeInbound inbound)
throws IOException {
request.doUpgrade(inbound);
}
public <T extends HttpUpgradeHandler> T upgrade(
Class<T> httpUpgradeHandlerClass) throws ServletException {
return request.upgrade(httpUpgradeHandlerClass);
}
}
|
package com.cxy7.data.fense.security;
import com.cxy7.data.fense.dao.RoleDao;
import com.cxy7.data.fense.dao.UserDao;
import com.cxy7.data.fense.model.Role;
import com.cxy7.data.fense.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
* @Author: XiaoYu
* @Date: 2021/3/21 0:10
*/
@Service
public class FenseUserDetailsService implements UserDetailsService {
@Autowired
private UserDao userDao;
@Autowired
private RoleDao roleDao;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userDao.getOneByName(username).orElseThrow(() -> new UsernameNotFoundException(String.format("No user found with username '%s'.", username)));
List<Role> roles = roleDao.findByUserId(user.getId());
List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
for (Role role : roles) {
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(role.getName());
grantedAuthorities.add(grantedAuthority);
}
if (user.getIsAdmin() == 1) {
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_ADMIN");
grantedAuthorities.add(grantedAuthority);
} else {
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_USER");
grantedAuthorities.add(grantedAuthority);
}
return new org.springframework.security.core.userdetails.User(user.getName(), user.getPassword(), grantedAuthorities);
}
}
|
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds 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.jclouds.abiquo.domain.config.options;
import org.jclouds.http.options.BaseHttpRequestOptions;
/**
* Available options to query icons.
*
* @author Francesc Montserrat
*/
public class IconOptions extends BaseHttpRequestOptions {
public static Builder builder() {
return new Builder();
}
@Override
protected Object clone() throws CloneNotSupportedException {
IconOptions options = new IconOptions();
options.queryParameters.putAll(queryParameters);
return options;
}
public static class Builder {
private String path;
public Builder path(final String path) {
this.path = path;
return this;
}
public IconOptions build() {
IconOptions options = new IconOptions();
if (path != null) {
options.queryParameters.put("path", path);
}
return options;
}
}
}
|
/*
* Copyright 2016-2021 Pnoker. 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.dc3.common.sdk.service.impl;
import cn.hutool.core.thread.ThreadUtil;
import com.dc3.common.bean.driver.AttributeInfo;
import com.dc3.common.bean.driver.DriverRegister;
import com.dc3.common.constant.Common;
import com.dc3.common.exception.ServiceException;
import com.dc3.common.model.*;
import com.dc3.common.sdk.bean.DriverContext;
import com.dc3.common.sdk.bean.DriverProperty;
import com.dc3.common.sdk.service.DriverMetadataService;
import com.dc3.common.sdk.service.DriverService;
import com.dc3.common.utils.Dc3Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.concurrent.*;
/**
* Driver Metadata Service Implements
*
* @author pnoker
*/
@Slf4j
@Service
public class DriverMetadataServiceImpl implements DriverMetadataService {
@Value("${server.port}")
private int port;
@Value("${spring.application.name}")
private String serviceName;
@Resource
private DriverContext driverContext;
@Resource
private DriverService driverService;
@Resource
private DriverProperty driverProperty;
@Resource
private ThreadPoolExecutor threadPoolExecutor;
@Override
public void initial() {
String localHost = Dc3Util.localHost();
if (!Dc3Util.isName(driverProperty.getName()) || !Dc3Util.isName(this.serviceName) || !Dc3Util.isHost(localHost)) {
throw new ServiceException("The driver name, service name or host name format is invalid");
}
if (!Dc3Util.isDriverPort(this.port)) {
throw new ServiceException("The driver port is invalid, port range is 8600-8799");
}
Driver driver = new Driver(driverProperty.getName(), this.serviceName, localHost, this.port);
driver.setDescription(driverProperty.getDescription());
log.info("The driver {}/{} is initializing", driver.getServiceName(), driver.getName());
registerHandshake();
driverService.driverEventSender(new DriverEvent(
serviceName,
Common.Driver.Event.DRIVER_REGISTER,
new DriverRegister(
driver,
driverProperty.getDriverAttribute(),
driverProperty.getPointAttribute()
)
));
syncDriverMetadata(driver);
log.info("The driver {}/{} is initialized successfully", driver.getServiceName(), driver.getName());
}
@Override
public void upsertProfile(Profile profile) {
// Add profile driver info to context
driverContext.getDriverMetadata().getProfileDriverInfoMap().computeIfAbsent(profile.getId(), k -> new ConcurrentHashMap<>(16));
// Add profile point to context
driverContext.getDriverMetadata().getProfilePointMap().computeIfAbsent(profile.getId(), k -> new ConcurrentHashMap<>(16));
}
@Override
public void deleteProfile(Long id) {
driverContext.getDriverMetadata().getProfileDriverInfoMap().entrySet().removeIf(next -> next.getKey().equals(id));
driverContext.getDriverMetadata().getProfilePointMap().entrySet().removeIf(next -> next.getKey().equals(id));
}
@Override
public void upsertDriverInfo(DriverInfo driverInfo) {
// Add driver info to driver info map context
DriverAttribute attribute = driverContext.getDriverMetadata().getDriverAttributeMap().get(driverInfo.getDriverAttributeId());
if (null != attribute) {
driverContext.getDriverMetadata().getProfileDriverInfoMap().computeIfAbsent(driverInfo.getProfileId(), k -> new ConcurrentHashMap<>(16))
.put(attribute.getName(), new AttributeInfo(driverInfo.getValue(), attribute.getType()));
}
}
@Override
public void deleteDriverInfo(Long attributeId, Long profileId) {
DriverAttribute attribute = driverContext.getDriverMetadata().getDriverAttributeMap().get(attributeId);
if (null != attribute) {
String attributeName = attribute.getName();
// Delete driver info from driver info map context
driverContext.getDriverMetadata().getProfileDriverInfoMap().computeIfPresent(profileId, (k, v) -> {
v.entrySet().removeIf(next -> next.getKey().equals(attributeName));
return v;
});
}
}
@Override
public void upsertDevice(Device device) {
// Add device to context
driverContext.getDriverMetadata().getDeviceMap().put(device.getId(), device);
// Add device name to context
driverContext.getDriverMetadata().getDeviceNameMap().put(device.getName(), device.getId());
}
@Override
public void deleteDevice(Long id) {
driverContext.getDriverMetadata().getDeviceMap().entrySet().removeIf(next -> next.getKey().equals(id));
driverContext.getDriverMetadata().getDeviceNameMap().entrySet().removeIf(next -> next.getValue().equals(id));
driverContext.getDriverMetadata().getDevicePointInfoMap().entrySet().removeIf(next -> next.getKey().equals(id));
}
@Override
public void upsertPoint(Point point) {
// Upsert point to profile point map context
driverContext.getDriverMetadata().getProfilePointMap().computeIfAbsent(point.getProfileId(), k -> new ConcurrentHashMap<>(16)).put(point.getId(), point);
}
@Override
public void deletePoint(Long pointId, Long profileId) {
// Delete point from profile point map context
driverContext.getDriverMetadata().getProfilePointMap().computeIfPresent(profileId, (k, v) -> {
v.entrySet().removeIf(next -> next.getKey().equals(pointId));
return v;
});
}
@Override
public void upsertPointInfo(PointInfo pointInfo) {
// Add the point info to the device point info map context
PointAttribute attribute = driverContext.getDriverMetadata().getPointAttributeMap().get(pointInfo.getPointAttributeId());
if (null != attribute) {
driverContext.getDriverMetadata().getDevicePointInfoMap().computeIfAbsent(pointInfo.getDeviceId(), k -> new ConcurrentHashMap<>(16))
.computeIfAbsent(pointInfo.getPointId(), k -> new ConcurrentHashMap<>(16))
.put(attribute.getName(), new AttributeInfo(pointInfo.getValue(), attribute.getType()));
}
}
@Override
public void deletePointInfo(Long pointId, Long attributeId, Long deviceId) {
PointAttribute attribute = driverContext.getDriverMetadata().getPointAttributeMap().get(attributeId);
if (null != attribute) {
String attributeName = attribute.getName();
// Delete the point info from the device info map context
driverContext.getDriverMetadata().getDevicePointInfoMap().computeIfPresent(deviceId, (key1, value1) -> {
value1.computeIfPresent(pointId, (key2, value2) -> {
value2.entrySet().removeIf(next -> next.getKey().equals(attributeName));
return value2;
});
return value1;
});
// If the point attribute is null, delete the point info from the device info map context
driverContext.getDriverMetadata().getDevicePointInfoMap().computeIfPresent(deviceId, (key, value) -> {
value.entrySet().removeIf(next -> next.getValue().size() < 1);
return value;
});
}
}
private void registerHandshake() {
try {
threadPoolExecutor.submit(() -> {
driverService.driverEventSender(new DriverEvent(
serviceName,
Common.Driver.Event.DRIVER_HANDSHAKE,
null
));
while (!Common.Driver.Status.REGISTERING.equals(driverContext.getDriverStatus())) {
ThreadUtil.sleep(500);
}
}).get(5, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException exception) {
driverService.close("The driver initialization failed, Check whether dc3-manager are started normally");
}
}
private void syncDriverMetadata(Driver driver) {
try {
threadPoolExecutor.submit(() -> {
driverService.driverEventSender(new DriverEvent(
serviceName,
Common.Driver.Event.DRIVER_METADATA_SYNC,
driver.getServiceName()
));
while (!Common.Driver.Status.ONLINE.equals(driverContext.getDriverStatus())) {
ThreadUtil.sleep(500);
}
}).get(5, TimeUnit.MINUTES);
} catch (InterruptedException | ExecutionException | TimeoutException exception) {
driverService.close("The driver initialization failed, Sync driver metadata from dc3-manager timeout");
}
}
}
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * Copyright (C) 2006 The Guava 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. */
end_comment
begin_package
DECL|package|com.google.common.util.concurrent
package|package
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|util
operator|.
name|concurrent
package|;
end_package
begin_import
import|import static
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|base
operator|.
name|Preconditions
operator|.
name|checkNotNull
import|;
end_import
begin_import
import|import static
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|util
operator|.
name|concurrent
operator|.
name|Futures
operator|.
name|getDone
import|;
end_import
begin_import
import|import static
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|util
operator|.
name|concurrent
operator|.
name|MoreExecutors
operator|.
name|rejectionPropagatingExecutor
import|;
end_import
begin_import
import|import static
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|util
operator|.
name|concurrent
operator|.
name|NullnessCasts
operator|.
name|uncheckedCastNullableTToT
import|;
end_import
begin_import
import|import static
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|util
operator|.
name|concurrent
operator|.
name|Platform
operator|.
name|isInstanceOfThrowableClass
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|annotations
operator|.
name|GwtCompatible
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|base
operator|.
name|Function
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|util
operator|.
name|concurrent
operator|.
name|internal
operator|.
name|InternalFutureFailureAccess
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|util
operator|.
name|concurrent
operator|.
name|internal
operator|.
name|InternalFutures
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|errorprone
operator|.
name|annotations
operator|.
name|ForOverride
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|concurrent
operator|.
name|ExecutionException
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|concurrent
operator|.
name|Executor
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|annotation
operator|.
name|CheckForNull
import|;
end_import
begin_import
import|import
name|org
operator|.
name|checkerframework
operator|.
name|checker
operator|.
name|nullness
operator|.
name|qual
operator|.
name|Nullable
import|;
end_import
begin_comment
comment|/** Implementations of {@code Futures.catching*}. */
end_comment
begin_annotation
annotation|@
name|GwtCompatible
end_annotation
begin_annotation
annotation|@
name|ElementTypesAreNonnullByDefault
end_annotation
begin_annotation
annotation|@
name|SuppressWarnings
argument_list|(
literal|"nullness"
argument_list|)
end_annotation
begin_comment
comment|// TODO(b/147136275): Remove once our checker understands& and |.
end_comment
begin_expr_stmt
DECL|class|AbstractCatchingFuture
specifier|abstract
name|class
name|AbstractCatchingFuture
operator|<
name|V
expr|extends @
name|Nullable
name|Object
operator|,
name|X
expr|extends
name|Throwable
operator|,
name|F
operator|,
name|T
expr|extends @
name|Nullable
name|Object
operator|>
expr|extends
name|FluentFuture
operator|.
name|TrustedFuture
argument_list|<
name|V
argument_list|>
expr|implements
name|Runnable
block|{
DECL|method|create ( ListenableFuture<? extends V> input, Class<X> exceptionType, Function<? super X, ? extends V> fallback, Executor executor)
specifier|static
operator|<
name|V
expr|extends @
name|Nullable
name|Object
block|,
name|X
expr|extends
name|Throwable
operator|>
name|ListenableFuture
argument_list|<
name|V
argument_list|>
name|create
argument_list|(
name|ListenableFuture
argument_list|<
name|?
extends|extends
name|V
argument_list|>
name|input
argument_list|,
name|Class
argument_list|<
name|X
argument_list|>
name|exceptionType
argument_list|,
name|Function
argument_list|<
name|?
super|super
name|X
argument_list|,
name|?
extends|extends
name|V
argument_list|>
name|fallback
argument_list|,
name|Executor
name|executor
argument_list|)
block|{
name|CatchingFuture
argument_list|<
name|V
argument_list|,
name|X
argument_list|>
name|future
operator|=
operator|new
name|CatchingFuture
argument_list|<>
argument_list|(
name|input
argument_list|,
name|exceptionType
argument_list|,
name|fallback
argument_list|)
block|;
name|input
operator|.
name|addListener
argument_list|(
name|future
argument_list|,
name|rejectionPropagatingExecutor
argument_list|(
name|executor
argument_list|,
name|future
argument_list|)
argument_list|)
block|;
return|return
name|future
return|;
block|}
DECL|method|create ( ListenableFuture<? extends V> input, Class<X> exceptionType, AsyncFunction<? super X, ? extends V> fallback, Executor executor)
specifier|static
operator|<
name|X
expr|extends
name|Throwable
operator|,
name|V
expr|extends @
name|Nullable
name|Object
operator|>
name|ListenableFuture
argument_list|<
name|V
argument_list|>
name|create
argument_list|(
name|ListenableFuture
argument_list|<
name|?
extends|extends
name|V
argument_list|>
name|input
operator|,
name|Class
argument_list|<
name|X
argument_list|>
name|exceptionType
operator|,
name|AsyncFunction
argument_list|<
name|?
super|super
name|X
argument_list|,
name|?
extends|extends
name|V
argument_list|>
name|fallback
operator|,
name|Executor
name|executor
argument_list|)
block|{
name|AsyncCatchingFuture
argument_list|<
name|V
argument_list|,
name|X
argument_list|>
name|future
operator|=
operator|new
name|AsyncCatchingFuture
argument_list|<>
argument_list|(
name|input
argument_list|,
name|exceptionType
argument_list|,
name|fallback
argument_list|)
block|;
name|input
operator|.
name|addListener
argument_list|(
name|future
argument_list|,
name|rejectionPropagatingExecutor
argument_list|(
name|executor
argument_list|,
name|future
argument_list|)
argument_list|)
block|;
return|return
name|future
return|;
block|}
end_expr_stmt
begin_comment
comment|/* * In certain circumstances, this field might theoretically not be visible to an afterDone() call * triggered by cancel(). For details, see the comments on the fields of TimeoutFuture. */
end_comment
begin_decl_stmt
DECL|field|inputFuture
annotation|@
name|CheckForNull
name|ListenableFuture
argument_list|<
name|?
extends|extends
name|V
argument_list|>
name|inputFuture
decl_stmt|;
end_decl_stmt
begin_decl_stmt
DECL|field|exceptionType
annotation|@
name|CheckForNull
name|Class
argument_list|<
name|X
argument_list|>
name|exceptionType
decl_stmt|;
end_decl_stmt
begin_decl_stmt
DECL|field|fallback
annotation|@
name|CheckForNull
name|F
name|fallback
decl_stmt|;
end_decl_stmt
begin_expr_stmt
DECL|method|AbstractCatchingFuture ( ListenableFuture<? extends V> inputFuture, Class<X> exceptionType, F fallback)
name|AbstractCatchingFuture
argument_list|(
name|ListenableFuture
argument_list|<
name|?
extends|extends
name|V
argument_list|>
name|inputFuture
operator|,
name|Class
argument_list|<
name|X
argument_list|>
name|exceptionType
operator|,
name|F
name|fallback
argument_list|)
block|{
name|this
operator|.
name|inputFuture
operator|=
name|checkNotNull
argument_list|(
name|inputFuture
argument_list|)
block|;
name|this
operator|.
name|exceptionType
operator|=
name|checkNotNull
argument_list|(
name|exceptionType
argument_list|)
block|;
name|this
operator|.
name|fallback
operator|=
name|checkNotNull
argument_list|(
name|fallback
argument_list|)
block|; }
expr|@
name|Override
DECL|method|run ()
specifier|public
name|final
name|void
name|run
argument_list|()
block|{
name|ListenableFuture
argument_list|<
name|?
extends|extends
name|V
argument_list|>
name|localInputFuture
operator|=
name|inputFuture
block|;
name|Class
argument_list|<
name|X
argument_list|>
name|localExceptionType
operator|=
name|exceptionType
block|;
name|F
name|localFallback
operator|=
name|fallback
block|;
if|if
condition|(
name|localInputFuture
operator|==
literal|null
operator||
name|localExceptionType
operator|==
literal|null
operator||
name|localFallback
operator|==
literal|null
comment|// This check, unlike all the others, is a volatile read
operator|||
name|isCancelled
argument_list|()
condition|)
block|{
return|return;
block|}
name|inputFuture
operator|=
literal|null
expr_stmt|;
end_expr_stmt
begin_comment
comment|// For an explanation of the cases here, see the comments on AbstractTransformFuture.run.
end_comment
begin_decl_stmt
name|V
name|sourceResult
init|=
literal|null
decl_stmt|;
end_decl_stmt
begin_decl_stmt
name|Throwable
name|throwable
init|=
literal|null
decl_stmt|;
end_decl_stmt
begin_try
try|try
block|{
if|if
condition|(
name|localInputFuture
operator|instanceof
name|InternalFutureFailureAccess
condition|)
block|{
name|throwable
operator|=
name|InternalFutures
operator|.
name|tryInternalFastPathGetFailure
argument_list|(
operator|(
name|InternalFutureFailureAccess
operator|)
name|localInputFuture
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|throwable
operator|==
literal|null
condition|)
block|{
name|sourceResult
operator|=
name|getDone
argument_list|(
name|localInputFuture
argument_list|)
expr_stmt|;
block|}
block|}
catch|catch
parameter_list|(
name|ExecutionException
name|e
parameter_list|)
block|{
name|throwable
operator|=
name|e
operator|.
name|getCause
argument_list|()
expr_stmt|;
if|if
condition|(
name|throwable
operator|==
literal|null
condition|)
block|{
name|throwable
operator|=
operator|new
name|NullPointerException
argument_list|(
literal|"Future type "
operator|+
name|localInputFuture
operator|.
name|getClass
argument_list|()
operator|+
literal|" threw "
operator|+
name|e
operator|.
name|getClass
argument_list|()
operator|+
literal|" without a cause"
argument_list|)
expr_stmt|;
block|}
block|}
catch|catch
parameter_list|(
name|Throwable
name|e
parameter_list|)
block|{
comment|// this includes cancellation exception
name|throwable
operator|=
name|e
expr_stmt|;
block|}
end_try
begin_if
if|if
condition|(
name|throwable
operator|==
literal|null
condition|)
block|{
comment|/* * The cast is safe: There was no exception, so the assignment from getDone must have * succeeded. */
name|set
argument_list|(
name|uncheckedCastNullableTToT
argument_list|(
name|sourceResult
argument_list|)
argument_list|)
expr_stmt|;
return|return;
block|}
end_if
begin_if
if|if
condition|(
operator|!
name|isInstanceOfThrowableClass
argument_list|(
name|throwable
argument_list|,
name|localExceptionType
argument_list|)
condition|)
block|{
name|setFuture
argument_list|(
name|localInputFuture
argument_list|)
expr_stmt|;
comment|// TODO(cpovirk): Test that fallback is not run in this case.
return|return;
block|}
end_if
begin_decl_stmt
annotation|@
name|SuppressWarnings
argument_list|(
literal|"unchecked"
argument_list|)
comment|// verified safe by isInstanceOfThrowableClass
name|X
name|castThrowable
init|=
operator|(
name|X
operator|)
name|throwable
decl_stmt|;
end_decl_stmt
begin_decl_stmt
name|T
name|fallbackResult
decl_stmt|;
end_decl_stmt
begin_try
try|try
block|{
name|fallbackResult
operator|=
name|doFallback
argument_list|(
name|localFallback
argument_list|,
name|castThrowable
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Throwable
name|t
parameter_list|)
block|{
name|setException
argument_list|(
name|t
argument_list|)
expr_stmt|;
return|return;
block|}
finally|finally
block|{
name|exceptionType
operator|=
literal|null
expr_stmt|;
name|fallback
operator|=
literal|null
expr_stmt|;
block|}
end_try
begin_expr_stmt
name|setResult
argument_list|(
name|fallbackResult
argument_list|)
expr_stmt|;
end_expr_stmt
begin_function
unit|} @
name|Override
annotation|@
name|CheckForNull
DECL|method|pendingToString ()
specifier|protected
name|String
name|pendingToString
parameter_list|()
block|{
name|ListenableFuture
argument_list|<
name|?
extends|extends
name|V
argument_list|>
name|localInputFuture
init|=
name|inputFuture
decl_stmt|;
name|Class
argument_list|<
name|X
argument_list|>
name|localExceptionType
init|=
name|exceptionType
decl_stmt|;
name|F
name|localFallback
init|=
name|fallback
decl_stmt|;
name|String
name|superString
init|=
name|super
operator|.
name|pendingToString
argument_list|()
decl_stmt|;
name|String
name|resultString
init|=
literal|""
decl_stmt|;
if|if
condition|(
name|localInputFuture
operator|!=
literal|null
condition|)
block|{
name|resultString
operator|=
literal|"inputFuture=["
operator|+
name|localInputFuture
operator|+
literal|"], "
expr_stmt|;
block|}
if|if
condition|(
name|localExceptionType
operator|!=
literal|null
operator|&&
name|localFallback
operator|!=
literal|null
condition|)
block|{
return|return
name|resultString
operator|+
literal|"exceptionType=["
operator|+
name|localExceptionType
operator|+
literal|"], fallback=["
operator|+
name|localFallback
operator|+
literal|"]"
return|;
block|}
elseif|else
if|if
condition|(
name|superString
operator|!=
literal|null
condition|)
block|{
return|return
name|resultString
operator|+
name|superString
return|;
block|}
return|return
literal|null
return|;
block|}
end_function
begin_comment
comment|/** Template method for subtypes to actually run the fallback. */
end_comment
begin_function_decl
annotation|@
name|ForOverride
annotation|@
name|ParametricNullness
DECL|method|doFallback (F fallback, X throwable)
specifier|abstract
name|T
name|doFallback
parameter_list|(
name|F
name|fallback
parameter_list|,
name|X
name|throwable
parameter_list|)
throws|throws
name|Exception
function_decl|;
end_function_decl
begin_comment
comment|/** Template method for subtypes to actually set the result. */
end_comment
begin_function_decl
annotation|@
name|ForOverride
DECL|method|setResult (@arametricNullness T result)
specifier|abstract
name|void
name|setResult
parameter_list|(
annotation|@
name|ParametricNullness
name|T
name|result
parameter_list|)
function_decl|;
end_function_decl
begin_function
annotation|@
name|Override
DECL|method|afterDone ()
specifier|protected
specifier|final
name|void
name|afterDone
parameter_list|()
block|{
name|maybePropagateCancellationTo
argument_list|(
name|inputFuture
argument_list|)
expr_stmt|;
name|this
operator|.
name|inputFuture
operator|=
literal|null
expr_stmt|;
name|this
operator|.
name|exceptionType
operator|=
literal|null
expr_stmt|;
name|this
operator|.
name|fallback
operator|=
literal|null
expr_stmt|;
block|}
end_function
begin_comment
comment|/** * An {@link AbstractCatchingFuture} that delegates to an {@link AsyncFunction} and {@link * #setFuture(ListenableFuture)}. */
end_comment
begin_expr_stmt
DECL|class|AsyncCatchingFuture
specifier|private
specifier|static
name|final
name|class
name|AsyncCatchingFuture
operator|<
name|V
expr|extends @
name|Nullable
name|Object
operator|,
name|X
expr|extends
name|Throwable
operator|>
expr|extends
name|AbstractCatchingFuture
argument_list|<
name|V
argument_list|,
name|X
argument_list|,
name|AsyncFunction
argument_list|<
name|?
super|super
name|X
argument_list|,
name|?
extends|extends
name|V
argument_list|>
argument_list|,
name|ListenableFuture
argument_list|<
name|?
extends|extends
name|V
argument_list|>
argument_list|>
block|{
DECL|method|AsyncCatchingFuture ( ListenableFuture<? extends V> input, Class<X> exceptionType, AsyncFunction<? super X, ? extends V> fallback)
name|AsyncCatchingFuture
argument_list|(
name|ListenableFuture
argument_list|<
name|?
extends|extends
name|V
argument_list|>
name|input
argument_list|,
name|Class
argument_list|<
name|X
argument_list|>
name|exceptionType
argument_list|,
name|AsyncFunction
argument_list|<
name|?
super|super
name|X
argument_list|,
name|?
extends|extends
name|V
argument_list|>
name|fallback
argument_list|)
block|{
name|super
argument_list|(
name|input
argument_list|,
name|exceptionType
argument_list|,
name|fallback
argument_list|)
block|; }
expr|@
name|Override
DECL|method|doFallback ( AsyncFunction<? super X, ? extends V> fallback, X cause)
name|ListenableFuture
argument_list|<
name|?
extends|extends
name|V
argument_list|>
name|doFallback
argument_list|(
name|AsyncFunction
argument_list|<
name|?
super|super
name|X
argument_list|,
name|?
extends|extends
name|V
argument_list|>
name|fallback
operator|,
name|X
name|cause
argument_list|)
throws|throws
name|Exception
block|{
name|ListenableFuture
argument_list|<
name|?
extends|extends
name|V
argument_list|>
name|replacement
operator|=
name|fallback
operator|.
name|apply
argument_list|(
name|cause
argument_list|)
block|;
name|checkNotNull
argument_list|(
name|replacement
argument_list|,
literal|"AsyncFunction.apply returned null instead of a Future. "
operator|+
literal|"Did you mean to return immediateFuture(null)? %s"
argument_list|,
name|fallback
argument_list|)
block|;
return|return
name|replacement
return|;
block|}
end_expr_stmt
begin_function
annotation|@
name|Override
DECL|method|setResult (ListenableFuture<? extends V> result)
name|void
name|setResult
parameter_list|(
name|ListenableFuture
argument_list|<
name|?
extends|extends
name|V
argument_list|>
name|result
parameter_list|)
block|{
name|setFuture
argument_list|(
name|result
argument_list|)
expr_stmt|;
block|}
end_function
begin_comment
unit|}
comment|/** * An {@link AbstractCatchingFuture} that delegates to a {@link Function} and {@link * #set(Object)}. */
end_comment
begin_expr_stmt
DECL|class|CatchingFuture
unit|private
specifier|static
name|final
name|class
name|CatchingFuture
operator|<
name|V
expr|extends @
name|Nullable
name|Object
operator|,
name|X
expr|extends
name|Throwable
operator|>
expr|extends
name|AbstractCatchingFuture
argument_list|<
name|V
argument_list|,
name|X
argument_list|,
name|Function
argument_list|<
name|?
super|super
name|X
argument_list|,
name|?
extends|extends
name|V
argument_list|>
argument_list|,
name|V
argument_list|>
block|{
DECL|method|CatchingFuture ( ListenableFuture<? extends V> input, Class<X> exceptionType, Function<? super X, ? extends V> fallback)
name|CatchingFuture
argument_list|(
name|ListenableFuture
argument_list|<
name|?
extends|extends
name|V
argument_list|>
name|input
argument_list|,
name|Class
argument_list|<
name|X
argument_list|>
name|exceptionType
argument_list|,
name|Function
argument_list|<
name|?
super|super
name|X
argument_list|,
name|?
extends|extends
name|V
argument_list|>
name|fallback
argument_list|)
block|{
name|super
argument_list|(
name|input
argument_list|,
name|exceptionType
argument_list|,
name|fallback
argument_list|)
block|; }
expr|@
name|Override
expr|@
name|ParametricNullness
DECL|method|doFallback (Function<? super X, ? extends V> fallback, X cause)
name|V
name|doFallback
argument_list|(
name|Function
argument_list|<
name|?
super|super
name|X
argument_list|,
name|?
extends|extends
name|V
argument_list|>
name|fallback
operator|,
name|X
name|cause
argument_list|)
throws|throws
name|Exception
block|{
return|return
name|fallback
operator|.
name|apply
argument_list|(
name|cause
argument_list|)
return|;
block|}
end_expr_stmt
begin_function
annotation|@
name|Override
DECL|method|setResult (@arametricNullness V result)
name|void
name|setResult
parameter_list|(
annotation|@
name|ParametricNullness
name|V
name|result
parameter_list|)
block|{
name|set
argument_list|(
name|result
argument_list|)
expr_stmt|;
block|}
end_function
unit|} }
end_unit
|
package uk.dangrew.nuts.graphics.goal;
import org.junit.Test;
public class GoalManagerPaneTest {
@Test public void untested() {
System.out.println( "WARNING: UNTESTED - " + getClass().getName() );
}//End Method
}
|
// 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.cloud.api.query.dao;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ejb.Local;
import javax.inject.Inject;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.apache.cloudstack.api.BaseCmd;
import org.apache.cloudstack.api.response.TemplateResponse;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine;
import org.apache.cloudstack.engine.subsystem.api.storage.TemplateState;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import com.cloud.api.ApiDBUtils;
import com.cloud.api.ApiResponseHelper;
import com.cloud.api.query.vo.ResourceTagJoinVO;
import com.cloud.api.query.vo.TemplateJoinVO;
import com.cloud.storage.Storage;
import com.cloud.storage.Storage.TemplateType;
import com.cloud.storage.VMTemplateHostVO;
import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
import com.cloud.template.VirtualMachineTemplate;
import com.cloud.user.Account;
import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
@Component
@Local(value = {TemplateJoinDao.class})
public class TemplateJoinDaoImpl extends GenericDaoBase<TemplateJoinVO, Long> implements TemplateJoinDao {
public static final Logger s_logger = Logger.getLogger(TemplateJoinDaoImpl.class);
@Inject
private ConfigurationDao _configDao;
private final SearchBuilder<TemplateJoinVO> tmpltIdPairSearch;
private final SearchBuilder<TemplateJoinVO> tmpltIdSearch;
private final SearchBuilder<TemplateJoinVO> tmpltZoneSearch;
private final SearchBuilder<TemplateJoinVO> activeTmpltSearch;
protected TemplateJoinDaoImpl() {
tmpltIdPairSearch = createSearchBuilder();
tmpltIdPairSearch.and("tempZonePairIN", tmpltIdPairSearch.entity().getTempZonePair(), SearchCriteria.Op.IN);
tmpltIdPairSearch.done();
tmpltIdSearch = createSearchBuilder();
tmpltIdSearch.and("id", tmpltIdSearch.entity().getId(), SearchCriteria.Op.EQ);
tmpltIdSearch.done();
tmpltZoneSearch = createSearchBuilder();
tmpltZoneSearch.and("id", tmpltZoneSearch.entity().getId(), SearchCriteria.Op.EQ);
tmpltZoneSearch.and("dataCenterId", tmpltZoneSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
tmpltZoneSearch.and("state", tmpltZoneSearch.entity().getState(), SearchCriteria.Op.EQ);
tmpltZoneSearch.done();
activeTmpltSearch = createSearchBuilder();
activeTmpltSearch.and("store_id", activeTmpltSearch.entity().getDataStoreId(), SearchCriteria.Op.EQ);
activeTmpltSearch.and("type", activeTmpltSearch.entity().getTemplateType(), SearchCriteria.Op.EQ);
activeTmpltSearch.done();
// select distinct pair (template_id, zone_id)
this._count = "select count(distinct temp_zone_pair) from template_view WHERE ";
}
private String getTemplateStatus(TemplateJoinVO template) {
boolean isAdmin = false;
Account caller = CallContext.current().getCallingAccount();
if ((caller == null) || BaseCmd.isAdmin(caller.getType())) {
isAdmin = true;
}
// If the user is an Admin, add the template download status
String templateStatus = null;
if (isAdmin || caller.getId() == template.getAccountId()) {
// add download status
if (template.getDownloadState() != Status.DOWNLOADED) {
templateStatus = "Processing";
if (template.getDownloadState() == VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS) {
if (template.getDownloadPercent() == 100) {
templateStatus = "Installing Template";
} else {
templateStatus = template.getDownloadPercent() + "% Downloaded";
}
} else {
templateStatus = template.getErrorString();
}
} else if (template.getDownloadState() == VMTemplateHostVO.Status.DOWNLOADED) {
templateStatus = "Download Complete";
} else {
templateStatus = "Successfully Installed";
}
}
return templateStatus;
}
@Override
public TemplateResponse newTemplateResponse(TemplateJoinVO template) {
TemplateResponse templateResponse = new TemplateResponse();
templateResponse.setId(template.getUuid());
templateResponse.setName(template.getName());
templateResponse.setDisplayText(template.getDisplayText());
templateResponse.setPublic(template.isPublicTemplate());
templateResponse.setCreated(template.getCreatedOnStore());
if (template.getFormat() == Storage.ImageFormat.BAREMETAL) {
// for baremetal template, we didn't download, but is ready to use.
templateResponse.setReady(true);
} else {
templateResponse.setReady(template.getState() == ObjectInDataStoreStateMachine.State.Ready);
}
templateResponse.setFeatured(template.isFeatured());
templateResponse.setExtractable(template.isExtractable() && !(template.getTemplateType() == TemplateType.SYSTEM));
templateResponse.setPasswordEnabled(template.isEnablePassword());
templateResponse.setDynamicallyScalable(template.isDynamicallyScalable());
templateResponse.setSshKeyEnabled(template.isEnableSshKey());
templateResponse.setCrossZones(template.isCrossZones());
templateResponse.setFormat(template.getFormat());
if (template.getTemplateType() != null) {
templateResponse.setTemplateType(template.getTemplateType().toString());
}
templateResponse.setHypervisor(template.getHypervisorType().toString());
templateResponse.setOsTypeId(template.getGuestOSUuid());
templateResponse.setOsTypeName(template.getGuestOSName());
// populate owner.
ApiResponseHelper.populateOwner(templateResponse, template);
// populate domain
templateResponse.setDomainId(template.getDomainUuid());
templateResponse.setDomainName(template.getDomainName());
// If the user is an Admin, add the template download status
String templateStatus = getTemplateStatus(template);
if (templateStatus != null) {
templateResponse.setStatus(templateStatus);
}
if (template.getDataCenterId() > 0) {
templateResponse.setZoneId(template.getDataCenterUuid());
templateResponse.setZoneName(template.getDataCenterName());
}
Long templateSize = template.getSize();
if (templateSize > 0) {
templateResponse.setSize(templateSize);
}
templateResponse.setChecksum(template.getChecksum());
if (template.getSourceTemplateId() != null) {
templateResponse.setSourceTemplateId(template.getSourceTemplateUuid());
}
templateResponse.setTemplateTag(template.getTemplateTag());
// set details map
if (template.getDetailName() != null) {
Map<String, String> details = new HashMap<String, String>();
details.put(template.getDetailName(), template.getDetailValue());
templateResponse.setDetails(details);
}
// update tag information
long tag_id = template.getTagId();
if (tag_id > 0) {
ResourceTagJoinVO vtag = ApiDBUtils.findResourceTagViewById(tag_id);
if (vtag != null) {
templateResponse.addTag(ApiDBUtils.newResourceTagResponse(vtag, false));
}
}
templateResponse.setObjectName("template");
return templateResponse;
}
//TODO: This is to keep compatibility with 4.1 API, where updateTemplateCmd and updateIsoCmd will return a simpler TemplateResponse
// compared to listTemplates and listIsos.
@Override
public TemplateResponse newUpdateResponse(TemplateJoinVO result) {
TemplateResponse response = new TemplateResponse();
response.setId(result.getUuid());
response.setName(result.getName());
response.setDisplayText(result.getDisplayText());
response.setPublic(result.isPublicTemplate());
response.setCreated(result.getCreated());
response.setFormat(result.getFormat());
response.setOsTypeId(result.getGuestOSUuid());
response.setOsTypeName(result.getGuestOSName());
response.setBootable(result.isBootable());
response.setHypervisor(result.getHypervisorType().toString());
// populate owner.
ApiResponseHelper.populateOwner(response, result);
// populate domain
response.setDomainId(result.getDomainUuid());
response.setDomainName(result.getDomainName());
// set details map
if (result.getDetailName() != null) {
Map<String, String> details = new HashMap<String, String>();
details.put(result.getDetailName(), result.getDetailValue());
response.setDetails(details);
}
// update tag information
long tag_id = result.getTagId();
if (tag_id > 0) {
ResourceTagJoinVO vtag = ApiDBUtils.findResourceTagViewById(tag_id);
if (vtag != null) {
response.addTag(ApiDBUtils.newResourceTagResponse(vtag, false));
}
}
response.setObjectName("iso");
return response;
}
@Override
public TemplateResponse setTemplateResponse(TemplateResponse templateResponse, TemplateJoinVO template) {
// update details map
if (template.getDetailName() != null) {
Map<String, String> details = templateResponse.getDetails();
if (details == null) {
details = new HashMap<String, String>();
}
details.put(template.getDetailName(), template.getDetailValue());
templateResponse.setDetails(details);
}
// update tag information
long tag_id = template.getTagId();
if (tag_id > 0) {
ResourceTagJoinVO vtag = ApiDBUtils.findResourceTagViewById(tag_id);
if (vtag != null) {
templateResponse.addTag(ApiDBUtils.newResourceTagResponse(vtag, false));
}
}
return templateResponse;
}
@Override
public TemplateResponse newIsoResponse(TemplateJoinVO iso) {
TemplateResponse isoResponse = new TemplateResponse();
isoResponse.setId(iso.getUuid());
isoResponse.setName(iso.getName());
isoResponse.setDisplayText(iso.getDisplayText());
isoResponse.setPublic(iso.isPublicTemplate());
isoResponse.setExtractable(iso.isExtractable() && !(iso.getTemplateType() == TemplateType.PERHOST));
isoResponse.setCreated(iso.getCreatedOnStore());
if (iso.getTemplateType() == TemplateType.PERHOST) {
// for xs-tools.iso and vmware-tools.iso, we didn't download, but is ready to use.
isoResponse.setReady(true);
} else {
isoResponse.setReady(iso.getState() == ObjectInDataStoreStateMachine.State.Ready);
}
isoResponse.setBootable(iso.isBootable());
isoResponse.setFeatured(iso.isFeatured());
isoResponse.setCrossZones(iso.isCrossZones());
isoResponse.setPublic(iso.isPublicTemplate());
isoResponse.setChecksum(iso.getChecksum());
isoResponse.setOsTypeId(iso.getGuestOSUuid());
isoResponse.setOsTypeName(iso.getGuestOSName());
// populate owner.
ApiResponseHelper.populateOwner(isoResponse, iso);
// populate domain
isoResponse.setDomainId(iso.getDomainUuid());
isoResponse.setDomainName(iso.getDomainName());
Account caller = CallContext.current().getCallingAccount();
boolean isAdmin = false;
if ((caller == null) || BaseCmd.isAdmin(caller.getType())) {
isAdmin = true;
}
// If the user is an admin, add the template download status
if (isAdmin || caller.getId() == iso.getAccountId()) {
// add download status
if (iso.getDownloadState() != Status.DOWNLOADED) {
String isoStatus = "Processing";
if (iso.getDownloadState() == VMTemplateHostVO.Status.DOWNLOADED) {
isoStatus = "Download Complete";
} else if (iso.getDownloadState() == VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS) {
if (iso.getDownloadPercent() == 100) {
isoStatus = "Installing ISO";
} else {
isoStatus = iso.getDownloadPercent() + "% Downloaded";
}
} else {
isoStatus = iso.getErrorString();
}
isoResponse.setStatus(isoStatus);
} else {
isoResponse.setStatus("Successfully Installed");
}
}
if (iso.getDataCenterId() > 0) {
isoResponse.setZoneId(iso.getDataCenterUuid());
isoResponse.setZoneName(iso.getDataCenterName());
}
Long isoSize = iso.getSize();
if (isoSize > 0) {
isoResponse.setSize(isoSize);
}
// update tag information
long tag_id = iso.getTagId();
if (tag_id > 0) {
ResourceTagJoinVO vtag = ApiDBUtils.findResourceTagViewById(tag_id);
if (vtag != null) {
isoResponse.addTag(ApiDBUtils.newResourceTagResponse(vtag, false));
}
}
isoResponse.setObjectName("iso");
return isoResponse;
}
@Override
public List<TemplateJoinVO> newTemplateView(VirtualMachineTemplate template) {
SearchCriteria<TemplateJoinVO> sc = tmpltIdSearch.create();
sc.setParameters("id", template.getId());
return searchIncludingRemoved(sc, null, null, false);
}
@Override
public List<TemplateJoinVO> newTemplateView(VirtualMachineTemplate template, long zoneId, boolean readyOnly) {
SearchCriteria<TemplateJoinVO> sc = tmpltZoneSearch.create();
sc.setParameters("id", template.getId());
sc.setParameters("dataCenterId", zoneId);
if (readyOnly) {
sc.setParameters("state", TemplateState.Ready);
}
return searchIncludingRemoved(sc, null, null, false);
}
@Override
public List<TemplateJoinVO> searchByTemplateZonePair(String... idPairs) {
// set detail batch query size
int DETAILS_BATCH_SIZE = 2000;
String batchCfg = _configDao.getValue("detail.batch.query.size");
if (batchCfg != null) {
DETAILS_BATCH_SIZE = Integer.parseInt(batchCfg);
}
// query details by batches
List<TemplateJoinVO> uvList = new ArrayList<TemplateJoinVO>();
// query details by batches
int curr_index = 0;
if (idPairs.length > DETAILS_BATCH_SIZE) {
while ((curr_index + DETAILS_BATCH_SIZE) <= idPairs.length) {
String[] labels = new String[DETAILS_BATCH_SIZE];
for (int k = 0, j = curr_index; j < curr_index + DETAILS_BATCH_SIZE; j++, k++) {
labels[k] = idPairs[j];
}
SearchCriteria<TemplateJoinVO> sc = tmpltIdPairSearch.create();
sc.setParameters("tempZonePairIN", labels);
List<TemplateJoinVO> vms = searchIncludingRemoved(sc, null, null, false);
if (vms != null) {
uvList.addAll(vms);
}
curr_index += DETAILS_BATCH_SIZE;
}
}
if (curr_index < idPairs.length) {
int batch_size = (idPairs.length - curr_index);
String[] labels = new String[batch_size];
for (int k = 0, j = curr_index; j < curr_index + batch_size; j++, k++) {
labels[k] = idPairs[j];
}
SearchCriteria<TemplateJoinVO> sc = tmpltIdPairSearch.create();
sc.setParameters("tempZonePairIN", labels);
List<TemplateJoinVO> vms = searchIncludingRemoved(sc, null, null, false);
if (vms != null) {
uvList.addAll(vms);
}
}
return uvList;
}
@Override
public List<TemplateJoinVO> listActiveTemplates(long storeId) {
SearchCriteria<TemplateJoinVO> sc = activeTmpltSearch.create();
sc.setParameters("store_id", storeId);
sc.setParameters("type", TemplateType.USER);
return searchIncludingRemoved(sc, null, null, false);
}
}
|
package com.voxela.gov.events;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import com.mewin.WGRegionEvents.events.RegionLeaveEvent;
import com.voxela.gov.Main;
import com.voxela.gov.players.primeminister.PrimeMinisterPlayer;
import net.md_5.bungee.api.ChatColor;
public class LeaveRegionEvent implements Listener {
@EventHandler
public void onRegionLeave(RegionLeaveEvent e) {
if (!(PrimeMinisterPlayer.playerIsPrimeMinister(e.getPlayer()))) return;
if (e.getRegion().getId().equals("primeminister") && e.isCancellable()) {
e.setCancelled(true);
e.getPlayer().sendMessage(Main.gamePrefix + ChatColor.RED + "You may not leave the Prime Minister's mansion.");
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pe.gob.mimp.gis.entity;
import java.io.Serializable;
import java.util.Date;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author Hariki
*/
public class Cancha implements Serializable {
private Integer CoCancha;
private String NoCancha;
private Integer CoLocal;
private Integer CoTipoCancha;
private Integer Qtlargo;
private Integer Qtancho;
private Integer CoPersona;
private Integer FlEstado;
/**
* @return the CoCancha
*/
public Cancha() {}
public Cancha(Integer CoCancha, String NoCancha, Integer CoLocal,Integer CoTipoCancha,
Integer Qtlargo, Integer Qtancho, Integer CoPersona, Integer FlEstado ) {
this.CoCancha=CoCancha;
this.NoCancha = NoCancha;
this.CoLocal = CoLocal;
this.CoTipoCancha =CoTipoCancha;
this.Qtlargo = Qtlargo;
this.Qtancho = Qtancho;
this.CoPersona = CoPersona;
this.FlEstado = FlEstado;
}
public Cancha(String NoCancha, Integer CoLocal,Integer CoTipoCancha,Integer Qtlargo,Integer Qtancho,
Integer CoPersona,Integer FlEstado) {
this.NoCancha = NoCancha;
this.CoLocal = CoLocal;
this.CoTipoCancha = CoTipoCancha;
this.Qtlargo = Qtlargo;
this.Qtancho = Qtancho;
this.CoPersona = CoPersona;
this.FlEstado = FlEstado;
}
public Cancha(String NoCancha,Integer CoLocal) {
this.NoCancha = NoCancha;
this.CoLocal = CoLocal;
}
public Integer getCoCancha() {
return CoCancha;
}
/**
* @param CoCancha the CoCancha to set
*/
public void setCoCancha(Integer CoCancha) {
this.CoCancha = CoCancha;
}
/**
* @return the NoCancha
*/
public String getNoCancha() {
return NoCancha;
}
/**
* @param NoCancha the NoCancha to set
*/
public void setNoCancha(String NoCancha) {
this.NoCancha = NoCancha;
}
/**
* @return the CoLocal
*/
public Integer getCoLocal() {
return CoLocal;
}
/**
* @param CoLocal the CoLocal to set
*/
public void setCoLocal(Integer CoLocal) {
this.CoLocal = CoLocal;
}
/**
* @return the CoTipoCancha
*/
public Integer getCoTipoCancha() {
return CoTipoCancha;
}
/**
* @param CoTipoCancha the CoTipoCancha to set
*/
public void setCoTipoCancha(Integer CoTipoCancha) {
this.CoTipoCancha = CoTipoCancha;
}
/**
* @return the Qtlargo
*/
public Integer getQtlargo() {
return Qtlargo;
}
/**
* @param Qtlargo the Qtlargo to set
*/
public void setQtlargo(Integer Qtlargo) {
this.Qtlargo = Qtlargo;
}
/**
* @return the QtAncho
*/
public Integer getQtAncho() {
return Qtancho;
}
/**
* @param QtAncho the QtAncho to set
*/
public void setQtAncho(Integer Qtancho) {
this.Qtancho = Qtancho;
}
/**
* @return the CoPersona
*/
public Integer getCoPersona() {
return CoPersona;
}
/**
* @param CoPersona the CoPersona to set
*/
public void setCoPersona(Integer CoPersona) {
this.CoPersona = CoPersona;
}
/**
* @return the FlEstado
*/
public Integer getFlEstado() {
return FlEstado;
}
/**
* @param FlEstado the FlEstado to set
*/
public void setFlEstado(Integer FlEstado) {
this.FlEstado = FlEstado;
}
}
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.indexing.snapshot;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.io.ByteArraySequence;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.CompressionUtil;
import com.intellij.util.ExceptionUtil;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.indexing.*;
import com.intellij.util.indexing.impl.IndexDebugProperties;
import com.intellij.util.indexing.impl.InputData;
import com.intellij.util.indexing.impl.forward.AbstractForwardIndexAccessor;
import com.intellij.util.indexing.impl.forward.AbstractMapForwardIndexAccessor;
import com.intellij.util.indexing.impl.forward.PersistentMapBasedForwardIndex;
import com.intellij.util.indexing.impl.perFileVersion.PersistentSubIndexerRetriever;
import com.intellij.util.indexing.impl.storage.VfsAwareMapReduceIndex;
import com.intellij.util.io.*;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.LongAdder;
@ApiStatus.Internal
public class SnapshotInputMappings<Key, Value> implements UpdatableSnapshotInputMappingIndex<Key, Value, FileContent> {
private static final Logger LOG = Logger.getInstance(SnapshotInputMappings.class);
public static int getVersion() {
assert FileBasedIndex.ourSnapshotMappingsEnabled;
return 0xFFF + // base index version modifier
1 // snapshot input mappings version
;
}
private final ID<Key, Value> myIndexId;
private final DataExternalizer<Map<Key, Value>> myMapExternalizer;
private final DataExternalizer<Value> myValueExternalizer;
private final DataIndexer<Key, Value, FileContent> myIndexer;
@NotNull
private final PersistentMapBasedForwardIndex myContents;
@NotNull
private final SnapshotHashEnumeratorService.HashEnumeratorHandle myEnumeratorHandle;
private volatile PersistentHashMap<Integer, String> myIndexingTrace;
private final Statistics myStatistics = IndexDebugProperties.DEBUG ? new Statistics() : null;
private final HashIdForwardIndexAccessor<Key, Value, FileContent> myHashIdForwardIndexAccessor;
private final CompositeHashIdEnumerator myCompositeHashIdEnumerator;
private PersistentSubIndexerRetriever<?, ?> mySubIndexerRetriever;
public SnapshotInputMappings(@NotNull IndexExtension<Key, Value, FileContent> indexExtension,
@NotNull AbstractMapForwardIndexAccessor<Key, Value, ?> accessor) throws IOException {
myIndexId = (ID<Key, Value>)indexExtension.getName();
boolean storeOnlySingleValue = indexExtension instanceof SingleEntryFileBasedIndexExtension;
myMapExternalizer = storeOnlySingleValue ? null : new InputMapExternalizer<>(indexExtension);
myValueExternalizer = storeOnlySingleValue ? new NullableDataExternalizer<>(indexExtension.getValueExternalizer()) : null;
myIndexer = indexExtension.getIndexer();
myContents = createContentsIndex();
myHashIdForwardIndexAccessor = new HashIdForwardIndexAccessor<>(this, accessor);
myIndexingTrace = IndexDebugProperties.EXTRA_SANITY_CHECKS ? createIndexingTrace() : null;
myEnumeratorHandle = SnapshotHashEnumeratorService.getInstance().createHashEnumeratorHandle(myIndexId);
if (VfsAwareMapReduceIndex.isCompositeIndexer(myIndexer)) {
myCompositeHashIdEnumerator = new CompositeHashIdEnumerator(myIndexId);
} else {
myCompositeHashIdEnumerator = null;
}
}
public HashIdForwardIndexAccessor<Key, Value, FileContent> getForwardIndexAccessor() {
return myHashIdForwardIndexAccessor;
}
public File getInputIndexStorageFile() {
return new File(IndexInfrastructure.getIndexRootDir(myIndexId), "fileIdToHashId");
}
@NotNull
@Override
public Map<Key, Value> readData(int hashId) throws IOException {
return ObjectUtils.notNull(doReadData(hashId), Collections.emptyMap());
}
@Nullable
@Override
public InputData<Key, Value> readData(@NotNull FileContent content) throws IOException {
if (!((FileContentImpl)content).isPhysicalContent()) {
throw new IllegalArgumentException("Non-physical data are not allowed.");
}
int hashId = getHashId(content);
Map<Key, Value> data = doReadData(hashId);
if (myStatistics != null) {
myStatistics.update(data == null);
}
if (data != null && IndexDebugProperties.EXTRA_SANITY_CHECKS) {
Map<Key, Value> contentData = myIndexer.map(content);
boolean sameValueForSavedIndexedResultAndCurrentOne;
if (myIndexer instanceof SingleEntryIndexer) {
Value contentValue = ContainerUtil.getFirstItem(contentData.values());
Value value = ContainerUtil.getFirstItem(data.values());
sameValueForSavedIndexedResultAndCurrentOne = Comparing.equal(contentValue, value);
}
else {
sameValueForSavedIndexedResultAndCurrentOne = contentData.equals(data);
}
if (!sameValueForSavedIndexedResultAndCurrentOne) {
LOG.error(
"Unexpected difference in indexing of" +
"\n" + getContentDebugData(content) +
"\n by index " + myIndexId +
"\nprevious indexed info " + myIndexingTrace.get(hashId) +
"\ndiff " + buildDiff(data, contentData));
}
}
return data == null ? null : new HashedInputData<>(data, hashId);
}
@Nullable
private Map<Key, Value> doReadData(int hashId) throws IOException {
ByteArraySequence byteSequence = readContents(hashId);
return byteSequence != null ? deserialize(byteSequence) : null;
}
@NotNull
private Map<Key, Value> deserialize(@NotNull ByteArraySequence byteSequence) throws IOException {
if (myMapExternalizer != null) {
return AbstractForwardIndexAccessor.deserializeFromByteSeq(byteSequence, myMapExternalizer);
} else {
assert myValueExternalizer != null;
Value value = AbstractForwardIndexAccessor.deserializeFromByteSeq(byteSequence, myValueExternalizer);
if (value == null && !((SingleEntryIndexer<?>)myIndexer).isAcceptNullValues()) {
return Collections.emptyMap();
}
//noinspection unchecked
return Collections.singletonMap((Key)Integer.valueOf(0), value);
}
}
@NotNull
private ByteArraySequence serializeData(@NotNull Map<Key, Value> data) throws IOException {
if (myMapExternalizer != null) {
return AbstractForwardIndexAccessor.serializeToByteSeq(data, myMapExternalizer, data.size() * 4);
} else {
assert myValueExternalizer != null;
return AbstractForwardIndexAccessor.serializeToByteSeq(ContainerUtil.getFirstItem(data.values()), myValueExternalizer, 4);
}
}
@Override
public InputData<Key, Value> putData(@NotNull FileContent content, @NotNull InputData<Key, Value> data) throws IOException {
int hashId;
InputData<Key, Value> result;
if (data instanceof HashedInputData) {
hashId = ((HashedInputData<Key, Value>)data).getHashId();
result = data;
} else {
hashId = getHashId(content);
result = hashId == 0 ? InputData.empty() : new HashedInputData<>(data.getKeyValues(), hashId);
}
boolean saved = savePersistentData(data.getKeyValues(), hashId);
if (IndexDebugProperties.EXTRA_SANITY_CHECKS) {
if (saved) {
try {
myIndexingTrace.put(hashId, getContentDebugData(content) + "," + ExceptionUtil.getThrowableText(new Throwable()));
}
catch (IOException ex) {
LOG.error(ex);
}
}
}
return result;
}
@NotNull
private String getContentDebugData(@NotNull FileContent input) {
FileContentImpl content = (FileContentImpl) input;
List<String> data = new ArrayList<>();
data.add(content.getFile().getPath());
data.add(content.getFileType().getName());
data.add(content.getCharset().name());
if (VfsAwareMapReduceIndex.isCompositeIndexer(myIndexer)) {
data.add("composite indexer: " + mySubIndexerRetriever.getVersion(content));
}
return "[" + StringUtil.join(data, ";") + "]";
}
private int getHashId(@Nullable FileContent content) throws IOException {
if (content == null) {
return 0;
}
int hash = doGetContentHash((FileContentImpl)content);
if (myCompositeHashIdEnumerator != null) {
int subIndexerTypeId = mySubIndexerRetriever.getFileIndexerId(content);
hash = myCompositeHashIdEnumerator.enumerate(hash, subIndexerTypeId);
}
return hash;
}
@Override
public void flush() {
myContents.force();
if (myIndexingTrace != null) myIndexingTrace.force();
if (myCompositeHashIdEnumerator != null) myCompositeHashIdEnumerator.force();
}
@Override
public void clear() throws IOException {
try {
if (myCompositeHashIdEnumerator != null) {
try {
myCompositeHashIdEnumerator.clear();
}
catch (IOException e) {
LOG.error(e);
}
}
if (myIndexingTrace != null) {
PersistentHashMap.deleteMap(myIndexingTrace);
myIndexingTrace = createIndexingTrace();
}
} finally {
try {
myContents.clear();
}
catch (IOException e) {
LOG.error(e);
}
}
}
@Override
public void close() {
IOUtil.closeSafe(LOG, myContents, myIndexingTrace, myCompositeHashIdEnumerator);
myEnumeratorHandle.release();
}
@NotNull
private PersistentMapBasedForwardIndex createContentsIndex() throws IOException {
final File saved = new File(IndexInfrastructure.getPersistentIndexRootDir(myIndexId), "values");
try {
return new PersistentMapBasedForwardIndex(saved.toPath(), false);
}
catch (IOException ex) {
IOUtil.deleteAllFilesStartingWith(saved);
throw ex;
}
}
private PersistentHashMap<Integer, String> createIndexingTrace() throws IOException {
final File mapFile = new File(IndexInfrastructure.getIndexRootDir(myIndexId), "indextrace");
try {
return new PersistentHashMap<>(mapFile.toPath(), EnumeratorIntegerDescriptor.INSTANCE,
new DataExternalizer<String>() {
@Override
public void save(@NotNull DataOutput out, String value) throws IOException {
out.write((byte[])CompressionUtil.compressStringRawBytes(value));
}
@Override
public String read(@NotNull DataInput in) throws IOException {
byte[] b = new byte[((InputStream)in).available()];
in.readFully(b);
return (String)CompressionUtil.uncompressStringRawBytes(b);
}
}, 4096);
}
catch (IOException ex) {
IOUtil.deleteAllFilesStartingWith(mapFile);
throw ex;
}
}
private ByteArraySequence readContents(int hashId) throws IOException {
return myContents.get(hashId);
}
// TODO replace it with constructor parameter
public void setSubIndexerRetriever(@NotNull PersistentSubIndexerRetriever<?, ?> retriever) {
assert myCompositeHashIdEnumerator != null;
mySubIndexerRetriever = retriever;
}
@NotNull
private Integer doGetContentHash(FileContentImpl content) throws IOException {
Integer previouslyCalculatedContentHashId = content.getUserData(ourContentHashIdKey);
if (previouslyCalculatedContentHashId == null) {
byte[] hash = IndexedHashesSupport.getOrInitIndexedHash(content);
previouslyCalculatedContentHashId = myEnumeratorHandle.enumerateHash(hash);
content.putUserData(ourContentHashIdKey, previouslyCalculatedContentHashId);
}
return previouslyCalculatedContentHashId;
}
private static final com.intellij.openapi.util.Key<Integer> ourContentHashIdKey = com.intellij.openapi.util.Key.create("saved.content.hash.id");
private StringBuilder buildDiff(Map<Key, Value> data, Map<Key, Value> contentData) {
StringBuilder moreInfo = new StringBuilder();
if (contentData.size() != data.size()) {
moreInfo.append("Indexer has different number of elements, previously ").append(data.size()).append(" after ")
.append(contentData.size()).append("\n");
} else {
moreInfo.append("total ").append(contentData.size()).append(" entries\n");
}
for(Map.Entry<Key, Value> keyValueEntry:contentData.entrySet()) {
if (!data.containsKey(keyValueEntry.getKey())) {
moreInfo.append("Previous data doesn't contain:").append(keyValueEntry.getKey()).append( " with value ").append(keyValueEntry.getValue()).append("\n");
}
else {
Value value = data.get(keyValueEntry.getKey());
if (!Comparing.equal(keyValueEntry.getValue(), value)) {
moreInfo.append("Previous data has different value for key:").append(keyValueEntry.getKey()).append( ", new value ").append(keyValueEntry.getValue()).append( ", oldValue:").append(value).append("\n");
}
}
}
for(Map.Entry<Key, Value> keyValueEntry:data.entrySet()) {
if (!contentData.containsKey(keyValueEntry.getKey())) {
moreInfo.append("New data doesn't contain:").append(keyValueEntry.getKey()).append( " with value ").append(keyValueEntry.getValue()).append("\n");
}
else {
Value value = contentData.get(keyValueEntry.getKey());
if (!Comparing.equal(keyValueEntry.getValue(), value)) {
moreInfo.append("New data has different value for key:").append(keyValueEntry.getKey()).append( " new value ").append(value).append( ", oldValue:").append(keyValueEntry.getValue()).append("\n");
}
}
}
return moreInfo;
}
private boolean savePersistentData(@NotNull Map<Key, Value> data, int id) {
try {
if (myContents.containsMapping(id)) return false;
ByteArraySequence bytes = serializeData(data);
myContents.put(id, bytes);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
return true;
}
@ApiStatus.Internal
public void dumpStatistics() {
if (myStatistics != null) {
myStatistics.dumpStatistics();
}
}
private class Statistics {
private final LongAdder totalRequests = new LongAdder();
private final LongAdder totalMisses = new LongAdder();
void update(boolean miss) {
totalRequests.increment();
if (miss) {
totalMisses.increment();
}
}
void dumpStatistics() {
long requests = totalRequests.longValue();
long misses = totalMisses.longValue();
String message =
"Snapshot mappings stats for " + myIndexId +
". requests: " + requests +
", hits: " + (requests - misses) +
", misses: " + misses;
LOG.info(message);
}
}
}
|
/*
* 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 dk.statsbiblioteket.summa.common.filter.object;
import dk.statsbiblioteket.summa.common.Record;
import dk.statsbiblioteket.summa.common.configuration.Configuration;
import dk.statsbiblioteket.summa.common.filter.Payload;
import junit.framework.TestCase;
import java.io.StringReader;
/**
* Test cases for {@link ScriptFilter}
*/
public class ScriptFilterTest extends TestCase {
public PayloadBufferFilter prepareFilterChain(ObjectFilter filter,
Record... records) {
// Set up the source filter
PushFilter source = new PushFilter(records.length+1, 2048);
for (int i = 0; i < records.length; i++) {
Payload p = new Payload(records[i]);
source.add(p);
}
source.signalEOF();
// Set up the endpoint filter
PayloadBufferFilter buf = new PayloadBufferFilter(
Configuration.newMemoryBased());
// Connect filters
filter.setSource(source);
buf.setSource(filter);
return buf;
}
public void testRenameRecordIdJS() throws Exception {
ObjectFilter filter = new ScriptFilter(
new StringReader("payload.getRecord().setId('processed');"));
PayloadBufferFilter buf = prepareFilterChain(
filter,
new Record("id1", "base1", "test content 1".getBytes()),
new Record("id2", "base1", "test content 2".getBytes()));
// Flush the filter chain
while (buf.pump()){}
assertEquals(2, buf.size());
assertEquals("processed", buf.get(0).getRecord().getId());
assertEquals("processed", buf.get(1).getRecord().getId());
}
public void testDropAllJS() throws Exception {
ObjectFilter filter = new ScriptFilter(
new StringReader("allowPayload = false;"));
PayloadBufferFilter buf = prepareFilterChain(
filter,
new Record("id1", "base1", "test content 1".getBytes()),
new Record("id2", "base1", "test content 2".getBytes()));
// Flush the filter chain
while (buf.pump()){}
assertEquals(0, buf.size());
}
public void testDropOneJS() throws Exception {
ObjectFilter filter = new ScriptFilter(
new StringReader(
"if (payload.getRecord().getId() == 'id1') { " +
" allowPayload = false;" +
"}"));
PayloadBufferFilter buf = prepareFilterChain(
filter,
new Record("id1", "base1", "test content 1".getBytes()),
new Record("id2", "base1", "test content 2".getBytes()));
// Flush the filter chain
while (buf.pump()){}
assertEquals(1, buf.size());
assertEquals("id2", buf.get(0).getRecord().getId());
}
public void testBasePrefixRecordIdJS() throws Exception {
ObjectFilter filter = new ScriptFilter(
new StringReader(
"var record = payload.getRecord();"+
"if (!record.getId().startsWith(record.getBase())) {"+
" record.setId(record.getBase() + \"_\" + record.getId())"+
"}"+
"if (record.getId().endsWith('taboo')) {"+
" allowPayload = false;" +
" feedbackMessage = 'Record id ends with \"taboo\"';" +
"}"));
PayloadBufferFilter buf = prepareFilterChain(
filter,
new Record("id1", "base1", "test content 1".getBytes()),
new Record("id2", "base1", "test content 2".getBytes()),
new Record("taboo", "base1", "test content".getBytes()));
// Flush the filter chain
while (buf.pump()){}
assertEquals(2, buf.size());
assertEquals("base1_id1", buf.get(0).getRecord().getId());
assertEquals("base1_id2", buf.get(1).getRecord().getId());
}
public void testInlineScript() throws Exception {
ObjectFilter filter = new ScriptFilter(
Configuration.load("common/inline-js.xml"));
PayloadBufferFilter buf = prepareFilterChain(
filter,
new Record("id1", "base1", "test content 1".getBytes()));
// Flush the filter chain
while (buf.pump()){}
assertEquals(1, buf.size());
assertEquals("inlineJavascript", buf.get(0).getRecord().getId());
}
public void testJavaCallbacksExternal() throws Exception {
ObjectFilter filter = new ScriptFilter(
Configuration.newMemoryBased(
ScriptFilter.CONF_SCRIPT_URL, "common/java-callbacks.js"
));
PayloadBufferFilter buf = prepareFilterChain(
filter,
new Record("id1", "base1",
("<root>\n"
+ " <child1>Foo</child1>\n"
+ " <child2>Bar</child2>\n"
+ "</root>\n").getBytes()));
// Flush the filter chain
while (buf.pump()) { }
assertEquals(1, buf.size());
assertEquals("Bar", buf.get(0).getRecord().getContentAsUTF8());
}
}
|
package com.ls.drupalcon.model.managers;
import com.ls.drupal.AbstractBaseDrupalEntity;
import com.ls.drupal.DrupalClient;
import com.ls.drupalcon.app.App;
import com.ls.drupalcon.model.dao.EventDao;
import com.ls.drupalcon.model.data.Event;
import com.ls.drupalcon.model.data.EventDetailsEvent;
import com.ls.drupalcon.model.data.TimeRange;
import java.util.List;
public class EventManager extends SynchronousItemManager<Event.Holder, Object, String> {
protected EventDao mEventDao;
public EventManager(DrupalClient client) {
super(client);
mEventDao = new EventDao(App.getContext());
}
@Override
protected AbstractBaseDrupalEntity getEntityToFetch(DrupalClient client, Object requestParams) {
return null;
}
@Override
protected String getEntityRequestTag(Object params) {
return null;
}
@Override
protected boolean storeResponse(Event.Holder requestResponse, String tag) {
return false;
}
public void saveEventSpeakers(Event data) {
Long eventId = data.getId();
List<Long> speakerEventIds = mEventDao.selectSpeakerEventIds();
for (Long speakerId : data.getSpeakers()) {
if (!speakerEventIds.contains(eventId)) {
mEventDao.insertEventSpeaker(eventId, speakerId);
}
}
}
public void deleteEvent(Event data) {
mEventDao.deleteDataSafe(data.getId());
mEventDao.deleteEventAndSpeakerByEvent(data.getId());
}
public EventDetailsEvent getEventById(long id) {
return mEventDao.getEventById(id);
}
public List<TimeRange> getDistrictTimeRangeSafe(int eventClass, long day) {
return mEventDao.selectDistrictTimeRangeSafe(eventClass, day);
}
public List<TimeRange> getDistrictTimeRangeSafe(int eventClass, long day, List<Long> levelIds, List<Long> trackIds) {
return mEventDao.selectDistrictTimeRangeByLevelTrackIdsSafe(eventClass, day, levelIds, trackIds);
}
public List<Long> getEventSpeakerSafe(long id) {
return mEventDao.selectEventSpeakersSafe(id);
}
public List<Event> getEventsByIdsAndDaySafe(long day) {
FavoriteManager favoriteManager = new FavoriteManager();
List<Long> favoriteEventIds = favoriteManager.getFavoriteEventsSafe();
return mEventDao.selectEventsByIdsAndDaySafe(favoriteEventIds, day);
}
public void clear() {
mEventDao.deleteAll();
}
public EventDao getEventDao() {
return mEventDao;
}
}
|
/*
* 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 uk.co.objectconnexions.expressiveobjects.viewer.dnd.calendar;
import java.util.Calendar;
public class MonthCells extends Cells {
public MonthCells(final Cells replacing) {
super(replacing);
}
@Override
public int defaultColumns() {
return 4;
}
@Override
public int defaultRows() {
return 3;
}
@Override
public void roundDown() {
date.set(Calendar.MONTH, 0);
}
@Override
public void add(final int interval) {
date.add(Calendar.MONTH, interval);
}
@Override
public String title(final int cell) {
final Calendar d = (Calendar) date.clone();
d.add(Calendar.MONTH, cell);
final String displayName = monthFormat.format(d.getTime()) + " " + d.get(Calendar.YEAR);
return displayName;
}
@Override
protected int period(final Calendar forDate) {
return forDate.get(Calendar.YEAR) * 12 - forDate.get(Calendar.MONTH);
}
}
|
// The MIT License (MIT)
//
// Copyright (c) 2018 - Present Onshape Inc.
//
// 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.onshape.api.responses;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.onshape.api.Onshape;
import com.onshape.api.types.AbstractResponseObject;
import java.lang.Boolean;
import java.lang.Override;
import java.lang.String;
import java.util.Map;
/**
* Object used in calls to getElementMetadata API endpoint.
* © 2018-Present Onshape Inc.
*/
public final class MetadataGetElementMetadataResponseParts extends AbstractResponseObject {
/**
* Part properties
*/
@JsonProperty("properties")
public Map[] properties;
/**
* Part id
*/
@JsonProperty("partId")
public String partId;
/**
* Part type
*/
@JsonProperty("partType")
public String partType;
/**
* True if part is a mesh
*/
@JsonProperty("isMesh")
public Boolean isMesh;
/**
* Part's thumbnail
*/
@JsonProperty("thumbnail")
public Map thumbnail;
/**
* URI of Part metadata
*/
@JsonProperty("href")
public String href;
/**
* Get Part properties
*
* @return Part properties
*
*/
public final Map[] getProperties() {
return this.properties;
}
/**
* Get Part id
*
* @return Part id
*
*/
public final String getPartId() {
return this.partId;
}
/**
* Get Part type
*
* @return Part type
*
*/
public final String getPartType() {
return this.partType;
}
/**
* Get True if part is a mesh
*
* @return True if part is a mesh
*
*/
public final Boolean getIsMesh() {
return this.isMesh;
}
/**
* Get Part's thumbnail
*
* @return Part's thumbnail
*
*/
public final Map getThumbnail() {
return this.thumbnail;
}
/**
* Get URI of Part metadata
*
* @return URI of Part metadata
*
*/
public final String getHref() {
return this.href;
}
@Override
public String toString() {
return Onshape.toString(this);
}
}
|
/*
* 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.mapper;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.collect.CopyOnWriteHashMap;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.logging.ESLoggerFactory;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.support.XContentMapValues;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class ObjectMapper extends Mapper implements Cloneable {
private static final DeprecationLogger deprecationLogger = new DeprecationLogger(ESLoggerFactory.getLogger(ObjectMapper.class));
public static final String CONTENT_TYPE = "object";
public static final String NESTED_CONTENT_TYPE = "nested";
public static class Defaults {
public static final boolean ENABLED = true;
public static final Nested NESTED = Nested.NO;
public static final Dynamic DYNAMIC = null; // not set, inherited from root
}
public enum Dynamic {
TRUE,
FALSE,
STRICT
}
public static class Nested {
public static final Nested NO = new Nested(false, false, false);
public static Nested newNested(boolean includeInParent, boolean includeInRoot) {
return new Nested(true, includeInParent, includeInRoot);
}
private final boolean nested;
private final boolean includeInParent;
private final boolean includeInRoot;
private Nested(boolean nested, boolean includeInParent, boolean includeInRoot) {
this.nested = nested;
this.includeInParent = includeInParent;
this.includeInRoot = includeInRoot;
}
public boolean isNested() {
return nested;
}
public boolean isIncludeInParent() {
return includeInParent;
}
public boolean isIncludeInRoot() {
return includeInRoot;
}
}
public static class Builder<T extends Builder, Y extends ObjectMapper> extends Mapper.Builder<T, Y> {
protected boolean enabled = Defaults.ENABLED;
protected Nested nested = Defaults.NESTED;
protected Dynamic dynamic = Defaults.DYNAMIC;
protected final List<Mapper.Builder> mappersBuilders = new ArrayList<>();
public Builder(String name) {
super(name);
this.builder = (T) this;
}
public T enabled(boolean enabled) {
this.enabled = enabled;
return builder;
}
public T dynamic(Dynamic dynamic) {
this.dynamic = dynamic;
return builder;
}
public T nested(Nested nested) {
this.nested = nested;
return builder;
}
public T add(Mapper.Builder builder) {
mappersBuilders.add(builder);
return this.builder;
}
@Override
public Y build(BuilderContext context) {
context.path().add(name);
Map<String, Mapper> mappers = new HashMap<>();
for (Mapper.Builder builder : mappersBuilders) {
Mapper mapper = builder.build(context);
Mapper existing = mappers.get(mapper.simpleName());
if (existing != null) {
mapper = existing.merge(mapper);
}
mappers.put(mapper.simpleName(), mapper);
}
context.path().remove();
ObjectMapper objectMapper = createMapper(name, context.path().pathAsText(name), enabled, nested, dynamic,
mappers, context.indexSettings());
return (Y) objectMapper;
}
protected ObjectMapper createMapper(String name, String fullPath, boolean enabled, Nested nested, Dynamic dynamic,
Map<String, Mapper> mappers, @Nullable Settings settings) {
return new ObjectMapper(name, fullPath, enabled, nested, dynamic, mappers, settings);
}
}
public static class TypeParser implements Mapper.TypeParser {
@Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
ObjectMapper.Builder builder = new Builder(name);
parseNested(name, node, builder, parserContext);
for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) {
Map.Entry<String, Object> entry = iterator.next();
String fieldName = entry.getKey();
Object fieldNode = entry.getValue();
if (parseObjectOrDocumentTypeProperties(fieldName, fieldNode, parserContext, builder)) {
iterator.remove();
}
}
return builder;
}
protected static boolean parseObjectOrDocumentTypeProperties(String fieldName, Object fieldNode, ParserContext parserContext, ObjectMapper.Builder builder) {
if (fieldName.equals("dynamic")) {
String value = fieldNode.toString();
if (value.equalsIgnoreCase("strict")) {
builder.dynamic(Dynamic.STRICT);
} else {
boolean dynamic = XContentMapValues.nodeBooleanValue(fieldNode, fieldName + ".dynamic");
builder.dynamic(dynamic ? Dynamic.TRUE : Dynamic.FALSE);
}
return true;
} else if (fieldName.equals("enabled")) {
builder.enabled(XContentMapValues.nodeBooleanValue(fieldNode, fieldName + ".enabled"));
return true;
} else if (fieldName.equals("properties")) {
if (fieldNode instanceof Collection && ((Collection) fieldNode).isEmpty()) {
// nothing to do here, empty (to support "properties: []" case)
} else if (!(fieldNode instanceof Map)) {
throw new ElasticsearchParseException("properties must be a map type");
} else {
parseProperties(builder, (Map<String, Object>) fieldNode, parserContext);
}
return true;
} else if (fieldName.equals("include_in_all")) {
deprecationLogger.deprecated("[include_in_all] is deprecated, the _all field have been removed in this version");
return true;
}
return false;
}
protected static void parseNested(String name, Map<String, Object> node, ObjectMapper.Builder builder,
ParserContext parserContext) {
boolean nested = false;
boolean nestedIncludeInParent = false;
boolean nestedIncludeInRoot = false;
Object fieldNode = node.get("type");
if (fieldNode!=null) {
String type = fieldNode.toString();
if (type.equals(CONTENT_TYPE)) {
builder.nested = Nested.NO;
} else if (type.equals(NESTED_CONTENT_TYPE)) {
nested = true;
} else {
throw new MapperParsingException("Trying to parse an object but has a different type [" + type + "] for [" + name + "]");
}
}
fieldNode = node.get("include_in_parent");
if (fieldNode != null) {
nestedIncludeInParent = XContentMapValues.nodeBooleanValue(fieldNode, name + ".include_in_parent");
node.remove("include_in_parent");
}
fieldNode = node.get("include_in_root");
if (fieldNode != null) {
nestedIncludeInRoot = XContentMapValues.nodeBooleanValue(fieldNode, name + ".include_in_root");
node.remove("include_in_root");
}
if (nested) {
builder.nested = Nested.newNested(nestedIncludeInParent, nestedIncludeInRoot);
}
}
protected static void parseProperties(ObjectMapper.Builder objBuilder, Map<String, Object> propsNode, ParserContext parserContext) {
Iterator<Map.Entry<String, Object>> iterator = propsNode.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Object> entry = iterator.next();
String fieldName = entry.getKey();
// Should accept empty arrays, as a work around for when the
// user can't provide an empty Map. (PHP for example)
boolean isEmptyList = entry.getValue() instanceof List && ((List<?>) entry.getValue()).isEmpty();
if (entry.getValue() instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, Object> propNode = (Map<String, Object>) entry.getValue();
String type;
Object typeNode = propNode.get("type");
if (typeNode != null) {
type = typeNode.toString();
} else {
// lets see if we can derive this...
if (propNode.get("properties") != null) {
type = ObjectMapper.CONTENT_TYPE;
} else if (propNode.size() == 1 && propNode.get("enabled") != null) {
// if there is a single property with the enabled
// flag on it, make it an object
// (usually, setting enabled to false to not index
// any type, including core values, which
type = ObjectMapper.CONTENT_TYPE;
} else {
throw new MapperParsingException("No type specified for field [" + fieldName + "]");
}
}
Mapper.TypeParser typeParser = parserContext.typeParser(type);
if (typeParser == null) {
throw new MapperParsingException("No handler for type [" + type + "] declared on field [" + fieldName + "]");
}
String[] fieldNameParts = fieldName.split("\\.");
String realFieldName = fieldNameParts[fieldNameParts.length - 1];
Mapper.Builder<?,?> fieldBuilder = typeParser.parse(realFieldName, propNode, parserContext);
for (int i = fieldNameParts.length - 2; i >= 0; --i) {
ObjectMapper.Builder<?, ?> intermediate = new ObjectMapper.Builder<>(fieldNameParts[i]);
intermediate.add(fieldBuilder);
fieldBuilder = intermediate;
}
objBuilder.add(fieldBuilder);
propNode.remove("type");
DocumentMapperParser.checkNoRemainingFields(fieldName, propNode, parserContext.indexVersionCreated());
iterator.remove();
} else if (isEmptyList) {
iterator.remove();
} else {
throw new MapperParsingException("Expected map for property [fields] on field [" + fieldName + "] but got a "
+ fieldName.getClass());
}
}
DocumentMapperParser.checkNoRemainingFields(propsNode, parserContext.indexVersionCreated(),
"DocType mapping definition has unsupported parameters: ");
}
}
private final String fullPath;
private final boolean enabled;
private final Nested nested;
private final String nestedTypePathAsString;
private final BytesRef nestedTypePathAsBytes;
private final Query nestedTypeFilter;
private volatile Dynamic dynamic;
private volatile CopyOnWriteHashMap<String, Mapper> mappers;
ObjectMapper(String name, String fullPath, boolean enabled, Nested nested, Dynamic dynamic,
Map<String, Mapper> mappers, Settings settings) {
super(name);
assert settings != null;
if (name.isEmpty()) {
throw new IllegalArgumentException("name cannot be empty string");
}
this.fullPath = fullPath;
this.enabled = enabled;
this.nested = nested;
this.dynamic = dynamic;
if (mappers == null) {
this.mappers = new CopyOnWriteHashMap<>();
} else {
this.mappers = CopyOnWriteHashMap.copyOf(mappers);
}
this.nestedTypePathAsString = "__" + fullPath;
this.nestedTypePathAsBytes = new BytesRef(nestedTypePathAsString);
this.nestedTypeFilter = new TermQuery(new Term(TypeFieldMapper.NAME, nestedTypePathAsBytes));
}
@Override
protected ObjectMapper clone() {
ObjectMapper clone;
try {
clone = (ObjectMapper) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
return clone;
}
/**
* Build a mapping update with the provided sub mapping update.
*/
public ObjectMapper mappingUpdate(Mapper mapper) {
ObjectMapper mappingUpdate = clone();
// reset the sub mappers
mappingUpdate.mappers = new CopyOnWriteHashMap<>();
mappingUpdate.putMapper(mapper);
return mappingUpdate;
}
@Override
public String name() {
return this.fullPath;
}
@Override
public String typeName() {
return CONTENT_TYPE;
}
public boolean isEnabled() {
return this.enabled;
}
public Mapper getMapper(String field) {
return mappers.get(field);
}
public Nested nested() {
return this.nested;
}
public Query nestedTypeFilter() {
return this.nestedTypeFilter;
}
protected void putMapper(Mapper mapper) {
mappers = mappers.copyAndPut(mapper.simpleName(), mapper);
}
@Override
public Iterator<Mapper> iterator() {
return mappers.values().iterator();
}
public String fullPath() {
return this.fullPath;
}
public String nestedTypePathAsString() {
return nestedTypePathAsString;
}
public final Dynamic dynamic() {
return dynamic;
}
/**
* Returns the parent {@link ObjectMapper} instance of the specified object mapper or <code>null</code> if there
* isn't any.
*/
public ObjectMapper getParentObjectMapper(MapperService mapperService) {
int indexOfLastDot = fullPath().lastIndexOf('.');
if (indexOfLastDot != -1) {
String parentNestObjectPath = fullPath().substring(0, indexOfLastDot);
return mapperService.getObjectMapper(parentNestObjectPath);
} else {
return null;
}
}
/**
* Returns whether all parent objects fields are nested too.
*/
public boolean parentObjectMapperAreNested(MapperService mapperService) {
for (ObjectMapper parent = getParentObjectMapper(mapperService);
parent != null;
parent = parent.getParentObjectMapper(mapperService)) {
if (parent.nested().isNested() == false) {
return false;
}
}
return true;
}
@Override
public ObjectMapper merge(Mapper mergeWith) {
if (!(mergeWith instanceof ObjectMapper)) {
throw new IllegalArgumentException("Can't merge a non object mapping [" + mergeWith.name() + "] with an object mapping [" + name() + "]");
}
ObjectMapper mergeWithObject = (ObjectMapper) mergeWith;
ObjectMapper merged = clone();
merged.doMerge(mergeWithObject);
return merged;
}
protected void doMerge(final ObjectMapper mergeWith) {
if (nested().isNested()) {
if (!mergeWith.nested().isNested()) {
throw new IllegalArgumentException("object mapping [" + name() + "] can't be changed from nested to non-nested");
}
} else {
if (mergeWith.nested().isNested()) {
throw new IllegalArgumentException("object mapping [" + name() + "] can't be changed from non-nested to nested");
}
}
if (mergeWith.dynamic != null) {
this.dynamic = mergeWith.dynamic;
}
for (Mapper mergeWithMapper : mergeWith) {
Mapper mergeIntoMapper = mappers.get(mergeWithMapper.simpleName());
checkEnabledFieldChange(mergeWith, mergeWithMapper, mergeIntoMapper);
Mapper merged;
if (mergeIntoMapper == null) {
// no mapping, simply add it
merged = mergeWithMapper;
} else {
// root mappers can only exist here for backcompat, and are merged in Mapping
merged = mergeIntoMapper.merge(mergeWithMapper);
}
putMapper(merged);
}
}
private static void checkEnabledFieldChange(ObjectMapper mergeWith, Mapper mergeWithMapper, Mapper mergeIntoMapper) {
if (mergeIntoMapper instanceof ObjectMapper && mergeWithMapper instanceof ObjectMapper) {
final ObjectMapper mergeIntoObjectMapper = (ObjectMapper) mergeIntoMapper;
final ObjectMapper mergeWithObjectMapper = (ObjectMapper) mergeWithMapper;
if (mergeIntoObjectMapper.isEnabled() != mergeWithObjectMapper.isEnabled()) {
final String path = mergeWith.fullPath() + "." + mergeWithObjectMapper.simpleName() + ".enabled";
throw new MapperException("Can't update attribute for type [" + path + "] in index mapping");
}
}
}
@Override
public ObjectMapper updateFieldType(Map<String, MappedFieldType> fullNameToFieldType) {
List<Mapper> updatedMappers = null;
for (Mapper mapper : this) {
Mapper updated = mapper.updateFieldType(fullNameToFieldType);
if (mapper != updated) {
if (updatedMappers == null) {
updatedMappers = new ArrayList<>();
}
updatedMappers.add(updated);
}
}
if (updatedMappers == null) {
return this;
}
ObjectMapper updated = clone();
for (Mapper updatedMapper : updatedMappers) {
updated.putMapper(updatedMapper);
}
return updated;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
toXContent(builder, params, null);
return builder;
}
public void toXContent(XContentBuilder builder, Params params, ToXContent custom) throws IOException {
builder.startObject(simpleName());
if (nested.isNested()) {
builder.field("type", NESTED_CONTENT_TYPE);
if (nested.isIncludeInParent()) {
builder.field("include_in_parent", true);
}
if (nested.isIncludeInRoot()) {
builder.field("include_in_root", true);
}
} else if (mappers.isEmpty() && custom == null) { // only write the object content type if there are no properties, otherwise, it is automatically detected
builder.field("type", CONTENT_TYPE);
}
if (dynamic != null) {
builder.field("dynamic", dynamic.name().toLowerCase(Locale.ROOT));
}
if (enabled != Defaults.ENABLED) {
builder.field("enabled", enabled);
}
if (custom != null) {
custom.toXContent(builder, params);
}
doXContent(builder, params);
// sort the mappers so we get consistent serialization format
Mapper[] sortedMappers = mappers.values().stream().toArray(size -> new Mapper[size]);
Arrays.sort(sortedMappers, new Comparator<Mapper>() {
@Override
public int compare(Mapper o1, Mapper o2) {
return o1.name().compareTo(o2.name());
}
});
int count = 0;
for (Mapper mapper : sortedMappers) {
if (!(mapper instanceof MetadataFieldMapper)) {
if (count++ == 0) {
builder.startObject("properties");
}
mapper.toXContent(builder, params);
}
}
if (count > 0) {
builder.endObject();
}
builder.endObject();
}
protected void doXContent(XContentBuilder builder, Params params) throws IOException {
}
}
|
package org.gavin.search.hawkeye.result;
import java.util.List;
/**
* ---------------------------------------------------
* File: PagingQueryResult
* Package: org.gavin.search.hawkeye.result
* Project: hawkeye
* ---------------------------------------------------
* Created by gavinguan on 2018/1/23 13:04.
* Copyright © 2018 gavinguan. All rights reserved.
*/
public class PagingQueryResult<T> {
private int totalHits;
private List<T> pagingDatas;
private int pageIndex;
private int pageSize;
public PagingQueryResult(int totalHits, List<T> pagingDatas, int pageIndex, int pageSize) {
this.totalHits = totalHits;
this.pagingDatas = pagingDatas;
this.pageIndex = pageIndex;
this.pageSize = pageSize;
}
public int getTotalHits() {
return totalHits;
}
public List<T> getPagingDatas() {
return pagingDatas;
}
public int getPageIndex() {
return pageIndex;
}
public int getPageSize() {
return pageSize;
}
}
|
package seedu.modulink.model.person;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static seedu.modulink.testutil.Assert.assertThrows;
import org.junit.jupiter.api.Test;
public class GitHubUsernameTest {
@Test
public void constructor_invalidName_throwsIllegalArgumentException() {
String invalidGitHubUsername = "";
assertThrows(IllegalArgumentException.class, () -> new GitHubUsername(invalidGitHubUsername));
}
@Test
public void isValidGitHubUsername() {
// invalid GitHub username
assertFalse(GitHubUsername.isValidUsername("")); // empty string
assertFalse(GitHubUsername.isValidUsername(" ")); // spaces only
assertFalse(GitHubUsername.isValidUsername("^")); // only non-alphanumeric characters
assertFalse(GitHubUsername.isValidUsername("@peter")); // contains non-alphanumeric characters
assertFalse(GitHubUsername.isValidUsername("alex yeoh")); // contains spaces
assertFalse(GitHubUsername.isValidUsername("alex_yeoh")); // contains underscore
// valid GitHub username
assertTrue(GitHubUsername.isValidUsername("peterjack")); // alphabets only
assertTrue(GitHubUsername.isValidUsername("12345")); // numbers only
assertTrue(GitHubUsername.isValidUsername("peterthe2nd")); // alphanumeric characters
assertTrue(GitHubUsername.isValidUsername("CapitalTan")); // with capital letters
assertTrue(GitHubUsername.isValidUsername("alexa-tan-test")); // with hyphens
// valid null GitHub username
assertTrue(GitHubUsername.isValidUsername(null));
}
}
|
package org.egorlitvinenko.certification.oca.book1.chapter4;
/**
* @author Egor Litvinenko
*/
public class Q12 {
}
class RopeSwing {
private static Rope rope1 = new Rope();
private static Rope rope2 = new Rope();
{
System.out.println(rope1.length);
}
public static void main(String[] args) {
rope1.length = 2;
rope2.length = 8;
System.out.println(Rope.length);
}
}
class Rope {
public static int length = 0;
}
|
/*
* Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0, which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package com.sun.xml.ws.security.policy;
/**
*
* @author Nithya Subramanian
*/
public interface SessionManagerStore {
public String getSessionTimeOut();
public String getSessionThreshold();
}
|
package com.vmware.avi.vro.model;
import java.util.*;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.vmware.o11n.plugin.sdk.annotation.VsoFinder;
import com.vmware.o11n.plugin.sdk.annotation.VsoMethod;
import com.vmware.o11n.plugin.sdk.annotation.VsoObject;
import com.vmware.avi.vro.Constants;
import org.springframework.stereotype.Service;
/**
* The GslbClientIpAddrGroup is a POJO class extends AviRestResource that used for creating
* GslbClientIpAddrGroup.
*
* @version 1.0
* @since
*
*/
@VsoObject(create = false, name = "GslbClientIpAddrGroup")
@VsoFinder(name = Constants.FINDER_VRO_GSLBCLIENTIPADDRGROUP)
@JsonIgnoreProperties(ignoreUnknown = true)
@Service
public class GslbClientIpAddrGroup extends AviRestResource {
@JsonProperty("addrs")
@JsonInclude(Include.NON_NULL)
private List<IpAddr> addrs = null;
@JsonProperty("prefixes")
@JsonInclude(Include.NON_NULL)
private List<IpAddrPrefix> prefixes = null;
@JsonProperty("ranges")
@JsonInclude(Include.NON_NULL)
private List<IpAddrRange> ranges = null;
@JsonProperty("type")
@JsonInclude(Include.NON_NULL)
private String type = "GSLB_IP_PUBLIC";
/**
* This is the getter method this will return the attribute value.
* Configure ip address(es).
* Field introduced in 17.1.2.
* @return addrs
*/
@VsoMethod
public List<IpAddr> getAddrs() {
return addrs;
}
/**
* This is the setter method. this will set the addrs
* Configure ip address(es).
* Field introduced in 17.1.2.
* @return addrs
*/
@VsoMethod
public void setAddrs(List<IpAddr> addrs) {
this.addrs = addrs;
}
/**
* This is the setter method this will set the addrs
* Configure ip address(es).
* Field introduced in 17.1.2.
* @return addrs
*/
@VsoMethod
public GslbClientIpAddrGroup addAddrsItem(IpAddr addrsItem) {
if (this.addrs == null) {
this.addrs = new ArrayList<IpAddr>();
}
this.addrs.add(addrsItem);
return this;
}
/**
* This is the getter method this will return the attribute value.
* Configure ip address prefix(es).
* Field introduced in 17.1.2.
* @return prefixes
*/
@VsoMethod
public List<IpAddrPrefix> getPrefixes() {
return prefixes;
}
/**
* This is the setter method. this will set the prefixes
* Configure ip address prefix(es).
* Field introduced in 17.1.2.
* @return prefixes
*/
@VsoMethod
public void setPrefixes(List<IpAddrPrefix> prefixes) {
this.prefixes = prefixes;
}
/**
* This is the setter method this will set the prefixes
* Configure ip address prefix(es).
* Field introduced in 17.1.2.
* @return prefixes
*/
@VsoMethod
public GslbClientIpAddrGroup addPrefixesItem(IpAddrPrefix prefixesItem) {
if (this.prefixes == null) {
this.prefixes = new ArrayList<IpAddrPrefix>();
}
this.prefixes.add(prefixesItem);
return this;
}
/**
* This is the getter method this will return the attribute value.
* Configure ip address range(s).
* Field introduced in 17.1.2.
* @return ranges
*/
@VsoMethod
public List<IpAddrRange> getRanges() {
return ranges;
}
/**
* This is the setter method. this will set the ranges
* Configure ip address range(s).
* Field introduced in 17.1.2.
* @return ranges
*/
@VsoMethod
public void setRanges(List<IpAddrRange> ranges) {
this.ranges = ranges;
}
/**
* This is the setter method this will set the ranges
* Configure ip address range(s).
* Field introduced in 17.1.2.
* @return ranges
*/
@VsoMethod
public GslbClientIpAddrGroup addRangesItem(IpAddrRange rangesItem) {
if (this.ranges == null) {
this.ranges = new ArrayList<IpAddrRange>();
}
this.ranges.add(rangesItem);
return this;
}
/**
* This is the getter method this will return the attribute value.
* Specify whether this client ip address range is public or private.
* Enum options - GSLB_IP_PUBLIC, GSLB_IP_PRIVATE.
* Field introduced in 17.1.2.
* Default value when not specified in API or module is interpreted by Avi Controller as GSLB_IP_PUBLIC.
* @return type
*/
@VsoMethod
public String getType() {
return type;
}
/**
* This is the setter method to the attribute.
* Specify whether this client ip address range is public or private.
* Enum options - GSLB_IP_PUBLIC, GSLB_IP_PRIVATE.
* Field introduced in 17.1.2.
* Default value when not specified in API or module is interpreted by Avi Controller as GSLB_IP_PUBLIC.
* @param type set the type.
*/
@VsoMethod
public void setType(String type) {
this.type = type;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
GslbClientIpAddrGroup objGslbClientIpAddrGroup = (GslbClientIpAddrGroup) o;
return Objects.equals(this.type, objGslbClientIpAddrGroup.type)&&
Objects.equals(this.addrs, objGslbClientIpAddrGroup.addrs)&&
Objects.equals(this.ranges, objGslbClientIpAddrGroup.ranges)&&
Objects.equals(this.prefixes, objGslbClientIpAddrGroup.prefixes);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class GslbClientIpAddrGroup {\n");
sb.append(" addrs: ").append(toIndentedString(addrs)).append("\n");
sb.append(" prefixes: ").append(toIndentedString(prefixes)).append("\n");
sb.append(" ranges: ").append(toIndentedString(ranges)).append("\n");
sb.append(" type: ").append(toIndentedString(type)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2012 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
package com.google.appinventor.components.annotations;
/**
* Categories for Simple properties. This is used only for documentation.
*
*/
public enum PropertyCategory {
// TODO(user): i18n category names
BEHAVIOR("Behavior"),
APPEARANCE("Appearance"),
LINKED_DATA("Linked Data"),
DEPRECATED("Deprecated"),
UNSET("Unspecified");
private String name;
PropertyCategory(String categoryName) {
name = categoryName;
}
public String getName() {
return name;
}
}
|
package com.planet_ink.coffee_mud.Locales;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2004-2018 Bo Zimmerman
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.
*/
public class SaltWaterThinSurface extends SaltWaterSurface
{
@Override
public String ID()
{
return "SaltWaterThinSurface";
}
public SaltWaterThinSurface()
{
super();
name = "the water";
basePhyStats.setWeight(2);
recoverPhyStats();
climask = Places.CLIMASK_WET;
}
@Override
public int domainType()
{
return Room.DOMAIN_OUTDOORS_WATERSURFACE;
}
@Override
protected String UnderWaterLocaleID()
{
return "UnderSaltWaterThinGrid";
}
@Override
protected int UnderWaterDomainType()
{
return Room.DOMAIN_OUTDOORS_UNDERWATER;
}
@Override
protected boolean IsUnderWaterFatClass(Room thatSea)
{
return (thatSea instanceof UnderSaltWaterGrid)
|| (thatSea instanceof UnderSaltWaterThinGrid)
|| (thatSea instanceof UnderSaltWaterColumnGrid);
}
@Override
public CMObject newInstance()
{
if (!CMSecurity.isDisabled(CMSecurity.DisFlag.THINGRIDS))
return super.newInstance();
return new SaltWaterSurface().newInstance();
}
}
|
/*
* Copyright (c) 2020, Jaisel Rahman <jaiselrahman@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 com.jaiselrahman.filepicker.model;
import android.content.ContentResolver;
import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.paging.LivePagedListBuilder;
import androidx.paging.PagedList;
import com.jaiselrahman.filepicker.config.Configurations;
public class DirViewModel extends ViewModel {
public LiveData<PagedList<Dir>> dirs;
private DirViewModel(ContentResolver contentResolver, Configurations configs) {
DirDataSource.Factory dirDataSourceFactory = new DirDataSource.Factory(contentResolver, configs);
dirs = new LivePagedListBuilder<>(
dirDataSourceFactory,
new PagedList.Config.Builder()
.setPageSize(Configurations.PAGE_SIZE)
.setInitialLoadSizeHint(15)
.setMaxSize(Configurations.PAGE_SIZE * 3)
.setPrefetchDistance(Configurations.PREFETCH_DISTANCE)
.setEnablePlaceholders(false)
.build()
).build();
}
public void refresh() {
if (dirs.getValue() != null)
dirs.getValue().getDataSource().invalidate();
}
public static class Factory extends ViewModelProvider.NewInstanceFactory {
private final ContentResolver contentResolver;
private final Configurations configs;
public Factory(ContentResolver contentResolver, Configurations configs) {
this.contentResolver = contentResolver;
this.configs = configs;
}
@NonNull
@Override
@SuppressWarnings("unchecked")
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
return (T) new DirViewModel(contentResolver, configs);
}
}
}
|
package service;
import po.User;
import java.util.List;
/**
* Created by Administrator on 2017/7/11.
*/
public interface SysService {
List<User> findAll();
User getUser(String name, String password);
}
|
package com.github.zhgxun.leetcode.tree;
import com.github.zhgxun.leetcode.TreeNode;
/**
* 面试题 04.10. 检查子树
* <p>
* https://leetcode-cn.com/problems/check-subtree-lcci/
* <p>
* 检查子树。你有两棵非常大的二叉树:T1,有几万个节点;T2,有几万个节点。设计一个算法,判断 T2 是否为 T1 的子树。
* <p>
* 如果 T1 有这么一个节点 n,其子树与 T2 一模一样,则 T2 为 T1 的子树,也就是说,从节点 n 处把树砍断,得到的树与 T2 完全相同。
*/
public class CheckSubTree {
public static void main(String[] args) {
TreeNode t1 = new TreeNode(1);
t1.left = new TreeNode(2);
t1.right = new TreeNode(3);
TreeNode t2 = t1.left;
System.out.println(new CheckSubTree().checkSubTree(t1, t2));
}
public boolean checkSubTree(TreeNode t1, TreeNode t2) {
if (t2 == null) {
return true;
}
TreeNode tree = findTreeNode(t1, t2);
if (tree == null) {
return false;
}
return compare(tree, t2);
}
// 从树中寻找某个节点, 不存在时返回null
private TreeNode findTreeNode(TreeNode source, TreeNode target) {
if (source == null) {
return null;
}
if (source.val == target.val) {
return source;
}
if (source.left != null) {
TreeNode find = findTreeNode(source.left, target);
if (find != null) {
return find;
}
}
if (source.right != null) {
return findTreeNode(source.right, target);
}
return null;
}
// 比较两棵树的所有节点值是否相同而非树本身是否相同
private boolean compare(TreeNode left, TreeNode right) {
if (left == null && right == null) {
return true;
}
if (left == null || right == null) {
return false;
}
return left.val == right.val && compare(left.left, right.left) && compare(left.right, right.right);
}
}
|
package uk.gov.ida.integrationtest.hub.samlsoapproxy.apprule.support;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.collect.ImmutableList;
import httpstub.HttpStubRule;
import uk.gov.ida.hub.samlsoapproxy.Urls;
import uk.gov.ida.hub.samlsoapproxy.builders.CertificateDtoBuilder;
import uk.gov.ida.hub.samlsoapproxy.builders.MatchingServiceConfigEntityDataDtoBuilder;
import uk.gov.ida.hub.samlsoapproxy.contract.MatchingServiceConfigEntityDataDto;
import uk.gov.ida.hub.samlsoapproxy.domain.CertificateDto;
import uk.gov.ida.shared.utils.string.StringEncoding;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import static javax.ws.rs.core.Response.Status.OK;
public class ConfigStubRule extends HttpStubRule {
public void setupStubForMatchingServiceHealthChecks(URI matchingServiceUri) throws JsonProcessingException {
Collection<MatchingServiceConfigEntityDataDto> matchingServiceConfigEntityDataDtos = ImmutableList.of(MatchingServiceConfigEntityDataDtoBuilder.aMatchingServiceConfigEntityDataDto().withUri(matchingServiceUri).build());
register(Urls.ConfigUrls.ENABLED_MATCHING_SERVICES_RESOURCE, Response.Status.OK.getStatusCode(), matchingServiceConfigEntityDataDtos);
}
public void setupStubForCertificates(String issuer) throws JsonProcessingException {
CertificateDto signingCertificate = new CertificateDtoBuilder().withIssuerId(issuer).withKeyUse(CertificateDto.KeyUse.Signing).build();
CertificateDto encryptionCertificate = new CertificateDtoBuilder().withIssuerId(issuer).withKeyUse(CertificateDto.KeyUse.Encryption).build();
registerStubForCertificates(issuer, signingCertificate, encryptionCertificate);
}
public void setupStubForCertificates(String issuer, String signingCertString, String encryptionCertString) throws JsonProcessingException {
CertificateDto signingCertificate = new CertificateDtoBuilder().withIssuerId(issuer).withCertificate(signingCertString).withKeyUse(CertificateDto.KeyUse.Signing).build();
CertificateDto encryptionCertificate = new CertificateDtoBuilder().withIssuerId(issuer).withCertificate(encryptionCertString).withKeyUse(CertificateDto.KeyUse.Encryption).build();
registerStubForCertificates(issuer, signingCertificate, encryptionCertificate);
}
private void registerStubForCertificates(String issuer, CertificateDto signingCertificate, CertificateDto encryptionCertificate) throws JsonProcessingException {
String signingCertificateUri = UriBuilder.fromPath(Urls.ConfigUrls.SIGNATURE_VERIFICATION_CERTIFICATES_RESOURCE).buildFromEncoded(StringEncoding.urlEncode(issuer)).toASCIIString();
Collection<CertificateDto> signingCertificates = new ArrayList<>();
signingCertificates.add(signingCertificate);
register(signingCertificateUri, OK.getStatusCode(), signingCertificates);
String encryptionCertificateUri = UriBuilder.fromPath(Urls.ConfigUrls.ENCRYPTION_CERTIFICATES_RESOURCE).buildFromEncoded(StringEncoding.urlEncode(issuer)).toASCIIString();
register(encryptionCertificateUri, OK.getStatusCode(), encryptionCertificate);
}
public void setUpStubForMatchingServiceHealthCheckRequest(URI msaUri, String msaEntityId) throws JsonProcessingException {
final MatchingServiceConfigEntityDataDto matchingServiceConfigEntityDataDto = new MatchingServiceConfigEntityDataDto(msaEntityId, msaUri, "rp-entity-id", true, false, null);
Collection<MatchingServiceConfigEntityDataDto> matchingServices = ImmutableList.of(matchingServiceConfigEntityDataDto);
String uri = UriBuilder.fromPath(Urls.ConfigUrls.ENABLED_MATCHING_SERVICES_RESOURCE).build().getPath();
register(uri, OK.getStatusCode(), matchingServices);
}
public void setUpStubForForcedMatchingServiceHealthCheckRequest(URI msaUri, String msaEntityId) throws JsonProcessingException {
final MatchingServiceConfigEntityDataDto matchingServiceConfigEntityDataDto = new MatchingServiceConfigEntityDataDto(msaEntityId, msaUri, "rp-entity-id", false, false, null);
Collection<MatchingServiceConfigEntityDataDto> matchingServices = ImmutableList.of(matchingServiceConfigEntityDataDto);
String uri = UriBuilder.fromPath(Urls.ConfigUrls.ENABLED_MATCHING_SERVICES_RESOURCE).build().getPath();
register(uri, OK.getStatusCode(), matchingServices);
}
public void setUpStubForTwoMatchingServiceHealthCheckRequests(URI msaUri, String msaEntityId, URI msaUri2, String msaEntityId2) throws JsonProcessingException {
final MatchingServiceConfigEntityDataDto matchingServiceConfigEntityDataDto = new MatchingServiceConfigEntityDataDto(msaEntityId, msaUri, "rp-entity-id", true, false, null);
final MatchingServiceConfigEntityDataDto matchingServiceConfigEntityDataDto2 = new MatchingServiceConfigEntityDataDto(msaEntityId2, msaUri2, "rp-entity-id2", true, false, null);
Collection<MatchingServiceConfigEntityDataDto> matchingServices = ImmutableList.of(matchingServiceConfigEntityDataDto, matchingServiceConfigEntityDataDto2);
String uri = UriBuilder.fromPath(Urls.ConfigUrls.ENABLED_MATCHING_SERVICES_RESOURCE).build().getPath();
register(uri, OK.getStatusCode(), matchingServices);
}
}
|
/*
* Copyright 2017 StreamSets 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.streamsets.pipeline.stage.processor.fieldorder.config;
import com.streamsets.pipeline.api.base.BaseEnumChooserValues;
public class ExtraFieldActionValueChooser extends BaseEnumChooserValues<ExtraFieldAction> {
public ExtraFieldActionValueChooser() {
super(ExtraFieldAction.class);
}
}
|
package edu.mum.mpp.util;
import edu.mum.mpp.service.AsyncService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* Created by Lukman.Arogundade on 8/22/2016.
*/
@Component
public class ScheduledTasks {
private static final Logger logger = LoggerFactory.getLogger(ScheduledTasks.class);
@Autowired
AsyncService asyncService;
@Scheduled(fixedRateString = "${email-sender-scheduler-rate}")
public void SendQueuedEmails() {
logger.debug("Sending Queued Emails Scheduler called");
this.asyncService.sendQueuedEmails();
}
}
|
package com.haxademic.core.debug;
import processing.core.PApplet;
import com.haxademic.core.app.P;
public class Stats {
protected PApplet p;
protected int _frames = 0;
protected int _time, _timeLastFrame, _timeLastSecond;
protected int _fps = 0;
protected int _fpsMin = 1000;
protected int _fpsMax = 0;
protected int _ms = 0;
protected int _msMin = 1000;
protected int _msMax = 0;
/**
* Ported from https://github.com/mrdoob/stats.js
* @param p
*/
public Stats( PApplet p ) {
this.p = p;
_time = p.millis();
_timeLastFrame = _time;
_timeLastSecond = _time;
}
public int getFps() {
return _fps;
}
public int getFpsMin() {
return _fpsMin;
}
public int getFpsMax() {
return _fpsMax;
}
public int getMs() {
return _ms;
}
public int getMsMin() {
return _msMin;
}
public int getMsMax() {
return _msMax;
}
public void update() {
_time = p.millis();
_ms = _time - _timeLastFrame;
_msMin = Math.min( _msMin, _ms );
_msMax = Math.max( _msMax, _ms );
_timeLastFrame = _time;
_frames++;
if ( _time > _timeLastSecond + 1000 ) {
_fps = Math.round( ( _frames * 1000 ) / ( _time - _timeLastSecond ) );
_fpsMin = Math.min( _fpsMin, _fps );
_fpsMax = Math.max( _fpsMax, _fps );
_timeLastSecond = _time;
_frames = 0;
}
}
public void printStats() {
P.println( _ms + " MS (" + _msMin + "-" + _msMax + ")" );
P.println( _fps + " FPS (" + _fpsMin + "-" + _fpsMax + ")" );
}
}
|
package chapter3.section1;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.Stopwatch;
import util.ArrayGenerator;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Rene Argento on 28/04/17.
*/
public class Exercise33_DriverSelfOrganizingSearch {
public static void main(String[] args) {
int[] arraySizes = {1000, 10000, 100000, 1000000};
Map<Integer, Comparable[]> allInputArrays = new HashMap<>();
for(int i=0; i < arraySizes.length; i++) {
Comparable[] array = ArrayGenerator.generateOrderedArray(arraySizes[i]);
allInputArrays.put(i, array);
}
Exercise33_DriverSelfOrganizingSearch driverSelfOrganizingSearch = new Exercise33_DriverSelfOrganizingSearch();
driverSelfOrganizingSearch.doExperiment(allInputArrays);
}
private void doExperiment(Map<Integer, Comparable[]> allInputArrays) {
StdOut.printf("%10s %25s %25s\n", "Array Size | ", "Self-Organizing Search Time | ", "Default Binary Search Time");
for(int i = 0; i < allInputArrays.size(); i++) {
BinarySearchSymbolTable<Integer, Integer> binarySearchSymbolTable = new BinarySearchSymbolTable<>();
Exercise22_SelfOrganizingSearch selfOrganizingSearch = new Exercise22_SelfOrganizingSearch();
Exercise22_SelfOrganizingSearch.ArraySTSelfOrganizing<Integer, Integer> arraySTSelfOrganizing =
selfOrganizingSearch.new ArraySTSelfOrganizing<>(2);
Comparable[] array = allInputArrays.get(i);
double[] probabilityDistribution = new double[array.length];
for(int p = 0; p < array.length; p++) {
probabilityDistribution[p] = Math.pow((1.0 / 2.0), p + 1);
}
//Self-Organizing Search Symbol Table
Stopwatch selfOrganizingSearchTimer = new Stopwatch();
for(Comparable key : array) {
int randomValue = StdRandom.uniform(0, 2);
arraySTSelfOrganizing.put((int) key, randomValue);
}
for(int search = 0; search < 10 * array.length; search++) {
double keyProbabilityToSearch = StdRandom.uniform();
for(int p = 0; p < probabilityDistribution.length; p++) {
keyProbabilityToSearch -= probabilityDistribution[p];
if(keyProbabilityToSearch <= 0) {
//Search hit
arraySTSelfOrganizing.get((int) array[p]);
break;
}
}
}
double selfOrganizingSearchRunningTime = selfOrganizingSearchTimer.elapsedTime();
//Binary Search Symbol Table
Stopwatch binarySearchTimer = new Stopwatch();
for(Comparable key : array) {
int randomValue = StdRandom.uniform(0, 2);
binarySearchSymbolTable.put((int) key, randomValue);
}
for(int search = 0; search < 10 * array.length; search++) {
double keyProbabilityToSearch = StdRandom.uniform();
for(int p = 0; p < probabilityDistribution.length; p++) {
keyProbabilityToSearch -= probabilityDistribution[p];
if(keyProbabilityToSearch <= 0) {
//Search hit
binarySearchSymbolTable.get((int) array[p]);
break;
}
}
}
double binarySearchRunningTime = binarySearchTimer.elapsedTime();
printResults(array.length, selfOrganizingSearchRunningTime, binarySearchRunningTime);
}
}
private void printResults(int arraySize, double selfOrganizingSearchRunningTime, double binarySearchRunningTime) {
StdOut.printf("%10d %30.2f %29.2f\n", arraySize, selfOrganizingSearchRunningTime, binarySearchRunningTime);
}
}
|
package com.mikelau.countrypickerx;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import java.util.Locale;
public class CountryListAdapter extends BaseAdapter {
private final Context mContext;
private LayoutInflater inflater;
private List<Country> countries;
private boolean showDialingCode;
public CountryListAdapter(Context context, List<Country> countries, boolean showDialingCode) {
mContext = context;
this.countries = countries;
this.showDialingCode = showDialingCode;
inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return countries.size();
}
@Override
public Object getItem(int position) {
return countries.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
Item item;
Country country = countries.get(position);
if (convertView == null) {
item = new Item();
itemView = inflater.inflate(R.layout.item_country, parent, false);
item.setIcon((ImageView) itemView.findViewById(R.id.ivFlag));
item.setName((TextView) itemView.findViewById(R.id.tvName));
itemView.setTag(item);
} else {
item = (Item) itemView.getTag();
}
item.getName().setText(new Locale(mContext.getResources().getConfiguration().locale.getLanguage(),
country.getIsoCode()).getDisplayCountry() + (showDialingCode ?
" (+" + country.getDialingCode() + ")" : ""));
String drawableName = country.getIsoCode().toLowerCase(Locale.ENGLISH) + "_flag";
item.getIcon().setImageResource(CountryUtils.getMipmapResId(mContext, drawableName));
return itemView;
}
public static class Item {
private TextView name;
private ImageView icon;
public ImageView getIcon() {
return icon;
}
public void setIcon(ImageView icon) {
this.icon = icon;
}
public TextView getName() {
return name;
}
public void setName(TextView name) {
this.name = name;
}
}
}
|
package uk.nhs.careconnect.nosql.providers;
import ca.uhn.fhir.rest.api.MethodOutcome;
import org.hl7.fhir.dstu3.model.Bundle;
import org.hl7.fhir.dstu3.model.IdType;
import org.hl7.fhir.dstu3.model.OperationOutcome;
import org.hl7.fhir.instance.model.api.IIdType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import uk.nhs.careconnect.nosql.dao.BundleResponse;
import uk.nhs.careconnect.nosql.dao.IBundle;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.when;
import static uk.nhs.careconnect.nosql.support.testdata.BundleTestData.aBundleWithDocumentReference;
@RunWith(MockitoJUnitRunner.class)
public class BundleProviderTest {
private static final Bundle BUNDLE = aBundleWithDocumentReference();
private static final Boolean CREATED = true;
private static final Boolean UPDATED = false;
private static final String ID = "id-1";
private static final String OPERATION_OUTCOME_ID = "operation-outcome-id-1";
private static final OperationOutcome OPERATION_OUTCOME = anOperationOutcome();
@Mock
IBundle bundleDao;
@InjectMocks
private BundleProvider bundleProvider;
@Test
public void createTest() {
//setup
MethodOutcome expectedMethodOutcome = aMethodOutcome(CREATED);
when(bundleDao.create(BUNDLE, null, null)).thenReturn(aBundleResponseWithOperationOutcome());
//when
MethodOutcome actualMethodOutcome = bundleProvider.create(BUNDLE);
//then
assertThatMethodOutcomeIsEqual(actualMethodOutcome, expectedMethodOutcome);
}
@Test
public void updateTest() {
//setup
IdType bundleId = new IdType().setValue(ID);
String conditional = "true";
MethodOutcome expectedMethodOutcome = aMethodOutcome(UPDATED);
when(bundleDao.update(BUNDLE, bundleId, conditional)).thenReturn(aBundleResponseWithOperationOutcome());
//when
MethodOutcome actualMethodOutcome = bundleProvider.update(BUNDLE, bundleId, conditional);
//then
assertThatMethodOutcomeIsEqual(actualMethodOutcome, expectedMethodOutcome);
}
private BundleResponse aBundleResponseWithOperationOutcome() {
return new BundleResponse(OPERATION_OUTCOME, BUNDLE);
}
private MethodOutcome aMethodOutcome(Boolean created) {
return new MethodOutcome()
.setCreated(created)
.setId(aIIdType())
.setOperationOutcome(OPERATION_OUTCOME)
.setResource(BUNDLE);
}
private static IIdType aIIdType() {
return new IdType()
.setValue(ID);
}
private static OperationOutcome anOperationOutcome() {
OperationOutcome operationOutcome = new OperationOutcome();
operationOutcome.setId(OPERATION_OUTCOME_ID);
return operationOutcome;
}
private void assertThatMethodOutcomeIsEqual(MethodOutcome actual, MethodOutcome expected) {
assertThat(actual.getCreated(), is(expected.getCreated()));
assertThat(actual.getOperationOutcome(), is(expected.getOperationOutcome()));
assertThat(actual.getOperationOutcome().getIdElement(), is(expected.getOperationOutcome().getIdElement()));
assertThat(actual.getResource(), is(expected.getResource()));
}
}
|
package com.celerysoft.imagepager.view.indicator;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.celerysoft.imagepager.R;
import com.celerysoft.imagepager.util.DensityUtil;
/**
* Created by admin on 16/12/21.
* Indicator with dots.
*/
public class DotIndicator extends LinearLayout implements Indicator {
private static final String TAG = "DotIndicator";
private int mImageCount;
private int mCurrentImagePosition;
private int mSelectedImageResourceId = R.drawable.ic_selected;
private int mUnselectedImageResourceId = R.drawable.ic_unselected;
private String noImagesText;
public DotIndicator(Context context) {
super(context);
setOrientation(HORIZONTAL);
setBackgroundResource(R.drawable.indicator_background);
}
public void setNoImagesText(String noImagesText) {
this.noImagesText = noImagesText;
}
public void setSelectedImageResource(int resId) {
mSelectedImageResourceId = resId;
}
public void setUnselectedImageResource(int resId) {
mUnselectedImageResourceId = resId;
}
@Override public void onPageSelected(int position) {
mCurrentImagePosition = position;
updateUi(position);
}
@Override public void onPageDeleted() {
removeViewAt(mImageCount - 1);
mImageCount -= 1;
mCurrentImagePosition = mCurrentImagePosition < mImageCount ? mCurrentImagePosition : mImageCount - 1;
if (mImageCount <= 0) {
TextView textView = new TextView(getContext());
// TODO: remove hardcoded value(for default - ok, otherwise must be set by setter\builder method
textView.setTextSize(20);
String text = TextUtils.isEmpty(noImagesText) ? getContext().getString(R.string.no_images) : noImagesText;
textView.setText(text);
addView(textView);
if (mImageCount < 0) {
Log.e(TAG, "image count less than 0, it could not be happened!");
}
} else {
updateUi(mCurrentImagePosition);
}
}
@Override public void onPageAdapterChanged(int imageCount) {
mImageCount = imageCount;
mCurrentImagePosition = 0;
removeAllViews();
for (int i = 0; i < mImageCount; ++i) {
View view = new View(getContext());
if (i == 0) {
view.setBackgroundResource(mSelectedImageResourceId);
} else {
view.setBackgroundResource(mUnselectedImageResourceId);
}
addView(view);
view.getLayoutParams().width = DensityUtil.dp2px(getContext(), 12);
view.getLayoutParams().height = DensityUtil.dp2px(getContext(), 12);
view.requestLayout();
}
}
private void updateUi(int selectedImagePosition) {
int count = getChildCount();
for (int i = 0; i < count; ++i) {
View v = getChildAt(i);
if (i == selectedImagePosition) {
if (mSelectedImageResourceId != -1) {
v.setBackgroundResource(mSelectedImageResourceId);
}
} else {
if (mUnselectedImageResourceId != -1) {
v.setBackgroundResource(mUnselectedImageResourceId);
}
}
}
}
}
|
/*
* Copyright 2012-2017 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.inspector.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
* <p>
* Used as a response element in the <a>PreviewAgents</a> action.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/AgentPreview" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AgentPreview implements Serializable, Cloneable {
/**
* <p>
* The ID of the EC2 instance where the agent is installed.
* </p>
*/
private String agentId;
/**
* <p>
* The Auto Scaling group for the EC2 instance where the agent is installed.
* </p>
*/
private String autoScalingGroup;
/**
* <p>
* The ID of the EC2 instance where the agent is installed.
* </p>
*
* @param agentId
* The ID of the EC2 instance where the agent is installed.
*/
public void setAgentId(String agentId) {
this.agentId = agentId;
}
/**
* <p>
* The ID of the EC2 instance where the agent is installed.
* </p>
*
* @return The ID of the EC2 instance where the agent is installed.
*/
public String getAgentId() {
return this.agentId;
}
/**
* <p>
* The ID of the EC2 instance where the agent is installed.
* </p>
*
* @param agentId
* The ID of the EC2 instance where the agent is installed.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public AgentPreview withAgentId(String agentId) {
setAgentId(agentId);
return this;
}
/**
* <p>
* The Auto Scaling group for the EC2 instance where the agent is installed.
* </p>
*
* @param autoScalingGroup
* The Auto Scaling group for the EC2 instance where the agent is installed.
*/
public void setAutoScalingGroup(String autoScalingGroup) {
this.autoScalingGroup = autoScalingGroup;
}
/**
* <p>
* The Auto Scaling group for the EC2 instance where the agent is installed.
* </p>
*
* @return The Auto Scaling group for the EC2 instance where the agent is installed.
*/
public String getAutoScalingGroup() {
return this.autoScalingGroup;
}
/**
* <p>
* The Auto Scaling group for the EC2 instance where the agent is installed.
* </p>
*
* @param autoScalingGroup
* The Auto Scaling group for the EC2 instance where the agent is installed.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public AgentPreview withAutoScalingGroup(String autoScalingGroup) {
setAutoScalingGroup(autoScalingGroup);
return this;
}
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getAgentId() != null)
sb.append("AgentId: ").append(getAgentId()).append(",");
if (getAutoScalingGroup() != null)
sb.append("AutoScalingGroup: ").append(getAutoScalingGroup());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof AgentPreview == false)
return false;
AgentPreview other = (AgentPreview) obj;
if (other.getAgentId() == null ^ this.getAgentId() == null)
return false;
if (other.getAgentId() != null && other.getAgentId().equals(this.getAgentId()) == false)
return false;
if (other.getAutoScalingGroup() == null ^ this.getAutoScalingGroup() == null)
return false;
if (other.getAutoScalingGroup() != null && other.getAutoScalingGroup().equals(this.getAutoScalingGroup()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getAgentId() == null) ? 0 : getAgentId().hashCode());
hashCode = prime * hashCode + ((getAutoScalingGroup() == null) ? 0 : getAutoScalingGroup().hashCode());
return hashCode;
}
@Override
public AgentPreview clone() {
try {
return (AgentPreview) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
|
package neighbors.handler;
import lombok.RequiredArgsConstructor;
import neighbors.enums.CategoryCommand;
import neighbors.enums.MainCommand;
import neighbors.enums.bot.State;
import neighbors.enums.bot.Text;
import neighbors.utils.TelegramUtils;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.meta.api.methods.PartialBotApiMethod;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import neighbors.entity.User;
import neighbors.repository.UserRepository;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup;
import java.io.Serializable;
import java.util.List;
import static neighbors.utils.TelegramUtils.createButton;
@Component
@RequiredArgsConstructor
public class MenuHandler implements Handler {
private final UserRepository userRepository;
@Override
public List<PartialBotApiMethod<? extends Serializable>> handle(User user, String message) {
SendMessage sendMessage = TelegramUtils.createMessageTemplate(user);
if (MainCommand.RENT.equals(message)) {
sendMessage.setText("Выберите категорию товара");
sendMessage.setReplyMarkup(setUpInlineKeyboardMarkup());
user.setState(State.RENTING_SELECT_CATEGORY);
} else if (MainCommand.RENT_OUT.equals(message)) {
sendMessage.setText("Выберите категорию товара");
sendMessage.setReplyMarkup(setUpInlineKeyboardMarkup());
user.setState(State.RENTING_OUT_SELECT_CATEGORY);
} else if (MainCommand.GET_MY_ADVERTS.equals(message)) {
sendMessage.setText(Text.REQUEST_RENTING_OUT_NAME);
user.setState(State.GET_MY_ADVERTS);
} else if (MainCommand.GET_RENT_OUT_ADVERTS.equals(message)) {
sendMessage.setText(Text.REQUEST_RENTING_OUT_NAME);
user.setState(State.GET_RENT_OUT_ADVERTS);
} else if (MainCommand.GET_RENT_ADVERTS.equals(message)) {
sendMessage.setText(Text.REQUEST_RENTING_OUT_NAME);
user.setState(State.GET_RENT_ADVERTS);
}
userRepository.save(user);
return List.of(sendMessage);
}
private InlineKeyboardMarkup setUpInlineKeyboardMarkup() {
InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup();
inlineKeyboardMarkup.setKeyboard(List.of(
List.of(createButton("Ремонт", CategoryCommand.REPAIR_THINGS)),
List.of(createButton("Одежда", CategoryCommand.CLOTHES)),
List.of(createButton("Другое", CategoryCommand.OTHER))
));
return inlineKeyboardMarkup;
}
@Override
public List<State> operatedBotState() {
return null;
}
@Override
public List<String> operatedCallBackQuery() {
return List.of(
MainCommand.RENT,
MainCommand.RENT_OUT,
MainCommand.GET_MY_ADVERTS,
MainCommand.GET_RENT_OUT_ADVERTS,
MainCommand.GET_RENT_ADVERTS
);
}
}
|
// Targeted by JavaCPP version 1.5.5: DO NOT EDIT THIS FILE
package org.bytedeco.tensorflow;
import org.bytedeco.tensorflow.Allocator;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.javacpp.presets.javacpp.*;
import static org.bytedeco.tensorflow.global.tensorflow.*;
// -------------------------------------------------------------------
@Namespace("tensorflow") @NoOffset @Properties(inherit = org.bytedeco.tensorflow.presets.tensorflow.class)
public class OpDeprecation extends MessageLite {
static { Loader.load(); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public OpDeprecation(Pointer p) { super(p); }
/** Native array allocator. Access with {@link Pointer#position(long)}. */
public OpDeprecation(long size) { super((Pointer)null); allocateArray(size); }
private native void allocateArray(long size);
@Override public OpDeprecation position(long position) {
return (OpDeprecation)super.position(position);
}
@Override public OpDeprecation getPointer(long i) {
return new OpDeprecation((Pointer)this).position(position + i);
}
public OpDeprecation() { super((Pointer)null); allocate(); }
private native void allocate();
public OpDeprecation(@Const @ByRef OpDeprecation from) { super((Pointer)null); allocate(from); }
private native void allocate(@Const @ByRef OpDeprecation from);
public native @ByRef @Name("operator =") OpDeprecation put(@Const @ByRef OpDeprecation from);
public native Arena GetArena();
public native Pointer GetMaybeArenaPointer();
public static native @Cast("const google::protobuf::Descriptor*") Pointer descriptor();
public static native @Cast("const google::protobuf::Descriptor*") Pointer GetDescriptor();
public static native @Cast("const google::protobuf::Reflection*") Pointer GetReflection();
public static native @Const @ByRef OpDeprecation default_instance();
public static native void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
public static native @Const OpDeprecation internal_default_instance();
@MemberGetter public static native int kIndexInFileMessages();
public static final int kIndexInFileMessages = kIndexInFileMessages();
public native void UnsafeArenaSwap(OpDeprecation other);
public native void Swap(OpDeprecation other);
// implements Message ----------------------------------------------
public native OpDeprecation New();
public native OpDeprecation New(Arena arena);
public native void CopyFrom(@Cast("const google::protobuf::Message*") @ByRef MessageLite from);
public native void MergeFrom(@Cast("const google::protobuf::Message*") @ByRef MessageLite from);
public native void CopyFrom(@Const @ByRef OpDeprecation from);
public native void MergeFrom(@Const @ByRef OpDeprecation from);
public native void Clear();
public native @Cast("bool") boolean IsInitialized();
public native @Cast("size_t") long ByteSizeLong();
// #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
// #else
public native @Cast("bool") boolean MergePartialFromCodedStream(
CodedInputStream input);
// #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
public native void SerializeWithCachedSizes(
CodedOutputStream output);
public native @Cast("google::protobuf::uint8*") BytePointer InternalSerializeWithCachedSizesToArray(
@Cast("google::protobuf::uint8*") BytePointer target);
public native @Cast("google::protobuf::uint8*") ByteBuffer InternalSerializeWithCachedSizesToArray(
@Cast("google::protobuf::uint8*") ByteBuffer target);
public native @Cast("google::protobuf::uint8*") byte[] InternalSerializeWithCachedSizesToArray(
@Cast("google::protobuf::uint8*") byte[] target);
public native int GetCachedSize();
public native @ByVal @Cast("google::protobuf::Metadata*") Pointer GetMetadata();
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// string explanation = 2;
public native void clear_explanation();
@MemberGetter public static native int kExplanationFieldNumber();
public static final int kExplanationFieldNumber = kExplanationFieldNumber();
public native @StdString BytePointer explanation();
public native void set_explanation(@StdString BytePointer value);
public native void set_explanation(@StdString String value);
public native void set_explanation(@Cast("const char*") BytePointer value, @Cast("size_t") long size);
public native void set_explanation(String value, @Cast("size_t") long size);
public native @StdString @Cast({"char*", "std::string*"}) BytePointer mutable_explanation();
public native @StdString @Cast({"char*", "std::string*"}) BytePointer release_explanation();
public native void set_allocated_explanation(@StdString @Cast({"char*", "std::string*"}) BytePointer explanation);
public native @StdString @Cast({"char*", "std::string*"}) BytePointer unsafe_arena_release_explanation();
public native void unsafe_arena_set_allocated_explanation(
@StdString @Cast({"char*", "std::string*"}) BytePointer explanation);
// int32 version = 1;
public native void clear_version();
@MemberGetter public static native int kVersionFieldNumber();
public static final int kVersionFieldNumber = kVersionFieldNumber();
public native @Cast("google::protobuf::int32") int version();
public native void set_version(@Cast("google::protobuf::int32") int value);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.