hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
866181448e04b73eef55d7f662e23ab8d9e0fc1c
224
package com.github.dstaflund.geomemorial.ui.activity.about; import android.os.Bundle; import android.support.annotation.Nullable; public interface AboutActivityPresenter { void onCreate(@Nullable Bundle savedState); }
24.888889
59
0.816964
eb8bbbb619dbd4bf978f80e584e02216af96829b
9,504
/******************************************************************************* * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Juerg Billeter, [email protected] - 47136 Search view should show match objects * Ulrich Etter, [email protected] - 47136 Search view should show match objects * Roman Fuchs, [email protected] - 47136 Search view should show match objects *******************************************************************************/ package ts.eclipse.ide.internal.ui.search; import java.util.Arrays; import java.util.Comparator; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.core.resources.IResource; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.StyledCellLabelProvider; import org.eclipse.jface.viewers.StyledString; import org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider.IStyledLabelProvider; import org.eclipse.ui.model.WorkbenchLabelProvider; import org.eclipse.search.internal.ui.Messages; import org.eclipse.search.internal.ui.SearchMessages; import org.eclipse.search.internal.ui.SearchPluginImages; import org.eclipse.search.internal.ui.text.BasicElementLabels; import org.eclipse.search.ui.text.AbstractTextSearchResult; import org.eclipse.search.ui.text.AbstractTextSearchViewPage; import org.eclipse.search.ui.text.Match; public class TypeScriptSearchLabelProvider extends LabelProvider implements IStyledLabelProvider { public static final int SHOW_LABEL= 1; public static final int SHOW_LABEL_PATH= 2; public static final int SHOW_PATH_LABEL= 3; private static final String fgSeparatorFormat= "{0} - {1}"; //$NON-NLS-1$ private static final String fgEllipses= " ... "; //$NON-NLS-1$ private final WorkbenchLabelProvider fLabelProvider; private final AbstractTextSearchViewPage fPage; private final Comparator fMatchComparator; private final Image fLineMatchImage; private int fOrder; public TypeScriptSearchLabelProvider(AbstractTextSearchViewPage page, int orderFlag) { fLabelProvider= new WorkbenchLabelProvider(); fOrder= orderFlag; fPage= page; fLineMatchImage= SearchPluginImages.get(SearchPluginImages.IMG_OBJ_TEXT_SEARCH_LINE); fMatchComparator= new Comparator() { public int compare(Object o1, Object o2) { return ((TypeScriptMatch) o1).getOriginalOffset() - ((TypeScriptMatch) o2).getOriginalOffset(); } }; } public void setOrder(int orderFlag) { fOrder= orderFlag; } public int getOrder() { return fOrder; } /* (non-Javadoc) * @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object) */ public String getText(Object object) { return getStyledText(object).getString(); } public StyledString getStyledText(Object element) { if (element instanceof LineElement) return getLineElementLabel((LineElement) element); if (!(element instanceof IResource)) return new StyledString(); IResource resource= (IResource) element; if (!resource.exists()) new StyledString(SearchMessages.FileLabelProvider_removed_resource_label); String name= BasicElementLabels.getResourceName(resource); if (fOrder == SHOW_LABEL) { return getColoredLabelWithCounts(resource, new StyledString(name)); } String pathString= BasicElementLabels.getPathLabel(resource.getParent().getFullPath(), false); if (fOrder == SHOW_LABEL_PATH) { StyledString str= new StyledString(name); String decorated= Messages.format(fgSeparatorFormat, new String[] { str.getString(), pathString }); StyledCellLabelProvider.styleDecoratedString(decorated, StyledString.QUALIFIER_STYLER, str); return getColoredLabelWithCounts(resource, str); } StyledString str= new StyledString(Messages.format(fgSeparatorFormat, new String[] { pathString, name })); return getColoredLabelWithCounts(resource, str); } private StyledString getLineElementLabel(LineElement lineElement) { int lineNumber= lineElement.getLine(); String lineNumberString= Messages.format(SearchMessages.FileLabelProvider_line_number, new Integer(lineNumber)); StyledString str= new StyledString(lineNumberString, StyledString.QUALIFIER_STYLER); Match[] matches= lineElement.getMatches(fPage.getInput()); Arrays.sort(matches, fMatchComparator); String content= lineElement.getContents(); int pos= evaluateLineStart(matches, content, lineElement.getOffset()); int length= content.length(); int charsToCut= getCharsToCut(length, matches); // number of characters to leave away if the line is too long for (int i= 0; i < matches.length; i++) { TypeScriptMatch match= (TypeScriptMatch) matches[i]; int start= Math.max(match.getOriginalOffset() - lineElement.getOffset(), 0); // append gap between last match and the new one if (pos < start) { if (charsToCut > 0) { charsToCut= appendShortenedGap(content, pos, start, charsToCut, i == 0, str); } else { str.append(content.substring(pos, start)); } } // append match int end= Math.min(match.getOriginalOffset() + match.getOriginalLength() - lineElement.getOffset(), lineElement.getLength()); str.append(content.substring(start, end), DecoratingTypeScriptSearchLabelProvider.HIGHLIGHT_STYLE); pos= end; } // append rest of the line if (charsToCut > 0) { appendShortenedGap(content, pos, length, charsToCut, false, str); } else { str.append(content.substring(pos)); } return str; } private static final int MIN_MATCH_CONTEXT= 10; // minimal number of characters shown after and before a match private int appendShortenedGap(String content, int start, int end, int charsToCut, boolean isFirst, StyledString str) { int gapLength= end - start; if (!isFirst) { gapLength-= MIN_MATCH_CONTEXT; } if (end < content.length()) { gapLength-= MIN_MATCH_CONTEXT; } if (gapLength < MIN_MATCH_CONTEXT) { // don't cut, gap is too small str.append(content.substring(start, end)); return charsToCut; } int context= MIN_MATCH_CONTEXT; if (gapLength > charsToCut) { context+= gapLength - charsToCut; } if (!isFirst) { str.append(content.substring(start, start + context)); // give all extra context to the right side of a match context= MIN_MATCH_CONTEXT; } str.append(fgEllipses, StyledString.QUALIFIER_STYLER); if (end < content.length()) { str.append(content.substring(end - context, end)); } return charsToCut - gapLength + fgEllipses.length(); } private int getCharsToCut(int contentLength, Match[] matches) { if (contentLength <= 256 || !"win32".equals(SWT.getPlatform()) || matches.length == 0) { //$NON-NLS-1$ return 0; // no shortening required } // XXX: workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=38519 return contentLength - 256 + Math.max(matches.length * fgEllipses.length(), 100); } private int evaluateLineStart(Match[] matches, String lineContent, int lineOffset) { int max= lineContent.length(); if (matches.length > 0) { TypeScriptMatch match= (TypeScriptMatch) matches[0]; max= match.getOriginalOffset() - lineOffset; if (max < 0) { return 0; } } for (int i= 0; i < max; i++) { char ch= lineContent.charAt(i); if (!Character.isWhitespace(ch) || ch == '\n' || ch == '\r') { return i; } } return max; } private StyledString getColoredLabelWithCounts(Object element, StyledString coloredName) { AbstractTextSearchResult result= fPage.getInput(); if (result == null) return coloredName; int matchCount= result.getMatchCount(element); if (matchCount <= 1) return coloredName; String countInfo= Messages.format(SearchMessages.FileLabelProvider_count_format, new Integer(matchCount)); coloredName.append(' ').append(countInfo, StyledString.COUNTER_STYLER); return coloredName; } /* (non-Javadoc) * @see org.eclipse.jface.viewers.LabelProvider#getImage(java.lang.Object) */ public Image getImage(Object element) { if (element instanceof LineElement) { return fLineMatchImage; } if (!(element instanceof IResource)) return null; IResource resource= (IResource)element; Image image= fLabelProvider.getImage(resource); return image; } /* (non-Javadoc) * @see org.eclipse.jface.viewers.BaseLabelProvider#dispose() */ public void dispose() { super.dispose(); fLabelProvider.dispose(); } /* (non-Javadoc) * @see org.eclipse.jface.viewers.BaseLabelProvider#isLabelProperty(java.lang.Object, java.lang.String) */ public boolean isLabelProperty(Object element, String property) { return fLabelProvider.isLabelProperty(element, property); } /* (non-Javadoc) * @see org.eclipse.jface.viewers.BaseLabelProvider#removeListener(org.eclipse.jface.viewers.ILabelProviderListener) */ public void removeListener(ILabelProviderListener listener) { super.removeListener(listener); fLabelProvider.removeListener(listener); } /* (non-Javadoc) * @see org.eclipse.jface.viewers.BaseLabelProvider#addListener(org.eclipse.jface.viewers.ILabelProviderListener) */ public void addListener(ILabelProviderListener listener) { super.addListener(listener); fLabelProvider.addListener(listener); } }
34.434783
127
0.736216
4161b4d5d20f9701b390574ad222e4f678e2126e
449
package br.com.flaviogf.decorator; public class QuackCounter implements Quackable { private static Integer numberOfQuacks = 0; private final Quackable quackable; public QuackCounter(Quackable quackable) { this.quackable = quackable; } @Override public void quack() { quackable.quack(); numberOfQuacks++; } public static Integer getNumberOfQuacks() { return numberOfQuacks; } }
21.380952
48
0.670379
36a38cace5deeb6af4686fb268959c779fd8a252
732
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/storage/v1/storage_resources.proto package com.google.storage.v1; public interface ServiceAccountOrBuilder extends // @@protoc_insertion_point(interface_extends:google.storage.v1.ServiceAccount) com.google.protobuf.MessageOrBuilder { /** * <pre> * The ID of the notification. * </pre> * * <code>string email_address = 1;</code> * @return The emailAddress. */ java.lang.String getEmailAddress(); /** * <pre> * The ID of the notification. * </pre> * * <code>string email_address = 1;</code> * @return The bytes for emailAddress. */ com.google.protobuf.ByteString getEmailAddressBytes(); }
24.4
83
0.678962
8ef6771d215369277297e42e49a2a7fae361478f
522
package com.ubiqlog.utils; public class SensorState { public static enum Bluetooth { NONE("none"), BONDING("bonding"), BONDED("bonded"); private String state; Bluetooth(String state) { this.state = state; } public String getState() { return state; } } public static enum Movement { FAST("fast"), SLOW("slow"), STEADY("steady"); private String state; Movement(String state) { this.state = state; } public String getState() { return state; } } }
14.108108
31
0.613027
de6b690d91bbdd7f94ec218a8fe949e17365589e
535
package org.team4909.bionicframework.subsystems.drive.commands; import org.team4909.bionicframework.interfaces.Commandable; import org.team4909.bionicframework.subsystems.drive.BionicDrive; public class InvertDriveDirection extends Commandable { private final DriveOI driveOI; public InvertDriveDirection(BionicDrive subsystem){ requires(subsystem); driveOI = subsystem.defaultCommand; } @Override public void initialize() { driveOI.speedMultiplier = -driveOI.speedMultiplier; } }
25.47619
65
0.760748
a38d665e41f9544d84f62c362aaae3ce9144e034
2,201
package com.ncme.springboot.configuration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.google.common.base.Predicates; import com.ncme.springboot.configuration.properties.Swagger2Properties; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * ClassName:Swagger2Configuration * Function: TODO swagger2 boot配置 * Reason: TODO 配置swagger环境 * * @author lyj * @version * @since version 1.0 * @Date 2017年8月25日 下午1:29:41 * * @see * */ @EnableSwagger2 @Configuration public class Swagger2Configuration { @Autowired Swagger2Properties swagger2Properties; @Value("${swagger2.enable}") boolean enable ; @SuppressWarnings("unchecked") @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .enable(swagger2Properties.isEnable()) .apiInfo(apiInfo()).pathMapping("/")//required :一般是项目路径 .select() //为当前包路径 .apis(RequestHandlerSelectors.basePackage("com.ncme.springboot.core.swagger")) .paths(Predicates.or(PathSelectors.regex("/api/.*")))//匹配符合规则的访问路径可以生成swagger接口文档 .build(); } //构建 api文档的详细信息函数 private ApiInfo apiInfo() { return new ApiInfoBuilder() //页面标题 .title("Spring Boot & swagger2") //创建人 .contact(new Contact("lyj", "https://my.oschina.net/lyj1989", "[email protected]")) //版本号 .version("1.0") //描述 .description("API 描述") .build(); } }
31.898551
101
0.684689
b86042538cb3861aadb22735b5c148d5c08df52d
1,742
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * The Apereo Foundation 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.tle.exceptions; import java.util.Arrays; import java.util.Collection; public class PrivilegeRequiredException extends AccessDeniedException { private static final long serialVersionUID = 1L; public PrivilegeRequiredException(String priv) { super("Privilege " + priv + " is required to perform the requested operation"); } public PrivilegeRequiredException(Collection<String> privs) { super("One of [" + privList(privs) + "] is required to perform requested operation"); } public PrivilegeRequiredException(String... privs) { this(Arrays.asList(privs)); } private static String privList(Collection<String> privs) { StringBuilder sbuf = new StringBuilder(); boolean first = true; for (String priv : privs) { if (!first) { sbuf.append(", "); // $NON-NLS-1$ } else { first = false; } sbuf.append(priv); } return sbuf.toString(); } }
32.867925
89
0.713548
4d30b4d84503dbabd4612cb99f632dc77e645c42
2,178
/* The contents of this file are subject to the license and copyright terms * detailed in the license directory at the root of the source tree (also * available online at http://fedora-commons.org/license/). */ package org.fcrepo.server.journal.xmlhelpers; import javax.xml.namespace.QName; import javax.xml.stream.XMLEventFactory; import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLStreamException; import org.fcrepo.server.journal.JournalConstants; /** * An abstract base class that provides some useful methods for the XML writer * classes. * * @author Jim Blake */ public class AbstractXmlWriter implements JournalConstants { private final XMLEventFactory factory = XMLEventFactory.newInstance(); protected void putStartDocument(XMLEventWriter writer) throws XMLStreamException { writer.add(factory.createStartDocument(DOCUMENT_ENCODING, DOCUMENT_VERSION)); } protected void putStartTag(XMLEventWriter writer, QName tagName) throws XMLStreamException { writer.add(factory.createStartElement(tagName, null, null)); } protected void putAttribute(XMLEventWriter writer, QName name, String value) throws XMLStreamException { writer.add(factory.createAttribute(name, value)); } protected void putAttributeIfNotNull(XMLEventWriter writer, QName attributeName, String value) throws XMLStreamException { if (value != null) { putAttribute(writer, attributeName, value); } } protected void putCharacters(XMLEventWriter writer, String chars) throws XMLStreamException { writer.add(factory.createCharacters(chars)); } protected void putEndTag(XMLEventWriter writer, QName tagName) throws XMLStreamException { writer.add(factory.createEndElement(tagName, null)); } protected void putEndDocument(XMLEventWriter writer) throws XMLStreamException { writer.add(factory.createEndDocument()); } }
32.507463
80
0.676309
5df2087d381fd65ef147c571b7a291df232dc403
1,369
package us.tlatoani.tablisknu.blueprint; import us.tlatoani.tablisknu.skin.retrieval.SkinFormat; import java.awt.image.BufferedImage; public class FaceBlueprint extends Blueprint { public final Part part; public final boolean isSecondLayer; public final Face face; FaceBlueprint(BufferedImage bufferedImage, Part part, boolean isSecondLayer, Face face, SkinFormat format) { super(bufferedImage, format); this.part = part; this.isSecondLayer = isSecondLayer; this.face = face; } public FaceBlueprint(Part part, boolean isSecondLayer, Face face, SkinFormat format) { this( new BufferedImage( Face.evaluateFormula(face.imageWidthFormula, part, format), Face.evaluateFormula(face.imageHeightFormula, part, format), BufferedImage.TYPE_INT_ARGB ), part, isSecondLayer, face, format ); } @Override public FaceBlueprint duplicate() { FaceBlueprint res = new FaceBlueprint(part, isSecondLayer, face, format); res.overlay(this); return res; } @Override public String toString() { return super.toString() + "(part = " + part + ", isSecondLayer = " + isSecondLayer + ", face = " + face + ", format = " + format + ")"; } }
32.595238
143
0.625274
4c95003943c673261355f702412682e4f53997c4
733
package io.cygnus.restful.client; import java.util.List; import io.cygnus.repository.entity.OrderEntity; import io.cygnus.restful.client.base.BaseApiClient; import io.cygnus.restful.client.base.PathParam; public class OrderApiClient extends BaseApiClient { private String orderUri = "/order"; private String ordersByInitUri = orderUri + "/init?tradingDay={tradingDay}&strategyId={strategyId}"; public List<OrderEntity> getOrdersByInit(String tradingDay, Integer strategyId) { return getResultSet(OrderEntity.class, ordersByInitUri, new PathParam("tradingDay", tradingDay), new PathParam("strategyId", strategyId.toString())); } public boolean putOrders(OrderEntity order) { return putBody(order, orderUri); } }
29.32
101
0.785812
2fdf2a9a5242a01ea1526f50f69eb6bf346f0b66
1,229
package kandrm.JLatVis.guiConnect.settings.logical; import kandrm.JLatVis.lattice.editing.history.HistoryEventTagLogical; import kandrm.JLatVis.lattice.editing.history.IHistoryEventListener; import kandrm.JLatVis.lattice.logical.Tag; /** * * @author Michal Kandr */ public class TagModel { private Tag tag = null; private String name = null; private String text = null; public TagModel(){} public TagModel(Tag tag){ setTag(tag); } public final void setTag(Tag tag) { this.tag = tag; name = tag.getName(); text = tag.getText(); } public String getName(){ return name; } public void setName(String name){ this.name = name; } public String getText() { return text; } public void setText(String text) { this.text = text; } public void apply(){ if(tag != null){ HistoryEventTagLogical e = new HistoryEventTagLogical(tag, tag.getName(), name, tag.getText(), text); for (IHistoryEventListener l : tag.getHistoryListeners()) { l.eventPerformed( e ); } tag.setName(name); tag.setText(text); } } }
22.345455
113
0.599675
10d950c7e49e772bdc98459bf3f0732b03bdaed2
7,229
package com.google.firebase.components; import androidx.annotation.GuardedBy; import com.google.android.gms.common.internal.Preconditions; import com.google.firebase.events.Event; import com.google.firebase.events.EventHandler; import com.google.firebase.events.Publisher; import com.google.firebase.events.Subscriber; import java.util.ArrayDeque; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; class EventBus implements Subscriber, Publisher { private final Executor defaultExecutor; @GuardedBy("this") private final Map<Class<?>, ConcurrentHashMap<EventHandler<Object>, Executor>> handlerMap = new HashMap(); @GuardedBy("this") private Queue<Event<?>> pendingEvents = new ArrayDeque(); EventBus(Executor executor) { this.defaultExecutor = executor; } /* JADX WARNING: Code restructure failed: missing block: B:11:0x001c, code lost: if (r0.hasNext() == false) goto L_0x0032; */ /* JADX WARNING: Code restructure failed: missing block: B:12:0x001e, code lost: r1 = (java.util.Map.Entry) r0.next(); ((java.util.concurrent.Executor) r1.getValue()).execute(com.google.firebase.components.EventBus$$Lambda$1.lambdaFactory$(r1, r4)); */ /* JADX WARNING: Code restructure failed: missing block: B:13:0x0032, code lost: return; */ /* JADX WARNING: Code restructure failed: missing block: B:9:0x0010, code lost: r0 = getHandlers(r4).iterator(); */ /* Code decompiled incorrectly, please refer to instructions dump. */ public void publish(com.google.firebase.events.Event<?> r4) { /* r3 = this; com.google.android.gms.common.internal.Preconditions.checkNotNull(r4) monitor-enter(r3) java.util.Queue<com.google.firebase.events.Event<?>> r0 = r3.pendingEvents // Catch:{ all -> 0x0033 } if (r0 == 0) goto L_0x000f java.util.Queue<com.google.firebase.events.Event<?>> r0 = r3.pendingEvents // Catch:{ all -> 0x0033 } r0.add(r4) // Catch:{ all -> 0x0033 } monitor-exit(r3) // Catch:{ all -> 0x0033 } return L_0x000f: monitor-exit(r3) // Catch:{ all -> 0x0033 } java.util.Set r0 = r3.getHandlers(r4) java.util.Iterator r0 = r0.iterator() L_0x0018: boolean r1 = r0.hasNext() if (r1 == 0) goto L_0x0032 java.lang.Object r1 = r0.next() java.util.Map$Entry r1 = (java.util.Map.Entry) r1 java.lang.Object r2 = r1.getValue() java.util.concurrent.Executor r2 = (java.util.concurrent.Executor) r2 java.lang.Runnable r1 = com.google.firebase.components.EventBus$$Lambda$1.lambdaFactory$(r1, r4) r2.execute(r1) goto L_0x0018 L_0x0032: return L_0x0033: r4 = move-exception monitor-exit(r3) // Catch:{ all -> 0x0033 } goto L_0x0037 L_0x0036: throw r4 L_0x0037: goto L_0x0036 */ throw new UnsupportedOperationException("Method not decompiled: com.google.firebase.components.EventBus.publish(com.google.firebase.events.Event):void"); } private synchronized Set<Entry<EventHandler<Object>, Executor>> getHandlers(Event<?> event) { Map map; map = (Map) this.handlerMap.get(event.getType()); return map == null ? Collections.emptySet() : map.entrySet(); } public synchronized <T> void subscribe(Class<T> cls, Executor executor, EventHandler<? super T> eventHandler) { Preconditions.checkNotNull(cls); Preconditions.checkNotNull(eventHandler); Preconditions.checkNotNull(executor); if (!this.handlerMap.containsKey(cls)) { this.handlerMap.put(cls, new ConcurrentHashMap()); } ((ConcurrentHashMap) this.handlerMap.get(cls)).put(eventHandler, executor); } public <T> void subscribe(Class<T> cls, EventHandler<? super T> eventHandler) { subscribe(cls, this.defaultExecutor, eventHandler); } /* JADX WARNING: Code restructure failed: missing block: B:11:0x0028, code lost: return; */ /* Code decompiled incorrectly, please refer to instructions dump. */ public synchronized <T> void unsubscribe(java.lang.Class<T> r2, com.google.firebase.events.EventHandler<? super T> r3) { /* r1 = this; monitor-enter(r1) com.google.android.gms.common.internal.Preconditions.checkNotNull(r2) // Catch:{ all -> 0x0029 } com.google.android.gms.common.internal.Preconditions.checkNotNull(r3) // Catch:{ all -> 0x0029 } java.util.Map<java.lang.Class<?>, java.util.concurrent.ConcurrentHashMap<com.google.firebase.events.EventHandler<java.lang.Object>, java.util.concurrent.Executor>> r0 = r1.handlerMap // Catch:{ all -> 0x0029 } boolean r0 = r0.containsKey(r2) // Catch:{ all -> 0x0029 } if (r0 != 0) goto L_0x0011 monitor-exit(r1) return L_0x0011: java.util.Map<java.lang.Class<?>, java.util.concurrent.ConcurrentHashMap<com.google.firebase.events.EventHandler<java.lang.Object>, java.util.concurrent.Executor>> r0 = r1.handlerMap // Catch:{ all -> 0x0029 } java.lang.Object r0 = r0.get(r2) // Catch:{ all -> 0x0029 } java.util.concurrent.ConcurrentHashMap r0 = (java.util.concurrent.ConcurrentHashMap) r0 // Catch:{ all -> 0x0029 } r0.remove(r3) // Catch:{ all -> 0x0029 } boolean r3 = r0.isEmpty() // Catch:{ all -> 0x0029 } if (r3 == 0) goto L_0x0027 java.util.Map<java.lang.Class<?>, java.util.concurrent.ConcurrentHashMap<com.google.firebase.events.EventHandler<java.lang.Object>, java.util.concurrent.Executor>> r3 = r1.handlerMap // Catch:{ all -> 0x0029 } r3.remove(r2) // Catch:{ all -> 0x0029 } L_0x0027: monitor-exit(r1) return L_0x0029: r2 = move-exception monitor-exit(r1) throw r2 */ throw new UnsupportedOperationException("Method not decompiled: com.google.firebase.components.EventBus.unsubscribe(java.lang.Class, com.google.firebase.events.EventHandler):void"); } /* access modifiers changed from: 0000 */ public void enablePublishingAndFlushPending() { Queue<Event> queue; synchronized (this) { if (this.pendingEvents != null) { queue = this.pendingEvents; this.pendingEvents = null; } else { queue = null; } } if (queue != null) { for (Event publish : queue) { publish(publish); } } } }
46.339744
226
0.609075
e3d444ba02127a500181dbfc619286eceefb2655
3,697
package com.example.yijinkang.pantryapp; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; /** * Handles the creation and deletion of the database * Call getReadableDatabase() or getWritableDatabase() on an instance of this class to get a SQLiteDatabase object * SQLiteDatabase provides insert(), update(), delete(), and execSQL() for writing to database; * rawQuery() and query() for reading, which return a Cursor object */ public class SQLiteHelper extends SQLiteOpenHelper { public static final int DATABASE_VERSION = 1; public static final String DATABASE_NAME = "PantryApp.db"; /** * constants that specify table and column names */ public static final String TABLE_RECIPES = "Recipes"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_RECIPENAME = "name"; public static final String COLUMN_INSTR = "instructions"; public static final String COLUMN_TYPE = "type"; public static final String TABLE_INGR = "Ingredients"; public static final String COLUMN_RECIPE = "recipe_id"; public static final String COLUMN_FOOD = "name"; public static final String COLUMN_QTY = "quantity"; public static final String COLUMN_UNIT = "unit"; public static final String TABLE_GROCERIES = "Groceries"; /** * constants for database actions */ private static final String SQL_CREATE_RECIPE_TABLE = "CREATE TABLE " + TABLE_RECIPES + " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_RECIPENAME + " TEXT NOT NULL, " + COLUMN_INSTR + " TEXT NULL, " + COLUMN_TYPE + " TEXT NOT NULL" + " );"; private static final String SQL_CREATE_INGR_TABLE = "CREATE TABLE " + TABLE_INGR + " (" + COLUMN_RECIPE + " INTEGER NOT NULL, " + COLUMN_FOOD + " TEXT NOT NULL, " + COLUMN_QTY + " REAL NOT NULL, " + COLUMN_UNIT + " TEXT NULL" + " );"; private static final String SQL_CREATE_GROCERIES_TABLE = "CREATE TABLE " + TABLE_GROCERIES + " (" + COLUMN_FOOD + " TEXT NOT NULL, " + COLUMN_QTY + " REAL NOT NULL, " + COLUMN_UNIT + " TEXT NOT NULL" + " );"; private static final String SQL_DELETE_DATABASE = "DROP TABLE IF EXISTS " + TABLE_RECIPES + "; " + "DROP TABLE IF EXISTS " + TABLE_INGR + "; " + "DROP TABLE IF EXISTS " + TABLE_GROCERIES + "; "; /** * constructor * @param context */ public SQLiteHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { // db.execSQL(SQL_CREATE_DATABASE); db.execSQL(SQL_CREATE_RECIPE_TABLE); db.execSQL(SQL_CREATE_INGR_TABLE); db.execSQL(SQL_CREATE_GROCERIES_TABLE); Log.d(SQLiteHelper.class.getName(), "created database"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(SQLiteHelper.class.getName(), "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL(SQL_DELETE_DATABASE); onCreate(db); } @Override public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { onUpgrade(db, oldVersion, newVersion); } }
40.184783
153
0.62429
4be5063c934e6464a6df0758dd7b21d36aada4c3
10,952
/** * Copyright (C) 2013-2016 The Rythm Engine project * for LICENSE and other details see: * https://github.com/rythmengine/rythmengine */ package org.rythmengine.sandbox; import org.rythmengine.RythmEngine; import org.rythmengine.Sandbox; import org.rythmengine.conf.RythmConfiguration; import org.rythmengine.conf.RythmConfigurationKey; import org.rythmengine.logger.ILogger; import org.rythmengine.logger.Logger; import org.rythmengine.utils.S; import sun.security.util.SecurityConstants; import java.io.File; import java.io.FilePermission; import java.net.InetAddress; import java.security.Permission; import java.util.Locale; /** * The default security manager to ensure template code run in a secure mode */ public class RythmSecurityManager extends SecurityManager { private static ILogger logger = Logger.get(RythmSecurityManager.class); private SecurityManager osm; private SecurityManager csm; // customized security manager private String code = null; private static RythmEngine engine() { return RythmEngine.get(); } public String getCode() { Throwable t = new Throwable(); StackTraceElement[] st = t.getStackTrace(); StackTraceElement ste = st[1]; if (S.ne(ste.getClassName(), RythmEngine.class.getName())) { forbidden(); } return code; } public RythmSecurityManager(SecurityManager customSecurityManager, String password, RythmEngine re) { osm = System.getSecurityManager(); csm = customSecurityManager; if (null == password) throw new NullPointerException(); code = password; } private static void forbidden() { throw new SecurityException("Access to protected resource is restricted in Sandbox mode"); } public void forbiddenIfCodeNotMatch(String code) { if (S.ne(code, this.code)) { forbidden(); } } private void checkRythm() { if (Sandbox.isRestricted()) { forbidden(); } } // @Override // public void checkCreateClassLoader() { // checkRythm(); // if (null != osm) osm.checkCreateClassLoader(); // } @Override public void checkAccess(Thread t) { //if (!(t instanceof SandboxThreadFactory.SandboxThread)) checkRythm(); if (null != osm) osm.checkAccess(t); if (null != csm) csm.checkAccess(t); } @Override public void checkAccess(ThreadGroup g) { checkRythm(); if (null != csm) csm.checkAccess(g); if (null != osm) osm.checkAccess(g); } @Override public void checkExit(int status) { checkRythm(); if (null != osm) osm.checkExit(status); if (null != csm) csm.checkExit(status); } @Override public void checkExec(String cmd) { checkRythm(); if (null != osm) osm.checkExec(cmd); if (null != csm) csm.checkExec(cmd); } @Override public void checkLink(String lib) { checkRythm(); if (null != osm) osm.checkLink(lib); if (null != csm) csm.checkLink(lib); } private interface IFilePathValidator { boolean isValid(String path); } private static boolean allowTmpDirIO(String path) { RythmConfiguration conf = RythmEngine.get().conf(); if (conf.sandboxTmpIO()) { String tmp = System.getProperty("java.io.tmpdir"); if (path.startsWith(tmp)) { return true; } else if ((path + File.separator).startsWith(tmp)) { return true; } } return false; } private static IFilePathValidator readable = new IFilePathValidator() { @Override public boolean isValid(String path) { String uxPath = path; if (path.matches("^(jar:file:)?[a-zA-Z]:.*")) { uxPath = "/" + path.replace("\\", "/").toLowerCase(); } if (uxPath.startsWith(BASE_RYTHM) || uxPath.startsWith(BASE_JDK)) { return true; } if (allowTmpDirIO(path)) { return true; }; if (engine().conf().playFramework()) { StackTraceElement[] st = new Throwable().getStackTrace(); if (st.length > 6) { StackTraceElement ste = st[5]; if (S.eq(ste.getClassName(), "play.classloading.ApplicationClasses")) { return true; } } } return false; } }; private static IFilePathValidator writable = new IFilePathValidator() { @Override public boolean isValid(String path) { return allowTmpDirIO(path); } }; private static IFilePathValidator deletable = writable; private void safeCheckFile(String path, IFilePathValidator validator) { if (!Sandbox.isRestricted()) return; Sandbox.enterSafeZone(code); try { if (!validator.isValid(path)) { forbidden(); } } finally { Sandbox.leaveCurZone(code); } } @Override public void checkRead(String file) { safeCheckFile(file, readable); if (null != csm) csm.checkRead(file); if (null != osm) osm.checkRead(file); } private static final String BASE_RYTHM = RythmEngine.class.getResource(RythmEngine.class.getSimpleName() + ".class").getFile().replace("RythmEngine.class", "").toLowerCase(Locale.US); private static final String BASE_JDK = Integer.class.getResource(Integer.class.getSimpleName() + ".class").getFile().replace("Integer.class", "").toLowerCase(Locale.US); @Override public void checkWrite(String file) { safeCheckFile(file, writable); if (null != csm) csm.checkWrite(file); if (null != osm) osm.checkWrite(file); } @Override public void checkDelete(String file) { safeCheckFile(file, deletable); if (null != csm) csm.checkDelete(file); if (null != osm) osm.checkDelete(file); } @Override public void checkConnect(String host, int port) { checkRythm(); if (null != csm) csm.checkConnect(host, port); if (null != osm) osm.checkConnect(host, port); } @Override public void checkConnect(String host, int port, Object context) { checkRythm(); if (null != csm) csm.checkConnect(host, port, context); if (null != osm) osm.checkConnect(host, port, context); } @Override public void checkListen(int port) { checkRythm(); if (null != csm) csm.checkListen(port); if (null != osm) osm.checkListen(port); } @Override public void checkAccept(String host, int port) { checkRythm(); if (null != csm) csm.checkAccept(host, port); if (null != osm) osm.checkAccept(host, port); } @Override public void checkMulticast(InetAddress maddr) { checkRythm(); if (null != csm) csm.checkMulticast(maddr); if (null != osm) osm.checkMulticast(maddr); } @Override public void checkPropertiesAccess() { checkRythm(); if (null != csm) csm.checkPropertiesAccess(); if (null != osm) osm.checkPropertiesAccess(); } @Override public void checkPropertyAccess(String key) { if (key.startsWith("rythm.")) { key = key.substring(7); } if (null != RythmConfigurationKey.valueOfIgnoreCase(key)) { return; } RythmEngine e = engine(); if (null == e) { // not in Rendering process yet, let's assume it's safe to check system properties return; } String s = e.conf().allowedSystemProperties(); if (s.indexOf(key) > -1) return; if (e.isDevMode()) { logger.info("checking security on property[%s] access on [%s]", key, s); } checkRythm(); if (null != csm) csm.checkPropertyAccess(key); if (null != osm) osm.checkPropertyAccess(key); } @Override public boolean checkTopLevelWindow(Object window) { checkRythm(); if (null != csm) return csm.checkTopLevelWindow(window); else if (null != osm) return osm.checkTopLevelWindow(window); else return true; } @Override public void checkPrintJobAccess() { checkRythm(); if (null != csm) csm.checkPrintJobAccess(); if (null != osm) osm.checkPrintJobAccess(); } @Override public void checkSystemClipboardAccess() { checkRythm(); if (null != osm) osm.checkSystemClipboardAccess(); if (null != csm) csm.checkSystemClipboardAccess(); } @Override public void checkAwtEventQueueAccess() { checkRythm(); if (null != osm) osm.checkAwtEventQueueAccess(); if (null != csm) csm.checkAwtEventQueueAccess(); } @Override public void checkPackageAccess(String pkg) { if (null != osm) osm.checkPackageAccess(pkg); if (null != csm) csm.checkPackageAccess(pkg); // TODO: implement Rythm restricted package check } @Override public void checkPackageDefinition(String pkg) { checkRythm(); if (null != osm) osm.checkPackageDefinition(pkg); if (null != osm) osm.checkPackageDefinition(pkg); } private void checkFilePermission(FilePermission fp) { String actions = fp.getActions(); String name = fp.getName(); if (actions.contains(SecurityConstants.FILE_READ_ACTION)){ checkRead(name); } if (actions.contains(SecurityConstants.FILE_WRITE_ACTION)) { checkWrite(name); } if (actions.contains(SecurityConstants.FILE_DELETE_ACTION)) { checkDelete(name); } if (actions.contains(SecurityConstants.FILE_EXECUTE_ACTION)) { checkExec(name); } } @Override public void checkPermission(Permission perm) { if (perm instanceof FilePermission) { FilePermission fp = (FilePermission)perm; checkFilePermission(fp); } else if ("setSecurityManager".equals(perm.getName())) { checkRythm(); } if (null != osm) osm.checkPermission(perm); if (null != csm) csm.checkPermission(perm); } @Override public void checkMemberAccess(Class<?> clazz, int which) { if (null != osm) osm.checkMemberAccess(clazz, which); if (null != csm) csm.checkMemberAccess(clazz, which); //Todo check rythm member access } @Override public void checkSetFactory() { checkRythm(); if (null != osm) osm.checkSetFactory(); if (null != csm) csm.checkSetFactory(); } }
31.202279
187
0.595051
c4582e6d8e62a27fcbd8ece5128badd9f06287d8
1,730
package cn.jerry.android.jeepcamera.gallery; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import cn.jerry.android.jeepcamera.R; import cn.jerry.android.jeepcamera.util.Util; /** * Created by JieGuo on 1/5/16. */ public class GalleryAdapter extends RecyclerView.Adapter<GalleryViewHolder> { private int contentWidth = 0; private int itemWidth = 0; private List<String> data = new ArrayList<>(); private View.OnClickListener onClickListener; public void addData(List<String> data) { this.data.clear(); this.data.addAll(data); } public void setOnClickListener(View.OnClickListener onClickListener) { this.onClickListener = onClickListener; } @Override public GalleryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.jeep_activity_gallery_item, parent, false); if (contentWidth == 0) { contentWidth = parent.getMeasuredWidth(); itemWidth = contentWidth / 3; } if (onClickListener != null) { itemView.setOnClickListener(onClickListener); } return new GalleryViewHolder(itemView, itemWidth); } @Override public void onBindViewHolder(GalleryViewHolder holder, int position) { holder.itemView.setTag(data.get(position)); Util.displayImage(holder.cover, "file:///" + data.get(position), itemWidth, itemWidth); } @Override public int getItemCount() { return data.size(); } }
28.833333
95
0.686705
d735695d1b2a61a03186b26a54cd263f66c2e121
654
package io.xol.dop.game.client.fx; //(c) 2014 XolioWare Interactive import io.xol.dop.game.client.renderer.NumbersRenderer; import io.xol.dop.game.units.Unit; public class FXDamage extends FXBase{ int x = 0; int y = 0; int timeLeft = 60; int pv; public FXDamage(Unit unit, int pv) { this.x = unit.posX*32; this.y = unit.posY*32; this.pv = pv; } @Override public void render(int camX, int camY) { y++; NumbersRenderer.renderNumerStringColor(pv+"", x-camX, y-camY, "FF0000",timeLeft/60f); //ObjectRenderer.renderTexturedRectAlpha(x-camX, y-camY, 32, 32, "units/say/"+name,1f); timeLeft--; if(timeLeft < 0) kill(); } }
20.4375
89
0.678899
960dc09700ee3781acee5ec1bdeccb8df6f5c10c
2,763
package io.ragnarok.shield; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; /** * Performs simple logistic regression. */ public class Logistic { /** the learning rate */ private double rate; /** the weight to learn */ private double[] weights; /** the number of iterations */ private int ITERATIONS = 3000; public Logistic(int n) { this.rate = 0.0001; weights = new double[n]; } private static double sigmoid(double z) { return 1.0 / (1.0 + Math.exp(-z)); } public void train(List<Instance> instances) { for (int n=0; n<ITERATIONS; n++) { for (int i=0; i<instances.size(); i++) { float[] x = instances.get(i).x; double predicted = classify(x); Float label = instances.get(i).label; for (int j=0; j<weights.length; j++) { weights[j] = weights[j] + rate * (label - predicted) * x[j]; } } System.out.println("iteration: " + n + " " + Arrays.toString(weights)); } } public double classify(float[] x) { double logit = 0.0; for (int i=0; i<weights.length;i++) { logit += weights[i] * x[i]; } return sigmoid(logit); } public static class Instance { public float label; public float[] x; public Instance(float label, float[] x) { this.label = label; this.x = x; } } public static List<Instance> readDataSet(String file, String user_name) throws FileNotFoundException { ArrayList<Instance> dataset = new ArrayList<Instance>(); Scanner scanner = null; try { scanner = new Scanner(new File(file)); while(scanner.hasNextLine()) { String line = scanner.nextLine(); String[] columns = line.split(","); if(columns[0].equals(user_name)) { // skip first column and last column is the label float[] data = new float[columns.length-6]; for (int i=5; i<columns.length-1; i++) { int k=i-5; data[k] = Float.parseFloat(columns[i]); } float label = Float.parseFloat(columns[columns.length-1]); Instance instance = new Instance(label, data); dataset.add(instance); } } } finally { if (scanner != null) scanner.close(); } return dataset; } }
28.193878
106
0.513572
e4e74365f9c7a48b8e8bf5a034b49d59b2779d2b
1,742
package com.spring.mybank.user.controller; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.spring.mybank.annotation.LogExecutionTime; import com.spring.mybank.user.model.User; import com.spring.mybank.user.service.UserService; import lombok.extern.slf4j.Slf4j; @RestController @Slf4j @RequestMapping("/user") @CrossOrigin public class UserController { @Autowired private UserService userService; @RequestMapping(value = "create", method = RequestMethod.POST) @LogExecutionTime public ResponseEntity<User> createUser(@RequestBody User user) { log.info("***** create user called *****"); return new ResponseEntity<User>( userService.createUser(User.builder().first_name(user.getFirst_name()).last_name(user.getLast_name()) .user_name(user.getUser_name()).password(user.getPassword()) .date_of_birth(user.getDate_of_birth()).company(user.getCompany()).build()), HttpStatus.OK); } @RequestMapping(value = "getAllUsers", method = RequestMethod.GET) @LogExecutionTime public List<String> getAllUsers() { log.info("***** Get all users called *****"); List<String> userList = new ArrayList<String>(); userList.add("Naveen"); userList.add("Balaji"); return userList; } }
34.156863
106
0.755454
0c54b1dddf9d0decb958b506eb289a5533b4964a
13,473
package org.firstinspires.ftc.teamcode.hardware.Dummy; import android.util.Log; import com.qualcomm.robotcore.util.ElapsedTime; import org.firstinspires.ftc.robotcore.external.ClassFactory; import org.firstinspires.ftc.robotcore.external.hardware.camera.WebcamName; import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer; import org.firstinspires.ftc.robotcore.external.tfod.Recognition; import org.firstinspires.ftc.robotcore.external.tfod.TFObjectDetector; import org.firstinspires.ftc.robotcore.external.tfod.TfodRoverRuckus; import org.firstinspires.ftc.teamcode.support.Logger; import org.firstinspires.ftc.teamcode.support.hardware.Configurable; import org.firstinspires.ftc.teamcode.support.hardware.Configuration; import java.util.List; //import static org.firstinspires.ftc.robotcore.external.tfod.TfodRoverRuckus.LABEL_SILVER_MINERAL; //import static org.firstinspires.ftc.robotcore.external.tfod.TfodRoverRuckus.TFOD_MODEL_ASSET; /** * Swerve chassis consists of 4 wheels with a Servo and DcMotor attached to each. * Track (distance between left and right wheels), wheelbase (distance between front and back wheels) * and wheel radius are adjustable. * Expected hardware configuration is:<br /> * Servos: servoFrontLeft, servoFrontRight, servoBackLeft, servoBackRight.<br /> * Motors: motorFrontLeft, motorFrontRight, motorBackLeft, motorBackRight.<br /> * Orientation sensors (optional): imu, imu2 */ public class CameraMineralDetector extends Logger<CameraMineralDetector> implements Configurable { static Logger<CameraMineralDetector> logger = new Logger<>(); static { logger.configureLogging("CameraMineralDetector", Log.VERBOSE); } private static final String VUFORIA_KEY = "AaaZDWL/////AAAAGYIaD+Gn/UUDhEiR/gcOJxdEJlKEpCOKSLPfhYJfYthUNZ0vnEGm0VGPutkNgRq8bq1ufm3eAySnLhkJQ7d4w6VDT7os5FGPEOGPfsIWMYNAFMdX+wlJo2JCyljeSxQtXUd/YileyfYKBXOl2uFA4KnStCC9WkYTUBrAof3H7RGKorzYixDeOpbmCsf25rayjtAUQrKCwG4j6P5rRdxy7SC//v4VC6NirNwgJ/xn1r02/jbx8vUDrDODGyut9iLk06IzMnrq/P01yKOp48clTw0WIKNmVT7WUQweXy+E1w6xwFplTlPkjC+gzerDOpxHPqYg8RusWD2Y/IMlmnk1yzJba1B9Xf9Ih6BJbm/fVwL4"; private VuforiaLocalizer vuforia; private TFObjectDetector tfod; @Override public void setAdjustmentMode(boolean on) { // CameraMineralDetector doesn't need an adjustment mode // Method is only declared for completeness of subsystem } @Override public String getUniqueName() { return "CameraMineralDetector"; } public void configure(Configuration configuration, boolean useExtCam) { logger.verbose("Start Configuration"); /* * Configure Vuforia by creating a Parameter object, and passing it to the Vuforia engine. */ VuforiaLocalizer.Parameters parameters = new VuforiaLocalizer.Parameters(); parameters.vuforiaLicenseKey = VUFORIA_KEY; if (useExtCam) { parameters.cameraName = configuration.getHardwareMap().get(WebcamName.class, "Webcam 1"); } else { parameters.cameraDirection = VuforiaLocalizer.CameraDirection.BACK; } // Instantiate the Vuforia engine vuforia = ClassFactory.getInstance().createVuforia(parameters); // Loading trackables is not necessary for the Tensor Flow Object Detection engine. int tfodMonitorViewId = configuration.getHardwareMap().appContext.getResources().getIdentifier( "tfodMonitorViewId", "id", configuration.getHardwareMap().appContext.getPackageName()); TFObjectDetector.Parameters tfodParameters = new TFObjectDetector.Parameters(tfodMonitorViewId); tfod = ClassFactory.getInstance().createTFObjectDetector(tfodParameters, vuforia); tfod.loadModelFromAsset(TfodRoverRuckus.TFOD_MODEL_ASSET, TfodRoverRuckus.LABEL_GOLD_MINERAL, TfodRoverRuckus.LABEL_SILVER_MINERAL); logger.verbose("CameraMineralDetector status: %s", tfod); tfodParameters.minimumConfidence = 0.2; com.vuforia.CameraDevice.getInstance().setFlashTorchMode(true); // com.vuforia.CameraDevice.getInstance().setField("iso", "800"); // register CameraMineralDetector as a configurable component configuration.register(this); } public ToboDummy.MineralDetection.SampleLocation getGoldPositionTF(boolean isHanging) { // The TFObjectDetector uses the camera frames from the VuforiaLocalizer, so we create that // first. logger.verbose("Start getGoldPositionTF()"); /** Activate Tensor Flow Object Detection. */ if (tfod != null) { logger.verbose("Start tfod Activation"); tfod.activate(); logger.verbose("tfod activate: ", tfod); } ElapsedTime elapsedTime = new ElapsedTime(); elapsedTime.startTime(); int minDistanceFromTop = isHanging ? 320 : 150; ToboDummy.MineralDetection.SampleLocation sampleLocation = ToboDummy.MineralDetection.SampleLocation.UNKNOWN; int goldXCoord = -1; int silverXCoord = -1; while (elapsedTime.seconds() < 2 && goldXCoord == -1 && silverXCoord == -1) { if (tfod != null) { // getUpdatedRecognitions() will return null if no new information is available since // the last time that call was made. List<Recognition> updatedRecognitions = tfod.getUpdatedRecognitions(); if (updatedRecognitions != null) { if (updatedRecognitions.size() >= 2) { logger.verbose("Starting recognitions"); logger.verbose("Recognitions: %d", (int) updatedRecognitions.size()); int validRecognitions = 0; for (Recognition recognition : updatedRecognitions) { if (recognition.getTop() > minDistanceFromTop) { validRecognitions++; } } logger.verbose("Valid recognitions: %d", validRecognitions); if (validRecognitions >= 2) { for (Recognition recognition : updatedRecognitions) { if (recognition.getLabel().equals(TfodRoverRuckus.LABEL_GOLD_MINERAL) && recognition.getTop() > minDistanceFromTop) { goldXCoord = (int) recognition.getLeft(); logger.verbose("Gold X = %d", (int) goldXCoord); logger.verbose("Gold -Y = %d", (int) recognition.getTop()); } else if (recognition.getLabel().equals(TfodRoverRuckus.LABEL_SILVER_MINERAL) && recognition.getTop() > minDistanceFromTop) { silverXCoord = (int) recognition.getLeft(); logger.verbose("Silver X = %d", (int) silverXCoord); logger.verbose("Silver -Y = %d", (int) recognition.getTop()); } if (goldXCoord != -1 && goldXCoord < silverXCoord) { sampleLocation = ToboDummy.MineralDetection.SampleLocation.LEFT; } else if (goldXCoord != -1 && goldXCoord > silverXCoord) { sampleLocation = ToboDummy.MineralDetection.SampleLocation.CENTER; } else if (goldXCoord == -1 && silverXCoord != -1) { sampleLocation = ToboDummy.MineralDetection.SampleLocation.RIGHT; } } } } } } } if (tfod != null) { tfod.deactivate(); tfod.shutdown(); logger.verbose("Tfod shutdown", tfod); } switch (sampleLocation) { case LEFT: logger.verbose("SampleLocation: Left"); case RIGHT: logger.verbose("SampleLocation: Right"); case CENTER: logger.verbose("SampleLocation: Center"); case UNKNOWN: logger.verbose("Sample Location: Unknown"); default: logger.verbose("Sample Location: Unknown"); } return sampleLocation; } public ToboDummy.MineralDetection.SampleLocation getGoldPositionTF_Titan(boolean isHanging) { // The TFObjectDetector uses the camera frames from the VuforiaLocalizer, so we create that // first. logger.verbose("Start getGoldPositionTF()"); /** Activate Tensor Flow Object Detection. */ if (tfod != null) { logger.verbose("Start tfod Activation"); tfod.activate(); logger.verbose("tfod activate: ", tfod); } ElapsedTime elapsedTime = new ElapsedTime(); elapsedTime.startTime(); int minDistanceFromTop; if (isHanging) minDistanceFromTop = 300; else minDistanceFromTop = 150; ToboDummy.MineralDetection.SampleLocation sampleLocation = ToboDummy.MineralDetection.SampleLocation.UNKNOWN; int goldXCoord = -1; int silverXCoord = -1; while (elapsedTime.seconds() < 2 && goldXCoord == -1 && silverXCoord == -1) { if (tfod != null) { // getUpdatedRecognitions() will return null if no new information is available since // the last time that call was made. List<Recognition> updatedRecognitions = tfod.getUpdatedRecognitions(); if (updatedRecognitions != null) { if (updatedRecognitions.size() >= 2) { logger.verbose("Starting recognitions"); logger.verbose("Recognitions: %d", (int) updatedRecognitions.size()); int validRecognitions = 0; for (Recognition recognition : updatedRecognitions) { if (recognition.getTop() > minDistanceFromTop) { validRecognitions++; } } logger.verbose("Valid recognitions: %d", validRecognitions); if (validRecognitions >= 2) { for (Recognition recognition : updatedRecognitions) { if (recognition.getLabel().equals(TfodRoverRuckus.LABEL_GOLD_MINERAL) && recognition.getTop() > minDistanceFromTop) { goldXCoord = (int) recognition.getLeft(); logger.verbose("Gold X = %d", (int) goldXCoord); logger.verbose("Gold -Y = %d", (int) recognition.getTop()); } else if (recognition.getLabel().equals(TfodRoverRuckus.LABEL_SILVER_MINERAL) && recognition.getTop() > minDistanceFromTop) { silverXCoord = (int) recognition.getLeft(); logger.verbose("Silver X = %d", (int) silverXCoord); logger.verbose("Silver -Y = %d", (int) recognition.getTop()); } if (goldXCoord != -1 && goldXCoord < silverXCoord) { sampleLocation = ToboDummy.MineralDetection.SampleLocation.LEFT; } else if (goldXCoord != -1 && goldXCoord > silverXCoord) { sampleLocation = ToboDummy.MineralDetection.SampleLocation.CENTER; } else if (goldXCoord == -1 && silverXCoord != -1) { sampleLocation = ToboDummy.MineralDetection.SampleLocation.RIGHT; } } } } } } } if (tfod != null) { tfod.deactivate(); tfod.shutdown(); logger.verbose("Tfod shutdown", tfod); } switch (sampleLocation) { case LEFT: logger.verbose("SampleLocation: Left"); case RIGHT: logger.verbose("SampleLocation: Right"); case CENTER: logger.verbose("SampleLocation: Center"); case UNKNOWN: logger.verbose("Sample Location: Unknown"); default: logger.verbose("Sample Location: Unknown"); } return sampleLocation; } } /** * Set up telemetry lines for chassis metrics * Shows current motor power, orientation sensors, * drive mode, heading deviation / servo adjustment (in <code>STRAIGHT</code> mode) * and servo position for each wheel */ // public void setupTelemetry(Telemetry telemetry) { // Telemetry.Line line = telemetry.addLine(); // if () // line.addData("CameraMineralDetector", "Recog. Count= %d", new Func<Integer>() { // @Override // public Integer value() { // // } // }); // }
49.171533
429
0.585245
b3edaab5d6cb88b475e9523a2ab6204c652d6250
1,144
package com.jiakaiyang.java.puncher.core; import com.jiakaiyang.java.puncher.utils.OutputUtils; /** * 负责把时间以某种指定的方式输出给用户 */ public class Outputer { private TimeManager timeManager = TimeManager.getInstance(); public Outputer(){ } /** * 输出指定的时间点到控制台,输出格式是毫秒的格式 * @param name */ public void pointToCLI(String name){ TimePoint timePoint = timeManager.getTimePoint(name); OutputUtils.outputToCLI(timePoint); } /** * 输出指定的时间点到控制台,输出的是表示时间的字符串,格式由第二个参数指定 * @param name 打孔时间的name * @param format 时间格式 */ public void pointToCLI(String name, String format){ TimePoint timePoint = timeManager.getTimePoint(name); OutputUtils.outputToCLI(timePoint, format); } /** * 输出一个时间段到控制台,输出的是毫秒格式 * @param nameStart 起始的时间点 * @param nameEnd 结束的时间点 */ public void intervalToCLI(String nameStart, String nameEnd){ TimePoint startTimePoint = timeManager.getTimePoint(nameStart); TimePoint endTimePoint = timeManager.getTimePoint(nameEnd); OutputUtils.outputToCLI(startTimePoint, endTimePoint); } }
23.833333
71
0.675699
4c514eced54a807aa9f52cc7816656f2b4c1174e
61,965
// *************************************************************************************************************************** // * 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.juneau.rest.test.client; import static java.util.Arrays.*; import static org.junit.Assert.*; import static org.apache.juneau.assertions.Assertions.*; import static org.apache.juneau.http.HttpMethod.*; import static org.apache.juneau.testutils.Constants.*; import java.io.*; import java.util.*; import javax.servlet.http.*; import org.apache.juneau.collections.*; import org.apache.juneau.http.annotation.Body; import org.apache.juneau.http.annotation.FormData; import org.apache.juneau.http.annotation.Header; import org.apache.juneau.http.annotation.Path; import org.apache.juneau.http.annotation.Query; import org.apache.juneau.rest.*; import org.apache.juneau.rest.annotation.*; import org.apache.juneau.serializer.annotation.*; import org.apache.juneau.testutils.pojos.*; /** * JUnit automated testcase resource. */ @Rest( path="/testThirdPartyProxy", logging=@Logging( disabled="true" ) ) @SerializerConfig(addRootType="true",addBeanTypes="true") @SuppressWarnings({"serial"}) public class ThirdPartyProxyResource extends BasicRestServletJena { public static FileWriter logFile; static { try { logFile = new FileWriter("./target/logs/third-party-proxy-resource.txt", false); } catch (IOException e) { e.printStackTrace(); } } @RestHook(HookEvent.START_CALL) public static void startCall(HttpServletRequest req) { try { logFile.append("START["+new Date()+"]-").append(req.getQueryString()).append("\n"); logFile.flush(); } catch (IOException e) { e.printStackTrace(); } } @RestHook(HookEvent.PRE_CALL) public static void preCall(HttpServletRequest req) { try { logFile.append("PRE["+new Date()+"]-").append(req.getQueryString()).append("\n"); logFile.flush(); } catch (IOException e) { e.printStackTrace(); } } @RestHook(HookEvent.POST_CALL) public static void postCall(HttpServletRequest req) { try { logFile.append("POST["+new Date()+"]-").append(req.getQueryString()).append("\n"); logFile.flush(); } catch (IOException e) { e.printStackTrace(); } } @RestHook(HookEvent.END_CALL) public static void endCall(HttpServletRequest req) { try { Throwable e = (Throwable)req.getAttribute("Exception"); Long execTime = (Long)req.getAttribute("ExecTime"); logFile.append("END["+new Date()+"]-").append(req.getQueryString()).append(", time=").append(""+execTime).append(", exception=").append(e == null ? null : e.toString()).append("\n"); logFile.flush(); } catch (IOException e) { e.printStackTrace(); } } //----------------------------------------------------------------------------------------------------------------- // Header tests //----------------------------------------------------------------------------------------------------------------- @RestMethod(method=GET, path="/primitiveHeaders") public String primitiveHeaders( @Header("a") String a, @Header("an") String an, @Header("b") int b, @Header("c") Integer c, @Header("cn") Integer cn, @Header("d") Boolean d, @Header("e") float e, @Header("f") Float f ) throws Exception { assertEquals(a, "foo"); assertNull(an); assertEquals(123, b); assertEquals(123, (int)c); assertNull(cn); assertTrue(d); assertTrue(1f == e); assertTrue(1f == f); return "OK"; } @RestMethod(method=GET, path="/primitiveCollectionHeaders") public String primitiveCollectionHeaders( @Header("a") int[][][] a, @Header("b") Integer[][][] b, @Header("c") String[][][] c, @Header("d") List<Integer> d, @Header("e") List<List<List<Integer>>> e, @Header("f") List<Integer[][][]> f, @Header("g") List<int[][][]> g, @Header("h") List<String> h ) throws Exception { assertObject(a).json().is("[[[1,2],null],null]"); assertObject(b).json().is("[[[1,null],null],null]"); assertObject(c).json().is("[[['foo',null],null],null]"); assertObject(d).json().is("[1,null]"); assertObject(e).json().is("[[[1,null],null],null]"); assertObject(f).json().is("[[[[1,null],null],null],null]"); assertObject(g).json().is("[[[[1,2],null],null],null]"); assertObject(h).json().is("['foo','bar',null]"); assertObject(d.get(0)).isType(Integer.class); assertObject(e.get(0).get(0).get(0)).isType(Integer.class); assertObject(f.get(0)).isType(Integer[][][].class); assertObject(g.get(0)).isType(int[][][].class); return "OK"; } @RestMethod(method=GET, path="/beanHeaders") public String beanHeaders( @Header(name="a",cf="uon") ABean a, @Header(name="an",cf="uon") ABean an, @Header(name="b",cf="uon") ABean[][][] b, @Header(name="c",cf="uon") List<ABean> c, @Header(name="d",cf="uon") List<ABean[][][]> d, @Header(name="e",cf="uon") Map<String,ABean> e, @Header(name="f",cf="uon") Map<String,List<ABean>> f, @Header(name="g",cf="uon") Map<String,List<ABean[][][]>> g, @Header(name="h",cf="uon") Map<Integer,List<ABean>> h ) throws Exception { assertObject(a).json().is("{a:1,b:'foo'}"); assertNull(an); assertObject(b).json().is("[[[{a:1,b:'foo'},null],null],null]"); assertObject(c).json().is("[{a:1,b:'foo'},null]"); assertObject(d).json().is("[[[[{a:1,b:'foo'},null],null],null],null]"); assertObject(e).json().is("{foo:{a:1,b:'foo'}}"); assertObject(f).json().is("{foo:[{a:1,b:'foo'}]}"); assertObject(g).json().is("{foo:[[[[{a:1,b:'foo'},null],null],null],null]}"); assertObject(h).json().is("{'1':[{a:1,b:'foo'}]}"); assertObject(c.get(0)).isType(ABean.class); assertObject(d.get(0)).isType(ABean[][][].class); assertObject(e.get("foo")).isType(ABean.class); assertObject(f.get("foo").get(0)).isType(ABean.class); assertObject(g.get("foo").get(0)).isType(ABean[][][].class); assertObject(h.keySet().iterator().next()).isType(Integer.class); assertObject(h.values().iterator().next().get(0)).isType(ABean.class); return "OK"; } @RestMethod(method=GET, path="/typedBeanHeaders") public String typedBeanHeaders( @Header(n="a",cf="uon") TypedBean a, @Header(n="an",cf="uon") TypedBean an, @Header(n="b",cf="uon") TypedBean[][][] b, @Header(n="c",cf="uon") List<TypedBean> c, @Header(n="d",cf="uon") List<TypedBean[][][]> d, @Header(n="e",cf="uon") Map<String,TypedBean> e, @Header(n="f",cf="uon") Map<String,List<TypedBean>> f, @Header(n="g",cf="uon") Map<String,List<TypedBean[][][]>> g, @Header(n="h",cf="uon") Map<Integer,List<TypedBean>> h ) throws Exception { assertObject(a).json().is("{a:1,b:'foo'}"); assertNull(an); assertObject(b).json().is("[[[{a:1,b:'foo'},null],null],null]"); assertObject(c).json().is("[{a:1,b:'foo'},null]"); assertObject(d).json().is("[[[[{a:1,b:'foo'},null],null],null],null]"); assertObject(e).json().is("{foo:{a:1,b:'foo'}}"); assertObject(f).json().is("{foo:[{a:1,b:'foo'}]}"); assertObject(g).json().is("{foo:[[[[{a:1,b:'foo'},null],null],null],null]}"); assertObject(h).json().is("{'1':[{a:1,b:'foo'}]}"); assertObject(a).isType(TypedBeanImpl.class); assertObject(b[0][0][0]).isType(TypedBeanImpl.class); assertObject(c.get(0)).isType(TypedBeanImpl.class); assertObject(d.get(0)[0][0][0]).isType(TypedBeanImpl.class); assertObject(e.get("foo")).isType(TypedBeanImpl.class); assertObject(f.get("foo").get(0)).isType(TypedBeanImpl.class); assertObject(g.get("foo").get(0)[0][0][0]).isType(TypedBeanImpl.class); assertObject(h.keySet().iterator().next()).isType(Integer.class); assertObject(h.get(1).get(0)).isType(TypedBeanImpl.class); return "OK"; } @RestMethod(method=GET, path="/swappedPojoHeaders") public String swappedPojoHeaders( @Header(n="a",cf="uon") SwappedPojo a, @Header(n="b",cf="uon") SwappedPojo[][][] b, @Header(n="c",cf="uon") Map<SwappedPojo,SwappedPojo> c, @Header(n="d",cf="uon") Map<SwappedPojo,SwappedPojo[][][]> d ) throws Exception { assertObject(a).json().is("'swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/'"); assertObject(b).json().is("[[['swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/',null],null],null]"); assertObject(c).json().is("{'swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/':'swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/'}"); assertObject(d).json().is("{'swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/':[[['swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/',null],null],null]}"); assertObject(a).isType(SwappedPojo.class); assertObject(b[0][0][0]).isType(SwappedPojo.class); assertObject(c.keySet().iterator().next()).isType(SwappedPojo.class); assertObject(c.values().iterator().next()).isType(SwappedPojo.class); assertObject(d.keySet().iterator().next()).isType(SwappedPojo.class); assertObject(d.values().iterator().next()[0][0][0]).isType(SwappedPojo.class); return "OK"; } @RestMethod(method=GET, path="/implicitSwappedPojoHeaders") public String implicitSwappedPojoHeaders( @Header(n="a",cf="uon") ImplicitSwappedPojo a, @Header(n="b",cf="uon") ImplicitSwappedPojo[][][] b, @Header(n="c",cf="uon") Map<ImplicitSwappedPojo,ImplicitSwappedPojo> c, @Header(n="d",cf="uon") Map<ImplicitSwappedPojo,ImplicitSwappedPojo[][][]> d ) throws Exception { assertObject(a).json().is("'swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/'"); assertObject(b).json().is("[[['swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/',null],null],null]"); assertObject(c).json().is("{'swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/':'swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/'}"); assertObject(d).json().is("{'swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/':[[['swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/',null],null],null]}"); assertObject(a).isType(ImplicitSwappedPojo.class); assertObject(b[0][0][0]).isType(ImplicitSwappedPojo.class); assertObject(c.keySet().iterator().next()).isType(ImplicitSwappedPojo.class); assertObject(c.values().iterator().next()).isType(ImplicitSwappedPojo.class); assertObject(d.keySet().iterator().next()).isType(ImplicitSwappedPojo.class); assertObject(d.values().iterator().next()[0][0][0]).isType(ImplicitSwappedPojo.class); return "OK"; } @RestMethod(method=GET, path="/enumHeaders") public String enumHeaders( @Header(n="a",cf="uon") TestEnum a, @Header(n="an",cf="uon") TestEnum an, @Header(n="b",cf="uon") TestEnum[][][] b, @Header(n="c",cf="uon") List<TestEnum> c, @Header(n="d",cf="uon") List<List<List<TestEnum>>> d, @Header(n="e",cf="uon") List<TestEnum[][][]> e, @Header(n="f",cf="uon") Map<TestEnum,TestEnum> f, @Header(n="g",cf="uon") Map<TestEnum,TestEnum[][][]> g, @Header(n="h",cf="uon") Map<TestEnum,List<TestEnum[][][]>> h ) throws Exception { assertEquals(TestEnum.TWO, a); assertNull(an); assertObject(b).json().is("[[['TWO',null],null],null]"); assertObject(c).json().is("['TWO',null]"); assertObject(d).json().is("[[['TWO',null],null],null]"); assertObject(e).json().is("[[[['TWO',null],null],null],null]"); assertObject(f).json().is("{ONE:'TWO'}"); assertObject(g).json().is("{ONE:[[['TWO',null],null],null]}"); assertObject(h).json().is("{ONE:[[[['TWO',null],null],null],null]}"); assertObject(c.get(0)).isType(TestEnum.class); assertObject(d.get(0).get(0).get(0)).isType(TestEnum.class); assertObject(e.get(0)).isType(TestEnum[][][].class); assertObject(f.keySet().iterator().next()).isType(TestEnum.class); assertObject(f.values().iterator().next()).isType(TestEnum.class); assertObject(g.keySet().iterator().next()).isType(TestEnum.class); assertObject(g.values().iterator().next()).isType(TestEnum[][][].class); assertObject(h.keySet().iterator().next()).isType(TestEnum.class); assertObject(h.values().iterator().next().get(0)).isType(TestEnum[][][].class); return "OK"; } @RestMethod(method=GET, path="/mapHeader") public String mapHeader( @Header("a") String a, @Header(name="b",allowEmptyValue=true) String b, @Header("c") String c ) throws Exception { assertEquals("foo", a); assertEquals("", b); assertEquals(null, c); return "OK"; } @RestMethod(method=GET, path="/beanHeader") public String beanHeader( @Header("a") String a, @Header(name="b",allowEmptyValue=true) String b, @Header("c") String c ) throws Exception { assertEquals("foo", a); assertEquals("", b); assertEquals(null, c); return "OK"; } @RestMethod(method=GET, path="/nameValuePairsHeader") public String nameValuePairsHeader( @Header("a") String a, @Header(name="b",allowEmptyValue=true) String b, @Header("c") String c ) throws Exception { assertEquals("foo", a); assertEquals("", b); assertEquals(null, c); return "OK"; } @RestMethod(method=GET, path="/headerIfNE1") public String headerIfNE1( @Header("a") String a ) throws Exception { assertEquals("foo", a); return "OK"; } @RestMethod(method=GET, path="/headerIfNE2") public String headerIfNE2( @Header("a") String a ) throws Exception { assertEquals(null, a); return "OK"; } @RestMethod(method=GET, path="/headerIfNEMap") public String headerIfNEMap( @Header("a") String a, @Header("b") String b, @Header("c") String c ) throws Exception { assertEquals("foo", a); assertEquals(null, b); assertEquals(null, c); return "OK"; } @RestMethod(method=GET, path="/headerIfNEBean") public String headerIfNEBean( @Header("a") String a, @Header("b") String b, @Header("c") String c ) throws Exception { assertEquals("foo", a); assertEquals(null, b); assertEquals(null, c); return "OK"; } @RestMethod(method=GET, path="/headerIfNEnameValuePairs") public String headerIfNEnameValuePairs( @Header("a") String a, @Header("b") String b, @Header("c") String c ) throws Exception { assertEquals("foo", a); assertEquals(null, b); assertEquals(null, c); return "OK"; } //----------------------------------------------------------------------------------------------------------------- // Query tests //----------------------------------------------------------------------------------------------------------------- @RestMethod(method=GET, path="/primitiveQueries") public String primitiveQueries( @Query("a") String a, @Query("an") String an, @Query("b") int b, @Query("c") Integer c, @Query("cn") Integer cn, @Query("d") Boolean d, @Query("e") float e, @Query("f") Float f ) throws Exception { assertEquals(a, "foo"); assertNull(an); assertEquals(123, b); assertEquals(123, (int)c); assertNull(cn); assertTrue(d); assertTrue(1f == e); assertTrue(1f == f); return "OK"; } @RestMethod(method=GET, path="/primitiveCollectionQueries") public String primitiveCollectionQueries( @Query("a") int[][][] a, @Query("b") Integer[][][] b, @Query("c") String[][][] c, @Query("d") List<Integer> d, @Query("e") List<List<List<Integer>>> e, @Query("f") List<Integer[][][]> f, @Query("g") List<int[][][]> g, @Query("h") List<String> h ) throws Exception { assertObject(a).json().is("[[[1,2],null],null]"); assertObject(b).json().is("[[[1,null],null],null]"); assertObject(c).json().is("[[['foo',null],null],null]"); assertObject(d).json().is("[1,null]"); assertObject(e).json().is("[[[1,null],null],null]"); assertObject(f).json().is("[[[[1,null],null],null],null]"); assertObject(g).json().is("[[[[1,2],null],null],null]"); assertObject(h).json().is("['foo','bar',null]"); assertObject(d.get(0)).isType(Integer.class); assertObject(e.get(0).get(0).get(0)).isType(Integer.class); assertObject(f.get(0)).isType(Integer[][][].class); assertObject(g.get(0)).isType(int[][][].class); return "OK"; } @RestMethod(method=GET, path="/beanQueries") public String beanQueries( @Query(n="a",cf="uon") ABean a, @Query(n="an",cf="uon") ABean an, @Query(n="b",cf="uon") ABean[][][] b, @Query(n="c",cf="uon") List<ABean> c, @Query(n="d",cf="uon") List<ABean[][][]> d, @Query(n="e",cf="uon") Map<String,ABean> e, @Query(n="f",cf="uon") Map<String,List<ABean>> f, @Query(n="g",cf="uon") Map<String,List<ABean[][][]>> g, @Query(n="h",cf="uon") Map<Integer,List<ABean>> h ) throws Exception { assertObject(a).json().is("{a:1,b:'foo'}"); assertNull(an); assertObject(b).json().is("[[[{a:1,b:'foo'},null],null],null]"); assertObject(c).json().is("[{a:1,b:'foo'},null]"); assertObject(d).json().is("[[[[{a:1,b:'foo'},null],null],null],null]"); assertObject(e).json().is("{foo:{a:1,b:'foo'}}"); assertObject(f).json().is("{foo:[{a:1,b:'foo'}]}"); assertObject(g).json().is("{foo:[[[[{a:1,b:'foo'},null],null],null],null]}"); assertObject(h).json().is("{'1':[{a:1,b:'foo'}]}"); assertObject(c.get(0)).isType(ABean.class); assertObject(d.get(0)).isType(ABean[][][].class); assertObject(e.get("foo")).isType(ABean.class); assertObject(f.get("foo").get(0)).isType(ABean.class); assertObject(g.get("foo").get(0)).isType(ABean[][][].class); assertObject(h.keySet().iterator().next()).isType(Integer.class); assertObject(h.values().iterator().next().get(0)).isType(ABean.class); return "OK"; } @RestMethod(method=GET, path="/typedBeanQueries") public String typedBeanQueries( @Query(n="a",cf="uon") TypedBean a, @Query(n="an",cf="uon") TypedBean an, @Query(n="b",cf="uon") TypedBean[][][] b, @Query(n="c",cf="uon") List<TypedBean> c, @Query(n="d",cf="uon") List<TypedBean[][][]> d, @Query(n="e",cf="uon") Map<String,TypedBean> e, @Query(n="f",cf="uon") Map<String,List<TypedBean>> f, @Query(n="g",cf="uon") Map<String,List<TypedBean[][][]>> g, @Query(n="h",cf="uon") Map<Integer,List<TypedBean>> h ) throws Exception { assertObject(a).json().is("{a:1,b:'foo'}"); assertNull(an); assertObject(b).json().is("[[[{a:1,b:'foo'},null],null],null]"); assertObject(c).json().is("[{a:1,b:'foo'},null]"); assertObject(d).json().is("[[[[{a:1,b:'foo'},null],null],null],null]"); assertObject(e).json().is("{foo:{a:1,b:'foo'}}"); assertObject(f).json().is("{foo:[{a:1,b:'foo'}]}"); assertObject(g).json().is("{foo:[[[[{a:1,b:'foo'},null],null],null],null]}"); assertObject(h).json().is("{'1':[{a:1,b:'foo'}]}"); assertObject(a).isType(TypedBeanImpl.class); assertObject(b[0][0][0]).isType(TypedBeanImpl.class); assertObject(c.get(0)).isType(TypedBeanImpl.class); assertObject(d.get(0)[0][0][0]).isType(TypedBeanImpl.class); assertObject(e.get("foo")).isType(TypedBeanImpl.class); assertObject(f.get("foo").get(0)).isType(TypedBeanImpl.class); assertObject(g.get("foo").get(0)[0][0][0]).isType(TypedBeanImpl.class); assertObject(h.keySet().iterator().next()).isType(Integer.class); assertObject(h.get(1).get(0)).isType(TypedBeanImpl.class); return "OK"; } @RestMethod(method=GET, path="/swappedPojoQueries") public String swappedPojoQueries( @Query(n="a",cf="uon") SwappedPojo a, @Query(n="b",cf="uon") SwappedPojo[][][] b, @Query(n="c",cf="uon") Map<SwappedPojo,SwappedPojo> c, @Query(n="d",cf="uon") Map<SwappedPojo,SwappedPojo[][][]> d ) throws Exception { assertObject(a).json().is("'swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/'"); assertObject(b).json().is("[[['swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/',null],null],null]"); assertObject(c).json().is("{'swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/':'swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/'}"); assertObject(d).json().is("{'swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/':[[['swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/',null],null],null]}"); assertObject(a).isType(SwappedPojo.class); assertObject(b[0][0][0]).isType(SwappedPojo.class); assertObject(c.keySet().iterator().next()).isType(SwappedPojo.class); assertObject(c.values().iterator().next()).isType(SwappedPojo.class); assertObject(d.keySet().iterator().next()).isType(SwappedPojo.class); assertObject(d.values().iterator().next()[0][0][0]).isType(SwappedPojo.class); return "OK"; } @RestMethod(method=GET, path="/implicitSwappedPojoQueries") public String implicitSwappedPojoQueries( @Query(n="a",cf="uon") ImplicitSwappedPojo a, @Query(n="b",cf="uon") ImplicitSwappedPojo[][][] b, @Query(n="c",cf="uon") Map<ImplicitSwappedPojo,ImplicitSwappedPojo> c, @Query(n="d",cf="uon") Map<ImplicitSwappedPojo,ImplicitSwappedPojo[][][]> d ) throws Exception { assertObject(a).json().is("'swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/'"); assertObject(b).json().is("[[['swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/',null],null],null]"); assertObject(c).json().is("{'swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/':'swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/'}"); assertObject(d).json().is("{'swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/':[[['swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/',null],null],null]}"); assertObject(a).isType(ImplicitSwappedPojo.class); assertObject(b[0][0][0]).isType(ImplicitSwappedPojo.class); assertObject(c.keySet().iterator().next()).isType(ImplicitSwappedPojo.class); assertObject(c.values().iterator().next()).isType(ImplicitSwappedPojo.class); assertObject(d.keySet().iterator().next()).isType(ImplicitSwappedPojo.class); assertObject(d.values().iterator().next()[0][0][0]).isType(ImplicitSwappedPojo.class); return "OK"; } @RestMethod(method=GET, path="/enumQueries") public String enumQueries( @Query(n="a",cf="uon") TestEnum a, @Query(n="an",cf="uon") TestEnum an, @Query(n="b",cf="uon") TestEnum[][][] b, @Query(n="c",cf="uon") List<TestEnum> c, @Query(n="d",cf="uon") List<List<List<TestEnum>>> d, @Query(n="e",cf="uon") List<TestEnum[][][]> e, @Query(n="f",cf="uon") Map<TestEnum,TestEnum> f, @Query(n="g",cf="uon") Map<TestEnum,TestEnum[][][]> g, @Query(n="h",cf="uon") Map<TestEnum,List<TestEnum[][][]>> h ) throws Exception { assertEquals(TestEnum.TWO, a); assertNull(an); assertObject(b).json().is("[[['TWO',null],null],null]"); assertObject(c).json().is("['TWO',null]"); assertObject(d).json().is("[[['TWO',null],null],null]"); assertObject(e).json().is("[[[['TWO',null],null],null],null]"); assertObject(f).json().is("{ONE:'TWO'}"); assertObject(g).json().is("{ONE:[[['TWO',null],null],null]}"); assertObject(h).json().is("{ONE:[[[['TWO',null],null],null],null]}"); assertObject(c.get(0)).isType(TestEnum.class); assertObject(d.get(0).get(0).get(0)).isType(TestEnum.class); assertObject(e.get(0)).isType(TestEnum[][][].class); assertObject(f.keySet().iterator().next()).isType(TestEnum.class); assertObject(f.values().iterator().next()).isType(TestEnum.class); assertObject(g.keySet().iterator().next()).isType(TestEnum.class); assertObject(g.values().iterator().next()).isType(TestEnum[][][].class); assertObject(h.keySet().iterator().next()).isType(TestEnum.class); assertObject(h.values().iterator().next().get(0)).isType(TestEnum[][][].class); return "OK"; } @RestMethod(method=GET, path="/stringQuery1") public String stringQuery1( @Query("a") int a, @Query("b") String b ) throws Exception { assertEquals(1, a); assertEquals("foo", b); return "OK"; } @RestMethod(method=GET, path="/stringQuery2") public String stringQuery2( @Query("a") int a, @Query("b") String b ) throws Exception { assertEquals(1, a); assertEquals("foo", b); return "OK"; } @RestMethod(method=GET, path="/mapQuery") public String mapQuery( @Query("a") int a, @Query("b") String b ) throws Exception { assertEquals(1, a); assertEquals("foo", b); return "OK"; } @RestMethod(method=GET, path="/beanQuery") public String beanQuery( @Query("a") String a, @Query(n="b",allowEmptyValue=true) String b, @Query("c") String c ) throws Exception { assertEquals("foo", a); assertEquals("", b); assertEquals(null, c); return "OK"; } @RestMethod(method=GET, path="/nameValuePairsQuery") public String nameValuePairsQuery( @Query("a") String a, @Query(n="b",allowEmptyValue=true) String b, @Query("c") String c ) throws Exception { assertEquals("foo", a); assertEquals("", b); assertEquals(null, c); return "OK"; } @RestMethod(method=GET, path="/queryIfNE1") public String queryIfNE1( @Query("a") String a ) throws Exception { assertEquals("foo", a); return "OK"; } @RestMethod(method=GET, path="/queryIfNE2") public String queryIfNE2( @Query("q") String a ) throws Exception { assertEquals(null, a); return "OK"; } @RestMethod(method=GET, path="/queryIfNEMap") public String queryIfNEMap( @Query("a") String a, @Query("b") String b, @Query("c") String c ) throws Exception { assertEquals("foo", a); assertEquals(null, b); assertEquals(null, c); return "OK"; } @RestMethod(method=GET, path="/queryIfNEBean") public String queryIfNEBean( @Query("a") String a, @Query("b") String b, @Query("c") String c ) throws Exception { assertEquals("foo", a); assertEquals(null, b); assertEquals(null, c); return "OK"; } @RestMethod(method=GET, path="/queryIfNEnameValuePairs") public String queryIfNEnameValuePairs( @Query("a") String a, @Query("b") String b, @Query("c") String c ) throws Exception { assertEquals("foo", a); assertEquals(null, b); assertEquals(null, c); return "OK"; } //----------------------------------------------------------------------------------------------------------------- // FormData tests //----------------------------------------------------------------------------------------------------------------- @RestMethod(method=POST, path="/primitiveFormData") public String primitiveFormData( @FormData("a") String a, @FormData("an") String an, @FormData("b") int b, @FormData("c") Integer c, @FormData("cn") Integer cn, @FormData("d") Boolean d, @FormData("e") float e, @FormData("f") Float f ) throws Exception { assertEquals("foo", a); assertNull(an); assertEquals(123, b); assertEquals(123, (int)c); assertNull(cn); assertTrue(d); assertTrue(1f == e); assertTrue(1f == f); return "OK"; } @RestMethod(method=POST, path="/primitiveCollectionFormData") public String primitiveCollectionFormData( @FormData("a") int[][][] a, @FormData("b") Integer[][][] b, @FormData("c") String[][][] c, @FormData("d") List<Integer> d, @FormData("e") List<List<List<Integer>>> e, @FormData("f") List<Integer[][][]> f, @FormData("g") List<int[][][]> g, @FormData("h") List<String> h ) throws Exception { assertObject(a).json().is("[[[1,2],null],null]"); assertObject(b).json().is("[[[1,null],null],null]"); assertObject(c).json().is("[[['foo',null],null],null]"); assertObject(d).json().is("[1,null]"); assertObject(e).json().is("[[[1,null],null],null]"); assertObject(f).json().is("[[[[1,null],null],null],null]"); assertObject(g).json().is("[[[[1,2],null],null],null]"); assertObject(h).json().is("['foo','bar',null]"); assertObject(d.get(0)).isType(Integer.class); assertObject(e.get(0).get(0).get(0)).isType(Integer.class); assertObject(f.get(0)).isType(Integer[][][].class); assertObject(g.get(0)).isType(int[][][].class); return "OK"; } @RestMethod(method=POST, path="/beanFormData") public String beanFormData( @FormData(n="a",cf="uon") ABean a, @FormData(n="an",cf="uon") ABean an, @FormData(n="b",cf="uon") ABean[][][] b, @FormData(n="c",cf="uon") List<ABean> c, @FormData(n="d",cf="uon") List<ABean[][][]> d, @FormData(n="e",cf="uon") Map<String,ABean> e, @FormData(n="f",cf="uon") Map<String,List<ABean>> f, @FormData(n="g",cf="uon") Map<String,List<ABean[][][]>> g, @FormData(n="h",cf="uon") Map<Integer,List<ABean>> h ) throws Exception { assertObject(a).json().is("{a:1,b:'foo'}"); assertNull(an); assertObject(b).json().is("[[[{a:1,b:'foo'},null],null],null]"); assertObject(c).json().is("[{a:1,b:'foo'},null]"); assertObject(d).json().is("[[[[{a:1,b:'foo'},null],null],null],null]"); assertObject(e).json().is("{foo:{a:1,b:'foo'}}"); assertObject(f).json().is("{foo:[{a:1,b:'foo'}]}"); assertObject(g).json().is("{foo:[[[[{a:1,b:'foo'},null],null],null],null]}"); assertObject(h).json().is("{'1':[{a:1,b:'foo'}]}"); assertObject(c.get(0)).isType(ABean.class); assertObject(d.get(0)).isType(ABean[][][].class); assertObject(e.get("foo")).isType(ABean.class); assertObject(f.get("foo").get(0)).isType(ABean.class); assertObject(g.get("foo").get(0)).isType(ABean[][][].class); assertObject(h.keySet().iterator().next()).isType(Integer.class); assertObject(h.values().iterator().next().get(0)).isType(ABean.class); return "OK"; } @RestMethod(method=POST, path="/typedBeanFormData") public String typedBeanFormData( @FormData(n="a",cf="uon") TypedBean a, @FormData(n="an",cf="uon") TypedBean an, @FormData(n="b",cf="uon") TypedBean[][][] b, @FormData(n="c",cf="uon") List<TypedBean> c, @FormData(n="d",cf="uon") List<TypedBean[][][]> d, @FormData(n="e",cf="uon") Map<String,TypedBean> e, @FormData(n="f",cf="uon") Map<String,List<TypedBean>> f, @FormData(n="g",cf="uon") Map<String,List<TypedBean[][][]>> g, @FormData(n="h",cf="uon") Map<Integer,List<TypedBean>> h ) throws Exception { assertObject(a).json().is("{a:1,b:'foo'}"); assertNull(an); assertObject(b).json().is("[[[{a:1,b:'foo'},null],null],null]"); assertObject(c).json().is("[{a:1,b:'foo'},null]"); assertObject(d).json().is("[[[[{a:1,b:'foo'},null],null],null],null]"); assertObject(e).json().is("{foo:{a:1,b:'foo'}}"); assertObject(f).json().is("{foo:[{a:1,b:'foo'}]}"); assertObject(g).json().is("{foo:[[[[{a:1,b:'foo'},null],null],null],null]}"); assertObject(h).json().is("{'1':[{a:1,b:'foo'}]}"); assertObject(a).isType(TypedBeanImpl.class); assertObject(b[0][0][0]).isType(TypedBeanImpl.class); assertObject(c.get(0)).isType(TypedBeanImpl.class); assertObject(d.get(0)[0][0][0]).isType(TypedBeanImpl.class); assertObject(e.get("foo")).isType(TypedBeanImpl.class); assertObject(f.get("foo").get(0)).isType(TypedBeanImpl.class); assertObject(g.get("foo").get(0)[0][0][0]).isType(TypedBeanImpl.class); assertObject(h.keySet().iterator().next()).isType(Integer.class); assertObject(h.get(1).get(0)).isType(TypedBeanImpl.class); return "OK"; } @RestMethod(method=POST, path="/swappedPojoFormData") public String swappedPojoFormData( @FormData(n="a",cf="uon") SwappedPojo a, @FormData(n="b",cf="uon") SwappedPojo[][][] b, @FormData(n="c",cf="uon") Map<SwappedPojo,SwappedPojo> c, @FormData(n="d",cf="uon") Map<SwappedPojo,SwappedPojo[][][]> d ) throws Exception { assertObject(a).json().is("'swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/'"); assertObject(b).json().is("[[['swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/',null],null],null]"); assertObject(c).json().is("{'swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/':'swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/'}"); assertObject(d).json().is("{'swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/':[[['swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/',null],null],null]}"); assertObject(a).isType(SwappedPojo.class); assertObject(b[0][0][0]).isType(SwappedPojo.class); assertObject(c.keySet().iterator().next()).isType(SwappedPojo.class); assertObject(c.values().iterator().next()).isType(SwappedPojo.class); assertObject(d.keySet().iterator().next()).isType(SwappedPojo.class); assertObject(d.values().iterator().next()[0][0][0]).isType(SwappedPojo.class); return "OK"; } @RestMethod(method=POST, path="/implicitSwappedPojoFormData") public String implicitSwappedPojoFormData( @FormData(n="a",cf="uon") ImplicitSwappedPojo a, @FormData(n="b",cf="uon") ImplicitSwappedPojo[][][] b, @FormData(n="c",cf="uon") Map<ImplicitSwappedPojo,ImplicitSwappedPojo> c, @FormData(n="d",cf="uon") Map<ImplicitSwappedPojo,ImplicitSwappedPojo[][][]> d ) throws Exception { assertObject(a).json().is("'swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/'"); assertObject(b).json().is("[[['swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/',null],null],null]"); assertObject(c).json().is("{'swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/':'swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/'}"); assertObject(d).json().is("{'swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/':[[['swap-~!@#$%^&*()_+`-={}[]|:;\"<,>.?/',null],null],null]}"); assertObject(a).isType(ImplicitSwappedPojo.class); assertObject(b[0][0][0]).isType(ImplicitSwappedPojo.class); assertObject(c.keySet().iterator().next()).isType(ImplicitSwappedPojo.class); assertObject(c.values().iterator().next()).isType(ImplicitSwappedPojo.class); assertObject(d.keySet().iterator().next()).isType(ImplicitSwappedPojo.class); assertObject(d.values().iterator().next()[0][0][0]).isType(ImplicitSwappedPojo.class); return "OK"; } @RestMethod(method=POST, path="/enumFormData") public String enumFormData( @FormData(n="a",cf="uon") TestEnum a, @FormData(n="an",cf="uon") TestEnum an, @FormData(n="b",cf="uon") TestEnum[][][] b, @FormData(n="c",cf="uon") List<TestEnum> c, @FormData(n="d",cf="uon") List<List<List<TestEnum>>> d, @FormData(n="e",cf="uon") List<TestEnum[][][]> e, @FormData(n="f",cf="uon") Map<TestEnum,TestEnum> f, @FormData(n="g",cf="uon") Map<TestEnum,TestEnum[][][]> g, @FormData(n="h",cf="uon") Map<TestEnum,List<TestEnum[][][]>> h ) throws Exception { assertEquals(TestEnum.TWO, a); assertNull(an); assertObject(b).json().is("[[['TWO',null],null],null]"); assertObject(c).json().is("['TWO',null]"); assertObject(d).json().is("[[['TWO',null],null],null]"); assertObject(e).json().is("[[[['TWO',null],null],null],null]"); assertObject(f).json().is("{ONE:'TWO'}"); assertObject(g).json().is("{ONE:[[['TWO',null],null],null]}"); assertObject(h).json().is("{ONE:[[[['TWO',null],null],null],null]}"); assertObject(c.get(0)).isType(TestEnum.class); assertObject(d.get(0).get(0).get(0)).isType(TestEnum.class); assertObject(e.get(0)).isType(TestEnum[][][].class); assertObject(f.keySet().iterator().next()).isType(TestEnum.class); assertObject(f.values().iterator().next()).isType(TestEnum.class); assertObject(g.keySet().iterator().next()).isType(TestEnum.class); assertObject(g.values().iterator().next()).isType(TestEnum[][][].class); assertObject(h.keySet().iterator().next()).isType(TestEnum.class); assertObject(h.values().iterator().next().get(0)).isType(TestEnum[][][].class); return "OK"; } @RestMethod(method=POST, path="/mapFormData") public String mapFormData( @FormData("a") String a, @FormData(n="b",aev=true) String b, @FormData("c") String c ) throws Exception { assertEquals("foo", a); assertEquals("", b); assertEquals(null, c); return "OK"; } @RestMethod(method=POST, path="/beanFormData2") public String beanFormData( @FormData("a") String a, @FormData(n="b",aev=true) String b, @FormData("c") String c ) throws Exception { assertEquals("foo", a); assertEquals("", b); assertEquals(null, c); return "OK"; } @RestMethod(method=POST, path="/nameValuePairsFormData") public String nameValuePairsFormData( @FormData("a") String a, @FormData(n="b",aev=true) String b, @FormData("c") String c ) throws Exception { assertEquals("foo", a); assertEquals("", b); //assertEquals(null, c); // This is impossible to represent. return "OK"; } @RestMethod(method=POST, path="/formDataIfNE1") public String formDataIfNE1( @FormData("a") String a ) throws Exception { assertEquals("foo", a); return "OK"; } @RestMethod(method=POST, path="/formDataIfNE2") public String formDataIfNE2( @FormData("a") String a ) throws Exception { assertEquals(null, a); return "OK"; } @RestMethod(method=POST, path="/formDataIfNEMap") public String formDataIfNEMap( @FormData("a") String a, @FormData("b") String b, @FormData("c") String c ) throws Exception { assertEquals("foo", a); assertEquals(null, b); assertEquals(null, c); return "OK"; } @RestMethod(method=POST, path="/formDataIfNEBean") public String formDataIfNEBean( @FormData("a") String a, @FormData("b") String b, @FormData("c") String c ) throws Exception { assertEquals("foo", a); assertEquals(null, b); assertEquals(null, c); return "OK"; } @RestMethod(method=POST, path="/formDataIfNENameValuePairs") public String formDataIfNENameValuePairs( @FormData("a") String a, @FormData("b") String b, @FormData("c") String c ) throws Exception { assertEquals("foo", a); assertEquals(null, b); assertEquals(null, c); return "OK"; } //----------------------------------------------------------------------------------------------------------------- // Path tests //----------------------------------------------------------------------------------------------------------------- @RestMethod(method=POST, path="/pathVars1/{a}/{b}") public String pathVars1( @Path("a") int a, @Path("b") String b ) throws Exception { assertEquals(1, a); assertEquals("foo", b); return "OK"; } @RestMethod(method=POST, path="/pathVars2/{a}/{b}") public String pathVars2( @Path("a") int a, @Path("b") String b ) throws Exception { assertEquals(1, a); assertEquals("foo", b); return "OK"; } @RestMethod(method=POST, path="/pathVars3/{a}/{b}") public String pathVars3( @Path("a") int a, @Path("b") String b ) throws Exception { assertEquals(1, a); assertEquals("foo", b); return "OK"; } //----------------------------------------------------------------------------------------------------------------- // @Request tests //----------------------------------------------------------------------------------------------------------------- @RestMethod(method=POST, path="/reqBeanPath/{a}/{b}") public String reqBeanPath( @Path("a") int a, @Path("b") String b ) throws Exception { assertEquals(1, a); assertEquals("foo", b); return "OK"; } @RestMethod(method=POST, path="/reqBeanQuery") public String reqBeanQuery( @Query("a") int a, @Query("b") String b ) throws Exception { assertEquals(1, a); assertEquals("foo", b); return "OK"; } @RestMethod(method=POST, path="/reqBeanQueryIfNE") public String reqBeanQueryIfNE( @Query("a") String a, @Query("b") String b, @Query("c") String c ) throws Exception { assertEquals("foo", a); assertNull(b); assertNull(c); return "OK"; } @RestMethod(method=POST, path="/reqBeanFormData") public String reqBeanFormData( @FormData("a") int a, @FormData("b") String b ) throws Exception { assertEquals(1, a); assertEquals("foo", b); return "OK"; } @RestMethod(method=POST, path="/reqBeanFormDataIfNE") public String reqBeanFormDataIfNE( @FormData("a") String a, @FormData("b") String b, @FormData("c") String c ) throws Exception { assertEquals("foo", a); assertNull(b); assertNull(c); return "OK"; } @RestMethod(method=POST, path="/reqBeanHeader") public String reqBeanHeader( @Header("a") int a, @Header("b") String b ) throws Exception { assertEquals(1, a); assertEquals("foo", b); return "OK"; } @RestMethod(method=POST, path="/reqBeanHeaderIfNE") public String reqBeanHeaderIfNE( @Header("a") String a, @Header("b") String b, @Header("c") String c ) throws Exception { assertEquals("foo", a); assertNull(b); assertNull(c); return "OK"; } //----------------------------------------------------------------------------------------------------------------- // Test return types. //----------------------------------------------------------------------------------------------------------------- // Various primitives @RestMethod(method=GET, path="/returnVoid") public void returnVoid() { } @RestMethod(method=GET, path="/returnInteger") public Integer returnInteger() { return 1; } @RestMethod(method=GET, path="/returnInt") public int returnInt() { return 1; } @RestMethod(method=GET, path="/returnBoolean") public boolean returnBoolean() { return true; } @RestMethod(method=GET, path="/returnFloat") public float returnFloat() { return 1f; } @RestMethod(method=GET, path="/returnFloatObject") public Float returnFloatObject() { return 1f; } @RestMethod(method=GET, path="/returnString") public String returnString() { return "foobar"; } @RestMethod(method=GET, path="/returnNullString") public String returnNullString() { return null; } @RestMethod(method=GET, path="/returnInt3dArray") public int[][][] returnInt3dArray() { return new int[][][]{{{1,2},null},null}; } @RestMethod(method=GET, path="/returnInteger3dArray") public Integer[][][] returnInteger3dArray() { return new Integer[][][]{{{1,null},null},null}; } @RestMethod(method=GET, path="/returnString3dArray") public String[][][] returnString3dArray() { return new String[][][]{{{"foo","bar",null},null},null}; } @RestMethod(method=GET, path="/returnIntegerList") public List<Integer> returnIntegerList() { return asList(new Integer[]{1,null}); } @RestMethod(method=GET, path="/returnInteger3dList") public List<List<List<Integer>>> returnInteger3dList() { return AList.of(AList.of(AList.of(1,null),null),null); } @RestMethod(method=GET, path="/returnInteger1d3dList") public List<Integer[][][]> returnInteger1d3dList() { return AList.of(new Integer[][][]{{{1,null},null},null},null); } @RestMethod(method=GET, path="/returnInt1d3dList") public List<int[][][]> returnInt1d3dList() { return AList.of(new int[][][]{{{1,2},null},null},null); } @RestMethod(method=GET, path="/returnStringList") public List<String> returnStringList() { return asList(new String[]{"foo","bar",null}); } // Beans @RestMethod(method=GET, path="/returnBean") public ABean returnBean() { return ABean.get(); } @RestMethod(method=GET, path="/returnBean3dArray") public ABean[][][] returnBean3dArray() { return new ABean[][][]{{{ABean.get(),null},null},null}; } @RestMethod(method=GET, path="/returnBeanList") public List<ABean> returnBeanList() { return asList(ABean.get()); } @RestMethod(method=GET, path="/returnBean1d3dList") public List<ABean[][][]> returnBean1d3dList() { return AList.of(new ABean[][][]{{{ABean.get(),null},null},null},null); } @RestMethod(method=GET, path="/returnBeanMap") public Map<String,ABean> returnBeanMap() { return AMap.of("foo",ABean.get()); } @RestMethod(method=GET, path="/returnBeanListMap") public Map<String,List<ABean>> returnBeanListMap() { return AMap.of("foo",asList(ABean.get())); } @RestMethod(method=GET, path="/returnBean1d3dListMap") public Map<String,List<ABean[][][]>> returnBean1d3dListMap() { return AMap.of("foo", AList.of(new ABean[][][]{{{ABean.get(),null},null},null},null)); } @RestMethod(method=GET, path="/returnBeanListMapIntegerKeys") public Map<Integer,List<ABean>> returnBeanListMapIntegerKeys() { return AMap.of(1,asList(ABean.get())); } // Typed beans @RestMethod(method=GET, path="/returnTypedBean") public TypedBean returnTypedBean() { return TypedBeanImpl.get(); } @RestMethod(method=GET, path="/returnTypedBean3dArray") public TypedBean[][][] returnTypedBean3dArray() { return new TypedBean[][][]{{{TypedBeanImpl.get(),null},null},null}; } @RestMethod(method=GET, path="/returnTypedBeanList") public List<TypedBean> returnTypedBeanList() { return asList((TypedBean)TypedBeanImpl.get()); } @RestMethod(method=GET, path="/returnTypedBean1d3dList") public List<TypedBean[][][]> returnTypedBean1d3dList() { return AList.of(new TypedBean[][][]{{{TypedBeanImpl.get(),null},null},null},null); } @RestMethod(method=GET, path="/returnTypedBeanMap") public Map<String,TypedBean> returnTypedBeanMap() { return AMap.of("foo",TypedBeanImpl.get()); } @RestMethod(method=GET, path="/returnTypedBeanListMap") public Map<String,List<TypedBean>> returnTypedBeanListMap() { return AMap.of("foo",asList((TypedBean)TypedBeanImpl.get())); } @RestMethod(method=GET, path="/returnTypedBean1d3dListMap") public Map<String,List<TypedBean[][][]>> returnTypedBean1d3dListMap() { return AMap.of("foo", AList.of(new TypedBean[][][]{{{TypedBeanImpl.get(),null},null},null},null)); } @RestMethod(method=GET, path="/returnTypedBeanListMapIntegerKeys") public Map<Integer,List<TypedBean>> returnTypedBeanListMapIntegerKeys() { return AMap.of(1,asList((TypedBean)TypedBeanImpl.get())); } // Swapped POJOs @RestMethod(method=GET, path="/returnSwappedPojo") public SwappedPojo returnSwappedPojo() { return new SwappedPojo(); } @RestMethod(method=GET, path="/returnSwappedPojo3dArray") public SwappedPojo[][][] returnSwappedPojo3dArray() { return new SwappedPojo[][][]{{{new SwappedPojo(),null},null},null}; } @RestMethod(method=GET, path="/returnSwappedPojoMap") public Map<SwappedPojo,SwappedPojo> returnSwappedPojoMap() { return AMap.of(new SwappedPojo(),new SwappedPojo()); } @RestMethod(method=GET, path="/returnSwappedPojo3dMap") public Map<SwappedPojo,SwappedPojo[][][]> returnSwappedPojo3dMap() { return AMap.of(new SwappedPojo(),new SwappedPojo[][][]{{{new SwappedPojo(),null},null},null}); } // Implicit swapped POJOs @RestMethod(method=GET, path="/returnImplicitSwappedPojo") public ImplicitSwappedPojo returnImplicitSwappedPojo() { return new ImplicitSwappedPojo(); } @RestMethod(method=GET, path="/returnImplicitSwappedPojo3dArray") public ImplicitSwappedPojo[][][] returnImplicitSwappedPojo3dArray() { return new ImplicitSwappedPojo[][][]{{{new ImplicitSwappedPojo(),null},null},null}; } @RestMethod(method=GET, path="/returnImplicitSwappedPojoMap") public Map<ImplicitSwappedPojo,ImplicitSwappedPojo> returnImplicitSwappedPojoMap() { return AMap.of(new ImplicitSwappedPojo(),new ImplicitSwappedPojo()); } @RestMethod(method=GET, path="/returnImplicitSwappedPojo3dMap") public Map<ImplicitSwappedPojo,ImplicitSwappedPojo[][][]> returnImplicitSwappedPojo3dMap() { return AMap.of(new ImplicitSwappedPojo(),new ImplicitSwappedPojo[][][]{{{new ImplicitSwappedPojo(),null},null},null}); } // Enums @RestMethod(method=GET, path="/returnEnum") public TestEnum returnEnum() { return TestEnum.TWO; } @RestMethod(method=GET, path="/returnEnum3d") public TestEnum[][][] returnEnum3d() { return new TestEnum[][][]{{{TestEnum.TWO,null},null},null}; } @RestMethod(method=GET, path="/returnEnumList") public List<TestEnum> returnEnumList() { return AList.of(TestEnum.TWO,null); } @RestMethod(method=GET, path="/returnEnum3dList") public List<List<List<TestEnum>>> returnEnum3dList() { return AList.of(AList.of(AList.of(TestEnum.TWO,null),null),null); } @RestMethod(method=GET, path="/returnEnum1d3dList") public List<TestEnum[][][]> returnEnum1d3dList() { return AList.of(new TestEnum[][][]{{{TestEnum.TWO,null},null},null},null); } @RestMethod(method=GET, path="/returnEnumMap") public Map<TestEnum,TestEnum> returnEnumMap() { return AMap.of(TestEnum.ONE,TestEnum.TWO); } @RestMethod(method=GET, path="/returnEnum3dArrayMap") public Map<TestEnum,TestEnum[][][]> returnEnum3dArrayMap() { return AMap.of(TestEnum.ONE,new TestEnum[][][]{{{TestEnum.TWO,null},null},null}); } @RestMethod(method=GET, path="/returnEnum1d3dListMap") public Map<TestEnum,List<TestEnum[][][]>> returnEnum1d3dListMap() { return AMap.of(TestEnum.ONE,AList.of(new TestEnum[][][]{{{TestEnum.TWO,null},null},null},null)); } //----------------------------------------------------------------------------------------------------------------- // Test parameters //----------------------------------------------------------------------------------------------------------------- // Various primitives @RestMethod(method=POST, path="/setInt") public void setInt(@Body int x) { assertEquals(1, x); } @RestMethod(method=POST, path="/setInteger") public void setInteger(@Body Integer x) { assertEquals((Integer)1, x); } @RestMethod(method=POST, path="/setBoolean") public void setBoolean(@Body boolean x) { assertTrue(x); } @RestMethod(method=POST, path="/setFloat") public void setFloat(@Body float x) { assertTrue(1f == x); } @RestMethod(method=POST, path="/setFloatObject") public void setFloatObject(@Body Float x) { assertTrue(1f == x); } @RestMethod(method=POST, path="/setString") public void setString(@Body String x) { assertEquals("foo", x); } @RestMethod(method=POST, path="/setNullString") public void setNullString(@Body String x) { assertNull(x); } @RestMethod(method=POST, path="/setInt3dArray") public String setInt3dArray(@Body int[][][] x) { return ""+x[0][0][0]; } @RestMethod(method=POST, path="/setInteger3dArray") public void setInteger3dArray(@Body Integer[][][] x) { assertObject(x).json().is("[[[1,null],null],null]"); } @RestMethod(method=POST, path="/setString3dArray") public void setString3dArray(@Body String[][][] x) { assertObject(x).json().is("[[['foo',null],null],null]"); } @RestMethod(method=POST, path="/setIntegerList") public void setIntegerList(@Body List<Integer> x) { assertObject(x).json().is("[1,null]"); assertObject(x.get(0)).isType(Integer.class); } @RestMethod(method=POST, path="/setInteger3dList") public void setInteger3dList(@Body List<List<List<Integer>>> x) { assertObject(x).json().is("[[[1,null],null],null]"); assertObject(x.get(0).get(0).get(0)).isType(Integer.class); } @RestMethod(method=POST, path="/setInteger1d3dList") public void setInteger1d3dList(@Body List<Integer[][][]> x) { assertObject(x).json().is("[[[[1,null],null],null],null]"); assertObject(x.get(0)).isType(Integer[][][].class); assertObject(x.get(0)[0][0][0]).isType(Integer.class); } @RestMethod(method=POST, path="/setInt1d3dList") public void setInt1d3dList(@Body List<int[][][]> x) { assertObject(x).json().is("[[[[1,2],null],null],null]"); assertObject(x.get(0)).isType(int[][][].class); } @RestMethod(method=POST, path="/setStringList") public void setStringList(@Body List<String> x) { assertObject(x).json().is("['foo','bar',null]"); } // Beans @RestMethod(method=POST, path="/setBean") public void setBean(@Body ABean x) { assertObject(x).json().is("{a:1,b:'foo'}"); } @RestMethod(method=POST, path="/setBean3dArray") public void setBean3dArray(@Body ABean[][][] x) { assertObject(x).json().is("[[[{a:1,b:'foo'},null],null],null]"); } @RestMethod(method=POST, path="/setBeanList") public void setBeanList(@Body List<ABean> x) { assertObject(x).json().is("[{a:1,b:'foo'}]"); } @RestMethod(method=POST, path="/setBean1d3dList") public void setBean1d3dList(@Body List<ABean[][][]> x) { assertObject(x).json().is("[[[[{a:1,b:'foo'},null],null],null],null]"); } @RestMethod(method=POST, path="/setBeanMap") public void setBeanMap(@Body Map<String,ABean> x) { assertObject(x).json().is("{foo:{a:1,b:'foo'}}"); } @RestMethod(method=POST, path="/setBeanListMap") public void setBeanListMap(@Body Map<String,List<ABean>> x) { assertObject(x).json().is("{foo:[{a:1,b:'foo'}]}"); } @RestMethod(method=POST, path="/setBean1d3dListMap") public void setBean1d3dListMap(@Body Map<String,List<ABean[][][]>> x) { assertObject(x).json().is("{foo:[[[[{a:1,b:'foo'},null],null],null],null]}"); } @RestMethod(method=POST, path="/setBeanListMapIntegerKeys") public void setBeanListMapIntegerKeys(@Body Map<Integer,List<ABean>> x) { assertObject(x).json().is("{'1':[{a:1,b:'foo'}]}"); // Note: JsonSerializer serializes key as string. assertObject(x.keySet().iterator().next()).isType(Integer.class); } // Typed beans @RestMethod(method=POST, path="/setTypedBean") public void setTypedBean(@Body TypedBean x) { assertObject(x).json().is("{a:1,b:'foo'}"); assertObject(x).isType(TypedBeanImpl.class); } @RestMethod(method=POST, path="/setTypedBean3dArray") public void setTypedBean3dArray(@Body TypedBean[][][] x) { assertObject(x).json().is("[[[{a:1,b:'foo'},null],null],null]"); assertObject(x[0][0][0]).isType(TypedBeanImpl.class); } @RestMethod(method=POST, path="/setTypedBeanList") public void setTypedBeanList(@Body List<TypedBean> x) { assertObject(x).json().is("[{a:1,b:'foo'}]"); assertObject(x.get(0)).isType(TypedBeanImpl.class); } @RestMethod(method=POST, path="/setTypedBean1d3dList") public void setTypedBean1d3dList(@Body List<TypedBean[][][]> x) { assertObject(x).json().is("[[[[{a:1,b:'foo'},null],null],null],null]"); assertObject(x.get(0)[0][0][0]).isType(TypedBeanImpl.class); } @RestMethod(method=POST, path="/setTypedBeanMap") public void setTypedBeanMap(@Body Map<String,TypedBean> x) { assertObject(x).json().is("{foo:{a:1,b:'foo'}}"); assertObject(x.get("foo")).isType(TypedBeanImpl.class); } @RestMethod(method=POST, path="/setTypedBeanListMap") public void setTypedBeanListMap(@Body Map<String,List<TypedBean>> x) { assertObject(x).json().is("{foo:[{a:1,b:'foo'}]}"); assertObject(x.get("foo").get(0)).isType(TypedBeanImpl.class); } @RestMethod(method=POST, path="/setTypedBean1d3dListMap") public void setTypedBean1d3dListMap(@Body Map<String,List<TypedBean[][][]>> x) { assertObject(x).json().is("{foo:[[[[{a:1,b:'foo'},null],null],null],null]}"); assertObject(x.get("foo").get(0)[0][0][0]).isType(TypedBeanImpl.class); } @RestMethod(method=POST, path="/setTypedBeanListMapIntegerKeys") public void setTypedBeanListMapIntegerKeys(@Body Map<Integer,List<TypedBean>> x) { assertObject(x).json().is("{'1':[{a:1,b:'foo'}]}"); // Note: JsonSerializer serializes key as string. assertObject(x.get(1).get(0)).isType(TypedBeanImpl.class); } // Swapped POJOs @RestMethod(method=POST, path="/setSwappedPojo") public void setSwappedPojo(@Body SwappedPojo x) { assertTrue(x.wasUnswapped); } @RestMethod(method=POST, path="/setSwappedPojo3dArray") public void setSwappedPojo3dArray(@Body SwappedPojo[][][] x) { assertObject(x).json().is("[[['"+SWAP+"',null],null],null]"); assertTrue(x[0][0][0].wasUnswapped); } @RestMethod(method=POST, path="/setSwappedPojoMap") public void setSwappedPojoMap(@Body Map<SwappedPojo,SwappedPojo> x) { assertObject(x).json().is("{'"+SWAP+"':'"+SWAP+"'}"); Map.Entry<SwappedPojo,SwappedPojo> e = x.entrySet().iterator().next(); assertTrue(e.getKey().wasUnswapped); assertTrue(e.getValue().wasUnswapped); } @RestMethod(method=POST, path="/setSwappedPojo3dMap") public void setSwappedPojo3dMap(@Body Map<SwappedPojo,SwappedPojo[][][]> x) { assertObject(x).json().is("{'"+SWAP+"':[[['"+SWAP+"',null],null],null]}"); Map.Entry<SwappedPojo,SwappedPojo[][][]> e = x.entrySet().iterator().next(); assertTrue(e.getKey().wasUnswapped); assertTrue(e.getValue()[0][0][0].wasUnswapped); } // Implicit swapped POJOs @RestMethod(method=POST, path="/setImplicitSwappedPojo") public void setImplicitSwappedPojo(@Body ImplicitSwappedPojo x) { assertTrue(x.wasUnswapped); } @RestMethod(method=POST, path="/setImplicitSwappedPojo3dArray") public void setImplicitSwappedPojo3dArray(@Body ImplicitSwappedPojo[][][] x) { assertObject(x).json().is("[[['"+SWAP+"',null],null],null]"); assertTrue(x[0][0][0].wasUnswapped); } @RestMethod(method=POST, path="/setImplicitSwappedPojoMap") public void setImplicitSwappedPojoMap(@Body Map<ImplicitSwappedPojo,ImplicitSwappedPojo> x) { assertObject(x).json().is("{'"+SWAP+"':'"+SWAP+"'}"); Map.Entry<ImplicitSwappedPojo,ImplicitSwappedPojo> e = x.entrySet().iterator().next(); assertTrue(e.getKey().wasUnswapped); assertTrue(e.getValue().wasUnswapped); } @RestMethod(method=POST, path="/setImplicitSwappedPojo3dMap") public void setImplicitSwappedPojo3dMap(@Body Map<ImplicitSwappedPojo,ImplicitSwappedPojo[][][]> x) { assertObject(x).json().is("{'"+SWAP+"':[[['"+SWAP+"',null],null],null]}"); Map.Entry<ImplicitSwappedPojo,ImplicitSwappedPojo[][][]> e = x.entrySet().iterator().next(); assertTrue(e.getKey().wasUnswapped); assertTrue(e.getValue()[0][0][0].wasUnswapped); } // Enums @RestMethod(method=POST, path="/setEnum") public void setEnum(@Body TestEnum x) { assertEquals(TestEnum.TWO, x); } @RestMethod(method=POST, path="/setEnum3d") public void setEnum3d(@Body TestEnum[][][] x) { assertObject(x).json().is("[[['TWO',null],null],null]"); } @RestMethod(method=POST, path="/setEnumList") public void setEnumList(@Body List<TestEnum> x) { assertObject(x).json().is("['TWO',null]"); assertObject(x.get(0)).isType(TestEnum.class); } @RestMethod(method=POST, path="/setEnum3dList") public void setEnum3dList(@Body List<List<List<TestEnum>>> x) { assertObject(x).json().is("[[['TWO',null],null],null]"); assertObject(x.get(0).get(0).get(0)).isType(TestEnum.class); } @RestMethod(method=POST, path="/setEnum1d3dList") public void setEnum1d3dList(@Body List<TestEnum[][][]> x) { assertObject(x).json().is("[[[['TWO',null],null],null],null]"); assertObject(x.get(0)).isType(TestEnum[][][].class); } @RestMethod(method=POST, path="/setEnumMap") public void setEnumMap(@Body Map<TestEnum,TestEnum> x) { assertObject(x).json().is("{ONE:'TWO'}"); Map.Entry<TestEnum,TestEnum> e = x.entrySet().iterator().next(); assertObject(e.getKey()).isType(TestEnum.class); assertObject(e.getValue()).isType(TestEnum.class); } @RestMethod(method=POST, path="/setEnum3dArrayMap") public void setEnum3dArrayMap(@Body Map<TestEnum,TestEnum[][][]> x) { assertObject(x).json().is("{ONE:[[['TWO',null],null],null]}"); Map.Entry<TestEnum,TestEnum[][][]> e = x.entrySet().iterator().next(); assertObject(e.getKey()).isType(TestEnum.class); assertObject(e.getValue()).isType(TestEnum[][][].class); } @RestMethod(method=POST, path="/setEnum1d3dListMap") public void setEnum1d3dListMap(@Body Map<TestEnum,List<TestEnum[][][]>> x) { assertObject(x).json().is("{ONE:[[[['TWO',null],null],null],null]}"); Map.Entry<TestEnum,List<TestEnum[][][]>> e = x.entrySet().iterator().next(); assertObject(e.getKey()).isType(TestEnum.class); assertObject(e.getValue().get(0)).isType(TestEnum[][][].class); } //----------------------------------------------------------------------------------------------------------------- // PartFormatter tests //----------------------------------------------------------------------------------------------------------------- @RestMethod(method=POST, path="/partFormatters/{p1}") public String partFormatter( @Path("p1") String p1, @Header("h1") String h1, @Query("q1") String q1, @FormData("f1") String f1 ) throws Exception { assertEquals("dummy-1", p1); assertEquals("dummy-2", h1); assertEquals("dummy-3", q1); assertEquals("dummy-4", f1); return "OK"; } //----------------------------------------------------------------------------------------------------------------- // @RemoteMethod(returns=HTTP_STATUS) //----------------------------------------------------------------------------------------------------------------- @RestMethod(method=GET, path="/httpStatusReturn200") public void httpStatusReturn200(RestResponse res) { res.setStatus(200); } @RestMethod(method=GET, path="/httpStatusReturn404") public void httpStatusReturn404(RestResponse res) { res.setStatus(404); } }
34.949239
186
0.601162
e8cf5e17eb72f5df481e7f8402772a62f1c7474b
25,212
package at.tuwien.service; import at.tuwien.api.database.query.ExecuteQueryDto; import at.tuwien.api.database.query.QueryDto; import at.tuwien.api.database.query.QueryResultDto; import at.tuwien.api.database.table.TableDto; import at.tuwien.entities.database.Database; import at.tuwien.entities.database.query.Query; import at.tuwien.entities.database.table.Table; import at.tuwien.entities.database.table.columns.TableColumn; import at.tuwien.exception.*; import at.tuwien.mapper.ImageMapper; import at.tuwien.mapper.QueryMapper; import at.tuwien.mapper.TableMapper; import at.tuwien.repository.jpa.DatabaseRepository; import at.tuwien.repository.jpa.QueryRepository; import at.tuwien.repository.jpa.TableRepository; import lombok.extern.log4j.Log4j2; import net.sf.jsqlparser.JSQLParserException; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.parser.CCJSqlParserManager; import net.sf.jsqlparser.statement.Statement; import net.sf.jsqlparser.statement.select.*; import net.sf.jsqlparser.statement.select.Select; import org.apache.commons.codec.digest.DigestUtils; import org.jooq.*; import org.jooq.exception.DataAccessException; import org.junit.jupiter.params.shadow.com.univocity.parsers.common.DataProcessingException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.StringReader; import java.math.BigInteger; import java.sql.SQLException; import java.sql.Timestamp; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Optional; import static org.jooq.impl.DSL.*; import static org.jooq.impl.SQLDataType.*; @Log4j2 @Service public class QueryStoreService extends JdbcConnector { public final static String QUERYSTORE_NAME = "userdb_querystore"; public final static String QUERYSTORE_SEQ_NAME = "seq_querystore_id"; private final DatabaseRepository databaseRepository; private final QueryRepository queryRepository; private final TableRepository tableRepository; private final TableMapper tableMapper; private final QueryMapper queryMapper; @Autowired public QueryStoreService(ImageMapper imageMapper, QueryMapper queryMapper, DatabaseRepository databaseRepository, QueryRepository queryRepository, TableRepository tableRepository, TableMapper tableMapper) { super(imageMapper); this.databaseRepository = databaseRepository; this.queryMapper = queryMapper; this.queryRepository = queryRepository; this.tableRepository = tableRepository; this.tableMapper = tableMapper; } @Transactional public List<Query> findAll(Long id) throws ImageNotSupportedException, DatabaseNotFoundException, DatabaseConnectionException, QueryStoreException { final Database database = findDatabase(id); if (!exists(database)) { create(id); } final DSLContext context; try { context = open(database); } catch (SQLException e) { throw new DatabaseConnectionException("Could not connect to remote container", e); } log.trace("select query {}", context.selectQuery() .fetch() .toString()); return queryMapper.recordListToQueryList(context .selectFrom(QUERYSTORE_NAME) .orderBy(field("execution_timestamp")) .fetch()); } @Transactional public QueryDto findOne(Long databaseId, Long queryId) throws DatabaseNotFoundException, ImageNotSupportedException, DatabaseConnectionException, QueryStoreException { Database database = findDatabase(databaseId); final DSLContext context; try { context = open(database); } catch (SQLException e) { throw new DatabaseConnectionException("Could not connect to remote container", e); } log.trace("select query {}", context.selectQuery() .fetch() .toString()); List<org.jooq.Record> records; try { records = context .selectFrom(QUERYSTORE_NAME) .where(condition("id = " + queryId)) .fetch(); } catch (DataAccessException e) { log.error("Failed to select records: {}", e.getMessage()); throw new QueryStoreException("Failed to select records", e); } if (records.size() != 1) { throw new QueryStoreException("Failed to get query from querystore"); } return queryMapper.recordToQueryDto(records.get(0)); } /** * Creates the query store on the remote container for a given database id * mw: unfortunately we cannot provide a default sequence nextval for the id * * @param databaseId The database id * @throws ImageNotSupportedException The image is not supported * @throws DatabaseNotFoundException The database was not found in the metadata database * @throws QueryStoreException Some error with the query store * @throws DatabaseConnectionException The connection to the remote container was not able to be established */ @Transactional public void create(Long databaseId) throws ImageNotSupportedException, DatabaseNotFoundException, QueryStoreException, DatabaseConnectionException { final Database database = findDatabase(databaseId); if (exists(database)) { log.error("Query store already exists for database id {}", databaseId); throw new QueryStoreException("Query store already exists"); } /* create database in container */ try { final DSLContext context = open(database); context.createSequence(QUERYSTORE_SEQ_NAME) .execute(); context.createTable(QUERYSTORE_NAME) .column("id", BIGINT) .column("doi", VARCHAR(255).nullable(false)) .column("title", VARCHAR(255).nullable(false)) .column("query", VARCHAR(255).nullable(false)) .column("query_hash", VARCHAR(255)) .column("execution_timestamp", TIMESTAMP) .column("result_hash", VARCHAR(255)) .column("result_number", BIGINT) .constraints( constraint("pk").primaryKey("id"), constraint("uk").unique("doi") ).execute(); log.info("Created query store in database id {}", databaseId); log.debug("created query store in database {}", database); } catch (SQLException e) { log.error("Failed to create query store: {}", e.getMessage()); throw new DataProcessingException("could not create table", e); } } /** * Saves a query result for a database * * @param database The database. * @param query The query. * @param queryResult The query result. * @return The query with result. * @throws ImageNotSupportedException When not MariaDB. * @throws QueryStoreException When the query store is not found. */ public QueryDto persistQueryResult(Database database, QueryDto query, QueryResultDto queryResult) throws ImageNotSupportedException, QueryStoreException { // TODO map in mapper next iteration query.setExecutionTimestamp(Instant.now()); query.setQueryNormalized(normalizeQuery(query.getQuery())); query.setQueryHash(String.valueOf(query.getQueryNormalized().toLowerCase(Locale.ROOT).hashCode())); query.setResultHash(query.getQueryHash()); query.setResultNumber(0L); try { final DSLContext context = open(database); final BigInteger idVal = nextSequence(database); int success = context.insertInto(table(QUERYSTORE_NAME)) .columns(field("id"), field("doi"), field("title"), field("query"), field("query_hash"), field("execution_timestamp"), field("result_hash"), field("result_number")) .values(idVal, "doi/" + idVal, query.getTitle(), query.getQuery(), query.getQueryHash(), LocalDateTime.ofInstant(query.getExecutionTimestamp(), ZoneId.of("Europe/Vienna")), getResultHash(queryResult), queryResult.getResult().size()) .execute(); log.info("Saved query into query store id {}", query.getId()); log.debug("Saved query into query store {}", query); if (success != 1) { log.error("Failed to insert record into query store"); throw new QueryStoreException("Failed to insert record into query store"); } } catch (SQLException e) { log.error("The mapped query is not valid: {}", e.getMessage()); throw new QueryStoreException("The mapped query is not valid", e); } return query; } // FIXME mw: lel private String normalizeQuery(String query) { return query; } /** * Retrieve the result hash * * @param result The result. * @return The hash. */ private String getResultHash(QueryResultDto result) { return "sha256:" + DigestUtils.sha256Hex(result.getResult().toString()); } @Deprecated private boolean checkValidity(String query) { String queryparts[] = query.toLowerCase().split("from"); if (queryparts[0].contains("select")) { //TODO add more checks return true; } return false; } /** * Executes a query on a database and table. * * @param databaseId The database. * @param tableId The table. * @param data The query data. * @return The query result. * @throws ImageNotSupportedException * @throws DatabaseNotFoundException * @throws QueryStoreException * @throws DatabaseConnectionException * @throws QueryMalformedException * @throws TableNotFoundException */ @Transactional public QueryResultDto execute(Long databaseId, Long tableId, ExecuteQueryDto data) throws ImageNotSupportedException, DatabaseNotFoundException, QueryStoreException, DatabaseConnectionException, QueryMalformedException, TableNotFoundException { final Database database = findDatabase(databaseId); final Table table = findTable(database, tableId); if (database.getContainer().getImage().getDialect().equals("MARIADB")) { if (!exists(database)) { create(databaseId); } } final DSLContext context; try { context = open(database); } catch (SQLException e) { log.error("Failed to connect to the remote database: {}", e.getMessage()); throw new DatabaseConnectionException("Failed to connect to the remote database", e); } final QueryDto queryDto = queryMapper.executeQueryDtoToQueryDto(data); final QueryResultDto queryResultDto = executeQueryOnContext(context, queryDto, database); log.trace("Result of the query is: \n {}", queryResultDto.getResult()); /* save some metadata */ final Query metaQuery = queryMapper.queryDtotoQuery(queryDto); metaQuery.setExecutionTimestamp(null); metaQuery.setTitle(data.getTitle()); metaQuery.setQdbid(databaseId); final Query res = queryRepository.save(metaQuery); log.info("Saved executed query in metadata database id {}", res.getId()); /* save the query in the store */ final QueryDto out = persistQueryResult(database, queryDto, queryResultDto); queryResultDto.setId(out.getId()); log.info("Saved executed query in query store {}", out.getId()); log.debug("query store {}", out); return queryResultDto; } private Query parse(QueryDto query, Database database) throws QueryMalformedException { query.setExecutionTimestamp(query.getExecutionTimestamp()); Statement statement; final CCJSqlParserManager parserRealSql = new CCJSqlParserManager(); try { statement = parserRealSql.parse(new StringReader(query.getQuery())); } catch (JSQLParserException e) { log.error("Could not parse statement"); throw new QueryMalformedException("Could not parse statement", e); } log.trace("given query {}", query.getQuery()); if (statement instanceof net.sf.jsqlparser.statement.select.Select) { final net.sf.jsqlparser.statement.select.Select selectStatement = (Select) statement; final PlainSelect select = (PlainSelect) selectStatement.getSelectBody(); final List<SelectItem> selectItems = select.getSelectItems(); /* parse all tables */ final List<FromItem> items = new ArrayList<>() {{ add(select.getFromItem()); }}; if (select.getJoins() != null && select.getJoins().size() > 0) { for (Join j : select.getJoins()) { if (j.getRightItem() != null) { items.add(j.getRightItem()); } } } //Checking if all tables exist List<TableColumn> allColumns = new ArrayList<>(); for (FromItem item : items) { boolean error = false; log.debug("from item iterated through: {}", item); for (Table t : database.getTables()) { if (item.toString().equals(t.getInternalName()) || item.toString().equals(t.getName())) { allColumns.addAll(t.getColumns()); error = false; break; } error = true; } if (error) { log.error("Table {} does not exist in remote database", item.toString()); throw new QueryMalformedException("Table does not exist in remote database"); } } //Checking if all columns exist for (SelectItem s : selectItems) { String manualSelect = s.toString(); if (manualSelect.trim().equals("*")) { log.warn("Please do not use * ('star select') to query data"); continue; } // ignore prefixes if (manualSelect.contains(".")) { log.debug("manual select {}", manualSelect); manualSelect = manualSelect.split("\\.")[1]; } boolean i = false; for (TableColumn tc : allColumns) { log.trace("table column {}, {}, {}", tc.getInternalName(), tc.getName(), s); if (manualSelect.equals(tc.getInternalName()) || manualSelect.toString().equals(tc.getName())) { i = false; break; } i = true; } if (i) { log.error("Column {} does not exist", s); throw new QueryMalformedException("Column does not exist"); } } //TODO Future work if (select.getWhere() != null) { Expression where = select.getWhere(); log.debug("where clause: {}", where); } return queryMapper.queryDtotoQuery(query); } else { log.error("Provided query is not a select statement, currently we only support 'select' statements"); throw new QueryMalformedException("Provided query is not a select statement"); } } /** * Saves a query without executing it for a database-table tuple. * * @param databaseId The database-table tuple. * @param tableId The database-table tuple. * @param data The query data. * @return The query entity. * @throws ImageNotSupportedException * @throws DatabaseNotFoundException * @throws QueryStoreException * @throws DatabaseConnectionException * @throws QueryMalformedException */ @Transactional public Query saveWithoutExecution(Long databaseId, Long tableId, ExecuteQueryDto data) throws ImageNotSupportedException, DatabaseNotFoundException, QueryStoreException, DatabaseConnectionException, QueryMalformedException, TableNotFoundException { final Database database = findDatabase(databaseId); final Table table = findTable(database, tableId); if (database.getContainer().getImage().getDialect().equals("MARIADB")) { if (!exists(database)) { create(databaseId); } } final QueryDto queryDto = queryMapper.executeQueryDtoToQueryDto(data); final DSLContext context; try { context = open(database); } catch (SQLException e) { throw new QueryMalformedException("Could not connect to the remote container database", e); } final QueryResultDto queryResultDto = executeQueryOnContext(context, queryDto, database); log.trace("Result of the query is: \n {}", queryResultDto.getResult()); /* save some metadata */ final Query metaQuery = queryMapper.queryDtotoQuery(queryDto); metaQuery.setExecutionTimestamp(null); metaQuery.setTitle(data.getTitle()); metaQuery.setQdbid(databaseId); metaQuery.setQtid(tableId); metaQuery.setTable(table); final Query res = queryRepository.save(metaQuery); log.info("Saved query in metadata database id {}", res.getId()); // Save the query in the store // final QueryDto out = saveQuery(database, query, queryResultDto); // queryResultDto.setId(out.getId()); // log.info("Saved query in query store {}", out.getId()); // log.debug("Save query {}", out); // return queryStoreService.findLast(database.getId(), query); // FIXME mw: why query last entry when we set it in the line above? return res; } /** * Re-executes a query with given id in a database by given id, returns a result of size and offset * * @param databaseId The database id * @param queryId The query id * @param page The offset * @param size The size * @return The result set * @throws DatabaseNotFoundException The database was not found in the metadata database * @throws ImageNotSupportedException The image is not supported * @throws DatabaseConnectionException The remote container is not available right now * @throws QueryStoreException There was an error with the query store in the remote container */ public QueryResultDto reexecute(Long databaseId, Long queryId, Integer page, Integer size) throws DatabaseNotFoundException, ImageNotSupportedException, QueryStoreException, QueryMalformedException, DatabaseConnectionException { log.info("re-execute query with the id {}", queryId); final DSLContext context; try { context = open(findDatabase(databaseId)); } catch (SQLException e) { throw new QueryStoreException("Could not establish connection to query store", e); } final QueryDto savedQuery = findOne(databaseId, queryId); final StringBuilder query = new StringBuilder(); query.append("SELECT * FROM ("); final String q = savedQuery.getQuery(); if (q.toLowerCase(Locale.ROOT).contains("where")) { String[] split = q.toLowerCase(Locale.ROOT).split("where"); if (split.length > 2) { //TODO FIX SUBQUERIES WITH MULTIPLE Wheres throw new QueryMalformedException("Query Contains Subqueries, this will be supported in a future version"); } else { query.append(split[0]) .append(" FOR SYSTEM_TIME AS OF TIMESTAMP'") .append(Timestamp.valueOf(savedQuery.getExecutionTimestamp().toString())) .append("' WHERE") .append(split[1]) .append(") as tab"); } } else { query.append(q) .append(" FOR SYSTEM_TIME AS OF TIMESTAMP'") .append(Timestamp.valueOf(savedQuery.getExecutionTimestamp().toString())) .append("') as tab"); } if (page != null && size != null) { page = Math.abs(page); size = Math.abs(size); query.append(" LIMIT ") .append(size) .append(" OFFSET ") .append(page * size); } query.append(";"); final Result<org.jooq.Record> result = context.resultQuery(query.toString()) .fetch(); log.debug("query string {}", query.toString()); log.trace("query result \n {}", result.toString()); return queryMapper.recordListToQueryResultDto(result, queryId); } /** * Find a database in the metadata database by id * * @param id The id. * @return The database. * @throws DatabaseNotFoundException The database is not found. */ @Transactional protected Database findDatabase(Long id) throws DatabaseNotFoundException { final Optional<Database> database = databaseRepository.findById(id); if (database.isEmpty()) { log.error("Database with id {} not found in metadata database", id); throw new DatabaseNotFoundException("Database not found in metadata database"); } return database.get(); } /** * Find a table in the metadata database by database and id * * @param database The database. * @param id The id. * @return The table. * @throws TableNotFoundException The table is not found. */ @Transactional protected Table findTable(Database database, Long id) throws TableNotFoundException { final Optional<Table> table = tableRepository.findByDatabaseAndId(database, id); if (table.isEmpty()) { log.error("Table with id {} not found in metadata database", id); throw new TableNotFoundException("Table not found in metadata database"); } return table.get(); } /** * Checks if a database exists in a remote container * * @param database The database * @return True if exists, false otherwise * @throws ImageNotSupportedException The image is not supported * @throws DatabaseConnectionException The remote container is not reachable */ protected boolean exists(Database database) throws ImageNotSupportedException, DatabaseConnectionException { final DSLContext context; try { context = open(database); } catch (SQLException e) { log.error("Could not connect to remote container: {}", e.getMessage()); throw new DatabaseConnectionException("Could not connect to remote container", e); } return context.select(count()) .from("information_schema.tables") .where("table_name like '" + QUERYSTORE_NAME + "'") .fetchOne(0, int.class) == 1; } /** * Execute query on a remote database context with database metadata to retrieve result * mw: did some refactoring for duplicate code * * @param context The context * @param query The query * @param database The database metadata * @return The result * @throws QueryMalformedException The query mapping is wrong */ protected QueryResultDto executeQueryOnContext(DSLContext context, QueryDto query, Database database) throws QueryMalformedException { final StringBuilder parsedQuery = new StringBuilder(); final String q; q = parse(query, database).getQuery(); if (q.charAt(q.length() - 1) == ';') { parsedQuery.append(q.substring(0, q.length() - 2)); } else { parsedQuery.append(q); } parsedQuery.append(";"); final List<org.jooq.Record> result = context.resultQuery(parsedQuery.toString()) .fetch(); return queryMapper.recordListToQueryResultDto(result, query.getId()); } }
43.770833
138
0.614628
0c8483364762290ab4276850c3e3f42d7b44df8b
6,494
package org.xms.g.tasks; /** * Creates a new CancellationToken or cancels one that has already created.<br/> * Combination of com.huawei.hmf.tasks.CancellationTokenSource and com.google.android.gms.tasks.CancellationTokenSource.<br/> * com.huawei.hmf.tasks.CancellationTokenSource: Creates CancellationToken.<br/> * com.google.android.gms.tasks.CancellationTokenSource: Creates a new CancellationToken or cancels one that has already created. There is a 1:1 CancellationTokenSource to CancellationToken relationship.To create a CancellationToken, create a CancellationTokenSource first and then call getToken() to get the CancellationToken for this CancellationTokenSource.<br/> */ public class CancellationTokenSource extends org.xms.g.utils.XObject { /** * org.xms.g.tasks.CancellationTokenSource.CancellationTokenSource(org.xms.g.utils.XBox) constructor of CancellationTokenSource with XBox.<br/> * Support running environments including both HMS and GMS which are chosen by users.<br/> * Below are the references of HMS apis and GMS apis respectively:<br/> * * @param param0 the wrapper of xms instance */ public CancellationTokenSource(org.xms.g.utils.XBox param0) { super(param0); } /** * org.xms.g.tasks.CancellationTokenSource.cancel() Cancels the CancellationToken if cancellation has not been requested yet.<br/> * Support running environments including both HMS and GMS which are chosen by users.<br/> * Below are the references of HMS apis and GMS apis respectively:<br/> * com.huawei.hmf.tasks.CancellationTokenSource.cancel(): <a href="https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/cancellationtokensource-0000001050121152-V5#EN-US_TOPIC_0000001050121152__section7201020155313">https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/cancellationtokensource-0000001050121152-V5#EN-US_TOPIC_0000001050121152__section7201020155313</a><br/> * com.google.android.gms.tasks.CancellationTokenSource.cancel(): <a href="https://developers.google.com/android/reference/com/google/android/gms/tasks/CancellationTokenSource#public-void-cancel">https://developers.google.com/android/reference/com/google/android/gms/tasks/CancellationTokenSource#public-void-cancel</a><br/> * */ public void cancel() { if (org.xms.g.utils.GlobalEnvSetting.isHms()) { org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hmf.tasks.CancellationTokenSource) this.getHInstance()).cancel()"); ((com.huawei.hmf.tasks.CancellationTokenSource) this.getHInstance()).cancel(); } else { org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.tasks.CancellationTokenSource) this.getGInstance()).cancel()"); ((com.google.android.gms.tasks.CancellationTokenSource) this.getGInstance()).cancel(); } } /** * org.xms.g.tasks.CancellationTokenSource.getToken() Gets the CancellationToken for this CancellationTokenSource.<br/> * Support running environments including both HMS and GMS which are chosen by users.<br/> * Below are the references of HMS apis and GMS apis respectively:<br/> * com.huawei.hmf.tasks.CancellationTokenSource.getToken(): <a href="https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/cancellationtokensource-0000001050121152-V5#EN-US_TOPIC_0000001050121152__section10478151064312">https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/cancellationtokensource-0000001050121152-V5#EN-US_TOPIC_0000001050121152__section10478151064312</a><br/> * com.google.android.gms.tasks.CancellationTokenSource.getToken(): <a href="https://developers.google.com/android/reference/com/google/android/gms/tasks/CancellationTokenSource#public-cancellationtoken-gettoken">https://developers.google.com/android/reference/com/google/android/gms/tasks/CancellationTokenSource#public-cancellationtoken-gettoken</a><br/> * * @return the CancellationToken that can be passed to asynchronous Task to cancel the Task */ public org.xms.g.tasks.CancellationToken getToken() { if (org.xms.g.utils.GlobalEnvSetting.isHms()) { org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hmf.tasks.CancellationTokenSource) this.getHInstance()).getToken()"); com.huawei.hmf.tasks.CancellationToken hReturn = ((com.huawei.hmf.tasks.CancellationTokenSource) this.getHInstance()).getToken(); return ((hReturn) == null ? null : (new org.xms.g.tasks.CancellationToken.XImpl(new org.xms.g.utils.XBox(null, hReturn)))); } else { org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.tasks.CancellationTokenSource) this.getGInstance()).getToken()"); com.google.android.gms.tasks.CancellationToken gReturn = ((com.google.android.gms.tasks.CancellationTokenSource) this.getGInstance()).getToken(); return ((gReturn) == null ? null : (new org.xms.g.tasks.CancellationToken.XImpl(new org.xms.g.utils.XBox(gReturn, null)))); } } /** * org.xms.g.tasks.CancellationTokenSource.dynamicCast(java.lang.Object) dynamic cast the input object to org.xms.g.tasks.CancellationTokenSource.<br/> * Support running environments including both HMS and GMS which are chosen by users.<br/> * * @param param0 the input object * @return casted CancellationTokenSource object */ public static org.xms.g.tasks.CancellationTokenSource dynamicCast(java.lang.Object param0) { return ((org.xms.g.tasks.CancellationTokenSource) param0); } /** * org.xms.g.tasks.CancellationTokenSource.isInstance(java.lang.Object) judge whether the Object is XMS instance or not.<br/> * Support running environments including both HMS and GMS which are chosen by users.<br/> * * @param param0 the input object * @return true if the Object is XMS instance, otherwise false */ public static boolean isInstance(java.lang.Object param0) { if (!(param0 instanceof org.xms.g.utils.XGettable)) { return false; } if (org.xms.g.utils.GlobalEnvSetting.isHms()) { return ((org.xms.g.utils.XGettable) param0).getHInstance() instanceof com.huawei.hmf.tasks.CancellationTokenSource; } else { return ((org.xms.g.utils.XGettable) param0).getGInstance() instanceof com.google.android.gms.tasks.CancellationTokenSource; } } }
72.966292
408
0.733138
cdbaec8735f9220a692b0f9a756e946e7a704f36
2,299
/* * Copyright (c) 2008-2019 Haulmont. * * 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.haulmont.cuba.gui.meta; import java.lang.annotation.*; /** * Indicates that the annotated interface should be available in Studio Screen Designer as a part of UI Component, * e.g. column, action, field, etc. Provides metadata for Properties Panel of Screen Designer. * * When used on the getter or setter method, indicates that the annotated method should be shown in * Studio Screen Designer as a nested element of UI component, e.g. validator, formatter. * Method return type or parameter type will be used to determine element type. */ @Target({ElementType.METHOD, ElementType.TYPE}) @Inherited public @interface StudioElement { /** * @return caption of the element in Studio Screen Designer */ String caption() default ""; /** * @return description of the element in Studio Screen Designer */ String description() default ""; /** * @return UI Components Hierarchy icon, SVG or PNG */ String icon() default ""; /** * @return XML tag of the element */ String xmlElement() default ""; /** * Specifies xml namespace required for the element. * * @return xml namespace */ String xmlns() default ""; /** * Specifies xml namespace alias required for the element. * * @return xml namespace alias */ String xmlnsAlias() default ""; /** * @return name of the default property, it will be automatically selected in Properties panel */ String defaultProperty() default ""; /** * @return names of unsupported properties that should be hidden from Properties panel */ String[] unsupportedProperties() default {}; }
30.653333
114
0.683341
6bcacf3d7f878b6ef7ffe5df6ff4e2111d803de1
1,083
package se.alipsa.r2jdbc.columns; import org.renjin.sexp.AtomicVector; import org.renjin.sexp.StringArrayVector; import org.renjin.sexp.StringVector; import java.sql.ResultSet; import java.sql.SQLException; public class StringColumnBuilder implements ColumnBuilder { private StringArrayVector.Builder vector = new StringVector.Builder(); public static boolean acceptsType(String columnType) { return columnType.equals("string") || columnType.equals("text") || columnType.equals("clob") || columnType.startsWith("varchar") || columnType.startsWith("character") || columnType.endsWith("char") || columnType.equals("date") || columnType.equals("time") || columnType.equals("uniqueidentifier") || columnType.equals("name") || columnType.equals("null") || columnType.equals("unknown"); } @Override public void addValue(ResultSet rs, int columnIndex) throws SQLException { vector.add(rs.getString(columnIndex)); } @Override public AtomicVector build() { return vector.build(); } }
33.84375
117
0.701754
2be48cd52b7035e4595cfb13e4a3f94871ea7ee8
6,326
package io.jenkins.plugins.monitoring; import com.google.common.collect.ImmutableSet; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.Extension; import hudson.model.Run; import hudson.model.TaskListener; import io.jenkins.plugins.monitoring.util.PortletService; import io.jenkins.plugins.monitoring.util.PullRequestFinder; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.jenkinsci.plugins.workflow.steps.Step; import org.jenkinsci.plugins.workflow.steps.StepContext; import org.jenkinsci.plugins.workflow.steps.StepExecution; import org.jenkinsci.plugins.workflow.steps.SynchronousStepExecution; import org.jenkinsci.plugins.workflow.steps.StepDescriptor; import org.json.JSONArray; import org.json.JSONObject; import org.kohsuke.stapler.DataBoundConstructor; import java.io.Serializable; import java.util.*; import java.util.stream.Collectors; /** * This {@link Step} is responsible for the configuration of the monitoring dashboard * via the corresponding Jenkinsfile. * * @author Simon Symhoven */ public final class Monitor extends Step implements Serializable { private static final long serialVersionUID = -1329798203887148860L; private String portlets; /** * Creates a new instance of {@link Monitor}. * * @param portlets * the monitor configuration as json array string. */ @DataBoundConstructor public Monitor(final String portlets) { super(); this.portlets = portlets; } public void setPortlets(String portlets) { this.portlets = portlets; } public String getPortlets() { return portlets; } @Override public StepExecution start(final StepContext stepContext) throws Exception { return new Execution(stepContext, this); } /** * The {@link Execution} routine for the monitoring step. */ static class Execution extends SynchronousStepExecution<Void> { private static final long serialVersionUID = 1300005476208035751L; private final Monitor monitor; Execution(final StepContext stepContext, final Monitor monitor) { super(stepContext); this.monitor = monitor; } @Override public Void run() throws Exception { if (!PortletService.isValidConfiguration(monitor.getPortlets())) { getContext().get(TaskListener.class).getLogger() .println("[Monitor] Portlet Configuration is invalid!"); return null; } JSONArray portlets = new JSONArray(monitor.getPortlets()); getContext().get(TaskListener.class).getLogger() .println("[Monitor] Portlet Configuration: " + portlets.toString(3)); List<String> classes = PortletService.getAvailablePortlets(getContext().get(Run.class)) .stream() .map(MonitorPortlet::getId) .collect(Collectors.toList()); getContext().get(TaskListener.class).getLogger() .println("[Monitor] Available portlets: [" + StringUtils.join(classes, ", ") + "]"); List<String> usedPortlets = new ArrayList<>(); for (Object o : portlets) { JSONObject portlet = (JSONObject) o; String id = portlet.getString("id"); if (usedPortlets.contains(id)) { getContext().get(TaskListener.class).getLogger() .println("[Monitor] Portlet with ID '" + id + "' already defined in list of portlets. Skip adding this portlet!"); } else { usedPortlets.add(id); } } List<String> missedPortletIds = new ArrayList<String>(CollectionUtils.removeAll(usedPortlets, classes)); if (!missedPortletIds.isEmpty()) { getContext().get(TaskListener.class).getLogger() .println("[Monitor] Can't find the following portlets " + missedPortletIds + " in list of available portlets! Will remove from current configuration."); JSONArray cleanedPortlets = new JSONArray(); for (Object o : portlets) { JSONObject portlet = (JSONObject) o; if (!missedPortletIds.contains(portlet.getString("id"))) { cleanedPortlets.put(portlet); } } monitor.setPortlets(cleanedPortlets.toString(3)); getContext().get(TaskListener.class).getLogger() .println("[Monitor] Cleaned Portlets: " + cleanedPortlets.toString(3)); } final Run<?, ?> run = getContext().get(Run.class); if (run == null) { getContext().get(TaskListener.class).getLogger() .println("[Monitor] Run not found!"); return null; } if (PullRequestFinder.isPullRequest(run.getParent())) { getContext().get(TaskListener.class).getLogger() .println("[Monitor] Build is part of a pull request. Add 'MonitoringCustomAction' now."); run.addAction(new MonitoringCustomAction(monitor.getPortlets())); } else { getContext().get(TaskListener.class).getLogger() .println("[Monitor] Build is not part of a pull request. Skip adding 'MonitoringCustomAction'."); } return null; } } /** * A {@link Descriptor} for the monitoring step. */ @Extension public static class Descriptor extends StepDescriptor { @Override public Set<? extends Class<?>> getRequiredContext() { return ImmutableSet.of(TaskListener.class, Run.class); } @Override public String getFunctionName() { return Messages.Step_FunctionName(); } @Override @NonNull public String getDisplayName() { return Messages.Step_DisplayName(); } } }
35.144444
128
0.599431
c12090843386af9f0adf7ac1aa3634cc0994ef23
1,039
package es.upm.miw.apaw_ep_themes.api_controllers; import es.upm.miw.apaw_ep_themes.business_controllers.ArtistBusinessController; import es.upm.miw.apaw_ep_themes.dtos.ArtistDto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(ArtistResource.ARTISTS) public class ArtistResource { static final String ARTISTS = "/artists"; private ArtistBusinessController artistBusinessController; @Autowired public ArtistResource(ArtistBusinessController artistBusinessController) { this.artistBusinessController = artistBusinessController; } @PostMapping public ArtistDto create(@RequestBody ArtistDto artistDto) { artistDto.validate(); return this.artistBusinessController.create(artistDto); } }
34.633333
79
0.810395
20be5d6f3ab5e9d8715be693cc25fd4ea416f1df
4,258
/*-----------------------------------------------------------------------+ | org.conqat.engine.index.incubator | | $Id: CLikeConditionHeuristicTest.java 51565 2015-01-20 13:00:50Z streitel $ | | | Copyright (c) 2009-2013 CQSE GmbH | +-----------------------------------------------------------------------*/ package org.conqat.engine.sourcecode.dataflow.heuristics.clike; import java.io.IOException; import java.util.EnumSet; import java.util.List; import org.conqat.engine.sourcecode.controlflow.Condition; import org.conqat.engine.sourcecode.resource.TokenTestCaseBase; import org.conqat.lib.scanner.ELanguage; import org.conqat.lib.scanner.ETokenType; import org.conqat.lib.scanner.IToken; /** * Tests the condition parsing heuristic for C-like languages. * * @author $Author: streitel $ * @version $Rev: 51565 $ * @ConQAT.Rating YELLOW Hash: BF1D4D1781A6BC6DD7EFC3CDF605DFFD */ public class CLikeConditionHeuristicTest extends TokenTestCaseBase { /** Tests null checks of a single variable. */ public void testSingleCondition() throws IOException { assertCondition("if (a == null) {", "yes=[a=A], no=[a=N], checked=[a]"); assertCondition("if (a != null) {", "yes=[a=N], no=[a=A], checked=[a]"); } /** Tests null-checks chained with other things using &&. */ public void testAndChain() throws IOException { assertCondition("if (a == null && b == null) {", "yes=[a=A, b=A], no=[], checked=[a, b]"); assertCondition("if (a == null && b == null && c == null) {", "yes=[a=A, b=A, c=A], no=[], checked=[a, b, c]"); assertCondition("if (a != null && b != null) {", "yes=[a=N, b=N], no=[], checked=[a, b]"); assertCondition("if (a != null && b == null) {", "yes=[a=N, b=A], no=[], checked=[a, b]"); assertCondition("if (a != null && a.length > 0) {", "yes=[a=N], no=[], checked=[a]"); } /** Tests null-checks chained with other things using ||. */ public void testOrChain() throws IOException { assertCondition("if (a == null || b == null) {", "yes=[], no=[a=N, b=N], checked=[a, b]"); assertCondition("if (a == null || b == null || c == null) {", "yes=[], no=[a=N, b=N, c=N], checked=[a, b, c]"); assertCondition("if (a != null || b != null) {", "yes=[], no=[a=A, b=A], checked=[a, b]"); assertCondition("if (a != null || b == null) {", "yes=[], no=[a=A, b=N], checked=[a, b]"); assertCondition("if (a == null || a.length == 0) {", "yes=[], no=[a=N], checked=[a]"); } /** Tests some conditions that cannot be understood. */ public void testIllegible() throws IOException { assertCondition("if (foo() && a != null || b.c == null) {", "yes=[], no=[], checked=[a]"); assertCondition("if (a != null || b == null && c == null) {", "yes=[], no=[], checked=[a, b, c]"); assertCondition("if ((a != null && a.length > 0) || a == null) {", "yes=[], no=[], checked=[a]"); assertCondition("if (foo()) {", "yes=[], no=[], checked=[]"); } /** Tests other conditional constructs such as "do..while" etc. */ public void testOtherConstructs() throws IOException { assertCondition("while (a == null && b == null) {", "yes=[a=A, b=A], no=[], checked=[a, b]"); assertCondition("} while (a == null && b == null);", "yes=[a=A, b=A], no=[], checked=[a, b]"); assertCondition("else if (a == null && b == null) {", "yes=[a=A, b=A], no=[], checked=[a, b]"); assertCondition("} while (a == null);", "yes=[a=A], no=[a=N], checked=[a]"); assertCondition("else if (a == null) {", "yes=[a=A], no=[a=N], checked=[a]"); } /** * Asserts that the given code parses to a condition with the given string * representation. */ private void assertCondition(String code, String expected) throws IOException { List<IToken> tokens = scan(code, ELanguage.JAVA); CLikeConditionHeuristic heuristic = new CLikeConditionHeuristic(null, EnumSet.of(ETokenType.DOT, ETokenType.LBRACK), EnumSet.of(ETokenType.DOT)); Condition condition = heuristic.parseCondition(tokens); assertEquals("condition(" + expected + ")", condition.toString()); } }
40.169811
90
0.561531
479597d94b454fa738ac995810364e8bbb3b3f13
1,115
package example.indices; import crawler.graph.DefaultNode; import crawler.graph.DirectedGraph; import system.consumer.GraphConsumerInterface; import java.util.ArrayList; import java.util.List; /** * Created by Fabi on 06.03.2015. */ public class LanguageConsumer implements GraphConsumerInterface<DefaultNode<Integer>> { @Override public String getName() { return "languages"; } @Override public String consume(DirectedGraph<DefaultNode<Integer>> graph) { List<String> languages = new ArrayList<>(); for(DefaultNode<Integer> n : graph.getVertices()) { if(!languages.contains(n.<String>getAttribute("language"))) { languages.add(n.<String>getAttribute("language")); } } StringBuilder builder = new StringBuilder(); boolean empty = true; for(String s : languages) { if(!empty) { builder.append(","); } builder.append(s); empty = false; } return builder.toString(); } }
27.195122
88
0.591031
b1e8812d061a66340080b0e9c82cfb0519c50224
1,135
package civitas; import java.util.ArrayList; public class SorpresaSalirCarcel extends Sorpresa{ private MazoSorpresa mazo; SorpresaSalirCarcel(MazoSorpresa _mazo){ super("Quedas libre de la carcel"); mazo = _mazo; } @Override public void aplicarAJugador(int actual, ArrayList<Jugador> todos){ if(super.jugadorCorrecto(actual, todos)){ boolean nadieLaTiene=true; for(int i=0; i<todos.size(); i++){ if(todos.get(i).tieneSalvoconducto()) nadieLaTiene=false; } if(nadieLaTiene){ SorpresaSalirCarcel salirCarcel=new SorpresaSalirCarcel(this.mazo); todos.get(actual).obtenerSalvoconducto(salirCarcel); salirDelMazo(); } } } void salirDelMazo(){ mazo.inhabilitarCartaEspecial(this); } void usada(){ mazo.habilitarCartaEspecial(this); } @Override public String toString(){ return "Sorpresa{ " + super.getTexto() + " }"; } }
25.222222
83
0.557709
54fb93c1f4577521dd86e3376beb8db77aebf107
2,963
package services; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import util.StringUtil; import dao.CommonDAO; import dto.VocabularyDto; import enums.CourseType; public class VocabularyService { /** * Search Vocabulary * * @param lessonId * @return List<VocabularyDto> */ public static List<VocabularyDto> searchVocabulary(Long lessonId) { // Result list List<VocabularyDto> vocabularyDtoList = new ArrayList<VocabularyDto>(); // Get DAO Connection conn = CommonDAO.getDAO(); PreparedStatement stmt = null; ResultSet rs = null; try { // Create SQL StringBuffer sqlQuery = new StringBuffer(); sqlQuery.append(" SELECT \n"); sqlQuery.append(" T3.VOCABULARY_ID \n"); sqlQuery.append(" ,T3.LESSON_COURSE_ID \n"); sqlQuery.append(" ,T3.WORD \n"); sqlQuery.append(" ,T3.KANJI \n"); sqlQuery.append(" ,T3.MEANING \n"); sqlQuery.append(" ,T3.PRONUNCE_FILE \n"); sqlQuery.append(" ,T3.EXPLAIN \n"); sqlQuery.append(" ,T3.ORDER_INDEX \n"); sqlQuery.append(" FROM \n"); sqlQuery.append(" T_LESSON T1 \n"); sqlQuery.append(" ,T_LESSON_COURSE T2 \n"); sqlQuery.append(" ,T_VOCABULARY T3 \n"); sqlQuery.append(" WHERE \n"); sqlQuery.append(" 1 = 1 \n"); sqlQuery.append(" AND T1.LESSON_ID = T2.LESSON_ID \n"); sqlQuery.append(" AND T2.LESSON_COURSE_ID = T3.LESSON_COURSE_ID \n"); sqlQuery.append(" AND T1.LESSON_ID = ? \n"); sqlQuery.append(" AND T2.COURSE_TYPE = ? \n"); sqlQuery.append(" ORDER BY \n"); sqlQuery.append(" T3.ORDER_INDEX \n"); // Create Statement stmt = conn.prepareStatement(sqlQuery.toString()); // Add condition stmt.setLong(1, lessonId); stmt.setString(2, CourseType.VOCABULARY.getCode()); // Execute query rs = stmt.executeQuery(); while (rs.next()) { // Edit Dto VocabularyDto vocabularyDto = new VocabularyDto(); vocabularyDto.setVocabularyId(rs.getLong("VOCABULARY_ID")); vocabularyDto.setLessonCourseId(rs.getLong("LESSON_COURSE_ID")); vocabularyDto.setWord(rs.getString("WORD")); vocabularyDto.setKanji(rs.getString("KANJI")); vocabularyDto.setMeaning(rs.getString("MEANING")); vocabularyDto.setPronunceFile(rs.getString("PRONUNCE_FILE")); vocabularyDto.setExplain(rs.getString("EXPLAIN")); vocabularyDto.setOrderIndex(rs.getInt("ORDER_INDEX")); // Get File if (!StringUtil.isNullOrEmpty(vocabularyDto.getPronunceFile())) { vocabularyDto.setPronunceFileStream( StringUtil.readUploadFile(vocabularyDto.getPronunceFile())); } // Add Dto to List vocabularyDtoList.add(vocabularyDto); } } catch(Exception ex) { ex.printStackTrace(); } finally { try { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } } catch (Exception ex) { } } return vocabularyDtoList; } }
28.490385
74
0.674992
5e52c292a5a3fb93a1f32cf94f49b09182b489e6
8,352
/* * Copyright (c) 2009-2010 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.gde.core.properties; import com.jme3.effect.shapes.EmitterShape; import com.jme3.gde.core.scene.SceneApplication; import com.jme3.gde.core.undoredo.AbstractUndoableSceneEdit; import com.jme3.gde.core.undoredo.SceneUndoRedoManager; import com.jme3.math.ColorRGBA; import com.jme3.math.Matrix3f; import com.jme3.math.Quaternion; import com.jme3.math.Vector2f; import com.jme3.math.Vector3f; import java.lang.reflect.InvocationTargetException; import java.util.Iterator; import java.util.LinkedList; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.logging.Level; import java.util.logging.Logger; import org.openide.nodes.PropertySupport; import org.openide.util.Exceptions; import org.openide.util.Lookup; /** * * @author normenhansen */ @SuppressWarnings("unchecked") public class SceneExplorerProperty<T> extends PropertySupport.Reflection<T> { protected LinkedList<ScenePropertyChangeListener> listeners = new LinkedList<ScenePropertyChangeListener>(); public SceneExplorerProperty(T instance, Class valueType, String getter, String setter) throws NoSuchMethodException { this(instance, valueType, getter, setter, null); } public SceneExplorerProperty(T instance, Class valueType, String getter, String setter, ScenePropertyChangeListener listener) throws NoSuchMethodException { super(instance, valueType, getter, setter); addPropertyChangeListener(listener); if (valueType == Vector3f.class) { setPropertyEditorClass(Vector3fPropertyEditor.class); } else if (valueType == Quaternion.class) { setPropertyEditorClass(QuaternionPropertyEditor.class); } else if (valueType == Matrix3f.class) { setPropertyEditorClass(Matrix3fPropertyEditor.class); } else if (valueType == ColorRGBA.class) { setPropertyEditorClass(ColorRGBAPropertyEditor.class); } else if (valueType == EmitterShape.class) { setPropertyEditorClass(EmitterShapePropertyEditor.class); } else if (valueType == Vector2f.class) { setPropertyEditorClass(Vector2fPropertyEditor.class); } for (SceneExplorerPropertyEditor di : Lookup.getDefault().lookupAll(SceneExplorerPropertyEditor.class)) { di.setEditor(valueType, this); } } @Override public T getValue() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { return super.getValue(); // try { // return SceneApplication.getApplication().enqueue(new Callable<T>() { // // public T call() throws Exception { // return getSuperValue(); // } // }).get(); // } catch (InterruptedException ex) { // Exceptions.printStackTrace(ex); // } catch (ExecutionException ex) { // Exceptions.printStackTrace(ex); // } // return null; } private T getSuperValue() { try { return super.getValue(); } catch (IllegalAccessException ex) { Exceptions.printStackTrace(ex); } catch (IllegalArgumentException ex) { Exceptions.printStackTrace(ex); } catch (InvocationTargetException ex) { Exceptions.printStackTrace(ex); } return null; } @Override public void setValue(final T val) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { try { notifyListeners(getSuperValue(), val); SceneApplication.getApplication().enqueue(new Callable<Void>() { public Void call() throws Exception { setSuperValue(val); return null; } }).get(); } catch (InterruptedException ex) { Exceptions.printStackTrace(ex); } catch (ExecutionException ex) { Exceptions.printStackTrace(ex); } } private void setSuperValue(T val, boolean undo) { try { if (undo) { try { Object oldValue = getSuperValue(); if (oldValue.getClass().getMethod("clone") != null) { addUndo(oldValue.getClass().getMethod("clone").invoke(oldValue), val); Logger.getLogger(SceneExplorerProperty.class.getName()).log(Level.INFO, "Add cloned undo {0}", oldValue.getClass().getMethod("clone").invoke(oldValue)); } } catch (Exception e) { addUndo(getSuperValue(), val); Logger.getLogger(SceneExplorerProperty.class.getName()).log(Level.INFO, "Add undo {0}", getSuperValue()); } } super.setValue(val); } catch (IllegalAccessException ex) { Exceptions.printStackTrace(ex); } catch (IllegalArgumentException ex) { Exceptions.printStackTrace(ex); } catch (InvocationTargetException ex) { Exceptions.printStackTrace(ex); } } private void setSuperValue(T val) { setSuperValue(val, true); } protected void addUndo(final Object before, final Object after) { SceneUndoRedoManager undoRedo = Lookup.getDefault().lookup(SceneUndoRedoManager.class); if (undoRedo == null) { Logger.getLogger(SceneExplorerProperty.class.getName()).log(Level.WARNING, "Cannot access SceneUndoRedoManager"); return; } undoRedo.addEdit(this, new AbstractUndoableSceneEdit() { @Override public void sceneUndo() { Logger.getLogger(SceneExplorerProperty.class.getName()).log(Level.INFO, "Do undo {0}", before); setSuperValue((T) before, false); } @Override public void sceneRedo() { setSuperValue((T) after, false); } @Override public void awtUndo() { } @Override public void awtRedo() { } }); } public void addPropertyChangeListener(ScenePropertyChangeListener listener) { listeners.add(listener); } public void removePropertyChangeListener(ScenePropertyChangeListener listener) { listeners.remove(listener); } private void notifyListeners(Object before, Object after) { for (Iterator<ScenePropertyChangeListener> it = listeners.iterator(); it.hasNext();) { ScenePropertyChangeListener propertyChangeListener = it.next(); propertyChangeListener.propertyChange(getName(), before, after); } } }
39.771429
176
0.656729
8c2e36532520e1129a6c9067a2961dd3e0842b38
2,153
// ============================================================================ // // Copyright (C) 2006-2021 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.designer.maven.ui.setting.project.page; import java.io.IOException; import org.eclipse.jface.dialogs.MessageDialog; import org.talend.commons.exception.ExceptionHandler; import org.talend.core.runtime.projectsetting.AbstractScriptProjectSettingPage; import org.talend.designer.maven.tools.AggregatorPomsHelper; import org.talend.designer.maven.ui.i18n.Messages; /** * DOC ggu class global comment. Detailled comment */ public abstract class AbstractPersistentProjectSettingPage extends AbstractScriptProjectSettingPage { private static boolean isUserIdentified; public AbstractPersistentProjectSettingPage() { super(); if (isUserIdentified) { isUserIdentified = false; } } public void load() throws IOException { // nothing to do } public void save() throws IOException { // nothing to do } @Override public boolean performOk() { boolean ok = super.performOk(); if (ok && getScriptTxt() != null && !getScriptTxt().isDisposed() && !isUserIdentified) { boolean generatePom = MessageDialog.openQuestion(getShell(), "Question", //$NON-NLS-1$ Messages.getString("AbstractPersistentProjectSettingPage.syncAllPoms")); //$NON-NLS-1$ isUserIdentified = true; if (generatePom) { try { save(); new AggregatorPomsHelper().syncAllPoms(); } catch (Exception e) { ExceptionHandler.process(e); } } } return ok; } }
32.621212
106
0.605202
8a680ccf76469d24771936f496d1b06a24485d97
2,459
/* * Copyright 2018. AppDynamics LLC and its affiliates. * All Rights Reserved. * This is unpublished proprietary source code of AppDynamics LLC and its affiliates. * The copyright notice above does not evidence any actual or intended publication of such source code. * */ package com.appdynamics.extensions.snmp.config; import org.apache.log4j.Logger; import java.io.*; import java.util.Properties; import java.util.concurrent.TimeUnit; public class EngineProperties extends Properties{ private static final int DEFAULT_ENGINE_BOOT_COUNT = 0; private long referenceDate = 1443121086695L; //Sept 24 2015 11:159am private static Logger logger = Logger.getLogger(EngineProperties.class); public static final String ENGINE_BOOTS = "engineBoots"; private String propertiesFile; //keeps track of number of times SNMP engine was booted. We keep it 0 and play with the engineTime only. private int engineBoots = DEFAULT_ENGINE_BOOT_COUNT; private int engineTime; public EngineProperties(String propertiesFile) throws IOException { this.propertiesFile = propertiesFile; //load(); calculateProps(); } private void calculateProps() { long currentTime = System.currentTimeMillis(); long prevTime = referenceDate; long timeDiffInMs = TimeUnit.MILLISECONDS.toSeconds(currentTime - prevTime); engineTime = (int)(timeDiffInMs % 2147483648L); } public int getEngineBoots() { return engineBoots; } /*public void load() throws IOException { FileInputStream is = null; try{ is = new FileInputStream(propertiesFile); load(is); engineBoots = Integer.parseInt(getProperty(ENGINE_BOOTS, "0")); } finally { is.close(); } } public void store() throws IOException { engineBoots++; setProperty(ENGINE_BOOTS, Integer.toString(engineBoots)); FileOutputStream fos = null; try { fos = new FileOutputStream(propertiesFile); store(fos,null); } finally { fos.close(); } }*/ @Override public String toString() { return "EngineProperties{" + "engineBoots=" + engineBoots + ",engineTime=" + engineTime + '}'; } public int getEngineTime() { return engineTime; } }
27.629213
108
0.643758
7d3a2a59a12388f69e3636a9f7de0ae50ae79699
1,805
package com.yishuifengxiao.common.crawler.cache; import org.apache.commons.lang3.StringUtils; import org.springframework.data.redis.core.BoundSetOperations; import org.springframework.data.redis.core.RedisTemplate; import java.util.concurrent.TimeUnit; /** * 基于redis实现的资源缓存器 * * @author yishui * @version 1.0.0 * @date 2019年11月28日 */ public class RedisRequestCache implements RequestCache { private RedisTemplate<String, Object> redisTemplate; public RedisRequestCache(RedisTemplate<String, Object> redisTemplate) { this.redisTemplate = redisTemplate; } @Override public boolean lookAndCache(String cacheName, String value) { boolean exist = this.exist(cacheName, value); this.save(cacheName, value); return exist; } @Override public Boolean exist(String cacheName, String value) { return this.getOps(cacheName).isMember(value); } @Override public void remove(String cacheName) { this.getOps(cacheName).expire(1L, TimeUnit.MILLISECONDS); } @Override public Long getCount(String cacheName) { return this.getOps(cacheName).size(); } @Override public void save(String cacheName, String value) { this.getOps(cacheName).add(value); } private BoundSetOperations<String, Object> getOps(String cacheName) { if (StringUtils.isEmpty(cacheName)) { throw new IllegalArgumentException("缓存集合的名字不能为空"); } return this.redisTemplate.boundSetOps(cacheName); } public RedisTemplate<String, Object> getRedisTemplate() { return redisTemplate; } public RedisRequestCache setRedisTemplate(RedisTemplate<String, Object> redisTemplate) { this.redisTemplate = redisTemplate; return this; } }
26.940299
92
0.697507
006361f4f1e2ad82b6628d8ede9dd90be9f831ba
5,265
/** * Copyright 2018 Matt Farmer (github.com/farmdawgnation) * * 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 me.frmr.kafka.connect; import io.confluent.connect.avro.AvroData; import java.io.File; import java.io.IOException; import java.io.ByteArrayOutputStream; import java.util.Map; import org.apache.avro.SchemaParseException; import org.apache.avro.io.DatumReader; import org.apache.avro.io.DatumWriter; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.generic.GenericDatumWriter; import org.apache.avro.generic.GenericRecord; import org.apache.avro.file.CodecFactory; import org.apache.avro.file.DataFileReader; import org.apache.avro.file.DataFileWriter; import org.apache.avro.file.SeekableByteArrayInput; import org.apache.kafka.connect.data.Schema; import org.apache.kafka.connect.data.SchemaAndValue; import org.apache.kafka.connect.errors.DataException; import org.apache.kafka.connect.storage.Converter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Implementation of Converter that uses Avro schemas and objects without * using an external schema registry. Requires that a `schema.path` configuration * option is provided that tells the converter where to find its Avro schema. */ public class RegistrylessAvroConverter implements Converter { private static Logger logger = LoggerFactory.getLogger(RegistrylessAvroConverter.class); /** * The default schema cache size. We pick 50 so that there's room in the cache for some recurring * nested types in a complex schema. */ private Integer schemaCacheSize = 50; private org.apache.avro.Schema avroSchema = null; private Schema connectSchema = null; private AvroData avroDataHelper = null; @Override public void configure(Map<String, ?> configs, boolean isKey) { if (configs.get("schema.cache.size") instanceof Integer) { schemaCacheSize = (Integer) configs.get("schema.cache.size"); } avroDataHelper = new AvroData(schemaCacheSize); if (configs.get("schema.path") instanceof String) { String avroSchemaPath = (String) configs.get("schema.path"); org.apache.avro.Schema.Parser parser = new org.apache.avro.Schema.Parser(); File avroSchemaFile = null; try { avroSchemaFile = new File(avroSchemaPath); avroSchema = parser.parse(avroSchemaFile); connectSchema = avroDataHelper.toConnectSchema(avroSchema); } catch (SchemaParseException spe) { throw new IllegalStateException("Unable to parse Avro schema when starting RegistrylessAvroConverter", spe); } catch (IOException ioe) { throw new IllegalStateException("Unable to parse Avro schema when starting RegistrylessAvroConverter", ioe); } } } @Override public byte[] fromConnectData(String topic, Schema schema, Object value) { DatumWriter<GenericRecord> datumWriter; if (avroSchema != null) { datumWriter = new GenericDatumWriter<GenericRecord>(avroSchema); } else { datumWriter = new GenericDatumWriter<GenericRecord>(); } GenericRecord avroInstance = (GenericRecord)avroDataHelper.fromConnectData(schema, value); try ( ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<GenericRecord>(datumWriter); ) { dataFileWriter.setCodec(CodecFactory.nullCodec()); if (avroSchema != null) { dataFileWriter.create(avroSchema, baos); } else { dataFileWriter.create(avroInstance.getSchema(), baos); } dataFileWriter.append(avroInstance); dataFileWriter.flush(); return baos.toByteArray(); } catch (IOException ioe) { throw new DataException("Error serializing Avro", ioe); } } @Override public SchemaAndValue toConnectData(String topic, byte[] value) { DatumReader<GenericRecord> datumReader; if (avroSchema != null) { datumReader = new GenericDatumReader<>(avroSchema); } else { datumReader = new GenericDatumReader<>(); } GenericRecord instance = null; try ( SeekableByteArrayInput sbai = new SeekableByteArrayInput(value); DataFileReader<GenericRecord> dataFileReader = new DataFileReader<>(sbai, datumReader); ) { instance = dataFileReader.next(instance); if (instance == null) { logger.warn("Instance was null"); } if (avroSchema != null) { return avroDataHelper.toConnectData(avroSchema, instance); } else { return avroDataHelper.toConnectData(instance.getSchema(), instance); } } catch (IOException ioe) { throw new DataException("Failed to deserialize Avro data from topic %s :".format(topic), ioe); } } }
36.818182
116
0.726876
88167fc5f2cf1d24417c0109c8c429ae64f126dd
1,457
package org.vaadin.erik; import com.vaadin.flow.component.AttachEvent; import com.vaadin.flow.component.ComponentEventListener; import com.vaadin.flow.component.UI; import com.vaadin.flow.component.login.AbstractLogin; import com.vaadin.flow.component.login.LoginForm; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.router.Route; /** * @author [email protected] * @since 24/01/2020 */ @Route public class LoginView extends VerticalLayout implements ComponentEventListener<AbstractLogin.LoginEvent> { private LoginForm loginForm; private void initialize() { setAlignItems(Alignment.CENTER); setJustifyContentMode(JustifyContentMode.CENTER); setSizeFull(); loginForm = new LoginForm(); loginForm.setForgotPasswordButtonVisible(false); add(loginForm); loginForm.addLoginListener(this); } @Override public void onAttach(AttachEvent event) { if (event.isInitialAttach()) { initialize(); } } @Override public void onComponentEvent(AbstractLogin.LoginEvent loginEvent) { boolean success = SecurityService.getInstance() .authenticate(loginEvent.getUsername(), loginEvent.getPassword()); if (success) { UI.getCurrent().navigate(SecurityService.getInstance().getDefaultView()); } else { loginForm.setError(true); } } }
28.568627
85
0.693205
46796490496e09fabccb3913c40cb39dedba32d9
3,183
package brickhouse.udf.counter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.apache.hadoop.hive.ql.exec.Description; import org.apache.hadoop.hive.ql.exec.UDF; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.mapreduce.MapContext; import org.apache.hadoop.conf.Configuration; /** * Increment Hadoop counters from a UDF. * * Useful for saving results of a calculation in Hadoop Counters, * which can then be checked for validation, * * Or for tracking progress of a Hive query,based on number of * rows of certain types being processed, to see the * relative distribution of the rows being processed. * * * For example * * INSERT OVERWRITE mytable * SELECT rowGrouping, increment_counter( "My Table Row Groupings", rowGrouping, count(*) ) as rowGroupingCount * FROM otherTable * GROUP BY rowGrouping; * * * Or * SELECT * .... * FROM * ( SELECT id, rowGrouping, increment_counter( "My Table Row Groupings", rowGrouping, 1 ) * FROM otherTable ) cntr * .... * */ @Description( name="increment_counter", value="_FUNC_(string, string, int) - increments the Hadoop counter by specified increment and returns the updated value", extended="SELECT _FUNC_( counterFamily, counter, count(*) ) FROM mytable GROUP BY counterFamily, counter;") public class IncrCounterUDF extends UDF { private Reporter reporter; public Long evaluate( String counterFamily, String counter, int increment) throws HiveException { try { Reporter reporter = getReporter(); reporter.incrCounter( counterFamily, counter, increment); return reporter.getCounter( counterFamily, counter).getValue(); } catch(Exception exc) { throw new HiveException("Error while accessing Hadoop Counters", exc); } } /** * Reporter can be accessed from the * Hive MapredContext, but that * is not available at compile time. * * Use reflection to access it at runtime * @throws ClassNotFoundException * @throws SecurityException * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalArgumentException * @throws IllegalAccessException */ public Reporter getReporter() throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { if(reporter == null) { reporter = GetReporter(); } return reporter; } public static Reporter GetReporter() throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Class clazz = Class.forName("org.apache.hadoop.hive.ql.exec.MapredContext"); Method staticGetMethod = clazz.getMethod("get"); Object mapredObj = staticGetMethod.invoke(null); Class mapredClazz = mapredObj.getClass(); Method getReporter = mapredClazz.getMethod("getReporter"); Object reporterObj= getReporter.invoke( mapredObj); return (Reporter)reporterObj; } }
35.366667
188
0.732014
e4f26ef41025ed814bbd9891391cf9c08af187c8
2,034
/******************************************************************************* * Copyright 2019 Markus Gronau * * This file is part of PowerFlowAnalyzer. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package net.ee.pfanalyzer.ui.viewer.network; public interface INetworkMapParameters { final static double[] ZOOM_GERMANY_COORDINATES = { 5.8, 15.1, 47, 55 }; final static int ZOOM_PERFECT_FIT = 0; final static int ZOOM_CUSTOM = 1; final static int ZOOM_GERMANY = 2; final static String PROPERTY_ZOOM_CHOICE = "ZOOM"; final static String PROPERTY_RESPECT_ASPECT_RATIO = "KEEP_ASPECT_RATIO"; final static String PROPERTY_DRAW_AREAS = "DRAW_AREAS"; final static String PROPERTY_DRAW_BUSSES = "DRAW_BUSSES"; final static String PROPERTY_DRAW_BUS_NAMES = "DRAW_BUS_NAMES"; final static String PROPERTY_DRAW_BRANCHES = "DRAW_BRANCHES"; final static String PROPERTY_DRAW_POWER_DIRECTION = "DRAW_POWER_FLOW_DIRECTION"; final static String PROPERTY_DRAW_GENERATORS = "DRAW_GENERATORS"; final static String PROPERTY_DRAW_OUTLINE = "DRAW_OUTLINE"; final static String PROPERTY_DRAW_LEGEND = "SHOW_LEGEND"; final static String PROPERTY_FADE_OUT_UNSELECTED = "FADE_OUT_UNSELECTED"; final static String PROPERTY_INTERACTION_ZOOM = "ALLOW_ZOOMING"; final static String PROPERTY_INTERACTION_MOVE = "ALLOW_DRAGGING"; final static String PROPERTY_SHOW_TOOLTIPS = "SHOW_TOOLTIPS"; }
46.227273
82
0.70649
97f8a7a78c9ed63de10f9171526c41640345ae92
49,565
/* * Copyright 2011 by Graz University of Technology, Austria * MOCCA has been developed by the E-Government Innovation Center EGIZ, a joint * initiative of the Federal Chancellery Austria and Graz University of Technology. * * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by * the European Commission - subsequent versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * http://www.osor.eu/eupl/ * * Unless required by applicable law or agreed to in writing, software * distributed under the Licence is distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Licence for the specific language governing permissions and * limitations under the Licence. * * This product combines work with different licenses. See the "NOTICE" text * file for details on the various modules and licenses. * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. */ package at.gv.egiz.smcctest; import at.gv.egiz.smcc.SignatureCardException; import at.gv.egiz.smcc.VerifyAPDUSpec; import at.gv.egiz.smcc.util.ISO7816Utils; import at.gv.egiz.smcc.util.TLV; import at.gv.egiz.smcc.util.TLVSequence; import iaik.asn1.ASN1; import iaik.asn1.ASN1Object; import iaik.asn1.CodingException; import iaik.asn1.DerCoder; //import iaik.security.provider.IAIK; import iaik.security.ecc.provider.ECCProvider; import iaik.security.provider.IAIK; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.math.BigInteger; import java.nio.charset.Charset; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.Signature; import java.security.SignatureException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.List; import javax.smartcardio.Card; import javax.smartcardio.CardChannel; import javax.smartcardio.CardException; import javax.smartcardio.CardTerminal; import javax.smartcardio.CommandAPDU; import javax.smartcardio.ResponseAPDU; import javax.smartcardio.TerminalFactory; //import org.junit.After; //import org.junit.AfterClass; //import org.junit.Before; //import org.junit.BeforeClass; //import org.junit.Ignore; //import org.junit.Test; //import org.opensc.pkcs15.asn1.PKCS15Certificate; //import org.opensc.pkcs15.asn1.PKCS15Objects; //import org.opensc.pkcs15.asn1.sequence.SequenceOf; /** * * @author clemens */ public class PKCS15Test { CardTerminal ct; Card icc; boolean liezert; public PKCS15Test() { } // @BeforeClass public static void setUpClass() throws Exception { } // @AfterClass public static void tearDownClass() throws Exception { } // @Before public void setUp() throws NoSuchAlgorithmException, CardException { IAIK.addAsJDK14Provider(); ECCProvider.addAsProvider(); System.out.println("create terminalFactory...\n"); TerminalFactory terminalFactory = TerminalFactory.getInstance("PC/SC", null); System.out.println("get supported terminals...\n"); List<CardTerminal> terminals = terminalFactory.terminals().list(); if (terminals.size() < 1) { throw new CardException("no terminals"); } ct = terminals.get(0); System.out.println("found " + terminals.size() + " terminals, using " + ct.getName() + "\n"); System.out.println("connecting " + ct.getName() + "\n"); icc = ct.connect("*"); byte[] atr = icc.getATR().getBytes(); liezert = Arrays.equals(atr, new byte[] {(byte) 0x3b, (byte) 0xbb, (byte) 0x18, (byte) 0x00, (byte) 0xc0, (byte) 0x10, (byte) 0x31, (byte) 0xfe, (byte) 0x45, (byte) 0x80, (byte) 0x67, (byte) 0x04, (byte) 0x12, (byte) 0xb0, (byte) 0x03, (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x81, (byte) 0x05, (byte) 0x3c}); byte[] historicalBytes = icc.getATR().getHistoricalBytes(); System.out.println("found card " + toString(atr) + " " + new String(historicalBytes, Charset.forName("ASCII")) + "\n\n"); } // @After public void tearDown() { } // @Test // @Ignore public void getEFDIR() throws CardException, SignatureCardException, InstantiationException, CodingException, IOException { CardChannel basicChannel = icc.getBasicChannel(); CommandAPDU cmdAPDU; ResponseAPDU resp; System.out.println("SELECT MF"); cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x00, 0x0c, new byte[] { 0x3F, 0x00}); System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); resp = basicChannel.transmit(cmdAPDU); System.out.println(" -> " + toString(resp.getBytes()) + "\n"); // for (int i = 0x1F00; i <= 0xFFFF; i++) { //// for (int i = 0x5000; i <= 0x6000; i++) { // cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x01, 0x00, new byte[] { (byte) ((i >> 8) & 0xFF), (byte) (i & 0xFF)}, 256); // resp = basicChannel.transmit(cmdAPDU); // if ((i & 0xFF) == 0) { // System.out.println(Integer.toHexString(i)); // } // if (resp.getSW() == 0x9000) { // System.out.println("found [" + Integer.toHexString((i >> 8) & 0xff) + ":" + Integer.toHexString((i) & 0xff) + "]"); // System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); // System.out.println(" -> " + toString(resp.getBytes()) + "\n"); // // byte[] fcx = new TLVSequence(resp.getBytes()).getValue(0x6f); // System.out.println(Integer.toHexString(i) + ": " + new TLVSequence(fcx)); // cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x00, 0x0C, new byte[] { 0x3F, 0x00}); // resp = basicChannel.transmit(cmdAPDU); // } // } System.out.println("SELECT DF.CIA"); // cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x04, 0x00, new byte[] { (byte) 0xE8, (byte) 0x28, (byte) 0xBD, (byte) 0x08, (byte) 0x0F }, 256); cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x04, 0x00, new byte[] { (byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x63,(byte) 0x50,(byte) 0x4B,(byte) 0x43,(byte) 0x53,(byte) 0x2D,(byte) 0x31,(byte) 0x35 }, 256); System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); resp = basicChannel.transmit(cmdAPDU); System.out.println(" -> " + toString(resp.getBytes()) + "\n"); // for (int i = 0x1F00; i <= 0xFFFF; i++) { //// for (int i = 0x5000; i <= 0x6000; i++) { // cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x02, 0x00, new byte[] { (byte) ((i >> 8) & 0xFF), (byte) (i & 0xFF)}, 256); // resp = basicChannel.transmit(cmdAPDU); // if ((i & 0xFF) == 0) { // System.out.println(Integer.toHexString(i)); // } // if (resp.getSW() == 0x9000) { // System.out.println("found [" + Integer.toHexString((i >> 8) & 0xff) + ":" + Integer.toHexString((i) & 0xff) + "]"); // System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); // System.out.println(" -> " + toString(resp.getBytes()) + "\n"); // // byte[] fcx = new TLVSequence(resp.getBytes()).getValue(0x6f); // System.out.println(Integer.toHexString(i) + ": " + new TLVSequence(fcx)); // cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x00, 0x0C, new byte[] { 0x3F, 0x00}); // resp = basicChannel.transmit(cmdAPDU); // } // } System.out.println("SELECT EF 0x0b 0x02"); cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x02, 0x00, new byte[] { (byte) 0x0B,(byte) 0x02 }, 256); System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); resp = basicChannel.transmit(cmdAPDU); System.out.println(" -> " + toString(resp.getBytes()) + "\n"); System.out.println("SELECT EF.CardInfo (P1=02 P2=00)"); cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x02, 0x00, new byte[] { (byte) 0x50,(byte) 0x32 }, 256); System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); resp = basicChannel.transmit(cmdAPDU); System.out.println(" -> " + toString(resp.getBytes()) + "\n"); System.out.println("READ EF.CardInfo"); byte[] efCardInfo = ISO7816Utils.readTransparentFile(basicChannel, -1); System.out.println(toString(efCardInfo)); ASN1Object efCardInfoASN1 = DerCoder.decode(efCardInfo); // try { // FileOutputStream os = new FileOutputStream("EF.CardInfo"); // os.write(efCardInfo); // os.close(); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } System.out.println(ASN1.print(efCardInfoASN1)); System.out.println("SELECT EF.OD"); cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x02, 0x00, new byte[] { (byte) 0x50,(byte) 0x31 }, 256); System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); resp = basicChannel.transmit(cmdAPDU); System.out.println(" -> " + toString(resp.getBytes()) + "\n"); System.out.println("READ EF.OD"); byte[] efod = ISO7816Utils.readTransparentFile(basicChannel, -1); System.out.println(" " + toString(efod)); for (TLV cio : new TLVSequence(efod)) { byte[] val = cio.getValue(); System.out.println("val: "+ toString(val)); byte[] path = Arrays.copyOfRange(val, 4, 4+val[3]); System.out.println("path: "+ toString(path)); System.out.println("\n\nTag = " + (cio.getTag() & 0x0f)); if (cio.getTag() == 0) { System.out.println("cannot decode null data"); continue; } ASN1Object object = DerCoder.decode(cio.getValue()); byte[] fid = (byte[]) object.getComponentAt(0).getValue(); System.out.println("SELECT EF fid=" + toString(fid)); cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x02, 0x04, fid, 256); System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); resp = basicChannel.transmit(cmdAPDU); System.out.println(" -> " + toString(resp.getBytes()) + "\n"); byte[] fcx = new TLVSequence(resp.getBytes()).getValue(0x62); //0x62 for FCP, 0x6f for FCI byte[] fd = new TLVSequence(fcx).getValue(0x82); // System.out.println("cio " + toString(fid) + " fd: " + toString(fd)); if ((fd[0] & 0x04) > 0) { // records int records = fd[fd.length - 1]; for (int record = 1; record < records; record++) { System.out.println("READ RECORD " + record); byte[] ef = ISO7816Utils.readRecord(basicChannel, record); System.out.println(" " + toString(ef)); ASN1Object informationObject = DerCoder.decode(Arrays.copyOfRange(ef, 2, ef.length)); System.out.println(ASN1.print(informationObject)); if (cio.getTag() == 0xa0 || cio.getTag() == 0xa1) { System.out.println("Path = " + toString((byte[]) informationObject.getComponentAt(3) .getComponentAt(0).getComponentAt(0).getComponentAt(0) .getValue())); } } } else if (fd[0] == 0x11) { System.out.println("transparent structure"); byte[] ef = ISO7816Utils.readTransparentFile(basicChannel, -1); // System.out.println(" " + toString(ef)); int i = 0; int j; do { System.out.println("tag: 0x" + Integer.toHexString(ef[i]) + ", length: 0x" + Integer.toHexString(ef[i+1])); int length = 0; int ll = 0; if ((ef[i+1] & 0xf0) == 0x80) { ll = ef[i+1] & 0x7f; for (int it = 0; it < ll; it++) { System.out.println(" + 0x" + Integer.toHexString(ef[i + it+2] & 0xff) ); length = (length << 8) + (ef[i+it+2] & 0xff); System.out.println("length: " + length + " (0x" + Integer.toHexString(length) + ")"); } } else { length = (ef[i+1] & 0xff); } // if ((ef[i+1] & 0xff) == 0x81) { // length = ef[i+2] & 0xff; // j = 3; //// System.out.println("ef["+(i+1)+"]=0x81, setting length=" + (ef[i+2] & 0xff)); // // } else if ((ef[i+1] & 0xff) == 0x82) { // length = ((ef[i+2] & 0xff) << 8) | (ef[i+3] & 0xff); // j = 4; //// System.out.println("ef["+(i+1)+"]=0x82, setting length=" + (((ef[i+2] & 0xff) << 8) | (ef[i+3] & 0xff))); // // } else { // length = ef[i+1] & 0xff; // j = 2; //// System.out.println("ef["+(i+1)+"]=0x" + Integer.toBinaryString(ef[i+1] & 0xff)); // } System.out.println("setting length: 0x" + Integer.toHexString(length)); // if (cio.getTag() == 0xa4) { // byte[] cert = Arrays.copyOfRange(ef, 0, ef.length-1); //// System.out.println("cert 1: \n " + toString(cert)); j = i + 2 + ll + length; System.out.println("reading ef[" + i +"-" + (j-1) + "]:\n" + toString(Arrays.copyOfRange(ef, i, j)) ); ASN1Object informationObject = DerCoder.decode(Arrays.copyOfRange(ef, i, j)); System.out.println(ASN1.print(informationObject)); if (Arrays.equals(fid, new byte[] { (byte)0x44, (byte)0x00})) { byte[] id = (byte[]) informationObject.getComponentAt(1).getComponentAt(0).getValue(); byte[] usage = (byte[]) informationObject.getComponentAt(1).getComponentAt(1).getValue(); byte[] access= (byte[]) informationObject.getComponentAt(1).getComponentAt(2).getValue(); BigInteger keyRef = (BigInteger) informationObject.getComponentAt(1).getComponentAt(3).getValue(); System.out.println("key iD " + toString(id) ); System.out.println("key ref " + keyRef); System.out.println("key usage " + toString(usage)); System.out.println("key access "+ toString(access) ); } else if (Arrays.equals(fid, new byte[] { (byte)0x44, (byte)0x04})) { System.out.println("Certificate (" + informationObject.getComponentAt(0).getComponentAt(0).getValue() + ") path: " + toString((byte[]) informationObject.getComponentAt(2).getComponentAt(0).getComponentAt(0).getComponentAt(0).getValue()) + "\n"); // iaik.me.asn1.ASN1 obj = new iaik.me.asn1.ASN1(Arrays.copyOfRange(ef, i, j)); // byte[] contextSpecific = obj.getElementAt(2).getEncoded(); // System.out.println("JCE ME ASN1 obj: " + toString(contextSpecific)); // if ((contextSpecific[0] & 0xff) != 0xa1) { // System.out.println("WARNING: expected CONTEXTSPECIFIC structure 0xa1, got 0x" + Integer.toHexString(contextSpecific[0])); // } // System.out.println("(contextSpecific[1] & 0xf0) = 0x" + Integer.toHexString(contextSpecific[1] & 0xf0)); // System.out.println("(contextSpecific[1] & 0xf0) == 0x80 " + ((contextSpecific[1] & 0xf0) == 0x80)); // System.out.println("(contextSpecific[1] & 0x0f) = 0x" + Integer.toHexString(contextSpecific[1] & 0x0f) + " = " + (contextSpecific[1] & 0x0f)); // System.out.println("(contextSpecific[1] & 0x0f) + 2 = 0x" + Integer.toHexString((contextSpecific[1] & 0x0f)+2) + " = " + ((contextSpecific[1] & 0x0f)+2)); // // int ll = ((contextSpecific[1] & 0xf0) == 0x80) ? (contextSpecific[1] & 0x0f) + 2 : 2; // System.out.println("ll = " + ll); // System.out.println(toString(Arrays.copyOfRange(contextSpecific, ll, contextSpecific.length))); // if ((contextSpecific[1] & 0xff) == 0x81) { // iaik.me.asn1.ASN1 x509CertificateAttributes = new iaik.me.asn1.ASN1( // Arrays.copyOfRange(contextSpecific, ll, contextSpecific.length)); // System.out.println("path?: " + toString(x509CertificateAttributes.getElementAt(0).getElementAt(0).gvByteArray())); // // } // byte[] ef_qcert = obj.getElementAt(2).getElementAt(0).getElementAt(0) // .getElementAt(0).gvByteArray(); // System.out.println("reading certificate " // + obj.getElementAt(0).getElementAt(0).gvString() // + " from fid=" + toString(ef_qcert)); } i = j; } while (i<ef.length && ef[i]>0); } } // System.out.println("SELECT by Path"); // cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x09, 0x00, new byte[] { (byte) 0x3F, (byte) 0x00, (byte) 0x56, (byte) 0x49 }, 256); // System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); // resp = basicChannel.transmit(cmdAPDU); // System.out.println(" -> " + toString(resp.getBytes()) + "\n"); // // System.out.println(new TLVSequence(new TLVSequence(resp.getData()).getValue(0x6f))); // // byte[] ef = ISO7816Utils.readTransparentFile(basicChannel, -1); // System.out.println(toString(ef)); // // try { // FileOutputStream fileOutputStream = new FileOutputStream("EF.IV"); // fileOutputStream.write(ef); // fileOutputStream.close(); // } catch (FileNotFoundException e1) { // e1.printStackTrace(); // } catch (IOException e1) { // e1.printStackTrace(); // } // // System.out.println("done."); } // @Test // @Ignore public void ecard() throws CardException, SignatureCardException, CodingException { CardChannel basicChannel = icc.getBasicChannel(); CommandAPDU cmdAPDU; ResponseAPDU resp; System.out.println("SELECT MF"); cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x00, 0x0c, new byte[] { (byte) 0x3F, (byte) 0x00 }); System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); resp = basicChannel.transmit(cmdAPDU); System.out.println(" -> " + toString(resp.getBytes()) + "\n"); System.out.println("SELECT EF.CardInfo (P1=02 P2=00)"); cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x02, 0x00, new byte[] { (byte) 0x50,(byte) 0x32 }, 256); System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); resp = basicChannel.transmit(cmdAPDU); System.out.println(" -> " + toString(resp.getBytes()) + "\n"); System.out.println("READ EF.CardInfo"); byte[] efCardInfo = ISO7816Utils.readTransparentFile(basicChannel, -1); System.out.println(toString(efCardInfo)); ASN1Object efCardInfoASN1 = DerCoder.decode(efCardInfo); System.out.println(ASN1.print(efCardInfoASN1)); cmdAPDU = new CommandAPDU(0x00, 0xa4, 0x04, 0x00, new byte[] { (byte) 0xd0, (byte) 0x40, (byte) 0x00, (byte) 0x00, (byte) 0x17, (byte) 0x00, (byte) 0x12, (byte) 0x01 }, 256); System.out.println("SELECT AID " + toString(cmdAPDU.getData())); System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); resp = basicChannel.transmit(cmdAPDU); System.out.println(" -> " + toString(resp.getBytes()) + "\n"); System.out.println(new TLVSequence(new TLVSequence(resp.getData()).getValue(0x6f))); System.out.println("SELECT CERTIFICATE"); cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x02, 0x00, new byte[] { (byte) 0xc0, (byte) 0x00 }, 256); System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); resp = basicChannel.transmit(cmdAPDU); System.out.println(" -> " + toString(resp.getBytes()) + "\n"); X509Certificate certificate = null; try { System.out.println("READ cert?"); CertificateFactory certificateFactory = CertificateFactory.getInstance("X509"); certificate = (X509Certificate) certificateFactory.generateCertificate(ISO7816Utils.openTransparentFileInputStream(basicChannel, -1)); // certificate = certificateFactory.generateCertificate(new BASE64DecoderStream(new ByteArrayInputStream(CERT.getBytes()))); // System.out.println("certificate: \n" + toString(certificate.getEncoded())); System.out.println("certificate: \n" + certificate); } catch (CertificateException e) { e.printStackTrace(); } byte[] fid = new byte[] {(byte) 0x00, (byte) 0x30 }; System.out.println("SELECT EF FID=" + toString(fid)); cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x02, 0x04, fid, 256); System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); resp = basicChannel.transmit(cmdAPDU); System.out.println(" -> " + toString(resp.getBytes()) + "\n"); System.out.println(new TLVSequence(new TLVSequence(resp.getData()).getValue(0x62))); byte[] fcx = new TLVSequence(resp.getBytes()).getValue(0x62); //0x62 for FCP, 0x6f for FCI byte[] fd = new TLVSequence(fcx).getValue(0x82); // System.out.println("cio " + toString(fid) + " fd: " + toString(fd)); if ((fd[0] & 0x04) > 0) { // records int records = fd[fd.length - 1]; for (int record = 1; record < records-1; record++) { System.out.println("READ RECORD " + record); byte[] ef = ISO7816Utils.readRecord(basicChannel, record); System.out.println(" " + toString(ef)); } } } // @Test // @Ignore public void sign() throws CardException, SignatureCardException, InstantiationException, CodingException { CardChannel basicChannel = icc.getBasicChannel(); CommandAPDU cmdAPDU; ResponseAPDU resp; System.out.println("SELECT DF.CIA"); cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x04, 0x00, new byte[] { (byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x63,(byte) 0x50,(byte) 0x4B,(byte) 0x43,(byte) 0x53,(byte) 0x2D,(byte) 0x31,(byte) 0x35 }, 256); System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); resp = basicChannel.transmit(cmdAPDU); System.out.println(" -> " + toString(resp.getBytes()) + "\n"); System.out.println("SELECT CERTIFICATE"); cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x02, 0x00, new byte[] { (byte) 0x0c, (byte) 0x02 }, 256); System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); resp = basicChannel.transmit(cmdAPDU); System.out.println(" -> " + toString(resp.getBytes()) + "\n"); Certificate certificate = null; try { CertificateFactory certificateFactory = CertificateFactory.getInstance("X509"); certificate = certificateFactory.generateCertificate(ISO7816Utils.openTransparentFileInputStream(basicChannel, -1)); // certificate = certificateFactory.generateCertificate(new BASE64DecoderStream(new ByteArrayInputStream(CERT.getBytes()))); System.out.println("Certificate: \n===================================\n" + toString(certificate.getEncoded()) + "\n===================================\n" + certificate + "\n===================================\n"); } catch (CertificateException e) { e.printStackTrace(); } System.out.println("SELECT MF"); cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x00, 0x0c, new byte[] { (byte) 0x3F, (byte) 0x00 }); System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); resp = basicChannel.transmit(cmdAPDU); System.out.println(" -> " + toString(resp.getBytes()) + "\n"); // byte[] fid = new byte[] {(byte) 0x50, (byte) 0x15 }; // System.out.println("SELECT DF FID=" + toString(fid)); // cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x01, 0x00, fid, 256); // System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); // resp = basicChannel.transmit(cmdAPDU); // System.out.println(" -> " + toString(resp.getBytes()) + "\n"); // System.out.println(new TLVSequence(new TLVSequence(resp.getData()).getValue(0x6f))); cmdAPDU = (liezert) ? new CommandAPDU(0x00, 0xA4, 0x04, 0x04, new byte[] { (byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x63,(byte) 0x50,(byte) 0x4B,(byte) 0x43,(byte) 0x53,(byte) 0x2D,(byte) 0x31,(byte) 0x35 }, 256) : new CommandAPDU(0x00, 0xa4, 0x04, 0x00, new byte[] { (byte) 0xd2, (byte) 0x76, (byte) 0x00, (byte) 0x00, (byte) 0x66, (byte) 0x01 }, 256); System.out.println("SELECT AID " + toString(cmdAPDU.getData())); System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); resp = basicChannel.transmit(cmdAPDU); System.out.println(" -> " + toString(resp.getBytes()) + "\n"); System.out.println(new TLVSequence(new TLVSequence(resp.getData()).getValue(0x62))); byte kid = (liezert) ? (byte) 0x82 // don't set to 0x03 (SO Pin, 63c2) : (byte) 0x81; // QuoVadis: 0x81 ?! CommonObjectAttributes.authId = 0x11 System.out.println("VERIFY kid=" + Integer.toHexString(kid & 0xff)); cmdAPDU = ISO7816Utils.createVerifyAPDU(new VerifyAPDUSpec(new byte[] {(byte) 0x00, (byte) 0x20, (byte) 0x00, kid}, 0, VerifyAPDUSpec.PIN_FORMAT_ASCII, (liezert) ? 8 : 0), "123456".toCharArray()); System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); resp = basicChannel.transmit(cmdAPDU); System.out.println(" -> " + toString(resp.getBytes()) + "\n"); // byte[] fid = new byte[] {(byte) 0x00, (byte) 0x30 }; // System.out.println("SELECT EF FID=" + toString(fid)); // cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x02, 0x04, fid, 256); // System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); // resp = basicChannel.transmit(cmdAPDU); // System.out.println(" -> " + toString(resp.getBytes()) + "\n"); // int seid = 1; // System.out.println("RESTORE SE Id " + seid); // cmdAPDU = new CommandAPDU(0x00, 0x22, 0xF3, seid); // System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); // resp = basicChannel.transmit(cmdAPDU); // System.out.println(" -> " + toString(resp.getBytes()) + "\n"); // byte keyRef = (liezert) // ? (byte) 132 //0x84 // : (byte) 2; //QuoVadis: 0x02 // System.out.println("SET DST (key ref: 0x" + Integer.toHexString(keyRef & 0xff) + ")"); // byte[] dst = new byte[] { //// (byte) 0x95, (byte) 0x01, (byte) 0x40, // (byte) 0x84, (byte) 0x03, (byte) 0x80, (byte) (0x80 ^ keyRef), (byte) 0x00, // (byte) 0x89, (byte) 0x03, (byte) 0x13, (byte) 0x23, (byte) 0x10 // }; // cmdAPDU = new CommandAPDU(0x00, 0x22, 0x41, 0xb6, dst, 256); // System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); // resp = basicChannel.transmit(cmdAPDU); // System.out.println(" -> " + toString(resp.getBytes()) + "\n"); int i = 1; byte[] dst = new byte[] { // 3 byte keyRef (key number 1) // (byte) 0x84, (byte) 0x03, (byte) 0x80, (byte) 0x01, (byte) 0xff, // 1 byte keyRef (key number 1) (byte) 0x84, (byte) 0x01, (byte) (0x80 | (i & 0x7f)), //RSA Authentication (byte) 0x89, (byte) 0x02, (byte) 0x23, (byte) 0x13 }; cmdAPDU = new CommandAPDU(0x00, 0x22, 0x41, 0xa4, dst); System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); resp = basicChannel.transmit(cmdAPDU); System.out.println(" -> " + toString(resp.getBytes()) + "\n"); byte[] oid = new byte[] { (byte) 0x30, (byte) 0x21, (byte) 0x30, (byte) 0x09, (byte) 0x06, (byte) 0x05, (byte) 0x2b, (byte) 0x0e, (byte) 0x03, (byte) 0x02, (byte) 0x1a, (byte) 0x05, (byte) 0x00, (byte) 0x04, (byte) 0x14 }; byte[] hash; try { MessageDigest md = MessageDigest.getInstance("SHA-1"); hash = md.digest(); System.out.println("hash value to be signed:\n " + toString(hash)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return; } // byte[] AI = new byte[] { // (byte) 0xF3, (byte) 0x15, (byte) 0x7B, (byte) 0xAC, (byte) 0x94, // (byte) 0xCA, (byte) 0x1D, (byte) 0xC1, (byte) 0xE7, (byte) 0x7D, // (byte) 0xCA, (byte) 0xF5, (byte) 0xF5, (byte) 0x3A, (byte) 0x80, // (byte) 0xEF, (byte) 0x6C, (byte) 0xC2, (byte) 0x1C, (byte) 0xE9 }; ByteArrayOutputStream data = new ByteArrayOutputStream(); try { // oid data.write(oid); // hash data.write(hash); } catch (IOException e) { throw new SignatureCardException(e); } cmdAPDU = new CommandAPDU(0x00, 0x88, 0x00, 0x00, data.toByteArray(), 256); System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); resp = basicChannel.transmit(cmdAPDU); System.out.println(" -> " + toString(resp.getBytes()) + "\n"); // for (int i = 1; i < 256; i++) { // System.out.println("trying alg id " + Integer.toHexString(i & 0xff)); // // final byte[] dst = { // (byte) 0x80, // algorithm reference // // (byte) 0x01, (byte) 0x12, // RSASSA-PKCS1-v1.5 using SHA1 // (byte) 0x01, (byte) (i & 0xff), // RSASSA-PKCS1-v1.5 using SHA1 // (byte) 0x84, // private key reference // (byte) 0x01, (byte) 0x82}; // // (byte) 0x91, (byte) 0x00 }; // random num provided by card // //// System.out.println("SET DST"); // cmdAPDU = new CommandAPDU(0x00, 0x22, 0x41, 0xb6, dst); //// System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); // resp = basicChannel.transmit(cmdAPDU); //// System.out.println(" -> " + toString(resp.getBytes()) + "\n"); // // if (resp.getSW() != 0x6a80) { // System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); // System.out.println(" -> " + toString(resp.getBytes()) + "\n"); // } // } // byte[] fid = new byte[] {(byte) 0x0f, (byte) 0x01 }; // System.out.println("SELECT EF FID=" + toString(fid)); // cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x02, 0x04, fid, 256); // System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); // resp = basicChannel.transmit(cmdAPDU); // System.out.println(" -> " + toString(resp.getBytes()) + "\n"); // System.out.println("READ priv key?"); // byte[] readTransparentFile = ISO7816Utils.readTransparentFile(basicChannel, -1); // System.out.println("read: " + toString(readTransparentFile)); // byte[] hash; // try { // MessageDigest md = MessageDigest.getInstance("SHA-1"); // hash = md.digest(); // System.out.println("hash value to be signed:\n " + toString(hash)); // } catch (NoSuchAlgorithmException e) { // e.printStackTrace(); // return; // } // // System.out.println("HASH"); // byte[] dataObj = new byte[hash.length+2]; // dataObj[0] = (byte) 0x90; // dataObj[1] = (byte) 0x14; // System.arraycopy(hash, 0, dataObj, 2, hash.length); // cmdAPDU = new CommandAPDU(0x00, 0x2a, 0x90, 0xa0, dataObj); // System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); // resp = basicChannel.transmit(cmdAPDU); // System.out.println(" -> " + toString(resp.getBytes()) + "\n"); // // System.out.println("PSO COMPUTE DIGITAL SIGNATURE"); // cmdAPDU = new CommandAPDU(0x00, 0x2A, 0x9E, 0x9A, 256); //data.toByteArray(), // System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); // resp = basicChannel.transmit(cmdAPDU); // System.out.println(" -> " + toString(resp.getBytes()) + "\n"); // // if (resp.getSW() != 0x9000) { // byte[] oid = new byte[] { (byte) 0x30, (byte) 0x21, (byte) 0x30, // (byte) 0x09, (byte) 0x06, (byte) 0x05, (byte) 0x2b, // (byte) 0x0e, (byte) 0x03, (byte) 0x02, (byte) 0x1a, // (byte) 0x05, (byte) 0x00, (byte) 0x04, (byte) 0x14 }; // // ByteArrayOutputStream data = new ByteArrayOutputStream(); // // try { // // oid // data.write(oid); // // hash // data.write(hash); // } catch (IOException e) { // throw new SignatureCardException(e); // } // // System.out.println("PSO COMPUTE DIGITAL SIGNATURE"); // cmdAPDU = new CommandAPDU(0x00, 0x2A, 0x9E, 0x9A, data.toByteArray(), 256); // System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); // resp = basicChannel.transmit(cmdAPDU); // System.out.println(" -> " + toString(resp.getBytes()) + "\n"); // } if (resp.getSW() == 0x9000 && certificate != null) { try { System.out.println("Verifying signature with " + ((X509Certificate) certificate).getIssuerDN()); Signature signature = Signature.getInstance("SHA/RSA"); signature.initVerify(certificate.getPublicKey()); boolean valid = signature.verify(resp.getData()); System.out.println("Signature is " + ((valid) ? "valid" : "invalid")); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (SignatureException e) { e.printStackTrace(); } } } private final static String CERT = //"-----BEGIN CERTIFICATE-----" + "MIIGFDCCBPygAwIBAgICDOEwDQYJKoZIhvcNAQEFBQAwgYYxCzAJBgNVBAYTAkxJ" +"MSMwIQYDVQQKExpMaWVjaHRlbnN0ZWluaXNjaGUgUG9zdCBBRzEoMCYGA1UECxMf" +"SXNzdWluZyBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTEoMCYGA1UEAxMfTGllY2h0" +"ZW5zdGVpbiBQb3N0IFF1YWxpZmllZCBDQTAeFw0xMDA5MDExMjQ5MTJaFw0xMTA5" +"MDExMjQ5MDdaMIHaMQswCQYDVQQGEwJMSTEOMAwGA1UEBxMFVmFkdXoxLDAqBgNV" +"BAoTI0xpZWNodGVuc3RlaW5pc2NoZSBMYW5kZXN2ZXJ3YWx0dW5nMUcwRQYDVQQL" +"Ez5UZXN0IGNlcnRpZmljYXRlIChubyBsaWFiaWxpdHkpIFRlc3R6ZXJ0aWZpa2F0" +"IChrZWluZSBIYWZ0dW5nKTErMCkGA1UECxMiQW10IGZ1ZXIgUGVyc29uYWwgdW5k" +"IE9yZ2FuaXNhdGlvbjEXMBUGA1UEAxMOVEVTVCBMTFYgQVBPIDIwggEiMA0GCSqG" +"SIb3DQEBAQUAA4IBDwAwggEKAoIBAQChDpzPyb0NIuqi+UGCOhypcODFMKas1kTw" +"HPyLW2ZdtqzmrgO7Q7Y5jm2CpPdCkd61Z+/lswEB+wPgSe+YnnNuytYtM0uYaNv9" +"UNxc6CmlthIOJTK2+VP9lwIOsS61Jr+boTEXjXszFVwkO288wGJtCB3SG6IZja6l" +"UD/veXoJckC5OIS43V6CqOKcyz6CNhu+OhKTwgqd07KXzzEdUeLemrgrNP9/qnDz" +"xnDiRtyu/zocCG9xR7Rq6ZNwX69JNPi6AljsAvMucM7bhdbW8pyPKVUEhBFLduM0" +"hmQYpodANUnPtpXA5ksxcgSWn/SdTuJ8VbG8SrvSR+1b70Coef0fAgMBAAGjggI0" +"MIICMDCB/gYDVR0gBIH2MIHzMAgGBgQAizABATCB5gYKKwYBBAG+WAGDEDCB1zCB" +"ngYIKwYBBQUHAgIwgZEagY5SZWxpYW5jZSBvbiB0aGUgUXVvVmFkaXMgUm9vdCBD" +"ZXJ0aWZpY2F0ZSBieSBhbnkgcGFydHkgYXNzdW1lcyBhY2NlcHRhbmNlIG9mIHRo" +"ZSBRdW9WYWRpcyBDZXJ0aWZpY2F0ZSBQb2xpY3kvQ2VydGlmaWNhdGlvbiBQcmFj" +"dGljZSBTdGF0ZW1lbnQuMDQGCCsGAQUFBwIBFihodHRwOi8vd3d3LnF1b3ZhZGlz" +"Z2xvYmFsLmNvbS9yZXBvc2l0b3J5MC4GCCsGAQUFBwEDBCIwIDAKBggrBgEFBQcL" +"AjAIBgYEAI5GAQEwCAYGBACORgEEMHIGCCsGAQUFBwEBBGYwZDAqBggrBgEFBQcw" +"AYYeaHR0cDovL29jc3AucXVvdmFkaXNnbG9iYWwuY29tMDYGCCsGAQUFBzAChipo" +"dHRwOi8vdHJ1c3QucXVvdmFkaXNnbG9iYWwuY29tL2xpcHFjYS5jcnQwDgYDVR0P" +"AQH/BAQDAgbAMB8GA1UdIwQYMBaAFPsbkJP9mNp/kmoaRiY20fOPhwDgMDkGA1Ud" +"HwQyMDAwLqAsoCqGKGh0dHA6Ly9jcmwucXVvdmFkaXNnbG9iYWwuY29tL2xpcHFj" +"YS5jcmwwHQYDVR0OBBYEFADlv8IBR5ga0KjxSiByi2T1whHEMA0GCSqGSIb3DQEB" +"BQUAA4IBAQB4LzgcpNxKcGwxdbep1E6MiXk3gwS6kq06Iaf7Ar/By2SuyLB8l0B7" +"myk8VvkIGVCP0f+i7WxblUV5xqXP2Itnq7Ynm4A5qdUkBZuXvOGY2sOtjNttqdnv" +"oemsshz3QIEBwlh10SZZbwtVv7W7uy0xUwbsWFX0r8/jiQyVANyPRQ+KqW+H6U05" +"13FG5da/AgXvUGGLYVDk66qGYn/TlGBgj8ijvWqqbZ94vvbog/rwGHG+P+0JMRTS" +"QsNR8hmlgd8OLwWc1SFB5TrDsjkDTCQHce/MJ0n6YNPXQr8EHWpu5And2gzmWrYh" +"Cx5l+gCuh6N9ITOAFmyc1gleyNdTenEE"; // +"-----END CERTIFICATE-----"; // @Ignore public void directoryListing(CommandAPDU cmdAPDU, ResponseAPDU resp, CardChannel basicChannel) throws CardException, SignatureCardException { byte[] dir = new byte[] {(byte) 0x50, (byte) 0x15}; System.out.println("SELECT MF"); cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x00, 0x0c, new byte[] { (byte) 0x3F, (byte) 0x00 }, 256); System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); resp = basicChannel.transmit(cmdAPDU); System.out.println(" -> " + toString(resp.getBytes()) + "\n"); // System.out.println("SELECT DF.CIA"); // cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x04, 0x00, new byte[] { (byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x63,(byte) 0x50,(byte) 0x4B,(byte) 0x43,(byte) 0x53,(byte) 0x2D,(byte) 0x31,(byte) 0x35 }, 256); // System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); // resp = basicChannel.transmit(cmdAPDU); // System.out.println(" -> " + toString(resp.getBytes()) + "\n"); System.out.println("SELECT [50:15]"); cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x01, 0x04, dir, 256); System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); resp = basicChannel.transmit(cmdAPDU); System.out.println(" -> " + toString(resp.getBytes()) + "\n"); for (int i = 0x1F00; i <= 0xFFFF; i++) { // for (int i = 0x0000; i <= 0x1F00; i++) { cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x02, 0x04, new byte[] { (byte) ((i >> 8) & 0xFF), (byte) (i & 0xFF)}, 256); resp = basicChannel.transmit(cmdAPDU); if ((i & 0xFF) == 0) { System.out.println(Integer.toHexString(i)); } if (resp.getSW() == 0x9000) { System.out.println("found [" + Integer.toHexString((i >> 8) & 0xff) + ":" + Integer.toHexString((i) & 0xff) + "]"); System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); System.out.println(" -> " + toString(resp.getBytes()) + "\n"); // byte[] fcx = new TLVSequence(resp.getBytes()).getValue(0x6f); // System.out.println(Integer.toHexString(i) + ": " + new TLVSequence(fcx)); cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x00, 0x0C, new byte[] { 0x3F, 0x00}); resp = basicChannel.transmit(cmdAPDU); cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x01, 0x04, dir); resp = basicChannel.transmit(cmdAPDU); } } } // @Test // @Ignore public void verify() throws CardException { CardChannel basicChannel = icc.getBasicChannel(); CommandAPDU cmdAPDU; ResponseAPDU resp; byte kid = (liezert) ? (byte) 0x82 // don't set to 0x03 (SO Pin, 63c2) : (byte) 0x81; // QuoVadis: 0x81 ?! CommonObjectAttributes.authId = 0x11 System.out.println("VERIFY kid=" + Integer.toHexString(kid & 0xff)); cmdAPDU = ISO7816Utils.createVerifyAPDU(new VerifyAPDUSpec(new byte[] {(byte) 0x00, (byte) 0x20, (byte) 0x00, kid}, 0, VerifyAPDUSpec.PIN_FORMAT_ASCII, (liezert) ? 8 : 0), "123456".toCharArray()); System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); resp = basicChannel.transmit(cmdAPDU); System.out.println(" -> " + toString(resp.getBytes()) + "\n"); cmdAPDU = new CommandAPDU(0x00, 0x20, 0x00, kid); System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); resp = basicChannel.transmit(cmdAPDU); System.out.println(" -> " + toString(resp.getBytes()) + "\n"); } // @Test // @Ignore public void selectAndRead() throws CardException, SignatureCardException { CardChannel basicChannel = icc.getBasicChannel(); CommandAPDU cmdAPDU; ResponseAPDU resp; System.out.println("SELECT MF"); cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x00, 0x0c, new byte[] { (byte) 0x3F, (byte) 0x00 }, 256); System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); resp = basicChannel.transmit(cmdAPDU); System.out.println(" -> " + toString(resp.getBytes()) + "\n"); System.out.println("SELECT DF.CIA"); cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x04, 0x04, new byte[] { (byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x63,(byte) 0x50,(byte) 0x4B,(byte) 0x43,(byte) 0x53,(byte) 0x2D,(byte) 0x31,(byte) 0x35 }, 256); System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); resp = basicChannel.transmit(cmdAPDU); System.out.println(" -> " + toString(resp.getBytes()) + "\n"); // byte kid = (liezert) // ? (byte) 0x82 // don't set to 0x03 (SO Pin, 63c2) // : (byte) 0x81; // QuoVadis: 0x81 ?! CommonObjectAttributes.authId = 0x11 // System.out.println("VERIFY kid=" + Integer.toHexString(kid & 0xff)); // cmdAPDU = ISO7816Utils.createVerifyAPDU(new VerifyAPDUSpec(new byte[] {(byte) 0x00, (byte) 0x20, (byte) 0x00, kid}, 0, VerifyAPDUSpec.PIN_FORMAT_ASCII, (liezert) ? 8 : 0), "123456".toCharArray()); // System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); // resp = basicChannel.transmit(cmdAPDU); // System.out.println(" -> " + toString(resp.getBytes()) + "\n"); byte[][] fids = new byte[][] {{(byte)0x00,(byte)0x12}, {(byte)0x00,(byte)0x13}, {(byte)0x00,(byte)0x15}, {(byte)0x00,(byte)0x16}, {(byte)0x00,(byte)0x30}, {(byte)0x00,(byte)0x37}, {(byte)0x0c,(byte)0x02}, {(byte)0x0e,(byte)0x01}, {(byte)0x0e,(byte)0x02}, {(byte)0x0f,(byte)0x01}, {(byte)0x0f,(byte)0x02}, {(byte)0x44,(byte)0x00}, {(byte)0x44,(byte)0x01}, {(byte)0x50,(byte)0x31}, {(byte)0x50,(byte)0x32}, {(byte)0x53,(byte)0x42}, {(byte)0x53,(byte)0x62}, {(byte)0xae,(byte)0x0a}}; for (int i = 0; i < fids.length; i++) { System.out.println("SELECT EF " + toString(fids[i])); cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x02, 0x04, fids[i], 256); // System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); resp = basicChannel.transmit(cmdAPDU); // System.out.println(" -> " + toString(resp.getBytes()) + "\n"); byte[] fcx = new TLVSequence(resp.getBytes()).getValue(0x62); //0x62 for FCP, 0x6f for FCI try { readFile(basicChannel, fids[i], fcx); } catch (Exception ex) { System.out.println("************ read failed: " + ex.getMessage()); } } } protected void readFile(CardChannel channel, byte[] fid, byte[] fcx) throws CardException, SignatureCardException, CodingException { byte[] fd = new TLVSequence(fcx).getValue(0x82); if ((fd[0] & 0x04) > 0 || fd[0] == 0x12) { System.out.println(" records"); int records = fd[fd.length - 1]; for (int record = 1; record < records; record++) { // System.out.println(" READ RECORD " + record); byte[] ef = ISO7816Utils.readRecord(channel, record); // System.out.println(" " + toString(ef)); // ASN1Object informationObject = DerCoder.decode(Arrays.copyOfRange(ef, 2, ef.length)); // System.out.println(ASN1.print(informationObject)); } } else if (fd[0] == 0x11) { System.out.println(" transparent structure"); byte[] ef = ISO7816Utils.readTransparentFile(channel, -1); // System.out.println(" " + toString(ef)); // int length; // int i = 0; // int j; // // do { // System.out.println("tag: 0x" + Integer.toHexString(ef[i]) + ", length: 0x" + Integer.toHexString(ef[i+1])); // if ((ef[i+1] & 0xff) == 0x81) { // length = ef[i+2] & 0xff; // j = 3; //// System.out.println("ef["+(i+1)+"]=0x81, setting length=" + (ef[i+2] & 0xff)); // // } else if ((ef[i+1] & 0xff) == 0x82) { // length = ((ef[i+2] & 0xff) << 8) | (ef[i+3] & 0xff); // j = 4; //// System.out.println("ef["+(i+1)+"]=0x82, setting length=" + (((ef[i+2] & 0xff) << 8) | (ef[i+3] & 0xff))); // // } else { // length = ef[i+1] & 0xff; // j = 2; //// System.out.println("ef["+(i+1)+"]=0x" + Integer.toBinaryString(ef[i+1] & 0xff)); // } // // System.out.println("setting length: 0x" + Integer.toHexString(length)); // //// if (cio.getTag() == 0xa4) { //// byte[] cert = Arrays.copyOfRange(ef, 0, ef.length-1); ////// System.out.println("cert 1: \n " + toString(cert)); // // j = i + j + length; // System.out.println("reading ef[" + i +"-" + (j-1) + "]:\n" + toString(Arrays.copyOfRange(ef, i, j)) ); // ASN1Object informationObject = DerCoder.decode(Arrays.copyOfRange(ef, i, j)); // System.out.println(ASN1.print(informationObject)); // i = j; // } while (i<ef.length && ef[i]>0); } else { System.out.println(" structure not supported: 0x" + Integer.toHexString(fd[0])); } } // @Ignore public void todo(Certificate certificate, CommandAPDU cmdAPDU, ResponseAPDU resp, CardChannel basicChannel) throws CardException, SignatureCardException { // System.out.println("SELECT by Path"); // cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x09, 0x00, new byte[] { (byte) 0x3F, (byte) 0x00, (byte) 0x56, (byte) 0x49 }, 256); // System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); // resp = basicChannel.transmit(cmdAPDU); // System.out.println(" -> " + toString(resp.getBytes()) + "\n"); // //// System.out.println(new TLVSequence(new TLVSequence(resp.getData()).getValue(0x6f))); // // byte[] ef = ISO7816Utils.readTransparentFile(basicChannel, -1); // System.out.println(toString(ef)); // // try { // FileOutputStream fileOutputStream = new FileOutputStream("EF.IV"); // fileOutputStream.write(ef); // fileOutputStream.close(); // } catch (FileNotFoundException e1) { // e1.printStackTrace(); // } catch (IOException e1) { // e1.printStackTrace(); // } // // System.out.println("done."); final byte[] AID = new byte[] {(byte) 0xd2, (byte) 0x76, (byte) 0x00, (byte) 0x00, (byte) 0x66, (byte) 0x01}; System.out.println("SELECT Application (" + toString(AID) + ")"); cmdAPDU = new CommandAPDU(0x00, 0xA4, 0x04, 0x00, AID, 256); System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); resp = basicChannel.transmit(cmdAPDU); System.out.println(" -> " + toString(resp.getBytes()) + "\n"); System.out.println(new TLVSequence(new TLVSequence(resp.getData()).getValue(0x6f))); // int seid = 1; // cmdAPDU = new CommandAPDU(0x00, 0x22, 0xF3, seid); // System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); // resp = basicChannel.transmit(cmdAPDU); // System.out.println(" -> " + toString(resp.getBytes()) + "\n"); System.out.println("VERIFY"); cmdAPDU = new CommandAPDU(0x00, 0x20, 0x00, 0x81, "123456".getBytes(Charset.forName("ASCII")), 256); System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); resp = basicChannel.transmit(cmdAPDU); System.out.println(" -> " + toString(resp.getBytes()) + "\n"); byte[] hash; try { MessageDigest md = MessageDigest.getInstance("SHA-1"); hash = md.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return; } byte[] oid = new byte[] { (byte) 0x30, (byte) 0x21, (byte) 0x30, (byte) 0x09, (byte) 0x06, (byte) 0x05, (byte) 0x2b, (byte) 0x0e, (byte) 0x03, (byte) 0x02, (byte) 0x1a, (byte) 0x05, (byte) 0x00, (byte) 0x04, (byte) 0x14 }; ByteArrayOutputStream data = new ByteArrayOutputStream(); try { // oid data.write(oid); // hash data.write(hash); } catch (IOException e) { throw new SignatureCardException(e); } System.out.println("PSO COMPUTE DIGITAL SIGNATURE"); cmdAPDU = new CommandAPDU(0x00, 0x2A, 0x9E, 0x9A, data.toByteArray(), 256); System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); resp = basicChannel.transmit(cmdAPDU); System.out.println(" -> " + toString(resp.getBytes()) + "\n"); if (resp.getSW() == 0x9000 && certificate != null) { try { System.out.println("Verifying signature with " + ((X509Certificate) certificate).getSubjectDN()); Signature signature = Signature.getInstance("SHA/RSA"); signature.initVerify(certificate.getPublicKey()); boolean valid = signature.verify(resp.getData()); System.out.println("Signature is " + ((valid) ? "valid" : "invalid")); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (SignatureException e) { e.printStackTrace(); } } // final byte[] data = new byte[] {}; //new byte[] {(byte) 0x7B, (byte) 0x02, (byte) 0xB6, (byte) 0x80}; // // System.out.println("GET DATA"); // for (int i = 0x004D; i <= 0x004D; i++) { // cmdAPDU = new CommandAPDU(0x00, 0xCA, 0xFF & (i >> 8), 0xFF & i, data , 256); // resp = basicChannel.transmit(cmdAPDU); // if (resp.getSW() == 0x9000) { // if (i == 0x180) { // try { // System.out.println(new String(resp.getData(), "ASCII")); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // } else { // System.out.println(Integer.toHexString(i) + " -> " + toString(resp.getData())); // } // } // } // final byte[] DST = new byte[] {}; // // System.out.println("MSE SET DST (" + toString(DST) + ")"); // cmdAPDU = new CommandAPDU(0x00, 0x22, 0x04, 0x01, DST); // System.out.println(" cmd apdu " + toString(cmdAPDU.getBytes())); // resp = basicChannel.transmit(cmdAPDU); // System.out.println(" -> " + toString(resp.getBytes()) + "\n"); } public static String toString(byte[] b) { StringBuffer sb = new StringBuffer(); sb.append('['); if (b != null && b.length > 0) { sb.append(Integer.toHexString((b[0] & 240) >> 4)); sb.append(Integer.toHexString(b[0] & 15)); for (int i = 1; i < b.length; i++) { sb.append((i % 32 == 0) ? '\n' : ':'); sb.append(Integer.toHexString((b[i] & 240) >> 4)); sb.append(Integer.toHexString(b[i] & 15)); } } sb.append(']'); return sb.toString(); } public static void main(String[] args) { try { System.out.println("manually running pkcs15 test..."); PKCS15Test test = new PKCS15Test(); test.setUp(); // test.getEFDIR(); test.sign(); // test.selectAndRead(); } catch (Exception ex) { ex.printStackTrace(); } } }
44.096975
319
0.615636
10e2e9b6536a7d6a9a152f87ae2563d4fc110c57
1,527
package com.pon.ents.base.functional; import java.util.function.Consumer; import java.util.function.Predicate; public abstract class MorePredicates { /** * Returns a {@link Predicate} that accepts instances of the given {@link Class}. */ public static <T> Predicate<T> isInstanceOf(Class<? extends T> cls) { return cls::isInstance; } /** * Returns a {@link Predicate} that will additionally {@link Consumer consume} every element that is accepted by the * given {@link Predicate}. * <p> * This is in general discouraged; the {@link Consumer} should not have a side-effect. */ public static <T> Predicate<T> afterAccepting(Predicate<T> underlying, Consumer<? super T> consumer) { return element -> { if (underlying.test(element)) { consumer.accept(element); return true; } else { return false; } }; } /** * Returns a {@link Predicate} that will additionally {@link Consumer consume} every element before testing it using * the given {@link Predicate}. * <p> * This is in general discouraged; the {@link Consumer} should not have a side-effect. */ public static <T> Predicate<T> beforeTesting(Consumer<? super T> consumer, Predicate<T> underlying) { return element -> { consumer.accept(element); return underlying.test(element); }; } }
33.933333
121
0.595285
61414113e6097a49ddaa5ad46ecf4160e1a88d5d
7,050
package com.yikekong.service.impl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.yikekong.dto.*; import com.yikekong.entity.AlarmEntity; import com.yikekong.influx.InfluxRepository; import com.yikekong.mapper.AlarmMapper; import com.yikekong.service.AlarmService; import com.yikekong.vo.Pager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.List; @Service public class AlarmServiceImpl extends ServiceImpl<AlarmMapper, AlarmEntity> implements AlarmService{ @Override public IPage<AlarmEntity> queryPage(Long page,Long pageSize,String alarmName, Integer quotaId) { LambdaQueryWrapper<AlarmEntity> wrapper = new LambdaQueryWrapper<>(); if(!Strings.isNullOrEmpty(alarmName)){ wrapper.like(AlarmEntity::getName,alarmName); } if(quotaId != null){ wrapper.eq(AlarmEntity::getQuotaId,quotaId); } wrapper.orderByDesc(AlarmEntity::getId); //wrapper.orderByDesc(AlarmEntity::getCreateTime); Page<AlarmEntity> pageResult = new Page<>(page,pageSize); return this.page(pageResult,wrapper); } @Override public List<AlarmEntity> getByQuotaId(Integer quotaId) { QueryWrapper<AlarmEntity> wrapper = new QueryWrapper<>(); wrapper .lambda() .eq(AlarmEntity::getQuotaId,quotaId) .orderByDesc(AlarmEntity::getLevel); return this.list(wrapper); } @Override public AlarmEntity verifyQuota(QuotaDTO quotaDTO) { //1.根据指标id查询告警判断规则列表 List<AlarmEntity> alarmEntityList = getByQuotaId(quotaDTO.getId()); AlarmEntity alarm=null; for( AlarmEntity alarmEntity:alarmEntityList ){ //判断:操作符和指标对比 if( "String".equals( quotaDTO.getValueType() ) || "Boolean".equals(quotaDTO.getValueType()) ){ if( alarmEntity.getOperator().equals("=") && quotaDTO.getStringValue().equals(alarmEntity.getThreshold()) ){ alarm=alarmEntity; break; } }else //数值 { if( alarmEntity.getOperator().equals(">") && quotaDTO.getValue()>alarmEntity.getThreshold() ){ alarm=alarmEntity; break; } if( alarmEntity.getOperator().equals("<") && quotaDTO.getValue()<alarmEntity.getThreshold() ){ alarm=alarmEntity; break; } if( alarmEntity.getOperator().equals("=") && quotaDTO.getValue().equals(alarmEntity.getThreshold()) ){ alarm=alarmEntity; break; } } } return alarm; } @Override public DeviceInfoDTO verifyDeviceInfo(DeviceInfoDTO deviceInfoDTO) { // 封装指标的告警 封装设备的告警 DeviceDTO deviceDTO = deviceInfoDTO.getDevice(); deviceDTO.setLevel(0);//假设不告警 deviceDTO.setAlarm(false); deviceDTO.setAlarmName("正常"); deviceDTO.setStatus(true); deviceDTO.setOnline(true); for(QuotaDTO quotaDTO :deviceInfoDTO.getQuotaList() ){ AlarmEntity alarmEntity = verifyQuota(quotaDTO);//根据指标得到告警信息 if(alarmEntity!=null){ //如果指标存在告警 quotaDTO.setAlarm("1"); quotaDTO.setAlarmName( alarmEntity.getName() );//告警名称 quotaDTO.setLevel( alarmEntity.getLevel()+"" );//告警级别 quotaDTO.setAlarmWebHook(alarmEntity.getWebHook());//告警web钩子 quotaDTO.setCycle( alarmEntity.getCycle() );//沉默周期 if(alarmEntity.getLevel().intValue()> deviceDTO.getLevel().intValue() ){ deviceDTO.setLevel( alarmEntity.getLevel() ); deviceDTO.setAlarm(true); deviceDTO.setAlarmName(alarmEntity.getName()); } }else{//如果指标不存储在告警 quotaDTO.setAlarm("0"); quotaDTO.setAlarmName("正常"); quotaDTO.setLevel("0"); quotaDTO.setAlarmWebHook(""); quotaDTO.setCycle(0); } } return deviceInfoDTO; } @Autowired private InfluxRepository influxRepository; @Override public Pager<QuotaAllInfo> queryAlarmLog(Long page, Long pageSize, String start, String end, String alarmName, String deviceId) { //1.where条件查询语句部分构建 StringBuilder whereQl=new StringBuilder("where alarm='1' "); if(!Strings.isNullOrEmpty(start)){ whereQl.append("and time>='"+start +"' "); } if(!Strings.isNullOrEmpty(end)){ whereQl.append("and time<='"+end +"' "); } if(!Strings.isNullOrEmpty(alarmName)){ whereQl.append("and alarmName=~/"+ alarmName+"/ "); } if(!Strings.isNullOrEmpty(deviceId)){ whereQl.append("and deviceId=~/^"+deviceId+"/ "); } //2.查询记录语句 StringBuilder listQl=new StringBuilder("select * from quota "); listQl.append( whereQl.toString() ); listQl.append( "order by desc limit "+ pageSize+" offset "+ (page-1)*pageSize ); //3.查询记录数语句 StringBuilder countQl=new StringBuilder("select count(value) from quota "); countQl.append(whereQl.toString()); //4.执行查询记录语句 List<QuotaAllInfo> quotaList = influxRepository.query(listQl.toString(), QuotaAllInfo.class); // 添加时间格式处理 for(QuotaAllInfo quotaAllInfo:quotaList){ //2020-09-19T09:58:34.926Z DateTimeFormatter.ISO_OFFSET_DATE_TIME //转换为 2020-09-19 09:58:34 格式 LocalDateTime dateTime = LocalDateTime.parse(quotaAllInfo.getTime(), DateTimeFormatter.ISO_OFFSET_DATE_TIME); String time = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss")); quotaAllInfo.setTime(time); } //5.执行统计语句 List<QuotaCount> quotaCount = influxRepository.query(countQl.toString(), QuotaCount.class); //6.封装返回结果 if(quotaCount==null || quotaCount.size()==0){ Pager<QuotaAllInfo> pager=new Pager<QuotaAllInfo>(0L,0L); pager.setPage(0); pager.setItems(Lists.newArrayList()); return pager; } Long totalCount = quotaCount.get(0).getCount();//总记录数 Pager<QuotaAllInfo> pager=new Pager<>(totalCount,pageSize); pager.setPage(page); pager.setItems(quotaList); return pager; } }
35.606061
133
0.618298
aff988b906b2598294b4db3d2b1015930648f6df
1,731
/******************************************************************************* * Copyright (c) 2019 Black Rook Software * This program and the accompanying materials are made available under * the terms of the MIT License, which accompanies this distribution. ******************************************************************************/ package com.blackrook.math.geometry; /** * Three-dimensional line segment. * @author Matthew Tropiano */ public class Line3D extends LineD<Point3D> { /** * Creates a line segment with two points, both (0, 0, 0). */ public Line3D() { this(0.0, 0.0, 0.0, 0.0, 0.0, 0.0); } /** * Creates a line segment from two points. * @param a the first point. * @param b the second point. */ public Line3D(Point3D a, Point3D b) { this(a.x, a.y, a.z, b.x, b.y, b.z); } /** * Creates a line segment from a set from * coordinates making up two points. * @param ax start point x-coordinate. * @param ay start point y-coordinate. * @param az start point z-coordinate. * @param bx end point x-coordinate. * @param by end point y-coordinate. * @param bz end point z-coordinate. */ public Line3D(double ax, double ay, double az, double bx, double by, double bz) { this.pointA = new Point3D(ax, ay, az); this.pointB = new Point3D(bx, by, bz); } /** * Creates a line by copying another. * @param line the source line */ public Line3D(Line3D line) { this.pointA = new Point3D(line.pointA); this.pointB = new Point3D(line.pointB); } /** * @return the length of this line in units. */ public double getLength() { return pointA.getDistanceTo(pointB); } @Override public Line3D copy() { return new Line3D(this); } }
23.391892
80
0.597343
14f9f53ae54b069106f55485df43ff99ce5ed4cd
2,104
package org.bndly.rest.swagger.impl; /*- * #%L * REST Swagger Integration * %% * Copyright (C) 2013 - 2020 Cybercon GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import org.bndly.rest.atomlink.api.JAXBMessageClassProvider; import org.bndly.rest.swagger.model.SchemaModel; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.annotation.XmlRootElement; /** * * @author cybercon &lt;[email protected]&gt; */ public class DocumentedMessageClassProvider { private final JAXBMessageClassProvider messageClassProvider; private final Map<String, Class> messageClassesByRootElementName = new HashMap<>(); private final List<SchemaModel> createdSchemaModels = new ArrayList<>(); public DocumentedMessageClassProvider(JAXBMessageClassProvider messageClassProvider) { this.messageClassProvider = messageClassProvider; Collection<Class<?>> classes = messageClassProvider.getJAXBMessageClasses(); for (Class<?> messageClass : classes) { XmlRootElement rootElement = messageClass.getAnnotation(XmlRootElement.class); if (rootElement != null) { messageClassesByRootElementName.put(rootElement.name(), messageClass); } } } public JAXBMessageClassProvider getMessageClassProvider() { return messageClassProvider; } public Class getMessageClassByRootElementName(String rootElementName) { return messageClassesByRootElementName.get(rootElementName); } public List<SchemaModel> getCreatedSchemaModels() { return createdSchemaModels; } }
31.878788
87
0.770437
aadf10a48c9671ff2aeb08a76140e96bc3679ef1
902
package io.moj.java.sdk.model.response; import java.util.Map; /** * Model object for a response that only contains a message string. The Mojio API usually returns this for DELETE * operations or error scenarios. * Created by skidson on 2016-04-13. */ public class MessageResponse { private String Message; private Map<String, String[]> ModelState; public String getMessage() { return Message; } public void setMessage(String message) { Message = message; } public Map<String, String[]> getModelState() { return ModelState; } public void setModelState(Map<String, String[]> modelState) { ModelState = modelState; } @Override public String toString() { return "MessageResponse{" + "Message='" + Message + '\'' + ", ModelState=" + ModelState + '}'; } }
23.128205
113
0.613082
817edfc1850bebae01d5bfc15bd4033d54f07b20
91
package p04_Telephony; public interface Browse { public String browse(String site); }
15.166667
38
0.758242
52051dead7f87b43b52df257e418052c06582706
1,081
/** * Copyright (c) Seamless Payments, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.seamlesspay.api.models; import android.os.Parcel; import android.os.Parcelable; import org.json.JSONException; import org.json.JSONObject; public class CardChargeBulder extends BaseChargeBuilder<CardChargeBulder> implements Parcelable { public CardChargeBulder() {} @Override protected void build(JSONObject json) throws JSONException { json.put(CVV_KEY, getCvv()); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); } protected CardChargeBulder(Parcel in) { super(in); } public static final Creator<CardChargeBulder> CREATOR = new Creator<CardChargeBulder>() { @Override public CardChargeBulder createFromParcel(Parcel in) { return new CardChargeBulder(in); } @Override public CardChargeBulder[] newArray(int size) { return new CardChargeBulder[size]; } }; }
22.520833
91
0.724329
55eae808f855257fcc5c94cbfa1cb17cb9fb12f2
479
package io.github.goldmensch.jall.transformer; /** * The transformer will be used to transform a {@link String} from the localizer to the needed * format * * @param <T> The output format */ @FunctionalInterface public interface Transformer<T> { /** * Transforms a {@link String} to the needed format * * @param value The final {@link String}, all placeholders are resolved * @return The localization as the needed format */ T transform(String value); }
23.95
94
0.703549
09ad364dae5fe8dfb7d1fd6dc09badd7c17d3418
19,112
/************************************************************** Copyright 2015 Anan Sriram 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.rnan.android.calendar; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; public class TYCalendar { private long _jd_pkn = 0; private int _daysInMonth = 0; private int _day = 0; private int _month = 0; private int _actualMonth = 0; private int _year = 0; public TYCalendar(){ _day = Calendar.getInstance().get(Calendar.DATE); _month = Calendar.getInstance().get(Calendar.MONTH); //month is an order start 0 to 11 _actualMonth = _month+1; _year = Calendar.getInstance().get(Calendar.YEAR); initDaysInMonth(); } private void initDaysInMonth(){ Calendar calendar= new GregorianCalendar(_year,_month,_day); _daysInMonth=calendar.getActualMaximum(Calendar.DAY_OF_MONTH); System.out.println("_daysInMonth:"+_daysInMonth); } public void initDaysInMonth(int y,int m,int d){ _day = d; _month = m; //month is an order start 0 to 11 _actualMonth = m+1; _year = y; initDaysInMonth(); } public ArrayList ProcessDaysInMonth(){ ArrayList allDateInfoInMonth = new ArrayList(); DateInfo.MoonType moonType = DateInfo.MoonType.NONE; for (int iDay=1;iDay<=_daysInMonth;iDay++) { Calendar c = new GregorianCalendar(_year,_month,iDay); long jd_pkn=Gregorian2JD( _actualMonth, iDay, _year, 12,0,0); ArrayList list = JD2PKN((int) jd_pkn); if (list != null) { String days_text=FindDate(jd_pkn); String moonDayText= list.get(17)+ " (" + list.get(18) +")"; //Calendar c = new GregorianCalendar(_year,_month,_day); //System.out.println(days_text + " " + moonDayText); boolean isWanPra=false; boolean isWanRam=true; if(list.get(21).toString().equals("1")) isWanRam=false; if(list.get(15).toString().equals("1")) isWanPra=true; int pak=Integer.parseInt(list.get(11).toString()); switch (pak){ case 8: if(isWanRam) { moonType = DateInfo.MoonType.LAST_QUARTER_MOON; }else{ moonType = DateInfo.MoonType.FIRST_QUARTER_MOON; } break; case 14: case 15: if(isWanRam){ moonType = DateInfo.MoonType.NEW_MOON; }else{ moonType = DateInfo.MoonType.FULL_MOON; } break; } DateInfo d = new DateInfo(c,days_text,moonDayText, moonType); d.SetWanPra(isWanPra); d.SetWanRam(isWanRam); if(d.IsWanPra()) allDateInfoInMonth.add(d); } } return allDateInfoInMonth; } /* private void init(){ Date tDate = new Date(); int day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH); int month = Calendar.getInstance().get(Calendar.MONTH); int year = Calendar.getInstance().get(Calendar.YEAR); System.out.println("tDate:"+tDate); _jd_pkn = Gregorian2JD( month+1, day, year, 12,0,0); System.out.println("jd_pkn:"+_jd_pkn); } public void ProcessDay(){ ArrayList list = JD2PKN((int)_jd_pkn); if(list!=null) { for (int i = 0; i < list.size(); i++) { System.out.println("ArrayList[" + i + "]" + list.get(i)); } CalDate(list); } } */ private String FindDate(long jd_pkn){ ArrayList cal_date = JD2Gregorian(jd_pkn); String[] thai_month_name = {"", "มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน", "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม"}; String[] thai_dow_name = {"อาทิตย์", "จันทร์", "อังคาร", "พุธ", "พฤหัสบดี", "ศุกร์", "เสาร์"}; String th_dow = thai_dow_name[jddayofweek(jd_pkn)]; int indexTHmonth= Integer.parseInt(cal_date.get(1).toString()); String cal_text = "วัน"+th_dow+"ที่ "+cal_date.get(0)+" "+thai_month_name[indexTHmonth]+" พ.ศ."+cal_date.get(2); //System.out.print("cal_text:"+cal_text); return cal_text; } private int jddayofweek(long jd) { return (int)(jd+1)%7; } private int jd2thdayofweek(long jd) { return jddayofweek(jd)+1; } private long mFrac(long r) { // // Return the fractional part of a real number. // return r - mFloor(r); } private ArrayList JD2Gregorian(long jd ) { //var j1, j2, j3, j4, j5; //scratch // // get the date from the Julian day number // long intgr = mFloor(jd); long frac = mFrac(jd); long gregjd = 2299161; // julian day of 15 Oct 1582 in Gregorian Calendar long tmp = mFloor( ( (intgr - 1867216) - 0.25 ) / 36524.25d ); long j1 = intgr + 1 + tmp - mFloor(0.25*tmp); //correction for half day offset double dayfrac = frac + 0.5; if( dayfrac >= 1.0 ) { dayfrac -= 1.0; j1++; } long j2 = j1 + 1524; long j3 = mFloor( 6680.0 + ( (j2 - 2439870) - 122.1 )/365.25 ); long j4 = mFloor( j3*365.25 ); long j5 = mFloor( (j2 - j4)/30.6001 ); long d = mFloor(j2 - j4 - mFloor(j5*30.6001)); long m = mFloor(j5 - 1); if( m > 12 ) { m -= 12; } long y = mFloor(j3 - 4715); if( m > 2 ) { y--; } if( y <= 0 ) { y--; } // // get time of day from day fraction // long hr = mFloor(dayfrac * 24.0); long mn = mFloor((dayfrac*24.0 - hr)*60.0); double f = ((dayfrac*24.0 - hr)*60.0 - mn)*60.0; long sc = mFloor(f); f -= sc; if( f > 0.5 ) { sc++; } if(sc >= 60) { sc -=60; mn++; } //return d+"/"+m+"/"+y+" "+hr+":"+mn+":"+sc; //var th_month_name = ["", "มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน", "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม"]; //return d+"/"+m+"/"+y; long buddhist_era = y + 543; //return d+" "+th_month_name[m]+" พ.ศ. "+buddhist_era+" (ค.ศ. "+y+")"; ArrayList sdate = new ArrayList(); sdate.add(0,d); sdate.add(1,m); sdate.add(2,buddhist_era); sdate.add(3,y); return sdate; } private long Gregorian2JD(int m,int d, int y, int h, int mn, int s ) { /* System.out.println("d:"+d); System.out.println("m:"+m); System.out.println("y:"+y); */ if( y == 0 ) { return 0; } if( y < 0 ) { y++; } int jy=0; int jm=0; if( m > 2 ) { jy = y; jm = m + 1; } else { jy = y - 1; jm = m + 13; } // integer part of Julian Day (from Gregorian Calendar) long intgr = mFloor( mFloor(365.25* jy) + mFloor(30.6001* jm) + d + 1720995 ); long ja = mFloor(0.01*jy); intgr += 2 - ja + mFloor(0.25*ja); //correct for half-day offset double dayfrac = h/24.0 - 0.5; if( dayfrac < 0.0 ) { dayfrac += 1.0; intgr--; } //now set the fraction of a day double frac = dayfrac + (mn + s/60.0)/60.0/24.0; //round to nearest second double jd0 = (intgr + frac)*100000; long jd = mFloor(jd0); if( (jd0 - jd) > 0.5 ) { jd++; } long result=jd/100000; //System.out.println("Gregorian2JD:"+result); return result; } /* function jddayofweek(jd) { return (jd+1)%7; } function jd2thdayofweek(jd) { return jddayofweek(jd)+1; } */ private int mRound(double num, int position) { int ten=10; return (int)(Math.round(num * Math.pow(ten, position)) / Math.pow(ten, position)); } private long mFloor(double num) { long numx=(long)num; //System.out.print("numx:"+numx); return Long.parseLong(String.valueOf(numx), 10); // INT function (like TRUNC). } private long mCeil(double num) { //System.out.println("num:" + num); if(num == mFloor(num) ) { return (long)num; } else { return mRound(num+0.5,0); } } private int JD2PD(int jd) { // วันเริ่มต้นปักขคณนา ตรงกับ วันเสาร์ แรม 1 ค่ำ เดือน 3 พ.ศ. 2278 ** // หรือ วันที่ 28 มกราคม พ.ศ. 2279 ตามปฏิทินสากล (แบบ gregorian) // สิ้นสุดในวันที่ 28 พฤศจิกายน พ.ศ. 3071 (gregorian) เป็นปักขคณนาครบ 1 รอบ // ** ( ศักราชไทยสมัยก่อนจะเปลี่ยนเมื่อ ขึ้น 1 ค่ำ เดือน 5 ) int jd_start = 2355148; // 28 มกราคม พ.ศ. 2279 (gregorian) int jd_r = mRound(jd,0); if( jd_r < 2355148) { return jd; } int days = mRound(jd,0) - jd_start + 1; // นับจำนวนวันทั้งหมดตั้งแต่วันที่ 28 ไป (วันที่ 28 เริ่มนับเป็นลำดับที่ 1...) return days; } private ArrayList JD2PKN(int jd) { int days = JD2PD(jd); //System.out.println("days:" + days); double input =days/289577d; //System.out.println("input:" + input); long pp = mCeil(input); // ปักขคณนารอบที่ //System.out.println("pp:" + pp); days = days % 289577; days += (days == 0)? 289577 : 0; // ปักคณนา 1 รอบ ใช้เวลาทั้งหมด 289577 วัน String[] A = {"", "B1", "B1", "B1", "B1", "B1", "B1", "B1", "B1", "B1", "B1", "B1", "B1", "B1", "B1", "B1", "B1", "B1", "B2"}; String[] B1 = {"", "C2", "C2", "C2", "C2", "C2", "C2", "C2", "C2", "C2", "C2", "C1"}; String[] B2 = {"", "C2", "C2", "C2", "C2", "C2", "C2", "C2", "C2", "C2", "C1"}; String[] C1 = {"", "D1", "D1", "D1", "D1", "D1", "D1", "D2"}; String[] C2 = {"", "D1", "D1", "D1", "D1", "D1", "D2"}; String[] D1 = {"", "E2", "E2", "E2", "E1"}; String[] D2 = {"", "E2", "E2", "E1"}; String[] E1 = {"", "F1", "F1", "F1", "F1", "F2" }; String[] E2 = {"", "F1", "F1", "F1", "F2"}; int F1 = 15; int F2 = 14; // สมการความสัมพันธ์ทั่วไปของปักขคณนาวิธี (จ.น.วัน) // $days = (pp-1)*A1 + ($a-1)*B1 + ($b-1)*C2 + ($c-1)*D1 + ($d-1)*E2 + ($e-1)*F1 + $f // A1 has 289577 days ปักขคณนา 1 รอบ // B1 has 16168 days มหาสัมพยุหะ // C2 has 1447 days จุลสัมพยุหะ // D1 has 251 days มหาสมุหะ // E2 has 59 days จุลวรรค // F1 has 15 days มหาปักษ์ // โดย $a , $b, $c, $d, $e, $f เป็นสมาชิกของจำนวนเต็ม long a = mCeil( days/16168d ); // Position ใน มัชฌิมคติ //System.out.println("a:" + a); if( a > 18) { a = 18; } String AA = A[(int)a]; // ประเภท สัมพยุหะ String BB=""; long b = mCeil(( days- (a-1)*16168)/1447d); // Position ใน สัมพยุหะ if( AA == "B1") { if( b > 11) { b = 11; } BB = B1[(int)b]; } else { if( b > 10) { b = 10; } BB = B2[(int)b];} // ประเภท พยุหะ String CC=""; long c = mCeil((days - (a-1)*16168 - (b-1)*1447)/251d); // Position ใน พยุหะ if( BB == "C1") { if( c > 7) { c = 7; } CC = C1[(int)c]; } else { if( c > 6) { c=6; } CC = C2[(int)c]; } // ประเภท สมุหะ String DD=""; long d = mCeil((days - (a-1)*16168 - (b-1)*1447 - (c-1)*251)/59d); // Position ใน สมุหะ if( CC == "D1" ) { if( d >4) { d = 4; } DD = D1[(int)d]; } else { if( d >3) { d = 3; } DD = D2[(int)d]; } // ประเภท วรรค String EE=""; long e = mCeil((days - (a-1)*16168 - (b-1)*1447 - (c-1)*251 - (d-1)*59)/15d); // Position ใน วรรค if( DD == "E1") { if ( e > 5) { e = 5; } EE = E1[(int)e]; } else { if( e > 4) { e = 4; } EE = E2[(int)e]; } // ประเภทปักษ์ String f_type=""; int f_max=0; long f = (days - (a-1)*16168 - (b-1)*1447 - (c-1)*251 - (d-1)*59 - (e-1)*15); // ดิถี if( EE == "F1" ) { f_max = F1; f_type = "ปักข์ถ้วน"; } else { f_max = F2; f_type = "ปักข์ขาด"; } // จ.น.วันในปักษ์ปัจจุบัน //if( f==0 || f > f_max) { return null; } //{print "PKN Bug!!!\n"; } --> หากต้องการจะทดสอบ BUG ให้เปลี่ยนเป็นอันหลังนี้ ซึ่งเท่าที่ทดสอบไม่พบ Bug // สมการความสัมพันธ์ทั่วไปของปักขคณนาวิธี (จ.น.ปักษ์) // สูตรนี้เป็น สูตรเพิ่มเติม ได้คิดใหม่ไม่มีมาแต่เดิม // ใช้สำหรับหาข้างขึ้นข้างแรม เทียบประกอบ long pak_total = (pp-1)*19612 + (a-1)*1095 + (b-1)*98 + (c-1)*17 + (d-1)*4 + e; String pak_type = ( pak_total % 2 )==0 ? "ขึ้น" : "แรม"; int pak_type2 = ( pak_total % 2 )==0 ? 1 : 0; long img_num=0; if( pak_type2==1) { // ข้างขึ้น img_num = ( f_max == 14 )? f+1: f; } else { // ข้างแรม img_num = ( f_max == 14 )? 15+f : 14+f; } String img_id = (img_num < 10)? "im0"+img_num : "im"+img_num; //pkn_text = "ปักขคณนารอบที่ "+pp+" "+AA+" "+a+" "+BB+" "+b+" "+CC+" "+c+" "+DD+" "+d+" "+EE+" "+e+" "+pak_type+" "+f+" ค่ำ ("+f_type+")"; String pkn_text = AA+" "+a+" "+BB+" "+b+" "+CC+" "+c+" "+DD+" "+d+" "+EE+" "+e+" "+pak_type+" "+f+" ค่ำ ("+f_type+")"; //System.out.println("pkn_text:" + pkn_text); pkn_text = pkn_text.replace("B1", "มหาสัมพยุหะ"); pkn_text = pkn_text.replace("B2", "จุลสัมพยุหะ"); pkn_text = pkn_text.replace("C1", "มหาพยุหะ"); pkn_text = pkn_text.replace("C2", "จุลพยุหะ"); pkn_text = pkn_text.replace("D1", "มหาสมุหะ"); pkn_text = pkn_text.replace("D2", "จุลสมุหะ"); pkn_text = pkn_text.replace("E1", "มหาวรรค"); pkn_text = pkn_text.replace("E2", "จุลวรรค"); pkn_text = pkn_text.replace("F1", "มหาปักข์"); pkn_text = pkn_text.replace("F2", "จุลปักข์"); String pkn_text2 = "<a title='แสดงตาม \"ปักษ์คณนาสำเร็จ\" ของ พระเจ้าบรมวงษเธอ กรมสมเด็จพระปวเรศวริยาลงกรณ์'><table CELLSPACING=0 CELLPADDING=0 style='font-size:15;' bgcolor=lightgreen><tr>"+ "<td>"+ ((AA == "B1")? ( (a>9)? MAHA_transform(mFloor(a/10)) : MAHA_transform(a)) : ( (a>9)? JULA_transform(mFloor(a/10)) : JULA_transform(a)) ) + "</td>"+ "<td>"+ ((BB == "C1")? ( (b>9)? MAHA_transform(mFloor(b/10)) : MAHA_transform(b)) : ( (b>9)? JULA_transform(mFloor(b/10)) : JULA_transform(b)) ) + "</td>"+ "<td>"+ ((CC == "D1")? ( (c>9)? MAHA_transform(mFloor(c/10)) : MAHA_transform(c)) : ( (c>9)? JULA_transform(mFloor(c/10)) : JULA_transform(c)) ) + "</td>"+ "<td>"+ ((DD == "E1")? ( (d>9)? MAHA_transform(mFloor(d/10)) : MAHA_transform(d)) : ( (d>9)? JULA_transform(mFloor(d/10)) : JULA_transform(d)) ) + "</td>"+ "<td>"+ ((EE == "F1")? ( (e>9)? MAHA_transform(mFloor(e/10)) : MAHA_transform(e)) : ( (e>9)? JULA_transform(mFloor(e/10)) : JULA_transform(e)) ) + "</td>"+"</tr>"+ "<tr>"+ "<td>"+ ((AA == "B1")? ( (a>9)? MAHA_transform(a %10) : "" ) : ( (a>9)? JULA_transform(a %10) : "" ) ) + "</td>"+ "<td>"+ ((BB == "C1")? ( (b>9)? MAHA_transform(b %10) : "" ) : ( (b>9)? JULA_transform(b %10) : "" ) ) + "</td>"+ "<td>"+ ((CC == "D1")? ( (c>9)? MAHA_transform(c %10) : "" ) : ( (c>9)? JULA_transform(c %10) : "" ) ) + "</td>"+ "<td>"+ ((DD == "E1")? ( (d>9)? MAHA_transform(d %10) : "" ) : ( (d>9)? JULA_transform(d %10) : "" ) ) + "</td>"+ "<td>"+ ((EE == "F1")? ( (e>9)? MAHA_transform(e %10) : "" ) : ( (e>9)? JULA_transform(e %10) : "" ) ) + "</td>"+ "</tr></table></a>"; ArrayList pkn = new ArrayList(); pkn.add(0,pkn_text); pkn.add(1,1); pkn.add(2, AA.replace("B", "")); pkn.add(3, BB.replace("C", "")); pkn.add(4, CC.replace("D", "")); pkn.add(5, DD.replace("E", "")); pkn.add(6,a); pkn.add(7,b); pkn.add(8,c); pkn.add(9,d); pkn.add(10,e); pkn.add(11,f); pkn.add(12,f_max); pkn.add(13,pp); pkn.add(14,jd); //** convert f_max to double for check value of หาร double double_f_max= f_max; pkn.add(15,( f/double_f_max == 4/7d || f/double_f_max == 8/15d || f/double_f_max == 1 )? 1 : 0); // วันพระธรรมยุติ pkn.add(16, img_id); pkn.add(17, pak_type+" "+f+" ค่ำ"); pkn.add(18,f_type); pkn.add(19,pak_total); pkn.add(20,pkn_text2); pkn.add(21,pak_type2); //0=ขึ้น 1=แรม //return a+","+b+","+c+","+d+","+e+","+f; return pkn; } private String MAHA_transform(long n ) { String result=""; switch ((int)n){ case 1: result="๑"; break; case 2: result="๒"; break; case 3: result="๓"; break; case 4: result="๔"; break; case 5: result="๕"; break; case 6: result="๖"; break; case 7: result="๗"; break; case 8: result="๘"; break; case 9: result="๙"; break; case 0: result="๐"; break; } return result; } private String JULA_transform(long n ) { String result=""; switch ((int)n){ case 1: result="ก"; break; case 2: result="ข"; break; case 3: result="ฅ"; break; case 4: result="จ"; break; case 5: result="ห"; break; case 6: result="ฉ"; break; case 7: result="ษ"; break; case 8: result="ฐ"; break; case 9: result="ฬ"; break; case 0: result="ฮ"; break; } return result; } }
36.895753
199
0.473786
81c18d37260f3b78c7bb64e1b67710d68d6bb347
7,402
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kansus.mediacenter.util; import org.kansus.mediacenter.structure.IImage; import org.kansus.mediacenter.structure.IImageList; import org.kansus.mediacenter.structure.VideoObject; import android.content.ContentResolver; import android.graphics.Bitmap; import android.os.Process; /* * Here's the loading strategy. For any given image, load the thumbnail * into memory and post a callback to display the resulting bitmap. * * Then proceed to load the full image bitmap. Three things can * happen at this point: * * 1. the image fails to load because the UI thread decided * to move on to a different image. This "cancellation" happens * by virtue of the UI thread closing the stream containing the * image being decoded. BitmapFactory.decodeStream returns null * in this case. * * 2. the image loaded successfully. At that point we post * a callback to the UI thread to actually show the bitmap. * * 3. when the post runs it checks to see if the image that was * loaded is still the one we want. The UI may have moved on * to some other image and if so we just drop the newly loaded * bitmap on the floor. */ public class ImageGetter { // The thread which does the work. private Thread mGetterThread; // The current request serial number. // This is increased by one each time a new job is assigned. // It is only written in the main thread. private int mCurrentSerial; // The base position that's being retrieved. The actual images retrieved // are this base plus each of the offets. -1 means there is no current // request needs to be finished. private int mCurrentPosition = -1; // The callback to invoke for each image. private ImageGetterCallback mCB; // The image list for the images. private IImageList mImageList; // The handler to do callback. private GetterHandler mHandler; // True if we want to cancel the current loading. private volatile boolean mCancel = true; // True if the getter thread is idle waiting. private boolean mIdle = false; // True when the getter thread should exit. private boolean mDone = false; private ContentResolver mCr; private class ImageGetterRunnable implements Runnable { private Runnable callback(final int position, final int offset, final boolean isThumb, final RotateBitmap bitmap, final int requestSerial) { return new Runnable() { public void run() { // check for inflight callbacks that aren't applicable // any longer before delivering them if (requestSerial == mCurrentSerial) { mCB.imageLoaded(position, offset, bitmap, isThumb); } else if (bitmap != null) { bitmap.recycle(); } } }; } private Runnable completedCallback(final int requestSerial) { return new Runnable() { public void run() { if (requestSerial == mCurrentSerial) { mCB.completed(); } } }; } public void run() { // Lower the priority of this thread to avoid competing with // the UI thread. Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); while (true) { synchronized (ImageGetter.this) { while (mCancel || mDone || mCurrentPosition == -1) { if (mDone) return; mIdle = true; ImageGetter.this.notify(); try { ImageGetter.this.wait(); } catch (InterruptedException ex) { // ignore } mIdle = false; } } executeRequest(); synchronized (ImageGetter.this) { mCurrentPosition = -1; } } } private void executeRequest() { int imageCount = mImageList.getCount(); int[] order = mCB.loadOrder(); for (int i = 0; i < order.length; i++) { if (mCancel) return; int offset = order[i]; int imageNumber = mCurrentPosition + offset; if (imageNumber >= 0 && imageNumber < imageCount) { if (!mCB.wantsThumbnail(mCurrentPosition, offset)) { continue; } IImage image = mImageList.getImageAt(imageNumber); if (image == null) continue; if (mCancel) return; Bitmap b = image.thumbBitmap(IImage.NO_ROTATE); if (b == null) continue; if (mCancel) { b.recycle(); return; } Runnable cb = callback(mCurrentPosition, offset, true, new RotateBitmap(b, image.getDegreesRotated()), mCurrentSerial); mHandler.postGetterCallback(cb); } } for (int i = 0; i < order.length; i++) { if (mCancel) return; int offset = order[i]; int imageNumber = mCurrentPosition + offset; if (imageNumber >= 0 && imageNumber < imageCount) { if (!mCB.wantsFullImage(mCurrentPosition, offset)) { continue; } IImage image = mImageList.getImageAt(imageNumber); if (image == null) continue; if (image instanceof VideoObject) continue; if (mCancel) return; int sizeToUse = mCB.fullImageSizeToUse(mCurrentPosition, offset); Bitmap b = image.fullSizeBitmap(sizeToUse, 3 * 1024 * 1024, IImage.NO_ROTATE, IImage.USE_NATIVE); if (b == null) continue; if (mCancel) { b.recycle(); return; } RotateBitmap rb = new RotateBitmap(b, image.getDegreesRotated()); Runnable cb = callback(mCurrentPosition, offset, false, rb, mCurrentSerial); mHandler.postGetterCallback(cb); } } mHandler.postGetterCallback(completedCallback(mCurrentSerial)); } } public ImageGetter(ContentResolver cr) { mCr = cr; mGetterThread = new Thread(new ImageGetterRunnable()); mGetterThread.setName("ImageGettter"); mGetterThread.start(); } // Cancels current loading (without waiting). public synchronized void cancelCurrent() { Util.Assert(mGetterThread != null); mCancel = true; BitmapManager.instance().cancelThreadDecoding(mGetterThread, mCr); } // Cancels current loading (with waiting). private synchronized void cancelCurrentAndWait() { cancelCurrent(); while (mIdle != true) { try { wait(); } catch (InterruptedException ex) { // ignore. } } } // Stops this image getter. public void stop() { synchronized (this) { cancelCurrentAndWait(); mDone = true; notify(); } try { mGetterThread.join(); } catch (InterruptedException ex) { // Ignore the exception } mGetterThread = null; } public synchronized void setPosition(int position, ImageGetterCallback cb, IImageList imageList, GetterHandler handler) { // Cancel the previous request. cancelCurrentAndWait(); // Set new data. mCurrentPosition = position; mCB = cb; mImageList = imageList; mHandler = handler; mCurrentSerial += 1; // Kick-start the current request. mCancel = false; BitmapManager.instance().allowThreadDecoding(mGetterThread); notify(); } }
26.625899
75
0.679141
86623cecadc0d0f2d25f778a5bdadf64202946e3
119
package ro.ase.cts_lab; public class Hi { public static void main (String[] args) { System.out.println("Hi"); } }
13.222222
41
0.672269
1a81c00039a075dcb0f6462d2aed68fa8eee9678
720
package com.example.hy.wanandroid.di.component.fragment; import com.example.hy.wanandroid.di.module.fragment.HierarchyFragmentModule; import com.example.hy.wanandroid.di.module.fragment.HierarchySecondFragmentModule; import com.example.hy.wanandroid.di.scope.PerFragment; import com.example.hy.wanandroid.view.hierarchy.HierarchySecondActivity; import com.example.hy.wanandroid.view.hierarchy.HierarchySecondFragment; import dagger.Subcomponent; /** * HierarchySecondFragment的Component * Created by 陈健宇 at 2018/10/29 */ @PerFragment @Subcomponent(modules = HierarchySecondFragmentModule.class) public interface HierarchySecondFragmentComponent { void inject(HierarchySecondFragment hierarchySecondFragment); }
36
82
0.844444
aa318a77fdd5fa8856e71966204b9fe0857b6b9c
616
package ru.job4j.list; /** * @author Sir-Hedgehog (mailto:[email protected]) * @version $Id$ * @since 04.03.2019 */ public class SimpleQueue<T> { private SimpleStack<T> one; private SimpleStack<T> two; public SimpleQueue(SimpleStack<T> one, SimpleStack<T> two) { this.one = one; this.two = two; } public void push(T date) { this.one.push(date); } public T poll() { if (this.two.isEmpty()) { while (!this.one.isEmpty()) { this.two.push(this.one.poll()); } } return this.two.poll(); } }
19.870968
64
0.540584
88708107d8266da0c386820f100283274c00bcf8
5,525
/** * 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.databoxedge.v2019_08_01; import com.microsoft.azure.arm.model.HasInner; import com.microsoft.azure.management.databoxedge.v2019_08_01.implementation.UserInner; import com.microsoft.azure.arm.model.Indexable; import com.microsoft.azure.arm.model.Refreshable; import com.microsoft.azure.arm.model.Updatable; import com.microsoft.azure.arm.model.Appliable; import com.microsoft.azure.arm.model.Creatable; import com.microsoft.azure.arm.resources.models.HasManager; import com.microsoft.azure.management.databoxedge.v2019_08_01.implementation.DataBoxEdgeManager; import java.util.List; /** * Type representing User. */ public interface User extends HasInner<UserInner>, Indexable, Refreshable<User>, Updatable<User.Update>, HasManager<DataBoxEdgeManager> { /** * @return the encryptedPassword value. */ AsymmetricEncryptedSecret encryptedPassword(); /** * @return the id value. */ String id(); /** * @return the name value. */ String name(); /** * @return the shareAccessRights value. */ List<ShareAccessRight> shareAccessRights(); /** * @return the type value. */ String type(); /** * @return the userType value. */ UserType userType(); /** * The entirety of the User definition. */ interface Definition extends DefinitionStages.Blank, DefinitionStages.WithDataBoxEdgeDevice, DefinitionStages.WithUserType, DefinitionStages.WithCreate { } /** * Grouping of User definition stages. */ interface DefinitionStages { /** * The first stage of a User definition. */ interface Blank extends WithDataBoxEdgeDevice { } /** * The stage of the user definition allowing to specify DataBoxEdgeDevice. */ interface WithDataBoxEdgeDevice { /** * Specifies deviceName, resourceGroupName. * @param deviceName The device name * @param resourceGroupName The resource group name * @return the next definition stage */ WithUserType withExistingDataBoxEdgeDevice(String deviceName, String resourceGroupName); } /** * The stage of the user definition allowing to specify UserType. */ interface WithUserType { /** * Specifies userType. * @param userType Type of the user. Possible values include: 'Share', 'LocalManagement', 'ARM' * @return the next definition stage */ WithCreate withUserType(UserType userType); } /** * The stage of the user definition allowing to specify EncryptedPassword. */ interface WithEncryptedPassword { /** * Specifies encryptedPassword. * @param encryptedPassword The password details * @return the next definition stage */ WithCreate withEncryptedPassword(AsymmetricEncryptedSecret encryptedPassword); } /** * The stage of the user definition allowing to specify ShareAccessRights. */ interface WithShareAccessRights { /** * Specifies shareAccessRights. * @param shareAccessRights List of shares that the user has rights on. This field should not be specified during user creation * @return the next definition stage */ WithCreate withShareAccessRights(List<ShareAccessRight> shareAccessRights); } /** * The stage of the definition which contains all the minimum required inputs for * the resource to be created (via {@link WithCreate#create()}), but also allows * for any other optional settings to be specified. */ interface WithCreate extends Creatable<User>, DefinitionStages.WithEncryptedPassword, DefinitionStages.WithShareAccessRights { } } /** * The template for a User update operation, containing all the settings that can be modified. */ interface Update extends Appliable<User>, UpdateStages.WithEncryptedPassword, UpdateStages.WithShareAccessRights { } /** * Grouping of User update stages. */ interface UpdateStages { /** * The stage of the user update allowing to specify EncryptedPassword. */ interface WithEncryptedPassword { /** * Specifies encryptedPassword. * @param encryptedPassword The password details * @return the next update stage */ Update withEncryptedPassword(AsymmetricEncryptedSecret encryptedPassword); } /** * The stage of the user update allowing to specify ShareAccessRights. */ interface WithShareAccessRights { /** * Specifies shareAccessRights. * @param shareAccessRights List of shares that the user has rights on. This field should not be specified during user creation * @return the next update stage */ Update withShareAccessRights(List<ShareAccessRight> shareAccessRights); } } }
33.484848
157
0.641267
a95968c28533a3fba640d73ce8242f9026defd25
12,308
package com.eurekakids.euraka1; /** * Created by Kirubanand on 12/09/2015. */ import android.app.Fragment; import android.content.Intent; import android.support.design.widget.NavigationView; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v4.view.ViewPager; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.Spinner; import android.widget.Switch; import android.widget.Toast; import android.app.AlertDialog; import android.content.DialogInterface; import com.eurekakids.com.eurekakids.db.DatabaseHandler; import com.eurekakids.db.datamodel.Assessment; import com.eurekakids.db.datamodel.Student; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; public class tam_page extends AppCompatActivity { //Defining Variables private Toolbar toolbar; private NavigationView navigationView; private DrawerLayout drawerLayout; ViewPager pager; ViewPagerAdapter adapter; SlidingTabLayout tabs; MainActivity main; CharSequence Titles[]={"Tamil","English","Maths"}; int Numboftabs =3; Student student; int centre_id; List<WeakReference<Fragment>> fragList = new ArrayList<WeakReference<Fragment>>(); int saved =0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.edit_child); Intent list_item = getIntent(); student = (Student) list_item.getSerializableExtra("list_item"); centre_id = list_item.getExtras().getInt("CENTRE_ID"); // TextView username = (TextView) findViewById(R.id.username); // username.setText(name); Toast.makeText(getApplicationContext(),"Quick select Child from Navigation drawer",Toast.LENGTH_LONG).show(); // Initializing Toolbar and setting it as the actionbar toolbar = (Toolbar) findViewById(R.id.tool_bar); setSupportActionBar(toolbar); setTitle(student.getStudentName()); // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs. adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs, student.getStudentId()); // Assigning ViewPager View and setting the adapter pager = (ViewPager) findViewById(R.id.pager); pager.setAdapter(adapter); // Assiging the Sliding Tab Layout View tabs = (SlidingTabLayout) findViewById(R.id.tabs); tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width // Setting Custom Color for the Scroll bar indicator of the Tab View tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() { @Override public int getIndicatorColor(int position) { return getResources().getColor(R.color.tabsScrollColor); } }); DatabaseHandler db = new DatabaseHandler(getApplicationContext()); final ArrayList<Student> students = db.getAllStudentsByCentreId(centre_id); db.close(); Student[] names = new Student[students.size()]; for(int i =0; i< students.size(); i++){ names[i] = students.get(i); } ListAdapter nadapter = new ArrayAdapter<Student>(this,android.R.layout.simple_expandable_list_item_1,names); ListView nview = (ListView) findViewById(R.id.name_list); nview.setAdapter(nadapter); nview.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String itemSelected = parent.getItemAtPosition(position).toString(); setTitle(itemSelected); drawerLayout.closeDrawers(); } }); // Setting the ViewPager For the SlidingTabsLayout tabs.setViewPager(pager); //Initializing NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view); //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { // This method will trigger on item Click of navigation menu @Override public boolean onNavigationItemSelected(MenuItem menuItem) { //Checking if the item is in checked state or not, if not make it in checked state if (menuItem.isChecked()) menuItem.setChecked(false); else menuItem.setChecked(true); //Closing drawer on item click drawerLayout.closeDrawers(); //Check to see which item was being clicked and perform appropriate action switch (menuItem.getItemId()) { //Replacing the main content with ContentFragment Which is our Inbox View; case R.id.tamil: Toast.makeText(getApplicationContext(), "Tamil Selected", Toast.LENGTH_SHORT).show(); tam_fragment tamil_frament = new tam_fragment(); setTitle(R.string.nav_sub_1); android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.frame, tamil_frament); fragmentTransaction.commit(); return true; // For rest of the options we just show a toast on click case R.id.english: Toast.makeText(getApplicationContext(), "English Selected", Toast.LENGTH_SHORT).show(); eng_fragment fragment1 = new eng_fragment(); setTitle(R.string.nav_sub_2); android.support.v4.app.FragmentTransaction fragmentTransaction1 = getSupportFragmentManager().beginTransaction(); fragmentTransaction1.replace(R.id.frame, fragment1); fragmentTransaction1.commit(); return true; case R.id.math: Toast.makeText(getApplicationContext(), "Maths Selected", Toast.LENGTH_SHORT).show(); math_fragment fragment2 = new math_fragment(); setTitle(R.string.nav_sub_3); android.support.v4.app.FragmentTransaction fragmentTransaction2 = getSupportFragmentManager().beginTransaction(); fragmentTransaction2.replace(R.id.frame, fragment2); fragmentTransaction2.commit(); default: //Toast.makeText(getApplicationContext(),"Somethings Wrong",Toast.LENGTH_SHORT).show(); return true; } } }); // Initializing Drawer Layout and ActionBarToggle drawerLayout = (DrawerLayout) findViewById(R.id.drawer); ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.openDrawer, R.string.closeDrawer) { @Override public void onDrawerClosed(View drawerView) { // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank super.onDrawerClosed(drawerView); } @Override public void onDrawerOpened(View drawerView) { // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank super.onDrawerOpened(drawerView); } }; //Setting the actionbarToggle to drawer layout drawerLayout.setDrawerListener(actionBarDrawerToggle); //calling sync state is necessay or else your hamburger icon wont show up actionBarDrawerToggle.syncState(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.sub_menu, menu); return true; } @Override public void onBackPressed() { if(saved ==0 ){ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setCancelable(false); builder.setMessage("Save Changes?"); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //if user pressed "yes", then he is allowed to exit from application dialog.cancel(); Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT).show(); } }); builder.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //if user select "No", just cancel this dialog and continue with app dialog.cancel(); Intent getListintent = new Intent(tam_page.this,Listscreen.class); getListintent.putExtra("CENTRE_ID", student.getStudentId()); startActivity(getListintent); } }); AlertDialog alert = builder.create(); alert.show(); }else{ super.onBackPressed(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if(id == R.id.action_save){ Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT).show(); saved = 1; int skill = 1; DatabaseHandler db = new DatabaseHandler(getApplicationContext()); List<android.support.v4.app.Fragment> allFragments = getSupportFragmentManager().getFragments(); ArrayList<Assessment> assessments = new ArrayList<>(); for(android.support.v4.app.Fragment fragment : allFragments){ if(fragment != null) { ViewGroup viewGroup = (ViewGroup) fragment.getView(); ViewGroup linear = (ViewGroup) viewGroup.getChildAt(0); int view_count = linear.getChildCount(); for (int i = 0; i < view_count; i++) { View view = linear.getChildAt(i); boolean check_value = ((Switch) view).isChecked(); assessments.add(new Assessment(skill, student.getStudentId(), (check_value == true) ? 1 : 0)); skill++; } } } db.updateAssessment(assessments); db.close(); return true; } //noinspection SimplifiableIfStatement if (id == R.id.action_spinner) { Intent getSpinnerIntent = new Intent(this,Spinnerscreen.class); startActivity(getSpinnerIntent); return true; } return super.onOptionsItemSelected(item); } }
42.736111
161
0.613178
41b2488152c3cd33edf41295395b7b675c3b987b
1,957
// Copyright 2019 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.analysis; import com.google.common.collect.ImmutableList; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.analysis.actions.FileWriteAction; import com.google.devtools.build.lib.vfs.PathFragment; /** The class for constructing command line for Bash. */ public final class BashCommandConstructor implements CommandConstructor { private final PathFragment shellPath; private final String scriptNameSuffix; BashCommandConstructor(PathFragment shellPath, String scriptNameSuffix) { this.shellPath = shellPath; this.scriptNameSuffix = scriptNameSuffix; } @Override public ImmutableList<String> asExecArgv(Artifact scriptFileArtifact) { return ImmutableList.of(shellPath.getPathString(), scriptFileArtifact.getExecPathString()); } @Override public ImmutableList<String> asExecArgv(String command) { return ImmutableList.of(shellPath.getPathString(), "-c", command); } @Override public Artifact commandAsScript(RuleContext ruleContext, String command) { String scriptFileName = ruleContext.getTarget().getName() + scriptNameSuffix; String scriptFileContents = "#!/bin/bash\n" + command; return FileWriteAction.createFile( ruleContext, scriptFileName, scriptFileContents, /*executable=*/ true); } }
38.372549
95
0.770567
cd016660dae0894b42c7b5c848c429bbf6779457
1,162
package EmojiMod.patches.com.megacrit.cardcrawl.core.CardCrawlGame; import EmojiMod.EmojiMod; import com.evacipated.cardcrawl.modthespire.lib.*; import com.megacrit.cardcrawl.core.CardCrawlGame; import com.megacrit.cardcrawl.core.Settings; import com.megacrit.cardcrawl.localization.LocalizedStrings; import javassist.CtBehavior; @SpirePatch(cls="com.megacrit.cardcrawl.core.CardCrawlGame", method="create") public class PostLoadLocalizationPatch { //get hecked I hardcoded it and didn't make a subscriber @SpireInsertPatch( locator = Locator.class ) public static void PostLocalization(CardCrawlGame __instance) { EmojiMod.PostLoadLocalizationStrings(); } private static class Locator extends SpireInsertLocator { @Override public int[] Locate(CtBehavior ctMethodToPatch) throws Exception { //Matcher finalMatcher = new Matcher.ConstructorCallMatcher(SingleCardViewPopup.class); Matcher finalMatcher = new Matcher.FieldAccessMatcher(Settings.class, "IS_FULLSCREEN"); return LineFinder.findInOrder(ctMethodToPatch, finalMatcher); } } }
37.483871
99
0.744406
efb032cf6dfa3bb40e5234dd8416fb47a0c1b61f
3,462
package com.xplusj.operator; import org.junit.Test; import java.util.Objects; import java.util.function.Function; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; public class OperatorDefinitionTest { @Test public void testDefinition(){ OperatorType type = OperatorType.BINARY; Precedence precedence = Precedence.low(); Function<OperatorContextImplTest,Double> function = (ctx)->0D; int paramsLength = 2; OperatorDefinitionTestImpl definition = new OperatorDefinitionTestImpl(type,precedence,function,paramsLength); assertEquals(type, definition.getType()); assertEquals(precedence, definition.getPrecedence()); assertEquals(function, definition.getFunction()); assertEquals(paramsLength, definition.getParamsLength()); } @Test public void testDefinitionHashCode(){ OperatorType type = OperatorType.BINARY; Precedence precedence = Precedence.low(); Function<OperatorContextImplTest,Double> function = (ctx)->0D; int paramsLength = 2; OperatorDefinitionTestImpl definition = new OperatorDefinitionTestImpl(type,precedence,function,paramsLength); assertEquals(Objects.hash(definition.getIdentifier(), type, paramsLength), definition.hashCode()); } @Test public void testDefinitionEquals(){ OperatorType type = OperatorType.BINARY; Precedence precedence = Precedence.low(); Function<OperatorContextImplTest,Double> function = (ctx)->0D; int paramsLength = 2; OperatorDefinitionTestImpl definition = new OperatorDefinitionTestImpl(type,precedence,function,paramsLength); OperatorDefinitionTestImpl definition2 = new OperatorDefinitionTestImpl(type,null,null,paramsLength); assertEquals(definition, definition2); } @Test public void testDefinitionEquals2(){ OperatorType type = OperatorType.BINARY; Precedence precedence = Precedence.low(); Function<OperatorContextImplTest,Double> function = (ctx)->0D; int paramsLength = 2; OperatorDefinitionTestImpl definition = new OperatorDefinitionTestImpl(type,precedence,function,paramsLength); OperatorDefinitionTestImpl definition2 = new OperatorDefinitionTestImpl(type,precedence,function,3); assertNotEquals(definition, definition2); } @Test public void testDefinitionEquals3(){ OperatorType type = OperatorType.BINARY; Precedence precedence = Precedence.low(); Function<OperatorContextImplTest,Double> function = (ctx)->0D; int paramsLength = 2; OperatorDefinitionTestImpl definition = new OperatorDefinitionTestImpl(type,precedence,function,paramsLength); OperatorDefinitionTestImpl definition2 = new OperatorDefinitionTestImpl(OperatorType.UNARY,precedence,function,paramsLength); assertNotEquals(definition, definition2); } static class OperatorContextImplTest extends OperatorContext{ protected OperatorContextImplTest() { super(null); } } static class OperatorDefinitionTestImpl extends OperatorDefinition<OperatorContextImplTest>{ OperatorDefinitionTestImpl(OperatorType type, Precedence precedence, Function<OperatorContextImplTest, Double> function, int paramsLength) { super("", type, precedence, function, paramsLength); } } }
38.898876
148
0.728192
04a1136f6d0d83e513eb0a5347c5405d5f1b4180
3,835
package uo.ri.model; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import uo.ri.model.types.Address; @Entity public class Cliente { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(unique = true) private String dni; private String nombre; private String apellidos; private Address address; @OneToMany(mappedBy = "cliente") private Set<Vehiculo> vehiculos = new HashSet<>(); @OneToMany(mappedBy = "cliente") private Set<MedioPago> mediosDePago = new HashSet<>(); /** * Allocates a client object and initializes it so that it represents a * client from the real world. */ Cliente() {} /** * Allocates a client object and initializes it so that it represents a * client from the real world. * * @param dni of the client. */ public Cliente( String dni ) { super(); this.dni = dni; } /** * Allocates a client object and initializes it so that it represents a * client from the real world. * * @param dni to set. * @param nombre of the client * @param apellidos of the client. */ public Cliente( String dni, String nombre, String apellidos ) { this( dni ); this.nombre = nombre; this.apellidos = apellidos; } /** * @return the unique id of the object. JPA. */ public Long getId() { return id; } /** * @return the dni of the client. */ public String getDni() { return dni; } /** * @return the name of the client. */ public String getNombre() { return nombre; } /** * Changes the name of the client. * * @param nombre of the client. */ public void setNombre( String nombre ) { this.nombre = nombre; } /** * @return the surname of the client. */ public String getApellidos() { return apellidos; } /** * Changes the surname of the client. * * @param apellidos of the client to change/set. */ public void setApellidos( String apellidos ) { this.apellidos = apellidos; } /** * @return the address of the client. */ public Address getAddress() { return address; } /** * Changes the address of the client. * * @param address of the client to change/set. */ public void setAddress( Address address ) { this.address = address; } /** * @return a copy of the original set of vehicles of the client. */ public Set<Vehiculo> getVehiculos() { return new HashSet<>( vehiculos ); } /** * @return a copy of the original set of payment types. */ public Set<MedioPago> getMediosPago() { return new HashSet<>( mediosDePago ); } /** * @return the original set of vehicles of the client. */ Set<Vehiculo> _getVehiculos() { return vehiculos; } /** * @return the original set of payment types of the client. */ Set<MedioPago> _getMediosPago() { return mediosDePago; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ( ( dni == null ) ? 0 : dni.hashCode() ); return result; } @Override public boolean equals( Object obj ) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Cliente other = (Cliente) obj; if (dni == null) { if (other.dni != null) return false; } else if (!dni.equals( other.dni )) return false; return true; } @Override public String toString() { return "Cliente [dni=" + dni + ", nombre=" + nombre + ", apellidos=" + apellidos + ", address=" + address + "]"; } }
21.914286
89
0.628162
008409890c281589f06fde86247291b1b0b12109
2,388
package com.cerner.beadledom.jaxrs.provider; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import java.util.List; /** * Basic model used for testing simple cases. */ @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonPropertyOrder({ "id", "name", "times", "tags", "inner_models" }) public class FakeModel { @JsonProperty("id") public String id; @JsonProperty("name") public String name; @JsonProperty("times") public int times; @JsonProperty("tags") public List<String> tags; @JsonProperty("inner_models") public List<FakeInnerModel> innerModels; public FakeModel() { } public FakeModel( String id, String name, int times, List<String> tags, List<FakeInnerModel> innerModels) { this.id = id; this.name = name; this.times = times; this.tags = tags; this.innerModels = innerModels; } public FakeModel setId(String id) { this.id = id; return this; } public FakeModel setName(String name) { this.name = name; return this; } public FakeModel setTimes(int times) { this.times = times; return this; } public FakeModel setTags(List<String> tags) { this.tags = tags; return this; } public FakeModel setInnerModels( List<FakeInnerModel> innerModels) { this.innerModels = innerModels; return this; } @JsonProperty("id") public String getId() { return id; } @JsonProperty("times") public int getTimes() { return times; } @JsonProperty("tags") public List<String> getTags() { return tags; } public List<FakeInnerModel> getInnerModels() { return innerModels; } @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonPropertyOrder({ "id", "name", "tags", }) /** * This is purposefully missing methods so that we can validate no performance impact occurs. */ public static class FakeInnerModel { @JsonProperty("id") public String id; @JsonProperty("name") public String name; @JsonProperty("tags") public List<String> tags; public FakeInnerModel(String id, String name, List<String> tags) { this.id = id; this.name = name; this.tags = tags; } public List<String> getTags() { return tags; } } }
20.237288
95
0.659548
a08f96739af95c6382e4ff27def025f1ec4ae6c8
4,004
package com.ybj.myshopping.fragment; import android.support.design.widget.FloatingActionButton; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.ybj.myshopping.adapter.HomeRecycleAdapter; import com.ybj.myshopping.R; import com.ybj.myshopping.bean.ResultBean; import com.ybj.myshopping.common.BaseFragment; import com.ybj.myshopping.ui.ScrollerTextView; import com.ybj.myshopping.utils.Constants; import butterknife.BindView; import butterknife.OnClick; /** * Created by 杨阳洋 on 2017/2/10. */ public class HomeFragment extends BaseFragment { @BindView(R.id.home_scan) LinearLayout mHomeScan; @BindView(R.id.home_search) ImageView mHomeSearch; @BindView(R.id.home_search_desc) ScrollerTextView mHomeSearchDesc; @BindView(R.id.home_camera) ImageView mHomeCamera; @BindView(R.id.home_point_msg) TextView mHomePointMsg; @BindView(R.id.home_msg) LinearLayout mHomeMsg; @BindView(R.id.home_recyclerView) RecyclerView mHomeRecyclerView; @BindView(R.id.home_fab) FloatingActionButton mHomeFab; private ResultBean mResultBean; private HomeRecycleAdapter mRecycleAdapter; @Override protected String getUrl() { return Constants.HOME_URL; } @Override protected void initData(String content) { processData(content); mRecycleAdapter = new HomeRecycleAdapter(getActivity(), mResultBean); //设置适配器 mHomeRecyclerView.setAdapter(mRecycleAdapter); //设置recyclerView的类型 final LinearLayoutManager manager = new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false); mHomeRecyclerView.setLayoutManager(manager); mHomeRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); int lastVisibleItemPosition = manager.findLastVisibleItemPosition(); if(lastVisibleItemPosition > 4) { mHomeFab.setVisibility(View.VISIBLE); }else{ mHomeFab.setVisibility(View.GONE); } } }); } /** * 解析数据 * * @param content */ private void processData(String content) { JSONObject jsonObject = JSON.parseObject(content); //得到状态码 String code = jsonObject.getString("code"); String msg = jsonObject.getString("msg"); String result = jsonObject.getString("result"); //得到resultBean的数据 mResultBean = JSON.parseObject(result, ResultBean.class); } @Override protected void initTitle() { } @Override public int getLayoutId() { return R.layout.fragment_home; } @OnClick({R.id.home_scan, R.id.home_search, R.id.home_search_desc, R.id.home_camera, R.id.home_point_msg, R.id.home_msg, R.id.home_recyclerView, R.id.home_fab}) public void onClick(View view) { switch (view.getId()) { case R.id.home_scan: break; case R.id.home_search: break; case R.id.home_search_desc: break; case R.id.home_camera: break; case R.id.home_point_msg: break; case R.id.home_msg: break; case R.id.home_recyclerView: break; case R.id.home_fab: break; } } }
29.014493
164
0.652348
d81a0817abba59ee0b33eff19c2f4b223f6d9787
1,100
package com.trains.fixtures; import com.trains.graph.Graph; import com.trains.graph.Vertex; import com.trains.graph.allpaths.AllPaths; import java.util.Arrays; import java.util.Collections; import java.util.List; public class AllPathsFixture { private final AllPaths allPaths; public AllPathsFixture(AllPaths allPaths) { this.allPaths = allPaths; } public int test6CountAllTripsCCMax3(Graph graph) { List<Vertex> vertices = graph.findVertices(Collections.singletonList("C")); return allPaths.AllPathsUpTo(3, vertices.get(0), vertices.get(0), graph).size(); } public int test7CountAllTripsAEEquals4(Graph graph) { List<Vertex> vertices = graph.findVertices(Arrays.asList("A", "C")); return allPaths.AllPathsEqualsTo(4, vertices.get(0), vertices.get(1), graph).size(); } public int test10CountAllTripsCCLessThan30(Graph graph) { List<Vertex> vertices = graph.findVertices(Collections.singletonList("C")); return allPaths.AllPathsWeightLessThan(30, vertices.get(0), vertices.get(0), graph).size(); } }
31.428571
99
0.716364
c5822da5aff7cfaa417b11f87d73d7257866a7fd
1,502
package com.mateuszkoslacz.moviper.rxsample.viper.view.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.mateuszkoslacz.moviper.rxsample.R; import com.mateuszkoslacz.moviper.rxsample.viper.entity.User; import com.mateuszkoslacz.moviper.rxsample.viper.view.viewholder.UserViewHolder; import java.util.List; /** * Created by jjodelka on 17/10/16. */ public class UserAdapter extends RecyclerView.Adapter<UserViewHolder> { private List<User> mUserList; private UserClickListener mUserClickListener; public UserAdapter(UserClickListener mUserClickListener) { this.mUserClickListener = mUserClickListener; } @Override public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_user_row, parent, false); return new UserViewHolder(itemView); } @Override public void onBindViewHolder(UserViewHolder holder, int position) { holder.bind(mUserList.get(position), mUserClickListener); } @Override public int getItemCount() { return mUserList != null ? mUserList.size() : 0; } public void setUserList(List<User> userList) { this.mUserList = userList; notifyDataSetChanged(); } public interface UserClickListener { void onUserClick(User user); } }
28.339623
80
0.728362
d754ca83db7e07241aa50ee27fe3e0ed4958d5ac
2,678
/* * MIT License * * Copyright (c) 2021 Solid * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.solid.testharness.reporting; import org.eclipse.rdf4j.model.IRI; import org.solid.common.vocab.SPEC; import org.solid.testharness.utils.DataModelBase; import java.util.List; public class SpecificationRequirement extends DataModelBase { private List<TestCase> testCases; public SpecificationRequirement(final IRI subject) { super(subject, ConstructMode.INC_REFS); testCases = getModelListByObject(SPEC.requirementReference, TestCase.class); } public String getRequirementSubject() { return getIriAsString(SPEC.requirementSubject); } public String getRequirementLevel() { return getIriAsString(SPEC.requirementLevel); } public String getStatement() { return getIriAsString(SPEC.statement); } public List<TestCase> getTestCases() { return testCases; } public int countTestCases() { return getTestCases() != null ? getTestCases().size() : 0; } public long countFailed() { return testCases != null ? testCases.stream().filter(TestCase::isFailed).count() : 0; } public long countPassed() { return testCases != null ? testCases.stream().filter(TestCase::isPassed).count() : 0; } public boolean isFailed() { return testCases != null && testCases.stream().anyMatch(TestCase::isFailed); } public boolean isPassed() { return testCases != null && testCases.stream().allMatch(TestCase::isPassed); } }
33.475
84
0.698282
2c95f23cafa8819ceacca871398663ee03d7b544
501
package net.hollowbit.archipeloserver.tools.entity; import net.hollowbit.archipeloserver.entity.Entity; public class EntityStepOnData { public String theirCollisionRectName; public String yourCollisionRectName; public Entity entity; public EntityStepOnData (String theirCollisionRectName, String yourCollisionRectName, Entity entity) { this.theirCollisionRectName = theirCollisionRectName; this.yourCollisionRectName = yourCollisionRectName; this.entity = entity; } }
29.470588
104
0.800399
c9233fd3206e009cda7702251f789c92ca778473
3,134
package common.model.ads; import java.io.Serializable; /** * @author Maycon Viana Bordin <[email protected]> */ public class AdEvent implements Serializable { private static final long serialVersionUID = 2107785080405113092L; private Type type; private String displayUrl; private long queryId; private long adID; private long userId; private long advertiserId; private long keywordId; private long titleId; private long descriptionId; private int depth; private int position; public AdEvent() { } public AdEvent(String displayUrl, long queryId, long adID, long userId, long advertiserId, long keywordId, long titleId, long descriptionId, int depth, int position) { this.displayUrl = displayUrl; this.queryId = queryId; this.adID = adID; this.userId = userId; this.advertiserId = advertiserId; this.keywordId = keywordId; this.titleId = titleId; this.descriptionId = descriptionId; this.depth = depth; this.position = position; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } public String getDisplayUrl() { return displayUrl; } public void setDisplayUrl(String displayUrl) { this.displayUrl = displayUrl; } public long getQueryId() { return queryId; } public void setQueryId(long queryId) { this.queryId = queryId; } public long getAdID() { return adID; } public void setAdID(long adID) { this.adID = adID; } public long getUserId() { return userId; } public void setUserId(long userId) { this.userId = userId; } public long getAdvertiserId() { return advertiserId; } public void setAdvertiserId(long advertiserId) { this.advertiserId = advertiserId; } public long getKeywordId() { return keywordId; } public void setKeywordId(long keywordId) { this.keywordId = keywordId; } public long getTitleId() { return titleId; } public void setTitleId(long titleId) { this.titleId = titleId; } public long getDescriptionId() { return descriptionId; } public void setDescriptionId(long descriptionId) { this.descriptionId = descriptionId; } public int getDepth() { return depth; } public void setDepth(int depth) { this.depth = depth; } public int getPosition() { return position; } public void setPosition(int position) { this.position = position; } @Override public String toString() { return "AdEvent{" + "type=" + type + ", displayUrl=" + displayUrl + ", queryId=" + queryId + ", adID=" + adID + ", userId=" + userId + ", advertiserId=" + advertiserId + ", keywordId=" + keywordId + ", titleId=" + titleId + ", descriptionId=" + descriptionId + ", depth=" + depth + ", position=" + position + '}'; } public enum Type {Click, Impression} }
23.56391
321
0.616146
52b388a57c7c13ad8b207acdb5f8882c2d383672
555
package javaexercises2; /** * * @author velko */ public class _14_CalcAbs { /** * @param args the command line arguments */ public static void main(String[] args) { // "Simulacion" de entrada de varios numeros int[] numbers = {-1, 2, -9, -8, 9, 1, 3, -6}; // Manual for(int currentNumber : numbers) { int abs = (currentNumber < 0) ? -currentNumber : currentNumber; System.out.println("Valor absoluto de " + currentNumber + ": " + abs); } } }
23.125
82
0.527928
6fac0d27fcee617d0860f74da4d53ef5ef4a3884
515
package de.egga.mega_types.texts.email; import de.egga.mega_types.Value; import java.util.regex.Matcher; import java.util.regex.Pattern; public abstract class EmailAddress extends Value<String>{ public EmailAddress(String value) { super(value); } abstract Pattern getValidationPattern(); public void validate() { Matcher matcher = getValidationPattern().matcher(getValue()); if (!matcher.matches()) { throw new IllegalArgumentException(); } } }
22.391304
69
0.679612
7ae029bf4fdf95469ad83160d2aa16224653c582
24,057
package com.licrafter.tagview; import android.animation.Animator; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.database.DataSetObserver; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PathMeasure; import android.graphics.RectF; import android.support.v4.view.GestureDetectorCompat; import android.util.AttributeSet; import android.util.Property; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import com.licrafter.tagview.utils.DipConvertUtils; import com.licrafter.tagview.views.ITagView; import com.licrafter.tagview.views.RippleView; import java.util.ArrayList; import java.util.List; /** * author: shell * date 2016/12/20 下午2:24 **/ public class TagViewGroup extends ViewGroup { public static final int DEFAULT_RADIUS = 8;//默认外圆半径 public static final int DEFAULT_INNER_RADIUS = 4;//默认内圆半径 public static final int DEFAULT_V_DISTANCE = 28;//默认竖直(上/下)方向线条长度 public static final int DEFAULT_TILT_DISTANCE = 20;//默认斜线长度 public static final int DEFAULT_LINES_WIDTH = 1;//默认线宽 public static final int DEFAULT_MAX_TAG = 6;//默认标签最大数量 private static final int DEFAULT_RIPPLE_MAX_RADIUS = 20;//水波纹默认最大半径 private static final int DEFULT_RIPPLE_ALPHA = 100;//默认水波纹透明度 static class ItemInfo { ITagView item; int position; RectF rectF = new RectF(); } private Paint mPaint; private Path mPath; private Path mDstPath; private PathMeasure mPathMeasure; private Animator mShowAnimator; private Animator mHideAnimator; private TagAdapter mAdapter; private GestureDetectorCompat mGestureDetector; private OnTagGroupClickListener mClickListener; private OnTagGroupDragListener mScrollListener; private final TagSetObserver mObserver = new TagSetObserver(); private RippleView mRippleView; private int mRippleMaxRadius;//水波纹最大半径 private int mRippleMinRadius;//水波纹最小半径 private int mRippleAlpha;//水波纹起始透明度 private int mRadius;//外圆半径 private int mInnerRadius;//内圆半径 private int mTDistance;//斜线长度 private int mVDistance;//竖直(上/下)方向线条长度 private float mTagAlpha;//Tag标签的透明度 private RectF mCenterRect; private ArrayList<ItemInfo> mItems = new ArrayList<>(); private int[] mChildUsed; private int mCenterX;//圆心 X 坐标 private int mCenterY;//圆心 Y 坐标 private float mPercentX; private float mPercentY; private int mLinesWidth;//线条宽度 private float mLinesRatio = 1; public TagViewGroup(Context context) { this(context, null); } public TagViewGroup(Context context, AttributeSet attrs) { this(context, attrs, 0); } public TagViewGroup(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); Resources.Theme theme = context.getTheme(); TypedArray array = theme.obtainStyledAttributes(attrs, R.styleable.TagViewGroup, defStyleAttr, 0); mRadius = array.getDimensionPixelSize(R.styleable.TagViewGroup_radius, DipConvertUtils.dip2px(context, DEFAULT_RADIUS)); mInnerRadius = array.getDimensionPixelSize(R.styleable.TagViewGroup_inner_radius, DipConvertUtils.dip2px(context, DEFAULT_INNER_RADIUS)); mTDistance = array.getDimensionPixelSize(R.styleable.TagViewGroup_tilt_distance, DipConvertUtils.dip2px(context, DEFAULT_TILT_DISTANCE)); mVDistance = array.getDimensionPixelSize(R.styleable.TagViewGroup_v_distance, DipConvertUtils.dip2px(context, DEFAULT_V_DISTANCE)); mLinesWidth = array.getDimensionPixelSize(R.styleable.TagViewGroup_line_width, DipConvertUtils.dip2px(context, DEFAULT_LINES_WIDTH)); mRippleMaxRadius = array.getDimensionPixelSize(R.styleable.TagViewGroup_ripple_maxRadius, DipConvertUtils.dip2px(context, DEFAULT_RIPPLE_MAX_RADIUS)); mRippleAlpha = array.getInteger(R.styleable.TagViewGroup_ripple_alpha, DEFULT_RIPPLE_ALPHA); mRippleMinRadius = mInnerRadius + (mRadius - mInnerRadius) / 2; array.recycle(); mPaint = new Paint(); mPath = new Path(); mDstPath = new Path(); mPathMeasure = new PathMeasure(); mPaint.setAntiAlias(true); mGestureDetector = new GestureDetectorCompat(context, new TagOnGestureListener()); mChildUsed = new int[4]; mCenterRect = new RectF(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); measureChildren(widthMeasureSpec, heightMeasureSpec); mChildUsed = getChildUsed(); //园中心默认在左上角 (0,0) mCenterX = (int) (getMeasuredWidth() * mPercentX); mCenterY = (int) (getMeasuredHeight() * mPercentY); checkBounds(); mCenterRect.set(mCenterX - mRadius, mCenterY - mRadius, mCenterX + mRadius, mCenterY + mRadius); if (mRippleView != null) { mRippleView.setCenterPoint(mCenterX, mCenterY); } } /** * 获取中心圆上下左右各个方向的宽度 * * @return int[]{left,top,right,bottom} */ private int[] getChildUsed() { int childCount = getChildCount(); int leftMax = mVDistance, topMax = mVDistance, rightMax = mVDistance, bottomMax = mVDistance; for (int i = 0; i < childCount; i++) { ITagView child = (ITagView) getChildAt(i); switch (child.getDirection()) { case RIGHT_TOP_TILT://右上斜线 rightMax = Math.max(rightMax, mTDistance + child.getMeasuredWidth()); topMax = Math.max(topMax, child.getMeasuredHeight() + mTDistance); break; case RIGHT_TOP://右上 rightMax = Math.max(rightMax, child.getMeasuredWidth()); topMax = Math.max(topMax, child.getMeasuredHeight() + mVDistance); break; case RIGHT_CENTER://右中 rightMax = Math.max(rightMax, child.getMeasuredWidth()); topMax = Math.max(topMax, Math.max(mVDistance, child.getMeasuredHeight())); break; case RIGHT_BOTTOM://右下 rightMax = Math.max(rightMax, child.getMeasuredWidth()); bottomMax = mVDistance; break; case RIGHT_BOTTOM_TILT: rightMax = Math.max(rightMax, mTDistance + child.getMeasuredWidth()); bottomMax = mTDistance; break; case LEFT_TOP://左上 leftMax = Math.max(leftMax, child.getMeasuredWidth()); topMax = Math.max(topMax, child.getMeasuredHeight() + mVDistance); break; case LEFT_TOP_TILT://左上斜线 leftMax = Math.max(leftMax, child.getMeasuredWidth() + mTDistance); topMax = Math.max(topMax, child.getMeasuredHeight() + mTDistance); break; case LEFT_CENTER://左中 leftMax = Math.max(leftMax, child.getMeasuredWidth()); topMax = Math.max(topMax, Math.max(mVDistance, child.getMeasuredHeight())); break; case LEFT_BOTTOM://左下 leftMax = Math.max(leftMax, child.getMeasuredWidth()); bottomMax = mVDistance; break; case LEFT_BOTTOM_TILT://左下斜线 leftMax = Math.max(leftMax, child.getMeasuredWidth() + mTDistance); bottomMax = mTDistance; break; } } return new int[]{leftMax, topMax, rightMax, bottomMax}; } private void checkBounds() { int rightAvailable = getMeasuredWidth() - mCenterX; int leftAvailable = mCenterX; if (mChildUsed[2] > rightAvailable) { mCenterX -= (mChildUsed[2] - rightAvailable); } if (mChildUsed[0] > leftAvailable) { mCenterX += (mChildUsed[0] - leftAvailable); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int left = 0, top = 0; for (int i = 0; i < getChildCount(); i++) { ITagView child = (ITagView) getChildAt(i); switch (child.getDirection()) { case RIGHT_TOP_TILT://右上斜线 top = mCenterY - mTDistance - child.getMeasuredHeight(); left = mCenterX + mTDistance; break; case RIGHT_TOP://右上 left = mCenterX; top = mCenterY - mVDistance - child.getMeasuredHeight(); break; case RIGHT_CENTER://右中 left = mCenterX; top = mCenterY - child.getMeasuredHeight(); break; case RIGHT_BOTTOM://右下 left = mCenterX; top = mVDistance + mCenterY - child.getMeasuredHeight(); break; case RIGHT_BOTTOM_TILT://右下斜线 left = mCenterX + mTDistance; top = mTDistance + mCenterY - child.getMeasuredHeight(); break; case LEFT_TOP://左上 left = mCenterX - child.getMeasuredWidth(); top = mCenterY - mVDistance - child.getMeasuredHeight(); break; case LEFT_TOP_TILT://左上斜线 left = mCenterX - child.getMeasuredWidth() - mTDistance; top = mCenterY - mTDistance - child.getMeasuredHeight(); break; case LEFT_CENTER://左中 left = mCenterX - child.getMeasuredWidth(); top = mCenterY - child.getMeasuredHeight(); break; case LEFT_BOTTOM://左下 left = mCenterX - child.getMeasuredWidth(); top = mVDistance + mCenterY - child.getMeasuredHeight(); break; case LEFT_BOTTOM_TILT://左下斜线 left = mCenterX - child.getMeasuredWidth() - mTDistance; top = mTDistance + mCenterY - child.getMeasuredHeight(); break; case CENTER: left = 0; top = 0; break; } child.layout(left, top, left + child.getMeasuredWidth(), top + child.getMeasuredHeight()); refreshTagsInfo(child); } } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); //绘制折线 drawLines(canvas); //绘制外圆 mPaint.setStyle(Paint.Style.FILL); mPaint.setColor(Color.parseColor("#30000000")); canvas.drawCircle(mCenterX, mCenterY, mRadius, mPaint); //绘制内圆 mPaint.setStyle(Paint.Style.FILL); mPaint.setColor(Color.WHITE); canvas.drawCircle(mCenterX, mCenterY, mInnerRadius, mPaint); } @Override protected void onAttachedToWindow() { if (mRippleView != null) { mRippleView.startRipple(); } super.onAttachedToWindow(); } @Override protected void onDetachedFromWindow() { if (mRippleView != null) { mRippleView.stopRipple(); } super.onDetachedFromWindow(); } private void drawTagAlpha(float alpha) { for (int i = 0; i < getChildCount(); i++) { getChildAt(i).setAlpha(alpha); } } private void drawLines(Canvas canvas) { mPaint.setColor(Color.WHITE); mPaint.setStrokeWidth(mLinesWidth); mPaint.setStyle(Paint.Style.STROKE); for (int i = 0; i < getChildCount(); i++) { ITagView child = (ITagView) getChildAt(i); mPath.reset(); mPath.moveTo(mCenterX, mCenterY); mDstPath.reset(); mDstPath.rLineTo(0, 0); switch (child.getDirection()) { case RIGHT_TOP://右上 case RIGHT_BOTTOM://右下 case RIGHT_TOP_TILT://右上斜线 case RIGHT_BOTTOM_TILT://右下斜线 mPath.lineTo(child.getLeft(), child.getBottom()); case RIGHT_CENTER://右中 mPath.lineTo(child.getRight(), child.getBottom()); break; case LEFT_TOP://左上 case LEFT_TOP_TILT://左上斜线 case LEFT_BOTTOM://左下 case LEFT_BOTTOM_TILT://左下斜线 mPath.lineTo(child.getRight(), child.getBottom()); case LEFT_CENTER://左中 mPath.lineTo(child.getLeft(), child.getBottom()); break; } mPathMeasure.setPath(mPath, false); mPathMeasure.getSegment(0, mPathMeasure.getLength() * mLinesRatio, mDstPath, true); canvas.drawPath(mDstPath, mPaint); } } ItemInfo addnewItem(int position) { ItemInfo itemInfo = new ItemInfo(); itemInfo.position = position; itemInfo.item = mAdapter.instantiateItem(this, position); mItems.add(itemInfo); return itemInfo; } /** * 得到 TagViewGroup 中的所有标签列表 * * @return */ public List<ITagView> getTagList() { List<ITagView> list = new ArrayList<>(); for (int i = 0; i < mItems.size(); i++) { list.add(mItems.get(i).item); } return list; } /** * 添加水波纹 */ public TagViewGroup addRipple() { mRippleView = new RippleView(getContext()); mRippleView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); mRippleView.setDirection(DIRECTION.CENTER); mRippleView.initAnimator(mRippleMinRadius, mRippleMaxRadius, mRippleAlpha); addView(mRippleView); return this; } public TagViewGroup setShowAnimator(Animator animator) { mShowAnimator = animator; return this; } public TagViewGroup setHideAnimator(Animator animator) { mHideAnimator = animator; return this; } public void startShowAnimator() { if (mShowAnimator != null && !mShowAnimator.isRunning()) { mShowAnimator.start(); } } public void startHideAnimator() { if (mHideAnimator != null && !mHideAnimator.isRunning()) { mHideAnimator.start(); } } public void setTagAdapter(TagAdapter adapter) { if (mAdapter != null) { mAdapter.unregisterDataSetObserver(mObserver); clearGroup(); } mAdapter = adapter; if (mAdapter != null) { mAdapter.registerDataSetObserver(mObserver); } populate(); } public TagAdapter getTagAdapter() { return mAdapter; } void clearGroup() { for (int i = 0; i < mItems.size(); i++) { ItemInfo itemInfo = mItems.get(i); mAdapter.destroyItem(this, itemInfo.position, itemInfo.item); mItems.clear(); removeAllViews(); } } void populate() { int count = mAdapter.getCount(); if (count < 0 || count > DEFAULT_MAX_TAG) { throw new IllegalStateException("TagView count must >= 0 and <= " + DEFAULT_MAX_TAG); } for (int i = 0; i < count; i++) { addnewItem(i); } } void dataSetChanged() { clearGroup(); populate(); } ItemInfo infoForChild(View child) { for (int i = 0; i < mItems.size(); i++) { ItemInfo info = mItems.get(i); if (mAdapter.isViewFromObject(child, info)) { return info; } } return null; } ItemInfo infoForTagView(ITagView tagView) { for (int i = 0; i < mItems.size(); i++) { ItemInfo info = mItems.get(i); if (info.item.equals(tagView)) { return info; } } return null; } private void refreshTagsInfo(ITagView child) { if (child.getDirection() != DIRECTION.CENTER) { infoForTagView(child).rectF.set(child.getLeft(), child.getTop(), child.getRight(), child.getBottom()); } } /** * 检测 Touch 事件发生在哪个 Tag 上 * * @param x * @param y * @return */ private ItemInfo isTouchingTags(float x, float y) { for (int i = 0; i < mItems.size(); i++) { ItemInfo info = mItems.get(i); if (info.rectF.contains(x, y)) { return info; } } return null; } //设置中心圆点坐标占整个 ViewGroup 的比例 public void setPercent(float percentX, float percentY) { mPercentX = percentX; mPercentY = percentY; } @Override public boolean onTouchEvent(MotionEvent event) { if (mClickListener != null) { return mGestureDetector.onTouchEvent(event); } return super.onTouchEvent(event); } public void setOnTagGroupClickListener(OnTagGroupClickListener listener) { mClickListener = listener; } public void setOnTagGroupDragListener(OnTagGroupDragListener listener) { this.mScrollListener = listener; } public interface OnTagGroupClickListener { //TagGroup 中心圆点被点击 void onCircleClick(TagViewGroup container); //TagGroup Tag子view被点击 void onTagClick(TagViewGroup container, ITagView tag, int position); //TagGroup 被长按 void onLongPress(TagViewGroup container); } public interface OnTagGroupDragListener { //TagGroup 拖动 void onDrag(TagViewGroup container, float percentX, float percentY); } //内部处理 touch 事件监听器 private class TagOnGestureListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onDown(MotionEvent e) { float x = e.getX(); float y = e.getY(); if (mCenterRect.contains(x, y) || isTouchingTags(x, y) != null) { return true; } return super.onDown(e); } @Override public boolean onSingleTapUp(MotionEvent e) { float x = e.getX(); float y = e.getY(); if (mCenterRect.contains(x, y)) { mClickListener.onCircleClick(TagViewGroup.this); } else { ItemInfo info = isTouchingTags(x, y); if (info != null) { mClickListener.onTagClick(TagViewGroup.this, info.item, info.position); } } return true; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { if (mScrollListener != null) { float currentX = mCenterX - distanceX; float currentY = mCenterY - distanceY; currentX = Math.min(Math.max(currentX, mChildUsed[0]), getMeasuredWidth() - mChildUsed[2]); currentY = Math.min(Math.max(currentY, mChildUsed[1]), getMeasuredHeight() - mChildUsed[3]); mPercentX = currentX / getMeasuredWidth(); mPercentY = currentY / getMeasuredHeight(); invalidate(); requestLayout(); mScrollListener.onDrag(TagViewGroup.this, mPercentX, mPercentY); } return true; } @Override public void onLongPress(MotionEvent e) { super.onLongPress(e); float x = e.getX(); float y = e.getY(); if (mCenterRect.contains(x, y) || isTouchingTags(x, y) != null) { mClickListener.onLongPress(TagViewGroup.this); } } } /** * 设置中心圆的半径 */ @SuppressWarnings("unused") public void setCircleRadius(int radius) { mRadius = radius; invalidate(); } public int getCircleRadius() { return mRadius; } /** * 设置中心内圆半径 */ @SuppressWarnings("unused") public void setCircleInnerRadius(int innerRadius) { mInnerRadius = innerRadius; invalidate(); } public int getCircleInnerRadius() { return mInnerRadius; } /** * 设置线条显示比例 */ @SuppressWarnings("unused") public void setLinesRatio(float ratio) { mLinesRatio = ratio; invalidate(); } public float getLinesRatio() { return mLinesRatio; } /** * 设置 Tag 的透明度 */ @SuppressWarnings("unused") public void setTagAlpha(float alpha) { mTagAlpha = alpha; drawTagAlpha(mTagAlpha); } public float getTagAlpha() { return mTagAlpha; } /** * 设置线条宽度 * * @param lineWidth 线条宽度 */ public void setLineWidth(int lineWidth) { mLinesWidth = lineWidth; invalidate(); } /** * 得到线条宽度 * * @return */ public int getLineWidth() { return mLinesWidth; } /** * 设置圆心到折点的垂直距离 * * @param vDistance 垂直距离 */ public void setVDistance(int vDistance) { mVDistance = vDistance; } public int getVDistance() { return mVDistance; } /** * 设置圆心到斜线折点的垂直距离 * * @param titlDistance 垂直距离 */ public void setTitlDistance(int titlDistance) { mTDistance = titlDistance; } public int getTitlDistance() { return mTDistance; } /** * 设置水波纹最大半径 * * @param radius 最大半径 */ public void setRippleMaxRadius(int radius) { mRippleMaxRadius = radius; } public int getRippleMaxRadius() { return mRippleMaxRadius; } /** * 设置水波纹起始透明度 * * @param alpha 透明度 */ public void setRippleAlpha(int alpha) { mRippleAlpha = alpha; } public int getRippleAlpha() { return mRippleAlpha; } public class TagSetObserver extends DataSetObserver { @Override public void onChanged() { dataSetChanged(); } } public static final Property<TagViewGroup, Integer> CIRCLE_RADIUS = new Property<TagViewGroup, Integer>(Integer.class, "circleRadius") { @Override public Integer get(TagViewGroup object) { return object.getCircleRadius(); } @Override public void set(TagViewGroup object, Integer value) { object.setCircleRadius(value); } }; public static final Property<TagViewGroup, Integer> CIRCLE_INNER_RADIUS = new Property<TagViewGroup, Integer>(Integer.class, "circleInnerRadius") { @Override public Integer get(TagViewGroup object) { return object.getCircleInnerRadius(); } @Override public void set(TagViewGroup object, Integer value) { object.setCircleInnerRadius(value); } }; public static final Property<TagViewGroup, Float> LINES_RATIO = new Property<TagViewGroup, Float>(Float.class, "linesRatio") { @Override public Float get(TagViewGroup object) { return object.getLinesRatio(); } @Override public void set(TagViewGroup object, Float value) { object.setLinesRatio(value); } }; public static final Property<TagViewGroup, Float> TAG_ALPHA = new Property<TagViewGroup, Float>(Float.class, "tagAlpha") { @Override public Float get(TagViewGroup object) { return object.getTagAlpha(); } @Override public void set(TagViewGroup object, Float value) { object.setTagAlpha(value); } }; }
32.553451
158
0.584362
2db7dc4282800c5db71e5b3f39b09fb30a7a72ed
371
package cn.ikidou.sample.okcallback; /** * Created by ikidou on 15-10-12. */ public class User { public String name; public int age; public Sex sex; @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + ", sex=" + sex + '}'; } }
18.55
40
0.450135
a9185df74bee9f67bda8b882adf6bb5326d99c19
4,027
package org.glob3.mobile.generated; // // TMSLayer.cpp // G3MiOSSDK // // Created by Eduardo de la Montaña on 05/03/13. // // // // TMSLayer.hpp // G3MiOSSDK // // Created by Eduardo de la Montaña on 05/03/13. // // public abstract class TMSLayer extends RasterLayer { private final URL _mapServerURL; private final String _mapLayer; private final Sector _dataSector ; private final String _format; private final boolean _isTransparent; public TMSLayer(String mapLayer, URL mapServerURL, Sector dataSector, String format, boolean isTransparent, LayerCondition condition, TimeInterval timeToCache, boolean readExpired, LayerTilesRenderParameters parameters, float transparency) { this(mapLayer, mapServerURL, dataSector, format, isTransparent, condition, timeToCache, readExpired, parameters, transparency, ""); } public TMSLayer(String mapLayer, URL mapServerURL, Sector dataSector, String format, boolean isTransparent, LayerCondition condition, TimeInterval timeToCache, boolean readExpired, LayerTilesRenderParameters parameters) { this(mapLayer, mapServerURL, dataSector, format, isTransparent, condition, timeToCache, readExpired, parameters, 1, ""); } public TMSLayer(String mapLayer, URL mapServerURL, Sector dataSector, String format, boolean isTransparent, LayerCondition condition, TimeInterval timeToCache, boolean readExpired) { this(mapLayer, mapServerURL, dataSector, format, isTransparent, condition, timeToCache, readExpired, null, 1, ""); } public TMSLayer(String mapLayer, URL mapServerURL, Sector dataSector, String format, boolean isTransparent, LayerCondition condition, TimeInterval timeToCache, boolean readExpired, LayerTilesRenderParameters parameters, float transparency, String disclaimerInfo) { super(timeToCache, readExpired, (parameters == null) ? LayerTilesRenderParameters.createDefaultWGS84(dataSector, 0, 17) : parameters, transparency, condition, disclaimerInfo); _mapServerURL = mapServerURL; _mapLayer = mapLayer; _dataSector = new Sector(dataSector); _format = format; _isTransparent = isTransparent; } public final java.util.ArrayList<Petition> createTileMapPetitions(G3MRenderContext rc, LayerTilesRenderParameters layerTilesRenderParameters, Tile tile) { java.util.ArrayList<Petition> petitions = new java.util.ArrayList<Petition>(); final Sector tileSector = tile._sector; if (!_dataSector.touchesWith(tileSector)) { return petitions; } IStringBuilder isb = IStringBuilder.newStringBuilder(); isb.addString(_mapServerURL._path); isb.addString(_mapLayer); isb.addString("/"); isb.addInt(tile._level); isb.addString("/"); isb.addInt(tile._column); isb.addString("/"); isb.addInt(tile._row); isb.addString("."); isb.addString(IStringUtils.instance().replaceSubstring(_format, "image/", "")); ILogger.instance().logInfo(isb.getString()); Petition petition = new Petition(tileSector, new URL(isb.getString(), false), _timeToCache, _readExpired, _isTransparent, _transparency); petitions.add(petition); return petitions; } public final URL getFeatureInfoURL(Geodetic2D g, Sector sector) { return URL.nullURL(); } public final String description() { return "[TMSLayer]"; } public final RenderState getRenderState() { _errors.clear(); if (_mapLayer.compareTo("") == 0) { _errors.add("Missing layer parameter: mapLayer"); } final String mapServerUrl = _mapServerURL._path; if (mapServerUrl.compareTo("") == 0) { _errors.add("Missing layer parameter: mapServerURL"); } if (_format.compareTo("") == 0) { _errors.add("Missing layer parameter: format"); } if (_errors.size() > 0) { return RenderState.error(_errors); } return RenderState.ready(); } }
33.558333
265
0.701266
d68018f4368779cf8f229156512054539383ae10
764
// // Copyright (c) FIRST and other WPILib contributors. // // Open Source Software; you can modify and/or share it under the terms of // // the WPILib BSD license file in the root directory of this project. // package frc.robot.subsystems; // import edu.wpi.first.wpilibj.XboxController; // import edu.wpi.first.wpilibj2.command.SubsystemBase; // public class LimeLightSend extends SubsystemBase { // /** Creates a new LimeLightSend. */ // private XboxController primaryController; // public LimeLightSend() { // } // @Override // public void periodic() { // // This method will be called once per scheduler run // } // public boolean whatIsY() { // if (primaryController.getYButtonPressed()) { // return true; // } else { // return false; // } // } // }
23.875
77
0.697644
1493e22f95da4617297a3032cc5d2b38c1404c0d
1,382
package app.eeui.framework.extend.integration.glide.load.resource; import android.content.Context; import androidx.annotation.NonNull; import app.eeui.framework.extend.integration.glide.load.Transformation; import app.eeui.framework.extend.integration.glide.load.engine.Resource; import java.security.MessageDigest; /** * A no-op Transformation that simply returns the given resource. * * @param <T> The type of the resource that will always be returned unmodified. */ public final class UnitTransformation<T> implements Transformation<T> { private static final Transformation<?> TRANSFORMATION = new UnitTransformation<>(); /** * Returns a UnitTransformation for the given type. * * @param <T> The type of the resource to be transformed. */ @SuppressWarnings("unchecked") @NonNull public static <T> UnitTransformation<T> get() { return (UnitTransformation<T>) TRANSFORMATION; } private UnitTransformation() { // Only accessible as a singleton. } @NonNull @Override public Resource<T> transform(@NonNull Context context, @NonNull Resource<T> resource, int outWidth, int outHeight) { return resource; } @Override public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) { // Do nothing. } /* Use default implementations of equals and hashcode. */ }
30.043478
88
0.717077
8e5149c99d80c391b5cc2ce3681cc1f7d7dc4743
752
package Node; public class SnapshotInfo { private int sentMessages; private int processedMessages; private int snapshotNumber; public SnapshotInfo() { this.sentMessages = 0; this.processedMessages = 0; this.snapshotNumber = 0; } public int getSentMessages() { return sentMessages; } public void incrementSentMessages() { this.sentMessages++; } public void incrementProcessedMessages() { this.processedMessages++; } public void incrementSnapshotNumber() { this.snapshotNumber++; } public int getProcessedMessages() { return processedMessages; } public int getSnapshotNumber() { return snapshotNumber; } }
19.789474
46
0.635638
ac834dcbcee11a9a1dff207fffbad67ffd6fd632
3,121
// // JSON.java // // AndroidJSCore project // https://github.com/ericwlange/AndroidJSCore/ // // LiquidPlayer project // https://github.com/LiquidPlayer // // Created by Eric Lange // /* Copyright (c) 2014-2016 Eric Lange. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.liquidplayer.javascript; /** * A convenience class for creating JavaScript values from JSON * @since 0.1.0 */ @SuppressWarnings("WeakerAccess,SameParameterValue") public class JSON extends JSValue { private JSON(JSContext ctx, final String str) { context = ctx; valueRef = context.ctxRef().makeFromJSONString(str); } /** * Gets a JSON string representation of any object * @param value The JSValue to convert to JSON * @return a JSON string representing 'object' * @since 0.1.0 */ public static String stringify(JSValue value) { return value.getContext().property("JSON").toObject() .property("stringify").toFunction().call(null,value) .toString(); } /** * Gets a JSON string representation of any object * @param ctx A js context * @param object The object to convert to JSON * @return a JSON string representing 'object' * @since 0.1.0 */ public static String stringify(JSContext ctx, Object object) { return ctx.property("JSON").toObject() .property("stringify").toFunction().call(null,object) .toString(); } /** * Creates a new JavaScript value from a JSString JSON string * @param ctx The context in which to create the value * @param json The string containing the JSON * @return a JSValue containing the parsed value, or JSValue.isNull() if malformed * @since 0.1.0 */ public static JSValue parse(JSContext ctx, String json) { return new JSON(ctx,json); } }
36.717647
86
0.708747
6d6f2d0e37745cfab93ec8e253756107d0b5b4a2
7,684
/* * (C) Copyright 2005-2021, by Christian Soltenborn and Contributors. * * JGraphT : a free Java graph-theory library * * See the CONTRIBUTORS.md file distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0, or the * GNU Lesser General Public License v2.1 or later * which is available at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html. * * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later */ package org.jgrapht.alg.connectivity; import org.jgrapht.*; import org.jgrapht.graph.*; import org.jgrapht.util.*; import java.util.*; /** * Computes strongly connected components of a directed graph. The algorithm is implemented after * "Cormen et al: Introduction to algorithms", Chapter 22.5. It has a running time of $O(V + E)$. * * <p> * Unlike {@link ConnectivityInspector}, this class does not implement incremental inspection. The * full algorithm is executed at the first call of * {@link KosarajuStrongConnectivityInspector#stronglyConnectedSets()} or * {@link KosarajuStrongConnectivityInspector#isStronglyConnected()}. * * @param <V> the graph vertex type * @param <E> the graph edge type * * @author Christian Soltenborn * @author Christian Hammer */ public class KosarajuStrongConnectivityInspector<V, E> extends AbstractStrongConnectivityInspector<V, E> { // stores the vertices, ordered by their finishing time in first dfs private LinkedList<VertexData<V>> orderedVertices; // maps vertices to their VertexData object private Map<V, VertexData<V>> vertexToVertexData; /** * Constructor * * @param graph the input graph * @throws NullPointerException if the input graph is null */ public KosarajuStrongConnectivityInspector(Graph<V, E> graph) { super(graph); } @Override public List<Set<V>> stronglyConnectedSets() { if (stronglyConnectedSets == null) { orderedVertices = new LinkedList<>(); stronglyConnectedSets = new ArrayList<>(); // create VertexData objects for all vertices, store them createVertexData(); // perform the first round of DFS, result is an ordering // of the vertices by decreasing finishing time for (VertexData<V> data : vertexToVertexData.values()) { if (!data.isDiscovered()) { dfsVisit(graph, data, null); } } // 'create' inverse graph (i.e. every edge is reversed) Graph<V, E> inverseGraph = new EdgeReversedGraph<>(graph); // get ready for next dfs round resetVertexData(); // second dfs round: vertices are considered in decreasing // finishing time order; every tree found is a strongly // connected set for (VertexData<V> data : orderedVertices) { if (!data.isDiscovered()) { // new strongly connected set Set<V> set = new HashSet<>(); stronglyConnectedSets.add(set); dfsVisit(inverseGraph, data, set); } } // clean up for garbage collection orderedVertices = null; vertexToVertexData = null; } return stronglyConnectedSets; } /* * Creates a VertexData object for every vertex in the graph and stores them in a HashMap. */ private void createVertexData() { vertexToVertexData = CollectionUtil.newHashMapWithExpectedSize(graph.vertexSet().size()); for (V vertex : graph.vertexSet()) { vertexToVertexData.put(vertex, new VertexData2<>(vertex, false, false)); } } /* * The subroutine of DFS. NOTE: the set is used to distinguish between 1st and 2nd round of DFS. * set == null: finished vertices are stored (1st round). set != null: all vertices found will * be saved in the set (2nd round) */ private void dfsVisit(Graph<V, E> visitedGraph, VertexData<V> vertexData, Set<V> vertices) { Deque<VertexData<V>> stack = new ArrayDeque<>(); stack.add(vertexData); while (!stack.isEmpty()) { VertexData<V> data = stack.removeLast(); if (!data.isDiscovered()) { data.setDiscovered(true); if (vertices != null) { vertices.add(data.getVertex()); } stack.add(new VertexData1<>(data, true, true)); // follow all edges for (E edge : visitedGraph.outgoingEdgesOf(data.getVertex())) { VertexData<V> targetData = vertexToVertexData.get(visitedGraph.getEdgeTarget(edge)); if (!targetData.isDiscovered()) { // the "recursion" stack.add(targetData); } } } else if (data.isFinished() && vertices == null) { orderedVertices.addFirst(data.getFinishedData()); } } } /* * Resets all VertexData objects. */ private void resetVertexData() { for (VertexData<V> data : vertexToVertexData.values()) { data.setDiscovered(false); data.setFinished(false); } } /* * Lightweight class storing some data for every vertex. */ private abstract static class VertexData<V> { private byte bitfield; private VertexData(boolean discovered, boolean finished) { this.bitfield = 0; setDiscovered(discovered); setFinished(finished); } private boolean isDiscovered() { return (bitfield & 1) == 1; } private boolean isFinished() { return (bitfield & 2) == 2; } private void setDiscovered(boolean discovered) { if (discovered) { bitfield |= 1; } else { bitfield &= ~1; } } private void setFinished(boolean finished) { if (finished) { bitfield |= 2; } else { bitfield &= ~2; } } abstract VertexData<V> getFinishedData(); abstract V getVertex(); } private static final class VertexData1<V> extends VertexData<V> { private final VertexData<V> finishedData; private VertexData1(VertexData<V> finishedData, boolean discovered, boolean finished) { super(discovered, finished); this.finishedData = finishedData; } @Override VertexData<V> getFinishedData() { return finishedData; } @Override V getVertex() { return null; } } private static final class VertexData2<V> extends VertexData<V> { private final V vertex; private VertexData2(V vertex, boolean discovered, boolean finished) { super(discovered, finished); this.vertex = vertex; } @Override VertexData<V> getFinishedData() { return null; } @Override V getVertex() { return vertex; } } }
28.996226
100
0.572749
3d77e891e57e6cb7ebd74c00fb71a31bf55a3569
12,653
/** * Copyright 2021 Shulie Technology, Co.Ltd * Email: [email protected] * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * See the License for the specific language governing permissions and * limitations under the License. */ package com.shulie.instrument.simulator.core.logback; import ch.qos.logback.classic.spi.LoggingEvent; import ch.qos.logback.core.CoreConstants; import ch.qos.logback.core.FileAppender; import ch.qos.logback.core.rolling.RollingPolicy; import ch.qos.logback.core.rolling.RollingPolicyBase; import ch.qos.logback.core.rolling.RolloverFailure; import ch.qos.logback.core.rolling.TriggeringPolicy; import ch.qos.logback.core.rolling.helper.CompressionMode; import ch.qos.logback.core.rolling.helper.FileNamePattern; import ch.qos.logback.core.util.ContextUtil; import com.shulie.instrument.simulator.core.util.CustomerReflectUtils; import org.apache.commons.lang.StringUtils; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.util.Map; import static ch.qos.logback.core.CoreConstants.CODES_URL; import static ch.qos.logback.core.CoreConstants.MORE_INFO_PREFIX; /** * @author angju * @date 2021/8/20 11:16 */ public class CustomerRollingFileAppender<E> extends FileAppender<E> { File currentlyActiveFile; TriggeringPolicy<E> triggeringPolicy; RollingPolicy rollingPolicy; static private final String RFA_NO_TP_URL = CODES_URL + "#rfa_no_tp"; static private final String RFA_NO_RP_URL = CODES_URL + "#rfa_no_rp"; static private final String COLLISION_URL = CODES_URL + "#rfa_collision"; static private final String RFA_LATE_FILE_URL = CODES_URL + "#rfa_file_after"; @Override public void start() { if (triggeringPolicy == null) { addWarn("No TriggeringPolicy was set for the RollingFileAppender named " + getName()); addWarn(MORE_INFO_PREFIX + RFA_NO_TP_URL); return; } if (!triggeringPolicy.isStarted()) { addWarn("TriggeringPolicy has not started. RollingFileAppender will not start"); return; } if (checkForCollisionsInPreviousRollingFileAppenders()) { addError("Collisions detected with FileAppender/RollingAppender instances defined earlier. Aborting."); addError(MORE_INFO_PREFIX + COLLISION_WITH_EARLIER_APPENDER_URL); return; } // we don't want to void existing log files if (!append) { addWarn("Append mode is mandatory for RollingFileAppender. Defaulting to append=true."); append = true; } if (rollingPolicy == null) { addError("No RollingPolicy was set for the RollingFileAppender named " + getName()); addError(MORE_INFO_PREFIX + RFA_NO_RP_URL); return; } // sanity check for http://jira.qos.ch/browse/LOGBACK-796 if (checkForFileAndPatternCollisions()) { addError("File property collides with fileNamePattern. Aborting."); addError(MORE_INFO_PREFIX + COLLISION_URL); return; } if (isPrudent()) { if (rawFileProperty() != null) { addWarn("Setting \"File\" property to null on account of prudent mode"); setFile(null); } if (rollingPolicy.getCompressionMode() != CompressionMode.NONE) { addError("Compression is not supported in prudent mode. Aborting"); return; } } currentlyActiveFile = new File(getFile()); addInfo("Active log file name: " + getFile()); super.start(); } private boolean checkForFileAndPatternCollisions() { if (triggeringPolicy instanceof RollingPolicyBase) { final RollingPolicyBase base = (RollingPolicyBase) triggeringPolicy; // final FileNamePattern fileNamePattern = base.fileNamePattern; final FileNamePattern fileNamePattern = CustomerReflectUtils.getFileNamePattern(base); // no use checking if either fileName or fileNamePattern are null if (fileNamePattern != null && fileName != null) { String regex = fileNamePattern.toRegex(); return fileName.matches(regex); } } return false; } private boolean checkForCollisionsInPreviousRollingFileAppenders() { boolean collisionResult = false; if (triggeringPolicy instanceof RollingPolicyBase) { final RollingPolicyBase base = (RollingPolicyBase) triggeringPolicy; // final FileNamePattern fileNamePattern = base.fileNamePattern; final FileNamePattern fileNamePattern = CustomerReflectUtils.getFileNamePattern(base); boolean collisionsDetected = innerCheckForFileNamePatternCollisionInPreviousRFA(fileNamePattern); if (collisionsDetected) { collisionResult = true; } } return collisionResult; } private boolean innerCheckForFileNamePatternCollisionInPreviousRFA(FileNamePattern fileNamePattern) { boolean collisionsDetected = false; @SuppressWarnings("unchecked") Map<String, FileNamePattern> map = (Map<String, FileNamePattern>) context.getObject( CoreConstants.RFA_FILENAME_PATTERN_COLLISION_MAP); if (map == null) { return collisionsDetected; } for (Map.Entry<String, FileNamePattern> entry : map.entrySet()) { if (fileNamePattern.equals(entry.getValue())) { addErrorForCollision("FileNamePattern", entry.getValue().toString(), entry.getKey()); collisionsDetected = true; } } if (name != null) { map.put(getName(), fileNamePattern); } return collisionsDetected; } @Override public void stop() { super.stop(); if (rollingPolicy != null) { rollingPolicy.stop(); } if (triggeringPolicy != null) { triggeringPolicy.stop(); } Map<String, FileNamePattern> map = ContextUtil.getFilenamePatternCollisionMap(context); if (map != null && getName() != null) { map.remove(getName()); } } @Override public void setFile(String file) { // http://jira.qos.ch/browse/LBCORE-94 // allow setting the file name to null if mandated by prudent mode if (file != null && ((triggeringPolicy != null) || (rollingPolicy != null))) { addError("File property must be set before any triggeringPolicy or rollingPolicy properties"); addError(MORE_INFO_PREFIX + RFA_LATE_FILE_URL); } super.setFile(file); } @Override public String getFile() { return rollingPolicy.getActiveFileName(); } /** * Implemented by delegating most of the rollover work to a rolling policy. */ public void rollover() { lock.lock(); try { // Note: This method needs to be synchronized because it needs exclusive // access while it closes and then re-opens the target file. // // make sure to close the hereto active log file! Renaming under windows // does not work for open files. this.closeOutputStream(); attemptRollover(); attemptOpenFile(); } finally { lock.unlock(); } } private void attemptOpenFile() { try { // update the currentlyActiveFile LOGBACK-64 currentlyActiveFile = new File(rollingPolicy.getActiveFileName()); // This will also close the file. This is OK since multiple close operations are safe. this.openFile(rollingPolicy.getActiveFileName()); } catch (IOException e) { addError("setFile(" + fileName + ", false) call failed.", e); } } private void attemptRollover() { try { rollingPolicy.rollover(); } catch (RolloverFailure rf) { addWarn("RolloverFailure occurred. Deferring roll-over."); // we failed to roll-over, let us not truncate and risk data loss this.append = true; } } /** * This method differentiates RollingFileAppender from its super class. */ @Override protected void subAppend(E event) { eventMsgHandler(event); // The roll-over check must precede actual writing. This is the // only correct behavior for time driven triggers. // We need to synchronize on triggeringPolicy so that only one rollover // occurs at a time synchronized (triggeringPolicy) { if (triggeringPolicy.isTriggeringEvent(currentlyActiveFile, event)) { rollover(); } } super.subAppend(event); } private volatile Field messageFiled = null; private volatile Field formattedMessageFiled = null; /** * 拼消息 * * @param event * @return */ private E eventMsgHandler(E event) { if (event instanceof LoggingEvent) { try { if (messageFiled == null) { messageFiled = event.getClass().getDeclaredField("message"); messageFiled.setAccessible(true); } if (formattedMessageFiled == null) { formattedMessageFiled = event.getClass().getDeclaredField("formattedMessage"); formattedMessageFiled.setAccessible(true); } } catch (NoSuchFieldException e) { //ignore } // try { // if (formattedMessageFiled == null){ // formattedMessageFiled = event.getClass().getDeclaredField("formattedMessage"); // formattedMessageFiled.setAccessible(true); // } // }catch (NoSuchFieldException e){ // //ignore // } String errorMsg = ((LoggingEvent) event).getFormattedMessage(); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("127.0.0.1").append("|"); stringBuilder.append(0).append("|"); stringBuilder.append(System.currentTimeMillis()).append("|"); if (StringUtils.isNotBlank(System.getProperty("pradar.env.code"))) { stringBuilder.append(System.getProperty("tenant.app.key")).append("|"); stringBuilder.append(System.getProperty("pradar.env.code")).append("|"); stringBuilder.append(System.getProperty("pradar.user.id")).append("|"); } stringBuilder.append(System.getProperty("agentId")).append("|"); stringBuilder.append(System.getProperty("app_name")).append("|"); stringBuilder.append(errorMsg); try { messageFiled.set(event, stringBuilder.toString()); formattedMessageFiled.set(event, stringBuilder.toString()); } catch (Exception e) { } // ((LoggingEvent)event).setMessage(errorMsg); } return event; } public RollingPolicy getRollingPolicy() { return rollingPolicy; } public TriggeringPolicy<E> getTriggeringPolicy() { return triggeringPolicy; } /** * Sets the rolling policy. In case the 'policy' argument also implements * {@link TriggeringPolicy}, then the triggering policy for this appender is * automatically set to be the policy argument. * * @param policy */ @SuppressWarnings("unchecked") public void setRollingPolicy(RollingPolicy policy) { rollingPolicy = policy; if (rollingPolicy instanceof TriggeringPolicy) { triggeringPolicy = (TriggeringPolicy<E>) policy; } } public void setTriggeringPolicy(TriggeringPolicy<E> policy) { triggeringPolicy = policy; if (policy instanceof RollingPolicy) { rollingPolicy = (RollingPolicy) policy; } } }
37.770149
115
0.618351
58783db1170c78e14b186f963775fd85c644bde0
1,023
package com.example.controlmoneyapi.service; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.stereotype.Service; import com.example.controlmoneyapi.model.Pessoa; import com.example.controlmoneyapi.repository.PessoaRepository; @Service public class PessoaService { @Autowired private PessoaRepository pessoaRepository; public Pessoa atualizar(Long codigo, Pessoa pessoa) { Pessoa pessoaSalva = this.pessoaRepository.findById(codigo) .orElseThrow(() -> new EmptyResultDataAccessException(1)); BeanUtils.copyProperties(pessoa, pessoaSalva, "codigo"); return pessoaRepository.save(pessoaSalva); } public void atualizarProAtivo(Long codigo, Boolean ativo) { Pessoa pessoaSalva = this.pessoaRepository.findById(codigo) .orElseThrow(() -> new EmptyResultDataAccessException(1)); pessoaSalva.setAtivo(ativo); pessoaRepository.save(pessoaSalva); } }
34.1
63
0.811339
1bdb2c68aaaae776d5a07d36996ffc22180b88e4
3,726
package com.synopsys.integration.alert.api.channel.issue.callback; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import java.util.Optional; import org.junit.jupiter.api.Test; import com.synopsys.integration.alert.api.channel.issue.model.IssueBomComponentDetails; import com.synopsys.integration.alert.api.channel.issue.model.ProjectIssueModel; import com.synopsys.integration.alert.common.channel.issuetracker.message.IssueTrackerCallbackInfo; import com.synopsys.integration.alert.common.message.model.LinkableItem; import com.synopsys.integration.alert.processor.api.extract.model.ProviderDetails; import com.synopsys.integration.alert.processor.api.extract.model.project.AbstractBomComponentDetails; import com.synopsys.integration.alert.processor.api.extract.model.project.ComponentUpgradeGuidance; import com.synopsys.integration.alert.processor.api.extract.model.project.ComponentVulnerabilities; public class IssueTrackerCallbackInfoCreatorTest { private static final LinkableItem TEST_ITEM = new LinkableItem("Test Label", "Test Value"); private static final AbstractBomComponentDetails BOM_COMPONENT_DETAILS = new AbstractBomComponentDetails( TEST_ITEM, TEST_ITEM, new ComponentVulnerabilities(List.of(), List.of(), List.of(), List.of()), List.of(), TEST_ITEM, "Example Usage", ComponentUpgradeGuidance.none(), List.of(), "https://issues-url" ) {}; private static final LinkableItem PROVIDER_ITEM = new LinkableItem("Provider", "Test Provider", "https://provider-url"); private static final ProviderDetails PROVIDER_DETAILS = new ProviderDetails(0L, PROVIDER_ITEM); private static final IssueBomComponentDetails ISSUE_BOM_COMPONENT_DETAILS = IssueBomComponentDetails.fromBomComponentDetails(BOM_COMPONENT_DETAILS); @Test public void createCallbackInfoNoProjectVersionUrlTest() { LinkableItem projectVersionNoUrl = new LinkableItem("Project Version", "A Project Version", null); ProjectIssueModel projectIssueModel = ProjectIssueModel.bom(PROVIDER_DETAILS, TEST_ITEM, projectVersionNoUrl, ISSUE_BOM_COMPONENT_DETAILS); IssueTrackerCallbackInfoCreator callbackInfoCreator = new IssueTrackerCallbackInfoCreator(); Optional<IssueTrackerCallbackInfo> callbackInfo = callbackInfoCreator.createCallbackInfo(projectIssueModel); assertTrue(callbackInfo.isEmpty(), "Expected no callback info to be present because no project-version url was present"); } @Test public void createCallbackInfoWithProjectVersionUrlTest() { LinkableItem projectVersionWithUrl = new LinkableItem("Project Version", "A Project Version", "https://project-version-url"); ProjectIssueModel projectIssueModel = ProjectIssueModel.bom(PROVIDER_DETAILS, TEST_ITEM, projectVersionWithUrl, ISSUE_BOM_COMPONENT_DETAILS); IssueTrackerCallbackInfoCreator callbackInfoCreator = new IssueTrackerCallbackInfoCreator(); Optional<IssueTrackerCallbackInfo> optionalCallbackInfo = callbackInfoCreator.createCallbackInfo(projectIssueModel); assertTrue(optionalCallbackInfo.isPresent(), "Expected a callback info to be present because a project-version url was present"); IssueTrackerCallbackInfo callbackInfo = optionalCallbackInfo.get(); assertEquals(PROVIDER_DETAILS.getProviderConfigId(), callbackInfo.getProviderConfigId()); assertEquals(BOM_COMPONENT_DETAILS.getBlackDuckIssuesUrl(), callbackInfo.getCallbackUrl()); assertEquals(projectVersionWithUrl.getUrl().orElse(null), callbackInfo.getBlackDuckProjectVersionUrl()); } }
59.142857
152
0.794686
ede055fafa8d8ddf350e675c0fc2f20b7bc64b7e
1,671
package com.sap.persistenceservice.refapp.controller; import com.fasterxml.jackson.databind.node.ArrayNode; import com.sap.persistenceservice.refapp.service.ConnectionPoolManager; import com.sap.persistenceservice.refapp.service.PreprocessingSubscriberService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import org.eclipse.paho.client.mqttv3.MqttException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController @Tag(name = "Preprocessing Subscriber") public class PreprocessingSubscriberController { private static final Logger log = LoggerFactory.getLogger(PreprocessingSubscriberController.class); @Autowired private ConnectionPoolManager connectionPoolManager; @Autowired private PreprocessingSubscriberService preprocessingSubscriberService; @PostMapping(value = "/preprocessing/subscribe") @Operation(description = "Subscribe to the MQTT topic") public void subscribe(@RequestBody String connectionUrl) throws MqttException { preprocessingSubscriberService.setupClient(connectionUrl); } @GetMapping(value = "/preprocessing/messages") @Operation(description = "Fetch all MQTT messages received on preprocessing output topic") public ArrayNode getMessages() { return preprocessingSubscriberService.getMessages(); } }
40.756098
103
0.813884
427352a81c2a9c01f8f2e52f95f9a0708da9108e
2,477
package br.skylight.commons; import java.util.logging.Logger; import br.skylight.commons.dli.annotations.MessageField; import br.skylight.commons.dli.services.Message; import br.skylight.commons.dli.services.MessageType; public class MessageFieldDef { private static final Logger logger = Logger.getLogger(MessageFieldDef.class.getName()); private MessageType messageType; private int fieldNumber; private String label; private Message message; public MessageFieldDef(MessageType messageType, int fieldNumber) { this.messageType = messageType; this.fieldNumber = fieldNumber; try { //set field label Message m = messageType.getImplementation().newInstance(); MessageField mf = m.getMessageField(fieldNumber); if(mf!=null) { label = m.getField(fieldNumber).getName(); } } catch (Exception e) { logger.throwing(null,null,e); } } public void updateMessage(Message message) { if(!message.getMessageType().equals(messageType)) { throw new IllegalArgumentException("Message type must be " + messageType); } this.message = message; } public String getFormattedValue() { try { return message.getFormattedValue(fieldNumber); } catch (Exception e) { logger.throwing(null,null,e); return "ERROR"; } } public double getValue() { try { return message.getValue(fieldNumber); } catch (Exception e) { logger.throwing(null,null,e); return Double.NaN; } } public MessageType getMessageType() { return messageType; } public int getFieldNumber() { return fieldNumber; } public String getLabel() { return label; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + fieldNumber; result = prime * result + ((messageType == null) ? 0 : messageType.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MessageFieldDef other = (MessageFieldDef) obj; if (fieldNumber != other.fieldNumber) return false; if (messageType == null) { if (other.messageType != null) return false; } else if (!messageType.equals(other.messageType)) return false; return true; } @Override public String toString() { return messageType + "["+ fieldNumber +"]"; } }
23.817308
89
0.670569
ec5f483f32fee33fd2d37711a235a50b8b884d1b
309
/******************************************************* * Copyright 2018 jpcode * contact http://www.jpcode.net/ * * --- stfx * ********************************************************/ package net.jpcode.stfx.aop; /** * 操作类别 * @author billyzh * */ public enum OpCategory { NONE, SYSTEM }
14.045455
58
0.375405
0173daca1f087acc9625dedd585004a00d13a442
2,278
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.workbench.common.stunner.core.registry.impl; import java.util.Collection; import java.util.Collections; import java.util.List; import org.kie.workbench.common.stunner.core.registry.DynamicRegistry; class ListRegistry<T> implements DynamicRegistry<T> { private final KeyProvider<T> keyProvider; private final List<T> items; public ListRegistry(final KeyProvider<T> keyProvider, final List<T> items) { this.keyProvider = keyProvider; this.items = items; } public void add(final int pos, final T item) { items.add(pos, item); } @Override public void register(final T item) { items.add(item); } public boolean remove(final T item) { return items.remove(item); } @Override public boolean contains(final T item) { return items.contains(item); } @Override public boolean isEmpty() { return items.isEmpty(); } public Collection<T> getItems() { return Collections.unmodifiableList(items); } public T getItemByKey(final String id) { if (null != id) { for (final T item : items) { final String itemId = getItemKey(item); if (id.equals(itemId)) { return item; } } } return null; } public void clear() { items.clear(); } public int indexOf(final T item) { return items.indexOf(item); } private String getItemKey(final T item) { return keyProvider.getKey(item); } }
25.595506
75
0.620281
a34d457453a3efad37b5d3b013cd157ca4d68bfe
3,713
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.cli.ifelse; import static org.junit.Assert.assertEquals; import org.jboss.as.cli.CommandContext; import org.jboss.as.test.integration.management.util.CLITestUtil; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.core.testrunner.WildflyTestRunner; /** * * @author Alexey Loubyansky */ @RunWith(WildflyTestRunner.class) public class BasicIfElseTestCase extends CLISystemPropertyTestBase { @Test public void testMain() throws Exception { final CommandContext ctx = CLITestUtil.getCommandContext(cliOut); try { ctx.connectController(); ctx.handle(this.getAddPropertyReq("\"true\"")); assertEquals("false", runIf(ctx)); assertEquals("true", runIf(ctx)); assertEquals("false", runIf(ctx)); } finally { ctx.handleSafe(this.getRemovePropertyReq()); ctx.terminateSession(); cliOut.reset(); } } @Test public void testIfMatchComparison() throws Exception { final CommandContext ctx = CLITestUtil.getCommandContext(cliOut); try { ctx.connectController(); ctx.handle(this.getAddPropertyReq("match-test-values", "\"AAA BBB\"")); assertEquals("true", runIfWithMatchComparison("match-test-values", "AAA", ctx)); assertEquals("true", runIfWithMatchComparison("match-test-values", "BBB", ctx)); assertEquals("false", runIfWithMatchComparison("match-test-values", "CCC", ctx)); } finally { ctx.handleSafe(this.getRemovePropertyReq("match-test-values")); ctx.terminateSession(); cliOut.reset(); } } protected String runIf(CommandContext ctx) throws Exception { ctx.handle("if result.value==\"true\" of " + this.getReadPropertyReq()); ctx.handle(this.getWritePropertyReq("\"false\"")); ctx.handle("else"); ctx.handle(this.getWritePropertyReq("\"true\"")); ctx.handle("end-if"); cliOut.reset(); ctx.handle(getReadPropertyReq()); return getValue(); } protected String runIfWithMatchComparison(String propertyName, String lookupValue, CommandContext ctx) throws Exception { ctx.handle("set match=false"); ctx.handle("if result.value~=\".*" + lookupValue + ".*\" of " + this.getReadPropertyReq(propertyName)); ctx.handle("set match=true"); ctx.handle("else"); ctx.handle("set match=false"); ctx.handle("end-if"); cliOut.reset(); ctx.handle("echo $match"); return cliOut.toString().trim(); } }
37.505051
125
0.666038
c1f70e74bf2bb99c592735529c8805da7bff301b
454
package es.unican.istr.sanchezbp.teaching.enterpriseSystems.iod; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; public class OrderHandler { @Autowired protected NotificationSender sender; public OrderHandler() { } public void processOrder(Order o) { this.sender.sendMessage("Order accepted",o.getUser()); } }
22.7
64
0.797357
f6d77b89557f98c9fba3743aff2bf0f33a8b1414
3,120
package it.multicoredev.mclib.db; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DBUtils { /** * Closes the ResultSet, the Statement and the Connection. * * @param result CompositeResult with ResultSet, Statement and Connection to close */ public static void closeQuietly(CompositeResult result) { try { if (result.getResult() != null) { if (!result.getResult().isClosed()) { result.getResult().close(); } } if (result.getStatement() != null) { if (!result.getStatement().isClosed()) { result.getStatement().close(); } } if (result.getConnection() != null) { if (!result.getConnection().isClosed()) { result.getConnection().close(); } } } catch (SQLException ignored) { } } /** * Closes the ResultSet, the Statement and the Connection. * * @param connection Connection to close * @param statement Statement to close * @param result ResultSet to close */ public static void closeQuietly(Connection connection, Statement statement, ResultSet result) { try { if (result != null) { if (!result.isClosed()) { result.close(); } } if (statement != null) { if (!statement.isClosed()) { statement.close(); } } if (connection != null) { if (!connection.isClosed()) { connection.close(); } } } catch (SQLException ignored) { } } /** * Closes the ResultSet, the Statement and the Connection. * * @param result ResultSet to close */ public static void closeQuietly(ResultSet result) { try { if (result != null) { if (!result.isClosed()) { result.close(); } } } catch (SQLException ignored) { } } /** * Closes the ResultSet, the Statement and the Connection. * * @param statement Statement to close */ public static void closeQuietly(Statement statement) { try { if (statement != null) { if (!statement.isClosed()) { statement.close(); } } } catch (SQLException ignored) { } } /** * Closes the ResultSet, the Statement and the Connection. * * @param connection Connection to close */ public static void closeQuietly(Connection connection) { try { if (connection != null) { if (!connection.isClosed()) { connection.close(); } } } catch (SQLException ignored) { } } }
26.896552
99
0.484295
c9f786e83084fc0bbe10c7d7e2bf9bdd084aef32
217
package ru.job4j; import ru.job4j.common.NamedArgs; import java.io.IOException; import java.util.Collection; public interface Search<T> { Collection<T> findFiles(final NamedArgs params) throws IOException; }
16.692308
71
0.774194
4cf5e8e788136b93d386340c28589125a2b39ac6
3,136
/* Copyright 2017 Ping Identity Corporation 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.pingidentity.labs.rapport.spi; import java.util.List; import javax.json.JsonArray; import javax.json.JsonValue; import com.pingidentity.labs.rapport.Application; import com.pingidentity.labs.rapport.Coordinator; import com.pingidentity.labs.rapport.Peer; import com.pingidentity.labs.rapport.StateManager; /** * Service Provider interface to handle Application initialization based on a provided implementation of this API. * Separates starting of the state manager and interactor for environments where headless operation is appropriate. * * An ApplicationFactory instance can be registered by adding a service descriptor to the JAR package - in * `META-INF/services/com.pingidentity.labs.rapport.spi.ApplicationFactory` * * @param <S> Java type of the state object being maintained by the {@link StateManager} of the application. * @param <T> Java type of the transactional message (or root type of several different messages) to be sent * by your backend {@link Coordinator} and parsed/received by the {@link StateManager} */ public interface ApplicationFactory<S,T> { /** * Create a new ApplicationFactory around an application implementation instance, a list of peer addresses, * and the system constitution. * * @param application class of application to initialize * @param peers list of peers * @param localConfiguration local configuration of this peer * @param constitution initial configuration of the distributed system * @return Initializer object which can start the state manager and application */ public Initializer newInstance( @SuppressWarnings("rawtypes") Class<? extends Application> application, List<? extends Peer> peers, JsonValue localConfiguration, JsonValue constitution); /** * Parse a JSON array into a list of peers within the system. The format of the peers is mostly * determined by the backend, although the file format description gives details on expected/required * keys. * * @param array JSON array of peers * @return list of peer objects */ public List<? extends Peer> parseJsonPeers(JsonArray array); /** * Initializer object, returned by the backend, to allow java code to control the initialization * of the state manager and interactor instances. */ public interface Initializer { /** Start state manager. State manager must be started before Interactor */ public void startStateManager(); /** Start user/system interaction process. State manager must be started before Interactor */ public void startInteractor(); } }
42.378378
115
0.772321
ea24a9c7119781fea910416707939d77d395a517
98
package ca.rcherara.services.vehicle.model; public enum Model{ SEDAN, SUV, SPORTS, MINIVAN; }
19.6
43
0.744898
ae958f1d55d40ccf3a427d74dd98be6756eee6d9
2,828
package dao.entities; import java.io.Serializable; import java.util.Date; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.Temporal; @Entity public class Chimiotherapie implements Serializable { /** * */ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id_Chim; @Enumerated(EnumType.STRING) private Deroulement deroulement; @Temporal(javax.persistence.TemporalType.DATE) private Date debut; @Temporal(javax.persistence.TemporalType.DATE) private Date fin; @OneToOne(mappedBy="chimiotherapie") private Traitement traitement; public Chimiotherapie() { super(); } public Chimiotherapie(Deroulement deroulement, Date debut, Date fin) { super(); this.deroulement = deroulement; this.debut = debut; this.fin = fin; } public int getId() { return id_Chim; } public void setId(int id) { this.id_Chim = id; } public Deroulement getDeroulement() { return deroulement; } public void setDeroulement(Deroulement deroulement) { this.deroulement = deroulement; } public Date getDebut() { return debut; } public void setDebut(Date debut) { this.debut = debut; } public Date getFin() { return fin; } public void setFin(Date fin) { this.fin = fin; } public Traitement getTraitement() { return traitement; } public void setTraitement(Traitement traitement) { this.traitement = traitement; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((debut == null) ? 0 : debut.hashCode()); result = prime * result + ((deroulement == null) ? 0 : deroulement.hashCode()); result = prime * result + ((fin == null) ? 0 : fin.hashCode()); result = prime * result + id_Chim; result = prime * result + ((traitement == null) ? 0 : traitement.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Chimiotherapie other = (Chimiotherapie) obj; if (debut == null) { if (other.debut != null) return false; } else if (!debut.equals(other.debut)) return false; if (deroulement != other.deroulement) return false; if (fin == null) { if (other.fin != null) return false; } else if (!fin.equals(other.fin)) return false; if (id_Chim != other.id_Chim) return false; if (traitement == null) { if (other.traitement != null) return false; } else if (!traitement.equals(other.traitement)) return false; return true; } }
23.566667
81
0.694837
a902b37a7788e30af25f873e0ba748ed1666a230
3,546
/* * Mastercard Loyalty Connect Service * Connecting payment and retail loyalty into a single checkout experience * * The version of the OpenAPI document: 2.2.1 * Contact: [email protected] * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.mastercard.developer.mastercard_loyalty_connect_client.model; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.mastercard.developer.mastercard_loyalty_connect_client.model.Address; import com.mastercard.developer.mastercard_loyalty_connect_client.model.Business; import com.mastercard.developer.mastercard_loyalty_connect_client.model.Meta; import com.mastercard.developer.mastercard_loyalty_connect_client.model.Telephone; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; /** * Model tests for Store */ public class StoreTest { private final Store model = new Store(); /** * Model tests for Store */ @Test public void testStore() { // TODO: test Store } /** * Test the property 'utcOffset' */ @Test public void utcOffsetTest() { // TODO: test utcOffset } /** * Test the property 'name' */ @Test public void nameTest() { // TODO: test name } /** * Test the property 'shortName' */ @Test public void shortNameTest() { // TODO: test shortName } /** * Test the property 'title' */ @Test public void titleTest() { // TODO: test title } /** * Test the property 'locale' */ @Test public void localeTest() { // TODO: test locale } /** * Test the property 'country' */ @Test public void countryTest() { // TODO: test country } /** * Test the property 'timeZone' */ @Test public void timeZoneTest() { // TODO: test timeZone } /** * Test the property 'telephone' */ @Test public void telephoneTest() { // TODO: test telephone } /** * Test the property 'business' */ @Test public void businessTest() { // TODO: test business } /** * Test the property 'emailAddress' */ @Test public void emailAddressTest() { // TODO: test emailAddress } /** * Test the property 'tags' */ @Test public void tagsTest() { // TODO: test tags } /** * Test the property 'meta' */ @Test public void metaTest() { // TODO: test meta } /** * Test the property 'key' */ @Test public void keyTest() { // TODO: test key } /** * Test the property 'address' */ @Test public void addressTest() { // TODO: test address } /** * Test the property 'taxNumber' */ @Test public void taxNumberTest() { // TODO: test taxNumber } /** * Test the property 'externalId' */ @Test public void externalIdTest() { // TODO: test externalId } }
19.921348
92
0.603215
a3be5eaad9790d92ca1fd8a87901d6950480c5d2
4,443
/* * _______ _____ _____ _____ * |__ __| | __ \ / ____| __ \ * | | __ _ _ __ ___ ___ ___| | | | (___ | |__) | * | |/ _` | '__/ __|/ _ \/ __| | | |\___ \| ___/ * | | (_| | | \__ \ (_) \__ \ |__| |____) | | * |_|\__,_|_| |___/\___/|___/_____/|_____/|_| * * ------------------------------------------------------------- * * TarsosDSP is developed by Joren Six at IPEM, University Ghent * * ------------------------------------------------------------- * * Info: http://0110.be/tag/TarsosDSP * Github: https://github.com/JorenSix/TarsosDSP * Releases: http://0110.be/releases/TarsosDSP/ * * TarsosDSP includes modified source code by various authors, * for credits and info, see README. * */ /* * Copyright (c) 2007 - 2008 by Damien Di Fede <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library 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 Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package be.tarsos.dsp.util.fft; /** * A Window function represents a curve which is applied to a sample buffer to * reduce the introduction of spectral leakage in the Fourier transform. * * <p> * <b>Windowing</b> * <p> * Windowing is the process of shaping the audio samples before transforming * them to the frequency domain. The Fourier Transform assumes the sample buffer * is is a repetitive signal, if a sample buffer is not truly periodic within * the measured interval sharp discontinuities may arise that can introduce * spectral leakage. Spectral leakage is the speading of signal energy across * multiple FFT bins. This "spreading" can drown out narrow band signals and * hinder detection. * <p> * A <a href="http://en.wikipedia.org/wiki/Window_function">windowing * function</a> attempts to reduce spectral leakage by attenuating the measured * sample buffer at its end points to eliminate discontinuities. If you call the * <code>window()</code> function with an appropriate WindowFunction, such as * <code>HammingWindow()</code>, the sample buffers passed to the object for * analysis will be shaped by the current window before being transformed. The * result of using a window is to reduce the leakage in the spectrum somewhat. * <p> * <code>WindowFunction</code> handles work associated with various window * functions such as the Hamming window. To create your own window function you * must extend <code>WindowFunction</code> and implement the * {@link #value(int, int) value} method which defines the shape of the window * at a given offset. <code>WindowFunction</code> will call this method to apply * the window to a sample buffer. The number passed to the method is an offset * within the length of the window curve. * * @author Damien Di Fede * @author Corban Brook * */ public abstract class WindowFunction { /** The float value of 2*PI. Provided as a convenience for subclasses. */ protected static final float TWO_PI = (float) (2 * Math.PI); protected int length; public WindowFunction() { } /** * Apply the window function to a sample buffer. * * @param samples * a sample buffer */ public void apply(float[] samples) { this.length = samples.length; for (int n = 0; n < samples.length; n++) { samples[n] *= value(samples.length, n); } } /** * Generates the curve of the window function. * * @param length * the length of the window * @return the shape of the window function */ public float[] generateCurve(int length) { float[] samples = new float[length]; for (int n = 0; n < length; n++) { samples[n] = 1f * value(length, n); } return samples; } protected abstract float value(int length, int index); }
37.336134
80
0.651587
33093d4aff4e298d6dc1e61d3d8b88fa66a800ae
352
/* * Copyright (c) 2018 Practice Insight Pty Ltd. All Rights Reserved. */ package io.wisetime.connector.template; /** * @author [email protected] */ public class TemplateProcessingException extends RuntimeException { public TemplateProcessingException(final String message, final Throwable cause) { super(message, cause); } }
22
83
0.752841
2e55e53496110021dc495be715deb9e918a47616
6,268
/* * The MIT License (MIT) * <p/> * Copyright (c) 2016-2017 Bertrand Martel * <p/> * 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: * <p/> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p/> * 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 fr.bmartel.speedtest.examples; import fr.bmartel.speedtest.SpeedTestReport; import fr.bmartel.speedtest.model.SpeedTestMode; import org.apache.logging.log4j.Logger; import java.math.BigDecimal; import java.math.RoundingMode; /** * Log utilities method for examples. * * @author Bertrand Martel */ public class LogUtils { /** * default scale for BigDecimal. */ private static final int DEFAULT_SCALE = 4; /** * default rounding mode for BigDecimal. */ private static final RoundingMode DEFAULT_ROUNDING_MODE = RoundingMode.HALF_EVEN; /** * conversion const for per second value. */ private static final BigDecimal VALUE_PER_SECONDS = new BigDecimal(1000); /** * conversion const for M per second value. */ private static final BigDecimal MEGA_VALUE_PER_SECONDS = new BigDecimal(1000000); /** * log report separator. */ public static final String LOG_REPORT_SEPARATOR = "--------------------------------------------------------"; /** * print speed examples report object. * * @param report speed examples report to log * @param logger log4j logger */ public static void logSpeedTestReport(final SpeedTestReport report, final Logger logger) { if (logger.isDebugEnabled()) { switch (report.getSpeedTestMode()) { case DOWNLOAD: logger.debug("--------------current download report--------------------"); break; case UPLOAD: logger.debug("---------------current upload report--------------------"); break; default: break; } logReport(report, logger); } } /** * print upload/download result. * * @param mode speed examples mode * @param packetSize packet size received * @param transferRateBitPerSeconds transfer rate in bps * @param transferRateOctetPerSeconds transfer rate in Bps * @param logger log4j logger */ public static void logFinishedTask(final SpeedTestMode mode, final long packetSize, final BigDecimal transferRateBitPerSeconds, final BigDecimal transferRateOctetPerSeconds, final Logger logger) { if (logger.isDebugEnabled()) { switch (mode) { case DOWNLOAD: logger.debug("======== Download [ OK ] ============="); break; case UPLOAD: logger.debug("========= Upload [ OK ] ============="); break; default: break; } logger.debug("packetSize : " + packetSize + " octet(s)"); logger.debug("transfer rate : " + transferRateBitPerSeconds + " bit/second | " + transferRateBitPerSeconds.divide(VALUE_PER_SECONDS, DEFAULT_SCALE, DEFAULT_ROUNDING_MODE) + " Kbit/second | " + transferRateBitPerSeconds.divide(MEGA_VALUE_PER_SECONDS) + " Mbit/second"); logger.debug("transfer rate : " + transferRateOctetPerSeconds + " octet/second | " + transferRateOctetPerSeconds.divide(VALUE_PER_SECONDS, DEFAULT_SCALE, DEFAULT_ROUNDING_MODE) + " Koctet/second | " + transferRateOctetPerSeconds.divide(MEGA_VALUE_PER_SECONDS, DEFAULT_SCALE, DEFAULT_ROUNDING_MODE) + " " + "Moctet/second"); logger.debug("##################################################################"); } } /** * Print log report from speed test report object. * * @param report speed test report instance * @param logger log4j logger */ public static void logReport(final SpeedTestReport report, final Logger logger) { if (logger.isDebugEnabled()) { logger.debug("progress : " + report.getProgressPercent() + "%"); logger.debug("transfer rate bit : " + report.getTransferRateBit() + "b/s"); logger.debug("transfer rate octet : " + report.getTransferRateOctet() + "B/s"); switch (report.getSpeedTestMode()) { case DOWNLOAD: logger.debug("downloaded for now : " + report.getTemporaryPacketSize() + "/" + report.getTotalPacketSize()); break; case UPLOAD: logger.debug("uploaded for now : " + report.getTemporaryPacketSize() + "/" + report.getTotalPacketSize()); break; default: break; } if (report.getStartTime() > 0) { logger.debug("amount of time : " + ((report.getReportTime() - report.getStartTime()) / 1000000000) + "s"); } logger.debug(LOG_REPORT_SEPARATOR); } } }
38.931677
118
0.574346
c88145432a06ffd1e5c6dffb6a3d4383d017efa3
592
package ch.imetrica.mdfa.series; import lombok.Data; import lombok.Getter; import lombok.ToString; /** * The time series entry with generic value V and * a string as the timeStamp which is typically in the form * of a standard DataTimeFormatter, for example * "yyyy-MM-dd HH:mm:ss" * "dd-MM-yyyy" * * @author Christian D. Blakely ([email protected]) * * @param <V> */ @Data @ToString(includeFieldNames=false) public class TimeSeriesEntry<V> { @Getter private final String timeStamp; @Getter private final V value; public String getDateTime() { return timeStamp; } }
19.733333
59
0.721284
758f94200878b1ddd860eb9d7102c3ac55a9350b
311
import java.util.function.UnaryOperator; public class Recursion { public static final UnaryOperator<Integer> count = x -> x == 0 ? 0 : x + Recursion.count.apply(x - 1); public static void main(String[] args) { for (int i = 0;; i++) { System.out.println(i + ": " + count.apply(i)); } } }
20.733333
52
0.610932
7a87d346d28dbdada704ee3083aed8a90a656b7c
65
// Printer Methods static void pn(Object o) { out.print(o); }
16.25
26
0.646154
a90ef7fc38fc2e715c426ccdb54a8fbb72dd1294
414
package davenkin; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; /** * Created by yteng on 4/3/17. */ @SpringBootApplication @EnableCaching public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
21.789474
68
0.772947
e4e605b940797da655df40f5a3d48ec1ec4fefc4
1,971
package com.liang.leetcode.daily.history; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * 三数之和 * * @author LiaNg * @date 2020/6/12 10:33 */ public class L15 { public static void main(String[] args) { L15 l15 = new L15(); int[] nums = new int[]{-2, 0, 1, 1, 2}; System.out.println("l15.threeSum(nums) = " + l15.threeSum(nums)); } /** * 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。 * 注意:答案中不可以包含重复的三元组。 *   * 示例: * 给定数组 nums = [-1, 0, 1, 2, -1, -4], * 满足要求的三元组集合为: * [ * [-1, 0, 1], * [-1, -1, 2] * ] * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/3sum * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ public List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); List<List<Integer>> res = new ArrayList<>(); for (int i = 0; i < nums.length; i++) { if (i > 0 && nums[i] == nums[i - 1]) { continue; } int target = -nums[i]; int j = i + 1; int k = nums.length - 1; while (j < k) { if (nums[j] + nums[k] == target) { List<Integer> currentList = new ArrayList<>(); currentList.add(nums[i]); currentList.add(nums[j]); currentList.add(nums[k]); res.add(currentList); j++; k--; while (j < k && nums[j] == nums[j - 1]) { j++; } while (k > j && nums[k] == nums[k + 1]) { k--; } } else if (nums[j] + nums[k] > target) { k--; } else { j++; } } } return res; } }
25.269231
90
0.404363