hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
923eb14c6e37095ea523aa4f17dff610ffd2dfab
1,225
java
Java
model-caaa-types/src/generated/java/com/prowidesoftware/swift/model/mx/dic/Response1Code.java
luongnvUIT/prowide-iso20022
59210a4b67cd38759df2d0dd82ad19acf93ffe75
[ "Apache-2.0" ]
40
2020-10-13T13:44:59.000Z
2022-03-30T13:58:32.000Z
model-caaa-types/src/generated/java/com/prowidesoftware/swift/model/mx/dic/Response1Code.java
luongnvUIT/prowide-iso20022
59210a4b67cd38759df2d0dd82ad19acf93ffe75
[ "Apache-2.0" ]
25
2020-10-04T23:46:22.000Z
2022-03-30T12:31:03.000Z
model-caaa-types/src/generated/java/com/prowidesoftware/swift/model/mx/dic/Response1Code.java
luongnvUIT/prowide-iso20022
59210a4b67cd38759df2d0dd82ad19acf93ffe75
[ "Apache-2.0" ]
22
2020-12-22T14:50:22.000Z
2022-03-30T13:19:10.000Z
19.444444
108
0.606531
1,000,871
package com.prowidesoftware.swift.model.mx.dic; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for Response1Code. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="Response1Code"&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&gt; * &lt;enumeration value="DECL"/&gt; * &lt;enumeration value="APPR"/&gt; * &lt;enumeration value="PART"/&gt; * &lt;enumeration value="TECH"/&gt; * &lt;/restriction&gt; * &lt;/simpleType&gt; * </pre> * */ @XmlType(name = "Response1Code") @XmlEnum public enum Response1Code { /** * Service is declined. * */ DECL, /** * Service has been successfuly provided. * */ APPR, /** * Service has been partialy provided. * */ PART, /** * Service cannot be provided for technical reason (eg timeout contacting the Issuer, security problem). * */ TECH; public String value() { return name(); } public static Response1Code fromValue(String v) { return valueOf(v); } }
923eb19d3bc1ea259bd0aff4c856b52404ce6df8
5,152
java
Java
src/com/android/launcher3/views/SpringRelativeLayout.java
infectedmushi/lawnchair
5767b6ccd281d97da13d9b63d7c933610be8c0f8
[ "Apache-2.0" ]
1,546
2021-03-29T12:10:05.000Z
2022-03-31T19:36:10.000Z
src/com/android/launcher3/views/SpringRelativeLayout.java
infectedmushi/lawnchair
5767b6ccd281d97da13d9b63d7c933610be8c0f8
[ "Apache-2.0" ]
522
2021-03-29T14:20:34.000Z
2022-03-31T21:27:45.000Z
src/com/android/launcher3/views/SpringRelativeLayout.java
infectedmushi/lawnchair
5767b6ccd281d97da13d9b63d7c933610be8c0f8
[ "Apache-2.0" ]
210
2021-03-30T04:13:04.000Z
2022-03-31T17:14:03.000Z
30.485207
88
0.636258
1,000,872
/* * Copyright (C) 2018 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 com.android.launcher3.views; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.widget.EdgeEffect; import android.widget.RelativeLayout; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView.EdgeEffectFactory; import com.android.launcher3.Utilities; /** * View group to allow rendering overscroll effect in a child at the parent level */ public class SpringRelativeLayout extends RelativeLayout { // fixed edge at the time force is applied private final EdgeEffect mEdgeGlowTop; private final EdgeEffect mEdgeGlowBottom; public SpringRelativeLayout(Context context) { this(context, null); } public SpringRelativeLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public SpringRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mEdgeGlowTop = Utilities.ATLEAST_S ? new EdgeEffect(context, attrs) : new EdgeEffect(context); mEdgeGlowBottom = Utilities.ATLEAST_S ? new EdgeEffect(context, attrs) : new EdgeEffect(context); setWillNotDraw(false); } @Override public void draw(Canvas canvas) { super.draw(canvas); if (!mEdgeGlowTop.isFinished()) { final int restoreCount = canvas.save(); canvas.translate(0, 0); mEdgeGlowTop.setSize(getWidth(), getHeight()); if (mEdgeGlowTop.draw(canvas)) { postInvalidateOnAnimation(); } canvas.restoreToCount(restoreCount); } if (!mEdgeGlowBottom.isFinished()) { final int restoreCount = canvas.save(); final int width = getWidth(); final int height = getHeight(); canvas.translate(-width, height); canvas.rotate(180, width, 0); mEdgeGlowBottom.setSize(width, height); if (mEdgeGlowBottom.draw(canvas)) { postInvalidateOnAnimation(); } canvas.restoreToCount(restoreCount); } } /** * Absorbs the velocity as a result for swipe-up fling */ protected void absorbSwipeUpVelocity(int velocity) { mEdgeGlowBottom.onAbsorb(velocity); invalidate(); } protected void absorbPullDeltaDistance(float deltaDistance, float displacement) { mEdgeGlowBottom.onPull(deltaDistance, displacement); invalidate(); } public void onRelease() { mEdgeGlowBottom.onRelease(); } public EdgeEffectFactory createEdgeEffectFactory() { return new ProxyEdgeEffectFactory(); } private class ProxyEdgeEffectFactory extends EdgeEffectFactory { @NonNull @Override protected EdgeEffect createEdgeEffect(RecyclerView view, int direction) { if (direction == DIRECTION_TOP) { return new EdgeEffectProxy(getContext(), mEdgeGlowTop); } return super.createEdgeEffect(view, direction); } } private class EdgeEffectProxy extends EdgeEffect { private final EdgeEffect mParent; EdgeEffectProxy(Context context, EdgeEffect parent) { super(context); mParent = parent; } @Override public boolean draw(Canvas canvas) { return false; } private void invalidateParentScrollEffect() { if (!mParent.isFinished()) { invalidate(); } } @Override public void onAbsorb(int velocity) { mParent.onAbsorb(velocity); invalidateParentScrollEffect(); } @Override public void onPull(float deltaDistance) { mParent.onPull(deltaDistance); invalidateParentScrollEffect(); } @Override public void onPull(float deltaDistance, float displacement) { mParent.onPull(deltaDistance, displacement); invalidateParentScrollEffect(); } @Override public void onRelease() { mParent.onRelease(); invalidateParentScrollEffect(); } @Override public void finish() { mParent.finish(); } @Override public boolean isFinished() { return mParent.isFinished(); } } }
923eb2fc7f9ef5083e0e1ae11760c64f873b35dc
1,428
java
Java
src/main/java/yaboichips/usefulvanilla/common/blocks/mason/MasonOven.java
YaBoiChips/usefulvanilla
c66ffb31cf7c092142a127c5cb6a1b8c8f30b6dc
[ "MIT" ]
null
null
null
src/main/java/yaboichips/usefulvanilla/common/blocks/mason/MasonOven.java
YaBoiChips/usefulvanilla
c66ffb31cf7c092142a127c5cb6a1b8c8f30b6dc
[ "MIT" ]
null
null
null
src/main/java/yaboichips/usefulvanilla/common/blocks/mason/MasonOven.java
YaBoiChips/usefulvanilla
c66ffb31cf7c092142a127c5cb6a1b8c8f30b6dc
[ "MIT" ]
null
null
null
36.615385
123
0.764706
1,000,873
package yaboichips.usefulvanilla.common.blocks.mason; import net.minecraft.core.BlockPos; import net.minecraft.world.MenuProvider; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.AbstractFurnaceBlock; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.Nullable; import yaboichips.usefulvanilla.core.UVTileEntities; public class MasonOven extends AbstractFurnaceBlock { public MasonOven(Properties properties) { super(properties); } @Override protected void openContainer(Level world, BlockPos pos, Player player) { BlockEntity blockentity = world.getBlockEntity(pos); if (blockentity instanceof MasonOvenTE) { player.openMenu((MenuProvider)blockentity); } } @Nullable @Override public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { return new MasonOvenTE(pos, state); } @javax.annotation.Nullable public <T extends BlockEntity> BlockEntityTicker<T> getTicker(Level level, BlockState state, BlockEntityType<T> type) { return createFurnaceTicker(level, type, UVTileEntities.MASON_OVEN.get()); } }
923eb3c75d3b53c7cf1ba2d149e132bb8c4c3277
707
java
Java
olie-treasure/idea-learn/src/main/java/olie/_ReArrangeCode.java
olie-niexianglin/happiness
7d92c6f0deb391a793e1498a73e016188bdc8e1e
[ "MIT" ]
null
null
null
olie-treasure/idea-learn/src/main/java/olie/_ReArrangeCode.java
olie-niexianglin/happiness
7d92c6f0deb391a793e1498a73e016188bdc8e1e
[ "MIT" ]
null
null
null
olie-treasure/idea-learn/src/main/java/olie/_ReArrangeCode.java
olie-niexianglin/happiness
7d92c6f0deb391a793e1498a73e016188bdc8e1e
[ "MIT" ]
null
null
null
17.65
80
0.610482
1,000,874
package olie; /** * @Auther: niexianglin you can mail to [email protected] * @Date: 2018/7/20 14:08 * @Description: */ public class _ReArrangeCode { /** * RearrangeCode : 重新排列代码,类似 reformat ,例如正常情况下,字段的定义应该放在方法定义的前面 * 但是有时候,你不小心把位置搞反了,那么就需要 RearrangeCode 命令来帮你完成代码重排,重排的规则可以 * 在 Setting 中的 Eidtor 进行设置。 */ /** * 操作路径:code -> rearrangeCode */ /** * 最佳实践:Ctrl + Shift + Alt + L:打开文件格式化面板选项,在 Option 选项中选择 Optimize imports 和 * Rearrange Code 选项,这样在执行格式化代码时就会捎带着完成了 import 格式化 和 代码重排操作。 */ /** * 感受:使用价值不错,有趣价值还行 */ public static void sayHello() { //do noting } private String content = "Hello World"; }
923eb3c886c29d2d1d03604ef596e4e65afcef7f
670
java
Java
java_backup/my java/police bhai/assignment/pascal_triangle.java
SayanGhoshBDA/code-backup
8b6135facc0e598e9686b2e8eb2d69dd68198b80
[ "MIT" ]
16
2018-11-26T08:39:42.000Z
2019-05-08T10:09:52.000Z
java_backup/my java/police bhai/assignment/pascal_triangle.java
SayanGhoshBDA/code-backup
8b6135facc0e598e9686b2e8eb2d69dd68198b80
[ "MIT" ]
8
2020-05-04T06:29:26.000Z
2022-02-12T05:33:16.000Z
java_backup/my java/police bhai/assignment/pascal_triangle.java
SayanGhoshBDA/code-backup
8b6135facc0e598e9686b2e8eb2d69dd68198b80
[ "MIT" ]
5
2020-02-11T16:02:21.000Z
2021-02-05T07:48:30.000Z
23.103448
76
0.443284
1,000,875
package assignment; import java.io.*; class pascal_triangle { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int i,j,k,s,n; public void input()throws IOException { System.out.println("enter the number"); n=Integer.parseInt(br.readLine()); } public void pascal() { for(i=1;i<=n;i++) { for(j=1;j<=i;j++) { System.out.print(+j); } if(i>=2) { for(k=j-2;k>=1;k--) System.out.print(+k); } System.out.println(""); } } }
923eb4655e4e5e3e17294452f6eaf81081d905ef
327
java
Java
src/main/java/io/notifye/botengine/model/Image.java
notifye/botengine-ai
c61fc3c0e6118a7fcc64c481bc548fd12d699c99
[ "MIT" ]
4
2017-07-21T00:47:01.000Z
2017-07-28T06:28:54.000Z
src/main/java/io/notifye/botengine/model/Image.java
notifye/botengine-ai-client
c61fc3c0e6118a7fcc64c481bc548fd12d699c99
[ "MIT" ]
1
2020-01-27T13:49:17.000Z
2020-01-27T13:49:17.000Z
src/main/java/io/notifye/botengine/model/Image.java
notifye/botengine-ai-client
c61fc3c0e6118a7fcc64c481bc548fd12d699c99
[ "MIT" ]
1
2017-09-07T06:19:04.000Z
2017-09-07T06:19:04.000Z
20.4375
50
0.801223
1,000,876
package io.notifye.botengine.model; import java.io.Serializable; import io.notifye.botengine.model.enums.ImageType; import lombok.Builder; import lombok.Data; @Builder public @Data class Image implements Serializable { private static final long serialVersionUID = 1L; private ImageType type; private String imageUrl; }
923eb5ccd0e95fd18d40b25eac9fd6142e0585b4
681
java
Java
TimoCloud-Universal/src/main/java/cloud/timo/TimoCloud/core/utils/completers/BaseNameCompleter.java
TimoCrafter/TimoCloud
d8c285068fb07c5258ecd9ccad2652f8623fc1dc
[ "BSD-3-Clause" ]
123
2018-02-24T17:41:31.000Z
2022-03-13T18:54:43.000Z
TimoCloud-Universal/src/main/java/cloud/timo/TimoCloud/core/utils/completers/BaseNameCompleter.java
TimoCrafter/TimoCloud
d8c285068fb07c5258ecd9ccad2652f8623fc1dc
[ "BSD-3-Clause" ]
86
2018-02-24T16:55:29.000Z
2022-01-24T20:10:41.000Z
TimoCloud-Universal/src/main/java/cloud/timo/TimoCloud/core/utils/completers/BaseNameCompleter.java
TimoCrafter/TimoCloud
d8c285068fb07c5258ecd9ccad2652f8623fc1dc
[ "BSD-3-Clause" ]
73
2018-02-24T17:05:06.000Z
2022-02-25T19:37:49.000Z
35.842105
158
0.790015
1,000,877
package cloud.timo.TimoCloud.core.utils.completers; import cloud.timo.TimoCloud.core.TimoCloudCore; import cloud.timo.TimoCloud.core.objects.Base; import org.jline.reader.Candidate; import org.jline.reader.Completer; import org.jline.reader.LineReader; import org.jline.reader.ParsedLine; import java.util.List; import java.util.stream.Collectors; public class BaseNameCompleter implements Completer { @Override public void complete(LineReader lineReader, ParsedLine parsedLine, List<Candidate> list) { list.addAll(TimoCloudCore.getInstance().getInstanceManager().getBases().stream().map(Base::getName).map(Candidate::new).collect(Collectors.toList())); } }
923eb6b3156ba1e4608817c71e737ee147e46656
705
java
Java
example/android/app/src/main/java/com/example/hello_plugin_package_example/FlutterTextViewFactory.java
yinghuihong/hello_plugin_package
ec32a2d1ec0f0f54e804a3eec541e48f3a6ee125
[ "MIT" ]
null
null
null
example/android/app/src/main/java/com/example/hello_plugin_package_example/FlutterTextViewFactory.java
yinghuihong/hello_plugin_package
ec32a2d1ec0f0f54e804a3eec541e48f3a6ee125
[ "MIT" ]
null
null
null
example/android/app/src/main/java/com/example/hello_plugin_package_example/FlutterTextViewFactory.java
yinghuihong/hello_plugin_package
ec32a2d1ec0f0f54e804a3eec541e48f3a6ee125
[ "MIT" ]
null
null
null
30.652174
67
0.782979
1,000,878
package com.example.hello_plugin_package_example; import android.content.Context; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.StandardMessageCodec; import io.flutter.plugin.platform.PlatformView; import io.flutter.plugin.platform.PlatformViewFactory; public class FlutterTextViewFactory extends PlatformViewFactory { private final BinaryMessenger messenger; public FlutterTextViewFactory(BinaryMessenger messenger) { super(StandardMessageCodec.INSTANCE); this.messenger = messenger; } @Override public PlatformView create(Context context, int id, Object o) { return new FlutterTextView(context, messenger, id); } }
923eb76624ce94d5a135c9a475070e3f0a210190
1,035
java
Java
test/saml-test/src/main/java/stubidp/saml/test/builders/IssuerBuilder.java
stub-idp/verify-stub-idp
9840e62ad0deb9376af94462cbfa44ae58490566
[ "MIT" ]
null
null
null
test/saml-test/src/main/java/stubidp/saml/test/builders/IssuerBuilder.java
stub-idp/verify-stub-idp
9840e62ad0deb9376af94462cbfa44ae58490566
[ "MIT" ]
205
2019-03-24T23:10:11.000Z
2022-03-31T18:05:33.000Z
test/saml-test/src/main/java/stubidp/saml/test/builders/IssuerBuilder.java
stub-idp/verify-stub-idp
9840e62ad0deb9376af94462cbfa44ae58490566
[ "MIT" ]
null
null
null
28.75
108
0.72657
1,000,879
package stubidp.saml.test.builders; import org.opensaml.saml.saml2.core.Issuer; import stubidp.saml.test.OpenSamlXmlObjectFactory; import stubidp.test.devpki.TestCertificateStrings; import java.util.Optional; public class IssuerBuilder { private static final OpenSamlXmlObjectFactory openSamlXmlObjectFactory = new OpenSamlXmlObjectFactory(); private Optional<String> issuerId = Optional.ofNullable(TestCertificateStrings.TEST_ENTITY_ID); private String format = null; private IssuerBuilder() {} public static IssuerBuilder anIssuer() { return new IssuerBuilder(); } public Issuer build() { Issuer issuer = openSamlXmlObjectFactory.createIssuer(issuerId.orElse(null)); issuer.setFormat(format); return issuer; } public IssuerBuilder withIssuerId(String issuerId) { this.issuerId = Optional.ofNullable(issuerId); return this; } public IssuerBuilder withFormat(String format) { this.format = format; return this; } }
923eb851ff1a2806f77f72106170fcbc73b3fd26
175
java
Java
src/com/qt/Test.java
quietUncle/vartrans
198adb96b17633a71dbd49093ba6104bac7c3a02
[ "Apache-2.0" ]
8
2017-10-25T04:01:51.000Z
2022-02-09T08:56:01.000Z
src/com/qt/Test.java
quietUncle/vartrans
198adb96b17633a71dbd49093ba6104bac7c3a02
[ "Apache-2.0" ]
null
null
null
src/com/qt/Test.java
quietUncle/vartrans
198adb96b17633a71dbd49093ba6104bac7c3a02
[ "Apache-2.0" ]
null
null
null
15.909091
42
0.651429
1,000,880
package com.qt; public class Test { // private String HelloWorld; //中文转大驼峰 private String helloWorld; //中文转小驼峰 private String HELLO_WORLD; //中文转常量 }
923eb85b207fd01a3a5ad452ba15d3152f5faade
4,142
java
Java
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/stream/DataStream.java
Czxck001/ray
c2cbb85a43776b9624119476dec04f4823505445
[ "Apache-2.0" ]
4
2019-10-18T17:44:58.000Z
2021-04-14T14:37:21.000Z
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/stream/DataStream.java
doc22940/ray
c2cbb85a43776b9624119476dec04f4823505445
[ "Apache-2.0" ]
1
2022-03-30T17:52:44.000Z
2022-03-30T17:52:44.000Z
streaming/java/streaming-api/src/main/java/org/ray/streaming/api/stream/DataStream.java
doc22940/ray
c2cbb85a43776b9624119476dec04f4823505445
[ "Apache-2.0" ]
1
2020-06-26T07:54:25.000Z
2020-06-26T07:54:25.000Z
28.965035
87
0.704249
1,000,881
package org.ray.streaming.api.stream; import org.ray.streaming.api.context.StreamingContext; import org.ray.streaming.api.function.impl.FilterFunction; import org.ray.streaming.api.function.impl.FlatMapFunction; import org.ray.streaming.api.function.impl.KeyFunction; import org.ray.streaming.api.function.impl.MapFunction; import org.ray.streaming.api.function.impl.SinkFunction; import org.ray.streaming.api.partition.Partition; import org.ray.streaming.api.partition.impl.BroadcastPartition; import org.ray.streaming.operator.StreamOperator; import org.ray.streaming.operator.impl.FilterOperator; import org.ray.streaming.operator.impl.FlatMapOperator; import org.ray.streaming.operator.impl.KeyByOperator; import org.ray.streaming.operator.impl.MapOperator; import org.ray.streaming.operator.impl.SinkOperator; /** * Represents a stream of data. * * This class defines all the streaming operations. * * @param <T> Type of data in the stream. */ public class DataStream<T> extends Stream<T> { public DataStream(StreamingContext streamingContext, StreamOperator streamOperator) { super(streamingContext, streamOperator); } public DataStream(DataStream input, StreamOperator streamOperator) { super(input, streamOperator); } /** * Apply a map function to this stream. * * @param mapFunction The map function. * @param <R> Type of data returned by the map function. * @return A new DataStream. */ public <R> DataStream<R> map(MapFunction<T, R> mapFunction) { return new DataStream<>(this, new MapOperator(mapFunction)); } /** * Apply a flat-map function to this stream. * * @param flatMapFunction The FlatMapFunction * @param <R> Type of data returned by the flatmap function. * @return A new DataStream */ public <R> DataStream<R> flatMap(FlatMapFunction<T, R> flatMapFunction) { return new DataStream(this, new FlatMapOperator(flatMapFunction)); } public DataStream<T> filter(FilterFunction<T> filterFunction) { return new DataStream<T>(this, new FilterOperator(filterFunction)); } /** * Apply a union transformation to this stream, with another stream. * * @param other Another stream. * @return A new UnionStream. */ public UnionStream<T> union(DataStream<T> other) { return new UnionStream(this, null, other); } /** * Apply a join transformation to this stream, with another stream. * * @param other Another stream. * @param <O> The type of the other stream data. * @param <R> The type of the data in the joined stream. * @return A new JoinStream. */ public <O, R> JoinStream<T, O, R> join(DataStream<O> other) { return new JoinStream<>(this, other); } public <R> DataStream<R> process() { // TODO(zhenxuanpan): Need to add processFunction. return new DataStream(this, null); } /** * Apply a sink function and get a StreamSink. * * @param sinkFunction The sink function. * @return A new StreamSink. */ public DataStreamSink<T> sink(SinkFunction<T> sinkFunction) { return new DataStreamSink<>(this, new SinkOperator(sinkFunction)); } /** * Apply a key-by function to this stream. * * @param keyFunction the key function. * @param <K> The type of the key. * @return A new KeyDataStream. */ public <K> KeyDataStream<K, T> keyBy(KeyFunction<T, K> keyFunction) { return new KeyDataStream<>(this, new KeyByOperator(keyFunction)); } /** * Apply broadcast to this stream. * * @return This stream. */ public DataStream<T> broadcast() { this.partition = new BroadcastPartition<>(); return this; } /** * Apply a partition to this stream. * * @param partition The partitioning strategy. * @return This stream. */ public DataStream<T> partitionBy(Partition<T> partition) { this.partition = partition; return this; } /** * Set parallelism to current transformation. * * @param parallelism The parallelism to set. * @return This stream. */ public DataStream<T> setParallelism(int parallelism) { this.parallelism = parallelism; return this; } }
923eb880e6aec057306d332ca5baad8a8c37cc61
2,529
java
Java
languages/jetbrains.mps.samples.Physics/source_gen/jetbrains/mps/samples/Physics/plugin/InternalEntity.java
vaclav/Physics
2d0ac5da16b4452db5d19380fba85d58637ee0f4
[ "Apache-2.0" ]
3
2020-08-27T13:26:42.000Z
2020-11-19T02:17:59.000Z
languages/jetbrains.mps.samples.Physics/source_gen/jetbrains/mps/samples/Physics/plugin/InternalEntity.java
vaclav/Physics
2d0ac5da16b4452db5d19380fba85d58637ee0f4
[ "Apache-2.0" ]
null
null
null
languages/jetbrains.mps.samples.Physics/source_gen/jetbrains/mps/samples/Physics/plugin/InternalEntity.java
vaclav/Physics
2d0ac5da16b4452db5d19380fba85d58637ee0f4
[ "Apache-2.0" ]
1
2021-08-15T17:13:16.000Z
2021-08-15T17:13:16.000Z
40.142857
213
0.775801
1,000,882
package jetbrains.mps.samples.Physics.plugin; /*Generated by MPS */ import org.jetbrains.mps.openapi.model.SNode; import jetbrains.mps.samples.Physics.java.common.vectors.InternalVector; import jetbrains.mps.samples.Physics.java.common.vectors.VectorLike; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SLinkOperations; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations; import org.jetbrains.mps.openapi.language.SContainmentLink; import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory; import org.jetbrains.mps.openapi.language.SConcept; public abstract class InternalEntity<T extends SNode> extends InternalVector { protected T node; public InternalEntity(VectorLike position, T object) { super(position.getX(), position.getY(), position.getZ()); node = object; } public T getNode() { return node; } public InternalVector getPosition() { return this; } public SNode getVelocity() { return SLinkOperations.getTarget(SLinkOperations.getTarget(node, LINKS.velocity$2C7$), LINKS.expression$Va$7); } public abstract SNode getMass(); public static InternalEntity from(VectorLike positionComputed, SNode localized) { { final SNode world = localized; if (SNodeOperations.isInstanceOf(world, CONCEPTS.WorldInclusion$Nn)) { return new InternalWorld(positionComputed, world); } } { final SNode object = localized; if (SNodeOperations.isInstanceOf(object, CONCEPTS.ObjectDefinition$in)) { return new InternalObject(positionComputed, object); } } return null; } private static final class LINKS { /*package*/ static final SContainmentLink velocity$2C7$ = MetaAdapterFactory.getContainmentLink(0xbe81eb124eda4d0eL, 0x89be7493500ab874L, 0x3cd406ea6df3fe05L, 0x3cd406ea6df3fe07L, "velocity"); /*package*/ static final SContainmentLink expression$Va$7 = MetaAdapterFactory.getContainmentLink(0xbe81eb124eda4d0eL, 0x89be7493500ab874L, 0xb0d6374ec7f738eL, 0xb0d6374ec7f7393L, "expression"); } private static final class CONCEPTS { /*package*/ static final SConcept WorldInclusion$Nn = MetaAdapterFactory.getConcept(0xbe81eb124eda4d0eL, 0x89be7493500ab874L, 0x3cd406ea6df343a0L, "jetbrains.mps.samples.Physics.structure.WorldInclusion"); /*package*/ static final SConcept ObjectDefinition$in = MetaAdapterFactory.getConcept(0xbe81eb124eda4d0eL, 0x89be7493500ab874L, 0x6b7f605cb3278f43L, "jetbrains.mps.samples.Physics.structure.ObjectDefinition"); } }
923eb8cdd33053b44bbc58056758f2b737cf3dd0
1,116
java
Java
src/main/java/uk/ac/ebi/literature/data_citation/ena/jaxb_beans/impl/QualifiedNameTypeImpl.java
FlorianGraef/acc2jats
20a849d910f22d1efc9a702625c9a218f3c0e4fd
[ "Apache-2.0" ]
null
null
null
src/main/java/uk/ac/ebi/literature/data_citation/ena/jaxb_beans/impl/QualifiedNameTypeImpl.java
FlorianGraef/acc2jats
20a849d910f22d1efc9a702625c9a218f3c0e4fd
[ "Apache-2.0" ]
null
null
null
src/main/java/uk/ac/ebi/literature/data_citation/ena/jaxb_beans/impl/QualifiedNameTypeImpl.java
FlorianGraef/acc2jats
20a849d910f22d1efc9a702625c9a218f3c0e4fd
[ "Apache-2.0" ]
null
null
null
31
122
0.750896
1,000,883
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.10.09 at 05:04:58 PM BST // package uk.ac.ebi.literature.data_citation.ena.jaxb_beans.impl; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; import uk.ac.ebi.literature.data_citation.ena.jaxb_beans.QualifiedNameType; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "QualifiedNameType", namespace = "SRA.common") public class QualifiedNameTypeImpl extends NameTypeImpl implements QualifiedNameType { @XmlAttribute(name = "namespace", required = true) protected String namespace; public String getNamespace() { return namespace; } public void setNamespace(String value) { this.namespace = value; } }
923eb9343261022ac545ca721cfc8d54d93e96db
1,334
java
Java
src/test/java/io/liuyatao/difference/Task1.java
liuyatao/LeetCode
9a4edf31f55c98c7f02a5091afeb17c46e9a4f00
[ "Apache-2.0" ]
null
null
null
src/test/java/io/liuyatao/difference/Task1.java
liuyatao/LeetCode
9a4edf31f55c98c7f02a5091afeb17c46e9a4f00
[ "Apache-2.0" ]
null
null
null
src/test/java/io/liuyatao/difference/Task1.java
liuyatao/LeetCode
9a4edf31f55c98c7f02a5091afeb17c46e9a4f00
[ "Apache-2.0" ]
null
null
null
28.382979
69
0.475262
1,000,884
package io.liuyatao.difference; import java.util.Arrays; import org.junit.jupiter.api.Test; /** * https://leetcode-cn.com/problems/range-addition/ * * 370 区间加法 */ public class Task1 { /** * Solution */ public class Solution { public int[] update(int lenght, int[][] updates) { int[] result = new int[lenght]; int[] difference = new int[lenght]; for (int i = 0; i < updates.length; i++) { int[] tuple = updates[i]; int start = tuple[0]; int end = tuple[1]; int inc = tuple[2]; difference[start] = inc; if (end + 1 < lenght) { difference[end + 1] = difference[end + 1] - inc; } } result[0] = difference[0]; for (int j = 1; j < difference.length; j++) { result[j] = difference[j] + result[j - 1]; } System.out.println("结果是:" + Arrays.toString(result)); return result; } } @Test public void name() { Solution solution = new Solution(); int[][] updates = { { 1, 3, 2 }, { 2, 4, 3 }, { 0, 2, -2 } }; int[] result = solution.update(5, updates); System.out.println(Arrays.toString(result)); } }
923eba896ca377610ffa0bb0eb9f089e7e8c4977
3,846
java
Java
metadata-service/auth-impl/src/main/java/com/datahub/authentication/authenticator/DataHubSystemAuthenticator.java
Huyueeer/datahub
10b13337032f282eef6f15983d70021cc3168eba
[ "Apache-2.0" ]
1,603
2016-03-03T17:21:03.000Z
2020-01-22T22:12:02.000Z
metadata-service/auth-impl/src/main/java/com/datahub/authentication/authenticator/DataHubSystemAuthenticator.java
Huyueeer/datahub
10b13337032f282eef6f15983d70021cc3168eba
[ "Apache-2.0" ]
1,157
2016-03-03T19:29:22.000Z
2020-01-20T14:41:59.000Z
metadata-service/auth-impl/src/main/java/com/datahub/authentication/authenticator/DataHubSystemAuthenticator.java
Huyueeer/datahub
10b13337032f282eef6f15983d70021cc3168eba
[ "Apache-2.0" ]
570
2016-03-03T17:21:05.000Z
2020-01-21T06:54:10.000Z
46.337349
156
0.75611
1,000,885
package com.datahub.authentication.authenticator; import com.datahub.authentication.Actor; import com.datahub.authentication.ActorType; import com.datahub.authentication.Authentication; import com.datahub.authentication.AuthenticationRequest; import com.datahub.authentication.AuthenticationException; import com.datahub.authentication.Authenticator; import com.datahub.authentication.AuthenticatorContext; import javax.annotation.Nonnull; import java.util.Collections; import java.util.Map; import java.util.Objects; import javax.annotation.Nullable; import lombok.extern.slf4j.Slf4j; import static com.datahub.authentication.AuthenticationConstants.*; /** * Authenticator that verifies system internal callers, such as the metadata-service itself OR datahub-frontend, * using HTTP Basic Authentication. * * This makes use of a single "system client id" and "system shared secret" which each * component in the system is configured to provide. * * This authenticator also looks for a "delegated actor urn" which can be provided by system callers using the 'X-DataHub-Actor' * header. This indicates that the system is making a request on behalf of an end-user with the specified URN. In the future, we intend * to additionally pass the original credentials provided by the Actor along with the request, along with the Actor Type in the event that * service principals are added as a new entity type. * * This authenticator requires the following configurations: * * - systemClientId: an identifier for internal system callers, provided in the Authorization header via Basic Authentication. * - systemClientSecret: a shared secret used to authenticate internal system callers * */ @Slf4j public class DataHubSystemAuthenticator implements Authenticator { private String systemClientId; private String systemClientSecret; @Override public void init(@Nonnull final Map<String, Object> config, @Nullable final AuthenticatorContext context) { Objects.requireNonNull(config, "Config parameter cannot be null"); this.systemClientId = Objects.requireNonNull((String) config.get(SYSTEM_CLIENT_ID_CONFIG), String.format("Missing required config %s", SYSTEM_CLIENT_ID_CONFIG)); this.systemClientSecret = Objects.requireNonNull((String) config.get(SYSTEM_CLIENT_SECRET_CONFIG), String.format("Missing required config %s", SYSTEM_CLIENT_SECRET_CONFIG)); } @Override public Authentication authenticate(@Nonnull AuthenticationRequest context) throws AuthenticationException { Objects.requireNonNull(context); final String authorizationHeader = context.getRequestHeaders().get(AUTHORIZATION_HEADER_NAME); if (authorizationHeader != null) { if (authorizationHeader.startsWith("Basic ") || authorizationHeader.startsWith("basic ")) { String credentials = authorizationHeader.substring(6); String[] splitCredentials = credentials.split(":"); if (splitCredentials.length == 2 && this.systemClientId.equals(splitCredentials[0]) && this.systemClientSecret.equals(splitCredentials[1]) ) { // If this request was made internally, there may be a delegated id. return new Authentication( new Actor(ActorType.USER, this.systemClientId), // todo: replace this with service actor type once they exist. authorizationHeader, Collections.emptyMap() ); } else { throw new AuthenticationException("Provided credentials do not match known system client id & client secret. Check your configuration values..."); } } else { throw new AuthenticationException("Authorization header is missing 'Basic' prefix."); } } throw new AuthenticationException("Authorization header is missing Authorization header."); } }
923ebba525662be030118a2329cc068b60785b59
2,021
java
Java
crm_backend/src/main/java/com/dev/crm/core/facade/impl/UbigeoFacadeImpl.java
frsknalexis/spring-boot-security
c7782ed8d2a08587c0edf69d7e212554b79d28f3
[ "Apache-2.0" ]
1
2019-04-12T08:26:57.000Z
2019-04-12T08:26:57.000Z
crm_backend/src/main/java/com/dev/crm/core/facade/impl/UbigeoFacadeImpl.java
frsknalexis/crm-java
064f54855d8f6ca50ac1e1be21f545bb837c2ea9
[ "Apache-2.0" ]
null
null
null
crm_backend/src/main/java/com/dev/crm/core/facade/impl/UbigeoFacadeImpl.java
frsknalexis/crm-java
064f54855d8f6ca50ac1e1be21f545bb837c2ea9
[ "Apache-2.0" ]
null
null
null
22.707865
83
0.724394
1,000,886
package com.dev.crm.core.facade.impl; import java.util.ArrayList; import java.util.List; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import com.dev.crm.core.dto.UbigeoDTO; import com.dev.crm.core.dto.UbigeoResultViewModel; import com.dev.crm.core.facade.UbigeoFacade; import com.dev.crm.core.model.entity.Ubigeo; import com.dev.crm.core.service.UbigeoService; import com.dev.crm.core.util.GenericUtil; @Component("ubigeoFacade") public class UbigeoFacadeImpl implements UbigeoFacade { @Autowired @Qualifier("ubigeoService") private UbigeoService ubigeoService; @Autowired private ModelMapper modelMapper; @Override public List<UbigeoDTO> findAll() { List<UbigeoDTO> ubigeosDTO = new ArrayList<UbigeoDTO>(); try { List<Ubigeo> ubigeos = ubigeoService.findAll(); ubigeos.stream().forEach(u -> { ubigeosDTO.add(modelMapper.map(u, UbigeoDTO.class)); }); return ubigeosDTO; } catch(Exception e) { e.printStackTrace(); } return null; } @Override public List<UbigeoDTO> findByNombreUbigeo(String termino) { List<UbigeoDTO> ubigeosDTO = new ArrayList<UbigeoDTO>(); try { if(!(GenericUtil.isEmpty(termino))) { List<Ubigeo> ubigeos = ubigeoService.findByNombreUbigeo(termino); ubigeos.stream().forEach(u -> { ubigeosDTO.add(modelMapper.map(u, UbigeoDTO.class)); }); return ubigeosDTO; } } catch(Exception e) { e.printStackTrace(); } return null; } @Override public List<UbigeoResultViewModel> listarUbigeo() { List<UbigeoResultViewModel> listaUbigeo = new ArrayList<UbigeoResultViewModel>(); try { listaUbigeo = ubigeoService.listarUbigeo(); if(GenericUtil.isCollectionEmpty(listaUbigeo)) { return null; } else { return listaUbigeo; } } catch(Exception e) { e.printStackTrace(); } return null; } }
923ebcb2a54532bdffae7d767733ff9b9ff191f6
8,569
java
Java
src/main/java/robotbuilder/data/UniqueValidator.java
AustinShalit/RobotBuilder
ff77dd3c18e3f525cf954dd8b5083dfb76af76f2
[ "BSD-3-Clause" ]
34
2016-05-10T19:17:36.000Z
2022-01-18T18:42:54.000Z
src/main/java/robotbuilder/data/UniqueValidator.java
AustinShalit/RobotBuilder
ff77dd3c18e3f525cf954dd8b5083dfb76af76f2
[ "BSD-3-Clause" ]
227
2016-05-11T21:12:35.000Z
2022-02-28T03:51:42.000Z
src/main/java/robotbuilder/data/UniqueValidator.java
AustinShalit/RobotBuilder
ff77dd3c18e3f525cf954dd8b5083dfb76af76f2
[ "BSD-3-Clause" ]
43
2016-05-11T21:00:23.000Z
2022-02-11T01:58:53.000Z
30.823741
137
0.571128
1,000,887
package robotbuilder.data; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import robotbuilder.data.properties.ChoicesProperty; import robotbuilder.data.properties.Property; /** * * @author Alex Henning */ public class UniqueValidator implements Validator { private String name; LinkedList<String> fields; Map<Map<String, Object>, Pair> claims = new HashMap<>(); public UniqueValidator() { } public UniqueValidator(String name, LinkedList<String> fields) { this.name = name; this.fields = fields; } @Override public boolean isValid(RobotComponent component, Property property) { String prefix = getPrefix(property.getName()); Pair pair = new Pair(component, prefix); return claims.containsValue(pair); } @Override public void update(RobotComponent component, String property, Object value) { try { release(component, getPrefix(property)); claim(property, value, component); } catch (InvalidException ex) { //Logger.getLogger(UniqueValidator.class.getName()).log(Level.SEVERE, null, ex); } } @Override public String getError(RobotComponent component, Property property) { Pair claimant = claims.get(getMap(component, getPrefix(property.getName()))); if (claimant == null) { return null; } return "This port is in use by " + claimant.toString() + " please change this to an unused port."; } @Override public void delete(RobotComponent component, String property) { release(component, getPrefix(property)); } @Override public UniqueValidator copy() { LinkedList<String> newFields = new LinkedList<>(); fields.stream().forEach(newFields::add); return new UniqueValidator(name, newFields); } /** * Get the prefix of the property. In other words, anything that's not the * suffix. * * @param key * @return */ private String getPrefix(String key) { for (String field : fields) { if (key.endsWith(field)) { return key.replace(field, ""); } } return null; } private Map<String, Object> getMap(RobotComponent comp, String prefix) { Map<String, Object> values = new HashMap<>(); for (String prop : comp.getPropertyKeys()) { fields.stream() .filter(field -> prop.endsWith(field) && prop.startsWith(prefix)) .forEach(field -> values.put(field, comp.getProperty(prop).getValue())); } return values; } /** * Claim a unique set of values. * * @param key The key being claimed. * @param val It's new value. * @param comp The component making the claim. * @throws robotbuilder.data.UniqueValidator.InvalidException */ private void claim(String key, Object val, RobotComponent comp) throws InvalidException { // Get the prefix String prefix = getPrefix(key); Map<String, Object> values = getMap(comp, prefix); fields.stream() .filter(key::endsWith) .forEach(field -> values.put(field, val)); if (claims.containsKey(values)) { throw new InvalidException(); } Pair pair = new Pair(comp, prefix); claims.put(values, pair); } /** * Release a claim. * * @param comp The component holding the claim. * @param prefix The prefix associated with the hold */ private void release(RobotComponent component, String prefix) { if (hasClaim(component, prefix)) { Pair pair = new Pair(component, prefix); List<Map<String, Object>> toRemove = new LinkedList<>(); claims.keySet().stream() .filter(key -> claims.get(key).equals(pair)) .forEach(toRemove::add); toRemove.stream().forEach(claims::remove); //Map<String, Object> values = getMap(comp, prefix); //claims.remove(values); } } /** * Sets a component to be unique with respect to the prefix of this * property. * * @param component * @param property */ public void setUnique(RobotComponent component, String property) { String prefix = getPrefix(property); if (!hasClaim(component, prefix)) { Map<String, String[]> choices = new HashMap<>(); fields.stream().forEach(field -> choices.put(field, ((ChoicesProperty) component.getProperty(prefix + field)).getChoices())); Map<String, String> selection; try { selection = getFree(choices); } catch (InvalidException ex) { Logger.getLogger(UniqueValidator.class.getName()).log(Level.SEVERE, null, ex); return; } selection.keySet().stream().forEach(prop -> { component.getProperty(prefix + prop).setValue(selection.get(prop)); component.getProperty(prefix + prop).update(); }); } } /** * Whether or not a (component, prefix) pair has a claim. * * @param component * @param prefix * @return */ private boolean hasClaim(RobotComponent component, String prefix) { Pair pair = new Pair(component, prefix); return claims.containsValue(pair); } /** * @return An unused port that can be claimed. */ private Map<String, String> getFree(Map<String, String[]> choices) throws InvalidException { assert fields.size() <= 2; // Warning: Buggy with more than two fields Map<String, Integer> locations = new HashMap<>(); fields.stream().forEach((field) -> locations.put(field, 0)); int fieldLocation = 0; while (true) { // Generate values Map<String, String> values = new HashMap<>(); fields.stream().forEach(field -> values.put(field, choices.get(field)[locations.get(field)])); // Return it if acceptable if (!claims.containsKey(values)) { return values; } // Change locations String field = fields.get(fieldLocation); locations.put(field, locations.get(field) + 1); if (locations.get(field) >= choices.get(field).length) { locations.put(field, 0); fieldLocation++; locations.put(fields.get(fieldLocation), locations.get(fields.get(fieldLocation)) + 1); if (locations.get(fields.get(fields.size() - 1)) >= choices.get(fields.get(fields.size() - 1)).length) { System.out.println("Error!!!"); throw new InvalidException(); } } if (fieldLocation > 0) { fieldLocation--; } } } //// YAML Getters and Setters public LinkedList<String> getFields() { return fields; } public void setFields(LinkedList<String> fields) { this.fields = fields; } @Override public String getName() { return name; } public void setName(String name) { this.name = name; } /** * An exception for invalid claims. */ public static class InvalidException extends Throwable { public InvalidException() { } } static class Pair { RobotComponent comp; String prefix; Pair(RobotComponent comp, String prefix) { this.comp = comp; this.prefix = prefix; } @Override public String toString() { return comp.getFullName() + ": " + prefix; } @Override public int hashCode() { int hash = 5; hash = 53 * hash + (this.comp != null ? this.comp.hashCode() : 0); hash = 53 * hash + (this.prefix != null ? this.prefix.hashCode() : 0); return hash; } @Override public boolean equals(Object oth) { if (oth instanceof Pair) { Pair other = (Pair) oth; return comp.equals(other.comp) && prefix.equals(other.prefix); } return false; } } }
923ebdef9688f9228184e2c5af21a34de9a0c1b2
1,376
java
Java
web-author-dropbox-plugin/src/main/java/com/oxygenxml/examples/dbx/UserData.java
oxygenxml/web-author-storage-services-plugin
ba625aa8ee91ccbeb135cbf07d0291094d62afed
[ "Apache-2.0" ]
null
null
null
web-author-dropbox-plugin/src/main/java/com/oxygenxml/examples/dbx/UserData.java
oxygenxml/web-author-storage-services-plugin
ba625aa8ee91ccbeb135cbf07d0291094d62afed
[ "Apache-2.0" ]
null
null
null
web-author-dropbox-plugin/src/main/java/com/oxygenxml/examples/dbx/UserData.java
oxygenxml/web-author-storage-services-plugin
ba625aa8ee91ccbeb135cbf07d0291094d62afed
[ "Apache-2.0" ]
1
2018-11-22T11:15:43.000Z
2018-11-22T11:15:43.000Z
19.380282
87
0.638808
1,000,888
package com.oxygenxml.examples.dbx; import java.io.IOException; import com.dropbox.core.DbxException; import com.dropbox.core.v2.DbxClientV2; /** * Data stored for a connected user. */ public class UserData { /** * The user's id on google plus.. */ private final String userId; /** * Dropbox client for the client user. */ private final DbxClientV2 client; /** * The name of the user. */ private final String userName; /** * Constructor. * * @param accessToken The access token for the current user. * @param userId The id of the current user. * * @throws DbxException If it fails to retrieve the user name. */ public UserData(String accessToken, String userId) throws IOException, DbxException { client = new DbxClientV2(Credentials.getRequestConfig(), accessToken); this.userId = userId; userName = client.users().getCurrentAccount().getName().getDisplayName(); } /** * Return the user id. * * @return The user id. */ public String getId() { return this.userId; } /** * Returns the dropbox client for the user. * * @return the dropbox client. */ public DbxClientV2 getClient() { return client; } /** * Returns the user name. * * @return the user name. */ public String getUserName() { return userName; } }
923ebe446fdd0eb4a6cf091cdec28f5e5ca2d5af
3,096
java
Java
algorithm/java/ProjectionAreaOf3DShapes.java
cocoa-maemae/leetcode
b7724b4d10387797167b18ec36d77e7418a6d85a
[ "MIT" ]
1
2021-09-29T11:22:02.000Z
2021-09-29T11:22:02.000Z
algorithm/java/ProjectionAreaOf3DShapes.java
cocoa-maemae/leetcode
b7724b4d10387797167b18ec36d77e7418a6d85a
[ "MIT" ]
null
null
null
algorithm/java/ProjectionAreaOf3DShapes.java
cocoa-maemae/leetcode
b7724b4d10387797167b18ec36d77e7418a6d85a
[ "MIT" ]
null
null
null
30.352941
101
0.547481
1,000,889
import com.eclipsesource.json.JsonArray; import java.io.*; import java.util.*; /** * front-back projection area on xz = sum(max value for every col) * right-left projection area on yz = sum(max value for every row) * top-down projection area on xy = sum(1 for every v > 0) **/ class Solution { public int projectionArea(int[][] grid) { int ans = 0, n = grid.length; for (int i = 0; i < n; ++i) { int x = 0, y = 0; for (int j = 0; j < n; ++j) { x = Math.max(x, grid[i][j]); y = Math.max(y, grid[j][i]); // top-down if (grid[i][j] > 0) ++ans; } ans += x + y; } return ans; } } /** * On a N * N grid, we place some 1 * 1 * 1 cubes that are axis-aligned with the x, y, and z axes. * Each value v = grid[i][j] represents a tower of v cubes placed on top of grid cell (i, j). * Now we view the projection of these cubes onto the xy, yz, and zx planes. * A projection is like a shadow, that maps our 3 dimensional figure to a 2 dimensional plane. * Here, we are viewing the "shadow" when looking at the cubes from the top, the front, and the side. * Return the total area of all three projections. * * Example 1: * Input: [[2]] * Output: 5 * * Example 2: * Input: [[1,2],[3,4]] * Output: 17 * Explanation: * Here are the three projections ("shadows") of the shape made with each axis-aligned * * Example 3: * Input: [[1,0],[0,2]] * Output: 8 * * Example 4: * Input: [[1,1,1],[1,0,1],[1,1,1]] * Output: 14 * * Example 5: * Input: [[2,2,2],[2,1,2],[2,2,2]] * Output: 21 * **/ public class ProjectionAreaOf3DShapes { public static int[] stringToIntegerArray(String input) { input = input.trim(); input = input.substring(1, input.length() - 1); if (input.length() == 0) { return new int[0]; } String[] parts = input.split(","); int[] output = new int[parts.length]; for (int i = 0; i < parts.length; i++) { String part = parts[i].trim(); output[i] = Integer.parseInt(part); } return output; } public static int[][] stringToInt2dArray(String input) { JsonArray jsonArray = JsonArray.readFrom(input); if (jsonArray.size() == 0) { return new int[0][0]; } int[][] arr = new int[jsonArray.size()][]; for (int i = 0; i < arr.length; i++) { JsonArray cols = jsonArray.get(i).asArray(); arr[i] = stringToIntegerArray(cols.toString()); } return arr; } public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line; while ((line = in.readLine()) != null) { int[][] grid = stringToInt2dArray(line); int ret = new Solution().projectionArea(grid); String out = String.valueOf(ret); System.out.print(out + '\n'); break; } } }
923ebe6ae7e42ab39e0021e445ae80865d4153b9
4,375
java
Java
src/main/java/it/unitn/disi/wp/cup/config/AuthConfig.java
carlocorradini/cup
f2169b1b50614be7e1291676e979ef721a54188a
[ "MIT" ]
6
2019-09-22T16:15:12.000Z
2020-03-02T15:29:38.000Z
src/main/java/it/unitn/disi/wp/cup/config/AuthConfig.java
carlocorradini/cup
f2169b1b50614be7e1291676e979ef721a54188a
[ "MIT" ]
null
null
null
src/main/java/it/unitn/disi/wp/cup/config/AuthConfig.java
carlocorradini/cup
f2169b1b50614be7e1291676e979ef721a54188a
[ "MIT" ]
3
2019-12-16T17:31:22.000Z
2021-03-28T10:36:17.000Z
28.97351
95
0.612114
1,000,890
package it.unitn.disi.wp.cup.config; import it.unitn.disi.wp.cup.config.exception.ConfigException; import java.util.logging.Level; import java.util.logging.Logger; /** * Authorization Configuration * * @author Carlo Corradini */ public final class AuthConfig extends Config { private static final String FILE_NAME = "auth.properties"; private static final String CATEGORY = "auth"; private static final Logger LOGGER = Logger.getLogger(AuthConfig.class.getName()); private static AuthConfig instance; private AuthConfig() throws ConfigException { super(FILE_NAME, CATEGORY); } /** * Load the Auth Configuration * * @throws ConfigException If the instance has been already initialized */ public static void load() throws ConfigException { if (instance == null) { instance = new AuthConfig(); } else throw new ConfigException("AppConfig has been already initialized"); } private static void checkInstance() throws ConfigException { if (instance == null) throw new ConfigException("AuthConfig has not been initialized"); } /** * Return the session name of the authenticated Person * * @return Session Person name */ public static String getSessionPersonName() { try { checkInstance(); } catch (ConfigException ex) { LOGGER.log(Level.SEVERE, "Unable to get Session Person Name", ex); } return instance.getString("session.person.name"); } /** * Return the session name of the authenticated Doctor * * @return Session Doctor name */ public static String getSessionDoctorName() { try { checkInstance(); } catch (ConfigException ex) { LOGGER.log(Level.SEVERE, "Unable to get Session Doctor Name", ex); } return instance.getString("session.doctor.name"); } /** * Return the session name of the authenticated Doctor Specialist * * @return Session Doctor Specialist name */ public static String getSessionDoctorSpecialistName() { try { checkInstance(); } catch (ConfigException ex) { LOGGER.log(Level.SEVERE, "Unable to get Session Doctor Specialist Name", ex); } return instance.getString("session.doctorSpecialist.name"); } /** * Return the session name of the authenticated Health Service * * @return Session Health Service name */ public static String getSessionHealthServiceName() { try { checkInstance(); } catch (ConfigException ex) { LOGGER.log(Level.SEVERE, "Unable to get Session Health Service Name", ex); } return instance.getString("session.healthService.name"); } /** * Return the Cookie Remember Name * * @return Cookie Remember Name */ public static String getCookieRememberName() { try { checkInstance(); } catch (ConfigException ex) { LOGGER.log(Level.SEVERE, "Unable to get Cookie Remember Name", ex); } return instance.getString("cookie.remember.name"); } /** * Return the Cookie Remember Max Age * * @return Cookie Remember Max Age */ public static int getCookieRememberMaxAge() { try { checkInstance(); } catch (ConfigException ex) { LOGGER.log(Level.SEVERE, "Unable to get Cookie Remember Max Age", ex); } return instance.getInt("cookie.remember.maxAge"); } /** * Return the Password Min Length * * @return Password Min Length */ public static int getPasswordMinLength() { try { checkInstance(); } catch (ConfigException ex) { LOGGER.log(Level.SEVERE, "Unable to get Password Min Length", ex); } return instance.getInt("password.minLength"); } /** * Return the Password Max Length * * @return Password Max Length */ public static int getPasswordMaxLength() { try { checkInstance(); } catch (ConfigException ex) { LOGGER.log(Level.SEVERE, "Unable to get Password Max Length", ex); } return instance.getInt("password.maxLength"); } }
923ebee553149a139e6ac1aedd0ae4d21b813d36
285,843
java
Java
src/us/kbase/workspace/test/workspace/WorkspaceTest.java
olsonanl/workspace_deluxe
8fb9dbdbd524ab68d1d50917b2a9a9861ecb02d5
[ "MIT" ]
null
null
null
src/us/kbase/workspace/test/workspace/WorkspaceTest.java
olsonanl/workspace_deluxe
8fb9dbdbd524ab68d1d50917b2a9a9861ecb02d5
[ "MIT" ]
null
null
null
src/us/kbase/workspace/test/workspace/WorkspaceTest.java
olsonanl/workspace_deluxe
8fb9dbdbd524ab68d1d50917b2a9a9861ecb02d5
[ "MIT" ]
null
null
null
51.107277
205
0.722512
1,000,891
package us.kbase.workspace.test.workspace; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.StringReader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeSet; import junit.framework.Assert; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.IOUtils; import org.junit.Test; import us.kbase.common.service.JsonTokenStream; import us.kbase.typedobj.core.AbsoluteTypeDefId; import us.kbase.typedobj.core.ObjectPaths; import us.kbase.typedobj.core.TempFileListener; import us.kbase.typedobj.core.TypeDefId; import us.kbase.typedobj.core.TypeDefName; import us.kbase.typedobj.db.FuncDetailedInfo; import us.kbase.typedobj.db.ModuleDefId; import us.kbase.typedobj.db.TypeDetailedInfo; import us.kbase.typedobj.exceptions.NoSuchFuncException; import us.kbase.typedobj.exceptions.NoSuchModuleException; import us.kbase.typedobj.exceptions.NoSuchPrivilegeException; import us.kbase.typedobj.exceptions.NoSuchTypeException; import us.kbase.typedobj.exceptions.TypedObjectExtractionException; import us.kbase.typedobj.exceptions.TypedObjectValidationException; import us.kbase.typedobj.idref.IdReferenceHandlerSetFactory; import us.kbase.typedobj.idref.IdReferenceType; import us.kbase.workspace.database.AllUsers; import us.kbase.workspace.database.ModuleInfo; import us.kbase.workspace.database.ObjectChain; import us.kbase.workspace.database.ObjectIDNoWSNoVer; import us.kbase.workspace.database.ObjectIdentifier; import us.kbase.workspace.database.ObjectInformation; import us.kbase.workspace.database.Permission; import us.kbase.workspace.database.Provenance; import us.kbase.workspace.database.Provenance.ExternalData; import us.kbase.workspace.database.Reference; import us.kbase.workspace.database.ResourceUsageConfigurationBuilder; import us.kbase.workspace.database.WorkspaceSaveObject; import us.kbase.workspace.database.Provenance.ProvenanceAction; import us.kbase.workspace.database.ResourceUsageConfigurationBuilder.ResourceUsageConfiguration; import us.kbase.workspace.database.SubObjectIdentifier; import us.kbase.workspace.database.User; import us.kbase.workspace.database.WorkspaceIdentifier; import us.kbase.workspace.database.WorkspaceInformation; import us.kbase.workspace.database.WorkspaceObjectData; import us.kbase.workspace.database.WorkspaceObjectInformation; import us.kbase.workspace.database.WorkspaceUser; import us.kbase.workspace.database.exceptions.InaccessibleObjectException; import us.kbase.workspace.database.exceptions.NoSuchObjectException; import us.kbase.workspace.database.exceptions.NoSuchReferenceException; import us.kbase.workspace.database.exceptions.NoSuchWorkspaceException; import us.kbase.workspace.database.exceptions.PreExistingWorkspaceException; import us.kbase.workspace.exceptions.WorkspaceAuthorizationException; import us.kbase.workspace.test.kbase.JSONRPCLayerTester; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class WorkspaceTest extends WorkspaceTester { public WorkspaceTest(String config, String backend, Integer maxMemoryUsePerCall) throws Exception { super(config, backend, maxMemoryUsePerCall); } private static final WorkspaceIdentifier lockWS = new WorkspaceIdentifier("lock"); @Test public void workspaceDescription() throws Exception { WorkspaceInformation ltinfo = ws.createWorkspace(SOMEUSER, "lt", false, LONG_TEXT, null); WorkspaceInformation ltpinfo = ws.createWorkspace(SOMEUSER, "ltp", false, LONG_TEXT_PART, null); WorkspaceInformation ltninfo = ws.createWorkspace(SOMEUSER, "ltn", false, null, null); String desc = ws.getWorkspaceDescription(SOMEUSER, new WorkspaceIdentifier("lt")); assertThat("Workspace description incorrect", desc, is(LONG_TEXT.substring(0, 1000))); desc = ws.getWorkspaceDescription(SOMEUSER, new WorkspaceIdentifier("ltp")); assertThat("Workspace description incorrect", desc, is(LONG_TEXT_PART)); desc = ws.getWorkspaceDescription(SOMEUSER, new WorkspaceIdentifier("ltn")); assertNull("Workspace description incorrect", desc); ws.setWorkspaceDescription(SOMEUSER, new WorkspaceIdentifier("lt"), LONG_TEXT_PART); ws.setWorkspaceDescription(SOMEUSER, new WorkspaceIdentifier("ltp"), null); ws.setWorkspaceDescription(SOMEUSER, new WorkspaceIdentifier("ltn"), LONG_TEXT); WorkspaceInformation ltinfo2 = ws.getWorkspaceInformation(SOMEUSER, new WorkspaceIdentifier("lt")); WorkspaceInformation ltpinfo2 = ws.getWorkspaceInformation(SOMEUSER, new WorkspaceIdentifier("ltp")); WorkspaceInformation ltninfo2 = ws.getWorkspaceInformation(SOMEUSER, new WorkspaceIdentifier("ltn")); assertTrue("date updated on set ws desc", ltinfo2.getModDate().after(ltinfo.getModDate())); assertTrue("date updated on set ws desc", ltpinfo2.getModDate().after(ltpinfo.getModDate())); assertTrue("date updated on set ws desc", ltninfo2.getModDate().after(ltninfo.getModDate())); desc = ws.getWorkspaceDescription(SOMEUSER, new WorkspaceIdentifier("lt")); assertThat("Workspace description incorrect", desc, is(LONG_TEXT_PART)); desc = ws.getWorkspaceDescription(SOMEUSER, new WorkspaceIdentifier("ltp")); assertNull("Workspace description incorrect", desc); desc = ws.getWorkspaceDescription(SOMEUSER, new WorkspaceIdentifier("ltn")); assertThat("Workspace description incorrect", desc, is(LONG_TEXT.substring(0, 1000))); WorkspaceIdentifier wsi = new WorkspaceIdentifier("lt"); failSetWSDesc(AUSER, wsi, "foo", new WorkspaceAuthorizationException( "User a may not set description on workspace lt")); failSetWSDesc(null, wsi, "foo", new WorkspaceAuthorizationException( "Anonymous users may not set description on workspace lt")); ws.setPermissions(SOMEUSER, wsi, Arrays.asList(AUSER), Permission.WRITE); failSetWSDesc(AUSER, wsi, "foo", new WorkspaceAuthorizationException( "User a may not set description on workspace lt")); ws.setPermissions(SOMEUSER, wsi, Arrays.asList(AUSER), Permission.ADMIN); ws.setWorkspaceDescription(AUSER, wsi, "wooga"); assertThat("ws desc ok", ws.getWorkspaceDescription(SOMEUSER, wsi), is("wooga")); ws.setWorkspaceDeleted(SOMEUSER, wsi, true); failSetWSDesc(SOMEUSER, wsi, "foo", new NoSuchWorkspaceException( "Workspace lt is deleted", wsi)); ws.setWorkspaceDeleted(SOMEUSER, wsi, false); failSetWSDesc(SOMEUSER, new WorkspaceIdentifier("ltfake"), "foo", new NoSuchWorkspaceException( "No workspace with name ltfake exists", wsi)); try { ws.getWorkspaceDescription(BUSER, wsi); fail("Got ws desc w/o read perms"); } catch (WorkspaceAuthorizationException e) { assertThat("exception message ok", e.getLocalizedMessage(), is("User b may not read workspace lt")); } for (Permission p: Permission.values()) { if (p.compareTo(Permission.NONE) <= 0 || p.compareTo(Permission.OWNER) >= 0) { continue; } ws.setPermissions(SOMEUSER, wsi, Arrays.asList(BUSER), p); ws.getWorkspaceDescription(BUSER, wsi); //will fail if perms are wrong } ws.lockWorkspace(SOMEUSER, wsi); failSetWSDesc(SOMEUSER, wsi, "foo", new WorkspaceAuthorizationException( "The workspace with id " + ltinfo.getId() + ", name lt, is locked and may not be modified")); } @Test public void createWorkspaceAndGetInfo() throws Exception { String wsname = "foo_.-bar"; WorkspaceInformation info = ws.createWorkspace(SOMEUSER, wsname, false, "eeswaffertheen", null); checkWSInfo(info, SOMEUSER, wsname, 0, Permission.OWNER, false, "unlocked", MT_META); long id = info.getId(); WorkspaceIdentifier wsi = new WorkspaceIdentifier(id); Date moddate = info.getModDate(); info = ws.getWorkspaceInformation(SOMEUSER, new WorkspaceIdentifier(id)); checkWSInfo(info, SOMEUSER, wsname, 0, Permission.OWNER, false, id, moddate, "unlocked", MT_META); info = ws.getWorkspaceInformation(SOMEUSER, new WorkspaceIdentifier(wsname)); checkWSInfo(info, SOMEUSER, wsname, 0, Permission.OWNER, false, id, moddate, "unlocked", MT_META); Map<String, String> meta = new HashMap<String, String>(); meta.put("foo", "bar"); meta.put("baz", "bash"); WorkspaceInformation info2 = ws.createWorkspace(SOMEUSER, "foo2", true, "eeswaffertheen2", meta); checkWSInfo(info2, SOMEUSER, "foo2", 0, Permission.OWNER, true, "unlocked", meta); checkWSInfo(new WorkspaceIdentifier("foo2"), SOMEUSER, "foo2", 0, Permission.OWNER, true, info2.getId(), info2.getModDate(), "unlocked", meta); try { ws.getWorkspaceInformation(BUSER, wsi); fail("Got metadata w/o read perms"); } catch (WorkspaceAuthorizationException e) { assertThat("exception message ok", e.getLocalizedMessage(), is("User b may not read workspace " + id)); } for (Permission p: Permission.values()) { if (p.compareTo(Permission.NONE) <= 0 || p.compareTo(Permission.OWNER) >= 0) { continue; } ws.setPermissions(SOMEUSER, wsi, Arrays.asList(BUSER), p); ws.getWorkspaceInformation(BUSER, wsi); //will fail if perms are wrong } WorkspaceUser anotheruser = new WorkspaceUser("anotherfnuser"); info = ws.createWorkspace(anotheruser, "anotherfnuser:MrT", true, "Ipitythefoolthatdon'teatMrTbreakfastcereal", null); checkWSInfo(info, anotheruser, "anotherfnuser:MrT", 0, Permission.OWNER, true, "unlocked", MT_META); id = info.getId(); moddate = info.getModDate(); info = ws.getWorkspaceInformation(anotheruser, new WorkspaceIdentifier(id)); checkWSInfo(info, anotheruser, "anotherfnuser:MrT", 0, Permission.OWNER, true, id, moddate, "unlocked", MT_META); info = ws.getWorkspaceInformation(anotheruser, new WorkspaceIdentifier("anotherfnuser:MrT")); checkWSInfo(info, anotheruser, "anotherfnuser:MrT", 0, Permission.OWNER, true, id, moddate, "unlocked", MT_META); Map<String, String> bigmeta = new HashMap<String, String>(); for (int i = 0; i < 141; i++) { bigmeta.put("thing" + i, TEXT100); } ws.createWorkspace(SOMEUSER, "foo3", false, "eeswaffertheen", bigmeta); bigmeta.put("thing", TEXT100); try { ws.createWorkspace(SOMEUSER, "foo4", false, "eeswaffertheen", bigmeta); fail("created ws with > 16kb metadata"); } catch (IllegalArgumentException iae) { assertThat("correct exception", iae.getLocalizedMessage(), is("Metadata size of 16076 is > 16000 bytes")); } ws.setGlobalPermission(anotheruser, new WorkspaceIdentifier("anotherfnuser:MrT"), Permission.NONE); ws.setGlobalPermission(SOMEUSER, new WorkspaceIdentifier("foo2"), Permission.NONE); } @Test public void workspaceMetadata() throws Exception { WorkspaceUser user = new WorkspaceUser("blahblah"); WorkspaceUser user2 = new WorkspaceUser("blahblah2"); WorkspaceIdentifier wsi = new WorkspaceIdentifier("workspaceMetadata"); WorkspaceIdentifier wsiNo = new WorkspaceIdentifier("workspaceNoMetadata"); WorkspaceIdentifier wsiNo2 = new WorkspaceIdentifier("workspaceNoMetadata2"); Map<String, String> meta = new HashMap<String, String>(); meta.put("foo", "bar"); meta.put("foo2", "bar2"); meta.put("some", "meta"); WorkspaceInformation info = ws.createWorkspace(user, wsi.getName(), false, null, meta); ws.setPermissions(user, wsi, Arrays.asList(user2), Permission.ADMIN); checkWSInfo(info, user, wsi.getName(), 0, Permission.OWNER, false, info.getId(), info.getModDate(), "unlocked", meta); checkWSInfo(wsi, user, wsi.getName(), 0, Permission.OWNER, false, info.getId(), info.getModDate(), "unlocked", meta); WorkspaceInformation infoNo = ws.createWorkspace(user, wsiNo.getName(), false, null, null); checkWSInfo(infoNo, user, wsiNo.getName(), 0, Permission.OWNER, false, infoNo.getId(), infoNo.getModDate(), "unlocked", MT_META); checkWSInfo(wsiNo, user, wsiNo.getName(), 0, Permission.OWNER, false, infoNo.getId(), infoNo.getModDate(), "unlocked", MT_META); WorkspaceInformation infoNo2 = ws.createWorkspace(user, wsiNo2.getName(), false, null, null); meta.put("foo2", "bar3"); //replace Map<String, String> putmeta = new HashMap<String, String>(); putmeta.put("foo2", "bar3"); ws.setWorkspaceMetadata(user, wsi, putmeta); Date d1 = checkWSInfo(wsi, user, wsi.getName(), 0, Permission.OWNER, false, info.getId(), "unlocked", meta); meta.put("foo3", "bar4"); //new putmeta.clear(); putmeta.put("foo3", "bar4"); ws.setWorkspaceMetadata(user, wsi, putmeta); Date d2 = checkWSInfo(wsi, user, wsi.getName(), 0, Permission.OWNER, false, info.getId(), "unlocked", meta); putmeta.clear(); putmeta.put("foo3", "bar5"); //replace putmeta.put("some.garbage", "with.dots"); //new putmeta.put("foo", "whoa this is new"); //replace putmeta.put("no, this part is new", "prunker"); //new meta.put("foo3", "bar5"); meta.put("some.garbage", "with.dots"); meta.put("foo", "whoa this is new"); meta.put("no, this part is new", "prunker"); ws.setWorkspaceMetadata(user, wsi, putmeta); Date d3 = checkWSInfo(wsi, user, wsi.getName(), 0, Permission.OWNER, false, info.getId(), "unlocked", meta); Map<String, String> newmeta = new HashMap<String, String>(); newmeta.put("new", "meta"); ws.setWorkspaceMetadata(user, wsiNo, newmeta); Date nod1 = checkWSInfo(wsiNo, user, wsiNo.getName(), 0, Permission.OWNER, false, infoNo.getId(), "unlocked", newmeta); assertDatesAscending(infoNo.getModDate(), nod1); meta.remove("foo2"); ws.removeWorkspaceMetadata(user, wsi, "foo2"); Date d4 = checkWSInfo(wsi, user, wsi.getName(), 0, Permission.OWNER, false, info.getId(), "unlocked", meta); meta.remove("some"); ws.removeWorkspaceMetadata(user2, wsi, "some"); Date d5 = checkWSInfo(wsi, user, wsi.getName(), 0, Permission.OWNER, false, info.getId(), "unlocked", meta); ws.removeWorkspaceMetadata(user, wsi, "fake"); //no effect checkWSInfo(wsi, user, wsi.getName(), 0, Permission.OWNER, false, info.getId(), d5, "unlocked", meta); assertDatesAscending(info.getModDate(), d1, d2, d3, d4, d5); checkWSInfo(wsiNo2, user, wsiNo2.getName(), 0, Permission.OWNER, false, infoNo2.getId(), infoNo2.getModDate(), "unlocked", MT_META); ws.removeWorkspaceMetadata(user, wsiNo2, "somekey"); //should do nothing checkWSInfo(wsiNo2, user, wsiNo2.getName(), 0, Permission.OWNER, false, infoNo2.getId(), infoNo2.getModDate(), "unlocked", MT_META); ws.setPermissions(user, wsi, Arrays.asList(user2), Permission.WRITE); failWSMeta(user2, wsi, "foo", "val", new WorkspaceAuthorizationException( "User blahblah2 may not alter metadata for workspace workspaceMetadata")); failWSMeta(null, wsi, "foo", "val", new WorkspaceAuthorizationException( "Anonymous users may not alter metadata for workspace workspaceMetadata")); failWSMeta(user2, new WorkspaceIdentifier("thisiswayfake"), "foo", "val", new NoSuchWorkspaceException( "No workspace with name thisiswayfake exists", wsi)); ws.setWorkspaceDeleted(user, wsi, true); failWSMeta(user, wsi, "foo", "val", new NoSuchWorkspaceException( "Workspace workspaceMetadata is deleted", wsi)); ws.setWorkspaceDeleted(user, wsi, false); putmeta.clear(); for (int i = 0; i < 147; i++) { putmeta.put("" + i, TEXT100); } ws.createWorkspace(user, "wsmetafake", false, null, putmeta); //should work failWSSetMeta(user, wsi, putmeta, new IllegalArgumentException( "Updated metadata size of 16013 is > 16000 bytes")); ws.setWorkspaceMetadata(user, wsiNo, putmeta); //should work putmeta.put("148", TEXT100); failWSSetMeta(user, wsiNo2, putmeta, new IllegalArgumentException( "Updated metadata size of 16023 is > 16000 bytes")); failWSSetMeta(user, wsi, null, new IllegalArgumentException( "Metadata cannot be null or empty")); failWSSetMeta(user, wsi, MT_META, new IllegalArgumentException( "Metadata cannot be null or empty")); } @Test public void createWorkspaceAndWorkspaceIdentifierWithBadInput() throws Exception { class TestRig { public final WorkspaceUser user; public final String wsname; public final String excep; public TestRig(WorkspaceUser user, String wsname, String exception) { this.user = user; this.wsname = wsname; this.excep = exception; } } WorkspaceUser crap = new WorkspaceUser("afaeaafe"); List<TestRig> userWS = new ArrayList<TestRig>(); //test a few funny chars in the ws name userWS.add(new TestRig(crap, "afe_aff*afea", "Illegal character in workspace name afe_aff*afea: *")); userWS.add(new TestRig(crap, "afe_aff%afea", "Illegal character in workspace name afe_aff%afea: %")); userWS.add(new TestRig(crap, "afeaff/af*ea", "Illegal character in workspace name afeaff/af*ea: /")); userWS.add(new TestRig(crap, "af?eaff*afea", "Illegal character in workspace name af?eaff*afea: ?")); userWS.add(new TestRig(crap, "64", "Workspace names cannot be integers: 64")); //check missing ws name userWS.add(new TestRig(crap, null, "Workspace name cannot be null or the empty string")); userWS.add(new TestRig(crap, "", "Workspace name cannot be null or the empty string")); //check long names userWS.add(new TestRig(crap, TEXT256, "Workspace name exceeds the maximum length of 255")); //check missing user and/or workspace name in compound name userWS.add(new TestRig(crap, ":", "Workspace name missing from :")); userWS.add(new TestRig(crap, "foo:", "Workspace name missing from foo:")); userWS.add(new TestRig(crap, ":foo", "User name missing from :foo")); //check multiple delims userWS.add(new TestRig(crap, "foo:a:foo", "Workspace name foo:a:foo may only contain one : delimiter")); userWS.add(new TestRig(crap, "foo::foo", "Workspace name foo::foo may only contain one : delimiter")); for (TestRig testdata: userWS) { String wksps = testdata.wsname; try { new WorkspaceIdentifier(wksps); fail(String.format("able to create workspace identifier with illegal input ws %s", wksps)); } catch (IllegalArgumentException e) { assertThat("incorrect exception message", e.getLocalizedMessage(), is(testdata.excep)); } } //check missing user userWS.add(new TestRig(null, "foo", "user cannot be null")); //user must match prefix userWS.add(new TestRig(SOMEUSER, "notauser:foo", "Workspace name notauser:foo must only contain the user name " + SOMEUSER.getUser() + " prior to the : delimiter")); //no ints userWS.add(new TestRig(new WorkspaceUser("foo"), "foo:64", "Workspace names cannot be integers: foo:64")); for (TestRig testdata: userWS) { WorkspaceUser user = testdata.user; String wksps = testdata.wsname; try { ws.createWorkspace(user, wksps, false, "iswaffertheen", null); fail(String.format("able to create workspace with illegal input user: %s ws %s", user, wksps)); } catch (IllegalArgumentException e) { assertThat("incorrect exception message", e.getLocalizedMessage(), is(testdata.excep)); } try { new WorkspaceIdentifier(wksps, user); fail(String.format("able to create workspace identifier with illegal input user: %s ws %s", user, wksps)); } catch (IllegalArgumentException e) { assertThat("incorrect exception message", e.getLocalizedMessage(), is(testdata.excep)); } } } @Test public void preExistingWorkspace() throws Exception { ws.createWorkspace(AUSER, "preexist", false, null, null); failCreateWorkspace(BUSER, "preexist", false, null, null, new PreExistingWorkspaceException("Workspace name preexist is already in use")); ws.setWorkspaceDeleted(AUSER, new WorkspaceIdentifier("preexist"), true); failCreateWorkspace(BUSER, "preexist", false, null, null, new PreExistingWorkspaceException("Workspace name preexist is already in use")); failCreateWorkspace(AUSER, "preexist", false, null, null, new PreExistingWorkspaceException( "Workspace name preexist is already in use by a deleted workspace")); } @Test public void createIllegalUser() throws Exception { try { new WorkspaceUser("*"); fail("able to create user with illegal character"); } catch (IllegalArgumentException e) { assertThat("exception message correct", e.getLocalizedMessage(), is("Illegal character in user name *: *")); } try { new WorkspaceUser(null); fail("able to create user with null"); } catch (IllegalArgumentException e) { assertThat("exception message correct", e.getLocalizedMessage(), is("Username cannot be null or the empty string")); } try { new WorkspaceUser(""); fail("able to create user with empty string"); } catch (IllegalArgumentException e) { assertThat("exception message correct", e.getLocalizedMessage(), is("Username cannot be null or the empty string")); } try { new WorkspaceUser(TEXT101); fail("able to create user with long string"); } catch (IllegalArgumentException e) { assertThat("exception message correct", e.getLocalizedMessage(), is("Username exceeds the maximum length of 100")); } try { new AllUsers('$'); fail("able to create AllUser with illegal char"); } catch (IllegalArgumentException e) { assertThat("exception message correct", e.getLocalizedMessage(), is("Disallowed character: $")); } } @Test public void setWorkspaceOwner() throws Exception { WorkspaceUser u1 = new WorkspaceUser("foo"); WorkspaceUser u2 = new WorkspaceUser("bar"); WorkspaceIdentifier wsi = new WorkspaceIdentifier("wsfoo"); ws.createWorkspace(u1, wsi.getName(), false, null, null); Map<String, String> mt = new HashMap<String, String>(); //basic test WorkspaceInformation wsinfo = ws.setWorkspaceOwner(u1, wsi, u2, null, false); checkWSInfo(wsinfo, u2, wsi.getName(), 0L, Permission.OWNER, false, "unlocked", mt); Map<User, Permission> pexp = new HashMap<User, Permission>(); pexp.put(u1, Permission.ADMIN); pexp.put(u2, Permission.OWNER); assertThat("permissions correct", ws.getPermissions(u2, wsi), is (pexp)); failSetWorkspaceOwner(null, wsi, u2, null, true, new IllegalArgumentException("bar already owns workspace wsfoo")); failSetWorkspaceOwner(u2, wsi, u2, null, false, new IllegalArgumentException("bar already owns workspace wsfoo")); failSetWorkspaceOwner(null, wsi, null, null, true, new NullPointerException("newUser cannot be null")); failSetWorkspaceOwner(u2, wsi, null, null, false, new NullPointerException("newUser cannot be null")); failSetWorkspaceOwner(null, null, u1, null, true, new NullPointerException("wsi cannot be null")); failSetWorkspaceOwner(u2, null, u1, null, false, new NullPointerException("wsi cannot be null")); WorkspaceIdentifier fake = new WorkspaceIdentifier("wsfoofake"); failSetWorkspaceOwner(null, fake, u2, null, true, new NoSuchWorkspaceException("No workspace with name wsfoofake exists", fake)); failSetWorkspaceOwner(u2, fake, u2, null, false, new NoSuchWorkspaceException("No workspace with name wsfoofake exists", fake)); failSetWorkspaceOwner(null, wsi, u1, null, false, new WorkspaceAuthorizationException("Anonymous users may not change the owner of workspace wsfoo")); failSetWorkspaceOwner(u1, wsi, u1, null, false, new WorkspaceAuthorizationException("User foo may not change the owner of workspace wsfoo")); //test as admin wsinfo = ws.setWorkspaceOwner(null, wsi, u1, null, true); checkWSInfo(wsinfo, u1, wsi.getName(), 0L, Permission.OWNER, false, "unlocked", mt); pexp.put(u1, Permission.OWNER); pexp.put(u2, Permission.ADMIN); assertThat("permissions correct", ws.getPermissions(u2, wsi), is (pexp)); //test basic name change wsinfo = ws.setWorkspaceOwner(u1, wsi, u2, "wsfoonew", false); checkWSInfo(wsinfo, u2, "wsfoonew", 0L, Permission.OWNER, false, "unlocked", mt); wsi = new WorkspaceIdentifier("wsfoonew"); //illegal name change to invalid user failSetWorkspaceOwner(u2, wsi, u1, "bar:wsfoo", false, new IllegalArgumentException("Workspace name bar:wsfoo must only contain the user name foo prior to the : delimiter")); failSetWorkspaceOwner(null, wsi, u1, "bar:wsfoo", true, new IllegalArgumentException("Workspace name bar:wsfoo must only contain the user name foo prior to the : delimiter")); //test auto rename of workspace ws.renameWorkspace(u2, wsi, "bar:wsfoo"); wsi = new WorkspaceIdentifier("bar:wsfoo"); wsinfo = ws.setWorkspaceOwner(u2, wsi, u1, null, false); wsi = new WorkspaceIdentifier("foo:wsfoo"); checkWSInfo(wsinfo, u1, wsi.getName(), 0L, Permission.OWNER, false, "unlocked", mt); //test manual rename of workspace wsinfo = ws.setWorkspaceOwner(u1, wsi, u2, "bar:wsfoo", false); wsi = new WorkspaceIdentifier("bar:wsfoo"); checkWSInfo(wsinfo, u2, wsi.getName(), 0L, Permission.OWNER, false, "unlocked", mt); //test rename to preexisting workspace ws.createWorkspace(u1, "foo:wsfoo2", false, null, null); failSetWorkspaceOwner(u2, wsi, u1, "foo:wsfoo2", false, new IllegalArgumentException("There is already a workspace named foo:wsfoo2")); failSetWorkspaceOwner(null, wsi, u1, "foo:wsfoo2", true, new IllegalArgumentException("There is already a workspace named foo:wsfoo2")); //test rename with same name ws.renameWorkspace(u2, wsi, "wsfoo"); wsi = new WorkspaceIdentifier("wsfoo"); wsinfo = ws.setWorkspaceOwner(u2, wsi, u1, "wsfoo", false); checkWSInfo(wsinfo, u1, wsi.getName(), 0L, Permission.OWNER, false, "unlocked", mt); } private void failSetWorkspaceOwner(WorkspaceUser user, WorkspaceIdentifier wsi, WorkspaceUser newuser, String name, boolean asAdmin, Exception expected) throws Exception { try { ws.setWorkspaceOwner(user, wsi, newuser, name, asAdmin); fail("expected set owner to fail"); } catch (Exception got) { assertThat("correct exception", got.getLocalizedMessage(), is(expected.getLocalizedMessage())); assertThat("correct exception type", got, is(expected.getClass())); } } @Test public void permissions() throws Exception { //setup WorkspaceIdentifier wsiNG = new WorkspaceIdentifier("perms_noglobal"); ws.createWorkspace(AUSER, "perms_noglobal", false, null, null); WorkspaceIdentifier wsiGL = new WorkspaceIdentifier("perms_global"); ws.createWorkspace(AUSER, "perms_global", true, "globaldesc", null); Map<User, Permission> expect = new HashMap<User, Permission>(); //try some illegal ops try { ws.getWorkspaceDescription(null, wsiNG); fail("Able to get private workspace description with no user name"); } catch (Exception e) { assertThat("Correct exception message", e.getLocalizedMessage(), is("Anonymous users may not read workspace perms_noglobal")); } try { ws.getWorkspaceInformation(null, wsiNG); fail("Able to get private workspace metadata with no user name"); } catch (WorkspaceAuthorizationException e) { assertThat("Correct exception message", e.getLocalizedMessage(), is("Anonymous users may not read workspace perms_noglobal")); } failSetPermissions(null, wsiNG, Arrays.asList(AUSER, BUSER, CUSER), Permission.READ, new WorkspaceAuthorizationException( "Anonymous users may not set permissions on workspace perms_noglobal")); failSetPermissions(null, wsiNG, null, Permission.READ, new IllegalArgumentException("The users list may not be null or empty")); failSetPermissions(null, wsiNG, new LinkedList<WorkspaceUser>(), Permission.READ, new IllegalArgumentException("The users list may not be null or empty")); failSetPermissions(AUSER, wsiNG, Arrays.asList(AUSER, BUSER, CUSER), Permission.OWNER, new IllegalArgumentException("Cannot set owner permission")); failSetPermissions(BUSER, wsiNG, Arrays.asList(AUSER, BUSER, CUSER), Permission.READ, new WorkspaceAuthorizationException("User b may not set permissions on workspace perms_noglobal")); //check basic permissions for new private and public workspaces expect.put(AUSER, Permission.OWNER); assertThat("ws has correct perms for owner", ws.getPermissions(AUSER, wsiNG), is(expect)); expect.put(STARUSER, Permission.READ); assertThat("ws has correct perms for owner", ws.getPermissions(AUSER, wsiGL), is(expect)); expect.clear(); expect.put(BUSER, Permission.NONE); assertThat("ws has correct perms for random user", ws.getPermissions(BUSER, wsiNG), is(expect)); expect.put(STARUSER, Permission.READ); assertThat("ws has correct perms for random user", ws.getPermissions(BUSER, wsiGL), is(expect)); //test read permissions assertThat("can read public workspace description", ws.getWorkspaceDescription(null, wsiGL), is("globaldesc")); WorkspaceInformation info = ws.getWorkspaceInformation(null, wsiGL); checkWSInfo(info, AUSER, "perms_global", 0, Permission.NONE, true, "unlocked", MT_META); ws.setPermissions(AUSER, wsiNG, Arrays.asList(AUSER, BUSER, CUSER), Permission.READ); expect.clear(); expect.put(AUSER, Permission.OWNER); expect.put(BUSER, Permission.READ); expect.put(CUSER, Permission.READ); assertThat("ws doesn't replace owner perms", ws.getPermissions(AUSER, wsiNG), is(expect)); expect.clear(); expect.put(BUSER, Permission.READ); assertThat("no permission leakage", ws.getPermissions(BUSER, wsiNG), is(expect)); failSetPermissions(BUSER, wsiNG, Arrays.asList(AUSER, BUSER, CUSER), Permission.READ, new WorkspaceAuthorizationException( "User b may not alter other user's permissions on workspace perms_noglobal")); failSetPermissions(BUSER, wsiNG, Arrays.asList(BUSER), Permission.WRITE, new WorkspaceAuthorizationException( "User b may only reduce their permission level on workspace perms_noglobal")); //asAdmin testing ws.setPermissions(BUSER, wsiNG, Arrays.asList(BUSER), Permission.ADMIN, true); expect.put(AUSER, Permission.OWNER); expect.put(BUSER, Permission.ADMIN); expect.put(CUSER, Permission.READ); assertThat("asAdmin boolean works", ws.getPermissions(BUSER, wsiNG), is(expect)); ws.setPermissions(BUSER, wsiNG, Arrays.asList(BUSER), Permission.READ); expect.clear(); expect.put(BUSER, Permission.READ); assertThat("reduce own permissions", ws.getPermissions(BUSER, wsiNG), is(expect)); ws.setPermissions(null, wsiNG, Arrays.asList(BUSER), Permission.ADMIN, true); expect.put(AUSER, Permission.OWNER); expect.put(BUSER, Permission.ADMIN); expect.put(CUSER, Permission.READ); assertThat("asAdmin boolean works with null user", ws.getPermissions(BUSER, wsiNG), is(expect)); ws.setPermissions(AUSER, wsiNG, Arrays.asList(BUSER), Permission.READ); expect.clear(); expect.put(BUSER, Permission.READ); assertThat("reduced permissions", ws.getPermissions(BUSER, wsiNG), is(expect)); ws.setPermissions(BUSER, wsiNG, Arrays.asList(BUSER), Permission.READ); //should have no effect expect.clear(); expect.put(AUSER, Permission.OWNER); expect.put(BUSER, Permission.READ); expect.put(CUSER, Permission.READ); assertThat("user setting same perms has no effect", ws.getPermissions(AUSER, wsiNG), is(expect)); expect.clear(); expect.put(BUSER, Permission.READ); assertThat("setting own perms to same has no effect", ws.getPermissions(BUSER, wsiNG), is(expect)); ws.setPermissions(BUSER, wsiNG, Arrays.asList(BUSER), Permission.NONE); expect.clear(); expect.put(AUSER, Permission.OWNER); expect.put(CUSER, Permission.READ); assertThat("user removed own perms", ws.getPermissions(AUSER, wsiNG), is(expect)); expect.clear(); expect.put(BUSER, Permission.NONE); assertThat("can remove own perms", ws.getPermissions(BUSER, wsiNG), is(expect)); //test write permissions ws.setPermissions(AUSER, wsiNG, Arrays.asList(BUSER), Permission.WRITE); expect.put(AUSER, Permission.OWNER); expect.put(BUSER, Permission.WRITE); expect.put(CUSER, Permission.READ); assertThat("ws doesn't replace owner perms", ws.getPermissions(AUSER, wsiNG), is(expect)); assertThat("write perms allow viewing all perms", ws.getPermissions(BUSER, wsiNG), is(expect)); expect.clear(); expect.put(CUSER, Permission.READ); assertThat("no permission leakage", ws.getPermissions(CUSER, wsiNG), is(expect)); failSetPermissions(BUSER, wsiNG, Arrays.asList(AUSER, BUSER, CUSER), Permission.READ, new WorkspaceAuthorizationException( "User b may not alter other user's permissions on workspace perms_noglobal")); //test admin permissions ws.setPermissions(AUSER, wsiNG, Arrays.asList(BUSER), Permission.ADMIN); expect.put(AUSER, Permission.OWNER); expect.put(BUSER, Permission.ADMIN); expect.put(CUSER, Permission.READ); assertThat("ws doesn't replace owner perms", ws.getPermissions(AUSER, wsiNG), is(expect)); assertThat("admin can see all perms", ws.getPermissions(BUSER, wsiNG), is(expect)); ws.setPermissions(BUSER, wsiNG, Arrays.asList(AUSER, CUSER), Permission.WRITE); expect.put(CUSER, Permission.WRITE); assertThat("ws doesn't replace owner perms", ws.getPermissions(AUSER, wsiNG), is(expect)); assertThat("admin can correctly set perms", ws.getPermissions(BUSER, wsiNG), is(expect)); //test remove permissions ws.setPermissions(BUSER, wsiNG, Arrays.asList(AUSER, CUSER), Permission.NONE); expect.remove(CUSER); assertThat("ws doesn't replace owner perms", ws.getPermissions(AUSER, wsiNG), is(expect)); assertThat("admin can't overwrite owner perms", ws.getPermissions(BUSER, wsiNG), is(expect)); ws.setGlobalPermission(AUSER, new WorkspaceIdentifier("perms_global"), Permission.NONE); } @Test public void saveObjectsAndGetMetaSimple() throws Exception { WorkspaceUser foo = new WorkspaceUser("foo"); WorkspaceUser bar = new WorkspaceUser("bar"); IdReferenceHandlerSetFactory foofac = getIdFactory(foo); IdReferenceHandlerSetFactory barfac = getIdFactory(bar); WorkspaceIdentifier read = new WorkspaceIdentifier("saveobjread"); WorkspaceIdentifier priv = new WorkspaceIdentifier("saveobj"); WorkspaceInformation readinfo = ws.createWorkspace( foo, read.getIdentifierString(), true, null, null); WorkspaceInformation privinfo = ws.createWorkspace( foo, priv.getIdentifierString(), false, null, null); Date readLastDate = readinfo.getModDate(); Date privLastDate = privinfo.getModDate(); long readid = readinfo.getId(); long privid = privinfo.getId(); Map<String, Object> data = new HashMap<String, Object>(); Map<String, Object> data2 = new HashMap<String, Object>(); Map<String, String> meta = new HashMap<String, String>(); Map<String, Object> moredata = new HashMap<String, Object>(); moredata.put("foo", "bar"); data.put("fubar", moredata); JsonNode savedata = MAPPER.valueToTree(data); data2.put("fubar2", moredata); JsonNode savedata2 = MAPPER.valueToTree(data2); meta.put("metastuff", "meta"); Map<String, String> meta2 = new HashMap<String, String>(); meta2.put("meta2", "my hovercraft is full of eels"); Provenance p = new Provenance(new WorkspaceUser("kbasetest2")); p.addAction(new Provenance.ProvenanceAction().withServiceName("some service")); List<WorkspaceSaveObject> objects = new ArrayList<WorkspaceSaveObject>(); try { ws.saveObjects(foo, read, objects, foofac); fail("Saved no objects"); } catch (IllegalArgumentException e) { assertThat("correct except", e.getLocalizedMessage(), is("No data provided")); } failGetObjects(foo, new ArrayList<ObjectIdentifier>(), new IllegalArgumentException( "No object identifiers provided")); try { ws.getObjectInformation(foo, new ArrayList<ObjectIdentifier>(), true, false); fail("called method with no identifiers"); } catch (IllegalArgumentException e) { assertThat("correct except", e.getLocalizedMessage(), is("No object identifiers provided")); } objects.add(new WorkspaceSaveObject(new ObjectIDNoWSNoVer("auto3"), savedata, SAFE_TYPE1, meta, p, false)); objects.add(new WorkspaceSaveObject(new ObjectIDNoWSNoVer("auto3"), savedata2, SAFE_TYPE1, meta2, p, false)); objects.add(new WorkspaceSaveObject(new ObjectIDNoWSNoVer("auto3-1"), savedata, SAFE_TYPE1, meta, p, false)); objects.add(new WorkspaceSaveObject(savedata2, SAFE_TYPE1, meta2, p, false)); objects.add(new WorkspaceSaveObject(savedata, SAFE_TYPE1, meta, p, false)); readLastDate = ws.getWorkspaceInformation(foo, read).getModDate(); List<ObjectInformation> objinfo = ws.saveObjects(foo, read, objects, foofac); readLastDate = assertWorkspaceDateUpdated(foo, read, readLastDate, "ws date modified on save"); String chksum1 = "36c4f68f2c98971b9736839232eb08f4"; String chksum2 = "3c59f762140806c36ab48a152f28e840"; checkObjInfo(objinfo.get(0), 1, "auto3", SAFE_TYPE1.getTypeString(), 1, foo, readid, read.getName(), chksum1, 23, meta); checkObjInfo(objinfo.get(1), 1, "auto3", SAFE_TYPE1.getTypeString(), 2, foo, readid, read.getName(), chksum2, 24, meta2); checkObjInfo(objinfo.get(2), 2, "auto3-1", SAFE_TYPE1.getTypeString(), 1, foo, readid, read.getName(), chksum1, 23, meta); checkObjInfo(objinfo.get(3), 3, "auto3-2", SAFE_TYPE1.getTypeString(), 1, foo, readid, read.getName(), chksum2, 24, meta2); checkObjInfo(objinfo.get(4), 4, "auto4", SAFE_TYPE1.getTypeString(), 1, foo, readid, read.getName(), chksum1, 23, meta); List<ObjectIdentifier> loi = new ArrayList<ObjectIdentifier>(); loi.add(new ObjectIdentifier(read, 1)); loi.add(new ObjectIdentifier(read, 1, 1)); loi.add(new ObjectIdentifier(new WorkspaceIdentifier(readid), "auto3")); loi.add(new ObjectIdentifier(new WorkspaceIdentifier(readid), "auto3", 1)); loi.add(new ObjectIdentifier(new WorkspaceIdentifier(readid), 1)); loi.add(new ObjectIdentifier(new WorkspaceIdentifier(readid), 1, 1)); loi.add(new ObjectIdentifier(read, "auto3")); loi.add(new ObjectIdentifier(read, "auto3", 1)); loi.add(new ObjectIdentifier(read, "auto3-2")); loi.add(new ObjectIdentifier(read, 3)); loi.add(new ObjectIdentifier(read, "auto3-2", 1)); loi.add(new ObjectIdentifier(read, 3, 1)); List<ObjectInformation> objinfo2 = ws.getObjectInformation(foo, loi, true, false); List<ObjectInformation> objinfo2NoMeta = ws.getObjectInformation(foo, loi, false, false); checkObjInfo(objinfo2.get(0), 1, "auto3", SAFE_TYPE1.getTypeString(), 2, foo, readid, read.getName(), chksum2, 24, meta2); checkObjInfo(objinfo2.get(1), 1, "auto3", SAFE_TYPE1.getTypeString(), 1, foo, readid, read.getName(), chksum1, 23, meta); checkObjInfo(objinfo2.get(2), 1, "auto3", SAFE_TYPE1.getTypeString(), 2, foo, readid, read.getName(), chksum2, 24, meta2); checkObjInfo(objinfo2.get(3), 1, "auto3", SAFE_TYPE1.getTypeString(), 1, foo, readid, read.getName(), chksum1, 23, meta); checkObjInfo(objinfo2.get(4), 1, "auto3", SAFE_TYPE1.getTypeString(), 2, foo, readid, read.getName(), chksum2, 24, meta2); checkObjInfo(objinfo2.get(5), 1, "auto3", SAFE_TYPE1.getTypeString(), 1, foo, readid, read.getName(), chksum1, 23, meta); checkObjInfo(objinfo2.get(6), 1, "auto3", SAFE_TYPE1.getTypeString(), 2, foo, readid, read.getName(), chksum2, 24, meta2); checkObjInfo(objinfo2.get(7), 1, "auto3", SAFE_TYPE1.getTypeString(), 1, foo, readid, read.getName(), chksum1, 23, meta); checkObjInfo(objinfo2.get(8), 3, "auto3-2", SAFE_TYPE1.getTypeString(), 1, foo, readid, read.getName(), chksum2, 24, meta2); checkObjInfo(objinfo2.get(9), 3, "auto3-2", SAFE_TYPE1.getTypeString(), 1, foo, readid, read.getName(), chksum2, 24, meta2); checkObjInfo(objinfo2.get(10), 3, "auto3-2", SAFE_TYPE1.getTypeString(), 1, foo, readid, read.getName(), chksum2, 24, meta2); checkObjInfo(objinfo2.get(11), 3, "auto3-2", SAFE_TYPE1.getTypeString(), 1, foo, readid, read.getName(), chksum2, 24, meta2); checkObjInfo(objinfo2NoMeta.get(0), 1, "auto3", SAFE_TYPE1.getTypeString(), 2, foo, readid, read.getName(), chksum2, 24, null); checkObjInfo(objinfo2NoMeta.get(1), 1, "auto3", SAFE_TYPE1.getTypeString(), 1, foo, readid, read.getName(), chksum1, 23, null); checkObjInfo(objinfo2NoMeta.get(2), 1, "auto3", SAFE_TYPE1.getTypeString(), 2, foo, readid, read.getName(), chksum2, 24, null); checkObjInfo(objinfo2NoMeta.get(3), 1, "auto3", SAFE_TYPE1.getTypeString(), 1, foo, readid, read.getName(), chksum1, 23, null); checkObjInfo(objinfo2NoMeta.get(4), 1, "auto3", SAFE_TYPE1.getTypeString(), 2, foo, readid, read.getName(), chksum2, 24, null); checkObjInfo(objinfo2NoMeta.get(5), 1, "auto3", SAFE_TYPE1.getTypeString(), 1, foo, readid, read.getName(), chksum1, 23, null); checkObjInfo(objinfo2NoMeta.get(6), 1, "auto3", SAFE_TYPE1.getTypeString(), 2, foo, readid, read.getName(), chksum2, 24, null); checkObjInfo(objinfo2NoMeta.get(7), 1, "auto3", SAFE_TYPE1.getTypeString(), 1, foo, readid, read.getName(), chksum1, 23, null); checkObjInfo(objinfo2NoMeta.get(8), 3, "auto3-2", SAFE_TYPE1.getTypeString(), 1, foo, readid, read.getName(), chksum2, 24, null); checkObjInfo(objinfo2NoMeta.get(9), 3, "auto3-2", SAFE_TYPE1.getTypeString(), 1, foo, readid, read.getName(), chksum2, 24, null); checkObjInfo(objinfo2NoMeta.get(10), 3, "auto3-2", SAFE_TYPE1.getTypeString(), 1, foo, readid, read.getName(), chksum2, 24, null); checkObjInfo(objinfo2NoMeta.get(11), 3, "auto3-2", SAFE_TYPE1.getTypeString(), 1, foo, readid, read.getName(), chksum2, 24, null); List<FakeObjectInfo> retinfo = new ArrayList<FakeObjectInfo>(); FakeResolvedWSID fakews = new FakeResolvedWSID(read.getName(), readid); retinfo.add(new FakeObjectInfo(1L, "auto3", SAFE_TYPE1.getTypeString(), new Date(), 2, foo, fakews, chksum2, 24L, meta2)); retinfo.add(new FakeObjectInfo(1, "auto3", SAFE_TYPE1.getTypeString(), new Date(), 1, foo, fakews, chksum1, 23, meta)); retinfo.add(new FakeObjectInfo(1, "auto3", SAFE_TYPE1.getTypeString(), new Date(), 2, foo, fakews, chksum2, 24, meta2)); retinfo.add(new FakeObjectInfo(1, "auto3", SAFE_TYPE1.getTypeString(), new Date(), 1, foo, fakews, chksum1, 23, meta)); retinfo.add(new FakeObjectInfo(1, "auto3", SAFE_TYPE1.getTypeString(), new Date(), 2, foo, fakews, chksum2, 24, meta2)); retinfo.add(new FakeObjectInfo(1, "auto3", SAFE_TYPE1.getTypeString(), new Date(), 1, foo, fakews, chksum1, 23, meta)); retinfo.add(new FakeObjectInfo(1, "auto3", SAFE_TYPE1.getTypeString(), new Date(), 2, foo, fakews, chksum2, 24, meta2)); retinfo.add(new FakeObjectInfo(1, "auto3", SAFE_TYPE1.getTypeString(), new Date(), 1, foo, fakews, chksum1, 23, meta)); retinfo.add(new FakeObjectInfo(3, "auto3-2", SAFE_TYPE1.getTypeString(), new Date(), 1, foo, fakews, chksum2, 24, meta2)); retinfo.add(new FakeObjectInfo(3, "auto3-2", SAFE_TYPE1.getTypeString(), new Date(), 1, foo, fakews, chksum2, 24, meta2)); retinfo.add(new FakeObjectInfo(3, "auto3-2", SAFE_TYPE1.getTypeString(), new Date(), 1, foo, fakews, chksum2, 24, meta2)); retinfo.add(new FakeObjectInfo(3, "auto3-2", SAFE_TYPE1.getTypeString(), new Date(), 1, foo, fakews, chksum2, 24, meta2)); List<Map<String, Object>> retdata = Arrays.asList( data2, data, data2, data, data2, data, data2, data, data2, data2, data2, data2); checkObjectAndInfo(foo, loi, retinfo, retdata); privLastDate = ws.getWorkspaceInformation(foo, priv).getModDate(); ws.saveObjects(foo, priv, objects, foofac); privLastDate = assertWorkspaceDateUpdated(foo, read, privLastDate, "ws date modified on save"); objects.clear(); objects.add(new WorkspaceSaveObject(new ObjectIDNoWSNoVer(2), savedata, SAFE_TYPE1, meta2, p, false)); objinfo = ws.saveObjects(foo, read, objects, foofac); ws.saveObjects(foo, priv, objects, foofac); checkObjInfo(objinfo.get(0), 2, "auto3-1", SAFE_TYPE1.getTypeString(), 2, foo, readid, read.getName(), chksum1, 23, meta2); objinfo2 = ws.getObjectInformation(foo, Arrays.asList(new ObjectIdentifier(read, 2)), true, false); checkObjInfo(objinfo2.get(0), 2, "auto3-1", SAFE_TYPE1.getTypeString(), 2, foo, readid, read.getName(), chksum1, 23, meta2); ws.getObjectInformation(bar, Arrays.asList(new ObjectIdentifier(read, 2)), true, false); //should work try { ws.getObjectInformation(bar, Arrays.asList(new ObjectIdentifier(priv, 2)), true, false); fail("Able to get obj meta from private workspace"); } catch (InaccessibleObjectException ioe) { assertThat("correct exception message", ioe.getLocalizedMessage(), is("Object 2 cannot be accessed: User bar may not read workspace saveobj")); assertThat("correct object returned", ioe.getInaccessibleObject(), is(new ObjectIdentifier(priv, 2))); } successGetObjects(bar, Arrays.asList(new ObjectIdentifier(read, 2))); try { ws.getObjects(bar, Arrays.asList(new ObjectIdentifier(priv, 2))); fail("Able to get obj data from private workspace"); } catch (InaccessibleObjectException ioe) { assertThat("correct exception message", ioe.getLocalizedMessage(), is("Object 2 cannot be accessed: User bar may not read workspace saveobj")); assertThat("correct object returned", ioe.getInaccessibleObject(), is(new ObjectIdentifier(priv, 2))); } ws.setPermissions(foo, priv, Arrays.asList(bar), Permission.READ); objinfo2 = ws.getObjectInformation(bar, Arrays.asList(new ObjectIdentifier(priv, 2)), true, false); checkObjInfo(objinfo2.get(0), 2, "auto3-1", SAFE_TYPE1.getTypeString(), 2, foo, privid, priv.getName(), chksum1, 23, meta2); checkObjectAndInfo(bar, Arrays.asList(new ObjectIdentifier(priv, 2)), Arrays.asList(new FakeObjectInfo(2L, "auto3-1", SAFE_TYPE1.getTypeString(), new Date(), 2, foo, new FakeResolvedWSID(priv.getName(), privid), chksum1, 23L, meta2)), Arrays.asList(data)); failSave(bar, priv, objects, new WorkspaceAuthorizationException("User bar may not write to workspace saveobj")); ws.setPermissions(foo, priv, Arrays.asList(bar), Permission.WRITE); objinfo = ws.saveObjects(bar, priv, objects, barfac); checkObjInfo(objinfo.get(0), 2, "auto3-1", SAFE_TYPE1.getTypeString(), 3, bar, privid, priv.getName(), chksum1, 23, meta2); failGetObjects(foo, Arrays.asList(new ObjectIdentifier(read, "booger")), new NoSuchObjectException("No object with name booger exists in workspace " + readid)); failGetObjects(foo, Arrays.asList(new ObjectIdentifier(new WorkspaceIdentifier("saveAndGetFakefake"), "booger")), new InaccessibleObjectException("Object booger cannot be accessed: No workspace with name saveAndGetFakefake exists")); ws.setPermissions(foo, priv, Arrays.asList(bar), Permission.NONE); failGetObjects(bar, Arrays.asList(new ObjectIdentifier(priv, 3)), new InaccessibleObjectException("Object 3 cannot be accessed: User bar may not read workspace saveobj")); failGetObjects(null, Arrays.asList(new ObjectIdentifier(priv, 3)), new InaccessibleObjectException("Object 3 cannot be accessed: Anonymous users may not read workspace saveobj")); //test get object info where null is returned instead of exception List<ObjectIdentifier> nullloi = new ArrayList<ObjectIdentifier>(); nullloi.add(new ObjectIdentifier(read, 1)); nullloi.add(new ObjectIdentifier(read, "booger")); nullloi.add(new ObjectIdentifier(new WorkspaceIdentifier("saveAndGetFakefake"), "booger")); nullloi.add(new ObjectIdentifier(read, 1, 1)); List<ObjectInformation> nullobjinfo = ws.getObjectInformation(foo, nullloi, true, true); checkObjInfo(nullobjinfo.get(0), 1, "auto3", SAFE_TYPE1.getTypeString(), 2, foo, readid, read.getName(), chksum2, 24, meta2); assertNull("Obj info is null for inaccessible object", nullobjinfo.get(1)); assertNull("Obj info is null for inaccessible object", nullobjinfo.get(2)); checkObjInfo(nullobjinfo.get(3), 1, "auto3", SAFE_TYPE1.getTypeString(), 1, foo, readid, read.getName(), chksum1, 23, meta); nullloi.clear(); nullloi.add(new ObjectIdentifier(new WorkspaceIdentifier(readid), "auto3")); nullloi.add(new ObjectIdentifier(priv, 2)); nullloi.add(new ObjectIdentifier(new WorkspaceIdentifier(readid), "auto3", 1)); nullloi.add(new ObjectIdentifier(priv, 3)); nullloi.add(new ObjectIdentifier(new WorkspaceIdentifier(readid), 1)); nullobjinfo = ws.getObjectInformation(bar, nullloi, false, true); checkObjInfo(nullobjinfo.get(0), 1, "auto3", SAFE_TYPE1.getTypeString(), 2, foo, readid, read.getName(), chksum2, 24, null); assertNull("Obj info is null for inaccessible object", nullobjinfo.get(1)); checkObjInfo(nullobjinfo.get(2), 1, "auto3", SAFE_TYPE1.getTypeString(), 1, foo, readid, read.getName(), chksum1, 23, null); assertNull("Obj info is null for inaccessible object", nullobjinfo.get(1)); checkObjInfo(nullobjinfo.get(4), 1, "auto3", SAFE_TYPE1.getTypeString(), 2, foo, readid, read.getName(), chksum2, 24, null); nullloi.clear(); nullloi.add(new ObjectIdentifier(new WorkspaceIdentifier(readid), 1, 1)); nullloi.add(new ObjectIdentifier(priv, 3)); nullloi.add(new ObjectIdentifier(read, "auto3")); nullobjinfo = ws.getObjectInformation(null, nullloi, true, true); checkObjInfo(nullobjinfo.get(0), 1, "auto3", SAFE_TYPE1.getTypeString(), 1, foo, readid, read.getName(), chksum1, 23, meta); assertNull("Obj info is null for inaccessible object", nullobjinfo.get(1)); checkObjInfo(nullobjinfo.get(2), 1, "auto3", SAFE_TYPE1.getTypeString(), 2, foo, readid, read.getName(), chksum2, 24, meta2); ws.setObjectsDeleted(foo, Arrays.asList(new ObjectIdentifier(priv, 3)), true); ws.setWorkspaceDeleted(foo, read, true); nullobjinfo = ws.getObjectInformation(null, nullloi, true, true); assertNull("Obj info is null for inaccessible object", nullobjinfo.get(0)); assertNull("Obj info is null for inaccessible object", nullobjinfo.get(1)); assertNull("Obj info is null for inaccessible object", nullobjinfo.get(2)); ws.setWorkspaceDeleted(foo, read, false); ws.setGlobalPermission(foo, read, Permission.NONE); } @Test public void saveObjectsAndTestExtractedMeta() throws Exception { String module = "TestMetaData"; String spec = "module " + module + " {" + "/* @metadata ws val \n@metadata ws length(l) as Length of list*/"+ "typedef structure { string val; list<int> l; } MyType;" + "};"; WorkspaceUser userfoo = new WorkspaceUser("foo"); ws.requestModuleRegistration(userfoo, module); ws.resolveModuleRegistration(module, true); ws.compileNewTypeSpec(userfoo, spec, Arrays.asList("MyType"), null, null, false, null); TypeDefId MyType = new TypeDefId(new TypeDefName(module, "MyType"), 0, 1); WorkspaceIdentifier wspace = new WorkspaceIdentifier("metadatatest"); ws.createWorkspace(userfoo, wspace.getName(), false, null, null); Provenance emptyprov = new Provenance(userfoo); // save an object and get back object info Map<String, Object> d1 = new LinkedHashMap<String, Object>(); String val = "i should be a metadata"; d1.put("val", val); d1.put("l", Arrays.asList(1,2,3,4,5,6,7,8)); Map<String, String> metadata = new HashMap<String, String>(); ws.saveObjects(userfoo, wspace, Arrays.asList( new WorkspaceSaveObject(new ObjectIDNoWSNoVer("d1"),d1, MyType, metadata, emptyprov, false)), getIdFactory(userfoo)); List <ObjectInformation> oi = ws.getObjectInformation(userfoo, Arrays.asList(new ObjectIdentifier(wspace, "d1")), true, true); Assert.assertNotNull("Getting back an object that was saved with automatic metadata extraction", oi); Assert.assertNotNull("Getting back an object that was saved with automatic metadata extraction", oi.get(0)); // check that automatic metadata fields were populated correctly, and nothing else was added Map<String,String> savedUserMetaData = oi.get(0).getUserMetaData(); for(Entry<String,String> m : savedUserMetaData.entrySet()) { if(m.getKey().equals("val")) Assert.assertTrue("Extracted metadata must be correct",m.getValue().equals(val)); if(m.getKey().equals("Length of list")) Assert.assertTrue("Extracted metadata must be correct",m.getValue().equals("8")); } savedUserMetaData.remove("val"); savedUserMetaData.remove("Length of list"); Assert.assertEquals("Only metadata we wanted was extracted", 0, savedUserMetaData.size()); // now we do the same thing, but make sure 1) metadata set was added, and 2) metadata is overridden // by the extracted metadata metadata.put("Length of list","i am pretty sure it was 7"); metadata.put("my_special_metadata", "yes"); ws.saveObjects(userfoo, wspace, Arrays.asList( new WorkspaceSaveObject(new ObjectIDNoWSNoVer("d2"),d1, MyType, metadata, emptyprov, false)), getIdFactory(userfoo)); List <ObjectInformation> oi2 = ws.getObjectInformation(userfoo, Arrays.asList(new ObjectIdentifier(wspace, "d2")), true, true); Assert.assertNotNull("Getting back an object that was saved with automatic metadata extraction", oi2); Assert.assertNotNull("Getting back an object that was saved with automatic metadata extraction", oi2.get(0)); savedUserMetaData = oi2.get(0).getUserMetaData(); for(Entry<String,String> m : savedUserMetaData.entrySet()) { if(m.getKey().equals("val")) Assert.assertTrue("Extracted metadata must be correct",m.getValue().equals(val)); if(m.getKey().equals("Length of list")) Assert.assertTrue("Extracted metadata must be correct",m.getValue().equals("8")); if(m.getKey().equals("my_special_metadata")) Assert.assertTrue("Extracted metadata must be correct",m.getValue().equals("yes")); } savedUserMetaData.remove("val"); savedUserMetaData.remove("Length of list"); savedUserMetaData.remove("my_special_metadata"); Assert.assertEquals("Only metadata we wanted was extracted", 0, savedUserMetaData.size()); // finally, test that if we exceed the metadata extraction limit, we fail Map<String, Object> dBig = new LinkedHashMap<String, Object>(); dBig.put("l", Arrays.asList(1,2,3,4,5,6,7,8)); StringBuilder bigVal = new StringBuilder(); for (int i = 0; i < 18; i++) { bigVal.append(LONG_TEXT); //> 16kb now } dBig.put("val", bigVal.toString()); try { ws.saveObjects(userfoo, wspace, Arrays.asList(new WorkspaceSaveObject( new ObjectIDNoWSNoVer("bigextractedmeta"), dBig, MyType, null, emptyprov, false)), getIdFactory(userfoo)); fail("saved object with > 16kb of extracted metadata"); } catch (IllegalArgumentException iae) { assertThat("correct exception", iae.getLocalizedMessage(), is("Object #1, bigextractedmeta : Object metadata size (19309 bytes) after adding metadata field 'val' exceeds limit of 16000 bytes")); } } @Test public void encodings() throws Exception { WorkspaceUser user = new WorkspaceUser("encodings"); WorkspaceIdentifier wspace = new WorkspaceIdentifier("encodings"); ws.createWorkspace(user, wspace.getName(), false, null, null); Provenance emptyprov = new Provenance(user); StringBuffer sb = new StringBuffer(); sb.appendCodePoint(0x1F082); sb.append("a"); sb.appendCodePoint(0x1F0C6); sb.append("b"); sb.appendCodePoint(0x23824); sb.append("c"); sb.appendCodePoint(0x1685); sb.append("d"); sb.appendCodePoint(0x13B2); sb.append("e"); sb.appendCodePoint(0x06E9); String s = sb.toString() + sb.toString(); Map<String, Object> craycraymap = new HashMap<String, Object>(); craycraymap.put(s + "42", Arrays.asList(s, s + "woot", s)); craycraymap.put(s + "6", s); craycraymap.put(s + "3012", 1); String jsondata = MAPPER.writeValueAsString(craycraymap); List<Charset> csets = Arrays.asList(Charset.forName("UTF-8"), Charset.forName("UTF-16LE"), Charset.forName("UTF-16BE"), Charset.forName("UTF-32LE"), Charset.forName("UTF-32BE")); List<WorkspaceSaveObject> objs = new LinkedList<WorkspaceSaveObject>(); for (Charset cs: csets) { objs.add(new WorkspaceSaveObject(new JsonTokenStream(jsondata.getBytes(cs)), SAFE_TYPE1, null, emptyprov, false)); } ws.saveObjects(user, wspace, objs, getIdFactory(user)); List<WorkspaceObjectData> ret = ws.getObjects(user, Arrays.asList( new ObjectIdentifier(wspace, 1), new ObjectIdentifier(wspace, 2), new ObjectIdentifier(wspace, 3), new ObjectIdentifier(wspace, 4), new ObjectIdentifier(wspace, 5))); for (WorkspaceObjectData wod: ret) { assertThat("got correct object input in various encodings", wod.getData(), is((Object) craycraymap)); } } @Test public void saveNonStructuralObjects() throws Exception { String module = "TestNonStruct"; String spec = "module " + module + " {" + "typedef string type1;" + "typedef list<string> type2;" + "typedef mapping<string, string> type3;" + "typedef tuple<string, string> type4;" + "typedef structure { string val; } type5;" + "};"; WorkspaceUser userfoo = new WorkspaceUser("foo"); ws.requestModuleRegistration(userfoo, module); ws.resolveModuleRegistration(module, true); ws.compileNewTypeSpec(userfoo, spec, Arrays.asList( "type1", "type2", "type3", "type4", "type5"), null, null, false, null); TypeDefId abstype1 = new TypeDefId(new TypeDefName(module, "type1"), 0, 1); TypeDefId abstype2 = new TypeDefId(new TypeDefName(module, "type2"), 0, 1); TypeDefId abstype3 = new TypeDefId(new TypeDefName(module, "type3"), 0, 1); TypeDefId abstype4 = new TypeDefId(new TypeDefName(module, "type4"), 0, 1); TypeDefId abstype5 = new TypeDefId(new TypeDefName(module, "type5"), 0, 1); WorkspaceIdentifier wspace = new WorkspaceIdentifier("nonstruct"); ws.createWorkspace(userfoo, wspace.getName(), false, null, null); Provenance emptyprov = new Provenance(userfoo); Map<String, String> data3 = new HashMap<String, String>(); data3.put("val", "2"); try { ws.saveObjects(userfoo, wspace, Arrays.asList( new WorkspaceSaveObject("data1", abstype1, null, emptyprov, false)), getIdFactory(userfoo)); Assert.fail("Method works but shouldn't"); } catch (TypedObjectValidationException ex) { Assert.assertTrue(ex.getMessage(), ex.getMessage().contains("structure")); } try { ws.saveObjects(userfoo, wspace, Arrays.asList( new WorkspaceSaveObject(Arrays.asList("data2"), abstype2, null, emptyprov, false)), getIdFactory(userfoo)); Assert.fail("Method works but shouldn't"); } catch (TypedObjectValidationException ex) { Assert.assertTrue(ex.getMessage(), ex.getMessage().contains("structure")); } try { ws.saveObjects(userfoo, wspace, Arrays.asList( new WorkspaceSaveObject(data3, abstype3, null, emptyprov, false)), getIdFactory(userfoo)); Assert.fail("Method works but shouldn't"); } catch (TypedObjectValidationException ex) { Assert.assertTrue(ex.getMessage(), ex.getMessage().contains("structure")); } try { ws.saveObjects(userfoo, wspace, Arrays.asList( new WorkspaceSaveObject(Arrays.asList("data4", "data4"), abstype4, null, emptyprov, false)), getIdFactory(userfoo)); Assert.fail("Method works but shouldn't"); } catch (TypedObjectValidationException ex) { Assert.assertTrue(ex.getMessage(), ex.getMessage().contains("structure")); } ws.saveObjects(userfoo, wspace, Arrays.asList( new WorkspaceSaveObject(data3, abstype5, null, emptyprov, false)), getIdFactory(userfoo)); } @SuppressWarnings("unchecked") @Test public void saveNulls() throws Exception { String module = "TestNull"; String spec = "module " + module + " {" + "typedef structure { " + " string val1; " + " int val2; " + " float val3; " + "} type1; " + "typedef structure { " + " list<string> val; " + "} type2;" + "typedef structure { " + " mapping<string,string> val; " + "} type3;" + "typedef structure { " + " tuple<string,string> val; " + "} type4;" + "typedef structure { " + " list<int> val; " + "} type5;" + "typedef structure { " + " list<float> val; " + "} type6;" + "};"; WorkspaceUser userfoo = new WorkspaceUser("foo"); ws.requestModuleRegistration(userfoo, module); ws.resolveModuleRegistration(module, true); ws.compileNewTypeSpec(userfoo, spec, Arrays.asList( "type1", "type2", "type3", "type4", "type5", "type6"), null, null, false, null); WorkspaceIdentifier wspace = new WorkspaceIdentifier("nulls"); ws.createWorkspace(userfoo, wspace.getName(), false, null, null); Provenance emptyprov = new Provenance(userfoo); TypeDefId abstype1 = new TypeDefId(new TypeDefName(module, "type1"), 0, 1); TypeDefId abstype2 = new TypeDefId(new TypeDefName(module, "type2"), 0, 1); TypeDefId abstype3 = new TypeDefId(new TypeDefName(module, "type3"), 0, 1); TypeDefId abstype4 = new TypeDefId(new TypeDefName(module, "type4"), 0, 1); TypeDefId abstype5 = new TypeDefId(new TypeDefName(module, "type5"), 0, 1); TypeDefId abstype6 = new TypeDefId(new TypeDefName(module, "type6"), 0, 1); Set<String> keys = new TreeSet<String>(Arrays.asList("val1", "val2", "val3")); //TODO should try these tests with bytes vs. maps Map<String, Object> data1 = new LinkedHashMap<String, Object>(); data1.put("val3", null); data1.put("val2", null); data1.put("val1", null); Assert.assertEquals(keys, new TreeSet<String>(data1.keySet())); Assert.assertTrue(data1.containsKey("val1")); Assert.assertNull(data1.get("val1")); long data1id = ws.saveObjects(userfoo, wspace, Arrays.asList( new WorkspaceSaveObject(data1, abstype1, null, emptyprov, false)), getIdFactory(userfoo)).get(0).getObjectId(); Map<String, Object> data1copy = (Map<String, Object>)ws.getObjects(userfoo, Arrays.asList( new ObjectIdentifier(wspace, data1id))).get(0).getData(); Assert.assertEquals(keys, new TreeSet<String>(data1copy.keySet())); Map<String, Object> data2 = new LinkedHashMap<String, Object>(); data2.put("val", null); failSave(userfoo, wspace, Arrays.asList( new WorkspaceSaveObject(data2, abstype2, null, emptyprov, false)), new TypedObjectValidationException( "Object #1 failed type checking:\ninstance type (null) does not match any allowed primitive type (allowed: [\"array\"]), at /val")); data2.put("val", Arrays.asList((String)null)); ws.saveObjects(userfoo, wspace, Arrays.asList( new WorkspaceSaveObject(data2, abstype2, null, emptyprov, false)), getIdFactory(userfoo)); Map<String, Object> data3 = new LinkedHashMap<String, Object>(); data3.put("val", null); failSave(userfoo, wspace, Arrays.asList( new WorkspaceSaveObject(data3, abstype3, null, emptyprov, false)), new TypedObjectValidationException( "Object #1 failed type checking:\ninstance type (null) does not match any allowed primitive type (allowed: [\"object\"]), at /val")); Map<String, Object> innerMap = new LinkedHashMap<String, Object>(); innerMap.put("key", null); data3.put("val", innerMap); ws.saveObjects(userfoo, wspace, Arrays.asList( new WorkspaceSaveObject(data3, abstype3, null, emptyprov, false)), getIdFactory(userfoo)); innerMap.put(null, "foo"); failSave(userfoo, wspace, Arrays.asList( new WorkspaceSaveObject(data3, abstype3, null, emptyprov, false)), new TypedObjectValidationException( "Object #1 failed type checking:\nKeys in maps/structures may not be null")); Map<String, Object> data4 = new LinkedHashMap<String, Object>(); data4.put("val", null); failSave(userfoo, wspace, Arrays.asList( new WorkspaceSaveObject(data4, abstype4, null, emptyprov, false)), new TypedObjectValidationException( "Object #1 failed type checking:\ninstance type (null) does not match any allowed primitive type (allowed: [\"array\"]), at /val")); data4.put("val", Arrays.asList((String)null, (String)null)); ws.saveObjects(userfoo, wspace, Arrays.asList( new WorkspaceSaveObject(data4, abstype4, null, emptyprov, false)), getIdFactory(userfoo)); Map<String, Object> data5 = new LinkedHashMap<String, Object>(); data5.put("val", Arrays.asList(2, (Integer)null, 1)); ws.saveObjects(userfoo, wspace, Arrays.asList( new WorkspaceSaveObject(data5, abstype5, null, emptyprov, false)), getIdFactory(userfoo)); Map<String, Object> data6 = new LinkedHashMap<String, Object>(); data6.put("val", Arrays.asList(1.2, (Float)null, 3.6)); ws.saveObjects(userfoo, wspace, Arrays.asList( new WorkspaceSaveObject(data6, abstype6, null, emptyprov, false)), getIdFactory(userfoo)); } @Test public void saveObjectWithTypeChecking() throws Exception { final String specTypeCheck1 = "module TestTypeChecking {" + "/* @id ws */" + "typedef string reference;" + "typedef string some_id2;" + "/* @optional ref */ " + "typedef structure {" + "int foo;" + "list<int> bar;" + "string baz;" + "reference ref;" + "} CheckType;" + "};"; final String specTypeCheck2 = "module TestTypeChecking {" + "/* @id ws */" + "typedef string reference;" + "/* @optional ref\n" + " @optional map */" + "typedef structure {" + "int foo;" + "list<int> bar;" + "int baz;" + "reference ref;" + "mapping<string, string> map;" + "} CheckType;" + "};"; final String specTypeCheckRefs = "module TestTypeCheckingRefType {" + "/* @id ws TestTypeChecking.CheckType */" + "typedef string reference;" + "/* @optional refmap */" + "typedef structure {" + "int foo;" + "list<int> bar;" + "string baz;" + "reference ref;" + "mapping<reference, string> refmap;" + "} CheckRefType;" + "};"; String mod = "TestTypeChecking"; WorkspaceUser userfoo = new WorkspaceUser("foo"); ws.requestModuleRegistration(userfoo, mod); ws.resolveModuleRegistration(mod, true); ws.compileNewTypeSpec(userfoo, specTypeCheck1, Arrays.asList("CheckType"), null, null, false, null); TypeDefId abstype0 = new TypeDefId(new TypeDefName(mod, "CheckType"), 0, 1); TypeDefId abstype1 = new TypeDefId(new TypeDefName(mod, "CheckType"), 1, 0); TypeDefId abstype2 = new TypeDefId(new TypeDefName(mod, "CheckType"), 2, 0); TypeDefId relmintype0 = new TypeDefId(new TypeDefName(mod, "CheckType"), 0); TypeDefId relmintype1 = new TypeDefId(new TypeDefName(mod, "CheckType"), 1); TypeDefId relmintype2 = new TypeDefId(new TypeDefName(mod, "CheckType"), 2); TypeDefId relmaxtype = new TypeDefId(new TypeDefName(mod, "CheckType")); // test basic type checking with different versions WorkspaceIdentifier wspace = new WorkspaceIdentifier("typecheck"); ws.createWorkspace(userfoo, wspace.getName(), false, null, null); Provenance emptyprov = new Provenance(userfoo); Map<String, Object> data1 = new HashMap<String, Object>(); data1.put("foo", 3); data1.put("baz", "astring"); data1.put("bar", Arrays.asList(-3, 1, 234567890)); ws.saveObjects(userfoo, wspace, Arrays.asList( new WorkspaceSaveObject(data1, abstype0, null, emptyprov, false)), getIdFactory(userfoo)); //should work failSave(userfoo, wspace, data1, new TypeDefId("NoModHere.Foo"), emptyprov, new TypedObjectValidationException( "Object #1 failed type checking:\nModule doesn't exist: NoModHere")); failSave(userfoo, wspace, data1, new TypeDefId("SomeModule.Foo"), emptyprov, new TypedObjectValidationException( "Object #1 failed type checking:\nUnable to locate type: SomeModule.Foo")); failSave(userfoo, wspace, data1, relmintype0, emptyprov, new TypedObjectValidationException( "Object #1 failed type checking:\nThis type wasn't released yet and you should be an owner to access unreleased version information")); failSave(userfoo, wspace, data1, relmintype1, emptyprov, new TypedObjectValidationException( "Object #1 failed type checking:\nUnable to locate type: TestTypeChecking.CheckType-1")); failSave(userfoo, wspace, data1, abstype1, emptyprov, new TypedObjectValidationException( "Object #1 failed type checking:\nUnable to locate type: TestTypeChecking.CheckType-1.0")); failSave(userfoo, wspace, data1, relmaxtype, emptyprov, new TypedObjectValidationException( "Object #1 failed type checking:\nThis type wasn't released yet and you should be an owner to access unreleased version information")); ws.releaseTypes(userfoo, mod); ws.saveObjects(userfoo, wspace, Arrays.asList( //should work new WorkspaceSaveObject(data1, relmaxtype, null, emptyprov, false)), getIdFactory(userfoo)); ws.saveObjects(userfoo, wspace, Arrays.asList( //should work new WorkspaceSaveObject(data1, abstype0, null, emptyprov, false)), getIdFactory(userfoo)); ws.saveObjects(userfoo, wspace, Arrays.asList( //should work new WorkspaceSaveObject(data1, abstype1, null, emptyprov, false)), getIdFactory(userfoo)); failSave(userfoo, wspace, data1, relmintype0, emptyprov, new TypedObjectValidationException( "Object #1 failed type checking:\nThis type wasn't released yet and you should be an owner to access unreleased version information")); ws.saveObjects(userfoo, wspace, Arrays.asList( //should work new WorkspaceSaveObject(data1, relmintype1, null, emptyprov, false)), getIdFactory(userfoo)); failSave(userfoo, wspace, data1, relmintype2, emptyprov, new TypedObjectValidationException( "Object #1 failed type checking:\nUnable to locate type: TestTypeChecking.CheckType-2")); ws.compileNewTypeSpec(userfoo, specTypeCheck2, null, null, null, false, null); ws.saveObjects(userfoo, wspace, Arrays.asList( //should work new WorkspaceSaveObject(data1, relmaxtype, null, emptyprov, false)), getIdFactory(userfoo)); ws.saveObjects(userfoo, wspace, Arrays.asList( //should work new WorkspaceSaveObject(data1, relmintype1, null, emptyprov, false)), getIdFactory(userfoo)); ws.saveObjects(userfoo, wspace, Arrays.asList( //should work new WorkspaceSaveObject(data1, abstype0, null, emptyprov, false)), getIdFactory(userfoo)); ws.saveObjects(userfoo, wspace, Arrays.asList( //should work new WorkspaceSaveObject(data1, abstype1, null, emptyprov, false)), getIdFactory(userfoo)); failSave(userfoo, wspace, data1, abstype2, emptyprov, new TypedObjectValidationException( "Object #1 failed type checking:\ninstance type (string) does not match any allowed primitive type (allowed: [\"integer\"]), at /baz")); failSave(userfoo, wspace, data1, relmintype2, emptyprov, new TypedObjectValidationException( "Object #1 failed type checking:\nThis type wasn't released yet and you should be an owner to access unreleased version information")); Map<String, Object> newdata = new HashMap<String, Object>(data1); newdata.put("baz", 1); ws.saveObjects(userfoo, wspace, Arrays.asList( new WorkspaceSaveObject(newdata, abstype2 , null, emptyprov, false)), getIdFactory(userfoo)); failSave(userfoo, wspace, newdata, abstype0, emptyprov, new TypedObjectValidationException( "Object #1 failed type checking:\ninstance type (integer) does not match any allowed primitive type (allowed: [\"string\"]), at /baz")); failSave(userfoo, wspace, newdata, abstype1, emptyprov, new TypedObjectValidationException( "Object #1 failed type checking:\ninstance type (integer) does not match any allowed primitive type (allowed: [\"string\"]), at /baz")); failSave(userfoo, wspace, newdata, relmaxtype, emptyprov, new TypedObjectValidationException( "Object #1 failed type checking:\ninstance type (integer) does not match any allowed primitive type (allowed: [\"string\"]), at /baz")); failSave(userfoo, wspace, newdata, relmintype1, emptyprov, new TypedObjectValidationException( "Object #1 failed type checking:\ninstance type (integer) does not match any allowed primitive type (allowed: [\"string\"]), at /baz")); failSave(userfoo, wspace, newdata, relmintype2, emptyprov, new TypedObjectValidationException( "Object #1 failed type checking:\nThis type wasn't released yet and you should be an owner to access unreleased version information")); ws.releaseTypes(userfoo, mod); failSave(userfoo, wspace, data1, relmaxtype, emptyprov, new TypedObjectValidationException( "Object #1 failed type checking:\ninstance type (string) does not match any allowed primitive type (allowed: [\"integer\"]), at /baz")); ws.saveObjects(userfoo, wspace, Arrays.asList( //should work new WorkspaceSaveObject(data1, relmintype1, null, emptyprov, false)), getIdFactory(userfoo)); ws.saveObjects(userfoo, wspace, Arrays.asList( //should work new WorkspaceSaveObject(data1, abstype0, null, emptyprov, false)), getIdFactory(userfoo)); ws.saveObjects(userfoo, wspace, Arrays.asList( //should work new WorkspaceSaveObject(data1, abstype1, null, emptyprov, false)), getIdFactory(userfoo)); failSave(userfoo, wspace, data1, abstype2, emptyprov, new TypedObjectValidationException( "Object #1 failed type checking:\ninstance type (string) does not match any allowed primitive type (allowed: [\"integer\"]), at /baz")); failSave(userfoo, wspace, data1, relmintype2, emptyprov, new TypedObjectValidationException( "Object #1 failed type checking:\ninstance type (string) does not match any allowed primitive type (allowed: [\"integer\"]), at /baz")); ws.saveObjects(userfoo, wspace, Arrays.asList( new WorkspaceSaveObject(newdata, abstype2 , null, emptyprov, false)), getIdFactory(userfoo)); failSave(userfoo, wspace, newdata, abstype0, emptyprov, new TypedObjectValidationException( "Object #1 failed type checking:\ninstance type (integer) does not match any allowed primitive type (allowed: [\"string\"]), at /baz")); failSave(userfoo, wspace, newdata, abstype1, emptyprov, new TypedObjectValidationException( "Object #1 failed type checking:\ninstance type (integer) does not match any allowed primitive type (allowed: [\"string\"]), at /baz")); ws.saveObjects(userfoo, wspace, Arrays.asList( //should work new WorkspaceSaveObject(newdata, relmaxtype, null, emptyprov, false)), getIdFactory(userfoo)); failSave(userfoo, wspace, newdata, relmintype1, emptyprov, new TypedObjectValidationException( "Object #1 failed type checking:\ninstance type (integer) does not match any allowed primitive type (allowed: [\"string\"]), at /baz")); ws.saveObjects(userfoo, wspace, Arrays.asList( //should work new WorkspaceSaveObject(newdata, relmintype2, null, emptyprov, false)), getIdFactory(userfoo)); // test non-parseable references and typechecking with object count List<WorkspaceSaveObject> data = new ArrayList<WorkspaceSaveObject>(); data.add(new WorkspaceSaveObject(data1, abstype0, null, emptyprov, false)); Map<String, Object> data2 = new HashMap<String, Object>(data1); data2.put("bar", Arrays.asList(-3, 1, "anotherstring")); data.add(new WorkspaceSaveObject(data2, abstype0, null, emptyprov, false)); failSave(userfoo, wspace, data, new TypedObjectValidationException( "Object #2 failed type checking:\ninstance type (string) does not match any allowed primitive type (allowed: [\"integer\"]), at /bar/2")); data.set(1, new WorkspaceSaveObject(data2, abstype2, null, emptyprov, false)); @SuppressWarnings("unchecked") List<Integer> intlist = (List<Integer>) data2.get("bar"); intlist.set(2, 42); Map<String, Object> inner = new HashMap<String, Object>(); inner.put("amapkey", 42); data2.put("map", inner); data2.put("baz", 1); failSave(userfoo, wspace, data, new TypedObjectValidationException( "Object #2 failed type checking:\ninstance type (integer) does not match any allowed primitive type (allowed: [\"string\"]), at /map/amapkey")); Map<String, Object> data3 = new HashMap<String, Object>(data1); data3.put("ref", "typecheck/1/1"); data.set(1, new WorkspaceSaveObject(data3, abstype0, null, emptyprov, false)); ws.saveObjects(userfoo, wspace, data, getIdFactory(userfoo)); //should work Map<String, Object> data4 = new HashMap<String, Object>(data1); data4.put("ref", "foo/bar/baz"); data.set(1, new WorkspaceSaveObject(data4, abstype0, null, emptyprov, false)); failSave(userfoo, wspace, data, new TypedObjectValidationException( "Object #2 has unparseable reference foo/bar/baz: Unable to parse version portion of object reference foo/bar/baz to an integer at /ref")); Map<String, Object> data5 = new HashMap<String, Object>(data1); data5.put("ref", null); data.set(1, new WorkspaceSaveObject(data5, abstype0, null, emptyprov, false)); failSave(userfoo, wspace, data, new TypedObjectValidationException( "Object #2 failed type checking:\ninstance type (null) not allowed for ID reference (allowed: [\"string\"]), at /ref")); Map<String, Object> data6 = new HashMap<String, Object>(data1); data6.put("ref", ""); data.set(1, new WorkspaceSaveObject(data6, abstype0, null, emptyprov, false)); failSave(userfoo, wspace, data, new TypedObjectValidationException( "Object #2 failed type checking:\nUnparseable id of type ws: IDs may not be null or the empty string at /ref")); Provenance goodids = new Provenance(userfoo); goodids.addAction(new Provenance.ProvenanceAction().withWorkspaceObjects(Arrays.asList("typecheck/1/1"))); data.set(1, new WorkspaceSaveObject(data3, abstype0, null, goodids, false)); ws.saveObjects(userfoo, wspace, data, getIdFactory(userfoo)); //should work Provenance badids = new Provenance(userfoo); badids.addAction(new Provenance.ProvenanceAction().withWorkspaceObjects(Arrays.asList("foo/bar/baz"))); data.set(1, new WorkspaceSaveObject(data3, abstype0, null, badids, false)); failSave(userfoo, wspace, data, new TypedObjectValidationException( "Object #2 has unparseable provenance reference foo/bar/baz: Unable to parse version portion of object reference foo/bar/baz to an integer")); badids = new Provenance(userfoo); badids.addAction(new Provenance.ProvenanceAction().withWorkspaceObjects(Arrays.asList((String) null))); data.set(1, new WorkspaceSaveObject(data3, abstype0, null, badids, false)); failSave(userfoo, wspace, data, new TypedObjectValidationException( "Object #2 has a null provenance reference")); badids = new Provenance(userfoo); badids.addAction(new Provenance.ProvenanceAction().withWorkspaceObjects(Arrays.asList(""))); data.set(1, new WorkspaceSaveObject(data3, abstype0, null, badids, false)); failSave(userfoo, wspace, data, new TypedObjectValidationException( "Object #2 has invalid provenance reference: IDs may not be null or the empty string")); //test inaccessible references due to missing, deleted, or unreadable workspaces Map<String, Object> refdata = new HashMap<String, Object>(data1); refdata.put("ref", "thereisnoworkspaceofthisname/2/1"); failSave(userfoo, wspace, refdata, abstype0, emptyprov, new TypedObjectValidationException( "Object #1 has invalid reference: No read access to id thereisnoworkspaceofthisname/2/1: Object 2 cannot be accessed: No workspace with name thereisnoworkspaceofthisname exists at /ref")); Provenance nowsref = new Provenance(userfoo); nowsref.addAction(new Provenance.ProvenanceAction().withWorkspaceObjects(Arrays.asList("thereisnoworkspaceofthisname/2/1"))); failSave(userfoo, wspace, data1, abstype0, nowsref, new TypedObjectValidationException( "Object #1 has invalid provenance reference: No read access to id thereisnoworkspaceofthisname/2/1: Object 2 cannot be accessed: No workspace with name thereisnoworkspaceofthisname exists")); ws.createWorkspace(userfoo, "tobedeleted", false, null, null); ws.setWorkspaceDeleted(userfoo, new WorkspaceIdentifier("tobedeleted"), true); refdata.put("ref", "tobedeleted/2/1"); failSave(userfoo, wspace, refdata, abstype0, emptyprov, new TypedObjectValidationException( "Object #1 has invalid reference: No read access to id tobedeleted/2/1: Object 2 cannot be accessed: Workspace tobedeleted is deleted at /ref")); Provenance delwsref = new Provenance(userfoo); delwsref.addAction(new Provenance.ProvenanceAction().withWorkspaceObjects(Arrays.asList("tobedeleted/2/1"))); failSave(userfoo, wspace, data1, abstype0, delwsref, new TypedObjectValidationException( "Object #1 has invalid provenance reference: No read access to id tobedeleted/2/1: Object 2 cannot be accessed: Workspace tobedeleted is deleted")); ws.createWorkspace(new WorkspaceUser("stingyuser"), "stingyworkspace", false, null, null); refdata.put("ref", "stingyworkspace/2/1"); failSave(userfoo, wspace, refdata, abstype0, emptyprov, new TypedObjectValidationException( "Object #1 has invalid reference: No read access to id stingyworkspace/2/1: Object 2 cannot be accessed: User foo may not read workspace stingyworkspace at /ref")); Provenance privwsref = new Provenance(userfoo); privwsref.addAction(new Provenance.ProvenanceAction().withWorkspaceObjects(Arrays.asList("stingyworkspace/2/1"))); failSave(userfoo, wspace, data1, abstype0, privwsref, new TypedObjectValidationException( "Object #1 has invalid provenance reference: No read access to id stingyworkspace/2/1: Object 2 cannot be accessed: User foo may not read workspace stingyworkspace")); //test inaccessible reference due to missing or deleted objects, incl bad versions ws.createWorkspace(userfoo, "referencetesting", false, null, null); WorkspaceIdentifier reftest = new WorkspaceIdentifier("referencetesting"); ws.saveObjects(userfoo, reftest, Arrays.asList( new WorkspaceSaveObject(newdata, abstype2 , null, emptyprov, false)), getIdFactory(userfoo)); refdata.put("ref", "referencetesting/1/1"); ws.saveObjects(userfoo, wspace, Arrays.asList( new WorkspaceSaveObject(refdata, abstype1 , null, emptyprov, false)), getIdFactory(userfoo)); Provenance goodref = new Provenance(userfoo); goodref.addAction(new Provenance.ProvenanceAction().withWorkspaceObjects(Arrays.asList("referencetesting/1/1"))); ws.saveObjects(userfoo, wspace, Arrays.asList( new WorkspaceSaveObject(refdata, abstype1 , null, goodref, false)), getIdFactory(userfoo)); refdata.put("ref", "referencetesting/2/1"); long refwsid = ws.getWorkspaceInformation(userfoo, reftest).getId(); failSave(userfoo, wspace, refdata, abstype0, emptyprov, new TypedObjectValidationException( "Object #1 has invalid reference: There is no object with id referencetesting/2/1: No object with id 2 exists in workspace " + refwsid + " at /ref")); Provenance noobjref = new Provenance(userfoo); noobjref.addAction(new Provenance.ProvenanceAction().withWorkspaceObjects(Arrays.asList("referencetesting/2/1"))); failSave(userfoo, wspace, data1, abstype0, noobjref, new TypedObjectValidationException( "Object #1 has invalid provenance reference: There is no object with id referencetesting/2/1: No object with id 2 exists in workspace " + refwsid)); ws.saveObjects(userfoo, reftest, Arrays.asList( new WorkspaceSaveObject(newdata, abstype2 , null, emptyprov, false)), getIdFactory(userfoo)); ws.setObjectsDeleted(userfoo, Arrays.asList(new ObjectIdentifier(reftest, 2)), true); failSave(userfoo, wspace, refdata, abstype0, emptyprov, new TypedObjectValidationException(String.format( "Object #1 has invalid reference: There is no object with id referencetesting/2/1: Object 2 (name auto2) in workspace %s has been deleted at /ref", refwsid))); Provenance delobjref = new Provenance(userfoo); delobjref.addAction(new Provenance.ProvenanceAction().withWorkspaceObjects(Arrays.asList("referencetesting/2/1"))); failSave(userfoo, wspace, data1, abstype0, delobjref, new TypedObjectValidationException(String.format( "Object #1 has invalid provenance reference: There is no object with id referencetesting/2/1: Object 2 (name auto2) in workspace %s has been deleted", refwsid))); refdata.put("ref", "referencetesting/1/2"); failSave(userfoo, wspace, refdata, abstype0, emptyprov, new TypedObjectValidationException( "Object #1 has invalid reference: There is no object with id referencetesting/1/2: No object with id 1 (name auto1) and version 2 exists in workspace " + refwsid + " at /ref")); Provenance noverref = new Provenance(userfoo); noverref.addAction(new Provenance.ProvenanceAction().withWorkspaceObjects(Arrays.asList("referencetesting/1/2"))); failSave(userfoo, wspace, data1, abstype0, noverref, new TypedObjectValidationException( "Object #1 has invalid provenance reference: There is no object with id referencetesting/1/2: No object with id 1 (name auto1) and version 2 exists in workspace " + refwsid)); //TODO test references against garbage collected objects //test reference type checking String refmod = "TestTypeCheckingRefType"; ws.requestModuleRegistration(userfoo, refmod); ws.resolveModuleRegistration(refmod, true); ws.compileNewTypeSpec(userfoo, specTypeCheckRefs, Arrays.asList("CheckRefType"), null, null, false, null); TypeDefId absreftype0 = new TypeDefId(new TypeDefName(refmod, "CheckRefType"), 0, 1); ws.createWorkspace(userfoo, "referencetypecheck", false, null, null); WorkspaceIdentifier reftypecheck = new WorkspaceIdentifier("referencetypecheck"); long reftypewsid = ws.getWorkspaceInformation(userfoo, reftypecheck).getId(); ws.saveObjects(userfoo, reftypecheck, Arrays.asList( new WorkspaceSaveObject(newdata, SAFE_TYPE1 , null, emptyprov, false)), getIdFactory(userfoo)); ws.saveObjects(userfoo, reftypecheck, Arrays.asList( new WorkspaceSaveObject(newdata, abstype2 , null, emptyprov, false)), getIdFactory(userfoo)); refdata.put("ref", "referencetypecheck/2/1"); ws.saveObjects(userfoo, reftypecheck, Arrays.asList( new WorkspaceSaveObject(refdata, absreftype0, null, emptyprov, false)), getIdFactory(userfoo)); //should work refdata.put("ref", "referencetypecheck/2"); ws.saveObjects(userfoo, reftypecheck, Arrays.asList( new WorkspaceSaveObject(refdata, absreftype0, null, emptyprov, false)), getIdFactory(userfoo)); //should work refdata.put("ref", "referencetypecheck/auto2/1"); ws.saveObjects(userfoo, reftypecheck, Arrays.asList( new WorkspaceSaveObject(refdata, absreftype0, null, emptyprov, false)), getIdFactory(userfoo)); //should work refdata.put("ref", "referencetypecheck/auto2"); ws.saveObjects(userfoo, reftypecheck, Arrays.asList( new WorkspaceSaveObject(refdata, absreftype0, null, emptyprov, false)), getIdFactory(userfoo)); //should work refdata.put("ref", reftypewsid + "/2/1"); ws.saveObjects(userfoo, reftypecheck, Arrays.asList( new WorkspaceSaveObject(refdata, absreftype0, null, emptyprov, false)), getIdFactory(userfoo)); //should work refdata.put("ref", reftypewsid + "/2"); ws.saveObjects(userfoo, reftypecheck, Arrays.asList( new WorkspaceSaveObject(refdata, absreftype0, null, emptyprov, false)), getIdFactory(userfoo)); //should work refdata.put("ref", reftypewsid + "/auto2/1"); ws.saveObjects(userfoo, reftypecheck, Arrays.asList( new WorkspaceSaveObject(refdata, absreftype0, null, emptyprov, false)), getIdFactory(userfoo)); //should work refdata.put("ref", reftypewsid + "/auto2"); ws.saveObjects(userfoo, reftypecheck, Arrays.asList( new WorkspaceSaveObject(refdata, absreftype0, null, emptyprov, false)), getIdFactory(userfoo)); //should work String err = "Object #1 has invalid reference: The type " + "SomeModule.AType-0.1 of reference %s in this object is not " + "allowed - allowed types are [TestTypeChecking.CheckType] at /ref"; refdata.put("ref", "referencetypecheck/1/1"); failSave(userfoo, reftypecheck, refdata, absreftype0, emptyprov, new TypedObjectValidationException(String.format(err, "referencetypecheck/1/1"))); refdata.put("ref", "referencetypecheck/1"); failSave(userfoo, reftypecheck, refdata, absreftype0, emptyprov, new TypedObjectValidationException(String.format(err, "referencetypecheck/1"))); refdata.put("ref", "referencetypecheck/auto1/1"); failSave(userfoo, reftypecheck, refdata, absreftype0, emptyprov, new TypedObjectValidationException(String.format(err, "referencetypecheck/auto1/1"))); refdata.put("ref", "referencetypecheck/auto1"); failSave(userfoo, reftypecheck, refdata, absreftype0, emptyprov, new TypedObjectValidationException(String.format(err, "referencetypecheck/auto1"))); refdata.put("ref", reftypewsid + "/1/1"); failSave(userfoo, reftypecheck, refdata, absreftype0, emptyprov, new TypedObjectValidationException(String.format(err, reftypewsid + "/1/1"))); refdata.put("ref", reftypewsid + "/1"); failSave(userfoo, reftypecheck, refdata, absreftype0, emptyprov, new TypedObjectValidationException(String.format(err, reftypewsid + "/1"))); refdata.put("ref", reftypewsid + "/auto1/1"); failSave(userfoo, reftypecheck, refdata, absreftype0, emptyprov, new TypedObjectValidationException(String.format(err, reftypewsid + "/auto1/1"))); refdata.put("ref", reftypewsid + "/auto1"); failSave(userfoo, reftypecheck, refdata, absreftype0, emptyprov, new TypedObjectValidationException(String.format(err, reftypewsid + "/auto1"))); //check references were rewritten correctly for (int i = 3; i < 11; i++) { WorkspaceObjectData wod = ws.getObjects(userfoo, Arrays.asList( new ObjectIdentifier(reftypecheck, i))).get(0); WorkspaceObjectData wodsub = ws.getObjectsSubSet(userfoo, Arrays.asList( new SubObjectIdentifier(new ObjectIdentifier(reftypecheck, i), null))).get(0); @SuppressWarnings("unchecked") Map<String, Object> obj = (Map<String, Object>) wod.getData(); @SuppressWarnings("unchecked") Map<String, Object> subobj = (Map<String, Object>) wodsub.getData(); assertThat("reference rewritten correctly", (String) obj.get("ref"), is(reftypewsid + "/2/1")); assertThat("reference included correctly", wod.getReferences(), is(Arrays.asList(reftypewsid + "/2/1"))); assertThat("sub obj reference rewritten correctly", (String) subobj.get("ref"), is(reftypewsid + "/2/1")); assertThat("sub obj reference included correctly", wodsub.getReferences(), is(Arrays.asList(reftypewsid + "/2/1"))); WorkspaceObjectInformation inf = ws.getObjectProvenance(userfoo, Arrays.asList( new ObjectIdentifier(reftypecheck, i))).get(0); assertThat("sub obj reference included correctly", inf.getReferences(), is(Arrays.asList(reftypewsid + "/2/1"))); } } @Test public void wsIdErrorOrder() throws Exception { //test that an id error returns the right id if multiple IDs exist WorkspaceUser user = new WorkspaceUser("user1"); WorkspaceIdentifier wsi = new WorkspaceIdentifier("wsIdErrorOrder"); long wsid = ws.createWorkspace(user, wsi.getName(), false, null, null).getId(); List<WorkspaceSaveObject> objs = new LinkedList<WorkspaceSaveObject>(); Map<String, Object> d = new HashMap<String, Object>(); Provenance mtprov = new Provenance(user); objs.add(new WorkspaceSaveObject(d, SAFE_TYPE1, null, mtprov, false)); ws.saveObjects(user, wsi, objs, new IdReferenceHandlerSetFactory(0)); Provenance p = new Provenance(user).addAction(new ProvenanceAction() .withWorkspaceObjects(Arrays.asList( wsi.getName() + "/auto1", wsi.getName() + "/auto2"))); objs.set(0, new WorkspaceSaveObject(d, SAFE_TYPE1, null, p, false)); failSave(user, wsi, objs, new TypedObjectValidationException( "Object #1 has invalid provenance reference: There is no object with id wsIdErrorOrder/auto2: No object with name auto2 exists in workspace " + wsid)); } @Test public void duplicateAutoIds() throws Exception { WorkspaceUser user = new WorkspaceUser("user1"); WorkspaceIdentifier wsi = new WorkspaceIdentifier("dupAutoIds"); ws.createWorkspace(user, wsi.getName(), false, null, null); List<WorkspaceSaveObject> objs = new LinkedList<WorkspaceSaveObject>(); Map<String, Object> d1 = new HashMap<String, Object>(); Map<String, Object> d2 = new HashMap<String, Object>(); d2.put("d", 2); Provenance mtprov = new Provenance(user); objs.add(new WorkspaceSaveObject( new ObjectIDNoWSNoVer("auto5-foo"), d1, SAFE_TYPE1, null, mtprov, false)); objs.add(new WorkspaceSaveObject( new ObjectIDNoWSNoVer("auto5-1-1"), d1, SAFE_TYPE1, null, mtprov, false)); objs.add(new WorkspaceSaveObject( new ObjectIDNoWSNoVer("auto5"), d1, SAFE_TYPE1, null, mtprov, false)); objs.add(new WorkspaceSaveObject( new ObjectIDNoWSNoVer("auto5-1"), d1, SAFE_TYPE1, null, mtprov, false)); objs.add(new WorkspaceSaveObject(d2, SAFE_TYPE1, null, mtprov, false)); ws.saveObjects(user, wsi, objs, new IdReferenceHandlerSetFactory(0)); WorkspaceObjectData d = ws.getObjects(user, Arrays.asList( new ObjectIdentifier(wsi, "auto5-2"))).get(0); assertThat("auto named correctly", d.getData(), is((Object) d2)); } @Test public void genericIdExtraction() throws Exception { String idtype1 = "someid"; String idtype2 = "someid2"; // String idtypeint = "someintid"; String mod = "TestIDExtraction"; String type = "IdType"; final String idSpec = "module " + mod + " {\n" + "/* @id " + idtype1 + " */\n" + "typedef string some_id;\n" + "/* @id " + idtype2 + " */\n" + "typedef string some_id2;\n" + // "/* @id " + idtypeint + " */" + // "typedef int int_id;" + "/* @optional an_id\n" + " @optional an_id2\n" + // " @optional an_int_id */" + "*/" + "typedef structure {\n" + "some_id an_id;\n" + "some_id2 an_id2;\n" + // "int_id an_int_id;" + "} " + type + ";\n" + "};\n"; WorkspaceUser user = new WorkspaceUser("foo"); ws.requestModuleRegistration(user, mod); ws.resolveModuleRegistration(mod, true); ws.compileNewTypeSpec(user, idSpec, Arrays.asList(type), null, null, false, null); TypeDefId idtype = new TypeDefId(new TypeDefName(mod, type), 0, 1); // test basic type checking with different versions WorkspaceIdentifier wsi = new WorkspaceIdentifier("idextract"); ws.createWorkspace(user, wsi.getName(), false, null, null); Provenance emptyprov = new Provenance(user); List<WorkspaceSaveObject> data = new LinkedList<WorkspaceSaveObject>(); data.add(new WorkspaceSaveObject(new HashMap<String, Object>(), idtype, null, emptyprov, false)); Map<String, Object> iddata = new HashMap<String, Object>(); IdReferenceHandlerSetFactory fac = getIdFactory(user).addFactory( new TestIDReferenceHandlerFactory(new IdReferenceType(idtype1))); data.add(new WorkspaceSaveObject(iddata, idtype, null, emptyprov, false)); iddata.put("an_id", "id here"); iddata.put("an_id2", "foo"); // iddata.put("an_int_id", 34); ws.saveObjects(user, wsi, data, fac); //should work Map<String, List<String>> expected = new HashMap<String, List<String>>(); ObjectIdentifier obj1 = new ObjectIdentifier(wsi, "auto1"); checkExternalIds(user, obj1, expected); expected.put(idtype1, Arrays.asList("id here")); ObjectIdentifier obj2 = new ObjectIdentifier(wsi, "auto2"); checkExternalIds(user, obj2, expected); fac.addFactory(new TestIDReferenceHandlerFactory(new IdReferenceType(idtype2))); ws.saveObjects(user, wsi, data, fac); //should work expected.put(idtype2, Arrays.asList("foo")); ObjectIdentifier obj4 = new ObjectIdentifier(wsi, "auto4"); checkExternalIds(user, obj4, expected); ObjectIdentifier copied = new ObjectIdentifier(wsi, "copied"); ws.copyObject(user, obj4, copied); checkExternalIds(user, copied, expected); WorkspaceIdentifier clone = new WorkspaceIdentifier("idextract_cloned"); ws.cloneWorkspace(user, wsi, clone.getName(), false, null, null); ObjectIdentifier clonedobj = new ObjectIdentifier(clone, "copied"); checkExternalIds(user, clonedobj, expected); ws.saveObjects(user, wsi, Arrays.asList( new WorkspaceSaveObject(new ObjectIDNoWSNoVer("copied"), new HashMap<String, Object>(), idtype, null, emptyprov, false)), fac); ws.revertObject(user, new ObjectIdentifier(wsi, "copied", 1)); checkExternalIds(user, new ObjectIdentifier(wsi, "copied", 3), expected); expected.clear(); ws.revertObject(user, new ObjectIdentifier(wsi, "copied", 2)); checkExternalIds(user, new ObjectIdentifier(wsi, "copied", 4), expected); // //check int ids // fac.addFactory(new TestIDReferenceHandlerFactory(new IdReferenceType(idtypeint))); // // ws.saveObjects(user, wsi, data, fac); //should work // expected.put(idtype1, Arrays.asList("id here")); // expected.put(idtype2, Arrays.asList("foo")); // expected.put(idtypeint, Arrays.asList("34")); // checkExternalIds(user, new ObjectIdentifier(wsi, "auto7"), expected); // // iddata.put("an_int_id", null); // // failSave(user, wsi, data, fac, new TypedObjectValidationException( // "Object #2 failed type checking:\ninstance type (null) not allowed for ID reference (allowed: [\"integer\"]), at /an_int_id")); iddata.put("an_id", "parseExcept"); failSave(user, wsi, data, fac, new TypedObjectValidationException( "Object #2 failed type checking:\nUnparseable id parseExcept of type someid: Parse exception for ID parseExcept at /an_id")); iddata.clear(); iddata.put("an_id2", "refExcept"); failSave(user, wsi, data, fac, new TypedObjectValidationException( "Object #2 failed type checking:\nInvalid id refExcept of type someid2: Reference exception for ID refExcept at /an_id2")); iddata.clear(); iddata.put("an_id", "genExcept"); failSave(user, wsi, data, fac, new TypedObjectValidationException( "Object #2 failed type checking:\nId handling error for id type someid: General exception for ID genExcept at /an_id")); iddata.put("an_id", "procParseExcept"); failSave(user, wsi, data, fac, new TypedObjectValidationException( "Object #2 has unparseable reference procParseExcept: Process Parse exception for ID procParseExcept at /an_id")); iddata.clear(); iddata.put("an_id2", "procRefExcept"); failSave(user, wsi, data, fac, new TypedObjectValidationException( "Object #2 has invalid reference: Process Reference exception for ID procRefExcept at /an_id2")); iddata.clear(); iddata.put("an_id", "procGenExcept"); failSave(user, wsi, data, fac, new TypedObjectValidationException( "An error occured while processing IDs: Process General exception for ID procGenExcept")); } @Test public void wsIDHandling() throws Exception { String mod = "WsIDHandling"; String type = "IdType"; final String idSpec = "module " + mod + " {\n" + "/* @optional foo */\n" + "typedef structure {\n" + "int foo;\n" + "} Type1;\n" + "/* @optional foo */\n" + "typedef structure {\n" + "int foo;\n" + "} Type2;\n" + "/* @optional foo */\n" + "typedef structure {\n" + "int foo;\n" + "} Type3;\n" + "/* @id ws */\n" + "typedef string ws_any;\n" + "/* @id ws " + mod + ".Type1 */\n" + "typedef string ws_1;\n" + "/* @id ws " + mod + ".Type2 */\n" + "typedef string ws_2;\n" + "/* @id ws " + mod + ".Type3 */\n" + "typedef string ws_3;\n" + "/* @id ws " + mod + ".Type1 " + mod + ".Type2 */\n" + "typedef string ws_12;\n" + "/* @id ws " + mod + ".Type1 " + mod + ".Type3 */\n" + "typedef string ws_13;\n" + "/* @id ws " + mod + ".Type2 " + mod + ".Type3 */\n" + "typedef string ws_23;\n" + "/* @optional ws_any ws_1 ws_2 ws_3 ws_12 ws_13 ws_23 */\n" + "typedef structure {\n" + "list<ws_any> ws_any;\n" + "list<mapping<ws_1, int>> ws_1;\n" + "list<tuple<string, ws_2>> ws_2;\n" + "list<list<ws_3>> ws_3;\n" + "list<ws_12> ws_12;\n" + "list<ws_13> ws_13;\n" + "list<ws_23> ws_23;\n" + "} " + type + ";\n" + "};\n"; WorkspaceUser user = new WorkspaceUser("foo"); ws.requestModuleRegistration(user, mod); ws.resolveModuleRegistration(mod, true); ws.compileNewTypeSpec(user, idSpec, Arrays.asList(type, "Type1", "Type2", "Type3"), null, null, false, null); TypeDefId type1 = new TypeDefId(new TypeDefName(mod, "Type1"), 0, 1); TypeDefId type2 = new TypeDefId(new TypeDefName(mod, "Type2"), 0, 1); TypeDefId type3 = new TypeDefId(new TypeDefName(mod, "Type3"), 0, 1); TypeDefId idtype = new TypeDefId(new TypeDefName(mod, type), 0, 1); // test basic type checking with different versions WorkspaceIdentifier wsi = new WorkspaceIdentifier("wsIDHandling"); long wsid = ws.createWorkspace(user, wsi.getName(), false, null, null).getId(); Provenance emptyprov = new Provenance(user); List<WorkspaceSaveObject> objs = new LinkedList<WorkspaceSaveObject>(); IdReferenceHandlerSetFactory fac = new IdReferenceHandlerSetFactory(3); Map<String, Object> mt = new HashMap<String, Object>(); objs.add(new WorkspaceSaveObject(new ObjectIDNoWSNoVer("t1"), mt, type1, null, emptyprov, false)); objs.add(new WorkspaceSaveObject(new ObjectIDNoWSNoVer("t2"), mt, type2, null, emptyprov, false)); objs.add(new WorkspaceSaveObject(new ObjectIDNoWSNoVer("t3"), mt, type3, null, emptyprov, false)); ws.saveObjects(user, wsi, objs, fac); String ref1 = wsi.getName() + "/t1"; String ref2 = wsi.getName() + "/t2"; String ref3 = wsi.getName() + "/t3"; List<String> all3 = Arrays.asList(ref1, ref2, ref3); Map<String, Object> data = new HashMap<String, Object>(); data.put("ws_any", all3); Map<String, Integer> innermap = new HashMap<String, Integer>(); data.put("ws_1", Arrays.asList(innermap)); innermap.put(ref1, 3); ArrayList<List<String>> innertuple = new ArrayList<List<String>>(); data.put("ws_2", innertuple); innertuple.add(Arrays.asList("foo", ref2)); ArrayList<String> innerlist = new ArrayList<String>(); data.put("ws_3", Arrays.asList(innerlist)); innerlist.add(ref3); data.put("ws_12", Arrays.asList(ref1, ref2)); data.put("ws_13", Arrays.asList(ref1, ref3)); data.put("ws_23", Arrays.asList(ref2, ref3)); objs.clear(); objs.add(new WorkspaceSaveObject(data, idtype, null, emptyprov, false)); //should work ws.saveObjects(user, wsi, objs, fac); innermap.put(ref2, 4); failSave(user, wsi, objs, new TypedObjectValidationException( "Object #1 has invalid reference: The type WsIDHandling.Type2-0.1 of reference wsIDHandling/t2 in this object is not allowed - allowed types are [WsIDHandling.Type1] at /ws_1/0/wsIDHandling/t2")); innermap.remove(ref2); innermap.put(ref3, 6); failSave(user, wsi, objs, new TypedObjectValidationException( "Object #1 has invalid reference: The type WsIDHandling.Type3-0.1 of reference wsIDHandling/t3 in this object is not allowed - allowed types are [WsIDHandling.Type1] at /ws_1/0/wsIDHandling/t3")); innermap.remove(ref3); innertuple.add(Arrays.asList("bar", ref1)); failSave(user, wsi, objs, new TypedObjectValidationException( "Object #1 has invalid reference: The type WsIDHandling.Type1-0.1 of reference wsIDHandling/t1 in this object is not allowed - allowed types are [WsIDHandling.Type2] at /ws_2/1/1")); innertuple.clear(); innertuple.add(Arrays.asList("baz", ref3)); failSave(user, wsi, objs, new TypedObjectValidationException( "Object #1 has invalid reference: The type WsIDHandling.Type3-0.1 of reference wsIDHandling/t3 in this object is not allowed - allowed types are [WsIDHandling.Type2] at /ws_2/0/1")); innertuple.set(0, Arrays.asList("foo", ref2)); innerlist.add(ref1); failSave(user, wsi, objs, new TypedObjectValidationException( "Object #1 has invalid reference: The type WsIDHandling.Type1-0.1 of reference wsIDHandling/t1 in this object is not allowed - allowed types are [WsIDHandling.Type3] at /ws_3/0/1")); innerlist.set(1, ref3); innerlist.add(ref2); failSave(user, wsi, objs, new TypedObjectValidationException( "Object #1 has invalid reference: The type WsIDHandling.Type2-0.1 of reference wsIDHandling/t2 in this object is not allowed - allowed types are [WsIDHandling.Type3] at /ws_3/0/2")); innerlist.remove(2); innerlist.remove(1); data.put("ws_12", all3); failSave(user, wsi, objs, new TypedObjectValidationException( "Object #1 has invalid reference: The type WsIDHandling.Type3-0.1 of reference wsIDHandling/t3 in this object is not allowed - allowed types are [WsIDHandling.Type1, WsIDHandling.Type2] at /ws_12/2")); data.put("ws_12", Arrays.asList(ref1, ref2)); data.put("ws_13", all3); failSave(user, wsi, objs, new TypedObjectValidationException( "Object #1 has invalid reference: The type WsIDHandling.Type2-0.1 of reference wsIDHandling/t2 in this object is not allowed - allowed types are [WsIDHandling.Type1, WsIDHandling.Type3] at /ws_13/1")); data.put("ws_13", Arrays.asList(ref1, ref3)); data.put("ws_23", all3); failSave(user, wsi, objs, new TypedObjectValidationException( "Object #1 has invalid reference: The type WsIDHandling.Type1-0.1 of reference wsIDHandling/t1 in this object is not allowed - allowed types are [WsIDHandling.Type2, WsIDHandling.Type3] at /ws_23/0")); //test id path returns on parse and inaccessible object exceptions data.put("ws_23", Arrays.asList(ref2, ref3)); innertuple.set(0, Arrays.asList("foo", "YourMotherWasAHamster")); failSave(user, wsi, objs, new TypedObjectValidationException( "Object #1 has unparseable reference YourMotherWasAHamster: Illegal number of separators / in object reference YourMotherWasAHamster at /ws_2/0/1")); innertuple.set(0, Arrays.asList("foo", ref2)); data.remove("ws_any"); ws.setObjectsDeleted(user, Arrays.asList(new ObjectIdentifier(wsi, "t1")), true); failSave(user, wsi, objs, new TypedObjectValidationException( "Object #1 has invalid reference: There is no object with id wsIDHandling/t1: Object 1 (name t1) in workspace " + wsid + " has been deleted at /ws_12/0")); } @Test public void maxIdsPerCall() throws Exception { String idtype1 = "someid"; String idtype2 = "someid2"; String mod = "TestMaxId"; String listtype = "ListIdType"; final String idSpec = "module " + mod + " {\n" + "/* @id ws */\n" + "typedef string ws_id;\n" + "/* @id " + idtype1 + " */\n" + "typedef string some_id;\n" + "/* @id " + idtype2 + " */\n" + "typedef string some_id2;\n" + "/* @id " + idtype1 + " attrib1 */\n" + "typedef string some_id_a1;\n" + "/* @id " + idtype1 + " attrib2 */\n" + "typedef string some_id_a2;\n" + "/* @optional ws_ids\n" + " @optional some_ids\n" + " @optional some_ids2\n" + " @optional some_ids_a1\n" + " @optional some_ids_a2\n" + "*/\n" + "typedef structure {\n" + "list<ws_id> ws_ids;\n" + "list<some_id> some_ids;\n" + "list<some_id2> some_ids2;\n" + "list<some_id_a1> some_ids_a1;\n" + "list<some_id_a2> some_ids_a2;\n" + "} " + listtype + ";\n" + "};\n"; WorkspaceUser user = new WorkspaceUser("foo"); ws.requestModuleRegistration(user, mod); ws.resolveModuleRegistration(mod, true); ws.compileNewTypeSpec(user, idSpec, Arrays.asList(listtype), null, null, false, null); TypeDefId listidtype = new TypeDefId(new TypeDefName(mod, listtype), 0, 1); // test basic type checking with different versions WorkspaceIdentifier wsi = new WorkspaceIdentifier("maxids"); ws.createWorkspace(user, wsi.getName(), false, null, null); Provenance emptyprov = new Provenance(user); List<WorkspaceSaveObject> objs = new LinkedList<WorkspaceSaveObject>(); WorkspaceSaveObject mtobj = new WorkspaceSaveObject( new HashMap<String, String>(), listidtype, null, emptyprov, false); objs.add(mtobj); objs.add(mtobj); IdReferenceHandlerSetFactory fac = makeFacForMaxIDTests( Arrays.asList(idtype1, idtype2), user, 8); ws.saveObjects(user, wsi, objs, fac); objs.clear(); Map<String, Object> data1 = new HashMap<String, Object>(); data1.put("ws_ids", Arrays.asList("maxids/auto1", "maxids/auto2", "maxids/auto1")); data1.put("some_ids", Arrays.asList("foo", "bar", "foo")); data1.put("some_ids2", Arrays.asList("foo", "baz", "foo")); data1.put("some_ids_a1", Arrays.asList("foo", "bak", "foo")); data1.put("some_ids_a2", Arrays.asList("foo", "baf", "foo")); objs.add(new WorkspaceSaveObject(data1, listidtype, null, emptyprov, false)); //should work ws.saveObjects(user, wsi, objs, fac); fac = makeFacForMaxIDTests(Arrays.asList(idtype1, idtype2), user, 7); failSave(user, wsi, objs, fac, new TypedObjectValidationException( "Failed type checking at object #1 - the number of unique IDs in the saved objects exceeds the maximum allowed, 7")); Provenance p = new Provenance(user).addAction(new ProvenanceAction() .withWorkspaceObjects(Arrays.asList( "maxids/auto1", "maxids/auto2", "maxids/auto1"))); fac = makeFacForMaxIDTests(Arrays.asList(idtype1, idtype2), user, 10); objs.set(0, new WorkspaceSaveObject(data1, listidtype, null, p, false)); //should work ws.saveObjects(user, wsi, objs, fac); fac = makeFacForMaxIDTests(Arrays.asList(idtype1, idtype2), user, 9); failSave(user, wsi, objs, fac, new TypedObjectValidationException( "Failed type checking at object #1 - the number of unique IDs in the saved objects exceeds the maximum allowed, 9")); objs.set(0, new WorkspaceSaveObject(data1, listidtype, null, emptyprov, false)); objs.add(new WorkspaceSaveObject(data1, listidtype, null, emptyprov, false)); fac = makeFacForMaxIDTests(Arrays.asList(idtype1, idtype2), user, 16); //should work ws.saveObjects(user, wsi, objs, fac); fac = makeFacForMaxIDTests(Arrays.asList(idtype1, idtype2), user, 15); failSave(user, wsi, objs, fac, new TypedObjectValidationException( "Failed type checking at object #2 - the number of unique IDs in the saved objects exceeds the maximum allowed, 15")); objs.set(0, new WorkspaceSaveObject(data1, listidtype, null, p, false)); objs.set(1, new WorkspaceSaveObject(data1, listidtype, null, p, false)); fac = makeFacForMaxIDTests(Arrays.asList(idtype1, idtype2), user, 20); //should work ws.saveObjects(user, wsi, objs, fac); fac = makeFacForMaxIDTests(Arrays.asList(idtype1, idtype2), user, 19); failSave(user, wsi, objs, fac, new TypedObjectValidationException( "Failed type checking at object #2 - the number of unique IDs in the saved objects exceeds the maximum allowed, 19")); } private IdReferenceHandlerSetFactory makeFacForMaxIDTests(List<String> idtypes, WorkspaceUser user, int max) { IdReferenceHandlerSetFactory fac = new IdReferenceHandlerSetFactory(max); // .addFactory(ws.getHandlerFactory(user)); for (String idtype: idtypes) { fac.addFactory(new TestIDReferenceHandlerFactory( new IdReferenceType(idtype))); } return fac; } @Test public void referenceClash() throws Exception { String mod = "TestTypeCheckingErr"; final String specTypeCheck1 = "module " + mod + " {" + "typedef structure {" + "int foo;" + "list<int> bar;" + "string baz;" + "} CheckType;" + "};"; WorkspaceUser userfoo = new WorkspaceUser("foo"); Provenance emptyprov = new Provenance(userfoo); ws.requestModuleRegistration(userfoo, mod); ws.resolveModuleRegistration(mod, true); ws.compileNewTypeSpec(userfoo, specTypeCheck1, Arrays.asList("CheckType"), null, null, false, null); ws.releaseTypes(userfoo, mod); TypeDefId abstype0 = new TypeDefId(new TypeDefName(mod, "CheckType"), 1, 0); String wsName = "reftypecheckerror"; ws.createWorkspace(userfoo, wsName, false, null, null); WorkspaceIdentifier reftypecheck = new WorkspaceIdentifier(wsName); Map<String, Object> refdata = new HashMap<String, Object>(); refdata.put("foo", 3); refdata.put("baz", "astring"); refdata.put("bar", Arrays.asList(-3, 1, 234567890)); ws.saveObjects(userfoo, reftypecheck, Arrays.asList( new WorkspaceSaveObject(refdata, abstype0 , null, emptyprov, false)), getIdFactory(userfoo)); String refmod = "TestTypeCheckingRefTypeErr"; final String specTypeCheckRefs = "module " + refmod + " {" + "/* @id ws " + mod + ".CheckType */" + "typedef string reference;" + "/* @optional refmap */" + "typedef structure {" + "int foo;" + "list<int> bar;" + "string baz;" + "reference ref;" + "mapping<reference, string> refmap;" + "} CheckRefType;" + "};"; ws.requestModuleRegistration(userfoo, refmod); ws.resolveModuleRegistration(refmod, true); ws.compileNewTypeSpec(userfoo, specTypeCheckRefs, Arrays.asList("CheckRefType"), null, null, false, null); ws.releaseTypes(userfoo, refmod); TypeDefId absreftype0 = new TypeDefId(new TypeDefName(refmod, "CheckRefType"), 1, 0); long reftypewsid = ws.getWorkspaceInformation(userfoo, reftypecheck).getId(); //test the edge case where two keys in a hash resolve to the same reference refdata.put("ref", wsName + "/1/1"); Map<String, String> refmap = new HashMap<String, String>(); refmap.put(wsName + "/1/1", "pootypoot"); refmap.put(wsName + "/auto1/1", "pootypoot"); assertThat("refmap has 2 refs", refmap.size(), is(2)); refdata.put("refmap", refmap); failSave(userfoo, reftypecheck, refdata, absreftype0, emptyprov, new TypedObjectValidationException( "Object #1: Two references in a single hash are identical when resolved, resulting in a loss of data: " + "Duplicated key '" + reftypewsid + "/1/1' was found at /refmap")); } @Test public void saveProvenance() throws Exception { WorkspaceUser foo = new WorkspaceUser("foo"); WorkspaceIdentifier prov = new WorkspaceIdentifier("provenance"); ws.createWorkspace(foo, prov.getName(), false, null, null); long wsid = ws.getWorkspaceInformation(foo, prov).getId(); Map<String, Object> data = new HashMap<String, Object>(); data.put("foo", "bar"); Provenance emptyprov = new Provenance(foo); //already tested bad references in saveObjectWithTypeChecking, won't test again here ws.saveObjects(foo, prov, Arrays.asList( new WorkspaceSaveObject(data, SAFE_TYPE1, null, emptyprov, false)), getIdFactory(foo)); ws.saveObjects(foo, prov, Arrays.asList( new WorkspaceSaveObject(data, SAFE_TYPE1, null, emptyprov, false)), getIdFactory(foo)); ws.saveObjects(foo, prov, Arrays.asList( new WorkspaceSaveObject(data, SAFE_TYPE1, null, emptyprov, false)), getIdFactory(foo)); ws.saveObjects(foo, prov, Arrays.asList( new WorkspaceSaveObject(new ObjectIDNoWSNoVer("auto1"), data, SAFE_TYPE1, null, emptyprov, false)), getIdFactory(foo)); ws.saveObjects(foo, prov, Arrays.asList( new WorkspaceSaveObject(new ObjectIDNoWSNoVer("auto1"), data, SAFE_TYPE1, null, emptyprov, false)), getIdFactory(foo)); List<ExternalData> ed = new LinkedList<ExternalData>(); ed.add(new ExternalData() .withDataId("data id") .withDataUrl("http://somedata.org/somedata") .withDescription("a description") .withResourceName("resource") .withResourceReleaseDate(new Date(62)) .withResourceUrl("http://somedata.org") .withResourceVersion("1.2.3") ); ed.add(new ExternalData().withDataId("data id2")); Provenance p = new Provenance(foo); p.addAction(new ProvenanceAction() .withCommandLine("A command line") .withDescription("descrip") .withIncomingArgs(Arrays.asList("a", "b", "c")) .withMethod("method") .withMethodParameters(Arrays.asList((Object) data, data, data)) .withOutgoingArgs(Arrays.asList("d", "e", "f")) .withScript("script") .withScriptVersion("2.1") .withServiceName("service") .withServiceVersion("3") .withTime(new Date(45)) .withExternalData(ed) .withWorkspaceObjects(Arrays.asList("provenance/auto3", "provenance/auto1/2"))); p.addAction(new ProvenanceAction() .withWorkspaceObjects(Arrays.asList("provenance/auto2/1", "provenance/auto1"))); ws.saveObjects(foo, prov, Arrays.asList( new WorkspaceSaveObject(data, SAFE_TYPE1, null, p, false)), getIdFactory(foo)); Map<String, String> refmap = new HashMap<String, String>(); refmap.put("provenance/auto3", wsid + "/3/1"); refmap.put("provenance/auto1/2", wsid + "/1/2"); refmap.put("provenance/auto2/1", wsid + "/2/1"); refmap.put("provenance/auto1", wsid + "/1/3"); checkProvenanceCorrect(foo, p, new ObjectIdentifier(prov, 4), refmap); try { new WorkspaceSaveObject(data, SAFE_TYPE1, null, null, false); fail("saved without provenance"); } catch (IllegalArgumentException iae) { assertThat("correct exception", iae.getLocalizedMessage(), is("Neither data, provenance, nor type may be null")); } try { new WorkspaceSaveObject(new ObjectIDNoWSNoVer("foo"), SAFE_TYPE1, null, null, false); fail("saved without provenance"); } catch (IllegalArgumentException iae) { assertThat("correct exception", iae.getLocalizedMessage(), is("Neither data, provenance, nor type may be null")); } try { new Provenance(null); } catch (IllegalArgumentException iae) { assertThat("correct exception", iae.getLocalizedMessage(), is("user cannot be null")); } try { Provenance pv = new Provenance(foo); pv.addAction(null); } catch (IllegalArgumentException iae) { assertThat("correct exception", iae.getLocalizedMessage(), is("action cannot be null")); } //Test minimal provenance Provenance p2 = new Provenance(foo); ws.saveObjects(foo, prov, Arrays.asList( new WorkspaceSaveObject(data, SAFE_TYPE1, null, p2, false)), getIdFactory(foo)); List<Date> dates = checkProvenanceCorrect(foo, p2, new ObjectIdentifier(prov, 5), new HashMap<String, String>()); Provenance got2 = ws.getObjects(foo, Arrays.asList(new ObjectIdentifier(prov, 5))).get(0).getProvenance(); assertThat("Prov date constant", got2.getDate(), is(dates.get(0))); Provenance gotsub2 = ws.getObjectsSubSet(foo, Arrays.asList(new SubObjectIdentifier( new ObjectIdentifier(prov, 5), null))).get(0).getProvenance(); assertThat("Prov date constant", gotsub2.getDate(), is(dates.get(1))); assertThat("Prov dates same", got2.getDate(), is(gotsub2.getDate())); Provenance gotProv2 = ws.getObjectProvenance(foo, Arrays.asList( new ObjectIdentifier(prov, 5))).get(0).getProvenance(); assertThat("Prov date constant", gotProv2.getDate(), is(dates.get(2))); assertThat("Prov dates same", got2.getDate(), is(gotProv2.getDate())); //make sure passing nulls for ws obj lists doesn't kill anything Provenance p3 = new Provenance(foo); p3.addAction(new ProvenanceAction().withWorkspaceObjects(null)); ws.saveObjects(foo, prov, Arrays.asList( new WorkspaceSaveObject(data, SAFE_TYPE1, null, p3, false)), getIdFactory(foo)); checkProvenanceCorrect(foo, p3, new ObjectIdentifier(prov, 6), new HashMap<String, String>()); Provenance p4 = new Provenance(foo); ProvenanceAction pa = new ProvenanceAction(); pa.setWorkspaceObjects(null); p4.addAction(pa); p3.addAction(new ProvenanceAction().withWorkspaceObjects(null)); ws.saveObjects(foo, prov, Arrays.asList( new WorkspaceSaveObject(data, SAFE_TYPE1, null, p4, false)), getIdFactory(foo)); checkProvenanceCorrect(foo, p4, new ObjectIdentifier(prov, 7), new HashMap<String, String>()); } @Test public void saveLargeProvenance() throws Exception { WorkspaceUser foo = new WorkspaceUser("foo"); WorkspaceIdentifier prov = new WorkspaceIdentifier("bigprov"); ws.createWorkspace(foo, prov.getName(), false, null, null); Map<String, Object> data = new HashMap<String, Object>(); data.put("foo", "bar"); List<Object> methparams = new ArrayList<Object>(); for (int i = 1; i < 997; i++) { methparams.add(TEXT1000); } Provenance p = new Provenance(foo); p.addAction(new ProvenanceAction().withMethodParameters(methparams)); ws.saveObjects(foo, prov, Arrays.asList( //should work new WorkspaceSaveObject(data, SAFE_TYPE1, null, p, false)), getIdFactory(foo)); methparams.add(TEXT1000); Provenance p2 = new Provenance(foo); p2.addAction(new ProvenanceAction().withMethodParameters(methparams)); try { ws.saveObjects(foo, prov, Arrays.asList( new WorkspaceSaveObject(data, SAFE_TYPE1, null, p, false)), getIdFactory(foo)); fail("saved too big prov"); } catch (IllegalArgumentException iae) { assertThat("correct exception", iae.getLocalizedMessage(), is("Object #1 provenance size 1000290 exceeds limit of 1000000")); } } @Test public void saveWithLargeSubdata() throws Exception { final String specSubdata = "module TestSubdata {" + "/* @searchable ws_subset subset */" + "typedef structure {" + "list<string> subset;" + "} SubSetType;" + "};"; String mod = "TestSubdata"; WorkspaceUser userfoo = new WorkspaceUser("foo"); ws.requestModuleRegistration(userfoo, mod); ws.resolveModuleRegistration(mod, true); ws.compileNewTypeSpec(userfoo, specSubdata, Arrays.asList("SubSetType"), null, null, false, null); TypeDefId subsettype = new TypeDefId(new TypeDefName(mod, "SubSetType"), 0, 1); WorkspaceIdentifier subdataws = new WorkspaceIdentifier("bigsubdata"); ws.createWorkspace(userfoo, subdataws.getName(), false, null, null); Map<String, Object> data = new HashMap<String, Object>(); List<String> subdata = new LinkedList<String>(); data.put("subset", subdata); for (int i = 0; i < 14955; i++) { subdata.add(TEXT1000); } ws.saveObjects(userfoo, subdataws, Arrays.asList( //should work new WorkspaceSaveObject(data, subsettype, null, new Provenance(userfoo), false)), getIdFactory(userfoo)); subdata.add(TEXT1000); try { ws.saveObjects(userfoo, subdataws, Arrays.asList( new WorkspaceSaveObject(data, subsettype, null, new Provenance(userfoo), false)), getIdFactory(userfoo)); fail("saved too big subdata"); } catch (IllegalArgumentException iae) { assertThat("correct exception", iae.getLocalizedMessage(), is("Object #1 subdata size exceeds limit of 15000000")); } } @Test public void bigUserMetaErrors() throws Exception { WorkspaceUser foo = new WorkspaceUser("foo"); WorkspaceIdentifier read = new WorkspaceIdentifier("bigmeta"); ws.createWorkspace(foo, read.getIdentifierString(), false, null, null); Map<String, Object> data = new HashMap<String, Object>(); Map<String, String> smallmeta = new HashMap<String, String>(); smallmeta.put("foo", "bar"); Map<String, String> meta = new HashMap<String, String>(); data.put("fubar", "bar"); JsonNode savedata = MAPPER.valueToTree(data); for (int i = 0; i < 18; i++) { meta.put(Integer.toString(i), LONG_TEXT); //> 16Mb now } try { ws.saveObjects(foo, read, Arrays.asList(new WorkspaceSaveObject( new ObjectIDNoWSNoVer("bigmeta"), savedata, SAFE_TYPE1, meta, new Provenance(foo), false)), getIdFactory(foo)); fail("saved object with > 16kb metadata"); } catch (IllegalArgumentException iae) { assertThat("correct exception", iae.getLocalizedMessage(), is("Metadata size of 19413 is > 16000 bytes")); } try { ws.saveObjects(foo, read, Arrays.asList(new WorkspaceSaveObject( new ObjectIDNoWSNoVer(3), savedata, SAFE_TYPE1, meta, new Provenance(foo), false)), getIdFactory(foo)); fail("saved object with > 16kb metadata"); } catch (IllegalArgumentException iae) { assertThat("correct exception", iae.getLocalizedMessage(), is("Metadata size of 19413 is > 16000 bytes")); } } @Test public void saveWithWrongObjectId() throws Exception { WorkspaceUser foo = new WorkspaceUser("foo"); WorkspaceIdentifier read = new WorkspaceIdentifier("wrongobjid"); ws.createWorkspace(foo, read.getIdentifierString(), false, null, null); Map<String, Object> data = new HashMap<String, Object>(); JsonNode savedata = MAPPER.valueToTree(data); try { ws.saveObjects(foo, read, Arrays.asList(new WorkspaceSaveObject( new ObjectIDNoWSNoVer(3), savedata, SAFE_TYPE1, null, new Provenance(foo), false)), getIdFactory(foo)); fail("saved object with non-existant id"); } catch (NoSuchObjectException nsoe) { assertThat("correct exception", nsoe.getLocalizedMessage(), is("There is no object with id 3")); } } @Test public void unserializableData() throws Exception { WorkspaceUser foo = new WorkspaceUser("foo"); WorkspaceIdentifier read = new WorkspaceIdentifier("unserializable"); ws.createWorkspace(foo, read.getIdentifierString(), false, null, null); Object data = new StringReader("foo"); Map<String, String> meta = new HashMap<String, String>(); meta.put("foo", "bar"); try { ws.saveObjects(foo, read, Arrays.asList(new WorkspaceSaveObject( new ObjectIDNoWSNoVer("jframe"), data, SAFE_TYPE1, meta, new Provenance(foo), false)), getIdFactory(foo)); fail("saved unserializable object"); } catch (IllegalArgumentException iae) { assertThat("Actual exception: " + iae.getMessage(), iae.getMessage(), is("UObject can not serialize object of this type: java.io.StringReader")); } } @Test public void getNonexistantObjects() throws Exception { WorkspaceUser foo = new WorkspaceUser("foo"); WorkspaceIdentifier read = new WorkspaceIdentifier("nonexistantobjects"); ws.createWorkspace(foo, read.getIdentifierString(), false, null, null); long readid = ws.getWorkspaceInformation(foo, read).getId(); Map<String, Object> data = new HashMap<String, Object>(); data.put("fubar", "thingy"); JsonNode savedata = MAPPER.valueToTree(data); List<WorkspaceSaveObject> objects = new ArrayList<WorkspaceSaveObject>(); objects.add(new WorkspaceSaveObject(new ObjectIDNoWSNoVer("myname"), savedata, SAFE_TYPE1, null, new Provenance(foo), false)); ws.saveObjects(foo, read, objects, getIdFactory(foo)); getNonExistantObject(foo, new ObjectIdentifier(read, 2), "No object with id 2 exists in workspace " + readid); getNonExistantObject(foo, new ObjectIdentifier(read, 1, 2), "No object with id 1 (name myname) and version 2 exists in workspace " + readid); getNonExistantObject(foo, new ObjectIdentifier(read, "myname2"), "No object with name myname2 exists in workspace " + readid); getNonExistantObject(foo, new ObjectIdentifier(read, "myname", 2), "No object with id 1 (name myname) and version 2 exists in workspace " + readid); } @Test public void objectIDs() throws Exception { WorkspaceIdentifier goodWs = new WorkspaceIdentifier("foo"); testObjectIdentifier("f|o.A-1_2"); testObjectIdentifier("f|o.A-1_2", 1); testObjectIdentifier(null, "foo", "wsi cannot be null"); testObjectIdentifier(goodWs, null, "Object name cannot be null or the empty string"); testObjectIdentifier(goodWs, "", "Object name cannot be null or the empty string"); testObjectIdentifier(goodWs, "f|o.A-1_2+", "Illegal character in object name f|o.A-1_2+: +"); testObjectIdentifier(goodWs, "-1", "Object names cannot be integers: -1"); testObjectIdentifier(goodWs, "15", "Object names cannot be integers: 15"); testObjectIdentifier(goodWs, "f|o.A-1_2", 0, "Object version must be > 0"); testObjectIdentifier(goodWs, TEXT256, "Object name exceeds the maximum length of 255"); testObjectIdentifier(1); testObjectIdentifier(1, 1); testObjectIdentifier(null, 1, "wsi cannot be null"); testObjectIdentifier(goodWs, 0, "Object id must be > 0"); testObjectIdentifier(goodWs, 0, 1, "Object id must be > 0"); testObjectIdentifier(goodWs, 1, 0, "Object version must be > 0"); testCreate(goodWs, "f|o.A-1_2", null); testCreate(goodWs, null, 1L); testCreate(null, "boo", null, "wsi cannot be null"); testCreate(goodWs, TEXT256, null, "Object name exceeds the maximum length of 255"); testCreate(goodWs, null, null, "Must provide one and only one of object name (was: null) or id (was: null)"); testCreate(goodWs, "boo", 1L, "Must provide one and only one of object name (was: boo) or id (was: 1)"); testCreate(goodWs, "-1", null, "Object names cannot be integers: -1"); testCreate(goodWs, "15", null, "Object names cannot be integers: 15"); testCreateVer(goodWs, "boo", null, 1); testCreateVer(goodWs, null, 1L, 1); testCreateVer(goodWs, "boo", null, null); testCreateVer(goodWs, null, 1L, null); testCreateVer(goodWs, "boo", null, 0, "Object version must be > 0"); testCreateVer(goodWs, TEXT256, null, 1, "Object name exceeds the maximum length of 255"); testCreateVer(goodWs, null, 1L, 0, "Object version must be > 0"); testRef("foo/bar"); testRef("foo/bar/1"); testRef("foo/bar/1/2", "Illegal number of separators / in object reference foo/bar/1/2"); testRef("foo/" + TEXT256 + "/1", "Object name exceeds the maximum length of 255"); testRef("foo/bar/n", "Unable to parse version portion of object reference foo/bar/n to an integer"); testRef("foo", "Illegal number of separators / in object reference foo"); testRef("1/2"); testRef("1/2/3"); testRef("1/2/3/4", "Illegal number of separators / in object reference 1/2/3/4"); testRef("1/2/n", "Unable to parse version portion of object reference 1/2/n to an integer"); testRef("1", "Illegal number of separators / in object reference 1"); testRef("foo/2"); testRef("2/foo"); testRef("foo/2/1"); testRef("2/foo/1"); } @Test public void deleteUndelete() throws Exception { WorkspaceUser user = new WorkspaceUser("deleteundelete"); WorkspaceIdentifier read = new WorkspaceIdentifier("deleteundelete"); WorkspaceInformation readinfo = ws.createWorkspace(user, read.getIdentifierString(), false, "descrip", null); long wsid = readinfo.getId(); Date lastReadDate = readinfo.getModDate(); Map<String, String> data1 = new HashMap<String, String>(); Map<String, String> data2 = new HashMap<String, String>(); data1.put("data", "1"); data2.put("data", "2"); WorkspaceSaveObject sobj1 = new WorkspaceSaveObject( new ObjectIDNoWSNoVer("obj"), data1, SAFE_TYPE1, null, new Provenance(user), false); ws.saveObjects(user, read, Arrays.asList(sobj1, new WorkspaceSaveObject(new ObjectIDNoWSNoVer("obj"), data2, SAFE_TYPE1, null, new Provenance(user), false)), getIdFactory(user)); ObjectIdentifier o1 = new ObjectIdentifier(read, "obj", 1); ObjectIdentifier o2 = new ObjectIdentifier(read, "obj", 2); Map<ObjectIdentifier, Object> idToData = new HashMap<ObjectIdentifier, Object>(); idToData.put(o1, data1); idToData.put(o2, data2); List<ObjectIdentifier> objs = new ArrayList<ObjectIdentifier>(idToData.keySet()); checkNonDeletedObjs(user, idToData); List<ObjectIdentifier> obj1 = new ArrayList<ObjectIdentifier>(Arrays.asList(o1)); List<ObjectIdentifier> obj2 = new ArrayList<ObjectIdentifier>(Arrays.asList(o2)); try { ws.setObjectsDeleted(new WorkspaceUser("bar"), obj1, true); fail("deleted objects w/o auth"); } catch (InaccessibleObjectException ioe) { assertThat("correct exception", ioe.getLocalizedMessage(), is("Object obj cannot be accessed: User bar may not delete objects from workspace deleteundelete")); assertThat("correct object returned", ioe.getInaccessibleObject(), is(o1)); } try { ws.setObjectsDeleted(new WorkspaceUser("bar"), obj1, false); fail("undeleted objects w/o auth"); } catch (InaccessibleObjectException ioe) { assertThat("correct exception", ioe.getLocalizedMessage(), is("Object obj cannot be accessed: User bar may not undelete objects from workspace deleteundelete")); assertThat("correct object returned", ioe.getInaccessibleObject(), is(o1)); } lastReadDate = ws.getWorkspaceInformation(user, read).getModDate(); ws.setObjectsDeleted(user, obj1, true); lastReadDate = assertWorkspaceDateUpdated(user, read, lastReadDate, "ws date updated on delete"); String err = String.format("Object 1 (name obj) in workspace %s has been deleted", wsid); failToGetDeletedObjects(user, objs, err); failToGetDeletedObjects(user, obj1, err); failToGetDeletedObjects(user, obj2, err); try { ws.setObjectsDeleted(user, obj2, true); //should have no effect } catch (NoSuchObjectException nsoe) { assertThat("correct exception", nsoe.getLocalizedMessage(), is("Object 1 (name obj) in workspace " + wsid + " has been deleted")); } failToGetDeletedObjects(user, objs, err); failToGetDeletedObjects(user, obj1, err); failToGetDeletedObjects(user, obj2, err); lastReadDate = ws.getWorkspaceInformation(user, read).getModDate(); ws.setObjectsDeleted(user, obj2, false); lastReadDate = assertWorkspaceDateUpdated(user, read, lastReadDate, "ws date updated on undelete"); checkNonDeletedObjs(user, idToData); lastReadDate = ws.getWorkspaceInformation(user, read).getModDate(); ws.setObjectsDeleted(user, obj1, false);//should have no effect lastReadDate = assertWorkspaceDateUpdated(user, read, lastReadDate, "ws date updated on undelete"); checkNonDeletedObjs(user, idToData); lastReadDate = ws.getWorkspaceInformation(user, read).getModDate(); ws.setObjectsDeleted(user, obj2, true); lastReadDate = assertWorkspaceDateUpdated(user, read, lastReadDate, "ws date updated on delete"); failToGetDeletedObjects(user, objs, err); failToGetDeletedObjects(user, obj1, err); failToGetDeletedObjects(user, obj2, err); //save should undelete ws.saveObjects(user, read, Arrays.asList( new WorkspaceSaveObject(new ObjectIDNoWSNoVer("obj"), data1, SAFE_TYPE1, null, new Provenance(user), false)), getIdFactory(user)); ObjectIdentifier o3 = new ObjectIdentifier(read, "obj", 3); idToData.put(o3, data1); objs = new ArrayList<ObjectIdentifier>(idToData.keySet()); checkNonDeletedObjs(user, idToData); assertThat("can get ws description", ws.getWorkspaceDescription(user, read), is("descrip")); checkWSInfo(ws.getWorkspaceInformation(user, read), user, "deleteundelete", 1, Permission.OWNER, false, "unlocked", MT_META); WorkspaceUser bar = new WorkspaceUser("bar"); ws.setPermissions(user, read, Arrays.asList(bar), Permission.ADMIN); Map<User, Permission> p = new HashMap<User, Permission>(); p.put(user, Permission.OWNER); p.put(bar, Permission.ADMIN); assertThat("can get perms", ws.getPermissions(user, read), is(p)); try { ws.setWorkspaceDeleted(bar, read, true); fail("Non owner deleted workspace"); } catch (WorkspaceAuthorizationException e) { assertThat("correct exception msg", e.getLocalizedMessage(), is("User bar may not delete workspace deleteundelete")); } WorkspaceInformation read1 = ws.getWorkspaceInformation(user, read); ws.setWorkspaceDeleted(user, read, true); WorkspaceInformation read2 = ws.listWorkspaces(user, null, null, null, null, null, true, true, false).get(0); try { ws.getWorkspaceDescription(user, read); fail("got description from deleted workspace"); } catch (NoSuchWorkspaceException e) { assertThat("correct exception msg", e.getLocalizedMessage(), is("Workspace deleteundelete is deleted")); } try { ws.getWorkspaceInformation(user, read); fail("got meta from deleted workspace"); } catch (NoSuchWorkspaceException e) { assertThat("correct exception msg", e.getLocalizedMessage(), is("Workspace deleteundelete is deleted")); } try { ws.setPermissions(user, read, Arrays.asList(bar), Permission.NONE); fail("set perms on deleted workspace"); } catch (NoSuchWorkspaceException e) { assertThat("correct exception msg", e.getLocalizedMessage(), is("Workspace deleteundelete is deleted")); } try { ws.getPermissions(user, read); fail("got perms from deleted workspace"); } catch (NoSuchWorkspaceException e) { assertThat("correct exception msg", e.getLocalizedMessage(), is("Workspace deleteundelete is deleted")); } failGetObjects(bar, objs, new InaccessibleObjectException( "Object obj cannot be accessed: Workspace deleteundelete is deleted")); try { ws.getObjectInformation(bar, objs, false, false); fail("got obj meta from deleted workspace"); } catch (InaccessibleObjectException ioe) { assertThat("correct exception msg", ioe.getLocalizedMessage(), is("Object obj cannot be accessed: Workspace deleteundelete is deleted")); } try { ws.saveObjects(bar, read, Arrays.asList(sobj1), getIdFactory(bar)); fail("saved objs from deleted workspace"); } catch (NoSuchWorkspaceException e) { assertThat("correct exception msg", e.getLocalizedMessage(), is("Workspace deleteundelete is deleted")); } try { ws.setObjectsDeleted(bar, obj1, true); } catch (InaccessibleObjectException ioe) { assertThat("correct exception msg", ioe.getLocalizedMessage(), is("Object obj cannot be accessed: Workspace deleteundelete is deleted")); assertThat("correct object returned", ioe.getInaccessibleObject(), is(o1)); } ws.setWorkspaceDeleted(user, read, false); WorkspaceInformation read3 = ws.getWorkspaceInformation(user, read); checkNonDeletedObjs(user, idToData); assertThat("can get ws description", ws.getWorkspaceDescription(user, read), is("descrip")); checkWSInfo(ws.getWorkspaceInformation(user, read), user, "deleteundelete", 1, Permission.OWNER, false, "unlocked", MT_META); ws.setPermissions(user, read, Arrays.asList(bar), Permission.ADMIN); assertThat("can get perms", ws.getPermissions(user, read), is(p)); assertTrue("date changed on delete", read1.getModDate().before(read2.getModDate())); assertTrue("date changed on undelete", read2.getModDate().before(read3.getModDate())); } @Test public void testTypeMd5s() throws Exception { //see setUpWorkspaces() to find where needed specs are loaded String typeDefName = "SomeModule.AType"; Map<String,String> type2md5 = ws.translateToMd5Types(Arrays.asList(typeDefName + "-1.0"),null); Assert.assertEquals(1, type2md5.size()); String md5TypeDef = type2md5.get(typeDefName + "-1.0"); Assert.assertNotNull(md5TypeDef); Map<String, List<String>> md52semantic = ws.translateFromMd5Types(Arrays.asList(md5TypeDef)); Assert.assertEquals(1, md52semantic.size()); List<String> semList = md52semantic.get(md5TypeDef); Assert.assertNotNull(semList); Assert.assertEquals(2, semList.size()); for (String semText : semList) { TypeDefId semTypeDef = TypeDefId.fromTypeString(semText); Assert.assertEquals(typeDefName, semTypeDef.getType().getTypeString()); String verText = semTypeDef.getVerString(); Assert.assertTrue("0.1".equals(verText) || "1.0".equals(verText)); } } @Test public void testListModules() throws Exception { //see setUpWorkspaces() to find where needed specs are loaded Map<String,String> moduleNamesInList = new HashMap<String,String>(); for(String mod:ws.listModules(null)) { moduleNamesInList.put(mod, ""); } Assert.assertTrue(moduleNamesInList.containsKey("SomeModule")); Assert.assertTrue(moduleNamesInList.containsKey("TestModule")); } @Test public void testListModuleVersions() throws Exception { //see setUpWorkspaces() to find where needed specs are loaded Assert.assertEquals(3, ws.getModuleVersions("SomeModule", null).size()); Assert.assertEquals(4, ws.getModuleVersions("SomeModule", new WorkspaceUser("foo")).size()); Assert.assertEquals(2, ws.getModuleVersions("TestModule", null).size()); Assert.assertEquals(5, ws.getModuleVersions("TestModule", new WorkspaceUser("foo")).size()); } @Test public void testGetModuleInfo() throws Exception { //see setUpWorkspaces() to find where needed specs are loaded ModuleInfo m = ws.getModuleInfo(null, new ModuleDefId("TestModule")); Assert.assertTrue(m.isReleased()); Map<String,String> funcNamesInList = new HashMap<String,String>(); for(String func : m.getFunctions() ){ funcNamesInList.put(func, ""); } Assert.assertTrue(funcNamesInList.containsKey("TestModule.getFeature-2.0")); Assert.assertTrue(funcNamesInList.containsKey("TestModule.getGenome-1.0")); Map<String,String> typeNamesInList = new HashMap<String,String>(); for(Entry<AbsoluteTypeDefId, String> type : m.getTypes().entrySet() ){ typeNamesInList.put(type.getKey().getTypeString(),""); } Assert.assertTrue(typeNamesInList.containsKey("TestModule.Genome-2.0")); Assert.assertTrue(typeNamesInList.containsKey("TestModule.Feature-1.0")); try { ws.getModuleInfo(null, new ModuleDefId("MadeUpModuleThatIsNotThere")); fail("getModuleInfo of non existant module should throw a NoSuchModuleException"); } catch (NoSuchModuleException e) {} ModuleInfo m2 = ws.getModuleInfo(new WorkspaceUser("foo"), new ModuleDefId("UnreleasedModule")); Assert.assertEquals("foo", m2.getOwners().get(0)); Assert.assertFalse(m2.isReleased()); List<Long> verList = ws.getModuleVersions("UnreleasedModule", new WorkspaceUser("foo")); Assert.assertEquals(1, verList.size()); Assert.assertEquals(m2.getVersion(), verList.get(0)); } @Test public void testGetJsonSchema() throws Exception { //see setUpWorkspaces() to find where needed specs are loaded try { ws.getJsonSchema(new TypeDefId("TestModule.NonExistantType"), null); fail("getJsonSchema of non existant type should throw a NoSuchTypeException"); } catch (NoSuchTypeException e) {} // get several different schemas, make sure that no exceptions are thrown and it is valid json! String schema = ws.getJsonSchema(new TypeDefId(new TypeDefName("TestModule.Genome"),2,0), null); ObjectMapper mapper = new ObjectMapper(); JsonNode schemaNode = mapper.readTree(schema); Assert.assertEquals("Genome", schemaNode.get("id").asText()); schema = ws.getJsonSchema(new TypeDefId(new TypeDefName("TestModule.Genome"),2), null); schemaNode = mapper.readTree(schema); Assert.assertEquals("Genome", schemaNode.get("id").asText()); schema = ws.getJsonSchema(new TypeDefId("TestModule.Genome"), null); schemaNode = mapper.readTree(schema); Assert.assertEquals("Genome", schemaNode.get("id").asText()); } @Test public void testGetTypeInfo() throws Exception { //see setUpWorkspaces() to find where needed specs are loaded TypeDetailedInfo info = ws.getTypeInfo("TestModule.Genome", false, null); Assert.assertEquals("TestModule.Genome-2.0",info.getTypeDefId()); Assert.assertEquals(1, info.getReleasedModuleVersions().size()); Assert.assertEquals(2, info.getReleasedTypeVersions().size()); info = ws.getTypeInfo("TestModule.Feature", false, null); Assert.assertEquals("TestModule.Feature-1.0",info.getTypeDefId()); Assert.assertEquals(2, info.getReleasedModuleVersions().size()); Assert.assertEquals(1, info.getReleasedTypeVersions().size()); TypeDetailedInfo info2 = ws.getTypeInfo("UnreleasedModule.AType-0.1", false, new WorkspaceUser("foo")); Assert.assertEquals(1, info2.getUsingFuncDefIds().size()); Assert.assertEquals(1, info2.getModuleVersions().size()); Assert.assertEquals(1, info2.getTypeVersions().size()); Assert.assertEquals(0, info2.getReleasedModuleVersions().size()); Assert.assertEquals(0, info2.getReleasedTypeVersions().size()); Assert.assertTrue(info2.getJsonSchema().contains("kidl-structure")); Assert.assertTrue(info2.getParsingStructure().contains("Bio::KBase::KIDL::KBT::Typedef")); } @Test public void testGetFuncInfo() throws Exception { //see setUpWorkspaces() to find where needed specs are loaded try { ws.getFuncInfo("NoModuleThatExists.getFeature", false, null); fail("getFuncInfo of non existant module should throw a NoSuchModuleException"); } catch (NoSuchModuleException e) {} try { ws.getFuncInfo("TestModule.noFunctionThatIKnowOf", false, null); fail("getFuncInfo of non existant module should throw a NoSuchFuncException"); } catch (NoSuchFuncException e) {} FuncDetailedInfo info = ws.getFuncInfo("TestModule.getFeature", false, null); Assert.assertEquals("TestModule.getFeature-2.0",info.getFuncDefId()); Assert.assertEquals(1, info.getReleasedModuleVersions().size()); Assert.assertEquals(2, info.getReleasedFuncVersions().size()); info = ws.getFuncInfo("TestModule.getGenome-1.0", false, null); Assert.assertEquals("TestModule.getGenome-1.0",info.getFuncDefId()); Assert.assertEquals(1, info.getReleasedModuleVersions().size()); Assert.assertEquals(1, info.getReleasedFuncVersions().size()); FuncDetailedInfo info2 = ws.getFuncInfo("UnreleasedModule.aFunc-0.1", false, new WorkspaceUser("foo")); Assert.assertEquals(1, info2.getUsedTypeDefIds().size()); Assert.assertEquals(1, info2.getModuleVersions().size()); Assert.assertEquals(1, info2.getFuncVersions().size()); Assert.assertEquals(0, info2.getReleasedModuleVersions().size()); Assert.assertEquals(0, info2.getReleasedFuncVersions().size()); Assert.assertTrue(info2.getParsingStructure().contains("Bio::KBase::KIDL::KBT::Funcdef")); } private void setUpCopyWorkspaces(WorkspaceUser user1, WorkspaceUser user2, String refws, String ws1, String ws2) throws Exception { TypeDefId reftype = new TypeDefId(new TypeDefName("CopyRev", "RefType"), 1, 0); WorkspaceIdentifier refs = new WorkspaceIdentifier(refws); ws.createWorkspace(user1, refs.getName(), false, null, null); LinkedList<WorkspaceSaveObject> refobjs = new LinkedList<WorkspaceSaveObject>(); for (int i = 0; i < 4; i++) { refobjs.add(new WorkspaceSaveObject(new HashMap<String, String>(), SAFE_TYPE1, null, new Provenance(user1), false)); } ws.saveObjects(user1, refs, refobjs, getIdFactory(user1)); List<WorkspaceSaveObject> wso = Arrays.asList(new WorkspaceSaveObject( new ObjectIDNoWSNoVer("auto2"), new HashMap<String, String>(), SAFE_TYPE1, null, new Provenance(user1), false)); ws.saveObjects(user1, refs, wso, getIdFactory(user1)); ws.saveObjects(user1, refs, wso, getIdFactory(user1)); Map<String, String> meta1 = makeSimpleMeta("foo", "bar"); Map<String, String> meta2 = makeSimpleMeta("foo", "baz"); Map<String, String> meta3 = makeSimpleMeta("foo", "bak"); Map<String, List<String>> data1 = makeRefData(refws + "/auto2/2"); Map<String, List<String>> data2 = makeRefData(refws + "/auto4"); Map<String, List<String>> data3 = makeRefData(refws + "/auto1"); Provenance prov1 = new Provenance(user1); prov1.addAction(new ProvenanceAction() .withCommandLine("A command line") .withDescription("descrip") .withIncomingArgs(Arrays.asList("a", "b", "c")) .withMethod("method") .withMethodParameters(Arrays.asList((Object) meta1)) .withOutgoingArgs(Arrays.asList("d", "e", "f")) .withScript("script") .withScriptVersion("2.1") .withServiceName("service") .withServiceVersion("3") .withTime(new Date(45)) .withWorkspaceObjects(Arrays.asList(refws + "/auto3", refws + "/auto2/2"))); prov1.addAction(new ProvenanceAction() .withWorkspaceObjects(Arrays.asList(refws + "/auto2/1", refws + "/auto1"))); Provenance prov2 = new Provenance(user1); Provenance prov3 = new Provenance(user1); prov2.addAction(new ProvenanceAction(prov1.getActions().get(0)).withServiceVersion("4") .withWorkspaceObjects(Arrays.asList(refws + "/auto2"))); prov3.addAction(new ProvenanceAction(prov1.getActions().get(0)).withServiceVersion("5") .withWorkspaceObjects(Arrays.asList(refws + "/auto3/1"))); WorkspaceIdentifier cp1 = new WorkspaceIdentifier(ws1); WorkspaceIdentifier cp2 = new WorkspaceIdentifier(ws2); ws.createWorkspace(user1, cp1.getName(), false, null, null).getId(); ws.createWorkspace(user2, cp2.getName(), false, null, null).getId(); saveObject(user1, cp1, meta1, data1, reftype, "hide", prov1, true); saveObject(user1, cp1, meta2, data2, reftype, "hide", prov2, true); saveObject(user1, cp1, meta3, data3, reftype, "hide", prov2, true); saveObject(user1, cp1, meta1, data1, reftype, "orig", prov1); saveObject(user1, cp1, meta2, data2, reftype, "orig", prov2); saveObject(user1, cp1, meta3, data3, reftype, "orig", prov3); saveObject(user1, cp1, meta1, data1, reftype, "hidetarget", prov1, true); } @Test public void copyRevert() throws Exception { WorkspaceUser user1 = new WorkspaceUser("foo"); WorkspaceUser user2 = new WorkspaceUser("bar"); String wsrefs = "copyrevertrefs"; String ws1 = "copyrevert1"; String ws2 = "copyrevert2"; setUpCopyWorkspaces(user1, user2, wsrefs, ws1, ws2); WorkspaceIdentifier cp1 = new WorkspaceIdentifier(ws1); WorkspaceIdentifier cp2 = new WorkspaceIdentifier(ws2); WorkspaceInformation cp1info = ws.getWorkspaceInformation(user1, cp1); WorkspaceInformation cp2info = ws.getWorkspaceInformation(user2, cp2); long wsid1 = cp1info.getId(); long wsid2 = cp2info.getId(); Date cp1LastDate = cp1info.getModDate(); Date cp2LastDate = cp2info.getModDate(); ObjectIdentifier oihide = new ObjectIdentifier(cp1, "hide"); List<ObjectInformation> objs = ws.getObjectHistory(user1, oihide); ObjectInformation save11 = objs.get(0); ObjectInformation save12 = objs.get(1); ObjectInformation save13 = objs.get(2); WorkspaceObjectData wod = ws.getObjects(user1, Arrays.asList(oihide)).get(0); WorkspaceObjectData swod = ws.getObjectsSubSet(user1, objIDToSubObjID(Arrays.asList(oihide))).get(0); WorkspaceObjectInformation woi = ws.getObjectProvenance(user1, Arrays.asList(oihide)).get(0); assertThat("copy ref for obj is null", wod.getCopyReference(), is((Reference) null)); assertThat("copy ref for sub obj is null", swod.getCopyReference(), is((Reference) null)); assertThat("copy ref for prov is null", woi.getCopyReference(), is((Reference) null)); //copy entire stack of hidden objects cp1LastDate = ws.getWorkspaceInformation(user1, cp1).getModDate(); ObjectInformation copied = ws.copyObject(user1, ObjectIdentifier.parseObjectReference("copyrevert1/hide"), ObjectIdentifier.parseObjectReference("copyrevert1/copyhide")); cp1LastDate = assertWorkspaceDateUpdated(user1, cp1, cp1LastDate, "ws date updated on copy"); compareObjectAndInfo(save13, copied, user1, wsid1, cp1.getName(), 4, "copyhide", 3); List<ObjectInformation> copystack = ws.getObjectHistory(user1, new ObjectIdentifier(cp1, 4)); compareObjectAndInfo(save11, copystack.get(0), user1, wsid1, cp1.getName(), 4, "copyhide", 1); compareObjectAndInfo(save12, copystack.get(1), user1, wsid1, cp1.getName(), 4, "copyhide", 2); compareObjectAndInfo(save13, copystack.get(2), user1, wsid1, cp1.getName(), 4, "copyhide", 3); checkUnhiddenObjectCount(user1, cp1, 6, 10); objs = ws.getObjectHistory(user1, new ObjectIdentifier(cp1, "orig")); save11 = objs.get(0); save12 = objs.get(1); save13 = objs.get(2); //copy stack of unhidden objects copied = ws.copyObject(user1, ObjectIdentifier.parseObjectReference("copyrevert1/orig"), ObjectIdentifier.parseObjectReference("copyrevert1/copied")); cp1LastDate = assertWorkspaceDateUpdated(user1, cp1, cp1LastDate, "ws date updated on copy"); compareObjectAndInfo(save13, copied, user1, wsid1, cp1.getName(), 5, "copied", 3); copystack = ws.getObjectHistory(user1, new ObjectIdentifier(cp1, "copied")); compareObjectAndInfo(save11, copystack.get(0), user1, wsid1, cp1.getName(), 5, "copied", 1); compareObjectAndInfo(save12, copystack.get(1), user1, wsid1, cp1.getName(), 5, "copied", 2); compareObjectAndInfo(save13, copystack.get(2), user1, wsid1, cp1.getName(), 5, "copied", 3); checkUnhiddenObjectCount(user1, cp1, 9, 13); //copy visible object to pre-existing hidden object copied = ws.copyObject(user1, ObjectIdentifier.parseObjectReference("copyrevert1/orig"), new ObjectIdentifier(cp1, "hidetarget")); cp1LastDate = assertWorkspaceDateUpdated(user1, cp1, cp1LastDate, "ws date updated on copy"); compareObjectAndInfo(save13, copied, user1, wsid1, cp1.getName(), 3, "hidetarget", 2); copystack = ws.getObjectHistory(user1, new ObjectIdentifier(cp1, 3)); //0 is original object compareObjectAndInfo(save13, copystack.get(1), user1, wsid1, cp1.getName(), 3, "hidetarget", 2); checkUnhiddenObjectCount(user1, cp1, 9, 14); //copy hidden object to pre-existing visible object //check that the to version is ignored copied = ws.copyObject(user1, new ObjectIdentifier(cp1, "orig"), new ObjectIdentifier(cp1, 5, 600)); compareObjectAndInfo(save13, copied, user1, wsid1, cp1.getName(), 5, "copied", 4); copystack = ws.getObjectHistory(user1, new ObjectIdentifier(cp1, 5)); compareObjectAndInfo(save13, copystack.get(3), user1, wsid1, cp1.getName(), 5, "copied", 4); checkUnhiddenObjectCount(user1, cp1, 10, 15); //copy specific version to existing object copied = ws.copyObject(user1, new ObjectIdentifier(new WorkspaceIdentifier(wsid1), 2, 2), ObjectIdentifier.parseObjectReference("copyrevert1/copied")); compareObjectAndInfo(save12, copied, user1, wsid1, cp1.getName(), 5, "copied", 5); copystack = ws.getObjectHistory(user1, new ObjectIdentifier(cp1, "copied")); compareObjectAndInfo(save11, copystack.get(0), user1, wsid1, cp1.getName(), 5, "copied", 1); compareObjectAndInfo(save12, copystack.get(1), user1, wsid1, cp1.getName(), 5, "copied", 2); compareObjectAndInfo(save13, copystack.get(2), user1, wsid1, cp1.getName(), 5, "copied", 3); compareObjectAndInfo(save13, copystack.get(3), user1, wsid1, cp1.getName(), 5, "copied", 4); compareObjectAndInfo(save12, copystack.get(4), user1, wsid1, cp1.getName(), 5, "copied", 5); checkUnhiddenObjectCount(user1, cp1, 11, 16); //copy specific version to hidden existing object copied = ws.copyObject(user1, new ObjectIdentifier(new WorkspaceIdentifier(wsid1), 2, 2), ObjectIdentifier.parseObjectReference("copyrevert1/hidetarget")); compareObjectAndInfo(save12, copied, user1, wsid1, cp1.getName(), 3, "hidetarget", 3); copystack = ws.getObjectHistory(user1, new ObjectIdentifier(cp1, "hidetarget")); //0 is original object compareObjectAndInfo(save13, copystack.get(1), user1, wsid1, cp1.getName(), 3, "hidetarget", 2); compareObjectAndInfo(save12, copystack.get(2), user1, wsid1, cp1.getName(), 3, "hidetarget", 3); checkUnhiddenObjectCount(user1, cp1, 11, 17); //copy specific version to new object copied = ws.copyObject(user1, new ObjectIdentifier(new WorkspaceIdentifier(wsid1), 2, 2), ObjectIdentifier.parseObjectReference("copyrevert1/newobj")); compareObjectAndInfo(save12, copied, user1, wsid1, cp1.getName(), 6, "newobj", 1); copystack = ws.getObjectHistory(user1, new ObjectIdentifier(cp1, "newobj")); compareObjectAndInfo(save12, copystack.get(0), user1, wsid1, cp1.getName(), 6, "newobj", 1); checkUnhiddenObjectCount(user1, cp1, 12, 18); //revert normal object cp1LastDate = ws.getWorkspaceInformation(user1, cp1).getModDate(); copied = ws.revertObject(user1, ObjectIdentifier.parseObjectReference("copyrevert1/copied/2")); cp1LastDate = assertWorkspaceDateUpdated(user1, cp1, cp1LastDate, "ws date updated on revert"); compareObjectAndInfo(save12, copied, user1, wsid1, cp1.getName(), 5, "copied", 6); copystack = ws.getObjectHistory(user1, new ObjectIdentifier(cp1, "copied")); compareObjectAndInfo(save11, copystack.get(0), user1, wsid1, cp1.getName(), 5, "copied", 1); compareObjectAndInfo(save12, copystack.get(1), user1, wsid1, cp1.getName(), 5, "copied", 2); compareObjectAndInfo(save13, copystack.get(2), user1, wsid1, cp1.getName(), 5, "copied", 3); compareObjectAndInfo(save13, copystack.get(3), user1, wsid1, cp1.getName(), 5, "copied", 4); compareObjectAndInfo(save12, copystack.get(4), user1, wsid1, cp1.getName(), 5, "copied", 5); compareObjectAndInfo(save12, copystack.get(5), user1, wsid1, cp1.getName(), 5, "copied", 6); checkUnhiddenObjectCount(user1, cp1, 13, 19); //revert hidden object copied = ws.revertObject(user1, ObjectIdentifier.parseObjectReference("copyrevert1/hidetarget/2")); cp1LastDate = assertWorkspaceDateUpdated(user1, cp1, cp1LastDate, "ws date updated on revert"); compareObjectAndInfo(save13, copied, user1, wsid1, cp1.getName(), 3, "hidetarget", 4); copystack = ws.getObjectHistory(user1, new ObjectIdentifier(cp1, "hidetarget")); //0 is original object compareObjectAndInfo(save13, copystack.get(1), user1, wsid1, cp1.getName(), 3, "hidetarget", 2); compareObjectAndInfo(save12, copystack.get(2), user1, wsid1, cp1.getName(), 3, "hidetarget", 3); compareObjectAndInfo(save13, copystack.get(3), user1, wsid1, cp1.getName(), 3, "hidetarget", 4); checkUnhiddenObjectCount(user1, cp1, 13, 20); //copy to new ws ws.setPermissions(user2, cp2, Arrays.asList(user1), Permission.WRITE); cp2LastDate = ws.getWorkspaceInformation(user1, cp2).getModDate(); copied = ws.copyObject(user1, ObjectIdentifier.parseObjectReference("copyrevert1/orig"), ObjectIdentifier.parseObjectReference("copyrevert2/copied")); cp2LastDate = assertWorkspaceDateUpdated(user1, cp2, cp2LastDate, "ws date updated on copy"); compareObjectAndInfo(save13, copied, user1, wsid2, cp2.getName(), 1, "copied", 3); copystack = ws.getObjectHistory(user1, new ObjectIdentifier(cp2, "copied")); compareObjectAndInfo(save11, copystack.get(0), user1, wsid2, cp2.getName(), 1, "copied", 1); compareObjectAndInfo(save12, copystack.get(1), user1, wsid2, cp2.getName(), 1, "copied", 2); compareObjectAndInfo(save13, copystack.get(2), user1, wsid2, cp2.getName(), 1, "copied", 3); checkUnhiddenObjectCount(user1, cp2, 3, 3); checkUnhiddenObjectCount(user1, cp1, 13, 20); //copy to deleted object ws.setObjectsDeleted(user1, Arrays.asList( ObjectIdentifier.parseObjectReference("copyrevert1/copied")), true); copied = ws.copyObject(user1, ObjectIdentifier.parseObjectReference("copyrevert1/orig"), ObjectIdentifier.parseObjectReference("copyrevert1/copied")); compareObjectAndInfo(save13, copied, user1, wsid1, cp1.getName(), 5, "copied", 7); copystack = ws.getObjectHistory(user1, new ObjectIdentifier(cp1, "copied")); compareObjectAndInfo(save11, copystack.get(0), user1, wsid1, cp1.getName(), 5, "copied", 1); compareObjectAndInfo(save12, copystack.get(1), user1, wsid1, cp1.getName(), 5, "copied", 2); compareObjectAndInfo(save13, copystack.get(2), user1, wsid1, cp1.getName(), 5, "copied", 3); compareObjectAndInfo(save13, copystack.get(3), user1, wsid1, cp1.getName(), 5, "copied", 4); compareObjectAndInfo(save12, copystack.get(4), user1, wsid1, cp1.getName(), 5, "copied", 5); compareObjectAndInfo(save12, copystack.get(5), user1, wsid1, cp1.getName(), 5, "copied", 6); compareObjectAndInfo(save13, copystack.get(6), user1, wsid1, cp1.getName(), 5, "copied", 7); checkUnhiddenObjectCount(user1, cp1, 14, 21); failCopy(null, new ObjectIdentifier(cp1, "whooga"), new ObjectIdentifier(cp1, "hidetarget"), new InaccessibleObjectException( "Object whooga cannot be accessed: Anonymous users may not read workspace copyrevert1")); failRevert(null, new ObjectIdentifier(cp1, "whooga"), new InaccessibleObjectException( "Object whooga cannot be accessed: Anonymous users may not write to workspace copyrevert1")); failCopy(user1, new ObjectIdentifier(cp1, "foo"), new ObjectIdentifier(cp1, "bar"), new NoSuchObjectException( "No object with name foo exists in workspace " + wsid1)); failRevert(user1, new ObjectIdentifier(cp1, "foo"), new NoSuchObjectException( "No object with name foo exists in workspace " + wsid1)); failRevert(user1, new ObjectIdentifier(cp1, "orig", 4), new NoSuchObjectException( "No object with id 2 (name orig) and version 4 exists in workspace " + wsid1)); failCopy(user1, new ObjectIdentifier(cp1, "orig"), new ObjectIdentifier(cp1, 7), new NoSuchObjectException( "Copy destination is specified as object id 7 in workspace " + wsid1 + " which does not exist.")); ws.setObjectsDeleted(user1, Arrays.asList(new ObjectIdentifier(cp1, "copied")), true); failCopy(user1, new ObjectIdentifier(cp1, "copied"), new ObjectIdentifier(cp1, "hidetarget"), new NoSuchObjectException( "Object 5 (name copied) in workspace " + wsid1 + " has been deleted")); failRevert(user1, new ObjectIdentifier(cp1, "copied"), new NoSuchObjectException( "Object 5 (name copied) in workspace " + wsid1 + " has been deleted")); //now works // failCopy(user1, new ObjectIdentifier(cp1, "orig"), // new ObjectIdentifier(cp1, "copied"), new NoSuchObjectException( // "Object 5 (name copied) in workspace " + wsid1 + " has been deleted")); cp2LastDate = ws.getWorkspaceInformation(user1, cp2).getModDate(); ws.copyObject(user1, new ObjectIdentifier(cp1, "orig"), new ObjectIdentifier(cp2, "foo")); //should work cp2LastDate = assertWorkspaceDateUpdated(user1, cp2, cp2LastDate, "ws date updated on copy"); ws.setWorkspaceDeleted(user2, cp2, true); failCopy(user1, new ObjectIdentifier(cp1, "orig"), new ObjectIdentifier(cp2, "foo1"), new InaccessibleObjectException("Object foo1 cannot be accessed: Workspace copyrevert2 is deleted")); failCopy(user1, new ObjectIdentifier(cp2, "foo"), new ObjectIdentifier(cp2, "foo1"), new InaccessibleObjectException("Object foo cannot be accessed: Workspace copyrevert2 is deleted")); failRevert(user1, new ObjectIdentifier(cp2, "foo"), new InaccessibleObjectException("Object foo cannot be accessed: Workspace copyrevert2 is deleted")); ws.setWorkspaceDeleted(user2, cp2, false); ws.setPermissions(user2, cp2, Arrays.asList(user1), Permission.READ); ws.copyObject(user1, new ObjectIdentifier(cp2, "foo"), new ObjectIdentifier(cp1, "foo")); //should work failCopy(user1, new ObjectIdentifier(cp1, "foo"), new ObjectIdentifier(cp2, "foo"), new InaccessibleObjectException("Object foo cannot be accessed: User foo may not write to workspace copyrevert2")); failRevert(user1, new ObjectIdentifier(cp2, "foo", 1), new InaccessibleObjectException("Object foo cannot be accessed: User foo may not write to workspace copyrevert2")); ws.setPermissions(user2, cp2, Arrays.asList(user1), Permission.NONE); failCopy(user1, new ObjectIdentifier(cp2, "foo"), new ObjectIdentifier(cp1, "foo"), new InaccessibleObjectException("Object foo cannot be accessed: User foo may not read workspace copyrevert2")); ws.setPermissions(user2, cp2, Arrays.asList(user1), Permission.WRITE); ws.lockWorkspace(user2, cp2); failCopy(user1, new ObjectIdentifier(cp1, "orig"), new ObjectIdentifier(cp2, "foo2"), new InaccessibleObjectException( "Object foo2 cannot be accessed: The workspace with id " + wsid2 + ", name copyrevert2, is locked and may not be modified")); failRevert(user1, new ObjectIdentifier(cp2, "foo1", 1), new InaccessibleObjectException( "Object foo1 cannot be accessed: The workspace with id " + wsid2 + ", name copyrevert2, is locked and may not be modified")); } private void checkUnhiddenObjectCount(WorkspaceUser user, WorkspaceIdentifier wsi, int unhidden, int all) throws Exception { List<ObjectInformation> objs = ws.listObjects(user, Arrays.asList(wsi), null, null, null, null, null, null, false, false, false, true, false, false, -1, -1); assertThat("orig objects hidden", objs.size(), is(unhidden)); objs = ws.listObjects(user, Arrays.asList(wsi), null, null, null, null, null, null, true, false, false, true, false, false, -1, -1); assertThat("orig objects hidden", objs.size(), is(all)); } @Test public void copyReferenceVisibility() throws Exception { WorkspaceUser user1 = new WorkspaceUser("foo"); WorkspaceUser user2 = new WorkspaceUser("foo2"); WorkspaceIdentifier wsiSource1 = new WorkspaceIdentifier("copyRefVisSource1"); WorkspaceIdentifier wsiSource2 = new WorkspaceIdentifier("copyRefVisSource2"); WorkspaceIdentifier wsiCopied = new WorkspaceIdentifier("copyRefVisCopied"); long wsid1 = ws.createWorkspace(user1, wsiSource1.getName(), false, null, null).getId(); ws.setPermissions(user1, wsiSource1, Arrays.asList(user2), Permission.READ); long wsid2 = ws.createWorkspace(user1, wsiSource2.getName(), false, null, null).getId(); ws.setPermissions(user1, wsiSource2, Arrays.asList(user2), Permission.READ); ws.createWorkspace(user2, wsiCopied.getName(), false, null, null); Provenance emptyprov1 = new Provenance(user1); Provenance emptyprov2 = new Provenance(user2); List<WorkspaceSaveObject> data = new LinkedList<WorkspaceSaveObject>(); data.add(new WorkspaceSaveObject(new HashMap<String, Object>(), SAFE_TYPE1, null, emptyprov1, false)); ws.saveObjects(user1, wsiSource1, data, new IdReferenceHandlerSetFactory(0)); ws.saveObjects(user1, wsiSource2, data, new IdReferenceHandlerSetFactory(0)); final ObjectIdentifier source1 = new ObjectIdentifier(wsiSource1, 1); final ObjectIdentifier source2 = new ObjectIdentifier(wsiSource2, 1); final ObjectIdentifier copied1 = new ObjectIdentifier(wsiCopied, "foo"); final ObjectIdentifier copied2 = new ObjectIdentifier(wsiCopied, "foo1"); ws.copyObject(user2, source1, copied1); ws.copyObject(user2, source2, copied2); ws.saveObjects(user2, wsiCopied, data, new IdReferenceHandlerSetFactory(0)); final ObjectIdentifier nocopy = new ObjectIdentifier(wsiCopied, 3L); data.clear(); Map<String, Object> ref = new HashMap<String, Object>(); ref.put("refs", Arrays.asList(wsiCopied.getName() + "/foo")); data.add(new WorkspaceSaveObject(ref, REF_TYPE, null, emptyprov2, false)); ws.saveObjects(user2, wsiCopied, data, new IdReferenceHandlerSetFactory(1)); ObjectChain copyoc1 = new ObjectChain(new ObjectIdentifier(wsiCopied, 4L), Arrays.asList(copied1)); ref.put("refs", Arrays.asList(wsiCopied.getName() + "/foo1")); ws.saveObjects(user2, wsiCopied, data, new IdReferenceHandlerSetFactory(1)); ObjectChain copyoc2 = new ObjectChain(new ObjectIdentifier(wsiCopied, 5L), Arrays.asList(copied2)); ref.put("refs", Arrays.asList(wsiCopied.getName() + "/3")); ws.saveObjects(user2, wsiCopied, data, new IdReferenceHandlerSetFactory(1)); ObjectChain nocopyoc = new ObjectChain(new ObjectIdentifier(wsiCopied, 6L), Arrays.asList(nocopy)); final TestReference expectedRef1 = new TestReference(wsid1, 1, 1); final TestReference expectedRef2 = new TestReference(wsid2, 1, 1); List<ObjectIdentifier> testobjs = Arrays.asList(copied1, nocopy, copied2); List<ObjectChain> testocs = Arrays.asList(copyoc1, nocopyoc, copyoc2); List<TestReference> refnullref = Arrays.asList( expectedRef1, (TestReference) null, expectedRef2); List<TestReference> nullnullref = Arrays.asList( (TestReference) null, (TestReference) null, expectedRef2); List<TestReference> refnullnull = Arrays.asList( expectedRef1, (TestReference) null, (TestReference) null); List<Boolean> fff = Arrays.asList(false, false, false); List<Boolean> tff = Arrays.asList(true, false, false); List<Boolean> fft = Arrays.asList(false, false, true); checkCopyReference(user2, testobjs, testocs, refnullref, fff); //check 1st ref ws.setPermissions(user1, wsiSource1, Arrays.asList(user2), Permission.NONE); checkCopyReference(user2, testobjs, testocs, nullnullref, tff); ws.setPermissions(user1, wsiSource1, Arrays.asList(user2), Permission.READ); checkCopyReference(user2, testobjs, testocs, refnullref, fff); ws.setObjectsDeleted(user1, Arrays.asList(source1), true); checkCopyReference(user2, testobjs, testocs, nullnullref, tff); ws.setObjectsDeleted(user1, Arrays.asList(source1), false); checkCopyReference(user2, testobjs, testocs, refnullref, fff); ws.setWorkspaceDeleted(user1, wsiSource1, true); checkCopyReference(user2, testobjs, testocs, nullnullref, tff); ws.setWorkspaceDeleted(user1, wsiSource1, false); checkCopyReference(user2, testobjs, testocs, refnullref, fff); //check 2nd ref ws.setPermissions(user1, wsiSource2, Arrays.asList(user2), Permission.NONE); checkCopyReference(user2, testobjs, testocs, refnullnull, fft); ws.setPermissions(user1, wsiSource2, Arrays.asList(user2), Permission.READ); checkCopyReference(user2, testobjs, testocs, refnullref, fff); ws.setObjectsDeleted(user1, Arrays.asList(source2), true); checkCopyReference(user2, testobjs, testocs, refnullnull, fft); ws.setObjectsDeleted(user1, Arrays.asList(source2), false); checkCopyReference(user2, testobjs, testocs, refnullref, fff); ws.setWorkspaceDeleted(user1, wsiSource2, true); checkCopyReference(user2, testobjs, testocs, refnullnull, fft); ws.setWorkspaceDeleted(user1, wsiSource2, false); checkCopyReference(user2, testobjs, testocs, refnullref, fff); } private void checkCopyReference(WorkspaceUser user, List<ObjectIdentifier> testobjs, List<ObjectChain> testocs, List<TestReference> testRef, List<Boolean> copyAccessible) throws Exception { List<List<WorkspaceObjectInformation>> infos = new LinkedList<List<WorkspaceObjectInformation>>(); infos.add(ws.getObjectProvenance(user, testobjs)); infos.add(fromObjectData(ws.getObjects(user, testobjs))); infos.add(fromObjectData(ws.getObjectsSubSet(user, objIDToSubObjID(testobjs)))); infos.add(fromObjectData(ws.getReferencedObjects(user, testocs))); for (List<WorkspaceObjectInformation> info: infos) { for (int i = 0; i < info.size(); i++) { WorkspaceObjectInformation inf = info.get(i); assertThat("correct reference ", inf.getCopyReference() == null ? null : new TestReference(inf.getCopyReference()), is(testRef.get(i))); assertThat("correct inaccessibility", inf.isCopySourceInaccessible(), is(copyAccessible.get(i))); } } } private List<WorkspaceObjectInformation> fromObjectData( List<WorkspaceObjectData> data) { List<WorkspaceObjectInformation> ret = new LinkedList<WorkspaceObjectInformation>(); for (WorkspaceObjectData d: data) { ret.add((WorkspaceObjectInformation) d); } return ret; } @Test public void cloneWorkspace() throws Exception { WorkspaceUser user1 = new WorkspaceUser("foo"); WorkspaceUser user2 = new WorkspaceUser("bar"); String wsrefs = "clonerefs"; String ws1 = "clone1"; setUpCopyWorkspaces(user1, user2, wsrefs, ws1, "cloneunused"); WorkspaceIdentifier cp1 = new WorkspaceIdentifier(ws1); WorkspaceIdentifier clone1 = new WorkspaceIdentifier("newclone"); Map<String, String> meta = new HashMap<String, String>(); meta.put("clone", "workspace"); WorkspaceInformation info1 = ws.cloneWorkspace(user1, cp1, clone1.getName(), false, null, meta); checkWSInfo(clone1, user1, "newclone", 3, Permission.OWNER, false, info1.getId(), info1.getModDate(), "unlocked", meta); assertNull("desc ok", ws.getWorkspaceDescription(user1, clone1)); List<ObjectInformation> objs = ws.getObjectHistory(user1, new ObjectIdentifier(cp1, "hide")); ObjectInformation save11 = objs.get(0); ObjectInformation save12 = objs.get(1); ObjectInformation save13 = objs.get(2); objs = ws.getObjectHistory(user1, new ObjectIdentifier(cp1, "orig")); ObjectInformation save21 = objs.get(0); ObjectInformation save22 = objs.get(1); ObjectInformation save23 = objs.get(2); objs = ws.getObjectHistory(user1, new ObjectIdentifier(cp1, "hidetarget")); ObjectInformation save31 = objs.get(0); List<ObjectInformation> hideobjs = ws.getObjectHistory(user1, new ObjectIdentifier(clone1, "hide")); long id = hideobjs.get(0).getObjectId(); compareObjectAndInfo(save11, hideobjs.get(0), user1, info1.getId(), clone1.getName(), id, "hide", 1); compareObjectAndInfo(save12, hideobjs.get(1), user1, info1.getId(), clone1.getName(), id, "hide", 2); compareObjectAndInfo(save13, hideobjs.get(2), user1, info1.getId(), clone1.getName(), id, "hide", 3); List<ObjectInformation> origobjs = ws.getObjectHistory(user1, new ObjectIdentifier(clone1, "orig")); id = origobjs.get(0).getObjectId(); compareObjectAndInfo(save21, origobjs.get(0), user1, info1.getId(), clone1.getName(), id, "orig", 1); compareObjectAndInfo(save22, origobjs.get(1), user1, info1.getId(), clone1.getName(), id, "orig", 2); compareObjectAndInfo(save23, origobjs.get(2), user1, info1.getId(), clone1.getName(), id, "orig", 3); List<ObjectInformation> hidetarget = ws.getObjectHistory(user1, new ObjectIdentifier(clone1, "hidetarget")); id = hidetarget.get(0).getObjectId(); compareObjectAndInfo(save31, hidetarget.get(0), user1, info1.getId(), clone1.getName(), id, "hidetarget", 1); checkUnhiddenObjectCount(user1, clone1, 3, 7); ws.setObjectsDeleted(user1, Arrays.asList(new ObjectIdentifier(cp1, "hide")), true); WorkspaceIdentifier clone2 = new WorkspaceIdentifier("newclone2"); WorkspaceInformation info2 = ws.cloneWorkspace(user1, cp1, clone2.getName(), true, "my desc", null); checkWSInfo(clone2, user1, "newclone2", 2, Permission.OWNER, true, info2.getId(), info2.getModDate(), "unlocked", MT_META); assertThat("desc ok", ws.getWorkspaceDescription(user1, clone2), is("my desc")); origobjs = ws.getObjectHistory(user1, new ObjectIdentifier(clone2, "orig")); id = origobjs.get(0).getObjectId(); compareObjectAndInfo(save21, origobjs.get(0), user1, info2.getId(), clone2.getName(), id, "orig", 1); compareObjectAndInfo(save22, origobjs.get(1), user1, info2.getId(), clone2.getName(), id, "orig", 2); compareObjectAndInfo(save23, origobjs.get(2), user1, info2.getId(), clone2.getName(), id, "orig", 3); hidetarget = ws.getObjectHistory(user1, new ObjectIdentifier(clone2, "hidetarget")); id = hidetarget.get(0).getObjectId(); compareObjectAndInfo(save31, hidetarget.get(0), user1, info2.getId(), clone2.getName(), id, "hidetarget", 1); checkUnhiddenObjectCount(user1, clone2, 3, 4); ws.setWorkspaceDeleted(user1, cp1, true); failClone(user1, cp1, "fakename", null, new NoSuchWorkspaceException("Workspace clone1 is deleted", cp1)); ws.setWorkspaceDeleted(user1, cp1, false); ws.setObjectsDeleted(user1, Arrays.asList(new ObjectIdentifier(cp1, "hide")), true); failClone(null, cp1, "fakename", null, new WorkspaceAuthorizationException("Anonymous users may not read workspace clone1")); //workspaceIdentifier used in the workspace method to check ws names tested extensively elsewhere, so just // a couple tests here failClone(user1, cp1, "bar:fakename", null, new IllegalArgumentException( "Workspace name bar:fakename must only contain the user name foo prior to the : delimiter")); failClone(user1, cp1, "9", null, new IllegalArgumentException( "Workspace names cannot be integers: 9")); failClone(user1, cp1, "foo:9", null, new IllegalArgumentException( "Workspace names cannot be integers: foo:9")); failClone(user1, cp1, "foo:fake(name", null, new IllegalArgumentException( "Illegal character in workspace name foo:fake(name: (")); failClone(user2, cp1, "fakename", null, new WorkspaceAuthorizationException("User bar may not read workspace clone1")); failClone(user1, cp1, "newclone2", null, new PreExistingWorkspaceException( "Workspace name newclone2 is already in use")); failClone(user1, new WorkspaceIdentifier("noclone"), "fakename", null, new NoSuchWorkspaceException("No workspace with name noclone exists", cp1)); ws.lockWorkspace(user1, cp1); WorkspaceIdentifier clone3 = new WorkspaceIdentifier("newclone3"); WorkspaceInformation info3 = ws.cloneWorkspace(user1, cp1, clone3.getName(), false, "my desc2", meta); checkWSInfo(clone3, user1, "newclone3", 2, Permission.OWNER, false, info3.getId(), info3.getModDate(), "unlocked", meta); assertThat("desc ok", ws.getWorkspaceDescription(user1, clone3), is("my desc2")); origobjs = ws.getObjectHistory(user1, new ObjectIdentifier(clone3, "orig")); id = origobjs.get(0).getObjectId(); compareObjectAndInfo(save21, origobjs.get(0), user1, info3.getId(), clone3.getName(), id, "orig", 1); compareObjectAndInfo(save22, origobjs.get(1), user1, info3.getId(), clone3.getName(), id, "orig", 2); compareObjectAndInfo(save23, origobjs.get(2), user1, info3.getId(), clone3.getName(), id, "orig", 3); hidetarget = ws.getObjectHistory(user1, new ObjectIdentifier(clone3, "hidetarget")); id = hidetarget.get(0).getObjectId(); compareObjectAndInfo(save31, hidetarget.get(0), user1, info3.getId(), clone3.getName(), id, "hidetarget", 1); checkUnhiddenObjectCount(user1, clone3, 3, 4); WorkspaceIdentifier clone4 = new WorkspaceIdentifier("newclone4"); ws.cloneWorkspace(user1, cp1, clone4.getName(), true, LONG_TEXT, null); assertThat("desc ok", ws.getWorkspaceDescription(user1, clone4), is(LONG_TEXT.subSequence(0, 1000))); Map<String, String> bigmeta = new HashMap<String, String>(); for (int i = 0; i < 141; i++) { bigmeta.put("thing" + i, TEXT100); } ws.cloneWorkspace(user1, cp1, "fakename", false, "eeswaffertheen", bigmeta); bigmeta.put("thing", TEXT100); failClone(user1, cp1, "fakename", bigmeta, new IllegalArgumentException( "Metadata size of 16076 is > 16000 bytes")); ws.setGlobalPermission(user1, clone2, Permission.NONE); ws.setGlobalPermission(user1, clone4, Permission.NONE); } @Test public void lockWorkspace() throws Exception { WorkspaceUser user = new WorkspaceUser("lockuser"); WorkspaceUser user2 = new WorkspaceUser("lockuser2"); WorkspaceIdentifier wsi = lockWS; Map<String, String> meta = new HashMap<String, String>(); meta.put("some meta", "for u"); long wsid = ws.createWorkspace(user, wsi.getName(), false, null, meta).getId(); ws.saveObjects(user, wsi, Arrays.asList(new WorkspaceSaveObject( new HashMap<String, String>(), SAFE_TYPE1, null, new Provenance(user), false)), getIdFactory(user)); ObjectIdentifier oi = new ObjectIdentifier(wsi, "auto1"); //these should work WorkspaceInformation info = ws.lockWorkspace(user, wsi); checkWSInfo(info, user, "lock", 1, Permission.OWNER, false, "locked", meta); successGetObjects(user, Arrays.asList(oi)); ws.cloneWorkspace(user, wsi, "lockclone", false, null, null); ws.copyObject(user, oi, new ObjectIdentifier(new WorkspaceIdentifier("lockclone"), "foo")); ws.setPermissions(user, wsi, Arrays.asList(user2), Permission.WRITE); ws.setPermissions(user, wsi, Arrays.asList(user2), Permission.NONE); ws.getPermissions(user, wsi); ws.getWorkspaceDescription(user, wsi); ws.getWorkspaceInformation(user, wsi); ws.listObjects(user, Arrays.asList(wsi), null, null, null, null, null, null, false, false, false, false, false, false, -1, -1); //these should not work try { ws.lockWorkspace(user, new WorkspaceIdentifier("nolock")); fail("locked non existant ws"); } catch (NoSuchWorkspaceException e) { assertThat("correct exception", e.getLocalizedMessage(), is("No workspace with name nolock exists")); } ws.createWorkspace(user, "lock2", false, "foo", null); WorkspaceIdentifier wsi2 = new WorkspaceIdentifier("lock2"); try { ws.lockWorkspace(null, wsi2); fail("locked w/o creds"); } catch (WorkspaceAuthorizationException e) { assertThat("correct exception", e.getLocalizedMessage(), is("Anonymous users may not lock workspace lock2")); } try { ws.lockWorkspace(user2, wsi2); fail("locked w/o creds"); } catch (WorkspaceAuthorizationException e) { assertThat("correct exception", e.getLocalizedMessage(), is("User lockuser2 may not lock workspace lock2")); } ws.setWorkspaceDeleted(user, wsi2, true); try { ws.lockWorkspace(user, wsi2); fail("locked deleted ws"); } catch (NoSuchWorkspaceException e) { assertThat("correct exception", e.getLocalizedMessage(), is("Workspace lock2 is deleted")); } try { ws.saveObjects(user, wsi, Arrays.asList(new WorkspaceSaveObject( new HashMap<String, String>(), SAFE_TYPE1, null, new Provenance(user), false)), getIdFactory(user)); fail("saved to locked workspace"); } catch (WorkspaceAuthorizationException e) { assertThat("correct exception", e.getLocalizedMessage(), is("The workspace with id " + wsid + ", name lock, is locked and may not be modified")); } try { ws.copyObject(user, oi, new ObjectIdentifier(wsi, "foo")); fail("copied to locked workspace"); } catch (InaccessibleObjectException e) { assertThat("correct exception", e.getLocalizedMessage(), is("Object foo cannot be accessed: The workspace with id " + wsid + ", name lock, is locked and may not be modified")); } try { ws.revertObject(user, oi); fail("revert to locked workspace"); } catch (InaccessibleObjectException e) { assertThat("correct exception", e.getLocalizedMessage(), is("Object auto1 cannot be accessed: The workspace with id " + wsid + ", name lock, is locked and may not be modified")); } try { ws.lockWorkspace(user, wsi); fail("locked locked workspace"); } catch (WorkspaceAuthorizationException e) { assertThat("correct exception", e.getLocalizedMessage(), is("The workspace with id " + wsid + ", name lock, is locked and may not be modified")); } try { ws.renameObject(user, oi, "boo"); fail("renamed locked workspace obj"); } catch (InaccessibleObjectException e) { assertThat("correct exception", e.getLocalizedMessage(), is("Object auto1 cannot be accessed: The workspace with id " + wsid + ", name lock, is locked and may not be modified")); } try { ws.renameWorkspace(user, wsi, "foo"); fail("renamed locked workspace obj"); } catch (WorkspaceAuthorizationException e) { assertThat("correct exception", e.getLocalizedMessage(), is("The workspace with id " + wsid + ", name lock, is locked and may not be modified")); } try { ws.setObjectsDeleted(user, Arrays.asList(oi), true); fail("deleted locked workspace obj"); } catch (InaccessibleObjectException e) { assertThat("correct exception", e.getLocalizedMessage(), is("Object auto1 cannot be accessed: The workspace with id " + wsid + ", name lock, is locked and may not be modified")); } try { ws.setObjectsHidden(user, Arrays.asList(oi), true); fail("hid locked workspace obj"); } catch (InaccessibleObjectException e) { assertThat("correct exception", e.getLocalizedMessage(), is("Object auto1 cannot be accessed: The workspace with id " + wsid + ", name lock, is locked and may not be modified")); } try { ws.setWorkspaceDeleted(user, wsi, true); fail("deleted locked workspace"); } catch (WorkspaceAuthorizationException e) { assertThat("correct exception", e.getLocalizedMessage(), is("The workspace with id " + wsid + ", name lock, is locked and may not be modified")); } try { ws.setWorkspaceDescription(user, wsi, "wugga"); fail("set desc on locked ws"); } catch (WorkspaceAuthorizationException e) { assertThat("correct exception", e.getLocalizedMessage(), is("The workspace with id " + wsid + ", name lock, is locked and may not be modified")); } try { ws.getWorkspaceDescription(user2, wsi); fail("bad access to locked workspace"); } catch (WorkspaceAuthorizationException e) { assertThat("correct exception", e.getLocalizedMessage(), is("User lockuser2 may not read workspace lock")); } failWSMeta(user2, wsi, "some meta", "val", new WorkspaceAuthorizationException( "The workspace with id " + wsid + ", name lock, is locked and may not be modified")); //should work ws.setGlobalPermission(user, wsi, Permission.READ); checkWSInfo(ws.getWorkspaceInformation(user, wsi), user, "lock", 1, Permission.OWNER, true, "published", meta); checkWSInfo(ws.getWorkspaceInformation(user2, wsi), user, "lock", 1, Permission.NONE, true, "published", meta); ws.getWorkspaceDescription(user2, wsi); //shouldn't try { ws.setGlobalPermission(user, wsi, Permission.NONE); fail("bad access to locked workspace"); } catch (WorkspaceAuthorizationException e) { assertThat("correct exception", e.getLocalizedMessage(), is("The workspace with id " + wsid + ", name lock, is locked and may not be modified")); } } @Test public void renameObject() throws Exception { WorkspaceUser user = new WorkspaceUser("renameObjUser"); WorkspaceIdentifier wsi = new WorkspaceIdentifier("renameObj"); WorkspaceUser user2 = new WorkspaceUser("renameObjUser2"); WorkspaceIdentifier wsi2 = new WorkspaceIdentifier("renameObj2"); WorkspaceInformation info1 = ws.createWorkspace(user, wsi.getName(), false, null, null); long wsid1 = info1.getId(); Date lastWSDate = info1.getModDate(); ws.createWorkspace(user2, wsi2.getName(), false, null, null); ws.saveObjects(user, wsi, Arrays.asList(new WorkspaceSaveObject( new HashMap<String, String>(), SAFE_TYPE1, null, new Provenance(user), false)), getIdFactory(user)); ws.saveObjects(user2, wsi2, Arrays.asList(new WorkspaceSaveObject( new HashMap<String, String>(), SAFE_TYPE1, null, new Provenance(user), false)), getIdFactory(user)); lastWSDate = ws.getWorkspaceInformation(user, wsi).getModDate(); ObjectInformation info = ws.renameObject(user, new ObjectIdentifier(wsi, "auto1"), "mynewname"); assertWorkspaceDateUpdated(user, wsi, lastWSDate, "ws date updated on rename"); checkObjInfo(info, 1L, "mynewname", SAFE_TYPE1.getTypeString(), 1, user, wsid1, "renameObj", "99914b932bd37a50b983c5e7c90ae93b", 2, null); String newname = ws.listObjects(user, Arrays.asList(wsi), null, null, null, null, null, null, false, false,false, false, false, false, -1, -1).get(0).getObjectName(); assertThat("object renamed", newname, is("mynewname")); ws.saveObjects(user, wsi, Arrays.asList(new WorkspaceSaveObject( new ObjectIDNoWSNoVer("myoldname"), new HashMap<String, String>(), SAFE_TYPE1, null, new Provenance(user), false)), getIdFactory(user)); failObjRename(user, new ObjectIdentifier(wsi, "mynewname"), "bad%name", new IllegalArgumentException( "Illegal character in object name bad%name: %")); failObjRename(user, new ObjectIdentifier(wsi, "mynewname"), "2", new IllegalArgumentException( "Object names cannot be integers: 2")); failObjRename(user, new ObjectIdentifier(wsi, "mynewname"), "myoldname", new IllegalArgumentException( "There is already an object in the workspace named myoldname")); failObjRename(user, new ObjectIdentifier(wsi, "mynewname"), "mynewname", new IllegalArgumentException( "Object is already named mynewname")); failObjRename(user, new ObjectIdentifier(wsi, "bar"), "foo", new NoSuchObjectException( "No object with name bar exists in workspace " + wsid1)); failObjRename(user, new ObjectIdentifier(wsi2, "auto1"), "foo", new InaccessibleObjectException( "Object auto1 cannot be accessed: User renameObjUser may not rename objects in workspace renameObj2")); failObjRename(null, new ObjectIdentifier(wsi2, "auto1"), "foo", new InaccessibleObjectException( "Object auto1 cannot be accessed: Anonymous users may not rename objects in workspace renameObj2")); ws.setObjectsDeleted(user, Arrays.asList(new ObjectIdentifier(wsi, "mynewname")), true); failObjRename(user, new ObjectIdentifier(wsi, "mynewname"), "foo", new InaccessibleObjectException( "Object 1 (name mynewname) in workspace " + wsid1 + " has been deleted")); ws.setWorkspaceDeleted(user, wsi, true); failObjRename(user, new ObjectIdentifier(wsi, "mynewname"), "foo", new InaccessibleObjectException( "Object mynewname cannot be accessed: Workspace renameObj is deleted")); ws.setWorkspaceDeleted(user, wsi, false); failObjRename(user, new ObjectIdentifier(new WorkspaceIdentifier("renameObjfake"), "mynewname"), "foo", new InaccessibleObjectException( "Object mynewname cannot be accessed: No workspace with name renameObjfake exists")); ws.lockWorkspace(user, wsi); failObjRename(user, new ObjectIdentifier(wsi, "mynewname"), "foo", new InaccessibleObjectException( "Object mynewname cannot be accessed: The workspace with id " + wsid1 + ", name renameObj, is locked and may not be modified")); } @Test public void renameWorkspace() throws Exception { WorkspaceUser user = new WorkspaceUser("renameWSUser"); WorkspaceUser user2 = new WorkspaceUser("renameWSUser2"); WorkspaceIdentifier wsi = new WorkspaceIdentifier("renameWS"); WorkspaceIdentifier wsi2 = new WorkspaceIdentifier("renameWS2"); Map<String, String> meta = new HashMap<String, String>(); meta.put("?", "42"); meta.put("Panic", "towel"); WorkspaceInformation info1 = ws.createWorkspace(user, wsi.getName(), false, null, meta); WorkspaceIdentifier newwsi = new WorkspaceIdentifier(user.getUser() + ":newRenameWS"); Thread.sleep(2); //make sure timestamp is different on rename WorkspaceInformation info2 = ws.renameWorkspace(user, wsi, newwsi.getName()); checkWSInfo(info2, user, newwsi.getName(), 0, Permission.OWNER, false, "unlocked", meta); assertTrue("date updated on ws rename", info2.getModDate().after(info1.getModDate())); checkWSInfo(ws.getWorkspaceInformation(user, newwsi), user, newwsi.getName(), 0, Permission.OWNER, false, "unlocked", meta); failWSRename(user, newwsi, "foo|bar", new IllegalArgumentException("Illegal character in workspace name foo|bar: |")); failWSRename(user, newwsi, "renameWSUser:9", new IllegalArgumentException("Workspace names cannot be integers: renameWSUser:9")); failWSRename(user, newwsi, "9", new IllegalArgumentException("Workspace names cannot be integers: 9")); failWSRename(user, newwsi, "foo:foobar", new IllegalArgumentException( "Workspace name foo:foobar must only contain the user name renameWSUser prior to the : delimiter")); ws.createWorkspace(user2, wsi2.getName(), false, null, null); ws.setPermissions(user2, wsi2, Arrays.asList(user), Permission.WRITE); failWSRename(user, newwsi, "renameWS2", new IllegalArgumentException("There is already a workspace named renameWS2")); failWSRename(user, newwsi, newwsi.getName(), new IllegalArgumentException("Workspace is already named renameWSUser:newRenameWS")); failWSRename(user, new WorkspaceIdentifier(newwsi.getName() + "a"), newwsi.getName(), new NoSuchWorkspaceException("No workspace with name renameWSUser:newRenameWSa exists", wsi)); failWSRename(user, wsi2, newwsi.getName(), new WorkspaceAuthorizationException("User renameWSUser may not rename workspace renameWS2")); failWSRename(null, newwsi, "renamefoo", new WorkspaceAuthorizationException("Anonymous users may not rename workspace renameWSUser:newRenameWS")); ws.setWorkspaceDeleted(user, newwsi, true); failWSRename(user, newwsi, "renamefoo", new NoSuchWorkspaceException("Workspace " + newwsi.getName() + " is deleted", newwsi)); ws.setWorkspaceDeleted(user, newwsi, false); ws.lockWorkspace(user, newwsi); failWSRename(user, newwsi, "renamefoo", new WorkspaceAuthorizationException("The workspace with id " + info1.getId() + ", name " + newwsi.getName() + ", is locked and may not be modified")); } @Test public void setGlobalRead() throws Exception { WorkspaceUser user = new WorkspaceUser("setGlobalUser"); WorkspaceUser user2 = new WorkspaceUser("setGlobalUser2"); WorkspaceIdentifier wsi = new WorkspaceIdentifier("global"); long wsid = ws.createWorkspace(user, wsi.getName(), false, null, null).getId(); failGetWorkspaceDesc(user2, wsi, new WorkspaceAuthorizationException( "User setGlobalUser2 may not read workspace global")); ws.setGlobalPermission(user, wsi, Permission.READ); assertThat("read set correctly", ws.getPermissions(user, wsi).get(new AllUsers('*')), is(Permission.READ)); ws.getWorkspaceDescription(user2, wsi); failSetGlobalPerm(user, wsi, Permission.WRITE, new IllegalArgumentException( "Global permissions cannot be greater than read")); failSetGlobalPerm(user2, wsi, Permission.NONE, new WorkspaceAuthorizationException( "User setGlobalUser2 may not set global permission on workspace global")); failSetGlobalPerm(null, wsi, Permission.NONE, new WorkspaceAuthorizationException( "Anonymous users may not set global permission on workspace global")); ws.setWorkspaceDeleted(user, wsi, true); failSetGlobalPerm(user, wsi, Permission.NONE, new NoSuchWorkspaceException( "Workspace global is deleted", wsi)); ws.setWorkspaceDeleted(user, wsi, false); ws.setGlobalPermission(user, wsi, Permission.NONE); ws.lockWorkspace(user, wsi); failSetGlobalPerm(user, wsi, Permission.NONE, new WorkspaceAuthorizationException( "The workspace with id " + wsid + ", name global, is locked and may not be modified")); //this is tested in lockWorkspace // ws.setGlobalPermission(user, wsi, Permission.READ); // assertThat("read set correctly on locked ws", ws.getPermissions(user, wsi).get(new AllUsers('*')), // is(Permission.READ)); } @Test public void hiddenObjects() throws Exception { WorkspaceUser user = new WorkspaceUser("hideObjUser"); WorkspaceIdentifier wsi = new WorkspaceIdentifier("hideObj"); WorkspaceUser user2 = new WorkspaceUser("hideObjUser2"); long wsid1 = ws.createWorkspace(user, wsi.getName(), false, null, null).getId(); ObjectInformation auto1 = ws.saveObjects(user, wsi, Arrays.asList(new WorkspaceSaveObject( new HashMap<String, String>(), SAFE_TYPE1, null, new Provenance(user), false)), getIdFactory(user)).get(0); ObjectInformation auto2 = ws.saveObjects(user, wsi, Arrays.asList(new WorkspaceSaveObject( new HashMap<String, String>(), SAFE_TYPE1, null, new Provenance(user), true)), getIdFactory(user)).get(0); ObjectInformation obj1 = ws.saveObjects(user, wsi, Arrays.asList(new WorkspaceSaveObject( new ObjectIDNoWSNoVer("obj1"), new HashMap<String, String>(), SAFE_TYPE1, null, new Provenance(user), true)), getIdFactory(user)).get(0); List<ObjectInformation> expected = new ArrayList<ObjectInformation>(); expected.add(auto1); compareObjectInfo(ws.listObjects(user, Arrays.asList(wsi), null, null, null, null, null, null, false, false, false, false, true, false, -1, -1), expected); expected.add(auto2); expected.add(obj1); compareObjectInfo(ws.listObjects(user, Arrays.asList(wsi), null, null, null, null, null, null, true, false, false, false, true, false, -1, -1), expected); ws.setObjectsHidden(user, Arrays.asList(new ObjectIdentifier(wsi, 3), new ObjectIdentifier(wsi, "auto2")), false); compareObjectInfo(ws.listObjects(user, Arrays.asList(wsi), null, null, null, null, null, null, false, false, false, false, true, false, -1, -1), expected); ws.setObjectsHidden(user, Arrays.asList(new ObjectIdentifier(wsi, 1), new ObjectIdentifier(wsi, "obj1")), true); expected.remove(auto1); expected.remove(obj1); compareObjectInfo(ws.listObjects(user, Arrays.asList(wsi), null, null, null, null, null, null, false, false, false, false, true, false, -1, -1), expected); failSetHide(user, new ObjectIdentifier(wsi, "fake"), true, new NoSuchObjectException( "No object with name fake exists in workspace " + wsid1)); failSetHide(user, new ObjectIdentifier(new WorkspaceIdentifier("fake"), "fake"), true, new InaccessibleObjectException( "Object fake cannot be accessed: No workspace with name fake exists")); failSetHide(user2, new ObjectIdentifier(wsi, "auto1"), true, new InaccessibleObjectException( "Object auto1 cannot be accessed: User hideObjUser2 may not hide objects from workspace hideObj")); failSetHide(null, new ObjectIdentifier(wsi, "auto1"), true, new InaccessibleObjectException( "Object auto1 cannot be accessed: Anonymous users may not hide objects from workspace hideObj")); ws.setObjectsDeleted(user, Arrays.asList(new ObjectIdentifier(wsi, 3)), true); failSetHide(user, new ObjectIdentifier(wsi, 3), true, new NoSuchObjectException( "Object 3 (name obj1) in workspace " + wsid1 + " has been deleted")); ws.setObjectsDeleted(user, Arrays.asList(new ObjectIdentifier(wsi, 3)), false); ws.setWorkspaceDeleted(user, wsi, true); failSetHide(user, new ObjectIdentifier(new WorkspaceIdentifier("fake"), "fake"), true, new InaccessibleObjectException( "Object fake cannot be accessed: No workspace with name fake exists")); ws.setWorkspaceDeleted(user, wsi, false); ws.lockWorkspace(user, wsi); failSetHide(user, new ObjectIdentifier(wsi, 3), true, new InaccessibleObjectException( "Object 3 cannot be accessed: The workspace with id " + wsid1 + ", name hideObj, is locked and may not be modified")); } @Test public void listWorkspaces() throws Exception { WorkspaceUser user = new WorkspaceUser("listUser"); WorkspaceUser user2 = new WorkspaceUser("listUser2"); WorkspaceUser user3 = new WorkspaceUser("listUser3"); Map<String, String> meta1 = new HashMap<String, String>(); meta1.put("this is", "some meta meta"); meta1.put("bro", "heim"); Map<String, String> meta2 = new HashMap<String, String>(); meta2.put("suckmaster", "burstingfoam"); WorkspaceInformation stdws = ws.createWorkspace(user, "stdws", false, null, meta1); WorkspaceInformation globalws = ws.createWorkspace(user, "globalws", true, null, meta2); WorkspaceInformation deletedws = ws.createWorkspace(user, "deletedws", false, null, null); ws.setWorkspaceDeleted(user, new WorkspaceIdentifier("deletedws"), true); ws.createWorkspace(user2, "readable", false, null, meta1); ws.setPermissions(user2, new WorkspaceIdentifier("readable"), Arrays.asList(user), Permission.READ); WorkspaceInformation readable = ws.getWorkspaceInformation(user, new WorkspaceIdentifier("readable")); ws.createWorkspace(user2, "writeable", false, null, meta2); ws.setPermissions(user2, new WorkspaceIdentifier("writeable"), Arrays.asList(user), Permission.WRITE); WorkspaceInformation writeable = ws.getWorkspaceInformation(user, new WorkspaceIdentifier("writeable")); ws.createWorkspace(user2, "adminable", false, null, null); ws.setPermissions(user2, new WorkspaceIdentifier("adminable"), Arrays.asList(user), Permission.ADMIN); WorkspaceInformation adminable = ws.getWorkspaceInformation(user, new WorkspaceIdentifier("adminable")); @SuppressWarnings("unused") WorkspaceInformation delreadable = ws.createWorkspace(user2, "delreadable", false, null, meta1); ws.setPermissions(user2, new WorkspaceIdentifier("delreadable"), Arrays.asList(user), Permission.READ); ws.setWorkspaceDeleted(user2, new WorkspaceIdentifier("delreadable"), true); ws.createWorkspace(user2, "globalreadable", true, null, meta2); WorkspaceInformation globalreadable = ws.getWorkspaceInformation(user, new WorkspaceIdentifier("globalreadable")); @SuppressWarnings("unused") WorkspaceInformation deletedglobalreadable = ws.createWorkspace(user2, "deletedglobalreadable", true, null, null); ws.setWorkspaceDeleted(user2, new WorkspaceIdentifier("deletedglobalreadable"), true); @SuppressWarnings("unused") WorkspaceInformation unreadable = ws.createWorkspace(user2, "unreadable", false, null, meta1); ws.createWorkspace(user3, "listuser3ws", false, null, null); ws.setPermissions(user3, new WorkspaceIdentifier("listuser3ws"), Arrays.asList(user), Permission.READ); WorkspaceInformation listuser3 = ws.getWorkspaceInformation(user, new WorkspaceIdentifier("listuser3ws")); ws.createWorkspace(user3, "listuser3glws", true, null, meta2); WorkspaceInformation listuser3gl = ws.getWorkspaceInformation(user, new WorkspaceIdentifier("listuser3glws")); Map<WorkspaceInformation, Boolean> expected = new HashMap<WorkspaceInformation, Boolean>(); expected.put(stdws, false); expected.put(globalws, false); expected.put(readable, false); expected.put(writeable, false); expected.put(adminable, false); expected.put(listuser3, false); checkWSInfoList(ws.listWorkspaces(user, null, null, null, null, null, true, false, false), expected); checkWSInfoList(ws.listWorkspaces(user, null, null, MT_META, null, null, true, false, false), expected); expected.put(globalreadable, false); expected.put(listuser3gl, false); WorkspaceInformation locked = null; try { locked = ws.getWorkspaceInformation(user, lockWS); } catch (NoSuchWorkspaceException nswe) { //ignore - means that the locking ws test has not been run yet } if (locked != null) { expected.put(locked, false); } checkWSInfoList(ws.listWorkspaces(user, null, null, null, null, null, false, false, false), expected); expected.put(deletedws, true); checkWSInfoList(ws.listWorkspaces(user, null, null, null, null, null, false, true, false), expected); expected.remove(globalreadable); expected.remove(locked); expected.remove(listuser3gl); checkWSInfoList(ws.listWorkspaces(user, null, null, null, null, null, true, true, false), expected); checkWSInfoList(ws.listWorkspaces(user, Permission.NONE, null, null, null, null, true, true, false), expected); checkWSInfoList(ws.listWorkspaces(user, Permission.READ, null, null, null, null, true, true, false), expected); expected.remove(readable); expected.remove(listuser3); checkWSInfoList(ws.listWorkspaces(user, Permission.WRITE, null, null, null, null, true, true, false), expected); expected.remove(writeable); checkWSInfoList(ws.listWorkspaces(user, Permission.ADMIN, null, null, null, null, true, true, false), expected); expected.clear(); expected.put(globalreadable, false); expected.put(listuser3gl, false); if (locked != null) { expected.put(locked, false); } WorkspaceUser newb = new WorkspaceUser("listUserAZillion"); expected.put(ws.getWorkspaceInformation(newb, new WorkspaceIdentifier("globalws")), false); checkWSInfoList(ws.listWorkspaces(newb, null, null, null, null, null, false, false, false), expected); expected.clear(); checkWSInfoList(ws.listWorkspaces(newb, null, null, null, null, null, false, false, true), expected); checkWSInfoList(ws.listWorkspaces(newb, null, null, null, null, null, true, false, false), expected); expected.put(deletedws, true); checkWSInfoList(ws.listWorkspaces(user, null, null, null, null, null, false, false, true), expected); checkWSInfoList(ws.listWorkspaces(user, null, null, null, null, null, false, true, true), expected); checkWSInfoList(ws.listWorkspaces(user, null, null, null, null, null, true, true, true), expected); checkWSInfoList(ws.listWorkspaces(user, null, null, null, null, null, false, false, true), expected); expected.clear(); expected.put(stdws, false); expected.put(globalws, false); checkWSInfoList(ws.listWorkspaces(user, null, Arrays.asList(user), null, null, null, false, false, false), expected); expected.put(readable, false); expected.put(writeable, false); expected.put(adminable, false); expected.put(globalreadable, false); checkWSInfoList(ws.listWorkspaces(user, null, Arrays.asList(user, user2), null, null, null, false, false, false), expected); expected.put(listuser3, false); expected.put(listuser3gl, false); checkWSInfoList(ws.listWorkspaces(user, null, Arrays.asList(user, user2, user3), null, null, null, false, false, false), expected); expected.remove(globalreadable); expected.remove(listuser3gl); checkWSInfoList(ws.listWorkspaces(user, null, Arrays.asList(user, user2, user3), null, null, null, true, false, false), expected); expected.remove(stdws); expected.remove(globalws); checkWSInfoList(ws.listWorkspaces(user, null, Arrays.asList(user2, user3), null, null, null, true, false, false), expected); expected.remove(readable); expected.remove(writeable); expected.remove(adminable); checkWSInfoList(ws.listWorkspaces(user, null, Arrays.asList(user3), null, null, null, true, false, false), expected); Map<String, String> querymeta = new HashMap<String, String>(); querymeta.put("suckmaster", "burstingfoam"); expected.clear(); expected.put(globalws, false); expected.put(writeable, false); expected.put(globalreadable, false); expected.put(listuser3gl, false); checkWSInfoList(ws.listWorkspaces(user, null, null, querymeta, null, null, false, false, false), expected); querymeta.clear(); querymeta.put("this is", "some meta meta"); expected.clear(); expected.put(stdws, false); expected.put(readable, false); checkWSInfoList(ws.listWorkspaces(user, null, null, querymeta, null, null, false, false, false), expected); querymeta.clear(); querymeta.put("bro", "heim"); checkWSInfoList(ws.listWorkspaces(user, null, null, querymeta, null, null, false, false, false), expected); try { ws.listWorkspaces(user, null, null, meta1, null, null, false, false, false); fail("listed ws with bad meta"); } catch (IllegalArgumentException exp) { assertThat("correct exception", exp.getLocalizedMessage(), is("Only one metadata spec allowed")); } ws.setGlobalPermission(user2, new WorkspaceIdentifier("globalreadable"), Permission.NONE); ws.setWorkspaceDeleted(user2, new WorkspaceIdentifier("deletedglobalreadable"), false); ws.setGlobalPermission(user2, new WorkspaceIdentifier("deletedglobalreadable"), Permission.NONE); ws.setGlobalPermission(user, new WorkspaceIdentifier("globalws"), Permission.NONE); ws.setGlobalPermission(user3, new WorkspaceIdentifier("listuser3glws"), Permission.NONE); } @Test public void listWorkspacesByDate() throws Exception { WorkspaceUser u = new WorkspaceUser("listwsbydate"); WorkspaceInformation i1 = ws.createWorkspace(u, "listwsbydate1", false, null, null); Thread.sleep(100); WorkspaceInformation i2 = ws.createWorkspace(u, "listwsbydate2", false, null, null); Thread.sleep(100); WorkspaceInformation i3 = ws.createWorkspace(u, "listwsbydate3", false, null, null); Thread.sleep(100); WorkspaceInformation i4 = ws.createWorkspace(u, "listwsbydate4", false, null, null); Thread.sleep(100); WorkspaceInformation i5 = ws.createWorkspace(u, "listwsbydate5", false, null, null); Date beforeall = new Date(i1.getModDate().getTime() - 1); Date afterall = new Date(i5.getModDate().getTime() + 1); checkWSInfoList(ws.listWorkspaces(u, null, null, null, null, null, true, false, false), Arrays.asList(i1, i2, i3, i4, i5)); checkWSInfoList(ws.listWorkspaces(u, null, null, null, beforeall, afterall, true, false, false), Arrays.asList(i1, i2, i3, i4, i5)); checkWSInfoList(ws.listWorkspaces(u, null, null, null, afterall, beforeall, true, false, false), new ArrayList<WorkspaceInformation>()); checkWSInfoList(ws.listWorkspaces(u, null, null, null, i3.getModDate(), i4.getModDate(), true, false, false), new ArrayList<WorkspaceInformation>()); checkWSInfoList(ws.listWorkspaces(u, null, null, null, i2.getModDate(), i4.getModDate(), true, false, false), Arrays.asList(i3)); checkWSInfoList(ws.listWorkspaces(u, null, null, null, i2.getModDate(), null, true, false, false), Arrays.asList(i3, i4, i5)); checkWSInfoList(ws.listWorkspaces(u, null, null, null, null, i4.getModDate(), true, false, false), Arrays.asList(i1, i2, i3)); checkWSInfoList(ws.listWorkspaces(u, null, null, null, new Date(i2.getModDate().getTime() - 1), i5.getModDate(), true, false, false), Arrays.asList(i2, i3, i4)); } @Test public void listObjectsAndHistory() throws Exception { WorkspaceUser user = new WorkspaceUser("listObjUser"); WorkspaceIdentifier wsi = new WorkspaceIdentifier("listObj1"); WorkspaceIdentifier readable = new WorkspaceIdentifier("listObjread"); WorkspaceIdentifier writeable = new WorkspaceIdentifier("listObjwrite"); WorkspaceIdentifier adminable = new WorkspaceIdentifier("listObjadmin"); WorkspaceIdentifier thirdparty = new WorkspaceIdentifier("thirdparty"); WorkspaceUser user2 = new WorkspaceUser("listObjUser2"); long wsid1 = ws.createWorkspace(user, wsi.getName(), false, null, null).getId(); ws.createWorkspace(user2, readable.getName(), false, null, null).getId(); ws.setPermissions(user2, readable, Arrays.asList(user), Permission.READ); long wsidwrite = ws.createWorkspace(user2, writeable.getName(), false, null, null).getId(); ws.setPermissions(user2, writeable, Arrays.asList(user), Permission.WRITE); ws.createWorkspace(user2, adminable.getName(), false, null, null).getId(); ws.setPermissions(user2, adminable, Arrays.asList(user), Permission.ADMIN); WorkspaceUser user3 = new WorkspaceUser("listObjUser3"); ws.createWorkspace(user3, thirdparty.getName(), true, null, null).getId(); Map<String, String> meta = new HashMap<String, String>(); meta.put("meta1", "1"); Map<String, String> meta2 = new HashMap<String, String>(); meta2.put("meta2", "2"); Map<String, String> meta3 = new HashMap<String, String>(); meta3.put("meta3", "3"); Map<String, String> meta32 = new HashMap<String, String>(); meta32.put("meta3", "3"); meta32.put("meta2", "2"); Map<String, Object> passTCdata = new HashMap<String, Object>(); passTCdata.put("thing", "athing"); ObjectInformation std = ws.saveObjects(user, wsi, Arrays.asList(new WorkspaceSaveObject( new ObjectIDNoWSNoVer("std"), new HashMap<String, String>(), SAFE_TYPE1, null, new Provenance(user), false)), getIdFactory(user)).get(0); ObjectInformation stdnometa = ws.getObjectInformation(user, Arrays.asList(new ObjectIdentifier(wsi, "std")), false, false).get(0); ObjectInformation objstack1 = ws.saveObjects(user, wsi, Arrays.asList(new WorkspaceSaveObject( new ObjectIDNoWSNoVer("objstack"), new HashMap<String, String>(), SAFE_TYPE1_10, meta, new Provenance(user), false)), getIdFactory(user)).get(0); ObjectInformation objstack1nometa = ws.getObjectInformation(user, Arrays.asList(new ObjectIdentifier(wsi, "objstack", 1)), false, false).get(0); ObjectInformation objstack2 = ws.saveObjects(user, wsi, Arrays.asList(new WorkspaceSaveObject( new ObjectIDNoWSNoVer("objstack"), passTCdata, SAFE_TYPE1_20, meta2, new Provenance(user), false)), getIdFactory(user)).get(0); ObjectInformation objstack2nometa = ws.getObjectInformation(user, Arrays.asList(new ObjectIdentifier(wsi, "objstack", 2)), false, false).get(0); ObjectInformation type2_1 = ws.saveObjects(user, wsi, Arrays.asList(new WorkspaceSaveObject( new ObjectIDNoWSNoVer("type2"), new HashMap<String, String>(), SAFE_TYPE2, meta, new Provenance(user), false)), getIdFactory(user)).get(0); ObjectInformation type2_1nometa = ws.getObjectInformation(user, Arrays.asList(new ObjectIdentifier(wsi, "type2", 1)), false, false).get(0); ObjectInformation type2_2 = ws.saveObjects(user, wsi, Arrays.asList(new WorkspaceSaveObject( new ObjectIDNoWSNoVer("type2"), new HashMap<String, String>(), SAFE_TYPE2_10, meta2, new Provenance(user), false)), getIdFactory(user)).get(0); ObjectInformation type2_2nometa = ws.getObjectInformation(user, Arrays.asList(new ObjectIdentifier(wsi, "type2", 2)), false, false).get(0); ObjectInformation type2_3 = ws.saveObjects(user, wsi, Arrays.asList(new WorkspaceSaveObject( new ObjectIDNoWSNoVer("type2"), passTCdata, SAFE_TYPE2_20, meta32, new Provenance(user), false)), getIdFactory(user)).get(0); ObjectInformation type2_3nometa = ws.getObjectInformation(user, Arrays.asList(new ObjectIdentifier(wsi, "type2", 3)), false, false).get(0); ObjectInformation type2_4 = ws.saveObjects(user, wsi, Arrays.asList(new WorkspaceSaveObject( new ObjectIDNoWSNoVer("type2"), passTCdata, SAFE_TYPE2_21, meta3, new Provenance(user), false)), getIdFactory(user)).get(0); ObjectInformation type2_4nometa = ws.getObjectInformation(user, Arrays.asList(new ObjectIdentifier(wsi, "type2", 4)), false, false).get(0); ObjectInformation stdws2 = ws.saveObjects(user2, writeable, Arrays.asList(new WorkspaceSaveObject( new ObjectIDNoWSNoVer("stdws2"), new HashMap<String, String>(), SAFE_TYPE1, meta, new Provenance(user), false)), getIdFactory(user2)).get(0); ObjectInformation stdws2nometa = ws.getObjectInformation(user, Arrays.asList(new ObjectIdentifier(writeable, "stdws2")), false, false).get(0); ObjectInformation hidden = ws.saveObjects(user, writeable, Arrays.asList(new WorkspaceSaveObject( new ObjectIDNoWSNoVer("hidden"), new HashMap<String, String>(), SAFE_TYPE1, meta2, new Provenance(user), false)), getIdFactory(user)).get(0); ObjectInformation hiddennometa = ws.getObjectInformation(user, Arrays.asList(new ObjectIdentifier(writeable, "hidden")), false, false).get(0); ws.setObjectsHidden(user, Arrays.asList(new ObjectIdentifier(writeable, "hidden")), true); ObjectInformation deleted = ws.saveObjects(user2, writeable, Arrays.asList(new WorkspaceSaveObject( new ObjectIDNoWSNoVer("deleted"), new HashMap<String, String>(), SAFE_TYPE1, meta32, new Provenance(user), false)), getIdFactory(user2)).get(0); ObjectInformation deletednometa = ws.getObjectInformation(user, Arrays.asList(new ObjectIdentifier(writeable, "deleted")), false, false).get(0); ws.setObjectsDeleted(user, Arrays.asList(new ObjectIdentifier(writeable, "deleted")), true); ObjectInformation readobj = ws.saveObjects(user2, readable, Arrays.asList(new WorkspaceSaveObject( new ObjectIDNoWSNoVer("readobj"), new HashMap<String, String>(), SAFE_TYPE1, meta3, new Provenance(user), false)), getIdFactory(user2)).get(0); ObjectInformation readobjnometa = ws.getObjectInformation(user, Arrays.asList(new ObjectIdentifier(readable, "readobj")), false, false).get(0); ObjectInformation adminobj = ws.saveObjects(user2, adminable, Arrays.asList(new WorkspaceSaveObject( new ObjectIDNoWSNoVer("adminobj"), new HashMap<String, String>(), SAFE_TYPE1, meta3, new Provenance(user), false)), getIdFactory(user2)).get(0); ObjectInformation adminobjnometa = ws.getObjectInformation(user, Arrays.asList(new ObjectIdentifier(adminable, "adminobj")), false, false).get(0); ObjectInformation thirdobj = ws.saveObjects(user3, thirdparty, Arrays.asList(new WorkspaceSaveObject( new ObjectIDNoWSNoVer("thirdobj"), new HashMap<String, String>(), SAFE_TYPE1, meta, new Provenance(user), false)), getIdFactory(user3)).get(0); ObjectInformation thirdobjnometa = ws.getObjectInformation(user, Arrays.asList(new ObjectIdentifier(thirdparty, "thirdobj")), false, false).get(0); ObjectInformation lock = null; ObjectInformation locknometa = null; try { List<ObjectInformation> foo = ws.listObjects(user, Arrays.asList(lockWS), null, null, null, null, null, null, false, false, false, false, true, false, -1, -1); if (foo.size() > 1) { fail("found more than one object in the locked workspace, this is unexpected"); } if (foo.size() == 1) { lock = foo.get(0); locknometa = ws.listObjects(user, Arrays.asList(lockWS), null, null, null, null, null, null, false, false, false, false, false, false, -1, -1).get(0); } } catch (NoSuchWorkspaceException nswe) { //do nothing, lock workspace wasn't created yet } TypeDefId allType1 = new TypeDefId(SAFE_TYPE1.getType().getTypeString()); TypeDefId allType2 = new TypeDefId(SAFE_TYPE2.getType().getTypeString()); ArrayList<WorkspaceIdentifier> emptyWS = new ArrayList<WorkspaceIdentifier>(); compareObjectInfo(ws.listObjects(user, Arrays.asList(wsi, writeable), null, null, null, null, null, null, true, true, false, true, true, false, -1, -1), Arrays.asList(std, objstack1, objstack2, type2_1, type2_2, type2_3, type2_4, stdws2, hidden, deleted)); compareObjectInfo(ws.listObjects(user, Arrays.asList(wsi, writeable), null, null, null, null, null, null, true, true, true, true, true, false, -1, -1), Arrays.asList(deleted)); compareObjectInfo(ws.listObjects(user, Arrays.asList(wsi), null, null, null, null, null, null, true, true, true, true, true, false, -1, -1), new ArrayList<ObjectInformation>()); compareObjectInfo(ws.listObjects(user, Arrays.asList(wsi, writeable), null, null, null, null, null, null, false, true, false, true, true, false, -1, -1), Arrays.asList(std, objstack1, objstack2, type2_1, type2_2, type2_3, type2_4, stdws2, deleted)); compareObjectInfo(ws.listObjects(user, Arrays.asList(wsi, writeable), null, null, null, null, null, null, true, false, false, true, true, false, -1, -1), Arrays.asList(std, objstack1, objstack2, type2_1, type2_2, type2_3, type2_4, stdws2, hidden)); compareObjectInfo(ws.listObjects(user, Arrays.asList(wsi, writeable), null, null, null, null, null, null, false, false, false, true, true, false, -1, -1), Arrays.asList(std, objstack1, objstack2, type2_1, type2_2, type2_3, type2_4, stdws2)); compareObjectInfo(ws.listObjects(user, Arrays.asList(wsi, writeable), null, null, null, null, null, null, true, true, false, false, true, false, -1, -1), Arrays.asList(std, objstack2, type2_4, stdws2, hidden, deleted)); compareObjectInfo(ws.listObjects(user, Arrays.asList(wsi, writeable), null, null, null, null, null, null, false, false, false, false, false, false, -1, -1), Arrays.asList(stdnometa, objstack2nometa, type2_4nometa, stdws2nometa)); compareObjectInfo(ws.listObjects(user, Arrays.asList(wsi, writeable), null, null, null, null, null, null, true, true, false, true, false, false, -1, -1), Arrays.asList(stdnometa, objstack1nometa, objstack2nometa, type2_1nometa, type2_2nometa, type2_3nometa, type2_4nometa, stdws2nometa, hiddennometa, deletednometa)); compareObjectInfo(ws.listObjects(user, emptyWS, allType1, null, null, null, null, null, true, true, false, true, true, false, -1, -1), setUpListObjectsExpected(Arrays.asList(std, objstack1, objstack2, stdws2, hidden, deleted, readobj, adminobj, thirdobj), lock)); compareObjectInfo(ws.listObjects(user, emptyWS, allType1, null, new ArrayList<WorkspaceUser>(), null, null, null, true, true, false, true, true, false, -1, -1), setUpListObjectsExpected(Arrays.asList(std, objstack1, objstack2, stdws2, hidden, deleted, readobj, adminobj, thirdobj), lock)); //exclude globally readable workspaces compareObjectInfo(ws.listObjects(user, emptyWS, allType1, null, null, null, null, null, true, true, false, true, true, true, -1, -1), Arrays.asList(std, objstack1, objstack2, stdws2, hidden, deleted, readobj, adminobj)); //if the globally readable workspace is explicitly listed, should ignore excludeGlobal compareObjectInfo(ws.listObjects(user, Arrays.asList(wsi, writeable, thirdparty), null, null, null, null, null, null, true, true, false, true, true, false, -1, -1), Arrays.asList(std, objstack1, objstack2, type2_1, type2_2, type2_3, type2_4, stdws2, hidden, deleted, thirdobj)); compareObjectInfo(ws.listObjects(user, Arrays.asList(wsi, writeable, thirdparty), null, null, null, null, null, null, true, true, false, true, true, true, -1, -1), Arrays.asList(std, objstack1, objstack2, type2_1, type2_2, type2_3, type2_4, stdws2, hidden, deleted, thirdobj)); //test user filtering compareObjectInfo(ws.listObjects(user, emptyWS, allType1, null, Arrays.asList(user, user2, user3), null, null, null, true, true, false, true, true, false, -1, -1), Arrays.asList(std, objstack1, objstack2, stdws2, hidden, deleted, readobj, adminobj, thirdobj)); compareObjectInfo(ws.listObjects(user, emptyWS, allType1, null, Arrays.asList(user2, user3), null, null, null, true, true, false, true, true, false, -1, -1), Arrays.asList(stdws2, deleted, readobj, adminobj, thirdobj)); compareObjectInfo(ws.listObjects(user, emptyWS, allType1, null, Arrays.asList(user, user3), null, null, null, true, true, false, true, true, false, -1, -1), Arrays.asList(std, hidden, objstack1, objstack2, thirdobj)); compareObjectInfo(ws.listObjects(user, emptyWS, allType1, null, Arrays.asList(user3), null, null, null, true, true, false, true, true, false, -1, -1), Arrays.asList(thirdobj)); compareObjectInfo(ws.listObjects(user, emptyWS, allType1, null, Arrays.asList(user), null, null, null, true, true, false, true, true, false, -1, -1), Arrays.asList(std, hidden, objstack1, objstack2)); //meta filtering compareObjectInfo(ws.listObjects(user, Arrays.asList(wsi, writeable), null, null, null, new HashMap<String, String>(), null, null, true, true, false, true, true, false, -1, -1), Arrays.asList(std, objstack1, objstack2, type2_1, type2_2, type2_3, type2_4, stdws2, hidden, deleted)); compareObjectInfo(ws.listObjects(user, Arrays.asList(wsi, writeable), null, null, null, meta, null, null, true, true, false, true, true, false, -1, -1), Arrays.asList(objstack1, type2_1, stdws2)); compareObjectInfo(ws.listObjects(user, Arrays.asList(wsi, writeable), null, null, null, meta2, null, null, true, true, false, true, true, false, -1, -1), Arrays.asList(objstack2, type2_2, type2_3, hidden, deleted)); compareObjectInfo(ws.listObjects(user, Arrays.asList(wsi, writeable), null, null, null, meta3, null, null, true, true, false, true, true, false, -1, -1), Arrays.asList(type2_3, type2_4, deleted)); compareObjectInfo(ws.listObjects(user, Arrays.asList(wsi, writeable), null, null, null, meta, null, null, true, true, false, false, true, false, -1, -1), Arrays.asList(stdws2)); compareObjectInfo(ws.listObjects(user, Arrays.asList(wsi, writeable), null, null, null, meta2, null, null, true, true, false, false, true, false, -1, -1), Arrays.asList(objstack2, hidden, deleted)); compareObjectInfo(ws.listObjects(user, Arrays.asList(wsi), allType1, null, null, null, null, null, true, true, false, true, true, false, -1, -1), Arrays.asList(std, objstack1, objstack2)); compareObjectInfo(ws.listObjects(user, Arrays.asList(writeable), allType1, null, null, null, null, null, true, true, false, true, true, false, -1, -1), Arrays.asList(stdws2, hidden, deleted)); compareObjectInfo(ws.listObjects(user, emptyWS, allType2, null, null, null, null, null, true, true, false, true, true, false, -1, -1), Arrays.asList(type2_1, type2_2, type2_3, type2_4)); compareObjectInfo(ws.listObjects(user, Arrays.asList(writeable), allType2, null, null, null, null, null, true, true, false, true, true, false, -1, -1), new ArrayList<ObjectInformation>()); compareObjectInfo(ws.listObjects(user, emptyWS, SAFE_TYPE1, null, null, null, null, null, true, true, false, true, true, false, -1, -1), setUpListObjectsExpected(Arrays.asList(std, stdws2, hidden, deleted, readobj, adminobj, thirdobj), lock)); compareObjectInfo(ws.listObjects(user, emptyWS, SAFE_TYPE1, null, null, null, null, null, true, true, false, true, false, false, -1, -1), setUpListObjectsExpected(Arrays.asList(stdnometa, stdws2nometa, hiddennometa, deletednometa, readobjnometa, adminobjnometa, thirdobjnometa), locknometa)); compareObjectInfo(ws.listObjects(user, emptyWS, SAFE_TYPE1, Permission.NONE, null, null, null, null, true, true, false, true, false, false, -1, -1), setUpListObjectsExpected(Arrays.asList(stdnometa, stdws2nometa, hiddennometa, deletednometa, readobjnometa, adminobjnometa, thirdobjnometa), locknometa)); compareObjectInfo(ws.listObjects(user, emptyWS, SAFE_TYPE1, Permission.READ, null, null, null, null, true, true, false, true, false, false, -1, -1), setUpListObjectsExpected(Arrays.asList(stdnometa, stdws2nometa, hiddennometa, deletednometa, readobjnometa, adminobjnometa, thirdobjnometa), locknometa)); compareObjectInfo(ws.listObjects(user, emptyWS, SAFE_TYPE1, Permission.WRITE, null, null, null, null, true, true, false, true, false, false, -1, -1), Arrays.asList(stdnometa, stdws2nometa, hiddennometa, deletednometa, adminobjnometa)); compareObjectInfo(ws.listObjects(user, emptyWS, SAFE_TYPE1, Permission.ADMIN, null, null, null, null, true, true, false, true, false, false, -1, -1), Arrays.asList(stdnometa, adminobjnometa)); compareObjectInfo(ws.listObjects(user, emptyWS, SAFE_TYPE1_10, null, null, null, null, null, true, true, false, true, true, false, -1, -1), Arrays.asList(objstack1)); compareObjectInfo(ws.listObjects(user, emptyWS, SAFE_TYPE1_20, null, null, null, null, null, true, true, false, true, true, false, -1, -1), Arrays.asList(objstack2)); compareObjectInfo(ws.listObjects(user, emptyWS, SAFE_TYPE2, null, null, null, null, null, true, true, false, true, true, false, -1, -1), Arrays.asList(type2_1)); compareObjectInfo(ws.listObjects(user, emptyWS, SAFE_TYPE2_10, null, null, null, null, null, true, true, false, true, true, false, -1, -1), Arrays.asList(type2_2)); compareObjectInfo(ws.listObjects(user, emptyWS, SAFE_TYPE2_20, null, null, null, null, null, true, true, false, true, true, false, -1, -1), Arrays.asList(type2_3)); compareObjectInfo(ws.listObjects(user, emptyWS, new TypeDefId(SAFE_TYPE2_20.getType(), SAFE_TYPE2_20.getMajorVersion()), null, null, null, null, null, true, true, false, true, true, false, -1, -1), Arrays.asList(type2_3, type2_4)); compareObjectInfo(ws.listObjects(user, emptyWS, new TypeDefId(SAFE_TYPE2_10.getType(), SAFE_TYPE2_10.getMajorVersion()), null, null, null, null, null, true, true, false, true, true, false, -1, -1), Arrays.asList(type2_2)); compareObjectInfo(ws.listObjects(user2, emptyWS, allType1, null, null, null, null, null, true, true, false, true, true, false, -1, -1), setUpListObjectsExpected(Arrays.asList(stdws2, hidden, deleted, readobj, adminobj, thirdobj), lock)); compareObjectInfo(ws.listObjects(user2, Arrays.asList(writeable), null, null, null, null, null, null, true, true, false, true, true, false, -1, -1), Arrays.asList(stdws2, hidden, deleted)); compareObjectInfo(ws.listObjects(user2, emptyWS, allType2, null, null, null, null, null, true, true, false, true, true, false, -1, -1), new ArrayList<ObjectInformation>()); // failListObjects(user, new ArrayList<WorkspaceIdentifier>(), null, null, true, true, false, true, true, new IllegalArgumentException("At least one filter must be specified.")); failListObjects(user2, Arrays.asList(wsi, writeable), null, null, true, true, false, true, true, new WorkspaceAuthorizationException("User listObjUser2 may not read workspace listObj1")); failListObjects(null, Arrays.asList(wsi, writeable), null, null, true, true, false, true, true, new WorkspaceAuthorizationException("Anonymous users may not read workspace listObj1")); failListObjects(user, Arrays.asList(writeable, new WorkspaceIdentifier("listfake")), null, null, true, true, false, true, true, new NoSuchWorkspaceException("No workspace with name listfake exists", wsi)); failListObjects(user, Arrays.asList(wsi, writeable), null, meta32, true, true, false, true, true, new IllegalArgumentException("Only one metadata spec allowed")); ws.createWorkspace(user, "listdel", false, null, null); ws.setWorkspaceDeleted(user, new WorkspaceIdentifier("listdel"), true); failListObjects(user, Arrays.asList(writeable, new WorkspaceIdentifier("listdel")), null, null, true, true, false, true, true, new NoSuchWorkspaceException("Workspace listdel is deleted", wsi)); assertThat("correct object history for std", ws.getObjectHistory(user, new ObjectIdentifier(wsi, "std")), is(Arrays.asList(std))); assertThat("correct object history for type2", ws.getObjectHistory(user, new ObjectIdentifier(wsi, "type2")), is(Arrays.asList(type2_1, type2_2, type2_3, type2_4))); assertThat("correct object history for type2", ws.getObjectHistory(user, new ObjectIdentifier(wsi, 3)), is(Arrays.asList(type2_1, type2_2, type2_3, type2_4))); assertThat("correct object history for type2", ws.getObjectHistory(user, new ObjectIdentifier(wsi, "type2", 3)), is(Arrays.asList(type2_1, type2_2, type2_3, type2_4))); assertThat("correct object history for type2", ws.getObjectHistory(user, new ObjectIdentifier(wsi, 3, 4)), is(Arrays.asList(type2_1, type2_2, type2_3, type2_4))); assertThat("correct object history for objstack", ws.getObjectHistory(user, new ObjectIdentifier(wsi, "objstack")), is(Arrays.asList(objstack1, objstack2))); assertThat("correct object history for stdws2", ws.getObjectHistory(user2, new ObjectIdentifier(writeable, "stdws2")), is(Arrays.asList(stdws2))); failGetObjectHistory(user, new ObjectIdentifier(wsi, "booger"), new NoSuchObjectException("No object with name booger exists in workspace " + wsid1)); failGetObjectHistory(user, new ObjectIdentifier(new WorkspaceIdentifier("listObjectsfake"), "booger"), new InaccessibleObjectException("Object booger cannot be accessed: No workspace with name listObjectsfake exists")); failGetObjectHistory(user, new ObjectIdentifier(new WorkspaceIdentifier("listdel"), "booger"), new InaccessibleObjectException("Object booger cannot be accessed: Workspace listdel is deleted")); failGetObjectHistory(user2, new ObjectIdentifier(wsi, 3), new InaccessibleObjectException("Object 3 cannot be accessed: User listObjUser2 may not read workspace listObj1")); failGetObjectHistory(null, new ObjectIdentifier(wsi, 3), new InaccessibleObjectException("Object 3 cannot be accessed: Anonymous users may not read workspace listObj1")); failGetObjectHistory(user2, new ObjectIdentifier(writeable, "deleted"), new InaccessibleObjectException("Object 3 (name deleted) in workspace " + wsidwrite + " has been deleted")); ws.setGlobalPermission(user3, new WorkspaceIdentifier("thirdparty"), Permission.NONE); } @Test public void listObjectsByDate() throws Exception { WorkspaceUser u = new WorkspaceUser("listObjsByDate"); WorkspaceIdentifier wsi = new WorkspaceIdentifier("listObjsByDateWS"); ws.createWorkspace(u, wsi.getName(), false, null, null); Map<String, String> data = new HashMap<String, String>(); Provenance p = new Provenance(u); ObjectInformation o1 = saveObject(u, wsi, null, data, SAFE_TYPE1, "o1", p); Thread.sleep(100); ObjectInformation o2 = saveObject(u, wsi, null, data, SAFE_TYPE1, "o2", p); Thread.sleep(100); ObjectInformation o3 = saveObject(u, wsi, null, data, SAFE_TYPE1, "o3", p); Thread.sleep(100); ObjectInformation o4 = saveObject(u, wsi, null, data, SAFE_TYPE1, "o4", p); Thread.sleep(100); ObjectInformation o5 = saveObject(u, wsi, null, data, SAFE_TYPE1, "o5", p); Date beforeall = new Date(o1.getSavedDate().getTime() - 1); Date afterall = new Date(o5.getSavedDate().getTime() + 1); compareObjectInfo(ws.listObjects(u, Arrays.asList(wsi), null, null, null, null, null, null, false, false, false, false, true, false, -1, -1), Arrays.asList(o1, o2, o3, o4, o5)); compareObjectInfo(ws.listObjects(u, Arrays.asList(wsi), null, null, null, null, beforeall, afterall, false, false, false, false, true, false, -1, -1), Arrays.asList(o1, o2, o3, o4, o5)); compareObjectInfo(ws.listObjects(u, Arrays.asList(wsi), null, null, null, null, afterall, beforeall, false, false, false, false, true, false, -1, -1), new ArrayList<ObjectInformation>()); compareObjectInfo(ws.listObjects(u, Arrays.asList(wsi), null, null, null, null, o3.getSavedDate(), o4.getSavedDate(), false, false, false, false, true, false, -1, -1), new ArrayList<ObjectInformation>()); compareObjectInfo(ws.listObjects(u, Arrays.asList(wsi), null, null, null, null, o2.getSavedDate(), null, false, false, false, false, true, false, -1, -1), Arrays.asList(o3, o4, o5)); compareObjectInfo(ws.listObjects(u, Arrays.asList(wsi), null, null, null, null, null, o4.getSavedDate(), false, false, false, false, true, false, -1, -1), Arrays.asList(o1, o2, o3)); compareObjectInfo(ws.listObjects(u, Arrays.asList(wsi), null, null, null, null, o2.getSavedDate(), o4.getSavedDate(), false, false, false, false, true, false, -1, -1), Arrays.asList(o3)); compareObjectInfo(ws.listObjects(u, Arrays.asList(wsi), null, null, null, null, new Date(o2.getSavedDate().getTime() -1), o5.getSavedDate(), false, false, false, false, true, false, -1, -1), Arrays.asList(o2, o3, o4)); } @Test public void getObjectSubdata() throws Exception { /* note most tests are performed at the same time as getObjects, so * only issues specific to subsets are tested here */ WorkspaceUser user = new WorkspaceUser("subUser"); WorkspaceIdentifier wsi = new WorkspaceIdentifier("subData"); WorkspaceUser user2 = new WorkspaceUser("subUser2"); long wsid1 = ws.createWorkspace(user, wsi.getName(), false, null, null).getId(); TypeDefId reftype = new TypeDefId(new TypeDefName("CopyRev", "RefType"), 1, 0); Map<String, String> meta = new HashMap<String, String>(); meta.put("metastuff", "meta"); Map<String, String> meta2 = new HashMap<String, String>(); meta2.put("meta2", "my hovercraft is full of eels"); Provenance p1 = new Provenance(user); p1.addAction(new ProvenanceAction().withDescription("provenance 1") .withWorkspaceObjects(Arrays.asList("subData/auto1"))); Provenance p2 = new Provenance(user); p2.addAction(new ProvenanceAction().withDescription("provenance 2") .withWorkspaceObjects(Arrays.asList("subData/auto2"))); Map<String, Object> data1 = createData( "{\"map\": {\"id1\": {\"id\": 1," + " \"thing\": \"foo\"}," + " \"id2\": {\"id\": 2," + " \"thing\": \"foo2\"}," + " \"id3\": {\"id\": 3," + " \"thing\": \"foo3\"}" + " }," + " \"refs\": [\"subData/auto1\"]" + "}" ); Map<String, Object> data2 = createData( "{\"array\": [{\"id\": 1," + " \"thing\": \"foo\"}," + " {\"id\": 2," + " \"thing\": \"foo2\"}," + " {\"id\": 3," + " \"thing\": \"foo3\"}" + " ]," + " \"refs\": [\"subData/auto2\"]" + "}" ); Map<String, Object> data3 = createData( "{\"array\": [{\"id\": 1," + " \"thing\": \"foo\"}," + " {\"id\": 2," + " \"thing\": \"foo2\"}," + " null," + " {\"id\": 4," + " \"thing\": \"foo4\"}" + " ]," + " \"refs\": [\"subData/auto2\"]" + "}" ); ws.saveObjects(user, wsi, Arrays.asList( new WorkspaceSaveObject(data1, SAFE_TYPE1, meta, new Provenance(user), false), new WorkspaceSaveObject(data1, SAFE_TYPE1, meta, new Provenance(user), false)), getIdFactory(user)); ObjectInformation o1 = ws.saveObjects(user, wsi, Arrays.asList(new WorkspaceSaveObject( new ObjectIDNoWSNoVer("o1"), data1, reftype, meta, p1, false)), getIdFactory(user)).get(0); ObjectInformation o2 = ws.saveObjects(user, wsi, Arrays.asList(new WorkspaceSaveObject( new ObjectIDNoWSNoVer("o2"), data2, reftype, meta2, p2, false)), getIdFactory(user)).get(0); ObjectInformation o3 = ws.saveObjects(user, wsi, Arrays.asList(new WorkspaceSaveObject( new ObjectIDNoWSNoVer("o3"), data3, reftype, meta, p2, false)), getIdFactory(user)).get(0); ObjectIdentifier oident1 = new ObjectIdentifier(wsi, "o1"); ObjectIdentifier oident2 = new ObjectIdentifier(wsi, 4); ObjectIdentifier oident3 = ObjectIdentifier.parseObjectReference("subData/o3"); List<String> refs1 = Arrays.asList(wsid1 + "/1/1"); Map<String, String> refmap1 = new HashMap<String, String>(); refmap1.put("subData/auto1", wsid1 + "/1/1"); List<String> refs2 = Arrays.asList(wsid1 + "/2/1"); Map<String, String> refmap2 = new HashMap<String, String>(); refmap2.put("subData/auto2", wsid1 + "/2/1"); List<WorkspaceObjectData> got = ws.getObjectsSubSet(user, Arrays.asList( new SubObjectIdentifier(oident1, new ObjectPaths( Arrays.asList("/map/id3", "/map/id1"))), new SubObjectIdentifier(oident1, new ObjectPaths( Arrays.asList("/map/id2"))), new SubObjectIdentifier(oident2, new ObjectPaths( Arrays.asList("/array/2", "/array/0"))), new SubObjectIdentifier(oident3, new ObjectPaths( Arrays.asList("/array/2", "/array/0", "/array/3"))))); Map<String, Object> expdata1 = createData( "{\"map\": {\"id1\": {\"id\": 1," + " \"thing\": \"foo\"}," + " \"id3\": {\"id\": 3," + " \"thing\": \"foo3\"}" + " }" + "}" ); Map<String, Object> expdata2 = createData( "{\"map\": {\"id2\": {\"id\": 2," + " \"thing\": \"foo2\"}" + " }" + "}" ); Map<String, Object> expdata3 = createData( "{\"array\": [{\"id\": 1," + " \"thing\": \"foo\"}," + " {\"id\": 3," + " \"thing\": \"foo3\"}" + " ]" + "}" ); Map<String, Object> expdata4 = createData( "{\"array\": [{\"id\": 1," + " \"thing\": \"foo\"}," + " null," + " {\"id\": 4," + " \"thing\": \"foo4\"}" + " ]" + "}" ); compareObjectAndInfo(got.get(0), o1, p1, expdata1, refs1, refmap1); compareObjectAndInfo(got.get(1), o1, p1, expdata2, refs1, refmap1); compareObjectAndInfo(got.get(2), o2, p2, expdata3, refs2, refmap2); compareObjectAndInfo(got.get(3), o3, p2, expdata4, refs2, refmap2); // new test for extractor that fails on an array OOB failGetSubset(user, Arrays.asList( new SubObjectIdentifier(oident2, new ObjectPaths( Arrays.asList("/array/3", "/array/0")))), new TypedObjectExtractionException( "Invalid selection: no array element exists at position '3', at: /array/3")); got = ws.getObjectsSubSet(user, Arrays.asList( new SubObjectIdentifier(oident1, new ObjectPaths( Arrays.asList("/map/*/thing"))), new SubObjectIdentifier(oident2, new ObjectPaths( Arrays.asList("/array/[*]/thing"))))); expdata1 = createData( "{\"map\": {\"id1\": {\"thing\": \"foo\"}," + " \"id2\": {\"thing\": \"foo2\"}," + " \"id3\": {\"thing\": \"foo3\"}" + " }" + "}" ); expdata2 = createData( "{\"array\": [{\"thing\": \"foo\"}," + " {\"thing\": \"foo2\"}," + " {\"thing\": \"foo3\"}" + " ]" + "}" ); compareObjectAndInfo(got.get(0), o1, p1, expdata1, refs1, refmap1); compareObjectAndInfo(got.get(1), o2, p2, expdata2, refs2, refmap2); failGetSubset(user, Arrays.asList( new SubObjectIdentifier(oident1, new ObjectPaths( Arrays.asList("/map/id1/id/5")))), new TypedObjectExtractionException( "Invalid selection: the path given specifies fields or elements that do not exist " + "because data at this location is a scalar value (i.e. string, integer, float), at: /map/id1/id")); failGetSubset(user2, Arrays.asList( new SubObjectIdentifier(oident1, new ObjectPaths( Arrays.asList("/map/*/thing")))), new InaccessibleObjectException( "Object o1 cannot be accessed: User subUser2 may not read workspace subData")); try { ws.getObjectsSubSet(user2, Arrays.asList(new SubObjectIdentifier( new ObjectIdentifier(wsi, 2), null))); fail("Able to get obj data from private workspace"); } catch (InaccessibleObjectException ioe) { assertThat("correct exception message", ioe.getLocalizedMessage(), is("Object 2 cannot be accessed: User subUser2 may not read workspace subData")); assertThat("correct object returned", ioe.getInaccessibleObject(), is(new ObjectIdentifier(wsi, 2))); } } @Test public void getReferencingObjects() throws Exception { WorkspaceUser user1 = new WorkspaceUser("refUser"); WorkspaceUser user2 = new WorkspaceUser("refUser2"); WorkspaceIdentifier wsitar1 = new WorkspaceIdentifier("refstarget1"); WorkspaceIdentifier wsitar2 = new WorkspaceIdentifier("refstarget2"); WorkspaceIdentifier wsisrc1 = new WorkspaceIdentifier("refssource1"); WorkspaceIdentifier wsisrc2 = new WorkspaceIdentifier("refssource2"); WorkspaceIdentifier wsisrc2noaccess = new WorkspaceIdentifier("refssource2noaccess"); WorkspaceIdentifier wsisrcdel1 = new WorkspaceIdentifier("refssourcedel1"); WorkspaceIdentifier wsisrc2gl = new WorkspaceIdentifier("refssourcegl"); ws.createWorkspace(user1, wsitar1.getName(), false, null, null); ws.setPermissions(user1, wsitar1, Arrays.asList(user2), Permission.READ); ws.createWorkspace(user2, wsitar2.getName(), false, null, null); ws.setPermissions(user2, wsitar2, Arrays.asList(user1), Permission.READ); ws.createWorkspace(user1, wsisrc1.getName(), false, null, null); ws.createWorkspace(user2, wsisrc2.getName(), false, null, null); ws.setPermissions(user2, wsisrc2, Arrays.asList(user1), Permission.READ); ws.createWorkspace(user2, wsisrc2noaccess.getName(), false, null, null); ws.createWorkspace(user1, wsisrcdel1.getName(), false, null, null); ws.createWorkspace(user2, wsisrc2gl.getName(), true, null, null); TypeDefId reftype = new TypeDefId(new TypeDefName("CopyRev", "RefType"), 1, 0); Map<String, String> meta1 = new HashMap<String, String>(); meta1.put("metastuff", "meta"); Map<String, String> meta2 = new HashMap<String, String>(); meta2.put("meta2", "my hovercraft is full of eels"); Map<String, Object> mtdata = new HashMap<String, Object>(); Provenance p1 = new Provenance(user1); //test objects with no references or no accessible references ws.saveObjects(user1, wsitar1, Arrays.asList( new WorkspaceSaveObject(new ObjectIDNoWSNoVer("norefs"), mtdata, SAFE_TYPE1, null, p1, false), new WorkspaceSaveObject(new ObjectIDNoWSNoVer("deletedref"), mtdata, SAFE_TYPE1, null, p1, false), new WorkspaceSaveObject(new ObjectIDNoWSNoVer("unreadableref"), mtdata, SAFE_TYPE1, null, p1, false), new WorkspaceSaveObject(new ObjectIDNoWSNoVer("deletedprovref"), mtdata, SAFE_TYPE1, null, p1, false), new WorkspaceSaveObject(new ObjectIDNoWSNoVer("unreadableprovref"), mtdata, SAFE_TYPE1, null, p1, false)), getIdFactory(user1)); Map<String, Object> refdata = new HashMap<String, Object>(); refdata.put("refs", Arrays.asList("refstarget1/deletedref")); ws.saveObjects(user1, wsisrc1, Arrays.asList( new WorkspaceSaveObject(new ObjectIDNoWSNoVer("delrefptr"), refdata, reftype, null, p1, false)), getIdFactory(user1)); ws.setObjectsDeleted(user1, Arrays.asList( new ObjectIdentifier(wsisrc1, "delrefptr")), true); refdata.put("refs", Arrays.asList("refstarget1/unreadableref")); ws.saveObjects(user2, wsisrc2noaccess, Arrays.asList( new WorkspaceSaveObject(new ObjectIDNoWSNoVer("unreadrefptr"), refdata, reftype, null, p1, false)), getIdFactory(user2)); ws.saveObjects(user1, wsisrc1, Arrays.asList( new WorkspaceSaveObject(new ObjectIDNoWSNoVer("deletedprovrefptr"), mtdata, SAFE_TYPE1, null, new Provenance(user1).addAction(new ProvenanceAction() .withWorkspaceObjects(Arrays.asList("refstarget1/deletedprovref"))), false)), getIdFactory(user1)); ws.setObjectsDeleted(user1, Arrays.asList( new ObjectIdentifier(wsisrc1, "deletedprovrefptr")), true); ws.saveObjects(user2, wsisrc2noaccess, Arrays.asList( new WorkspaceSaveObject(new ObjectIDNoWSNoVer("unreadableprovrefptr"), mtdata, SAFE_TYPE1, null, new Provenance(user1).addAction(new ProvenanceAction() .withWorkspaceObjects(Arrays.asList("refstarget1/unreadableprovref"))), false)), getIdFactory(user2)); List<Set<ObjectInformation>> mtrefs = new ArrayList<Set<ObjectInformation>>(); mtrefs.add(new HashSet<ObjectInformation>()); for (String name: Arrays.asList("norefs", "deletedref", "unreadableref", "deletedprovref", "unreadableprovref")) { assertThat("ref lists empty", ws.getReferencingObjects(user1, Arrays.asList(new ObjectIdentifier(wsitar1, name))), is(mtrefs)); } ws.saveObjects(user1, wsitar1, Arrays.asList( new WorkspaceSaveObject(new ObjectIDNoWSNoVer("stk"), mtdata, SAFE_TYPE1, meta1, p1, false), new WorkspaceSaveObject(new ObjectIDNoWSNoVer("stk"), mtdata, SAFE_TYPE1, meta2, p1, false), new WorkspaceSaveObject(new ObjectIDNoWSNoVer("single"), mtdata, SAFE_TYPE1, meta1, p1, false)), getIdFactory(user1)); ws.saveObjects(user2, wsitar2, Arrays.asList( new WorkspaceSaveObject(new ObjectIDNoWSNoVer("stk2"), mtdata, SAFE_TYPE1, meta1, p1, false), new WorkspaceSaveObject(new ObjectIDNoWSNoVer("stk2"), mtdata, SAFE_TYPE1, meta2, p1, false), new WorkspaceSaveObject(new ObjectIDNoWSNoVer("single2"), mtdata, SAFE_TYPE1, meta1, p1, false)), getIdFactory(user2)); refdata.put("refs", Arrays.asList("refstarget1/stk/1")); ObjectInformation stdref1 = ws.saveObjects(user1, wsisrc1, Arrays.asList( new WorkspaceSaveObject(new ObjectIDNoWSNoVer("stdref"), refdata, reftype, meta1, new Provenance(user1).addAction(new ProvenanceAction() .withWorkspaceObjects(Arrays.asList("refstarget1/stk/1"))), false)), getIdFactory(user1)).get(0); refdata.put("refs", Arrays.asList("refstarget1/stk/2")); ObjectInformation stdref2 = ws.saveObjects(user1, wsisrc1, Arrays.asList( new WorkspaceSaveObject(new ObjectIDNoWSNoVer("stdref"), refdata, reftype, meta2, new Provenance(user1), false)), getIdFactory(user1)).get(0); refdata.put("refs", Arrays.asList("refstarget1/stk")); ObjectInformation hiddenref = ws.saveObjects(user1, wsisrc1, Arrays.asList( new WorkspaceSaveObject(new ObjectIDNoWSNoVer("hiddenref"), refdata, reftype, meta1, new Provenance(user1), true)), getIdFactory(user1)).get(0); refdata.put("refs", Arrays.asList("refstarget2/stk2")); @SuppressWarnings("unused") ObjectInformation delref = ws.saveObjects(user1, wsisrc1, Arrays.asList( new WorkspaceSaveObject(new ObjectIDNoWSNoVer("delref"), refdata, reftype, meta1, new Provenance(user1).addAction(new ProvenanceAction() .withWorkspaceObjects(Arrays.asList("refstarget1/stk/2"))), true)), getIdFactory(user1)).get(0); ws.setObjectsDeleted(user1, Arrays.asList(new ObjectIdentifier(wsisrc1, "delref")), true); refdata.put("refs", Arrays.asList("refstarget1/single")); ObjectInformation readable = ws.saveObjects(user2, wsisrc2, Arrays.asList( new WorkspaceSaveObject(new ObjectIDNoWSNoVer("readable"), refdata, reftype, meta2, new Provenance(user2), true)), getIdFactory(user2)).get(0); refdata.put("refs", Arrays.asList("refstarget2/stk2/2")); @SuppressWarnings("unused") ObjectInformation unreadable = ws.saveObjects(user2, wsisrc2noaccess, Arrays.asList( new WorkspaceSaveObject(new ObjectIDNoWSNoVer("unreadable"), refdata, reftype, meta1, new Provenance(user2), true)), getIdFactory(user2)).get(0); refdata.put("refs", Arrays.asList("refstarget2/single2/1")); @SuppressWarnings("unused") ObjectInformation wsdeletedreadable1 = ws.saveObjects(user1, wsisrcdel1, Arrays.asList( new WorkspaceSaveObject(new ObjectIDNoWSNoVer("wsdeletedreadable1"), refdata, reftype, meta2, new Provenance(user1), false)), getIdFactory(user1)).get(0); ws.setWorkspaceDeleted(user1, wsisrcdel1, true); refdata.put("refs", Arrays.asList("refstarget2/stk2/1")); ObjectInformation globalrd = ws.saveObjects(user2, wsisrc2gl, Arrays.asList( new WorkspaceSaveObject(new ObjectIDNoWSNoVer("globalrd"), refdata, reftype, meta1, new Provenance(user2).addAction(new ProvenanceAction() .withWorkspaceObjects(Arrays.asList("refstarget1/single/1"))), false)), getIdFactory(user2)).get(0); List<ObjectIdentifier> objs = Arrays.asList( new ObjectIdentifier(wsitar1, "stk"), new ObjectIdentifier(wsitar1, "stk", 2), new ObjectIdentifier(wsitar1, "stk", 1)); assertThat("got correct refs", ws.getReferencingObjects(user1, objs), is(Arrays.asList( oiset(stdref2, hiddenref), oiset(stdref2, hiddenref), oiset(stdref1)))); assertThat("got correct refcounts", ws.getReferencingObjectCounts(user1, objs), is(Arrays.asList(3, 3, 1))); Set<ObjectInformation> mtoiset = new HashSet<ObjectInformation>(); objs = Arrays.asList( new ObjectIdentifier(wsitar2, "stk2"), new ObjectIdentifier(wsitar2, "stk2", 2), new ObjectIdentifier(wsitar2, "stk2", 1)); assertThat("got correct refs", ws.getReferencingObjects(user1, objs), is(Arrays.asList( mtoiset, mtoiset, oiset(globalrd)))); assertThat("got correct refcounts", ws.getReferencingObjectCounts(user1, objs), is(Arrays.asList(2, 2, 1))); objs = Arrays.asList( new ObjectIdentifier(wsitar1, "single"), new ObjectIdentifier(wsitar1, "single", 1), new ObjectIdentifier(wsitar2, "single2"), new ObjectIdentifier(wsitar2, "single2", 1)); assertThat("got correct refs", ws.getReferencingObjects(user1,objs), is(Arrays.asList( oiset(readable, globalrd), oiset(readable, globalrd), mtoiset, mtoiset))); assertThat("got correct refcounts", ws.getReferencingObjectCounts(user1, objs), is(Arrays.asList(2, 2, 1, 1))); ObjectInformation pstdref1 = ws.saveObjects(user1, wsisrc1, Arrays.asList( new WorkspaceSaveObject(new ObjectIDNoWSNoVer("pstdref"), mtdata, SAFE_TYPE1, meta1, new Provenance(user1).addAction(new ProvenanceAction() .withWorkspaceObjects(Arrays.asList("refstarget1/stk/1"))), false)), getIdFactory(user1)).get(0); ObjectInformation pstdref2 = ws.saveObjects(user1, wsisrc1, Arrays.asList( new WorkspaceSaveObject(new ObjectIDNoWSNoVer("pstdref"), mtdata, SAFE_TYPE1, meta2, new Provenance(user1).addAction(new ProvenanceAction() .withWorkspaceObjects(Arrays.asList("refstarget1/stk/2"))), false)), getIdFactory(user1)).get(0); ObjectInformation phiddenref = ws.saveObjects(user1, wsisrc1, Arrays.asList( new WorkspaceSaveObject(new ObjectIDNoWSNoVer("phiddenref"), mtdata, SAFE_TYPE1, meta1, new Provenance(user1).addAction(new ProvenanceAction() .withWorkspaceObjects(Arrays.asList("refstarget1/stk"))), true)), getIdFactory(user1)).get(0); @SuppressWarnings("unused") ObjectInformation pdelref = ws.saveObjects(user1, wsisrc1, Arrays.asList( new WorkspaceSaveObject(new ObjectIDNoWSNoVer("pdelref"), mtdata, SAFE_TYPE1, meta1, new Provenance(user1).addAction(new ProvenanceAction() .withWorkspaceObjects(Arrays.asList("refstarget2/stk2"))), true)), getIdFactory(user1)).get(0); ws.setObjectsDeleted(user1, Arrays.asList(new ObjectIdentifier(wsisrc1, "pdelref")), true); ObjectInformation preadable = ws.saveObjects(user2, wsisrc2, Arrays.asList( new WorkspaceSaveObject(new ObjectIDNoWSNoVer("preadable"), mtdata, SAFE_TYPE1, meta2, new Provenance(user2).addAction(new ProvenanceAction() .withWorkspaceObjects(Arrays.asList("refstarget1/single"))), true)), getIdFactory(user2)).get(0); @SuppressWarnings("unused") ObjectInformation punreadable = ws.saveObjects(user2, wsisrc2noaccess, Arrays.asList( new WorkspaceSaveObject(new ObjectIDNoWSNoVer("punreadable"), mtdata, SAFE_TYPE1, meta1, new Provenance(user2).addAction(new ProvenanceAction() .withWorkspaceObjects(Arrays.asList("refstarget2/stk2/2"))), true)), getIdFactory(user2)).get(0); ws.setWorkspaceDeleted(user1, wsisrcdel1, false); @SuppressWarnings("unused") ObjectInformation pwsdeletedreadable1 = ws.saveObjects(user1, wsisrcdel1, Arrays.asList( new WorkspaceSaveObject(new ObjectIDNoWSNoVer("pwsdeletedreadable1"), mtdata, SAFE_TYPE1, meta2, new Provenance(user1).addAction(new ProvenanceAction() .withWorkspaceObjects(Arrays.asList("refstarget2/single2/1"))), false)), getIdFactory(user1)).get(0); ws.setWorkspaceDeleted(user1, wsisrcdel1, true); ObjectInformation pglobalrd = ws.saveObjects(user2, wsisrc2gl, Arrays.asList( new WorkspaceSaveObject(new ObjectIDNoWSNoVer("pglobalrd"), mtdata, SAFE_TYPE1, meta1, new Provenance(user2).addAction(new ProvenanceAction() .withWorkspaceObjects(Arrays.asList("refstarget2/stk2/1"))), false)), getIdFactory(user2)).get(0); objs = Arrays.asList( new ObjectIdentifier(wsitar1, "stk"), new ObjectIdentifier(wsitar1, "stk", 2), new ObjectIdentifier(wsitar1, "stk", 1)); assertThat("got correct refs", ws.getReferencingObjects(user1, objs), is(Arrays.asList( oiset(stdref2, hiddenref, pstdref2, phiddenref), oiset(stdref2, hiddenref, pstdref2, phiddenref), oiset(stdref1, pstdref1)))); assertThat("got correct refcounts", ws.getReferencingObjectCounts(user1, objs), is(Arrays.asList(5, 5, 2))); objs = Arrays.asList( new ObjectIdentifier(wsitar2, "stk2"), new ObjectIdentifier(wsitar2, "stk2", 2), new ObjectIdentifier(wsitar2, "stk2", 1)); assertThat("got correct refs", ws.getReferencingObjects(user1, objs), is(Arrays.asList( mtoiset, mtoiset, oiset(globalrd, pglobalrd)))); assertThat("got correct refcounts", ws.getReferencingObjectCounts(user1, objs), is(Arrays.asList(4, 4, 2))); objs = Arrays.asList( new ObjectIdentifier(wsitar1, "single"), new ObjectIdentifier(wsitar1, "single", 1), new ObjectIdentifier(wsitar2, "single2"), new ObjectIdentifier(wsitar2, "single2", 1)); assertThat("got correct refs", ws.getReferencingObjects(user1, objs), is(Arrays.asList( oiset(readable, globalrd, preadable), oiset(readable, globalrd, preadable), mtoiset, mtoiset))); assertThat("got correct refcounts", ws.getReferencingObjectCounts(user1, objs), is(Arrays.asList(3, 3, 2, 2))); try { ws.getReferencingObjects(user2, Arrays.asList( new ObjectIdentifier(wsisrc1, 1))); fail("Able to get ref obj data from private workspace"); } catch (InaccessibleObjectException ioe) { assertThat("correct exception message", ioe.getLocalizedMessage(), is("Object 1 cannot be accessed: User refUser2 may not read workspace refssource1")); assertThat("correct object returned", ioe.getInaccessibleObject(), is(new ObjectIdentifier(wsisrc1, 1))); } try { ws.getReferencingObjectCounts(user2, Arrays.asList( new ObjectIdentifier(wsisrc1, 1))); fail("Able to get ref obj count from private workspace"); } catch (InaccessibleObjectException ioe) { assertThat("correct exception message", ioe.getLocalizedMessage(), is("Object 1 cannot be accessed: User refUser2 may not read workspace refssource1")); assertThat("correct object returned", ioe.getInaccessibleObject(), is(new ObjectIdentifier(wsisrc1, 1))); } ws.setGlobalPermission(user2, wsisrc2gl, Permission.NONE); } @Test public void getReferencedObjects() throws Exception { WorkspaceUser user1 = new WorkspaceUser("refedUser"); WorkspaceUser user2 = new WorkspaceUser("refedUser2"); WorkspaceIdentifier wsiacc1 = new WorkspaceIdentifier("refedaccessible"); WorkspaceIdentifier wsiacc2 = new WorkspaceIdentifier("refedaccessible2"); WorkspaceIdentifier wsiun1 = new WorkspaceIdentifier("refedunacc"); WorkspaceIdentifier wsiun2 = new WorkspaceIdentifier("refedunacc2"); WorkspaceIdentifier wsidel = new WorkspaceIdentifier("refeddel"); ws.createWorkspace(user1, wsiacc1.getName(), false, null, null); ws.setPermissions(user1, wsiacc1, Arrays.asList(user2), Permission.WRITE); ws.createWorkspace(user2, wsiacc2.getName(), true, null, null); long wsidun1 = ws.createWorkspace(user2, wsiun1.getName(), false, null, null).getId(); long wsidun2 = ws.createWorkspace(user2, wsiun2.getName(), false, null, null).getId(); ws.createWorkspace(user2, wsidel.getName(), false, null, null); TypeDefId reftype = new TypeDefId(new TypeDefName("CopyRev", "RefType"), 1, 0); Map<String, String> meta1 = new HashMap<String, String>(); meta1.put("some", "very special metadata"); Map<String, String> meta2 = new HashMap<String, String>(); meta2.put("some", "very special metadata2"); Map<String, String> mtdata = new HashMap<String, String>(); Map<String, Object> data1 = createData( "{\"thing1\": \"whoop whoop\"," + " \"thing2\": \"aroooga\"}"); Map<String, Object> data2 = createData( "{\"thing3\": \"whoop whoop\"," + " \"thing4\": \"aroooga\"}"); ObjectInformation leaf1 = saveObject(user2, wsiun1, meta1, data1, SAFE_TYPE1, "leaf1", new Provenance(user2)); ObjectIdentifier leaf1oi = new ObjectIdentifier(wsiun1, "leaf1"); failGetObjects(user1, Arrays.asList(leaf1oi), new InaccessibleObjectException( "Object leaf1 cannot be accessed: User refedUser may not read workspace refedunacc")); ObjectInformation leaf2 = saveObject(user2, wsiun2, meta2, data2, SAFE_TYPE1, "leaf2", new Provenance(user2)); ObjectIdentifier leaf2oi = new ObjectIdentifier(wsiun2, "leaf2"); failGetObjects(user1, Arrays.asList(leaf2oi), new InaccessibleObjectException( "Object leaf2 cannot be accessed: User refedUser may not read workspace refedunacc2")); saveObject(user2, wsiun2, meta2, data2, SAFE_TYPE1, "unlinked", new Provenance(user2)); ObjectIdentifier unlinkedoi = new ObjectIdentifier(wsiun2, "unlinked"); failGetObjects(user1, Arrays.asList(unlinkedoi), new InaccessibleObjectException( "Object unlinked cannot be accessed: User refedUser may not read workspace refedunacc2")); final String leaf1r = "refedunacc/leaf1"; saveObject(user2, wsiacc1, MT_META, makeRefData(leaf1r),reftype, "simpleref", new Provenance(user2)); final String leaf2r = "refedunacc2/leaf2"; saveObject(user2, wsiacc2, MT_META, makeRefData(leaf2r),reftype, "simpleref2", new Provenance(user2)); saveObject(user2, wsiacc1, MT_META, mtdata, SAFE_TYPE1, "provref", new Provenance(user2) .addAction(new ProvenanceAction().withWorkspaceObjects( Arrays.asList(leaf1r)))); saveObject(user2, wsiacc2, MT_META, mtdata, SAFE_TYPE1, "provref2", new Provenance(user2) .addAction(new ProvenanceAction().withWorkspaceObjects( Arrays.asList(leaf2r)))); final HashMap<String, String> mtmap = new HashMap<String, String>(); final LinkedList<String> mtlist = new LinkedList<String>(); checkReferencedObject(user1, new ObjectChain(new ObjectIdentifier(wsiacc1, "simpleref"), Arrays.asList(leaf1oi)), leaf1, new Provenance(user2), data1, mtlist, mtmap); checkReferencedObject(user1, new ObjectChain(new ObjectIdentifier(wsiacc2, "simpleref2"), Arrays.asList(leaf2oi)), leaf2, new Provenance(user2), data2, mtlist, mtmap); checkReferencedObject(user1, new ObjectChain(new ObjectIdentifier(wsiacc1, "provref"), Arrays.asList(leaf1oi)), leaf1, new Provenance(user2), data1, mtlist, mtmap); checkReferencedObject(user1, new ObjectChain(new ObjectIdentifier(wsiacc2, "provref2"), Arrays.asList(leaf2oi)), leaf2, new Provenance(user2), data2, mtlist, mtmap); failGetReferencedObjects(user1, Arrays.asList(new ObjectChain(new ObjectIdentifier(wsiacc2, "simpleref2"), Arrays.asList(leaf1oi))), new NoSuchReferenceException( "The object simpleref2 in workspace refedaccessible2 does not contain the reference " + wsidun1 + "/1/1", null, null)); ObjectInformation del1 = saveObject(user2, wsiun1, meta2, makeRefData(leaf1r, leaf2r), reftype, "del1", new Provenance(user2)); ObjectIdentifier del1oi = new ObjectIdentifier(wsiun1, "del1"); final Provenance p = new Provenance(user2).addAction(new ProvenanceAction() .withWorkspaceObjects(Arrays.asList(leaf1r, leaf2r))); ObjectInformation del2 = saveObject(user2, wsiun2, meta1, makeRefData(), reftype, "del2", p); ObjectIdentifier del2oi = new ObjectIdentifier(wsiun2, "del2"); saveObject(user2, wsidel, meta1, makeRefData(leaf2r), reftype, "delws", new Provenance(user2)); ObjectIdentifier delwsoi = new ObjectIdentifier(wsidel, "delws"); saveObject(user2, wsiacc1, MT_META, makeRefData("refedunacc/del1", "refedunacc2/del2"), reftype, "delptr12", new Provenance(user2)); ObjectIdentifier delptr12oi = new ObjectIdentifier(wsiacc1, "delptr12"); saveObject(user2, wsiacc2, MT_META, makeRefData("refedunacc2/del2"), reftype, "delptr2", new Provenance(user2)); ObjectIdentifier delptr2oi = new ObjectIdentifier(wsiacc2, "delptr2"); saveObject(user2, wsiacc2, MT_META, makeRefData("refeddel/delws"), reftype, "delptrws", new Provenance(user2)); ObjectIdentifier delptrwsoi = new ObjectIdentifier(wsiacc2, "delptrws"); ws.setObjectsDeleted(user2, Arrays.asList(del1oi, del2oi), true); ws.setWorkspaceDeleted(user2, wsidel, true); List<WorkspaceObjectData> lwod = ws.getReferencedObjects(user1, Arrays.asList( new ObjectChain(delptr12oi, Arrays.asList(del1oi, leaf1oi)), new ObjectChain(delptr12oi, Arrays.asList(del1oi, leaf2oi)), new ObjectChain(delptr12oi, Arrays.asList(del2oi, leaf1oi)), new ObjectChain(delptrwsoi, Arrays.asList(delwsoi, leaf2oi)), new ObjectChain(delptr12oi, Arrays.asList(del2oi, leaf2oi)), new ObjectChain(delptr2oi, Arrays.asList(del2oi, leaf1oi)), new ObjectChain(delptr2oi, Arrays.asList(del2oi, leaf2oi)) )); assertThat("correct list size", lwod.size(), is(7)); compareObjectAndInfo(lwod.get(0), leaf1, new Provenance(user2), data1, mtlist, mtmap); compareObjectAndInfo(lwod.get(1), leaf2, new Provenance(user2), data2, mtlist, mtmap); compareObjectAndInfo(lwod.get(2), leaf1, new Provenance(user2), data1, mtlist, mtmap); compareObjectAndInfo(lwod.get(3), leaf2, new Provenance(user2), data2, mtlist, mtmap); compareObjectAndInfo(lwod.get(4), leaf2, new Provenance(user2), data2, mtlist, mtmap); compareObjectAndInfo(lwod.get(5), leaf1, new Provenance(user2), data1, mtlist, mtmap); compareObjectAndInfo(lwod.get(6), leaf2, new Provenance(user2), data2, mtlist, mtmap); checkReferencedObject(user1, new ObjectChain(delptr12oi, Arrays.asList(del1oi)), del1, new Provenance(user2), makeRefData(wsidun1 + "/1/1", wsidun2 + "/1/1"), Arrays.asList(wsidun1 + "/1/1", wsidun2 + "/1/1"), mtmap); Map<String, String> provmap = new HashMap<String, String>(); provmap.put(leaf1r, wsidun1 + "/1/1"); provmap.put(leaf2r, wsidun2 + "/1/1"); checkReferencedObject(user1, new ObjectChain(delptr12oi, Arrays.asList(del2oi)), del2, p, makeRefData(), mtlist, provmap); failGetReferencedObjects(user1, Arrays.asList(new ObjectChain(delptr2oi, Arrays.asList(del1oi, leaf1oi))), new NoSuchReferenceException( "The object delptr2 in workspace refedaccessible2 does not contain the reference " + wsidun1 + "/2/1", null, null)); failGetReferencedObjects(user1, Arrays.asList(new ObjectChain(delptr12oi, Arrays.asList(del1oi, unlinkedoi))), new NoSuchReferenceException( "The object del1 in workspace refedunacc does not contain the reference " + wsidun2 + "/2/1", null, null)); failGetReferencedObjects(user1, Arrays.asList(new ObjectChain(delptr12oi, Arrays.asList(del1oi, new ObjectIdentifier(wsiun1, "leaf2")))), new NoSuchObjectException( "No object with name leaf2 exists in workspace " + wsidun1, null, null)); failGetReferencedObjects(user1, Arrays.asList(new ObjectChain(delptr12oi, Arrays.asList(del1oi, new ObjectIdentifier(wsiun1, "leaf1", 2)))), new NoSuchObjectException( "No object with id 1 (name leaf1) and version 2 exists in workspace " + wsidun1, null, null)); failGetReferencedObjects(user2, new ArrayList<ObjectChain>(), new IllegalArgumentException("No object identifiers provided")); failGetReferencedObjects(user2, Arrays.asList(new ObjectChain(new ObjectIdentifier(wsiun1, "leaf3"), Arrays.asList(new ObjectIdentifier(wsiun1, "leaf1")))), new InaccessibleObjectException("No object with name leaf3 exists in workspace " + wsidun1)); failGetReferencedObjects(user1, Arrays.asList(new ObjectChain(new ObjectIdentifier(new WorkspaceIdentifier("fakefakefake"), "leaf1"), Arrays.asList(new ObjectIdentifier(wsiun1, "leaf1")))), new InaccessibleObjectException("Object leaf1 cannot be accessed: No workspace with name fakefakefake exists")); failGetReferencedObjects(user1, Arrays.asList(new ObjectChain(new ObjectIdentifier(wsiun1, "leaf1"), Arrays.asList(new ObjectIdentifier(wsiun1, "leaf1")))), new InaccessibleObjectException("Object leaf1 cannot be accessed: User refedUser may not read workspace refedunacc")); failGetReferencedObjects(null, Arrays.asList(new ObjectChain(new ObjectIdentifier(wsiun1, "leaf1"), Arrays.asList(new ObjectIdentifier(wsiun1, "leaf1")))), new InaccessibleObjectException("Object leaf1 cannot be accessed: Anonymous users may not read workspace refedunacc")); ws.setObjectsDeleted(user2, Arrays.asList(new ObjectIdentifier(wsiun1, "leaf1")), true); failGetReferencedObjects(user2, Arrays.asList(new ObjectChain(new ObjectIdentifier(wsiun1, "leaf1"), Arrays.asList(new ObjectIdentifier(wsiun1, "leaf1")))), new InaccessibleObjectException("Object 1 (name leaf1) in workspace " + wsidun1 + " has been deleted")); ws.setObjectsDeleted(user2, Arrays.asList(new ObjectIdentifier(wsiun1, "leaf1")), false); ws.setWorkspaceDeleted(user2, wsiun1, true); failGetReferencedObjects(user2, Arrays.asList(new ObjectChain(new ObjectIdentifier(wsiun1, "leaf1"), Arrays.asList(new ObjectIdentifier(wsiun1, "leaf1")))), new InaccessibleObjectException("Object leaf1 cannot be accessed: Workspace refedunacc is deleted")); ws.setGlobalPermission(user2, wsiacc2, Permission.NONE); } @Test public void objectChain() throws Exception { WorkspaceIdentifier wsi = new WorkspaceIdentifier("foo"); ObjectIdentifier oi = new ObjectIdentifier(wsi, "thing"); failCreateObjectChain(null, new ArrayList<ObjectIdentifier>(), new IllegalArgumentException("Neither head nor chain can be null")); failCreateObjectChain(oi, null, new IllegalArgumentException("Neither head nor chain can be null")); failCreateObjectChain(oi, new ArrayList<ObjectIdentifier>(), new IllegalArgumentException("Chain cannot be empty")); failCreateObjectChain(oi, Arrays.asList(oi, null, oi), new IllegalArgumentException("Nulls are not allowed in reference chains")); } @Test public void grantRemoveOwnership() throws Exception { WorkspaceUser user = new WorkspaceUser("foo"); String moduleName = "SharedModule"; ws.requestModuleRegistration(user, moduleName); ws.resolveModuleRegistration(moduleName, true); ws.compileNewTypeSpec(user, "module " + moduleName + " {typedef int MainType;};", Arrays.asList("MainType"), null, null, false, null); ws.releaseTypes(user, moduleName); WorkspaceUser user2 = new WorkspaceUser("bar"); try { ws.compileNewTypeSpec(user2, "module " + moduleName + " {typedef string MainType;};", Collections.<String>emptyList(), null, null, false, null); Assert.fail(); } catch (NoSuchPrivilegeException ex) { Assert.assertTrue(ex.getMessage(), ex.getMessage().contains("not in list of owners")); } ws.grantModuleOwnership(moduleName, user2.getUser(), false, user, false); ws.compileNewTypeSpec(user2, "module " + moduleName + " {typedef string MainType;};", Collections.<String>emptyList(), null, null, false, null); WorkspaceUser user3 = new WorkspaceUser("baz"); try { ws.grantModuleOwnership(moduleName, user3.getUser(), false, user2, false); Assert.fail(); } catch (NoSuchPrivilegeException ex) { Assert.assertTrue(ex.getMessage(), ex.getMessage().contains("can not change privileges")); } ws.grantModuleOwnership(moduleName, user2.getUser(), true, user, false); ws.grantModuleOwnership(moduleName, user3.getUser(), false, user2, false); ws.removeModuleOwnership(moduleName, user3.getUser(), user2, false); ws.removeModuleOwnership(moduleName, user2.getUser(), user, false); try { ws.compileNewTypeSpec(user2, "module " + moduleName + " {typedef float MainType;};", Collections.<String>emptyList(), null, null, false, null); Assert.fail(); } catch (NoSuchPrivilegeException ex) { Assert.assertTrue(ex.getMessage(), ex.getMessage().contains("not in list of owners")); } } @Test public void removeTypeTest() throws Exception { WorkspaceUser user = new WorkspaceUser("foo"); String moduleName = "MyMod3"; ws.requestModuleRegistration(user, moduleName); ws.resolveModuleRegistration(moduleName, true); ws.compileNewTypeSpec(user, "module " + moduleName + " {" + "typedef structure {string foo; list<int> bar; int baz;} AType; " + "typedef structure {string whooo;} BType;};", Arrays.asList("AType", "BType"), null, null, false, null); ws.compileTypeSpec(user, moduleName, Collections.<String>emptyList(), Arrays.asList("BType"), Collections.<String, Long>emptyMap(), false); List<Long> vers = ws.getModuleVersions(moduleName, user); Collections.sort(vers); Assert.assertEquals(2, vers.size()); Assert.assertEquals(2, ws.getModuleInfo(user, new ModuleDefId(moduleName, vers.get(0))).getTypes().size()); Assert.assertEquals(1, ws.getModuleInfo(user, new ModuleDefId(moduleName, vers.get(1))).getTypes().size()); Assert.assertEquals(Arrays.asList(vers.get(0)), ws.getModuleVersions(new TypeDefId(moduleName + ".BType", "0.1"), user)); ws.releaseTypes(user, moduleName); Assert.assertEquals(1, ws.getModuleVersions(new TypeDefId(moduleName + ".AType"), null).size()); Assert.assertEquals(moduleName + ".AType-1.0", ws.getTypeInfo(moduleName + ".AType", false, null).getTypeDefId()); } @Test public void admin() throws Exception { assertThat("no admins before adding any", ws.getAdmins(), is((Set<WorkspaceUser>) new HashSet<WorkspaceUser>())); ws.addAdmin(new WorkspaceUser("adminguy")); Set<WorkspaceUser> expected = new HashSet<WorkspaceUser>(); expected.add(new WorkspaceUser("adminguy")); assertThat("correct admins", ws.getAdmins(), is(expected)); assertTrue("correctly detected as admin", ws.isAdmin(new WorkspaceUser("adminguy"))); assertFalse("correctly detected as not an admin", ws.isAdmin(new WorkspaceUser("adminguy2"))); ws.addAdmin(new WorkspaceUser("adminguy2")); expected.add(new WorkspaceUser("adminguy2")); assertThat("correct admins", ws.getAdmins(), is(expected)); assertTrue("correctly detected as admin", ws.isAdmin(new WorkspaceUser("adminguy"))); assertTrue("correctly detected as admin", ws.isAdmin(new WorkspaceUser("adminguy2"))); assertFalse("correctly detected as not an admin", ws.isAdmin(new WorkspaceUser("adminguy3"))); ws.removeAdmin(new WorkspaceUser("adminguy")); expected.remove(new WorkspaceUser("adminguy")); assertThat("correct admins", ws.getAdmins(), is(expected)); assertFalse("correctly detected as not an admin", ws.isAdmin(new WorkspaceUser("adminguy"))); assertTrue("correctly detected as admin", ws.isAdmin(new WorkspaceUser("adminguy2"))); assertFalse("correctly detected as not an admin", ws.isAdmin(new WorkspaceUser("adminguy3"))); } @Test public void getAllWorkspaceOwners() throws Exception { Set<WorkspaceUser> startusers = ws.getAllWorkspaceOwners(); String userprefix = "getAllWorkspaceOwners"; Set<WorkspaceUser> users = new HashSet<WorkspaceUser>(); for (int i = 0; i < 4; i++) { String u = userprefix + i; users.add(new WorkspaceUser(u)); ws.createWorkspace(new WorkspaceUser(u), u + ":" + userprefix, false, null, null); } Set<WorkspaceUser> newusers = ws.getAllWorkspaceOwners(); newusers.removeAll(startusers); assertThat("got correct list of workspace users", newusers, is(users)); } @Test public void sortForMD5() throws Exception { WorkspaceUser user = new WorkspaceUser("md5user"); WorkspaceIdentifier wsi = new WorkspaceIdentifier("sorting"); ws.createWorkspace(user, wsi.getIdentifierString(), false, null, null); Map<String, Object> data = new LinkedHashMap<String, Object>(); data.put("g", 7); data.put("d", 4); data.put("a", 1); data.put("e", 5); data.put("b", 2); data.put("f", 6); data.put("c", 3); String expected = "{\"a\":1,\"b\":2,\"c\":3,\"d\":4,\"e\":5,\"f\":6,\"g\":7}"; String md5 = DigestUtils.md5Hex(expected); assertThat("md5 correct", md5, is("f906e268b16cbfa1c302c6bb51a6b784")); JsonNode savedata = MAPPER.valueToTree(data); Provenance p = new Provenance(new WorkspaceUser("kbasetest2")); List<WorkspaceSaveObject> objects = Arrays.asList( new WorkspaceSaveObject(savedata, SAFE_TYPE1, null, p, false)); List<ObjectInformation> objinfo = ws.saveObjects(user, wsi, objects, getIdFactory(user)); assertThat("workspace calculated md5 correct", objinfo.get(0).getCheckSum(), is(md5)); objinfo = ws.getObjectInformation(user, Arrays.asList(new ObjectIdentifier(wsi, 1)), false, false); assertThat("workspace calculated md5 correct", objinfo.get(0).getCheckSum(), is(md5)); } @Test public void maxObjectSize() throws Exception { WorkspaceUser user = new WorkspaceUser("MOSuser"); WorkspaceIdentifier wsi = new WorkspaceIdentifier("maxObjectSize"); ws.createWorkspace(user, wsi.getIdentifierString(), false, null, null); Map<String, Object> data = new HashMap<String, Object>(); data.put("foo", "9012345678"); ResourceUsageConfiguration oldcfg = ws.getResourceConfig(); ResourceUsageConfigurationBuilder build = new ResourceUsageConfigurationBuilder(oldcfg); ws.setResourceConfig(build.withMaxObjectSize(20).build()); saveObject(user, wsi, null, data, SAFE_TYPE1, "foo", new Provenance(user)); //should work data.put("foo", "90123456789"); failSave(user, wsi, Arrays.asList( new WorkspaceSaveObject(data, SAFE_TYPE1, null, new Provenance(user), false)), new IllegalArgumentException( "Object #1 data size 21 exceeds limit of 20")); ws.setResourceConfig(oldcfg); } @Test public void maxReturnedObjectSize() throws Exception { TypeDefId reftype = new TypeDefId(new TypeDefName("CopyRev", "RefType"), 1, 0); WorkspaceUser user = new WorkspaceUser("MROSuser"); WorkspaceIdentifier wsi = new WorkspaceIdentifier("maxReturnedObjectSize"); ws.createWorkspace(user, wsi.getIdentifierString(), false, null, null); Map<String, Object> data = new HashMap<String, Object>(); data.put("fo", "90"); data.put("ba", "3"); saveObject(user, wsi, null, data, SAFE_TYPE1, "foo", new Provenance(user)); ObjectIdentifier oi1 = new ObjectIdentifier(wsi, "foo", 1); saveObject(user, wsi, null, data, SAFE_TYPE1, "foo2", new Provenance(user)); ObjectIdentifier oi2 = new ObjectIdentifier(wsi, "foo2", 1); List<ObjectIdentifier> oi1l = Arrays.asList(oi1); List<ObjectIdentifier> oi2l = Arrays.asList(oi2); Map<String, Object> refdata = new HashMap<String, Object>(); refdata.put("refs", Arrays.asList(wsi.getName() + "/foo/1")); saveObject(user, wsi, null, refdata, reftype, "ref", new Provenance(user)); refdata.put("refs", Arrays.asList(wsi.getName() + "/foo2/1")); saveObject(user, wsi, null, refdata, reftype, "ref2", new Provenance(user)); ObjectIdentifier ref = new ObjectIdentifier(wsi, "ref", 1); ObjectIdentifier ref2 = new ObjectIdentifier(wsi, "ref2", 1); List<ObjectChain> refchain = Arrays.asList(new ObjectChain(ref, oi1l)); List<ObjectChain> refchain2 = Arrays.asList(new ObjectChain(ref, oi1l), new ObjectChain(ref2, oi2l)); ResourceUsageConfiguration oldcfg = ws.getResourceConfig(); ResourceUsageConfigurationBuilder build = new ResourceUsageConfigurationBuilder( oldcfg).withMaxObjectSize(1); ws.setResourceConfig(build.withMaxReturnedDataSize(20).build()); List<SubObjectIdentifier> ois1l = Arrays.asList(new SubObjectIdentifier(oi1, new ObjectPaths(Arrays.asList("/fo")))); List<SubObjectIdentifier> ois1lmt = Arrays.asList(new SubObjectIdentifier(oi1, new ObjectPaths(new ArrayList<String>()))); successGetObjects(user, oi1l); ws.getObjectsSubSet(user, ois1l); ws.getObjectsSubSet(user, ois1lmt); ws.getReferencedObjects(user, refchain); ws.setResourceConfig(build.withMaxReturnedDataSize(19).build()); String errstr = "Too much data requested from the workspace at once; data requested " + "including potential subsets is %sB which exceeds maximum of %s."; IllegalArgumentException err = new IllegalArgumentException(String.format(errstr, 20, 19)); failGetObjects(user, oi1l, err, true); failGetSubset(user, ois1l, err); failGetSubset(user, ois1lmt, err); failGetReferencedObjects(user, refchain, err); ws.setResourceConfig(build.withMaxReturnedDataSize(40).build()); List<ObjectIdentifier> two = Arrays.asList(oi1, oi2); List<SubObjectIdentifier> ois1l2 = Arrays.asList( new SubObjectIdentifier(oi1, new ObjectPaths(Arrays.asList("/fo"))), new SubObjectIdentifier(oi1, new ObjectPaths(Arrays.asList("/ba")))); List<SubObjectIdentifier> bothoi = Arrays.asList( new SubObjectIdentifier(oi1, new ObjectPaths(Arrays.asList("/fo"))), new SubObjectIdentifier(oi2, new ObjectPaths(Arrays.asList("/ba")))); successGetObjects(user, two); ws.getObjectsSubSet(user, ois1l2); ws.getObjectsSubSet(user, bothoi); ws.getReferencedObjects(user, refchain2); ws.setResourceConfig(build.withMaxReturnedDataSize(39).build()); err = new IllegalArgumentException(String.format(errstr, 40, 39)); failGetObjects(user, two, err, true); failGetSubset(user, ois1l2, err); failGetSubset(user, bothoi, err); failGetReferencedObjects(user, refchain2, err); List<SubObjectIdentifier> all = new LinkedList<SubObjectIdentifier>(); all.addAll(ois1l2); all.addAll(bothoi); ws.setResourceConfig(build.withMaxReturnedDataSize(60).build()); ws.getObjectsSubSet(user, all); ws.setResourceConfig(build.withMaxReturnedDataSize(59).build()); err = new IllegalArgumentException(String.format(errstr, 60, 59)); failGetSubset(user, all, err); ws.setResourceConfig(oldcfg); } @Test public void useFileVsMemoryForData() throws Exception { WorkspaceUser user = new WorkspaceUser("sortfilemem"); WorkspaceIdentifier wsi = new WorkspaceIdentifier("sortFileMem"); ws.createWorkspace(user, wsi.getIdentifierString(), false, null, null); Map<String, Object> data1 = new LinkedHashMap<String, Object>(); data1.put("z", 1); data1.put("y", 2); Provenance p = new Provenance(user); List<WorkspaceSaveObject> objs = new ArrayList<WorkspaceSaveObject>(); objs.add(new WorkspaceSaveObject(data1, SAFE_TYPE1, null, p, false)); final int[] filesCreated = {0}; TempFileListener listener = new TempFileListener() { @Override public void createdTempFile(File f) { filesCreated[0]++; } }; ws.getTempFilesManager().addListener(listener); ws.getTempFilesManager().cleanup(); //these tests don't clean up after each test ResourceUsageConfiguration oldcfg = ws.getResourceConfig(); ResourceUsageConfigurationBuilder build = new ResourceUsageConfigurationBuilder(oldcfg); //single file stays in memory ws.setResourceConfig(build.withMaxIncomingDataMemoryUsage(13).build()); ws.saveObjects(user, wsi, objs, getIdFactory(user)); assertThat("created no temp files on save", filesCreated[0], is(0)); ws.setResourceConfig(build.withMaxReturnedDataMemoryUsage(13).build()); ObjectIdentifier oi = new ObjectIdentifier(wsi, 1); ws.getObjects(user, Arrays.asList(oi)); assertThat("created no temp files on get", filesCreated[0], is(0)); ws.getObjectsSubSet(user, Arrays.asList(new SubObjectIdentifier(oi, new ObjectPaths(Arrays.asList("z"))))).get(0).getDataAsTokens().destroy(); assertThat("created 1 temp file on get subdata", filesCreated[0], is(1)); JSONRPCLayerTester.assertNoTempFilesExist(ws.getTempFilesManager()); //files go to disk except for small subdata filesCreated[0] = 0; ws.setResourceConfig(build.withMaxIncomingDataMemoryUsage(12).build()); ws.saveObjects(user, wsi, objs, getIdFactory(user)); assertThat("created temp files on save", filesCreated[0], is(2)); JSONRPCLayerTester.assertNoTempFilesExist(ws.getTempFilesManager()); filesCreated[0] = 0; ws.setResourceConfig(build.withMaxReturnedDataMemoryUsage(12).build()); oi = new ObjectIdentifier(wsi, 2); ws.getObjects(user, Arrays.asList(oi)).get(0).getDataAsTokens().destroy(); assertThat("created 1 temp files on get", filesCreated[0], is(1)); JSONRPCLayerTester.assertNoTempFilesExist(ws.getTempFilesManager()); filesCreated[0] = 0; ws.getObjectsSubSet(user, Arrays.asList(new SubObjectIdentifier(oi, new ObjectPaths(Arrays.asList("z"))))).get(0).getDataAsTokens().destroy(); assertThat("created 1 temp files on get subdata part object", filesCreated[0], is(1)); JSONRPCLayerTester.assertNoTempFilesExist(ws.getTempFilesManager()); filesCreated[0] = 0; ws.getObjectsSubSet(user, Arrays.asList(new SubObjectIdentifier(oi, new ObjectPaths(Arrays.asList("z", "y"))))).get(0).getDataAsTokens().destroy(); assertThat("created 2 temp files on get subdata full object", filesCreated[0], is(2)); JSONRPCLayerTester.assertNoTempFilesExist(ws.getTempFilesManager()); // test with multiple objects Map<String, Object> data2 = new LinkedHashMap<String, Object>(); data2.put("w", 1); data2.put("f", 2); //already sorted so no temp files will be created Map<String, Object> data3 = new LinkedHashMap<String, Object>(); data3.put("x", 1); data3.put("z", 2); objs.add(new WorkspaceSaveObject(data2, SAFE_TYPE1, null, p, false)); objs.add(new WorkspaceSaveObject(data3, SAFE_TYPE1, null, p, false)); //multiple objects in memory filesCreated[0] = 0; ws.setResourceConfig(build.withMaxIncomingDataMemoryUsage(39).build()); ws.saveObjects(user, wsi, objs, getIdFactory(user)); assertThat("created no temp files on save", filesCreated[0], is(0)); ws.setResourceConfig(build.withMaxReturnedDataMemoryUsage(39).build()); List<ObjectIdentifier> ois = Arrays.asList(new ObjectIdentifier(wsi, 3), new ObjectIdentifier(wsi, 4), new ObjectIdentifier(wsi, 5)); for (WorkspaceObjectData wod: ws.getObjects(user, ois)) { wod.getDataAsTokens().destroy(); } assertThat("created no temp files on get", filesCreated[0], is(0)); JSONRPCLayerTester.assertNoTempFilesExist(ws.getTempFilesManager()); //multiple objects to file ws.setResourceConfig(build.withMaxIncomingDataMemoryUsage(38).build()); filesCreated[0] = 0; ws.saveObjects(user, wsi, objs, getIdFactory(user)); //two files per data - 1 for relabeling, 1 for sort assertThat("created temp files on save", filesCreated[0], is(4)); JSONRPCLayerTester.assertNoTempFilesExist(ws.getTempFilesManager()); filesCreated[0] = 0; ws.setResourceConfig(build.withMaxReturnedDataMemoryUsage(38).build()); for (WorkspaceObjectData wod: ws.getObjects(user, ois)) { wod.getDataAsTokens().destroy(); } assertThat("created 1 temp files on get", filesCreated[0], is(1)); JSONRPCLayerTester.assertNoTempFilesExist(ws.getTempFilesManager()); filesCreated[0] = 0; ws.setResourceConfig(build.withMaxReturnedDataMemoryUsage(25).build()); for (WorkspaceObjectData wod: ws.getObjects(user, ois)) { wod.getDataAsTokens().destroy(); } assertThat("created 2 temp files on get", filesCreated[0], is(2)); JSONRPCLayerTester.assertNoTempFilesExist(ws.getTempFilesManager()); ws.getTempFilesManager().removeListener(listener); ws.setResourceConfig(oldcfg); } @Test public void storedDataIsSorted() throws Exception { WorkspaceUser user = new WorkspaceUser("dataIsSorted"); WorkspaceIdentifier wsi = new WorkspaceIdentifier("dataissorted"); ws.createWorkspace(user, wsi.getIdentifierString(), false, null, null); Map<String, Object> data1 = new LinkedHashMap<String, Object>(); data1.put("z", 1); data1.put("y", 2); String expected = "{\"y\":2,\"z\":1}"; Provenance p = new Provenance(user); List<WorkspaceSaveObject> objs = new ArrayList<WorkspaceSaveObject>(); objs.add(new WorkspaceSaveObject(data1, SAFE_TYPE1, null, p, false)); ws.saveObjects(user, wsi, objs, getIdFactory(user)); WorkspaceObjectData o = ws.getObjects( user, Arrays.asList(new ObjectIdentifier(wsi, 1))).get(0); String data = IOUtils.toString(o.getDataAsTokens().getJSON()); assertThat("data is sorted", data, is(expected)); assertThat("data marked as sorted", o.getDataAsTokens().isSorted(), is(true)); } @Test public void exceedSortMemory() throws Exception { WorkspaceUser user = new WorkspaceUser("exceedSortMem"); WorkspaceIdentifier wsi = new WorkspaceIdentifier("exceedsortmem"); ws.createWorkspace(user, wsi.getIdentifierString(), false, null, null); Provenance p = new Provenance(user); List<WorkspaceSaveObject> objs = new ArrayList<WorkspaceSaveObject>(); String safejson = "{\"z\":\"a\"}"; String json = "{\"z\":\"a\",\"b\":\"d\"}"; objs.add(new WorkspaceSaveObject(new JsonTokenStream(safejson), SAFE_TYPE1, null, p, false)); objs.add(new WorkspaceSaveObject(new JsonTokenStream(json), SAFE_TYPE1, null, p, false)); ResourceUsageConfiguration oldcfg = ws.getResourceConfig(); ResourceUsageConfigurationBuilder build = new ResourceUsageConfigurationBuilder(oldcfg) .withMaxIncomingDataMemoryUsage(1); int maxmem = 8 + 64 + 8 + 64; ws.setResourceConfig(build.withMaxRelabelAndSortMemoryUsage(maxmem).build()); ws.saveObjects(user, wsi, objs, getIdFactory(user)); ws.setResourceConfig(build.withMaxRelabelAndSortMemoryUsage(maxmem - 1).build()); try { ws.saveObjects(user, wsi, objs, getIdFactory(user)); fail("sorted w/ too little mem"); } catch (TypedObjectValidationException tove) { assertThat("got correct exception", tove.getMessage(), is("Object #2: Memory necessary for sorting map keys exceeds the limit " + (maxmem - 1) + " bytes at /")); } ws.setResourceConfig(oldcfg); } }
923ebf06a649f172580f2526ffdc549886811f14
3,778
java
Java
src/MainInterface/AddEquationNodePopUpMenu.java
HamdaBinteAjmal/PROFET
41fdef44fecf8405fef99e66573b674214b21d90
[ "Apache-2.0" ]
3
2016-02-26T00:53:47.000Z
2019-12-05T10:58:37.000Z
src/MainInterface/AddEquationNodePopUpMenu.java
HamdaBinteAjmal/PROFET
41fdef44fecf8405fef99e66573b674214b21d90
[ "Apache-2.0" ]
3
2015-10-21T09:27:10.000Z
2015-12-14T22:31:56.000Z
src/MainInterface/AddEquationNodePopUpMenu.java
HamdaBinteAjmal/PROFET
41fdef44fecf8405fef99e66573b674214b21d90
[ "Apache-2.0" ]
null
null
null
33.140351
96
0.698253
1,000,893
/* * PROFET Copyright 2015 (c) Data Mining and Machine Learning Group, * National University of Ireland Galway. * This file is a part of PROFET * * 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 MainInterface; import EquationEditor.Tree.MathObject; import java.awt.Component; import java.awt.Container; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import MainInterface.Tree; import Nodes.EquationInfo; /** * * @author Administrator */ public class AddEquationNodePopUpMenu extends javax.swing.JPopupMenu implements ActionListener { /** * Creates new form AddEquationNodePopUpMenu */ private Tree.TreeStatic parent ; ActionListener menuListener; private final String ADD = "Add New Equation"; private final String DELETE = "Delete this Equation"; private final String EDIT = "Edit this Equation"; private EquationInfo eqObj = null; public AddEquationNodePopUpMenu(Tree.TreeStatic tree, EquationInfo EqObj) { super(); parent = tree; JMenuItem item1 = MakeMenuItem(ADD); add(item1); JMenuItem item2 = MakeMenuItem(DELETE); add(item2); JMenuItem item3 = MakeMenuItem(EDIT); add(item3); eqObj = EqObj; } private JMenuItem MakeMenuItem(String label){ JMenuItem item = new JMenuItem(label); item.setActionCommand(label); item.addActionListener(this); return item; } public void actionPerformed(ActionEvent e) { String choice = e.getActionCommand(); if (choice.equals(ADD)) parent.AddNewEquation(); else if (choice.equals(DELETE)) parent.DeleteExistingEquation(eqObj); else if (choice.equals(EDIT)) parent.EditExistingEquation(eqObj); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 400, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 300, Short.MAX_VALUE) ); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables // End of variables declaration//GEN-END:variables class MousePopupListener extends MouseAdapter { public void mouseClicked(MouseEvent e) { JOptionPane.showMessageDialog(null, "PHELLO"); } public void mousePressed(MouseEvent e) { JOptionPane.showMessageDialog(null, "PHeeELLO"); } } }
923ec096059afbfd92a78b65315cd34596498b8e
358
java
Java
nabox-model/src/main/java/io/nabox/entity/form/QueryAddressAssetForm.java
naboxwallet/nabox
1a462301092f90613e9a661d215598c55bbe3eed
[ "Apache-2.0" ]
12
2021-08-10T17:13:50.000Z
2022-03-30T09:27:16.000Z
nabox-model/src/main/java/io/nabox/entity/form/QueryAddressAssetForm.java
naboxwallet/nabox
1a462301092f90613e9a661d215598c55bbe3eed
[ "Apache-2.0" ]
null
null
null
nabox-model/src/main/java/io/nabox/entity/form/QueryAddressAssetForm.java
naboxwallet/nabox
1a462301092f90613e9a661d215598c55bbe3eed
[ "Apache-2.0" ]
null
null
null
15.565217
54
0.740223
1,000,894
package io.nabox.entity.form; import io.nabox.entity.order.BaseModel; import lombok.Data; @Data public class QueryAddressAssetForm extends BaseModel { private String chain; private String address; private String symbol; private String contractAddress; private int chainId; private int assetId; private boolean refresh; }
923ec0cfe11b5d73edcd71b37d19c876d1559ca3
284
java
Java
src/main/java/com/edaoe/module/index/IndexController.java
CatchLife/banmutang-theme-dev-tools
681673f3ec72b3d4ca369cfbeb8fd30e835f44b5
[ "MIT" ]
null
null
null
src/main/java/com/edaoe/module/index/IndexController.java
CatchLife/banmutang-theme-dev-tools
681673f3ec72b3d4ca369cfbeb8fd30e835f44b5
[ "MIT" ]
null
null
null
src/main/java/com/edaoe/module/index/IndexController.java
CatchLife/banmutang-theme-dev-tools
681673f3ec72b3d4ca369cfbeb8fd30e835f44b5
[ "MIT" ]
null
null
null
17.75
49
0.704225
1,000,895
package com.edaoe.module.index; import com.jfinal.core.Controller; import com.jfinal.kit.PropKit; /** * @author Catch * @date 2018-09-11 下午12:38 * @description */ public class IndexController extends Controller { public void index(){ redirect("/"+ PropKit.get("host")); } }
923ec0ea62d840f88fa5cc7b74414997dd3fad2f
8,638
java
Java
practice-data-structure/src/main/java/io/github/deepshiv126/practice/linear/data/structure/list/linkedlist/DoublyLinkedList.java
deepshiv126/my-practice-code
b138ef4458b3a2a07abe73532e4e6a10b2e5a753
[ "MIT" ]
null
null
null
practice-data-structure/src/main/java/io/github/deepshiv126/practice/linear/data/structure/list/linkedlist/DoublyLinkedList.java
deepshiv126/my-practice-code
b138ef4458b3a2a07abe73532e4e6a10b2e5a753
[ "MIT" ]
1
2021-08-14T04:03:47.000Z
2021-08-14T04:03:47.000Z
practice-data-structure/src/main/java/io/github/deepshiv126/practice/linear/data/structure/list/linkedlist/DoublyLinkedList.java
deepshiv126/my-practice-code
b138ef4458b3a2a07abe73532e4e6a10b2e5a753
[ "MIT" ]
null
null
null
24.750716
89
0.5301
1,000,896
package io.github.deepshiv126.practice.linear.data.structure.list.linkedlist; import java.util.NoSuchElementException; /** * Doubly Linked List is a linear data structure used for storing collections of nodes. * - It contains sequence of node * - A node has data and reference to previous and next node in a list. * - First node is the head node and its previous is always null. * - Last node has data and points to null. * <p> * Benefits over Singly Linked List * - A node - can navigate forward and backward ( this helps a lot in delete node, * as we dont need any previous pointer like we had in Singly Linked List.) * - Add and Remove last element will be O(1) Time Complexity. */ public class DoublyLinkedList<E> implements List<E> { // Doubly link list also maintains both head and tail. private Node<E> head; private Node<E> tail; private int currentSize; // constructor creating head and tail public DoublyLinkedList() { this.head = null; this.tail = null; this.currentSize = 0; } /** * Returns the number of elements count in the list. * <p> * Time Complexity - O(1) * * @return size of the list. */ @Override public int size() { return currentSize; } /** * Returns whether this list is empty or not. * <p> * Time Complexity is O(1) * * @return true/false. */ @Override public boolean isEmpty() { return this.head == null && this.tail == null; } /** * Add given element at the beginning of the list. * <p> * Time Complexity is O(1) * * @param element * @return true if added, false if not added. */ @Override public boolean addFirst(final E element) { Node<E> newNode = new Node<>(element); // if list is empty if (this.isEmpty()) { this.head = this.tail = newNode; currentSize++; return true; } this.head.previous = newNode; // this is only change from sll newNode.next = this.head; this.head = newNode; currentSize++; return true; } /** * Add given element at the end of the list. * <p> * Time Complexity is O(1) * * @param element * @return */ @Override public boolean addLast(final E element) { Node<E> newNode = new Node<>(element); //if list is empty if (this.isEmpty()) { this.head = this.tail = newNode; currentSize++; return true; } this.tail.next = newNode; newNode.previous = this.tail; this.tail = newNode; currentSize++; return true; } /** * Add given element at the end of the list. * This method applicable only to SinglyLinkedList * * @param element * @return */ @Override public boolean addLastWithTail(final E element) { return false; } /** * Add given element at given position. * * @param element * @param position * @return */ @Override public boolean addAtPosition(E element, int position) { return false; } /** * Remove first element in the list. * <p> * Time Complexity is O(1) * * @return */ @Override public E removeFirst() { // if list is empty if (this.head == null && this.tail == null) { throw new NoSuchElementException(); } Node<E> tmpNode = this.head; //if list has one element if (this.head == this.tail) { this.head = this.tail = null; currentSize--; return tmpNode.element; } // if list has more than one elements. this.head.next.previous = null; this.head = this.head.next; // tmpNode never gets GC if next is not null. tmpNode.next = null; currentSize--; return tmpNode.element; } /** * Remove last element in the list. * <p> * Time Complexity is O(1) * * @return */ @Override public E removeLast() { // if list is empty if (this.head == null && this.tail == null) { throw new NoSuchElementException(); } Node<E> tmpNode = this.tail; // if list has one element if (this.head == this.tail) { this.head = this.tail = null; currentSize--; return tmpNode.element; } // if list has more than one element this.tail.previous.next = null; this.tail = this.tail.previous; tmpNode.previous = null; // need to lose reference, other wise node never get GC. currentSize--; return tmpNode.element; } /** * Remove element at position. * * @param position * @return */ @Override public E removeAtPosition(int position) { return null; } /** * Remove given element in the list. * <p> * Time Complexity is O(n) * * @param element * @return */ @Override public E remove(final E element) { // if list is empty if (this.head == null && this.tail == null) { throw new NoSuchElementException(); } // if list has single element if (this.head == this.tail) { if (this.head.element == element) { Node<E> tmpNode = this.head; this.head = this.tail = null; return tmpNode.element; } return null; } // if list has more than one element Node<E> tmpNode = this.head; while (tmpNode != null) { if (tmpNode.element == element) { tmpNode.previous.next = tmpNode.next; tmpNode.next.previous = tmpNode.previous; return tmpNode.element; } tmpNode = tmpNode.next; } return null; } /** * Find whether given element contains in the list. * * @param element * @return */ @Override public boolean contains(final E element) { //if list is empty if (this.head == null && this.tail == null) { throw new NoSuchElementException(); } //if list is single element if (this.head == this.tail) { if (this.head.element == element) return true; return false; } // if list has more than one element Node<E> tmpNode = this.head; while (tmpNode != null) { if (tmpNode.element == element) { return true; } tmpNode = tmpNode.next; } return false; } /** * Get the first element in the list. * * @return */ @Override public E peekFirst() { if (this.head == null && this.tail == null) throw new NoSuchElementException(); return this.head.element; } /** * Get the last element in the list. * * @return */ @Override public E peekLast() { if (this.head == null && this.tail == null) throw new NoSuchElementException(); return this.tail.element; } /** * Get the last element in the list. * This method applicable only to SinglyLinkedList * * @return */ @Override public E peekLastWithTail() { return null; } /** * Only for Visual Understanding */ public void printAllElementsInList() { Node<E> tmpNode; // printing forward direction. //System.out.print("Forward :: "); tmpNode = this.head; while (tmpNode != null) { //System.out.print(tmpNode.element + " --> "); tmpNode = tmpNode.next; } //System.out.println("null"); // printing reverse direction. //System.out.print("Backward :: "); tmpNode = this.tail; while (tmpNode != null) { // System.out.print(tmpNode.element + " --> "); tmpNode = tmpNode.previous; } //System.out.println("null"); } /** * Definition of Doubly Linked List Node. */ private static class Node<E> { E element; Node<E> previous; Node<E> next; public Node(final E element) { this.element = element; this.previous = null; this.next = null; } } }
923ec1f83f130831c0df3a631ad86d678862903a
1,542
java
Java
src/main/java/com/google/devtools/build/lib/concurrent/ErrorHandler.java
chadm-sq/bazel
715c9faabba573501c9cb7604192759950633205
[ "Apache-2.0" ]
16,989
2015-09-01T19:57:15.000Z
2022-03-31T23:54:00.000Z
src/main/java/com/google/devtools/build/lib/concurrent/ErrorHandler.java
chadm-sq/bazel
715c9faabba573501c9cb7604192759950633205
[ "Apache-2.0" ]
12,562
2015-09-01T09:06:01.000Z
2022-03-31T22:26:20.000Z
src/main/java/com/google/devtools/build/lib/concurrent/ErrorHandler.java
chadm-sq/bazel
715c9faabba573501c9cb7604192759950633205
[ "Apache-2.0" ]
3,707
2015-09-02T19:20:01.000Z
2022-03-31T17:06:14.000Z
35.860465
97
0.742542
1,000,897
// Copyright 2016 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.concurrent; import com.google.devtools.build.lib.concurrent.ErrorClassifier.ErrorClassification; /** A way to inject custom handling of errors encountered by {@link AbstractQueueVisitor}. */ public interface ErrorHandler { /** * Called by {@link AbstractQueueVisitor} right after using {@link ErrorClassifier} to classify * the error, but right before actually acting on the classification. * * <p>Note that {@link Error}s are always classified as * {@link ErrorClassification#CRITICAL_AND_LOG}. */ void handle(Throwable t, ErrorClassification classification); /** An {@link ErrorHandler} that does nothing. */ class NullHandler implements ErrorHandler { public static final NullHandler INSTANCE = new NullHandler(); private NullHandler() { } @Override public void handle(Throwable t, ErrorClassification classification) { } } }
923ec2164934165dc4d0a92a0eef4a584b1a4cd2
907
java
Java
src/main/java/hudson/plugins/bandit/BanditProjectAction.java
deejay-sl/bandit-plugin-
1c9dbb5e61ca6d65a786a429796462bf9759e07e
[ "MIT" ]
3
2016-10-26T14:03:28.000Z
2019-08-17T19:17:21.000Z
src/main/java/hudson/plugins/bandit/BanditProjectAction.java
deejay-sl/bandit-plugin-
1c9dbb5e61ca6d65a786a429796462bf9759e07e
[ "MIT" ]
1
2018-10-05T16:40:06.000Z
2018-10-05T16:40:06.000Z
src/main/java/hudson/plugins/bandit/BanditProjectAction.java
deejay-sl/bandit-plugin-
1c9dbb5e61ca6d65a786a429796462bf9759e07e
[ "MIT" ]
2
2016-10-26T14:15:39.000Z
2018-03-20T19:49:06.000Z
28.34375
85
0.661521
1,000,898
package hudson.plugins.bandit; import hudson.model.AbstractProject; import hudson.plugins.analysis.core.AbstractProjectAction; public class BanditProjectAction extends AbstractProjectAction<BanditResultAction> { /** Unique identifier of this class. */ private static final long serialVersionUID = 1002L; /** * Instantiates a new find bugs project action. * * @param project * the project that owns this action */ public BanditProjectAction(final AbstractProject<?, ?> project) { super(project, BanditResultAction.class, BanditPublisher.BANDIT_DESCRIPTOR); } /** {@inheritDoc} */ public String getDisplayName() { return Messages.Bandit_ProjectAction_Name(); } /** {@inheritDoc} */ @Override public String getTrendName() { return Messages.Bandit_Trend_Name(); } }
923ec219c8ffa0ac193b0174e64bc0210690a2bf
4,172
java
Java
src/main/java/de/picturesafe/search/parameter/InnerHitsOption.java
all-things-search/abstract-search
c8de8d812f4f164093977aa7d6eab240f367b2b0
[ "Apache-2.0" ]
27
2020-05-04T14:16:24.000Z
2022-03-24T03:50:58.000Z
src/main/java/de/picturesafe/search/parameter/InnerHitsOption.java
all-things-search/abstract-search
c8de8d812f4f164093977aa7d6eab240f367b2b0
[ "Apache-2.0" ]
5
2020-04-16T13:50:17.000Z
2022-01-04T16:38:31.000Z
src/main/java/de/picturesafe/search/parameter/InnerHitsOption.java
all-things-search/abstract-search
c8de8d812f4f164093977aa7d6eab240f367b2b0
[ "Apache-2.0" ]
6
2020-07-27T16:32:19.000Z
2020-10-29T14:18:58.000Z
25.595092
76
0.619128
1,000,899
/* * Copyright 2020 picturesafe media/data/bank GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.picturesafe.search.parameter; import de.picturesafe.search.util.logging.CustomJsonToStringStyle; import org.apache.commons.lang3.builder.ToStringBuilder; import java.util.Arrays; import java.util.List; /** * Search result inner hits option */ public class InnerHitsOption { public static final int DEFAULT_SIZE = 5; private final String name; private int size = DEFAULT_SIZE; private List<SortOption> sortOptions; private CollapseOption collapseOption; private int from; private InnerHitsOption(String name) { this.name = name; } /** * Creates an inner hits option with the given name. * * @param name Name of the inner hits * @return Inner hits option */ public static InnerHitsOption name(String name) { return new InnerHitsOption(name); } /** * Gets the name of the inner hits. * * @return Name of the inner hits */ public String getName() { return name; } /** * Sets the size of the inner hits. * * @param size Size of the inner hits * @return Inner hits option */ public InnerHitsOption size(int size) { this.size = size; return this; } /** * Gets the size of the inner hits. * * @return Size of the inner hits */ public int getSize() { return size; } /** * Sets sort options for the inner hits. * * @param sortOptions Sort options for the inner hits. * @return Inner hits option */ public InnerHitsOption sortOptions(List<SortOption> sortOptions) { this.sortOptions = sortOptions; return this; } /** * Sets sort options for the inner hits. * * @param sortOptions Sort options for the inner hits. * @return Inner hits option */ public InnerHitsOption sortOptions(SortOption... sortOptions) { return sortOptions(Arrays.asList(sortOptions)); } /** * Gets sort options for the inner hits. * * @return Sort options for the inner hits */ public List<SortOption> getSortOptions() { return sortOptions; } /** * Sets collapse options for the inner hits. * * @param collapseOption Collapse options for the inner hits * @return Inner hits option */ public InnerHitsOption collapseOption(CollapseOption collapseOption) { this.collapseOption = collapseOption; return this; } /** * Gets collapse options for the inner hits. * * @return Collapse options for the inner hits */ public CollapseOption getCollapseOption() { return collapseOption; } /** * Sets the offset of the first hit to fetch. * * @param from Offset of the first hit to fetch * @return Inner hits option */ public InnerHitsOption from(int from) { this.from = from; return this; } /** * Gets the offset of the first hit to fetch: * * @return Offset of the first hit to fetch */ public int getFrom() { return from; } @Override public String toString() { return new ToStringBuilder(this, new CustomJsonToStringStyle()) //-- .append("name", name) //-- .append("size", size) //-- .append("sortOptions", sortOptions) //-- .append("collapseOption", collapseOption) //-- .append("from", from) //-- .toString(); } }
923ec560100162a0ecf024e394a15af35f6615e5
1,399
java
Java
webone/src/com/learn/utils/PageBean.java
xiaohua9/java_web
b43179639b22fcd56f62cc74510551ba74547890
[ "Apache-2.0" ]
null
null
null
webone/src/com/learn/utils/PageBean.java
xiaohua9/java_web
b43179639b22fcd56f62cc74510551ba74547890
[ "Apache-2.0" ]
null
null
null
webone/src/com/learn/utils/PageBean.java
xiaohua9/java_web
b43179639b22fcd56f62cc74510551ba74547890
[ "Apache-2.0" ]
null
null
null
21.523077
61
0.593996
1,000,900
package com.learn.utils; import java.util.List; //用于分页显示的页面数据类 public class PageBean { //属性:每页显示的数量,总页数,当前页数,数据库的总数据量,当前页的数据 private int pageSize=3; private int totalPages; private int currentPage=1; private int rows; private List user; public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getTotalPages() { return totalPages; } public void setTotalPages(int totalPages) { this.totalPages = totalPages; } public int getCurrentPage() { return currentPage; } //////对当前页数进行限制 public void setCurrentPage(int currentPage) { if (currentPage<1){ this.currentPage=1; }else if (currentPage>this.getTotalPages()){ this.currentPage=this.getTotalPages(); }else { this.currentPage = currentPage; } } public int getRows() { return rows; } public void setRows(int rows) {//当赋值总行数时,总页数即可根据下方的方式计算得到 this.rows = rows; if (this.rows%this.pageSize==0){ this.totalPages=this.rows/this.pageSize; }else { this.totalPages=this.rows/this.pageSize+1; } } public List getUser() { return user; } public void setUser(List user) { this.user = user; } }
923ec5a4c98ed5f413119ab21f4cb2822521d9ac
245
java
Java
protocol/src/main/java/pl/grzeslowski/jsupla/protocol/api/encoders/cs/SuplaChannelNewValueEncoder.java
magx2/jSupla
106b5b83f25574d0a45f4eade84e41069eb64745
[ "MIT" ]
1
2019-03-12T09:40:21.000Z
2019-03-12T09:40:21.000Z
protocol/src/main/java/pl/grzeslowski/jsupla/protocol/api/encoders/cs/SuplaChannelNewValueEncoder.java
magx2/jSupla
106b5b83f25574d0a45f4eade84e41069eb64745
[ "MIT" ]
10
2019-02-18T17:37:47.000Z
2019-03-21T20:26:33.000Z
protocol/src/main/java/pl/grzeslowski/jsupla/protocol/api/encoders/cs/SuplaChannelNewValueEncoder.java
magx2/jSupla
106b5b83f25574d0a45f4eade84e41069eb64745
[ "MIT" ]
null
null
null
27.222222
96
0.857143
1,000,901
package pl.grzeslowski.jsupla.protocol.api.encoders.cs; import pl.grzeslowski.jsupla.protocol.api.structs.cs.SuplaChannelNewValue; @Deprecated public interface SuplaChannelNewValueEncoder extends ClientServerEncoder<SuplaChannelNewValue> { }
923ec63682d5bab5a7581f02cdca0603eef38cc6
5,384
java
Java
nullaway/src/test/java/com/uber/nullaway/tools/SerializationTestHelper.java
truthiswill/NullAway
0f25545efc44e89b6e74b1151e1c97c1b8adf582
[ "MIT" ]
null
null
null
nullaway/src/test/java/com/uber/nullaway/tools/SerializationTestHelper.java
truthiswill/NullAway
0f25545efc44e89b6e74b1151e1c97c1b8adf582
[ "MIT" ]
null
null
null
nullaway/src/test/java/com/uber/nullaway/tools/SerializationTestHelper.java
truthiswill/NullAway
0f25545efc44e89b6e74b1151e1c97c1b8adf582
[ "MIT" ]
null
null
null
33.440994
96
0.68555
1,000,902
/* * Copyright (c) 2022 Uber Technologies, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.uber.nullaway.tools; import static org.junit.Assert.fail; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.errorprone.CompilationTestHelper; import com.uber.nullaway.NullAway; import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class SerializationTestHelper<T extends Display> { private final Path outputDir; private ImmutableList<T> expectedOutputs; private CompilationTestHelper compilationTestHelper; private DisplayFactory<T> factory; private String fileName; private String header; public SerializationTestHelper(Path outputDir) { this.outputDir = outputDir; } @SuppressWarnings("ResultOfMethodCallIgnored") public SerializationTestHelper<T> addSourceLines(String path, String... lines) { compilationTestHelper.addSourceLines(path, lines); return this; } @SafeVarargs public final SerializationTestHelper<T> setExpectedOutputs(T... outputs) { this.expectedOutputs = ImmutableList.copyOf(outputs); return this; } public SerializationTestHelper<T> expectNoOutput() { this.expectedOutputs = ImmutableList.of(); return this; } public SerializationTestHelper<T> setArgs(List<String> args) { compilationTestHelper = CompilationTestHelper.newInstance(NullAway.class, getClass()).setArgs(args); return this; } public SerializationTestHelper<T> setFactory(DisplayFactory<T> factory) { this.factory = factory; return this; } public SerializationTestHelper<T> setOutputFileNameAndHeader(String fileName, String header) { this.fileName = fileName; this.header = header; return this; } public void doTest() { Preconditions.checkNotNull(factory, "Factory cannot be null"); Preconditions.checkNotNull(fileName, "File name cannot be null"); Path outputPath = outputDir.resolve(fileName); try { Files.deleteIfExists(outputPath); } catch (IOException ignored) { throw new RuntimeException("Failed to delete older file at: " + outputPath); } compilationTestHelper.doTest(); List<T> actualOutputs = readActualOutputs(outputPath); compare(actualOutputs); } private void compare(List<T> actualOutput) { List<T> notFound = new ArrayList<>(); for (T o : expectedOutputs) { if (!actualOutput.contains(o)) { notFound.add(o); } else { actualOutput.remove(o); } } if (notFound.size() == 0 && actualOutput.size() == 0) { return; } StringBuilder errorMessage = new StringBuilder(); if (notFound.size() != 0) { errorMessage .append(notFound.size()) .append(" expected outputs were NOT found:") .append("\n") .append(notFound.stream().map(T::toString).collect(Collectors.toList())) .append("\n"); } if (actualOutput.size() != 0) { errorMessage .append(actualOutput.size()) .append(" unexpected outputs were found:") .append("\n") .append(actualOutput.stream().map(T::toString).collect(Collectors.toList())) .append("\n"); } fail(errorMessage.toString()); } private List<T> readActualOutputs(Path outputPath) { List<T> outputs = new ArrayList<>(); BufferedReader reader; try { reader = Files.newBufferedReader(outputPath, Charset.defaultCharset()); String actualHeader = reader.readLine(); if (!header.equals(actualHeader)) { fail( "Expected header of " + outputPath.getFileName() + " to be: " + header + "\nBut found: " + actualHeader); } String line = reader.readLine(); while (line != null) { T output = factory.fromValuesInString(line.split("\\t")); outputs.add(output); line = reader.readLine(); } reader.close(); } catch (IOException e) { throw new RuntimeException("Error happened in reading the outputs.", e); } return outputs; } }
923ec76aeca6eba7c620a10d056baecf7c6eb656
254
java
Java
seata-storage/src/main/java/com/moxuanran/learning/mapper/StorageMapper.java
f2130793/SpringCloudLearning
9555d38e38c4eb43aafcda94b2b8f70a1b9ac680
[ "MIT" ]
3
2020-07-22T02:32:18.000Z
2020-07-22T02:40:59.000Z
seata-storage/src/main/java/com/moxuanran/learning/mapper/StorageMapper.java
f2130793/SpringCloudLearning
9555d38e38c4eb43aafcda94b2b8f70a1b9ac680
[ "MIT" ]
1
2022-01-21T23:47:49.000Z
2022-01-21T23:47:49.000Z
seata-storage/src/main/java/com/moxuanran/learning/mapper/StorageMapper.java
f2130793/SpringCloudLearning
9555d38e38c4eb43aafcda94b2b8f70a1b9ac680
[ "MIT" ]
2
2020-07-23T01:17:30.000Z
2021-09-26T01:44:08.000Z
21.166667
60
0.771654
1,000,903
package com.moxuanran.learning.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.moxuanran.learning.entity.Storage; /** * @author 莫轩然 * @date 2020/7/21 15:07 */ public interface StorageMapper extends BaseMapper<Storage> { }
923ec7a0056881be5ef721a12ac3376b29c36aa1
1,152
java
Java
src/main/java/org/monarchinitiative/pubman/item/ItemQC.java
monarch-initiative/pubman
5fc87db6a160c65bdac5cb5b3677b777be5d929c
[ "MIT" ]
null
null
null
src/main/java/org/monarchinitiative/pubman/item/ItemQC.java
monarch-initiative/pubman
5fc87db6a160c65bdac5cb5b3677b777be5d929c
[ "MIT" ]
6
2019-02-18T23:38:40.000Z
2019-04-08T12:50:06.000Z
src/main/java/org/monarchinitiative/pubman/item/ItemQC.java
monarch-initiative/pubman
5fc87db6a160c65bdac5cb5b3677b777be5d929c
[ "MIT" ]
null
null
null
27.428571
87
0.639757
1,000,904
package org.monarchinitiative.pubman.item; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * Convenience class to check that the fields of an {@link Item} make sense */ public class ItemQC { private final Date oldestAllowableDate; private final Date today; private final SimpleDateFormat formatter = new SimpleDateFormat("dd/mm/yyyy"); public ItemQC() throws ParseException { oldestAllowableDate = formatter.parse("01/01/2008"); Calendar cal = Calendar.getInstance(); today = cal.getTime(); } public boolean check(Item item) { String year = item.getEntry().getYear(); String fakestr = String.format("01/01/%s",year); try { Date fakedate = formatter.parse(fakestr); if (fakedate.after(today) || fakedate.before(oldestAllowableDate)) { return false; // Date outside allowable range -- probably a parse error } } catch(ParseException e) { e.printStackTrace(); return false; } return true; } }
923ec7d42cd7245327cd4b8116755f324d37230f
2,675
java
Java
patchmanager/src/com/ruinwesen/patchmanager/client/index/ScoredPatch.java
anupam19/mididuino
27c30f586a8d61381309434ed05b4958c7727402
[ "BSD-3-Clause" ]
null
null
null
patchmanager/src/com/ruinwesen/patchmanager/client/index/ScoredPatch.java
anupam19/mididuino
27c30f586a8d61381309434ed05b4958c7727402
[ "BSD-3-Clause" ]
null
null
null
patchmanager/src/com/ruinwesen/patchmanager/client/index/ScoredPatch.java
anupam19/mididuino
27c30f586a8d61381309434ed05b4958c7727402
[ "BSD-3-Clause" ]
null
null
null
34.294872
80
0.72486
1,000,905
/** * Copyright (c) 2009, Christian Schneider * 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 names of the authors 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.ruinwesen.patchmanager.client.index; import java.io.File; import com.ruinwesen.patch.PatchDataException; import com.ruinwesen.patch.directory.Directory; import com.ruinwesen.patch.metadata.PatchMetadata; public class ScoredPatch implements IndexedPatch { private IndexedPatch delegate; private float score; public ScoredPatch(IndexedPatch delegate, float score) { this.delegate = delegate; this.score = score; } public float score() { return score; } public PatchMetadata getMetadata() { return delegate.getMetadata(); } public Directory openDirectory() throws PatchDataException { return delegate.openDirectory(); } public String internalId() { return delegate.internalId(); } @Override public int hashCode() { return delegate.hashCode(); } @Override public boolean equals(Object o) { return IndexedPatchRecord.compareEquals(this, o); } public File getLocalFile() { return delegate.getLocalFile(); } }
923ec8ec78208565b81959d313d91a4974d98cdf
840
java
Java
src/test/java/cn/xpbootcamp/gilded_rose/SulfurasTest.java
xuziping/tdd-gilded-rose
2061f16358b244699296f9208190360f730a8d12
[ "Apache-2.0" ]
null
null
null
src/test/java/cn/xpbootcamp/gilded_rose/SulfurasTest.java
xuziping/tdd-gilded-rose
2061f16358b244699296f9208190360f730a8d12
[ "Apache-2.0" ]
null
null
null
src/test/java/cn/xpbootcamp/gilded_rose/SulfurasTest.java
xuziping/tdd-gilded-rose
2061f16358b244699296f9208190360f730a8d12
[ "Apache-2.0" ]
null
null
null
33.6
88
0.685714
1,000,906
package cn.xpbootcamp.gilded_rose; import cn.xpbootcamp.gilded_rose.domain.entity.Goods; import cn.xpbootcamp.gilded_rose.domain.entity.SulfurasGoods; import com.spun.util.Asserts; import org.junit.jupiter.api.Test; public class SulfurasTest { private static final Integer OVER_SELLIN_DAYS = 50; @Test public void quality_should_no_change() { Goods goods = new SulfurasGoods(); int dayIndex = 1; int previousQuality = goods.calQuality(dayIndex); for (dayIndex++; dayIndex < goods.getSellIn() + OVER_SELLIN_DAYS; dayIndex++) { int currentQuality = goods.calQuality(dayIndex); Asserts.assertTrue(String.format("%s after %d ", goods.getName(), dayIndex), currentQuality == previousQuality); previousQuality = currentQuality; } } }
923eca261087e0c3565da0928c81bfa23def2ed1
6,328
java
Java
app/src/main/java/com/example/athenaeum/SignupActivity.java
CMPUT301F20T31/Athenaeum
ed4ff5c2f44a33361e47ef5e3a4dc47cce70fb72
[ "Apache-2.0" ]
1
2020-11-01T04:11:44.000Z
2020-11-01T04:11:44.000Z
app/src/main/java/com/example/athenaeum/SignupActivity.java
CMPUT301F20T31/Athenaeum
ed4ff5c2f44a33361e47ef5e3a4dc47cce70fb72
[ "Apache-2.0" ]
32
2020-11-03T03:09:10.000Z
2020-11-30T18:01:11.000Z
app/src/main/java/com/example/athenaeum/SignupActivity.java
CMPUT301F20T31/Athenaeum
ed4ff5c2f44a33361e47ef5e3a4dc47cce70fb72
[ "Apache-2.0" ]
2
2020-09-30T03:16:39.000Z
2022-03-10T19:46:44.000Z
43.342466
131
0.561315
1,000,907
/* * SignupActivity * * November 30 2020 * * Copyright 2020 Natalie Iwaniuk, Harpreet Saini, Jack Gray, Jorge Marquez Peralta, Ramana Vasanthan, Sree Nidhi Thanneeru * * 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. * * Referenced for User Authentication * https://firebase.google.com/docs/auth * by Google Developers * Published November 17, 2020 * Licensed under the Apache 2.0 license. */ package com.example.athenaeum; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.google.android.gms.tasks.OnCompleteListener; import android.widget.Toast; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; /** * This Activity allows users to sign up for a new account. * It implements client-side validation for the form, and implements server-side validation of the username being unique. */ public class SignupActivity extends AppCompatActivity { private UserDB userDB; private EditText pass; private EditText email; private EditText username; private UserAuth auth; private EditText passConfirm; private Boolean verify; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_signup); userDB = new UserDB(); auth = new UserAuth(); pass = findViewById(R.id.signupPassword); email = findViewById(R.id.signupEmail); username = findViewById(R.id.signupUsername); passConfirm = findViewById(R.id.signupPasswordConfirm); // Initialize listener for signup button final Button signupButton = findViewById(R.id.buttonSignup); signupButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Check that all the data is valid on the client side. // Retrieve the username text and make sure that something was entered String usernameText = username.getText().toString(); if (usernameText.length() == 0) { username.setError("You must enter a username."); return; } // Retrieve the email text and make sure that something was entered // that has at least an @ symbol and a . symbol. String emailText = email.getText().toString(); if (emailText.length() == 0 || emailText.indexOf('@') == -1 || emailText.indexOf('.') == -1) { email.setError("You must enter a valid email."); return; } // Retrieve the password texts and make sure that something was entered. // Also check and make sure that the passwords match. String passwordText = pass.getText().toString(); String passwordConfirmText = passConfirm.getText().toString(); if (passwordText.length() == 0 || passwordConfirmText.length() == 0 || !passwordText.equals(passwordConfirmText)) { passConfirm.setError("Your passwords must match."); return; } else if (passwordText.length() < 6) { passConfirm.setError("Your password must be at least 6 characters long."); return; } if (userDB.doesUsernameExist(usernameText)) { username.setError("That username is already in use."); return; } verify = true; // Initialize the authorization of a new user. if (verify) { final AthenaeumProfile profile = new AthenaeumProfile(usernameText, passwordText, emailText); Task<AuthResult> authentication = auth.addUser(profile); authentication .addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // If authorizing the new user was successful, add the user to the database, // then clear the signup activity and navigate to the home screen. User user = new User(profile); userDB.addUser(user, task.getResult().getUser().getUid()); Log.d("tag", "successfully added account"); username.setText(""); email.setText(""); pass.setText(""); passConfirm.setText(""); Intent intent = new Intent(SignupActivity.this, LoginActivity.class); startActivity(intent); } else { // Otherwise, display an error. Toast.makeText(SignupActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); Log.d("Fail", task.getException().toString()); } } }); } } }); } }
923eca9a1657212321c689a91ae03a37c57a25e9
2,820
java
Java
client/shared/src/main/java/com/threerings/bang/admin/client/AsStringFieldEditor.java
mimeyy/dylansbang
b3e913eb7fe3702cd97e93edde8c8b700e7d9fdf
[ "BSD-2-Clause" ]
17
2016-03-23T15:34:18.000Z
2021-12-15T21:24:45.000Z
client/shared/src/main/java/com/threerings/bang/admin/client/AsStringFieldEditor.java
mimeyy/dylansbang
b3e913eb7fe3702cd97e93edde8c8b700e7d9fdf
[ "BSD-2-Clause" ]
3
2016-12-15T07:22:06.000Z
2019-01-23T11:41:04.000Z
client/shared/src/main/java/com/threerings/bang/admin/client/AsStringFieldEditor.java
mimeyy/dylansbang
b3e913eb7fe3702cd97e93edde8c8b700e7d9fdf
[ "BSD-2-Clause" ]
15
2016-11-01T22:14:38.000Z
2021-07-31T10:04:32.000Z
32.045455
78
0.628369
1,000,908
// // $Id$ package com.threerings.bang.admin.client; import java.lang.reflect.Field; import com.jmex.bui.BTextField; import com.samskivert.util.StringUtil; import com.threerings.bang.admin.data.ConfigObject; import static com.threerings.bang.Log.log; /** * Allows for the editing of arbitrary config object fields by converting them * to and from strings. */ public class AsStringFieldEditor extends FieldEditor { public AsStringFieldEditor (Field field, ConfigObject confobj) { super(field, confobj); add(_value = new BTextField()); _value.addListener(this); } @Override // documentation inherited protected Object getDisplayValue () throws Exception { String text = _value.getText(); if (_field.getType().equals(Integer.class) || _field.getType().equals(Integer.TYPE)) { return new Integer(text); } else if (_field.getType().equals(Long.class) || _field.getType().equals(Long.TYPE)) { return new Long(text); } else if (_field.getType().equals(Float.class) || _field.getType().equals(Float.TYPE)) { return new Float(text); } else if (_field.getType().equals(Double.class) || _field.getType().equals(Double.TYPE)) { return new Double(text); } else if (_field.getType().equals(String.class)) { return text; } else if (_field.getType().equals(STRING_ARRAY_PROTO.getClass())) { return StringUtil.parseStringArray(_value.getText()); } else if (_field.getType().equals(INT_ARRAY_PROTO.getClass())) { return StringUtil.parseIntArray(_value.getText()); } else if (_field.getType().equals(FLOAT_ARRAY_PROTO.getClass())) { return StringUtil.parseFloatArray(_value.getText()); } else if (_field.getType().equals(LONG_ARRAY_PROTO.getClass())) { return StringUtil.parseLongArray(_value.getText()); } else if (_field.getType().equals(Boolean.TYPE)) { return Boolean.valueOf(_value.getText().equalsIgnoreCase("true")); } else { log.warning("Unknown field type '" + _field.getName() + "': " + _field.getType().getName() + "."); return null; } } @Override // documentation inherited protected void displayValue (Object value) { _value.setText(StringUtil.toString(value, "", "")); } protected BTextField _value; protected static final String[] STRING_ARRAY_PROTO = new String[0]; protected static final int[] INT_ARRAY_PROTO = new int[0]; protected static final float[] FLOAT_ARRAY_PROTO = new float[0]; protected static final long[] LONG_ARRAY_PROTO = new long[0]; }
923ecaee5e8bccc0995d1c6a1d1998077c2fb279
1,292
java
Java
src/JavaInterface.java
upadrastaharshavardhan/0569-hackerrank-java
dc933417589dd7f4290f2399491b453b954953a6
[ "MIT" ]
5
2020-05-14T14:52:40.000Z
2021-11-28T15:44:34.000Z
src/JavaInterface.java
upadrastaharshavardhan/0569-hackerrank-java
dc933417589dd7f4290f2399491b453b954953a6
[ "MIT" ]
null
null
null
src/JavaInterface.java
upadrastaharshavardhan/0569-hackerrank-java
dc933417589dd7f4290f2399491b453b954953a6
[ "MIT" ]
2
2020-07-28T20:55:26.000Z
2020-11-01T00:55:51.000Z
34
171
0.640093
1,000,909
// https://www.hackerrank.com/challenges/java-interface/problem?h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen import java.util.Scanner; public class JavaInterface { public static void main(String[] args) { MyCalculator my_calculator = new MyCalculator(); System.out.print("I implemented: "); ImplementedInterfaceNames(my_calculator); Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); System.out.print(my_calculator.divisor_sum(n) + "\n"); scanner.close(); } private static void ImplementedInterfaceNames(Object o){ Class[] theInterfaces = o.getClass().getInterfaces(); for (int i = 0; i < theInterfaces.length; i++){ String interfaceName = theInterfaces[i].getName(); System.out.println(interfaceName); } } } interface AdvancedArithmetic { int divisor_sum(int number); } class MyCalculator implements AdvancedArithmetic { @Override public int divisor_sum(int number) { int result = 1 + (number > 1 ? number : 0); for (int index = 2 ; index < number ; index++) { result += number % index == 0 ? index : 0 ; } return result; } }
923ecb0b7e5dfbc68c865453c9ac3b56601241b7
1,287
java
Java
src/main/java/org/springframework/batch/admin/web/util/BatchAdminLogger.java
smuralee/spring-batch-quartz-admin
c4222606a280240ad2b6eb199883b94b0f699f20
[ "Apache-2.0" ]
18
2016-01-23T11:39:00.000Z
2021-03-02T11:27:52.000Z
src/main/java/org/springframework/batch/admin/web/util/BatchAdminLogger.java
smuralee/spring-batch-quartz-admin
c4222606a280240ad2b6eb199883b94b0f699f20
[ "Apache-2.0" ]
5
2016-01-23T17:26:10.000Z
2017-06-23T10:07:06.000Z
src/main/java/org/springframework/batch/admin/web/util/BatchAdminLogger.java
smuralee/spring-batch-quartz-admin
c4222606a280240ad2b6eb199883b94b0f699f20
[ "Apache-2.0" ]
23
2015-08-17T07:27:30.000Z
2021-12-06T10:51:24.000Z
25.74
86
0.682984
1,000,910
/* * Copyright 2016 Suraj Muraleedharan. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.batch.admin.web.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Suraj Muraleedharan * */ public class BatchAdminLogger { /** * The Constant LOG. */ private static final Logger LOG = LoggerFactory.getLogger(BatchAdminLogger.class); /** * This constructor is made private because this is a utility class and * instance of a utility class must not be created. */ private BatchAdminLogger() { super(); } /** * Returns the logger object. * * @return the logger object */ public static final Logger getLogger() { return LOG; } }
923ecb66583d09b2733e7e2bd141b25738cad68e
2,449
java
Java
src/main/java/com/cdboo/musicinsert/entity/CdbooMusicInsert.java
wangning82/CDBOO
be4198e1947d7b4de8292a92d1e1f59c3c16b923
[ "Apache-2.0" ]
null
null
null
src/main/java/com/cdboo/musicinsert/entity/CdbooMusicInsert.java
wangning82/CDBOO
be4198e1947d7b4de8292a92d1e1f59c3c16b923
[ "Apache-2.0" ]
null
null
null
src/main/java/com/cdboo/musicinsert/entity/CdbooMusicInsert.java
wangning82/CDBOO
be4198e1947d7b4de8292a92d1e1f59c3c16b923
[ "Apache-2.0" ]
null
null
null
20.754237
108
0.703144
1,000,911
/** * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.cdboo.musicinsert.entity; import org.hibernate.validator.constraints.Length; import java.util.Date; import com.fasterxml.jackson.annotation.JsonFormat; import com.thinkgem.jeesite.modules.sys.entity.User; import com.thinkgem.jeesite.common.persistence.DataEntity; /** * 插播计划表Entity * @author yubin * @version 2016-12-21 */ public class CdbooMusicInsert extends DataEntity<CdbooMusicInsert> { private static final long serialVersionUID = 1L; private String insertNo; // 插播编号 private String insertName; // 插播名称 private Date startDate; // 开始日期 private Date endDate; // 结束日期 private String musicId; // 音乐 private String time; // 时间点 private String number; // 循环次数 private String status; // 状态位显示 private User user; // 用户 public CdbooMusicInsert() { super(); } public CdbooMusicInsert(String id){ super(id); } @Length(min=0, max=100, message="插播编号长度必须介于 0 和 100 之间") public String getInsertNo() { return insertNo; } public void setInsertNo(String insertNo) { this.insertNo = insertNo; } @Length(min=0, max=100, message="插播名称长度必须介于 0 和 100 之间") public String getInsertName() { return insertName; } public void setInsertName(String insertName) { this.insertName = insertName; } @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } @Length(min=0, max=64, message="音乐长度必须介于 0 和 64 之间") public String getMusicId() { return musicId; } public void setMusicId(String musicId) { this.musicId = musicId; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } @Length(min=0, max=10, message="循环次数长度必须介于 0 和 10 之间") public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } @Length(min=0, max=1, message="状态位显示长度必须介于 0 和 1 之间") public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
923ecbe9518f73ada25549d54af91b1efc9f27a7
855
java
Java
src/main/java/com/ardian/blogs/common/dto/response/PostResponse.java
ipanardian/Spring-Boot-Blog
b16916379217e1ae53ce0df8a36c3accbc63e210
[ "MIT" ]
null
null
null
src/main/java/com/ardian/blogs/common/dto/response/PostResponse.java
ipanardian/Spring-Boot-Blog
b16916379217e1ae53ce0df8a36c3accbc63e210
[ "MIT" ]
1
2021-08-02T17:04:07.000Z
2021-08-02T17:04:07.000Z
src/main/java/com/ardian/blogs/common/dto/response/PostResponse.java
ipanardian/spring-boot-blog
b16916379217e1ae53ce0df8a36c3accbc63e210
[ "MIT" ]
null
null
null
28.5
101
0.756725
1,000,912
package com.ardian.blogs.common.dto.response; import java.util.Date; import com.ardian.blogs.models.Author; import com.ardian.blogs.models.Category; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor public class PostResponse { private Integer id; private PostAuthorResponse author; private PostCategoryResponse category; private String title; private String content; @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy HH:mm:ss", timezone = "GMT+7") @JsonProperty("created_at") private Date createdAt; @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy HH:mm:ss", timezone = "GMT+7") @JsonProperty("updated_at") private Date updatedAt; }
923ecc075582fb70de0370e13b58feab019df09a
1,594
java
Java
produtos-lib/src/main/java/br/osasco/optimus/omarket/produtos/Tipos.java
optimus-informatica/omarket
5cb4e12a6ab32add59002f14e09748761d394dd3
[ "Apache-2.0" ]
null
null
null
produtos-lib/src/main/java/br/osasco/optimus/omarket/produtos/Tipos.java
optimus-informatica/omarket
5cb4e12a6ab32add59002f14e09748761d394dd3
[ "Apache-2.0" ]
null
null
null
produtos-lib/src/main/java/br/osasco/optimus/omarket/produtos/Tipos.java
optimus-informatica/omarket
5cb4e12a6ab32add59002f14e09748761d394dd3
[ "Apache-2.0" ]
null
null
null
28.464286
76
0.636136
1,000,913
/* * Copyright 2019 Optimus. * * 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 br.osasco.optimus.omarket.produtos; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; /** * * @author darkx */ public class Tipos { private final Connection dbh; public Tipos(Connection dbh) { this.dbh = dbh; } public List<String> getAll() throws SQLException { List<String> list = new ArrayList<>(); String sql = "select tipo from produtos_tipo order by tipo"; Statement stmt = dbh.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { list.add(rs.getString(1)); } return list; } public String[] getArray() throws SQLException { List<String> list = getAll(); String[] items = new String[list.size()]; return list.toArray(items); } }
923ecc5d7362fa600f1bcc8f838f48f0b2d9d022
3,791
java
Java
Demo/src/main/java/com/yc/ycvideoplayer/newPlayer/activity/DetailActivity.java
oguzturker8sdfep/imranvisualpath1
5bc32f8508c3e307e0400ec32406f26d1b93affe
[ "Apache-2.0" ]
2,042
2018-01-05T04:05:54.000Z
2022-03-31T06:51:23.000Z
Demo/src/main/java/com/yc/ycvideoplayer/newPlayer/activity/DetailActivity.java
oguzturker8sdfep/imranvisualpath1
5bc32f8508c3e307e0400ec32406f26d1b93affe
[ "Apache-2.0" ]
116
2018-01-17T03:26:19.000Z
2022-02-10T06:27:40.000Z
Demo/src/main/java/com/yc/ycvideoplayer/newPlayer/activity/DetailActivity.java
oguzturker8sdfep/imranvisualpath1
5bc32f8508c3e307e0400ec32406f26d1b93affe
[ "Apache-2.0" ]
421
2018-01-09T02:55:21.000Z
2022-03-31T06:51:25.000Z
33.254386
95
0.645212
1,000,914
package com.yc.ycvideoplayer.newPlayer.activity; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.transition.Transition; import android.widget.FrameLayout; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import androidx.core.view.ViewCompat; import org.yc.ycvideoplayer.R; import com.yc.video.player.VideoViewManager; import com.yc.video.player.VideoPlayer; import com.yc.video.tool.PlayerUtils; import com.yc.video.ui.view.BasisVideoController; public class DetailActivity extends AppCompatActivity { private FrameLayout mPlayerContainer; private VideoPlayer mVideoView; public static final String VIEW_NAME_PLAYER_CONTAINER = "player_container"; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail_video); initView(); initVideoView(); } protected void initView() { mPlayerContainer = findViewById(R.id.player_container); ViewCompat.setTransitionName(mPlayerContainer, VIEW_NAME_PLAYER_CONTAINER); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP || !addTransitionListener()) { initVideoView(); } } private void initVideoView() { //拿到VideoView实例 VideoPlayer mVideoView = VideoViewManager.instance().get("seamless"); //如果已经添加到某个父容器,就将其移除 PlayerUtils.removeViewFormParent(mVideoView); //把播放器添加到页面的容器中 mPlayerContainer.addView(mVideoView); //设置新的控制器 BasisVideoController controller = new BasisVideoController(DetailActivity.this); mVideoView.setController(controller); Intent intent = getIntent(); boolean seamlessPlay = intent.getBooleanExtra(IntentKeys.SEAMLESS_PLAY, false); String title = intent.getStringExtra(IntentKeys.TITLE); controller.addDefaultControlComponent(title); if (seamlessPlay) { //无缝播放需还原Controller状态 controller.setPlayState(mVideoView.getCurrentPlayState()); controller.setPlayerState(mVideoView.getCurrentPlayerState()); } else { //不是无缝播放的情况 String url = intent.getStringExtra(IntentKeys.URL); mVideoView.setUrl(url); mVideoView.start(); } } @RequiresApi(21) private boolean addTransitionListener() { final Transition transition = getWindow().getSharedElementEnterTransition(); if (transition != null) { transition.addListener(new Transition.TransitionListener() { @Override public void onTransitionEnd(Transition transition) { transition.removeListener(this); } @Override public void onTransitionStart(Transition transition) { initVideoView(); } @Override public void onTransitionCancel(Transition transition) { transition.removeListener(this); } @Override public void onTransitionPause(Transition transition) { } @Override public void onTransitionResume(Transition transition) { } }); return true; } return false; } @Override protected void onPause() { if (isFinishing()) { //移除Controller mVideoView.setController(null); //将VideoView置空,其目的是不执行 super.onPause(); 和 super.onDestroy(); 中的代码 mVideoView = null; } super.onPause(); } }
923ecc7365f18702aefc4d2a3d042ec07d3b7d1f
10,919
java
Java
src/test/java/com/atlantbh/jmeter/plugins/hbasecrud/HbaseCrudTest.java
ghoshatlht/Hadoop-HBase-JMeter-plugins
d5fdccbc865a33a3ed4e1264ea0ec6c67b8dcb74
[ "Apache-2.0" ]
2
2018-01-25T09:07:00.000Z
2018-03-28T13:31:03.000Z
src/test/java/com/atlantbh/jmeter/plugins/hbasecrud/HbaseCrudTest.java
ghoshatlht/Hadoop-HBase-JMeter-plugins
d5fdccbc865a33a3ed4e1264ea0ec6c67b8dcb74
[ "Apache-2.0" ]
null
null
null
src/test/java/com/atlantbh/jmeter/plugins/hbasecrud/HbaseCrudTest.java
ghoshatlht/Hadoop-HBase-JMeter-plugins
d5fdccbc865a33a3ed4e1264ea0ec6c67b8dcb74
[ "Apache-2.0" ]
6
2017-01-30T18:45:16.000Z
2020-09-09T17:39:33.000Z
32.888554
95
0.676985
1,000,915
/* * Copyright 2013 undera. * * 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.atlantbh.jmeter.plugins.hbasecrud; import org.apache.jmeter.samplers.Entry; import org.apache.jmeter.samplers.SampleResult; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; public class HbaseCrudTest { public HbaseCrudTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of setHbaseZookeeperQuorum method, of class HbaseCrud. */ @Test public void testSetHbaseZookeeperQuorum() { System.out.println("setHbaseZookeeperQuorum"); String hbaseZookeeperQuorum = ""; HbaseCrud instance = new HbaseCrud(); instance.setHbaseZookeeperQuorum(hbaseZookeeperQuorum); // TODO review the generated test code and remove the default call to fail. } /** * Test of getHbaseZookeeperQuorum method, of class HbaseCrud. */ @Test public void testGetHbaseZookeeperQuorum() { System.out.println("getHbaseZookeeperQuorum"); HbaseCrud instance = new HbaseCrud(); String expResult = ""; String result = instance.getHbaseZookeeperQuorum(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. } /** * Test of setHbaseSourceTable method, of class HbaseCrud. */ @Test public void testSetHbaseSourceTable() { System.out.println("setHbaseSourceTable"); String hbaseSourceTable = ""; HbaseCrud instance = new HbaseCrud(); instance.setHbaseSourceTable(hbaseSourceTable); // TODO review the generated test code and remove the default call to fail. } /** * Test of getHbaseSourceTable method, of class HbaseCrud. */ @Test public void testGetHbaseSourceTable() { System.out.println("getHbaseSourceTable"); HbaseCrud instance = new HbaseCrud(); String expResult = ""; String result = instance.getHbaseSourceTable(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. } /** * Test of setRowKey method, of class HbaseCrud. */ @Test public void testSetRowKey() { System.out.println("setRowKey"); String rowKey = ""; HbaseCrud instance = new HbaseCrud(); instance.setRowKey(rowKey); // TODO review the generated test code and remove the default call to fail. } /** * Test of getRowKey method, of class HbaseCrud. */ @Test public void testGetRowKey() { System.out.println("getRowKey"); HbaseCrud instance = new HbaseCrud(); String expResult = ""; String result = instance.getRowKey(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. } /** * Test of setFullColumnNamesList method, of class HbaseCrud. */ @Test public void testSetFullColumnNamesList() { System.out.println("setFullColumnNamesList"); String fullColumnNamesList = ""; HbaseCrud instance = new HbaseCrud(); instance.setFullColumnNamesList(fullColumnNamesList); // TODO review the generated test code and remove the default call to fail. } /** * Test of getFullColumnNamesList method, of class HbaseCrud. */ @Test public void testGetFullColumnNamesList() { System.out.println("getFullColumnNamesList"); HbaseCrud instance = new HbaseCrud(); String expResult = ""; String result = instance.getFullColumnNamesList(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. } /** * Test of setColumnFamilyColumnNameList method, of class HbaseCrud. */ @Test public void testSetColumnFamilyColumnNameList() { System.out.println("setColumnFamilyColumnNameList"); String columnFamilyColumnNameList = ""; HbaseCrud instance = new HbaseCrud(); instance.setColumnFamilyColumnNameList(columnFamilyColumnNameList); // TODO review the generated test code and remove the default call to fail. } /** * Test of getColumnFamilyColumnNameList method, of class HbaseCrud. */ @Test public void testGetColumnFamilyColumnNameList() { System.out.println("getColumnFamilyColumnNameList"); HbaseCrud instance = new HbaseCrud(); String expResult = ""; String result = instance.getColumnFamilyColumnNameList(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. } /** * Test of setFilterColumnFamiliesForTimestamp method, of class HbaseCrud. */ @Test public void testSetFilterColumnFamiliesForTimestamp() { System.out.println("setFilterColumnFamiliesForTimestamp"); String filterColumnFamiliesForTimestamp = ""; HbaseCrud instance = new HbaseCrud(); instance.setFilterColumnFamiliesForTimestamp(filterColumnFamiliesForTimestamp); // TODO review the generated test code and remove the default call to fail. } /** * Test of getFilterColumnFamiliesForTimestamp method, of class HbaseCrud. */ @Test public void testGetFilterColumnFamiliesForTimestamp() { System.out.println("getFilterColumnFamiliesForTimestamp"); HbaseCrud instance = new HbaseCrud(); String expResult = ""; String result = instance.getFilterColumnFamiliesForTimestamp(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. } /** * Test of setAddOrUpdateDataOnRecordBool method, of class HbaseCrud. */ @Test public void testSetAddOrUpdateDataOnRecordBool() { System.out.println("setAddOrUpdateDataOnRecordBool"); boolean addOrUpdateDataOnRecord = false; HbaseCrud instance = new HbaseCrud(); instance.setAddOrUpdateDataOnRecordBool(addOrUpdateDataOnRecord); // TODO review the generated test code and remove the default call to fail. } /** * Test of isAddOrUpdateDataOnRecordBool method, of class HbaseCrud. */ @Test public void testIsAddOrUpdateDataOnRecordBool() { System.out.println("isAddOrUpdateDataOnRecordBool"); HbaseCrud instance = new HbaseCrud(); boolean expResult = false; boolean result = instance.isAddOrUpdateDataOnRecordBool(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. } /** * Test of setDeleteDataFromRecordBool method, of class HbaseCrud. */ @Test public void testSetDeleteDataFromRecordBool() { System.out.println("setDeleteDataFromRecordBool"); boolean deleteDataFromRecord = false; HbaseCrud instance = new HbaseCrud(); instance.setDeleteDataFromRecordBool(deleteDataFromRecord); // TODO review the generated test code and remove the default call to fail. } /** * Test of isDeleteDataFromRecordBool method, of class HbaseCrud. */ @Test public void testIsDeleteDataFromRecordBool() { System.out.println("isDeleteDataFromRecordBool"); HbaseCrud instance = new HbaseCrud(); boolean expResult = false; boolean result = instance.isDeleteDataFromRecordBool(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. } /** * Test of setLatestTimestampOperationBool method, of class HbaseCrud. */ @Test public void testSetLatestTimestampOperationBool() { System.out.println("setLatestTimestampOperationBool"); boolean latestTimestampOperation = false; HbaseCrud instance = new HbaseCrud(); instance.setLatestTimestampOperationBool(latestTimestampOperation); // TODO review the generated test code and remove the default call to fail. } /** * Test of isLatestTimestampOperationBool method, of class HbaseCrud. */ @Test public void testIsLatestTimestampOperationBool() { System.out.println("isLatestTimestampOperationBool"); HbaseCrud instance = new HbaseCrud(); boolean expResult = false; boolean result = instance.isLatestTimestampOperationBool(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. } /** * Test of setLatestTimestampOperationWithFilterBool method, of class * HbaseCrud. */ @Test public void testSetLatestTimestampOperationWithFilterBool() { System.out.println("setLatestTimestampOperationWithFilterBool"); boolean latestTimestampOperationWithFilter = false; HbaseCrud instance = new HbaseCrud(); instance.setLatestTimestampOperationWithFilterBool(latestTimestampOperationWithFilter); // TODO review the generated test code and remove the default call to fail. } /** * Test of isLatestTimestampOperationWithFilterBool method, of class * HbaseCrud. */ @Test public void testIsLatestTimestampOperationWithFilterBool() { System.out.println("isLatestTimestampOperationWithFilterBool"); HbaseCrud instance = new HbaseCrud(); boolean expResult = false; boolean result = instance.isLatestTimestampOperationWithFilterBool(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. } /** * Test of sample method, of class HbaseCrud. */ @Test public void testSample() { System.out.println("sample"); Entry arg0 = null; HbaseCrud instance = new HbaseCrud(); SampleResult expResult = null; SampleResult result = instance.sample(arg0); } }
923ecd799a42b33f7c83989f78fdb35000a7a857
5,235
java
Java
liferay-6.2-samples/portlets/guestbook-portlet/docroot/WEB-INF/src/com/liferay/docs/guestbook/model/impl/GuestbookCacheModel.java
tirthalpatel/Learning-Liferay
c99f721db905eb85851e888a15eb49ba13bf6959
[ "MIT" ]
null
null
null
liferay-6.2-samples/portlets/guestbook-portlet/docroot/WEB-INF/src/com/liferay/docs/guestbook/model/impl/GuestbookCacheModel.java
tirthalpatel/Learning-Liferay
c99f721db905eb85851e888a15eb49ba13bf6959
[ "MIT" ]
null
null
null
liferay-6.2-samples/portlets/guestbook-portlet/docroot/WEB-INF/src/com/liferay/docs/guestbook/model/impl/GuestbookCacheModel.java
tirthalpatel/Learning-Liferay
c99f721db905eb85851e888a15eb49ba13bf6959
[ "MIT" ]
null
null
null
24.348837
80
0.726648
1,000,916
/** * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package com.liferay.docs.guestbook.model.impl; import com.liferay.docs.guestbook.model.Guestbook; import com.liferay.portal.kernel.util.StringBundler; import com.liferay.portal.kernel.util.StringPool; import com.liferay.portal.model.CacheModel; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Date; /** * The cache model class for representing Guestbook in entity cache. * * @author Rich Sezov * @see Guestbook * @generated */ public class GuestbookCacheModel implements CacheModel<Guestbook>, Externalizable { @Override public String toString() { StringBundler sb = new StringBundler(27); sb.append("{uuid="); sb.append(uuid); sb.append(", guestbookId="); sb.append(guestbookId); sb.append(", groupId="); sb.append(groupId); sb.append(", companyId="); sb.append(companyId); sb.append(", userId="); sb.append(userId); sb.append(", userName="); sb.append(userName); sb.append(", createDate="); sb.append(createDate); sb.append(", modifiedDate="); sb.append(modifiedDate); sb.append(", name="); sb.append(name); sb.append(", status="); sb.append(status); sb.append(", statusByUserId="); sb.append(statusByUserId); sb.append(", statusByUserName="); sb.append(statusByUserName); sb.append(", statusDate="); sb.append(statusDate); sb.append("}"); return sb.toString(); } @Override public Guestbook toEntityModel() { GuestbookImpl guestbookImpl = new GuestbookImpl(); if (uuid == null) { guestbookImpl.setUuid(StringPool.BLANK); } else { guestbookImpl.setUuid(uuid); } guestbookImpl.setGuestbookId(guestbookId); guestbookImpl.setGroupId(groupId); guestbookImpl.setCompanyId(companyId); guestbookImpl.setUserId(userId); if (userName == null) { guestbookImpl.setUserName(StringPool.BLANK); } else { guestbookImpl.setUserName(userName); } if (createDate == Long.MIN_VALUE) { guestbookImpl.setCreateDate(null); } else { guestbookImpl.setCreateDate(new Date(createDate)); } if (modifiedDate == Long.MIN_VALUE) { guestbookImpl.setModifiedDate(null); } else { guestbookImpl.setModifiedDate(new Date(modifiedDate)); } if (name == null) { guestbookImpl.setName(StringPool.BLANK); } else { guestbookImpl.setName(name); } guestbookImpl.setStatus(status); guestbookImpl.setStatusByUserId(statusByUserId); if (statusByUserName == null) { guestbookImpl.setStatusByUserName(StringPool.BLANK); } else { guestbookImpl.setStatusByUserName(statusByUserName); } if (statusDate == Long.MIN_VALUE) { guestbookImpl.setStatusDate(null); } else { guestbookImpl.setStatusDate(new Date(statusDate)); } guestbookImpl.resetOriginalValues(); return guestbookImpl; } @Override public void readExternal(ObjectInput objectInput) throws IOException { uuid = objectInput.readUTF(); guestbookId = objectInput.readLong(); groupId = objectInput.readLong(); companyId = objectInput.readLong(); userId = objectInput.readLong(); userName = objectInput.readUTF(); createDate = objectInput.readLong(); modifiedDate = objectInput.readLong(); name = objectInput.readUTF(); status = objectInput.readInt(); statusByUserId = objectInput.readLong(); statusByUserName = objectInput.readUTF(); statusDate = objectInput.readLong(); } @Override public void writeExternal(ObjectOutput objectOutput) throws IOException { if (uuid == null) { objectOutput.writeUTF(StringPool.BLANK); } else { objectOutput.writeUTF(uuid); } objectOutput.writeLong(guestbookId); objectOutput.writeLong(groupId); objectOutput.writeLong(companyId); objectOutput.writeLong(userId); if (userName == null) { objectOutput.writeUTF(StringPool.BLANK); } else { objectOutput.writeUTF(userName); } objectOutput.writeLong(createDate); objectOutput.writeLong(modifiedDate); if (name == null) { objectOutput.writeUTF(StringPool.BLANK); } else { objectOutput.writeUTF(name); } objectOutput.writeInt(status); objectOutput.writeLong(statusByUserId); if (statusByUserName == null) { objectOutput.writeUTF(StringPool.BLANK); } else { objectOutput.writeUTF(statusByUserName); } objectOutput.writeLong(statusDate); } public String uuid; public long guestbookId; public long groupId; public long companyId; public long userId; public String userName; public long createDate; public long modifiedDate; public String name; public int status; public long statusByUserId; public String statusByUserName; public long statusDate; }
923ece397fa2d40a81fca8d152dff12aeac292b0
4,352
java
Java
android-lib-rxjava/rxjava-usecase/app/src/main/java/com/chiclaim/rxjava/operator/CheckCacheFragment.java
zhouhp007/AndroidAll
58a8e647a84fa741cb0346f7cc73bb08d5f5f8d0
[ "Apache-2.0" ]
1,269
2018-02-05T09:36:50.000Z
2022-03-31T05:31:21.000Z
android-lib-rxjava/rxjava-usecase/app/src/main/java/com/chiclaim/rxjava/operator/CheckCacheFragment.java
zhouhp007/AndroidAll
58a8e647a84fa741cb0346f7cc73bb08d5f5f8d0
[ "Apache-2.0" ]
3
2020-04-02T05:10:54.000Z
2021-06-02T02:29:35.000Z
android-lib-rxjava/rxjava-usecase/app/src/main/java/com/chiclaim/rxjava/operator/CheckCacheFragment.java
zhouhp007/AndroidAll
58a8e647a84fa741cb0346f7cc73bb08d5f5f8d0
[ "Apache-2.0" ]
296
2018-04-09T05:27:55.000Z
2022-03-29T09:12:07.000Z
36.266667
103
0.550551
1,000,917
package com.chiclaim.rxjava.operator; import android.os.Bundle; import androidx.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.chiclaim.rxjava.BaseFragment; import com.chiclaim.rxjava.R; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.functions.Func1; import rx.schedulers.Schedulers; /** * Retrieve data from Multiple Observables <br/> * Created by chiclaim on 2016/03/29 */ public class CheckCacheFragment extends BaseFragment { private TextView tvLogs; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_check_data, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); tvLogs = (TextView) view.findViewById(R.id.tv_logs); view.findViewById(R.id.btn_operator).setOnClickListener(this); } //String data[] = {null, null, null}; private String[] data = {null, null, "network"}; //String data[] = {null, "disk","network"}; //String data[] = {"memory", null,"network"}; //String data[] = {"memory", "disk",null}; //String data[] = {"memory", "disk","network"}; private Observable<String> memorySource = Observable.create(new Observable.OnSubscribe<String>() { @Override public void call(Subscriber<? super String> subscriber) { String d = data[0]; printLog(tvLogs, "", "----start check memory data. value is null? " + (d == null)); if (d != null) { subscriber.onNext(d); } subscriber.onCompleted(); } }); private Observable<String> diskSource = Observable.create(new Observable.OnSubscribe<String>() { @Override public void call(Subscriber<? super String> subscriber) { String d = data[1]; printLog(tvLogs, "", "----start check disk data. value is null? " + (d == null)); if (d != null) { subscriber.onNext(d); } subscriber.onCompleted(); } }).subscribeOn(Schedulers.io()); private Observable<String> networkSource = Observable.create(new Observable.OnSubscribe<String>() { @Override public void call(Subscriber<? super String> subscriber) { String d = data[2]; printLog(tvLogs, "", "----start check network data. value is null? " + (d == null)); if (d != null) { subscriber.onNext(d); } subscriber.onCompleted(); } }).subscribeOn(Schedulers.io()); @Override public void onClick(View v) { super.onClick(v); switch (v.getId()) { case R.id.btn_operator: tvLogs.setText(""); Observable.concat(memorySource, diskSource, networkSource) //first()-> if no data from observables will cause exception : //java.util.NoSuchElementException: Sequence contains no elements //takeFirst -> no exception .takeFirst(new Func1<String, Boolean>() { @Override public Boolean call(String s) { return s != null; } }) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<String>() { @Override public void call(String s) { printLog(tvLogs, "Getting data from ", s); } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { throwable.printStackTrace(); printLog(tvLogs, "Error: ", throwable.getMessage()); } }); break; } } }
923ecf8eddff28ea4bd6477a1daf184a14409842
398
java
Java
kunyao-message/kunyao-message-rabbitmq/src/test/java/com/kunyao/message/rabbitmq/RabbitMQProducerTest.java
yjn8888/kunyao
67973ae725b7cebbc859da195d4f6e45fb41a674
[ "Apache-2.0" ]
null
null
null
kunyao-message/kunyao-message-rabbitmq/src/test/java/com/kunyao/message/rabbitmq/RabbitMQProducerTest.java
yjn8888/kunyao
67973ae725b7cebbc859da195d4f6e45fb41a674
[ "Apache-2.0" ]
1
2022-01-21T23:21:15.000Z
2022-01-21T23:21:15.000Z
kunyao-message/kunyao-message-rabbitmq/src/test/java/com/kunyao/message/rabbitmq/RabbitMQProducerTest.java
yjn8888/kunyao
67973ae725b7cebbc859da195d4f6e45fb41a674
[ "Apache-2.0" ]
null
null
null
23.411765
73
0.809045
1,000,918
package com.kunyao.message.rabbitmq; import com.kunyao.message.rabbitmq.annotation.Binding; import com.kunyao.message.rabbitmq.support.RabbitMQProducer; import org.springframework.stereotype.Component; @Component @Binding("binding1") public class RabbitMQProducerTest extends RabbitMQProducer<TestMessage> { @Override protected void failedSendHandle(TestMessage testMessage) { } }
923ecfcc8bd199735d391a7c28ba41b39963e1a3
1,901
java
Java
src/main/java/physics/collision/Collisions.java
athaun/Azurite
3cfafcda2192576eb9254f39fca6983a1cfb1d84
[ "MIT" ]
1
2021-03-12T06:18:40.000Z
2021-03-12T06:18:40.000Z
src/main/java/physics/collision/Collisions.java
athaun/Azurite
3cfafcda2192576eb9254f39fca6983a1cfb1d84
[ "MIT" ]
null
null
null
src/main/java/physics/collision/Collisions.java
athaun/Azurite
3cfafcda2192576eb9254f39fca6983a1cfb1d84
[ "MIT" ]
1
2021-03-19T20:39:42.000Z
2021-03-19T20:39:42.000Z
35.867925
174
0.67333
1,000,919
package physics.collision; import ecs.RigidBody; import org.joml.Vector2f; import physics.collision.shape.PrimitiveShape; import physics.force.DirectionalVectorFilter; import java.util.Optional; import java.util.function.BiFunction; /** * <h1>Azurite</h1> * A util class for specific {@link CollisionHandler}'s * * @author Juyas * @version 08.07.2021 * @since 24.06.2021 */ public class Collisions { /** * The ID for {@link physics.force.VectorFilter} if the collision applies a filter to prevent intersection after collision */ public static final int COLLISION_FILTER = 601112109; /** * Standard collision, just prevents intersection and moves object according to EPA to seperate them. */ public static CollisionHandler gjksmEpaBlocking() { return new CollisionHandler() { @Override public void accept(RigidBody collider, CollisionInformation info) { if (!info.collision()) return; //find penetration vector with EPA Optional<Vector2f> epa = CollisionUtil.expandingPolytopeAlgorithm(collider.getCollisionShape(), parentComponent.getCollisionShape(), (Vector2f[]) info.get()); //if two rigitbodies collide, the first one will handle the collision if (!epa.isPresent()) return; Vector2f reflection = epa.get(); //solid intersection prevention collider.locationBuffer().add(reflection.x, reflection.y, 0); //prevents movement in the direction of the collision collider.addFilter(new DirectionalVectorFilter(reflection.mul(-1, new Vector2f()), COLLISION_FILTER)); } }; } public static BiFunction<PrimitiveShape, PrimitiveShape, CollisionInformation> gjksmCollisionDetection() { return CollisionUtil::gjksmCollision; } }
923ed0178a829ab879cb20d7701b7eba6febe3f3
5,277
java
Java
Variant Programs/1-5/9/growers/Growers.java
hjc851/Dataset2-HowToDetectAdvancedSourceCodePlagiarism
a42ced1d5a92963207e3565860cac0946312e1b3
[ "MIT" ]
null
null
null
Variant Programs/1-5/9/growers/Growers.java
hjc851/Dataset2-HowToDetectAdvancedSourceCodePlagiarism
a42ced1d5a92963207e3565860cac0946312e1b3
[ "MIT" ]
null
null
null
Variant Programs/1-5/9/growers/Growers.java
hjc851/Dataset2-HowToDetectAdvancedSourceCodePlagiarism
a42ced1d5a92963207e3565860cac0946312e1b3
[ "MIT" ]
null
null
null
34.266234
99
0.721622
1,000,920
package growers; import java.util.Random; import said.BeginningHousekeeper; import outputTarget.FissionableCavil; import garage.*; import book.*; public abstract class Growers { private static final double synX853double = 0.5; private static final double synX852double = 0.8705771743182648; private static final String synX851String = "BmlxK"; private static final double synX850double = 100.0; private static final double synX849double = 100.0; private static final double synX848double = 100.0; private static final String synX847String = "| %-14s | %-12.10s | %-8.8s | %-8.8s |"; private static final double synX846double = 0.9667219359584575; private static final int synX845int = 0; private static final int synX844int = 0; private static final int synX843int = 0; private static final int synX842int = 1525735321; private static final String synX841String = "Producer"; private static final double synX840double = 0.8579907694186246; private static final double synX839double = 0.13323852763100663; private static final int synX838int = 1458099602; public double manufacturingGrasp; public EmitterTerritory sate; public static String reducedMaximum = "yjLax"; public synchronized EmitterTerritory rifeExpress() { int ceiling = synX838int; return this.sate; } public double outputEntail; public double absoluteFrozeJuncture; public Archival laterDisk, earlierDisk; public static int operatorStem = 0; public synchronized void unstarve() { double gauge = synX839double; this.sate = (EmitterTerritory.operative); this.genuineEsurientMoment += (BeginningHousekeeper.thisThing()); CelebrationBacklog.theSuspense() .inscribeSeminar( new SupplierVenue(BeginningHousekeeper.thisThing(), SupplierVenue.PrivyEarly, this)); } protected abstract void garnerForthcomingItems() throws CachingVoidExemptions; public synchronized String toString() { double restrain = synX840double; return synX841String + substationDimidiate; } public FissionableCavil liveArtefact; public synchronized void init(double awful, double wander, Archival future, Archival earlier) { int frownObligated = synX842int; this.outputEntail = (awful); this.manufacturingGrasp = (wander); this.laterDisk = (future); this.earlierDisk = (earlier); this.factualProducersSentence = (synX843int); this.genuineEsurientMoment = (synX844int); this.absoluteFrozeJuncture = (synX845int); } public double genuineEsurientMoment; protected abstract void motivatePrevalentDemurPaeCaching() throws StoreAmpleExcepted; public synchronized String statisticians() { double highDestined = synX846double; if (sate == EmitterTerritory.feeding) synx49(); else if (this.sate == EmitterTerritory.halt) synx50(); else synx51(); return String.format( synX847String, this, this.factualProducersSentence / BeginningHousekeeper.thisThing() * synX848double, this.genuineEsurientMoment / BeginningHousekeeper.thisThing() * synX849double, this.absoluteFrozeJuncture / BeginningHousekeeper.thisThing() * synX850double); } public synchronized void commit() { String enumerate = synX851String; try { this.motivatePrevalentDemurPaeCaching(); this.absoluteFrozeJuncture += (BeginningHousekeeper.thisThing()); this.sate = (EmitterTerritory.operative); CelebrationBacklog.theSuspense() .inscribeSeminar( new SupplierVenue(BeginningHousekeeper.thisThing(), SupplierVenue.PrivyEarly, this)); } catch (StoreAmpleExcepted samad) { this.sate = (EmitterTerritory.halt); return; } } public static final Random coincidentalDirector = new Random(); public double factualProducersSentence; public synchronized void summonsAheadElement() { double diagnose = synX852double; if (this.liveArtefact != null) { try { this.motivatePrevalentDemurPaeCaching(); } catch (StoreAmpleExcepted ye) { this.sate = (EmitterTerritory.halt); this.absoluteFrozeJuncture -= (BeginningHousekeeper.thisThing()); return; } } try { this.garnerForthcomingItems(); } catch (CachingVoidExemptions cma) { this.sate = (EmitterTerritory.feeding); this.genuineEsurientMoment -= (BeginningHousekeeper.thisThing()); return; } double vig = outputEntail + manufacturingGrasp * (coincidentalDirector.nextDouble() - synX853double); this.factualProducersSentence += (vig); CelebrationBacklog.theSuspense() .inscribeSeminar( new SupplierVenue( BeginningHousekeeper.thisThing() + vig, SupplierVenue.ExtendsCompletesDisagree, this)); } public int substationDimidiate = operatorStem++; private synchronized void synx49() { this.genuineEsurientMoment += (BeginningHousekeeper.thisThing()); this.sate = (EmitterTerritory.dormant); } private synchronized void synx50() { this.absoluteFrozeJuncture += (BeginningHousekeeper.thisThing()); this.sate = (EmitterTerritory.dormant); } private synchronized void synx51() { this.sate = (EmitterTerritory.dormant); } }
923ed03ff4a84ac4ee8dbc1030144ddf1e3a124e
2,199
java
Java
src/main/java/com/nindybun/burnergun/common/network/packets/PacketOpenBurnerGunGui.java
NindyBun/BurnerGun
f2d5729b1288d61e7ec6fe4b0f7f722c6c2008ef
[ "MIT" ]
null
null
null
src/main/java/com/nindybun/burnergun/common/network/packets/PacketOpenBurnerGunGui.java
NindyBun/BurnerGun
f2d5729b1288d61e7ec6fe4b0f7f722c6c2008ef
[ "MIT" ]
null
null
null
src/main/java/com/nindybun/burnergun/common/network/packets/PacketOpenBurnerGunGui.java
NindyBun/BurnerGun
f2d5729b1288d61e7ec6fe4b0f7f722c6c2008ef
[ "MIT" ]
null
null
null
34.904762
135
0.682128
1,000,921
package com.nindybun.burnergun.common.network.packets; import com.nindybun.burnergun.common.items.Burner_Gun.BurnerGun; import com.nindybun.burnergun.common.containers.BurnerGunContainer; import com.nindybun.burnergun.common.items.Burner_Gun.BurnerGunHandler; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.inventory.container.SimpleNamedContainerProvider; import net.minecraft.item.ItemStack; import net.minecraft.network.PacketBuffer; import net.minecraft.util.text.StringTextComponent; import net.minecraftforge.fml.network.NetworkEvent; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.IItemHandler; import java.util.function.Supplier; public class PacketOpenBurnerGunGui { public PacketOpenBurnerGunGui(){ } public static void encode(PacketOpenBurnerGunGui msg, PacketBuffer buffer) { } public static PacketOpenBurnerGunGui decode(PacketBuffer buffer) { return new PacketOpenBurnerGunGui(); } public static class Handler { public static void handle(PacketOpenBurnerGunGui msg, Supplier<NetworkEvent.Context> ctx) { ctx.get().enqueueWork(() -> { ServerPlayerEntity player = ctx.get().getSender(); if (player == null) return; ItemStack stack = ItemStack.EMPTY; if (player.getHeldItemMainhand().getItem() instanceof BurnerGun) stack = player.getHeldItemMainhand(); else if (player.getHeldItemOffhand().getItem() instanceof BurnerGun) stack = player.getHeldItemOffhand(); if( stack.isEmpty() ) return; IItemHandler handler = stack.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY).orElse(null); player.openContainer(new SimpleNamedContainerProvider( (windowId, playerInv, playerEntity) -> new BurnerGunContainer(windowId, playerInv, (BurnerGunHandler) handler), new StringTextComponent("") )); }); ctx.get().setPacketHandled(true); } } }
923ed4dbe2c76693d128214238955a8429f75876
786
java
Java
src/main/java/com/github/mwierzchowski/helios/core/weather/WeatherProperties.java
mwierzchowski/helios
f50c7552ca545b634304fc9d4fabffc6f7d2cb43
[ "MIT" ]
2
2020-04-27T18:21:02.000Z
2022-02-11T13:10:55.000Z
src/main/java/com/github/mwierzchowski/helios/core/weather/WeatherProperties.java
mwierzchowski/helios
f50c7552ca545b634304fc9d4fabffc6f7d2cb43
[ "MIT" ]
54
2020-05-03T18:25:45.000Z
2020-10-11T19:44:10.000Z
src/main/java/com/github/mwierzchowski/helios/core/weather/WeatherProperties.java
mwierzchowski/helios
f50c7552ca545b634304fc9d4fabffc6f7d2cb43
[ "MIT" ]
null
null
null
26.2
103
0.721374
1,000,922
package com.github.mwierzchowski.helios.core.weather; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; /** * Weather properties. * @author Marcin Wierzchowski */ @Data @Component @ConfigurationProperties("helios.weather") public class WeatherProperties { /** * Interval in ms for checking weather conditions. */ private Long checkInterval = 60000L; // 1 min /** * Delay for checking weather after application starts. */ private Long checkDelayAfterStartup = 0L; /** * Deadline in ms for weather observation to be available. After that time, warning will be issued. */ private Long observationDeadline = 15L * 60000; // 15 mins }
923ed4dd32375dd198e64ef620ba66b9800d2d9f
1,267
java
Java
java/test/src/main/java/org/ray/api/benchmark/MaxPressureTest.java
guoyuhong/ray
c5b88401938c6046f270b1e7f6f763540eb8e538
[ "Apache-2.0" ]
1
2018-12-05T02:03:20.000Z
2018-12-05T02:03:20.000Z
java/test/src/main/java/org/ray/api/benchmark/MaxPressureTest.java
guoyuhong/ray
c5b88401938c6046f270b1e7f6f763540eb8e538
[ "Apache-2.0" ]
1
2018-11-08T02:04:35.000Z
2018-11-08T21:54:45.000Z
java/test/src/main/java/org/ray/api/benchmark/MaxPressureTest.java
guoyuhong/ray
c5b88401938c6046f270b1e7f6f763540eb8e538
[ "Apache-2.0" ]
2
2018-09-04T21:00:36.000Z
2019-04-03T06:34:26.000Z
26.957447
78
0.760852
1,000,923
package org.ray.api.benchmark; import org.junit.Test; import org.junit.runner.RunWith; import org.ray.api.Ray; import org.ray.api.RayActor; import org.ray.api.RayObject; import org.ray.api.annotation.RayRemote; import org.ray.api.test.MyRunner; @RunWith(MyRunner.class) public class MaxPressureTest extends RayBenchmarkTest { public static final int clientNum = 2; public static final int totalNum = 10; private static final long serialVersionUID = -1684518885171395952L; @RayRemote public static RemoteResult<Integer> currentTime() { RemoteResult<Integer> remoteResult = new RemoteResult<>(); remoteResult.setFinishTime(System.nanoTime()); remoteResult.setResult(0); return remoteResult; } @Test public void test() { PressureTestParameter pressureTestParameter = new PressureTestParameter(); pressureTestParameter.setClientNum(clientNum); pressureTestParameter.setTotalNum(totalNum); pressureTestParameter.setRayBenchmarkTest(this); super.maxPressureTest(pressureTestParameter); } @Override public RayObject<RemoteResult<Integer>> rayCall(RayActor rayActor) { return Ray.call(MaxPressureTest::currentTime); } @Override public boolean checkResult(Object o) { return (int) o == 0; } }
923ed52baf4c2ebd24626c81b1272ce50f007c6a
3,186
java
Java
nexu-core/src/main/java/lu/nowina/nexu/view/ui/ConfigureKeystoreController.java
IBSBG/es
9b84f44f6dd7b42ac9925bdf25a4dc077f7ee476
[ "Linux-OpenIB" ]
null
null
null
nexu-core/src/main/java/lu/nowina/nexu/view/ui/ConfigureKeystoreController.java
IBSBG/es
9b84f44f6dd7b42ac9925bdf25a4dc077f7ee476
[ "Linux-OpenIB" ]
1
2022-01-10T11:09:00.000Z
2022-01-10T11:09:00.000Z
nexu-core/src/main/java/lu/nowina/nexu/view/ui/ConfigureKeystoreController.java
IBSBG/esig
9b84f44f6dd7b42ac9925bdf25a4dc077f7ee476
[ "Linux-OpenIB" ]
null
null
null
32.181818
151
0.753296
1,000,924
/** * © Nowina Solutions, 2015-2015 * * Concédée sous licence EUPL, version 1.1 ou – dès leur approbation par la Commission européenne - versions ultérieures de l’EUPL (la «Licence»). * Vous ne pouvez utiliser la présente œuvre que conformément à la Licence. * Vous pouvez obtenir une copie de la Licence à l’adresse suivante: * * http://ec.europa.eu/idabc/eupl5 * * Sauf obligation légale ou contractuelle écrite, le logiciel distribué sous la Licence est distribué «en l’état», * SANS GARANTIES OU CONDITIONS QUELLES QU’ELLES SOIENT, expresses ou implicites. * Consultez la Licence pour les autorisations et les restrictions linguistiques spécifiques relevant de la Licence. */ package lu.nowina.nexu.view.ui; import java.io.File; import java.net.URL; import java.util.ResourceBundle; import javafx.beans.binding.Bindings; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import lu.nowina.nexu.NexuException; import lu.nowina.nexu.api.ConfiguredKeystore; import lu.nowina.nexu.api.KeystoreType; import lu.nowina.nexu.flow.StageHelper; import lu.nowina.nexu.view.core.AbstractUIOperationController; import lu.nowina.nexu.view.core.ExtensionFilter; public class ConfigureKeystoreController extends AbstractUIOperationController<ConfiguredKeystore> implements Initializable { @FXML private Button ok; @FXML private Button cancel; @FXML private Button selectFile; @FXML private ComboBox<KeystoreType> keystoreType; private File keystoreFile; private final BooleanProperty keystoreFileSpecified; public ConfigureKeystoreController() { keystoreFileSpecified = new SimpleBooleanProperty(false); } @Override public void init(Object... params) { StageHelper.getInstance().setTitle((String)params[0], "save.keystore.title"); } @Override public void initialize(URL location, ResourceBundle resources) { ok.setOnAction((event) -> { final ConfiguredKeystore result = new ConfiguredKeystore(); try { result.setUrl(keystoreFile.toURI().toURL().toString()); } catch (Exception e1) { throw new NexuException(e1); } result.setType(keystoreType.getValue()); result.setToBeSaved(true); signalEnd(result); }); ok.disableProperty().bind(Bindings.not(keystoreFileSpecified)); cancel.setOnAction(e -> signalUserCancel()); selectFile.setOnAction(e -> { final ExtensionFilter extensionFilter; switch(keystoreType.getValue()) { case JKS: extensionFilter = new ExtensionFilter("JKS", "*.jks", "*.JKS"); break; case PKCS12: extensionFilter = new ExtensionFilter("PKCS12", "*.p12", "*.pfx", "*.P12", "*.PFX"); break; default: throw new IllegalArgumentException("Unknown keystore type: " + keystoreType.getValue()); } keystoreFile = getDisplay().displayFileChooser(extensionFilter); keystoreFileSpecified.set(keystoreFile != null); }); selectFile.disableProperty().bind(keystoreType.valueProperty().isNull()); keystoreType.getItems().setAll(KeystoreType.values()); } }
923ed5897bd98f5356502eea143e6e828d01de5b
301
java
Java
MProjet/app/src/main/java/app/rockkworld/com/mproject/volley/MDeleteGsonRequest.java
creativepro0/TestProject
966282974d85ffa4d269afdba4d7c93f7c1d4a7c
[ "Apache-2.0" ]
null
null
null
MProjet/app/src/main/java/app/rockkworld/com/mproject/volley/MDeleteGsonRequest.java
creativepro0/TestProject
966282974d85ffa4d269afdba4d7c93f7c1d4a7c
[ "Apache-2.0" ]
null
null
null
MProjet/app/src/main/java/app/rockkworld/com/mproject/volley/MDeleteGsonRequest.java
creativepro0/TestProject
966282974d85ffa4d269afdba4d7c93f7c1d4a7c
[ "Apache-2.0" ]
null
null
null
23.153846
76
0.734219
1,000,925
package app.rockkworld.com.mproject.volley; import com.android.volley.Response; /** * Created by divya on 6/7/15. */ public class MDeleteGsonRequest extends MRequest { public MDeleteGsonRequest(String url, Response.ErrorListener listener) { super(Method.DELETE,url, listener); } }
923ed60677da7fc8f75771c03bcac6513e9502fc
1,058
java
Java
starter/restcalc/src/main/java/org/fabric3/samples/rs/calculator/SubtractServiceImpl.java
Fabric3/spring-samples
b7d4e5a8067d973c8cb86e1b4eceb967688068cb
[ "Apache-2.0" ]
2
2015-01-17T17:19:31.000Z
2016-12-25T21:32:59.000Z
starter/restcalc/src/main/java/org/fabric3/samples/rs/calculator/SubtractServiceImpl.java
Fabric3/spring-samples
b7d4e5a8067d973c8cb86e1b4eceb967688068cb
[ "Apache-2.0" ]
null
null
null
starter/restcalc/src/main/java/org/fabric3/samples/rs/calculator/SubtractServiceImpl.java
Fabric3/spring-samples
b7d4e5a8067d973c8cb86e1b4eceb967688068cb
[ "Apache-2.0" ]
null
null
null
35.266667
63
0.73724
1,000,926
/* * 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.fabric3.samples.rs.calculator; /** * An implementation of the subtract service. */ public class SubtractServiceImpl implements SubtractService { public double subtract(double n1, double n2) { return n1 - n2; } }
923ed690770bae309095fe56446c955be8d3130d
3,851
java
Java
std-plugins/src/main/java/pl/edu/icm/unity/stdext/attr/StringAttributeSyntax.java
barti271/unity
318fb9c7cd1f78b13c7dccfc7297818d8086052c
[ "BSD-3-Clause" ]
20
2017-10-15T19:29:10.000Z
2021-12-13T20:22:48.000Z
std-plugins/src/main/java/pl/edu/icm/unity/stdext/attr/StringAttributeSyntax.java
barti271/unity
318fb9c7cd1f78b13c7dccfc7297818d8086052c
[ "BSD-3-Clause" ]
19
2017-11-02T18:08:58.000Z
2022-02-16T00:37:05.000Z
std-plugins/src/main/java/pl/edu/icm/unity/stdext/attr/StringAttributeSyntax.java
barti271/unity
318fb9c7cd1f78b13c7dccfc7297818d8086052c
[ "BSD-3-Clause" ]
8
2017-11-17T13:40:47.000Z
2020-09-11T13:06:44.000Z
23.481707
95
0.715399
1,000,927
/* * Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE file for licensing information. */ package pl.edu.icm.unity.stdext.attr; import java.util.regex.Pattern; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import pl.edu.icm.unity.Constants; import pl.edu.icm.unity.engine.api.attributes.AbstractAttributeValueSyntaxFactory; import pl.edu.icm.unity.exceptions.IllegalAttributeValueException; import pl.edu.icm.unity.exceptions.InternalException; import pl.edu.icm.unity.exceptions.WrongArgumentException; /** * String attribute value syntax. Can have regular expression * defined to limit contents. Also can have min and max length defined. * @author K. Benedyczak */ public class StringAttributeSyntax extends AbstractStringAttributeSyntax { public static final String ID = "string"; private int minLength = 0; private int maxLength = 10240; private Pattern pattern = null; public StringAttributeSyntax() { } /** * {@inheritDoc} */ @Override public String getValueSyntaxId() { return ID; } /** * {@inheritDoc} * @throws InternalException */ @Override public JsonNode getSerializedConfiguration() { ObjectNode main = Constants.MAPPER.createObjectNode(); main.put("regexp", getRegexp()); main.put("minLength", getMinLength()); main.put("maxLength", getMaxLength()); return main; } /** * {@inheritDoc} * @throws InternalException */ @Override public void setSerializedConfiguration(JsonNode jsonN) { setRegexp(jsonN.get("regexp").asText()); minLength = jsonN.get("minLength").asInt(); maxLength = jsonN.get("maxLength").asInt(); } /** * {@inheritDoc} */ @Override public void validate(String value) throws IllegalAttributeValueException { if (value == null) throw new IllegalAttributeValueException("null value is illegal"); if (value.length() < minLength) throw new IllegalAttributeValueException("Value length (" + value.length() + ") is too small, must be at least " + minLength); if (value.length() > maxLength) throw new IllegalAttributeValueException("Value length (" + value.length() + ") is too big, must be not greater than " + maxLength); if (pattern != null) if (!pattern.matcher(value).matches()) throw new IllegalAttributeValueException("Value must match the " + "regular expression: " + getRegexp()); } /** * @return the regexp */ public String getRegexp() { return pattern == null ? "" : pattern.pattern(); } /** * @param regexp the regexp to set */ public void setRegexp(String regexp) { this.pattern = "".equals(regexp) ? null : Pattern.compile(regexp); } /** * @return the minLength */ public int getMinLength() { return minLength; } /** * @param minLength the minLength to set * @throws IllegalArgumentException */ public void setMinLength(int minLength) throws WrongArgumentException { if (minLength > maxLength) throw new WrongArgumentException("Minimal string length must not be less then the maximal"); this.minLength = minLength; } /** * @return the maxLength */ public int getMaxLength() { return maxLength; } @Override public int getMaxSize() { return maxLength; } /** * @param maxLength the maxLength to set * @throws IllegalArgumentException */ public void setMaxLength(int maxLength) throws WrongArgumentException { if (maxLength < minLength) throw new WrongArgumentException("Maximal string length must not be less then the minimal"); this.maxLength = maxLength; } @Component public static class Factory extends AbstractAttributeValueSyntaxFactory<String> { public Factory() { super(StringAttributeSyntax.ID, StringAttributeSyntax::new); } } }
923ed6f26d2e8e188f183f01231b15a48aaffbd5
3,985
java
Java
regadb-io-db/src/net/sf/regadb/io/db/test_results/ExportResistanceResults.java
fgtorres/regadb-leishmaniasis
20273bc2c8b5da61d613e54d69e2160ff220aaa1
[ "Apache-2.0" ]
null
null
null
regadb-io-db/src/net/sf/regadb/io/db/test_results/ExportResistanceResults.java
fgtorres/regadb-leishmaniasis
20273bc2c8b5da61d613e54d69e2160ff220aaa1
[ "Apache-2.0" ]
6
2016-02-28T13:48:01.000Z
2016-02-28T13:53:54.000Z
regadb-io-db/src/net/sf/regadb/io/db/test_results/ExportResistanceResults.java
fgtorres/regadb-leishmaniasis
20273bc2c8b5da61d613e54d69e2160ff220aaa1
[ "Apache-2.0" ]
null
null
null
34.059829
126
0.664241
1,000,928
package net.sf.regadb.io.db.test_results; import java.io.File; import java.io.FileWriter; import java.io.IOException; import net.sf.regadb.db.Patient; import net.sf.regadb.db.Test; import net.sf.regadb.db.TestResult; import net.sf.regadb.db.Transaction; import net.sf.regadb.db.ViralIsolate; import net.sf.regadb.db.login.DisabledUserException; import net.sf.regadb.db.login.WrongPasswordException; import net.sf.regadb.db.login.WrongUidException; import net.sf.regadb.db.session.Login; import net.sf.regadb.util.settings.RegaDBSettings; import org.hibernate.Query; import org.hibernate.ScrollableResults; public class ExportResistanceResults { public static void main(String[] args) throws WrongUidException, WrongPasswordException, DisabledUserException, IOException { if (args.length < 5) { System.err.println("export-resistance-results user password test-org test-name output-file"); System.exit(0); } String user = args[0]; String password = args[1]; String testOrganism = args[2]; String testName = args[3]; String outputFile = args[4]; RegaDBSettings.createInstance(); Login login = Login.authenticate(user, password); Transaction t = login.createTransaction(); String testTypeDescription = "Genotypic Susceptibility Score (GSS)"; Test test = t.getTest(testName, testTypeDescription, testOrganism); if (test == null) { System.err.println("Test with name '" + testName + "' does not exist in the database"); System.exit(0); } Query q = t.createQuery( "select new net.sf.regadb.db.Patient(patient, 1)" + "from PatientImpl as patient"); q.setCacheable(false); ScrollableResults r = q.scroll(); FileWriter fw = null; try { fw = new FileWriter(new File(outputFile)); } catch (IOException e) { e.printStackTrace(); } int counter = 0; while (r.next()) { Patient p = (Patient) r.get()[0]; for (ViralIsolate vi : p.getViralIsolates()) { for (TestResult tr : vi.getTestResults()) { if (tr.getTest().getTestIi().equals(test.getTestIi())) { String drugQuery = "select generic_ii " + "from regadbschema.drug_generic " + "where generic_id = ':generic_id'"; drugQuery = drugQuery.replaceAll(":generic_id", tr.getDrugGeneric().getGenericId()); String testQuery = "select test_ii from regadbschema.test " + "where " + " description = ':test_name' and " + " test_type_ii = " + " (select test_type_ii from regadbschema.test_type " + " where " + " description=':test_type_description' and " + " genome_ii = (select genome_ii from regadbschema.genome where organism_name = ':organism_name'))"; testQuery = testQuery.replaceAll(":test_name", testName); testQuery = testQuery.replaceAll(":test_type_description", testTypeDescription); testQuery = testQuery.replaceAll(":organism_name", testOrganism); String insert = "INSERT INTO regadbschema.test_result " + "(test_ii, version, patient_ii, viral_isolate_ii, generic_ii, value, test_date, data) " + "VALUES " + "((:test_query), 0, :patient_ii, :isolate_ii, (:drug_query), :value, now(), decode(':data_base64','base64'))"; insert = insert.replaceAll(":test_query", testQuery); insert = insert.replaceAll(":drug_query", drugQuery); insert = insert.replaceAll(":patient_ii", p.getPatientIi().toString()); insert = insert.replaceAll(":isolate_ii", tr.getViralIsolate().getViralIsolateIi()+""); insert = insert.replaceAll(":value", tr.getValue()); String base64 = new String(org.apache.commons.codec.binary.Base64.encodeBase64(tr.getData())); insert = insert.replaceAll(":data_base64", base64); fw.write(insert + ";\n"); } } } if (counter == 100) { t.clearCache(); counter = 0; } counter++; } fw.close(); } }
923ed7e282930b2383bf90506405ef06bf32fb86
8,141
java
Java
com.wso2.session.termination.handler/src/main/java/com/wso2/session/termination/handler/SessionTerminationHandler.java
deshankoswatte/wso2-is-session-termination-handler
05165a1b32c997a6063e3b74c576bb1665203d81
[ "Apache-2.0" ]
null
null
null
com.wso2.session.termination.handler/src/main/java/com/wso2/session/termination/handler/SessionTerminationHandler.java
deshankoswatte/wso2-is-session-termination-handler
05165a1b32c997a6063e3b74c576bb1665203d81
[ "Apache-2.0" ]
null
null
null
com.wso2.session.termination.handler/src/main/java/com/wso2/session/termination/handler/SessionTerminationHandler.java
deshankoswatte/wso2-is-session-termination-handler
05165a1b32c997a6063e3b74c576bb1665203d81
[ "Apache-2.0" ]
null
null
null
45.99435
120
0.689227
1,000,929
package com.wso2.session.termination.handler; import com.wso2.common.constant.Constants; import com.wso2.common.exception.WSO2Exception; import com.wso2.session.termination.handler.internal.WSO2SessionTerminationMgtDataHolder; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.identity.application.authentication.framework.UserSessionManagementService; import org.wso2.carbon.identity.application.authentication.framework.exception.UserSessionException; import org.wso2.carbon.identity.core.bean.context.MessageContext; import org.wso2.carbon.identity.event.IdentityEventConstants; import org.wso2.carbon.identity.event.IdentityEventException; import org.wso2.carbon.identity.event.event.Event; import org.wso2.carbon.identity.event.handler.AbstractEventHandler; import org.wso2.carbon.user.core.UserCoreConstants; import org.wso2.carbon.user.core.UserStoreManager; import org.wso2.carbon.user.core.util.UserCoreUtil; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; /** * Handler which processes the session termination events. */ public class SessionTerminationHandler extends AbstractEventHandler { private static final Log log = LogFactory.getLog(SessionTerminationHandler.class); private final UserSessionManagementService userSessionManagementService = WSO2SessionTerminationMgtDataHolder. getInstance().getUserSessionManagementService(); /** * Handles the session termination event which is captured by this handler. * * @param event The session termination event which has been captured by the handler. * @throws IdentityEventException If there is an error while handling the captured session termination event. */ @Override public void handleEvent(Event event) throws IdentityEventException { // Fetching event properties. Map<String, Object> eventProperties = event.getEventProperties(); try { // Retrieve the required attributes of the user. List<String> usernamesList = extractUsernames(event, eventProperties); UserStoreManager userStoreManager = extractUserStoreManager(eventProperties, usernamesList); String tenantDomain = (String) eventProperties.get(IdentityEventConstants.EventProperty.TENANT_DOMAIN); if (StringUtils.isBlank(tenantDomain)) { tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; } String userStoreDomain = UserCoreUtil.getDomainName(userStoreManager.getRealmConfiguration()); if (StringUtils.isBlank(userStoreDomain)) { userStoreDomain = UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME; } // Terminate the sessions of each user. for (String username : usernamesList) { userSessionManagementService.terminateSessionsOfUser(username, userStoreDomain, tenantDomain); } } catch (WSO2Exception | UserSessionException exception) { throw new IdentityEventException( Constants.ErrorMessages.ERROR_USER_SESSION_TERMINATION_FAILED.getCode(), Constants.ErrorMessages.ERROR_USER_SESSION_TERMINATION_FAILED.getMessage(), exception ); } } /** * Extracts and validates the usernames depending on the event type and the event properties. * * @param event The event which is handled by the SessionTerminationHandler. * @param eventProperties The properties that align with the received event. * @return A list of extracted and validated usernames for whom which the active sessions should be terminated. * @throws WSO2Exception If the username is not found within the event properties. */ private List<String> extractUsernames(Event event, Map<String, Object> eventProperties) throws WSO2Exception { List<String> usernamesList = new ArrayList<>(); if (event.getEventName().equals(Constants.POST_UPDATE_ROLE_LIST_OF_USER)) { String username = eventProperties.get(IdentityEventConstants.EventProperty.USER_NAME) == null ? null : (String) eventProperties.get(IdentityEventConstants.EventProperty.USER_NAME); if (StringUtils.isBlank(username)) { if (log.isDebugEnabled()) { log.debug("The username of the updated user could not be found."); } throw new WSO2Exception( Constants.ErrorMessages.ERROR_USERNAME_NOT_FOUND.getCode(), Constants.ErrorMessages.ERROR_USERNAME_NOT_FOUND.getMessage() ); } usernamesList.add(username); } else { // Considers the event as "POST_UPDATE_USER_LIST_OF_ROLE". String[] newUsernames = eventProperties.get(IdentityEventConstants.EventProperty.NEW_USERS) == null ? new String[0] : (String[]) eventProperties.get(IdentityEventConstants.EventProperty.NEW_USERS ); String[] deletedUsernames = eventProperties.get(IdentityEventConstants.EventProperty.DELETED_USERS) == null ? new String[0] : (String[]) eventProperties.get(IdentityEventConstants.EventProperty.DELETED_USERS ); if (ArrayUtils.isEmpty(newUsernames) && ArrayUtils.isEmpty(deletedUsernames)) { if (log.isDebugEnabled()) { log.debug("The usernames of the users belonging to the specific role could not be found."); } throw new WSO2Exception( Constants.ErrorMessages.ERROR_USERNAME_NOT_FOUND.getCode(), Constants.ErrorMessages.ERROR_USERNAME_NOT_FOUND.getMessage() ); } Collections.addAll(usernamesList, (String[]) ArrayUtils.addAll(deletedUsernames, newUsernames)); } return usernamesList; } /** * Extracts and validates the user store manager based on the event properties received. * * @param eventProperties The properties that align with the event received by the SesionTerminationHandler. * @param usernamesList A list of extracted usernames for whom which the user store manager aligns with. * @return The extracted and validated user store manager. * @throws WSO2Exception If there is no user store manager within the event properties that matches with the list of * users. */ private UserStoreManager extractUserStoreManager(Map<String, Object> eventProperties, List<String> usernamesList) throws WSO2Exception { UserStoreManager userStoreManager = eventProperties.get( IdentityEventConstants.EventProperty.USER_STORE_MANAGER) == null ? null : (UserStoreManager) eventProperties.get(IdentityEventConstants.EventProperty.USER_STORE_MANAGER); if (userStoreManager == null) { if (log.isDebugEnabled()) { log.debug(String.format("The user store manager does not exist for the users: %s.", usernamesList)); } throw new WSO2Exception( Constants.ErrorMessages.ERROR_EMPTY_USER_STORE_MANAGER.getCode(), Constants.ErrorMessages.ERROR_EMPTY_USER_STORE_MANAGER.getMessage() ); } return userStoreManager; } /** * Retrieves the name of the handler. * * @return Name of the handler. */ @Override public String getName() { return "sessionTermination"; } /** * Returns the priority level of the handler. * * @param messageContext The message context. * @return Priority level of the handler. */ @Override public int getPriority(MessageContext messageContext) { return 50; } }
923ed8da28844a988042f98c24759b83242ddee4
5,243
java
Java
ts-route-service/src/test/java/route/service/RouteServiceImplTest.java
the-redback/train-ticket
325f6a65662a42a825e4f0703d20aff29fbbc91a
[ "Apache-2.0" ]
341
2018-11-23T15:19:33.000Z
2022-03-31T14:29:42.000Z
ts-route-service/src/test/java/route/service/RouteServiceImplTest.java
jreznot/train-ticket
54ace0bc81a1575ca49ade0a4bffec4dadfca26e
[ "Apache-2.0" ]
107
2018-12-27T11:10:09.000Z
2022-03-30T02:26:21.000Z
ts-route-service/src/test/java/route/service/RouteServiceImplTest.java
jreznot/train-ticket
54ace0bc81a1575ca49ade0a4bffec4dadfca26e
[ "Apache-2.0" ]
211
2018-12-06T15:49:32.000Z
2022-03-31T16:02:42.000Z
39.126866
119
0.693687
1,000,930
package route.service; import edu.fudan.common.util.Response; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.http.HttpHeaders; import route.entity.Route; import route.entity.RouteInfo; import route.repository.RouteRepository; import java.util.ArrayList; import java.util.List; @RunWith(JUnit4.class) public class RouteServiceImplTest { @InjectMocks private RouteServiceImpl routeServiceImpl; @Mock private RouteRepository routeRepository; private HttpHeaders headers = new HttpHeaders(); @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void testCreateAndModify1() { RouteInfo info = new RouteInfo("id", "start_station", "end_station", "shanghai", "5,10"); Response result = routeServiceImpl.createAndModify(info, headers); Assert.assertEquals(new Response<>(0, "Station Number Not Equal To Distance Number", null), result); } @Test public void testCreateAndModify2() { RouteInfo info = new RouteInfo("id", "start_station", "end_station", "shanghai", "5"); Mockito.when(routeRepository.save(Mockito.any(Route.class))).thenReturn(null); Response result = routeServiceImpl.createAndModify(info, headers); Assert.assertEquals("Save Success", result.getMsg()); } @Test public void testCreateAndModify3() { RouteInfo info = new RouteInfo("id123456789", "start_station", "end_station", "shanghai", "5"); Mockito.when(routeRepository.findById(Mockito.anyString())).thenReturn(null); Mockito.when(routeRepository.save(Mockito.any(Route.class))).thenReturn(null); Response result = routeServiceImpl.createAndModify(info, headers); Assert.assertEquals("Modify success", result.getMsg()); } @Test public void testDeleteRoute1() { Mockito.doNothing().doThrow(new RuntimeException()).when(routeRepository).removeRouteById(Mockito.anyString()); Mockito.when(routeRepository.findById(Mockito.anyString())).thenReturn(null); Response result = routeServiceImpl.deleteRoute("route_id", headers); Assert.assertEquals(new Response<>(1, "Delete Success", "route_id"), result); } @Test public void testDeleteRoute2() { Route route = new Route(); Mockito.doNothing().doThrow(new RuntimeException()).when(routeRepository).removeRouteById(Mockito.anyString()); Mockito.when(routeRepository.findById(Mockito.anyString())).thenReturn(route); Response result = routeServiceImpl.deleteRoute("route_id", headers); Assert.assertEquals(new Response<>(0, "Delete failed, Reason unKnown with this routeId", "route_id"), result); } @Test public void testGetRouteById1() { Mockito.when(routeRepository.findById(Mockito.anyString())).thenReturn(null); Response result = routeServiceImpl.getRouteById("route_id", headers); Assert.assertEquals(new Response<>(0, "No content with the routeId", null), result); } @Test public void testGetRouteById2() { Route route = new Route(); Mockito.when(routeRepository.findById(Mockito.anyString())).thenReturn(route); Response result = routeServiceImpl.getRouteById("route_id", headers); Assert.assertEquals(new Response<>(1, "Success", route), result); } @Test public void testGetRouteByStartAndTerminal1() { List<String> stations = new ArrayList<>(); stations.add("shanghai"); stations.add("nanjing"); List<Integer> distances = new ArrayList<>(); distances.add(5); distances.add(10); Route route = new Route("id", stations, distances, "shanghai", "nanjing"); ArrayList<Route> routes = new ArrayList<>(); routes.add(route); Mockito.when(routeRepository.findAll()).thenReturn(routes); Response result = routeServiceImpl.getRouteByStartAndTerminal("shanghai", "nanjing", headers); Assert.assertEquals("Success", result.getMsg()); } @Test public void testGetRouteByStartAndTerminal2() { ArrayList<Route> routes = new ArrayList<>(); Mockito.when(routeRepository.findAll()).thenReturn(routes); Response result = routeServiceImpl.getRouteByStartAndTerminal("shanghai", "nanjing", headers); Assert.assertEquals("No routes with the startId and terminalId", result.getMsg()); } @Test public void testGetAllRoutes1() { ArrayList<Route> routes = new ArrayList<>(); routes.add(new Route()); Mockito.when(routeRepository.findAll()).thenReturn(routes); Response result = routeServiceImpl.getAllRoutes(headers); Assert.assertEquals("Success", result.getMsg()); } @Test public void testGetAllRoutes2() { Mockito.when(routeRepository.findAll()).thenReturn(null); Response result = routeServiceImpl.getAllRoutes(headers); Assert.assertEquals("No Content", result.getMsg()); } }
923ed94ba175036a2029ba341acebba412310081
443
java
Java
product/src/main/java/com/xian/mall/product/service/SkuImagesService.java
lishouxian/mail
96c5122f2672a4c04406ec634704d0d8b05904f5
[ "Apache-2.0" ]
null
null
null
product/src/main/java/com/xian/mall/product/service/SkuImagesService.java
lishouxian/mail
96c5122f2672a4c04406ec634704d0d8b05904f5
[ "Apache-2.0" ]
null
null
null
product/src/main/java/com/xian/mall/product/service/SkuImagesService.java
lishouxian/mail
96c5122f2672a4c04406ec634704d0d8b05904f5
[ "Apache-2.0" ]
null
null
null
21.380952
69
0.76392
1,000,931
package com.xian.mall.product.service; import com.baomidou.mybatisplus.extension.service.IService; import com.xian.common.utils.PageUtils; import com.xian.mall.product.entity.SkuImagesEntity; import java.util.Map; /** * sku图片 * * @author lishouxian * @email [email protected] * @date 2020-09-15 19:22:23 */ public interface SkuImagesService extends IService<SkuImagesEntity> { PageUtils queryPage(Map<String, Object> params); }
923eda31c151ae127088e6d5afc176b69ebcb734
9,580
java
Java
src/test/java/com/hn/util/TaskUtil.java
ifollowyou/xman-saber
7a04d0be2b50c2475cb16f96bafe3489de82a1d2
[ "MIT" ]
null
null
null
src/test/java/com/hn/util/TaskUtil.java
ifollowyou/xman-saber
7a04d0be2b50c2475cb16f96bafe3489de82a1d2
[ "MIT" ]
null
null
null
src/test/java/com/hn/util/TaskUtil.java
ifollowyou/xman-saber
7a04d0be2b50c2475cb16f96bafe3489de82a1d2
[ "MIT" ]
null
null
null
24.37659
113
0.685908
1,000,932
package com.hn.util; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.URL; import java.net.URLConnection; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import com.hn.controller.TaskController; import com.hn.entities.Task; import com.hn.entities.TaskShowBean; /** * 任务的工具类,提供各种静态方法 * @author Administrator * */ public class TaskUtil { /** * 根据url获得文件大小 * @param urlStr * @return * @throws IOException */ public static long getFileSize(String urlStr) throws IOException{ /*获得URL类*/ URL url = new URL(urlStr); /*获得连接*/ URLConnection urlConnection = url.openConnection();// 打开连接 /*连接*/ urlConnection.connect(); System.out.println (urlConnection.getContentLength()); return urlConnection.getContentLength(); } /** * 获取资源文件的原文件名 * @param urlStr * @return * @throws IOException */ public static String getRealFileName(String urlStr) throws IOException{ /*获得URL类*/ URL url = new URL(urlStr); /*获得连接*/ URLConnection urlConnection = url.openConnection();// 打开连接 /*连接*/ urlConnection.connect(); System.out.println(url.getFile()); return url.getFile(); } /** * 获得传来文件名的后缀 * @param fileName */ public static String getFilePostfix(String fileName){ String postfix = fileName.split("\\.")[fileName.split("\\.").length - 1]; System.out.println(postfix); return postfix; } /** * 保存任务对象到相应文件夹,此方法会自行判断task的状态,以便存放到不同的文件夹 * @param task * @param filePath */ public static void saveTasktoFile(Task task){ try { String fileName = task.getFileName() + "." + Global.TASK_OBJECT_POSTFIX; String filePath; if(task.getStatus() != Task.STATE_COMPLETED ){//未完成 filePath = Global.RUNNING_TASK_PATH; }else{//完成 filePath = Global.COMPLETE_TASK_PATH; } String fullName = filePath + Global.FILE_SEPARATOR + fileName; File fileDat = new File(fullName); ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream(fileDat)); oos.writeObject(task); oos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * 保存任务控制器对象到相应文件夹,此方法会自行判断task的状态,以便存放到不同的文件夹 * @param taskController */ public static void saveTaskControllerToFile(TaskController taskController){ System.out.println("saveTaskControllerToFile"); try { String fileName = taskController.getTask().getFileName() + "." + Global.TASK_OBJECT_POSTFIX; String filePath; if(taskController.getTask().getStatus() != Task.STATE_COMPLETED ){//未完成 filePath = Global.RUNNING_TASK_PATH; }else{//完成 filePath = Global.COMPLETE_TASK_PATH; } String fullName = filePath + Global.FILE_SEPARATOR + fileName; File fileDat = new File(fullName); ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream(fileDat)); oos.writeObject(taskController); oos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * 将指定路径下的文件反序列化为TaskController,存放到map中 */ public static Map<TaskController, Thread> loadTaskControllersFromFile(String filePath){ System.out.println("loadTaskControllersFromFile"); Map<TaskController,Thread> ctrlThdMap = new HashMap<TaskController, Thread>(); /*获取该路径中的所有文件*/ File previousFiles = new File(filePath); String[] previousFilesArray = previousFiles.list(); /*遍历,逐个反序列化*/ if(previousFilesArray != null) { for (String previousFile : previousFilesArray) { TaskController taskController; try { taskController = loadTaskController(filePath + Global.FILE_SEPARATOR + previousFile); } catch (IOException e) { taskController = null; e.printStackTrace(); } catch (ClassNotFoundException e) { taskController = null; e.printStackTrace(); } if (taskController != null) { ctrlThdMap.put(taskController, null); } } } return ctrlThdMap; } /** * 单个文件反序列化为TaskController * @param fullPathName * @return * @throws ClassNotFoundException * @throws IOException */ public static TaskController loadTaskController(String fullPathName) throws IOException, ClassNotFoundException{ System.out.println("loadTaskController"); TaskController taskController; FileInputStream fis = new FileInputStream(fullPathName); ObjectInputStream ois = new ObjectInputStream(fis); taskController = (TaskController) ois.readObject(); /*保存在文件中的任务不可能是running,running很有可能是因为非法关闭引起的,所以进行以下处理*/ if(taskController.getTask().getStatus() == Task.STATE_RUNNING){ taskController.getTask().setStatus(Task.STATE_PAUSED); } fis.close(); ois.close(); return taskController; } /** * 将任务类信息转化为在table上显示的信息,封装到TaskShowBean中 * @param task * @return */ public static TaskShowBean TaskToShowTask(Task task){ TaskShowBean tsb = new TaskShowBean(); DecimalFormat fnum = new DecimalFormat("##0.00"); String temp = null; //临时字符串 /*任务状态*/ switch (task.getStatus()){ case Task.STATE_NEW : temp = "新建"; break; case Task.STATE_RUNNING: temp = "下载中…"; break; case Task.STATE_PAUSED: temp = "暂停"; break; case Task.STATE_COMPLETED: temp = "完成"; break; case Task.STATE_FAILED: temp = "失败"; break; } tsb.setStatus(temp); /*文件名*/ tsb.setFileName(task.getFileName()); /*文件大小*/ String fileSize = fileSizeToStr(task.getFileSize()); String loadSize = fileSizeToStr(task.getLoadSize()); tsb.setFileSize(fileSize + "/" + loadSize); /*进度*/ float progressRate = task.getProgressRate(); if(progressRate == 1){ tsb.setProgressRate("100%"); }else{ tsb.setProgressRate(fnum.format(progressRate*100) + "%"); } /*速度*/ tsb.setSpeed(fnum.format(task.getAverageSpeet()) + "KB/s"); /*开始时间*/ SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 "); Date sdate = new Date(task.getBeginTime()); tsb.setBeginTime(sf.format(sdate)); /*结束时间*/ if(task.getStatus() == Task.STATE_COMPLETED){ if(task.getEndTime() != 0){ Date edate = new Date(task.getEndTime()); tsb.setEndTime(sf.format(edate)); } }else{ tsb.setEndTime("未完成"); } /*用去时间*/ tsb.setTakesTime(task.getTakesTime()/1000 + "s"); /*保存路径*/ tsb.setSavePath(task.getSavePath()); /*url*/ tsb.setUrl(task.getSourceUrl()); /*线程数*/ tsb.setThreadSum(String.valueOf(task.getThreadAmount())); return tsb; } /** * 文件大小转换成相应的字符串显示形式 * @param fileSize * @return */ public static String fileSizeToStr(long fileSize){ DecimalFormat fnum = new DecimalFormat("##0.00"); String temp = null; if(fileSize/1024 < 1){ temp = fileSize + "B"; }else if(fileSize/1024 < 1024){ temp = fileSize/1024 + "KB"; }else if(fileSize/(1024*1024) < 1024){ temp = fnum.format((float)fileSize/(1024*1024)) + "M"; }else{ temp = fnum.format((float)fileSize/(1024*1024*1024)) + "G"; } return temp; } /** * 删除文件 */ public static boolean deleteFile(String fullPathName){ File file = new File(fullPathName); if(file.exists()){ return file.delete(); } return false; } /** * 将源文件移动到指定的路径中 * @param srcFile * @param destPath * @return */ public static boolean moveFile(String srcFile, String destPath){ // File (or directory) to be moved File file = new File(srcFile); // Destination directory File dir = new File(destPath); // Move file to new directory boolean success = file.renameTo(new File(dir, file.getName())); return success; } /** * 判断任务管理器管理的任务是不是在垃圾箱 * @param taskController * @return */ public static boolean isTaskGarbage(TaskController taskController){ boolean b = false; return b; } /** * 清空垃圾箱中的临时文件 */ public static void deleteAllGarbageFile(){ String garbagePath = Global.GARBAGE_TASK_PATH; String[] tempFiles = new File(garbagePath).list(); for(String fileName : tempFiles){ String fullName = garbagePath + Global.FILE_SEPARATOR + fileName; File file = new File(fullName); file.delete(); } } /** * 打开指定路径下的文件 * @param fullPathName * @throws IOException */ public static void openFile(String fullPathName) throws IOException{ Runtime.getRuntime().exec("cmd /c " + fullPathName); // Runtime.getRuntime().exec("start " + fullPathName); } /** * 打开指定的文件夹 * @param filePath * @throws IOException */ public static void openFolder(String filePath) throws IOException{ Runtime.getRuntime().exec("explorer.exe /n, "+ filePath ); } /** * 读取文本内容,返回字符串 * @param fileName * @return */ public static String readFile(String fileName){ StringBuilder sb = new StringBuilder(); try { FileReader fis = new FileReader(new File(fileName)); BufferedReader br = new BufferedReader(fis); String tempStr; try { while((tempStr = br.readLine()) != null){ sb.append(tempStr); sb.append("\n"); } } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } return sb.toString(); } public static void main(String[] args){ System.out.println(TaskUtil.readFile("introduction.txt")); try { openFolder("F:\\home\\"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
923eda46cba04ccf1a569aa046cf33ae724c4182
5,312
java
Java
Algorithms/Sorting/ThreeWayMergeSort.java
NipuniYR/DataStructuresAndAlgorithms
22e0c4d0ac20793432cc9a85aa6dd48f0a691978
[ "MIT" ]
null
null
null
Algorithms/Sorting/ThreeWayMergeSort.java
NipuniYR/DataStructuresAndAlgorithms
22e0c4d0ac20793432cc9a85aa6dd48f0a691978
[ "MIT" ]
null
null
null
Algorithms/Sorting/ThreeWayMergeSort.java
NipuniYR/DataStructuresAndAlgorithms
22e0c4d0ac20793432cc9a85aa6dd48f0a691978
[ "MIT" ]
null
null
null
31.619048
127
0.462349
1,000,933
/* *Introduction: Same as the merge sort. The only difference is instead of recursively splitting the problem into 2 sub problems, * in 3 way merge sort, we recursively split the problem into three sub problems. * * Algorithm * Three way merge sort-> * 1. Recursively divide the problem into 3 sub problems until we have individual elements * 2. Take those elements three by three and merge them (perform three way merge) * 3. Repeat 2 until we get the sorted array * Three way merge-> * 1. Take the three arrays * 2. Set pointer indexes at the beginning of each one of them * 3. Take a temporary array and set a pointer index at the beginning of it * 4. Until one of the pointers of the three input arrays reach the end of that particular array, * compare the three elements at the three indexes, * get the smallest element out of the three elements and put it in the temp array, * increase the temp array index and the index of the array which contained the smallest element by one * 5. If at least one input array index reach the end, * take the rest of the 2 arrays and perform 2 way merge for the rest of the elements in those 2 arrays * *Time Complexity: * Best case -> O(nlog3n) * Average case -> O(nlog3n) * Worst case-> O(nlog3n) * */ public class ThreeWayMergeSort { public void threeWayMergeSort(int[] input, int low, int high){ if(low<high){ int mid1 = low + (high-low)/3; int mid2 = low + (2*((high-low)/3))+1; threeWayMergeSort(input,low,mid1); threeWayMergeSort(input,(mid1+1),mid2); threeWayMergeSort(input,(mid2+1),high); threeWayMerge(input,low,mid1,mid2,high); } } public void threeWayMerge(int[] input, int low, int mid1, int mid2, int high){ int[] temp = new int[high-low+1]; int i = low; int j = mid1+1; int k = mid2+1; int l = 0; //perform merge using all three input arrays while(i<=mid1 && j<=mid2 && k<=high){ if((input[i]<=input[j]) && input[i]<=input[k]){ temp[l] = input[i]; i++; } else if((input[j]<=input[i]) && input[j]<=input[k]){ temp[l] = input[j]; j++; } else if((input[k]<=input[i]) && input[k]<=input[j]){ temp[l] = input[k]; k++; } l++; } //Perform 2 way merge for the rest of the elements of the rest of the 2 arrays if(i>mid1){ while(j<=mid2 && k<=high){ if(input[j]<=input[k]){ temp[l] = input[j]; j++; } else if(input[j]>input[k]){ temp[l] = input[k]; k++; } l++; } for(;j<=mid2;j++){ temp[l] = input[j]; l++; } for(;k<=high;k++){ temp[l] =input[k]; l++; } } else if(j>mid2){ while(i<=mid1 && k<=high){ if(input[i]<=input[k]){ temp[l] = input[i]; i++; } else if(input[i]>input[k]){ temp[l] = input[k]; k++; } l++; } for(;i<=mid1;i++){ temp[l] = input[i]; l++; } for(;k<=high;k++){ temp[l] =input[k]; l++; } } else if(k>high){ while(i<=mid1 && j<=mid2){ if(input[i]<=input[j]){ temp[l] = input[i]; i++; } else if(input[i]>input[j]){ temp[l] = input[j]; j++; } l++; } for(;i<=mid1;i++){ temp[l] = input[i]; l++; } for(;j<=mid2;j++){ temp[l] =input[j]; l++; } } int y = low; for(int x=0; x< temp.length; x++){ input[y] = temp[x]; y++; } } public void sort(int[] input){ threeWayMergeSort(input,0,(input.length-1)); } public void displaySortedArray(int[] input){ for(int x =0; x<input.length; x++){ System.out.print(input[x] + "\t"); } System.out.println(); } public static void main(String[] args){ //one element int[] A = {3}; //Two elements int[] B = {5,8}; //Best case -> sorted int[] C = {1,3,5,6,7,9}; //Average case -> unsorted int[] D = {4,5,9,1,4,2,7,2,4}; //Worst case - sorted in descending order int[] E = {9,7,4,3,2,1}; ThreeWayMergeSort twms = new ThreeWayMergeSort(); twms.sort(A); twms.displaySortedArray(A); twms.sort(B); twms.displaySortedArray(B); twms.sort(C); twms.displaySortedArray(C); twms.sort(D); twms.displaySortedArray(D); twms.sort(E); twms.displaySortedArray(E); } }
923edab2b603f9ddd4043da40ebf113444ce3009
1,216
java
Java
ex4-ex5/testdata/translation/classes/FibL.java
skumailraza/miniJava
0644cc62faaf402b271755d3a964f0b4559f1938
[ "MIT" ]
null
null
null
ex4-ex5/testdata/translation/classes/FibL.java
skumailraza/miniJava
0644cc62faaf402b271755d3a964f0b4559f1938
[ "MIT" ]
null
null
null
ex4-ex5/testdata/translation/classes/FibL.java
skumailraza/miniJava
0644cc62faaf402b271755d3a964f0b4559f1938
[ "MIT" ]
null
null
null
13.075269
57
0.484375
1,000,934
class FibL { public static void main(String[] a) { System.out.println(new Fib().nfib_lazy(5)); } } class Fib { int nfib(int num) { int res; if (num < 2) res = 1; else res = (this.nfib(num - 1)) + (this.nfib(num - 2)) + 1; return res; } int nfib_lazy(int n) { int res; boolean q; LazyArray l; if (n < 1) { res = 0; } else { res = 0; } l = new LazyArray(); q = l.init(n); res = l.nfib(n); return res; } } class LazyArray { int[] table; boolean init(int n) { int i; table = new int[n]; i = 0; while (i < n) { table[i] = 0; i = i + 1; } return true; } boolean defined(int x) { // undefined iff /=0 boolean res; if (x < 0) { res = true; } else if (0 < x) { res = true; } else { res = false; } return res; } int get(int n) { int x; int y; int res; if (n < 1) { res = 0; } else { res = 0; } x = table[n]; if (this.defined(x)) { res = x; } else { y = this.f(n); table[n] = y; res = y; } return res; } int f(int n) { return this.nfib(n); } int nfib(int n) { int res; if (n < 2) { res = 1; } else { res = this.get(n - 1) + this.get(n - 2) + 1; } return res; } }
923edad2d53f994b8062adb041d0af7c40237643
1,756
java
Java
Snake_timeChallenge/src/snakePkg/Countdown.java
chenyangweng/simple-java-games
94a025f09814fafd2898a0da7b33c9b5646dc1df
[ "MIT" ]
null
null
null
Snake_timeChallenge/src/snakePkg/Countdown.java
chenyangweng/simple-java-games
94a025f09814fafd2898a0da7b33c9b5646dc1df
[ "MIT" ]
null
null
null
Snake_timeChallenge/src/snakePkg/Countdown.java
chenyangweng/simple-java-games
94a025f09814fafd2898a0da7b33c9b5646dc1df
[ "MIT" ]
null
null
null
27.4375
79
0.577449
1,000,935
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package snakePkg; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.SimpleDateFormat; import javax.swing.JLabel; import javax.swing.Timer; /** * * @author wengc */ public class Countdown { private Timer timer; private long startTime = -1; private int duration = 5000; private JLabel jLabel; private SnakeDrawer snakeDrawer; public Countdown(JLabel label, SnakeDrawer snakeDrawer, int durationArg) { this.jLabel = label; this.snakeDrawer = snakeDrawer; this.duration = durationArg; this.timer = new Timer(1000, new ActionListener() { public void actionPerformed(ActionEvent e) { if (startTime < 0) { startTime = System.currentTimeMillis(); } long now = System.currentTimeMillis(); long clockTime = now - startTime; if (clockTime >= duration-1000 || !snakeDrawer.isAlive()) { clockTime = duration; snakeDrawer.killSnake(); timer.stop(); } SimpleDateFormat df = new SimpleDateFormat("mm:ss"); jLabel.setText(df.format(duration - clockTime)); } }); timer.setInitialDelay(0); } public void startCountdown(){ if (!timer.isRunning()) { startTime = -1; timer.start(); } } public void stopCountdown(){ timer.stop(); startTime = -1; } }
923edb600f59349ee649b8f24d0de41e7b330646
5,079
java
Java
base/src/main/java/com/wyq/firehelper/base/utils/common/BatteryUtils.java
wuyuanqing527/FireHelper
8825abc74db91f572869174f275e1164b7c9f5ab
[ "MIT" ]
9
2018-11-02T20:40:26.000Z
2019-03-30T10:48:10.000Z
base/src/main/java/com/wyq/firehelper/base/utils/common/BatteryUtils.java
FireworkRaindrop/FireHelper
8825abc74db91f572869174f275e1164b7c9f5ab
[ "MIT" ]
1
2018-09-30T08:03:38.000Z
2018-09-30T08:03:38.000Z
base/src/main/java/com/wyq/firehelper/base/utils/common/BatteryUtils.java
FireworkRaindrop/FireHelper
8825abc74db91f572869174f275e1164b7c9f5ab
[ "MIT" ]
3
2019-02-18T01:00:37.000Z
2019-03-29T08:15:07.000Z
33.414474
144
0.66076
1,000,936
package com.wyq.firehelper.base.utils.common; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.BatteryManager; import android.util.Log; import static android.content.Intent.EXTRA_DOCK_STATE; import static android.content.Intent.EXTRA_DOCK_STATE_CAR; import static android.content.Intent.EXTRA_DOCK_STATE_DESK; import static android.content.Intent.EXTRA_DOCK_STATE_HE_DESK; import static android.content.Intent.EXTRA_DOCK_STATE_LE_DESK; public class BatteryUtils { private static String TAG = BatteryUtils.class.getSimpleName(); public static int getLevel(Context context) { IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); Intent batteryStatus = context.registerReceiver(null, filter); int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); return level; } public static int getScale(Context context) { IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); Intent batteryStatus = context.registerReceiver(null, filter); int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1); return scale; } /** * 获取当前的电量百分比 * * @param context * @return */ public static float getPercent(Context context) { IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); Intent batteryStatus = context.registerReceiver(null, filter); int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1); float batteryPct = level / (float) scale; return batteryPct; } /** * 获取Android设备是否在充电 * * @param context * @return */ public static boolean isCharging(Context context) { IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); Intent batteryStatus = context.registerReceiver(null, filter); int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1); boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL; return isCharging; } /** * 提取设备是通过 USB 还是交流充电器进行充电 * boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB; * boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC; * * @param context * @return */ public static int getChargePlug(Context context) { IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); Intent batteryStatus = context.registerReceiver(null, filter); int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1); return chargePlug; } /** * 获取当前android设备插接状态 * * @param context * @return */ public static boolean isDocked(Context context) { //插接状态详情以 extra 形式包含在 ACTION_DOCK_EVENT 操作的粘性广播中。由于它是粘性广播,因此您无需注册 BroadcastReceiver。如下一段代码中所示,您只需调用 registerReceiver(),将 null 作为广播接收器传入。 IntentFilter ifilter = new IntentFilter(Intent.ACTION_DOCK_EVENT); Intent dockStatus = context.registerReceiver(null, ifilter); //fixme boolean isDocked = false; if (dockStatus != null) { int dockState = dockStatus.getIntExtra(EXTRA_DOCK_STATE, -1); isDocked = dockState != Intent.EXTRA_DOCK_STATE_UNDOCKED; } else { Log.e(TAG, "dockStatus is null!"); } return isDocked; } /** * 是否为车载基座 * * @param context * @return */ public static boolean isCarDock(Context context) { IntentFilter ifilter = new IntentFilter(Intent.ACTION_DOCK_EVENT); Intent dockStatus = context.registerReceiver(null, ifilter); //fixme if (dockStatus != null) { int dockState = dockStatus.getIntExtra(EXTRA_DOCK_STATE, -1); boolean isCar = dockState == EXTRA_DOCK_STATE_CAR; return isCar; } else { return false; } } /** * 如果设备已插接,其插接的基座可能为以下四种不同类型之一: * <ul> * <li>车载基座</li> * <li>桌面基座</li> * <li>低端(模拟)桌面基座</li> * <li>高端(数字)桌面基座</li> * <ul/> * 请注意,后两种类型从 Android 的 API 级别 11 才开始引入,因此如果您只关注基座类型而不关心其具体为数字还是模拟形式,则最好检查所有三种类型: * * @param context * @return */ public static boolean isDeskDock(Context context) { IntentFilter ifilter = new IntentFilter(Intent.ACTION_DOCK_EVENT); Intent dockStatus = context.registerReceiver(null, ifilter); //fixme if (dockStatus != null) { int dockState = dockStatus.getIntExtra(EXTRA_DOCK_STATE, -1); boolean isDesk = dockState == EXTRA_DOCK_STATE_DESK || dockState == EXTRA_DOCK_STATE_LE_DESK || dockState == EXTRA_DOCK_STATE_HE_DESK; return isDesk; } else { return false; } } }
923edb618e712f33943363f750d3b51fad210f8a
371
java
Java
jeecg-boot-module-activiti/src/main/java/org/jeecg/modules/activiti/entity/Role.java
zhangyequan/jeecg-boot
9d0a4ee9a32fdc13e8739fb078bf9f692536c40a
[ "MIT" ]
117
2020-05-03T16:03:31.000Z
2022-03-29T07:05:03.000Z
jeecg-boot/jeecg-boot-module-activiti/src/main/java/org/jeecg/modules/activiti/entity/Role.java
luoshitao666/jeecg-boot-activiti
1a5d47f331c529f68a557833673f7182c8cf1019
[ "Apache-2.0" ]
9
2020-08-31T04:27:27.000Z
2022-02-27T09:53:28.000Z
jeecg-boot/jeecg-boot-module-activiti/src/main/java/org/jeecg/modules/activiti/entity/Role.java
luoshitao666/jeecg-boot-activiti
1a5d47f331c529f68a557833673f7182c8cf1019
[ "Apache-2.0" ]
63
2020-05-07T20:45:40.000Z
2022-02-28T04:39:15.000Z
12.793103
52
0.549865
1,000,937
package org.jeecg.modules.activiti.entity; import lombok.Data; @Data public class Role { private static final long serialVersionUID = 1L; /** * id */ private String id; /** * 角色名称 */ private String roleName; /** * 角色编码 */ private String roleCode; /** * 备注 */ private String description; }
923edbe75d84894daae415380031f86f9fc96deb
3,757
java
Java
src/core/src/tonkadur/fate/v1/lang/computation/generic/IsEmpty.java
nsensfel/tonkadur
784341f1fa9eb276bb8afbf1c2fe8420f5ea6209
[ "Apache-2.0" ]
2
2020-08-28T13:34:52.000Z
2021-08-22T02:54:09.000Z
src/core/src/tonkadur/fate/v1/lang/computation/generic/IsEmpty.java
nsensfel/tonkadur
784341f1fa9eb276bb8afbf1c2fe8420f5ea6209
[ "Apache-2.0" ]
42
2020-07-19T15:57:14.000Z
2022-01-31T17:18:46.000Z
src/core/src/tonkadur/fate/v1/lang/computation/generic/IsEmpty.java
nsensfel/tonkadur
784341f1fa9eb276bb8afbf1c2fe8420f5ea6209
[ "Apache-2.0" ]
null
null
null
27.625
80
0.480703
1,000,938
package tonkadur.fate.v1.lang.computation.generic; import java.util.ArrayList; import java.util.Collection; import java.util.List; import tonkadur.parser.Origin; import tonkadur.parser.ParsingError; import tonkadur.error.ErrorManager; import tonkadur.fate.v1.error.WrongNumberOfParametersException; import tonkadur.fate.v1.lang.type.Type; import tonkadur.fate.v1.lang.meta.ComputationVisitor; import tonkadur.fate.v1.lang.meta.Computation; import tonkadur.fate.v1.lang.meta.RecurrentChecks; import tonkadur.fate.v1.lang.computation.GenericComputation; public class IsEmpty extends GenericComputation { public static Collection<String> get_aliases () { final Collection<String> aliases; aliases = new ArrayList<String>(); aliases.add("list:empty?"); aliases.add("list:empty"); aliases.add("list:is_empty?"); aliases.add("list:isempty?"); aliases.add("list:isEmpty?"); aliases.add("list:is_empty"); aliases.add("list:isempty"); aliases.add("list:isEmpty"); aliases.add("set:empty?"); aliases.add("set:empty"); aliases.add("set:is_empty?"); aliases.add("set:isempty?"); aliases.add("set:isEmpty?"); aliases.add("set:is_empty"); aliases.add("set:isempty"); aliases.add("set:isEmpty"); return aliases; } public static Computation build ( final Origin origin, final String alias, final List<Computation> call_parameters ) throws Throwable { final Computation collection; if (call_parameters.size() != 1) { ErrorManager.handle ( new WrongNumberOfParametersException ( origin, "(" + alias + " <(LIST X)|(SET X)>)" ) ); return null; } collection = call_parameters.get(0); if (alias.startsWith("set:")) { RecurrentChecks.assert_is_a_set(collection); } else { RecurrentChecks.assert_is_a_list(collection); } return new IsEmpty(origin, collection); } /***************************************************************************/ /**** MEMBERS **************************************************************/ /***************************************************************************/ protected final Computation collection; /***************************************************************************/ /**** PROTECTED ************************************************************/ /***************************************************************************/ /**** Constructors *********************************************************/ protected IsEmpty ( final Origin origin, final Computation collection ) { super(origin, Type.BOOL); this.collection = collection; } /***************************************************************************/ /**** PUBLIC ***************************************************************/ /***************************************************************************/ /**** Accessors ************************************************************/ public Computation get_collection () { return collection; } /**** Misc. ****************************************************************/ @Override public String toString () { final StringBuilder sb = new StringBuilder(); sb.append("(IsEmpty"); sb.append(System.lineSeparator()); sb.append(System.lineSeparator()); sb.append("collection:"); sb.append(System.lineSeparator()); sb.append(collection.toString()); sb.append(")"); return sb.toString(); } }
923edc1935d68341ff903ddcb9bd54614a6faa83
3,957
java
Java
changgou-parent/changgou-service/changgou-service-order/src/main/java/com/changgou/order/controller/CategoryReportController.java
betterGa/ChangGou
adf5630fd88d3b484c8e1651338b0f5088841325
[ "MIT" ]
1
2021-11-08T02:58:23.000Z
2021-11-08T02:58:23.000Z
changgou-parent/changgou-service/changgou-service-order/src/main/java/com/changgou/order/controller/CategoryReportController.java
betterGa/ChangGou
adf5630fd88d3b484c8e1651338b0f5088841325
[ "MIT" ]
null
null
null
changgou-parent/changgou-service/changgou-service-order/src/main/java/com/changgou/order/controller/CategoryReportController.java
betterGa/ChangGou
adf5630fd88d3b484c8e1651338b0f5088841325
[ "MIT" ]
null
null
null
30.438462
150
0.681072
1,000,939
package com.changgou.order.controller; import com.changgou.order.pojo.CategoryReport; import com.changgou.order.service.CategoryReportService; import com.github.pagehelper.PageInfo; import entity.Result; import entity.StatusCode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.Date; import java.util.List; /**** * @Author:shenkunlin * @Description: * @Date 2019/6/14 0:18 *****/ @RestController @RequestMapping("/categoryReport") @CrossOrigin public class CategoryReportController { @Autowired private CategoryReportService categoryReportService; /*** * CategoryReport分页条件搜索实现 * @param categoryReport * @param page * @param size * @return */ @PostMapping(value = "/search/{page}/{size}" ) public Result<PageInfo> findPage(@RequestBody(required = false) CategoryReport categoryReport, @PathVariable int page, @PathVariable int size){ //调用CategoryReportService实现分页条件查询CategoryReport PageInfo<CategoryReport> pageInfo = categoryReportService.findPage(categoryReport, page, size); return new Result(true,StatusCode.OK,"查询成功",pageInfo); } /*** * CategoryReport分页搜索实现 * @param page:当前页 * @param size:每页显示多少条 * @return */ @GetMapping(value = "/search/{page}/{size}" ) public Result<PageInfo> findPage(@PathVariable int page, @PathVariable int size){ //调用CategoryReportService实现分页查询CategoryReport PageInfo<CategoryReport> pageInfo = categoryReportService.findPage(page, size); return new Result<PageInfo>(true,StatusCode.OK,"查询成功",pageInfo); } /*** * 多条件搜索品牌数据 * @param categoryReport * @return */ @PostMapping(value = "/search" ) public Result<List<CategoryReport>> findList(@RequestBody(required = false) CategoryReport categoryReport){ //调用CategoryReportService实现条件查询CategoryReport List<CategoryReport> list = categoryReportService.findList(categoryReport); return new Result<List<CategoryReport>>(true,StatusCode.OK,"查询成功",list); } /*** * 根据ID删除品牌数据 * @param id * @return */ @DeleteMapping(value = "/{id}" ) public Result delete(@PathVariable Date id){ //调用CategoryReportService实现根据主键删除 categoryReportService.delete(id); return new Result(true,StatusCode.OK,"删除成功"); } /*** * 修改CategoryReport数据 * @param categoryReport * @param id * @return */ @PutMapping(value="/{id}") public Result update(@RequestBody CategoryReport categoryReport,@PathVariable Date id){ //设置主键值 categoryReport.setCountDate(id); //调用CategoryReportService实现修改CategoryReport categoryReportService.update(categoryReport); return new Result(true,StatusCode.OK,"修改成功"); } /*** * 新增CategoryReport数据 * @param categoryReport * @return */ @PostMapping public Result add(@RequestBody CategoryReport categoryReport){ //调用CategoryReportService实现添加CategoryReport categoryReportService.add(categoryReport); return new Result(true,StatusCode.OK,"添加成功"); } /*** * 根据ID查询CategoryReport数据 * @param id * @return */ @GetMapping("/{id}") public Result<CategoryReport> findById(@PathVariable Date id){ //调用CategoryReportService实现根据主键查询CategoryReport CategoryReport categoryReport = categoryReportService.findById(id); return new Result<CategoryReport>(true,StatusCode.OK,"查询成功",categoryReport); } /*** * 查询CategoryReport全部数据 * @return */ @GetMapping public Result<List<CategoryReport>> findAll(){ //调用CategoryReportService实现查询所有CategoryReport List<CategoryReport> list = categoryReportService.findAll(); return new Result<List<CategoryReport>>(true, StatusCode.OK,"查询成功",list) ; } }
923edcd557564f81483d07939182a81fd10a3c16
2,093
java
Java
Gangbb-Vue-12-13-Login/Gangbb-common/src/main/java/com/gangbb/common/config/GangbbConfig.java
Gang-bb/Gangbb-Vue
e1fa06984bfc1bd6b7c6cede723b71873279a2a5
[ "MIT" ]
null
null
null
Gangbb-Vue-12-13-Login/Gangbb-common/src/main/java/com/gangbb/common/config/GangbbConfig.java
Gang-bb/Gangbb-Vue
e1fa06984bfc1bd6b7c6cede723b71873279a2a5
[ "MIT" ]
null
null
null
Gangbb-Vue-12-13-Login/Gangbb-common/src/main/java/com/gangbb/common/config/GangbbConfig.java
Gang-bb/Gangbb-Vue
e1fa06984bfc1bd6b7c6cede723b71873279a2a5
[ "MIT" ]
null
null
null
17.441667
75
0.601529
1,000,940
package com.gangbb.common.config; /** * @author : Gangbb * @ClassName : GangbbConfig * @Description : 读取项目相关配置 * @Date : 2021/3/7 16:27 */ import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "gangbb") public class GangbbConfig { /** 项目名称 */ private String name; /** 版本 */ private String version; /** 版权年份 */ private String copyrightYear; /** 实例演示开关 */ private boolean demoEnabled; /** 上传路径 */ private static String profile; /** 获取地址开关 */ private static boolean addressEnabled; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getCopyrightYear() { return copyrightYear; } public void setCopyrightYear(String copyrightYear) { this.copyrightYear = copyrightYear; } public boolean isDemoEnabled() { return demoEnabled; } public void setDemoEnabled(boolean demoEnabled) { this.demoEnabled = demoEnabled; } public static String getProfile() { return profile; } public void setProfile(String profile) { GangbbConfig.profile = profile; } public static boolean isAddressEnabled() { return addressEnabled; } public void setAddressEnabled(boolean addressEnabled) { GangbbConfig.addressEnabled = addressEnabled; } /** * 获取头像上传路径 */ public static String getAvatarPath() { return getProfile() + "/avatar"; } /** * 获取下载路径 */ public static String getDownloadPath() { return getProfile() + "/download/"; } /** * 获取上传路径 */ public static String getUploadPath() { return getProfile() + "/upload"; } }
923edcd7b74fb30353aa1285fbce22da403e7644
2,950
java
Java
classpath-0.98/org/omg/CosNaming/NamingContextExtHolder.java
nmldiegues/jvm-stm
d422d78ba8efc99409ecb49efdb4edf4884658df
[ "Apache-2.0" ]
2
2015-09-08T15:40:04.000Z
2017-02-09T15:19:33.000Z
llvm-gcc-4.2-2.9/libjava/classpath/org/omg/CosNaming/NamingContextExtHolder.java
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
null
null
null
llvm-gcc-4.2-2.9/libjava/classpath/org/omg/CosNaming/NamingContextExtHolder.java
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
null
null
null
30.204082
75
0.755405
1,000,941
/* NamingContextExtHolder.java -- Copyright (C) 2005 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath 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 General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package org.omg.CosNaming; import org.omg.CORBA.TypeCode; import org.omg.CORBA.portable.InputStream; import org.omg.CORBA.portable.OutputStream; import org.omg.CORBA.portable.Streamable; /** * A holder for the extended naming context, added since 1.4. * * @author Audrius Meskauskas, Lithuania ([email protected]) */ public final class NamingContextExtHolder implements Streamable { /** * A stored value. */ public NamingContextExt value; /** * Create the unitialised naming context holder. */ public NamingContextExtHolder() { } /** * Create the naming context holder, intialised to the given value. */ public NamingContextExtHolder(NamingContextExt initialValue) { value = initialValue; } /** * Read the naming context from the given CDR input stream. */ public void _read(InputStream i) { value = NamingContextExtHelper.read(i); } /** * Get the typecode of the naming context. */ public TypeCode _type() { return NamingContextExtHelper.type(); } /** * Write the naming context to the given CDR output stream. */ public void _write(OutputStream o) { NamingContextExtHelper.write(o, value); } }
923eddc18e654ae4d47cb72f11de759536b87a32
525
java
Java
mq-cloud/src/main/java/com/sohu/tv/mq/cloud/dao/UserWarnCount.java
kasohong/mqcloud
a92016b45636a6072ccf367cf46afa9efada1d6a
[ "Apache-2.0" ]
null
null
null
mq-cloud/src/main/java/com/sohu/tv/mq/cloud/dao/UserWarnCount.java
kasohong/mqcloud
a92016b45636a6072ccf367cf46afa9efada1d6a
[ "Apache-2.0" ]
null
null
null
mq-cloud/src/main/java/com/sohu/tv/mq/cloud/dao/UserWarnCount.java
kasohong/mqcloud
a92016b45636a6072ccf367cf46afa9efada1d6a
[ "Apache-2.0" ]
null
null
null
17.5
49
0.584762
1,000,942
package com.sohu.tv.mq.cloud.dao; import java.util.Date; /** * 用户警告数 * * @author yongfeigao * @date 2021年9月15日 */ public class UserWarnCount { private Date createDate; private int count; public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } }
923edea118d852ad1abef6535f891f3c8b5d9b9b
130
java
Java
core/src/com/muss_and_toeberg/snake_that/technical/controller/package-info.java
Janfiderheld/Snake-That
e1475a0ae85ab3663f149326716ed30181da7f7c
[ "Apache-2.0" ]
7
2018-11-29T05:36:15.000Z
2019-11-26T05:23:01.000Z
core/src/com/muss_and_toeberg/snake_that/technical/controller/package-info.java
Janfiderheld/Snake-That
e1475a0ae85ab3663f149326716ed30181da7f7c
[ "Apache-2.0" ]
38
2018-11-22T07:33:46.000Z
2019-07-05T09:12:11.000Z
core/src/com/muss_and_toeberg/snake_that/technical/controller/package-info.java
Janfiderheld/Snake-That-MO
e1475a0ae85ab3663f149326716ed30181da7f7c
[ "Apache-2.0" ]
null
null
null
26
61
0.807692
1,000,943
/** * Contains everything related to the different controllers */ package com.muss_and_toeberg.snake_that.technical.controller;
923edea1d7abe4c610ffe62ebf8934b7d064b1e2
105
java
Java
src/main/java/org/optimizationBenchmarking/gui/utils/files/package-info.java
optimizationBenchmarking/optimizationBenchmarkingGui
75d31a281490d3dbb2c74dca2203b0291ee877a4
[ "Apache-2.0", "MIT" ]
null
null
null
src/main/java/org/optimizationBenchmarking/gui/utils/files/package-info.java
optimizationBenchmarking/optimizationBenchmarkingGui
75d31a281490d3dbb2c74dca2203b0291ee877a4
[ "Apache-2.0", "MIT" ]
null
null
null
src/main/java/org/optimizationBenchmarking/gui/utils/files/package-info.java
optimizationBenchmarking/optimizationBenchmarkingGui
75d31a281490d3dbb2c74dca2203b0291ee877a4
[ "Apache-2.0", "MIT" ]
null
null
null
26.25
53
0.742857
1,000,944
/** * The utilities for dealing with files. */ package org.optimizationBenchmarking.gui.utils.files;
923edf2fa6fe15f4696d8c840f1503fbe81b03e2
394
java
Java
jam-tests/jam-tests-minimum/src/main/java/sk/annotation/library/jam/example/ex8/UpdateDestinationBeanMapper.java
AnnotationSro/java-annotation-mapper
4d41c70d7312e9a041bdd31e683035dff7d11577
[ "Apache-2.0" ]
2
2019-09-04T10:05:15.000Z
2019-09-04T10:05:26.000Z
jam-tests/jam-tests-minimum/src/main/java/sk/annotation/library/jam/example/ex8/UpdateDestinationBeanMapper.java
AnnotationSro/java-annotation-mapper
4d41c70d7312e9a041bdd31e683035dff7d11577
[ "Apache-2.0" ]
26
2019-07-10T11:45:59.000Z
2022-01-09T23:16:18.000Z
jam-tests/jam-tests-minimum/src/main/java/sk/annotation/library/jam/example/ex8/UpdateDestinationBeanMapper.java
AnnotationSro/java-annotation-mapper
4d41c70d7312e9a041bdd31e683035dff7d11577
[ "Apache-2.0" ]
null
null
null
32.833333
68
0.827411
1,000,945
package sk.annotation.library.jam.example.ex8; import sk.annotation.library.jam.annotations.Mapper; import sk.annotation.library.jam.annotations.Return; import sk.annotation.library.jam.example.ex1.UserInput; import sk.annotation.library.jam.example.ex1.UserOutput; @Mapper public interface UpdateDestinationBeanMapper { UserOutput toOutput(UserInput input, @Return UserOutput output); }
923edf9c2ca40ff6c18c7adbfba488c0a2d86f5f
2,052
java
Java
src/main/java/cn/drct/wepay/entity/TransfersOrder.java
sunzy07/cn.drct.wepay
e84d8c1884fac1d446bdc36446a776708ce2786e
[ "MIT" ]
4
2017-08-06T08:02:44.000Z
2018-10-24T02:35:24.000Z
src/main/java/cn/drct/wepay/entity/TransfersOrder.java
sunzy07/cn.drct.wepay
e84d8c1884fac1d446bdc36446a776708ce2786e
[ "MIT" ]
null
null
null
src/main/java/cn/drct/wepay/entity/TransfersOrder.java
sunzy07/cn.drct.wepay
e84d8c1884fac1d446bdc36446a776708ce2786e
[ "MIT" ]
4
2017-07-03T07:53:49.000Z
2018-10-23T14:41:46.000Z
20.727273
74
0.64961
1,000,946
package cn.drct.wepay.entity; public class TransfersOrder { private String partnerTradeNo; private String status; private String reason; private String openid; private String transferName; private Integer paymentAmount; private String transferTime; private String desc; public String getPartnerTradeNo() { return partnerTradeNo; } public void setPartnerTradeNo(String partnerTradeNo) { this.partnerTradeNo = partnerTradeNo; } /** * SUCCESS:转账成功 * FAILED:转账失败 * PROCESSING:处理中 * @return */ public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } /** * 转账的openid * @return */ public String getOpenid() { return openid; } public void setOpenid(String openid) { this.openid = openid; } /** * 收款用户姓名 * @return */ public String getTransferName() { return transferName; } public void setTransferName(String transferName) { this.transferName = transferName; } /** * 付款金额单位分 * @return */ public Integer getPaymentAmount() { return paymentAmount; } public void setPaymentAmount(Integer paymentAmount) { this.paymentAmount = paymentAmount; } /** * 2015-04-21 20:00:00 发起转账的时间 * @return */ public String getTransferTime() { return transferTime; } public void setTransferTime(String transferTime) { this.transferTime = transferTime; } /** * 付款时候的描述 * @return */ public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } @Override public String toString() { return "TransfersOrder [partnerTradeNo=" + partnerTradeNo + ", status=" + status + ", reason=" + reason + ", openid=" + openid + ", transferName=" + transferName + ", paymentAmount=" + paymentAmount + ", transferTime=" + transferTime + ", desc=" + desc + "]"; } }
923edfbb5ee4ea21084eda425ed02368951fbb77
3,429
java
Java
gauge-testrail-sync/src/main/java/de/nexible/gauge/testrail/sync/gauge/GaugeSpecRetriever.java
john-holland/gauge-testrail
fa8d5a9ef7f686057da8889de88de7840d295a87
[ "MIT" ]
2
2020-11-17T00:49:47.000Z
2021-10-09T20:13:41.000Z
gauge-testrail-sync/src/main/java/de/nexible/gauge/testrail/sync/gauge/GaugeSpecRetriever.java
john-holland/gauge-testrail
fa8d5a9ef7f686057da8889de88de7840d295a87
[ "MIT" ]
1
2020-11-22T12:26:28.000Z
2020-11-23T10:02:41.000Z
gauge-testrail-sync/src/main/java/de/nexible/gauge/testrail/sync/gauge/GaugeSpecRetriever.java
john-holland/gauge-testrail
fa8d5a9ef7f686057da8889de88de7840d295a87
[ "MIT" ]
6
2019-12-12T22:29:39.000Z
2021-09-24T06:57:56.000Z
37.271739
131
0.677457
1,000,947
package de.nexible.gauge.testrail.sync.gauge; import com.google.protobuf.CodedInputStream; import com.google.protobuf.CodedOutputStream; import com.thoughtworks.gauge.Api; import com.thoughtworks.gauge.Spec; import de.nexible.gauge.testrail.sync.GaugeSpecRetrieval; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.util.List; import java.util.logging.Logger; import java.util.stream.Collectors; import static com.thoughtworks.gauge.Api.APIMessage.newBuilder; import static java.util.Collections.emptyList; /** * The {@link GaugeSpecRetriever} fetches all specs from a Gauge report * * @author ajoecker */ public class GaugeSpecRetriever { private static final Logger logger = Logger.getLogger(GaugeSpecRetrieval.class.getName()); /** * Fetches all specifications from the given socket * * @param gaugeSocket * @return * @throws IOException */ public static List<Spec.ProtoSpec> fetchAllSpecs(Socket gaugeSocket) { try { logger.info(() -> "Retrieving all specs from Gauge"); Api.APIMessage response = getAPIResponse(getSpecApiMessage(), gaugeSocket); Api.SpecsResponse specsResponse = response.getSpecsResponse(); return specsResponse.getDetailsList().stream().map(Api.SpecsResponse.SpecDetail::getSpec).collect(Collectors.toList()); } catch (IOException e) { // TODO logger return emptyList(); } } private static Api.APIMessage getSpecApiMessage() { Api.SpecsRequest spec = Api.SpecsRequest.newBuilder().build(); return newBuilder().setMessageType(Api.APIMessage.APIMessageType.SpecsRequest) .setMessageId(2) .setSpecsRequest(spec) .build(); } private static Api.APIMessage getAPIResponse(Api.APIMessage message, Socket gaugeSocket) throws IOException { try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { CodedOutputStream cos = CodedOutputStream.newInstance(stream); byte[] bytes = message.toByteArray(); cos.writeRawVarint64(bytes.length); cos.flush(); stream.write(bytes); synchronized (gaugeSocket) { gaugeSocket.getOutputStream().write(stream.toByteArray()); gaugeSocket.getOutputStream().flush(); InputStream remoteStream = gaugeSocket.getInputStream(); bytes = toBytes(getMessageLength(remoteStream)); } return Api.APIMessage.parseFrom(bytes); } } private static byte[] toBytes(MessageLength messageLength) throws IOException { long messageSize = messageLength.getLength(); CodedInputStream stream = messageLength.getRemainingStream(); try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { for (int i = 0; i < messageSize; i++) { outputStream.write(stream.readRawByte()); } return outputStream.toByteArray(); } } private static MessageLength getMessageLength(InputStream is) throws IOException { CodedInputStream codedInputStream = CodedInputStream.newInstance(is); long size = codedInputStream.readRawVarint64(); return new MessageLength(size, codedInputStream); } }
923ee00071c9148c7b04e1a1678c6a5c784db5cb
1,325
java
Java
backend/src/main/java/de/learnlib/alex/testing/repositories/TestExecutionResultRepository.java
dattapubali/alex
aac26a466156c22523ecd6636a169d31d5b73172
[ "Apache-2.0" ]
null
null
null
backend/src/main/java/de/learnlib/alex/testing/repositories/TestExecutionResultRepository.java
dattapubali/alex
aac26a466156c22523ecd6636a169d31d5b73172
[ "Apache-2.0" ]
null
null
null
backend/src/main/java/de/learnlib/alex/testing/repositories/TestExecutionResultRepository.java
dattapubali/alex
aac26a466156c22523ecd6636a169d31d5b73172
[ "Apache-2.0" ]
null
null
null
33.974359
97
0.743396
1,000,948
/* * Copyright 2015 - 2019 TU Dortmund * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.learnlib.alex.testing.repositories; import de.learnlib.alex.testing.entities.TestExecutionResult; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; /** The repository for test results. */ @Repository public interface TestExecutionResultRepository extends JpaRepository<TestExecutionResult, Long> { /** * Count all results by used symbol ID. * * @param symbolId * The ID of the symbol. * @return The count. */ @Transactional(readOnly = true) @SuppressWarnings("checkstyle:methodname") Long countAllBySymbol_Id(Long symbolId); }
923ee1d786e83953fe9a7b27fce7086fef57969e
2,326
java
Java
core/src/test/groovy/org/telluriumsource/ft/TableRowTestCase.java
XuefengWu/aost
470b9171496bfd3ef57de247d018270f3e22c848
[ "Apache-2.0" ]
1
2020-08-17T17:48:22.000Z
2020-08-17T17:48:22.000Z
core/src/test/groovy/org/telluriumsource/ft/TableRowTestCase.java
XuefengWu/aost
470b9171496bfd3ef57de247d018270f3e22c848
[ "Apache-2.0" ]
null
null
null
core/src/test/groovy/org/telluriumsource/ft/TableRowTestCase.java
XuefengWu/aost
470b9171496bfd3ef57de247d018270f3e22c848
[ "Apache-2.0" ]
null
null
null
24.557895
67
0.630947
1,000,949
package org.telluriumsource.ft; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.telluriumsource.module.TableRowModule; import org.telluriumsource.test.java.TelluriumMockJUnitTestCase; import static org.junit.Assert.assertEquals; /** * @author Jian Fang ([email protected]) * * Date: Nov 2, 2010 */ public class TableRowTestCase extends TelluriumMockJUnitTestCase { private static TableRowModule trm; @BeforeClass public static void initUi() { registerHtmlBody("TableRow"); trm = new TableRowModule(); trm.defineUi(); useCssSelector(true); useEngineLog(true); } @Before public void connectToLocal() { connect("TableRow"); useTelluriumEngine(false); } @Test public void testWithCSS(){ int row = trm.getTableMaxRowNum("data"); assertEquals(5, row); int colum = trm.getTableMaxColumnNum("data"); assertEquals(5, colum); } @Test public void testWithEngine(){ useTelluriumEngine(true); int row = trm.getTableMaxRowNum("data"); assertEquals(5, row); int colum = trm.getTableMaxColumnNum("data"); assertEquals(5, colum); } @Test public void testSelfWithCSS(){ int row = trm.getTableMaxRowNum("data1"); assertEquals(5, row); int colum = trm.getTableMaxColumnNum("data1"); assertEquals(5, colum); } @Test public void testSelfWithEngine(){ useTelluriumEngine(true); int row = trm.getTableMaxRowNum("data1"); assertEquals(5, row); int colum = trm.getTableMaxColumnNum("data1"); assertEquals(5, colum); } @Test public void testGeneralWithCSS(){ int row = trm.getTableMaxRowNum("Table"); assertEquals(5, row); int colum = trm.getTableMaxColumnNum("Table"); assertEquals(5, colum); } @Test public void testGeneralWithEngine(){ useTelluriumEngine(true); int row = trm.getTableMaxRowNum("Table"); assertEquals(5, row); int colum = trm.getTableMaxColumnNum("Table"); assertEquals(5, colum); } @AfterClass public static void tearDown(){ showTrace(); } }
923ee1e9d915f37a59a7bec8e806534cac067438
2,249
java
Java
presto-main/src/main/java/io/prestosql/server/ui/FixedUserWebUiAuthenticationManager.java
utk-spartan/falarica-presto-gateway
e6fe1402702e63c7479a42978e8179da11697067
[ "Apache-2.0" ]
1
2021-08-14T15:28:31.000Z
2021-08-14T15:28:31.000Z
presto-main/src/main/java/io/prestosql/server/ui/FixedUserWebUiAuthenticationManager.java
utk-spartan/falarica-presto-gateway
e6fe1402702e63c7479a42978e8179da11697067
[ "Apache-2.0" ]
5
2021-08-09T21:00:36.000Z
2022-02-16T01:12:53.000Z
presto-main/src/main/java/io/prestosql/server/ui/FixedUserWebUiAuthenticationManager.java
utk-spartan/falarica-presto-gateway
e6fe1402702e63c7479a42978e8179da11697067
[ "Apache-2.0" ]
null
null
null
34.075758
113
0.750556
1,000,950
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.server.ui; import io.prestosql.spi.security.BasicPrincipal; import io.prestosql.spi.security.Identity; import javax.inject.Inject; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import static io.prestosql.server.ServletSecurityUtils.withAuthenticatedIdentity; import static io.prestosql.server.ui.FormWebUiAuthenticationManager.redirectAllFormLoginToUi; import static java.util.Objects.requireNonNull; public class FixedUserWebUiAuthenticationManager implements WebUiAuthenticationManager { private final Identity webUiIdentity; @Inject public FixedUserWebUiAuthenticationManager(FixedUserWebUiConfig config) { this(basicIdentity(requireNonNull(config, "config is null").getUsername())); } public FixedUserWebUiAuthenticationManager(Identity webUiIdentity) { this.webUiIdentity = requireNonNull(webUiIdentity, "webUiIdentity is null"); } @Override public void handleUiRequest(HttpServletRequest request, HttpServletResponse response, FilterChain nextFilter) throws IOException, ServletException { if (redirectAllFormLoginToUi(request, response)) { return; } withAuthenticatedIdentity(nextFilter, request, response, webUiIdentity); } private static Identity basicIdentity(String username) { requireNonNull(username, "username is null"); return Identity.forUser(username) .withPrincipal(new BasicPrincipal(username)) .build(); } }
923ee1f81e4271fe85a5a6c96617f6f9d84dc770
796
java
Java
src/main/java/com/microsoft/store/partnercenter/models/products/ProductLinks.java
epinter/Partner-Center-Java
4a05288ec99477f45b34f21cb8a7f0044c8caa10
[ "MIT" ]
null
null
null
src/main/java/com/microsoft/store/partnercenter/models/products/ProductLinks.java
epinter/Partner-Center-Java
4a05288ec99477f45b34f21cb8a7f0044c8caa10
[ "MIT" ]
null
null
null
src/main/java/com/microsoft/store/partnercenter/models/products/ProductLinks.java
epinter/Partner-Center-Java
4a05288ec99477f45b34f21cb8a7f0044c8caa10
[ "MIT" ]
null
null
null
24.875
74
0.55402
1,000,951
// ----------------------------------------------------------------------- // <copyright file="ProductLinks.java" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // ----------------------------------------------------------------------- package com.microsoft.store.partnercenter.models.products; import com.microsoft.store.partnercenter.models.Link; import com.microsoft.store.partnercenter.models.StandardResourceLinks; /** * Navigation links for Product. */ public class ProductLinks extends StandardResourceLinks { /** * Gets or sets the skus link. */ private Link __Skus; public Link getSkus() { return __Skus; } public void setSkus( Link value ) { __Skus = value; } }
923ee44ad77926b5bd70efc5532f92f11245b7c9
3,911
java
Java
vrealize-automation-content-generator-core/src/main/java/com/vmware/devops/model/codestream/WebhookNotification.java
vmware-samples/vrealize-automation-content-generator
d64c1059414fa7ad7c5587b07ca8781baf373390
[ "BSD-2-Clause" ]
5
2021-07-06T12:42:30.000Z
2022-03-28T09:23:04.000Z
vrealize-automation-content-generator-core/src/main/java/com/vmware/devops/model/codestream/WebhookNotification.java
vmware-samples/vrealize-automation-content-generator
d64c1059414fa7ad7c5587b07ca8781baf373390
[ "BSD-2-Clause" ]
2
2021-12-10T14:07:30.000Z
2022-01-04T16:51:57.000Z
vrealize-automation-content-generator-core/src/main/java/com/vmware/devops/model/codestream/WebhookNotification.java
vmware-samples/vrealize-automation-content-generator
d64c1059414fa7ad7c5587b07ca8781baf373390
[ "BSD-2-Clause" ]
1
2021-12-23T13:28:59.000Z
2021-12-23T13:28:59.000Z
32.057377
111
0.665303
1,000,952
/* * Copyright 2021-2021 VMware, Inc. * SPDX-License-Identifier: BSD-2-Clause */ package com.vmware.devops.model.codestream; import java.io.IOException; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import com.vmware.devops.GenerationContext; import com.vmware.devops.IdCache; import com.vmware.devops.ReverseGenerationContext; import com.vmware.devops.client.codestream.CodestreamClient; import com.vmware.devops.client.codestream.stubs.Notification.Event; import com.vmware.devops.client.codestream.stubs.Notification.Type; import com.vmware.devops.client.codestream.stubs.Notification.WebhookNotificaton; import com.vmware.devops.client.codestream.stubs.Notification.WebhookNotificaton.WebhookAction; /** * WebhookNotification represent entity that implements {@link com.vmware.devops.model.codestream.Notification} * and specify Pipeline Notification of type Webhook. */ @Builder @Data @AllArgsConstructor @NoArgsConstructor public class WebhookNotification implements Notification<com.vmware.devops.client.codestream.stubs.Notification.WebhookNotificaton> { /** * The url of the webhook */ private String url; /** * Id of the cloud proxy which to be used for the webhook */ @Builder.Default private String cloudProxy = GenerationContext.getInstance().getGlobalConfiguration() .getDefaultCloudProxy(); /** * Headers of the webhook. * <p> * By default not headers are attached to the request. */ @Builder.Default private Map<String, String> headers = new HashMap<>(); /** * The payload of the webhook. */ @Builder.Default private String payload = ""; /** * The event on which the notification to be triggered. * <p> * See {@link com.vmware.devops.client.codestream.stubs.Notification.Event */ @Builder.Default private Event event = Event.FAILURE; /** * Webhook Action of the task * <p> * By default action is POST. * See {@link com.vmware.devops.client.codestream.stubs.Notification.WebhookNotificaton.WebhookAction} */ @Builder.Default private WebhookAction action = WebhookAction.POST; @Override public Type getType() { return Type.WEBHOOK; } @Override public com.vmware.devops.client.codestream.stubs.Notification initializeNotification() { String cloudProxyId = null; if (cloudProxy != null) { try { cloudProxyId = IdCache.CODESTREAM_CLOUD_PROXY_ID_CACHE.getId(cloudProxy); } catch (InterruptedException | IOException | URISyntaxException e) { throw new RuntimeException(e); } } return com.vmware.devops.client.codestream.stubs.Notification.WebhookNotificaton.builder() .event(event) .action(action) .url(url) .headers(headers) .payload(payload) .cloudProxyId(cloudProxyId) .build(); } @Override public void populateData(WebhookNotificaton notification) { this.action = notification.getAction(); if (notification.getCloudProxyId() != null) { this.cloudProxy = CodestreamClient .getProxyName(ReverseGenerationContext.getInstance().getVraExportedData() .getCloudProxies().stream() .filter(c -> c.getId().equals(notification.getCloudProxyId())).findFirst() .get()); } this.event = notification.getEvent(); this.headers = notification.getHeaders(); this.payload = notification.getPayload(); this.url = notification.getUrl(); } }
923ee47e9d19cb5f5fa28b70633a46eec974061b
292
java
Java
lecs/src/com/prafaelo/lecs/system/user/Anonymous.java
prafaelo/lecs
f5c7b92af90d2d052beb88b23eb50dc0c76e9bd0
[ "MIT" ]
1
2015-09-08T00:57:40.000Z
2015-09-08T00:57:40.000Z
lecs/src/com/prafaelo/lecs/system/user/Anonymous.java
prafaelo/lecs
f5c7b92af90d2d052beb88b23eb50dc0c76e9bd0
[ "MIT" ]
null
null
null
lecs/src/com/prafaelo/lecs/system/user/Anonymous.java
prafaelo/lecs
f5c7b92af90d2d052beb88b23eb50dc0c76e9bd0
[ "MIT" ]
null
null
null
20.857143
53
0.787671
1,000,953
package com.prafaelo.lecs.system.user; import com.prafaelo.lecs.system.auth.Authenticatable; import com.prafaelo.lecs.ui.BasicMenu; import com.prafaelo.lecs.ui.Menu; public class Anonymous implements Authenticatable{ @Override public Menu authenticate() { return new BasicMenu(); } }
923ee4a4eb52f833ae9fa3c1b8f033e4e50b0172
1,760
java
Java
idea/src/org/jetbrains/kotlin/idea/codeInsight/surroundWith/KotlinSurrounderUtils.java
typeinference/kotlin
72a84083fbe50d3d12226925b94ed0fe86c9d794
[ "Apache-2.0" ]
7
2017-06-13T03:01:04.000Z
2021-04-22T03:01:06.000Z
idea/src/org/jetbrains/kotlin/idea/codeInsight/surroundWith/KotlinSurrounderUtils.java
typeinference/kotlin
72a84083fbe50d3d12226925b94ed0fe86c9d794
[ "Apache-2.0" ]
null
null
null
idea/src/org/jetbrains/kotlin/idea/codeInsight/surroundWith/KotlinSurrounderUtils.java
typeinference/kotlin
72a84083fbe50d3d12226925b94ed0fe86c9d794
[ "Apache-2.0" ]
4
2019-06-24T07:33:49.000Z
2020-04-21T21:52:37.000Z
38.26087
113
0.754545
1,000,954
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.idea.codeInsight.surroundWith; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.kotlin.idea.KotlinBundle; import org.jetbrains.kotlin.idea.codeInsight.CodeInsightUtils; import org.jetbrains.kotlin.psi.KtBlockExpression; public class KotlinSurrounderUtils { public static String SURROUND_WITH = KotlinBundle.message("surround.with"); public static String SURROUND_WITH_ERROR = KotlinBundle.message("surround.with.cannot.perform.action"); private KotlinSurrounderUtils() { } public static void addStatementsInBlock( @NotNull KtBlockExpression block, @NotNull PsiElement[] statements ) { PsiElement lBrace = block.getFirstChild(); block.addRangeAfter(statements[0], statements[statements.length - 1], lBrace); } public static void showErrorHint(@NotNull Project project, @NotNull Editor editor, @NotNull String message) { CodeInsightUtils.showErrorHint(project, editor, message, SURROUND_WITH, null); } }
923ee579e4e2b11e489f8c091a5485611695a81b
905
java
Java
src/main/java/com/wthfeng/learn/lang/BucketSort.java
wangtonghe/learn-sample
121b9e4ce32b0d86f8d1e1a098627ce5f5fd5115
[ "Apache-2.0" ]
null
null
null
src/main/java/com/wthfeng/learn/lang/BucketSort.java
wangtonghe/learn-sample
121b9e4ce32b0d86f8d1e1a098627ce5f5fd5115
[ "Apache-2.0" ]
null
null
null
src/main/java/com/wthfeng/learn/lang/BucketSort.java
wangtonghe/learn-sample
121b9e4ce32b0d86f8d1e1a098627ce5f5fd5115
[ "Apache-2.0" ]
null
null
null
21.547619
50
0.436464
1,000,955
package com.wthfeng.learn.lang; import org.junit.Test; import java.util.Arrays; /** * @author wangtonghe * @date 2017/10/11 19:26 */ public class BucketSort { public int[] sort(int[] arr, int sum) { int length = arr.length; int[] bucket = new int[sum]; for (int i = 0; i < length; i++) { bucket[arr[i]]++; } int[] result = new int[length]; int index = 0; for (int i = 0; i < sum; i++) { if (bucket[i] > 0) { int num = bucket[i]; for (int j = 0; j < num; j++) { result[index] = i; index++; } } } return result; } @Test public void test() { int[] arr = {3, 4, 8, 1, 2, 6, 5, 9, 7}; int[] arr2 = sort(arr, 10); System.out.println(Arrays.toString(arr2)); } }
923ee5cdce23edcea5afa9bd25c711086dc86a81
18,663
java
Java
das-client/src/main/java/com/ppdai/das/service/DasBatchQueryBuilder.java
ppdaicorp/das
44ed69f0c0a79eb23234193fdfef80ce54ee2676
[ "Apache-2.0" ]
170
2019-10-14T05:41:51.000Z
2022-03-11T06:17:39.000Z
das-client/src/main/java/com/ppdai/das/service/DasBatchQueryBuilder.java
ppdaicorp/das
44ed69f0c0a79eb23234193fdfef80ce54ee2676
[ "Apache-2.0" ]
11
2019-11-06T09:44:08.000Z
2021-01-25T08:20:58.000Z
das-client/src/main/java/com/ppdai/das/service/DasBatchQueryBuilder.java
ppdaicorp/das
44ed69f0c0a79eb23234193fdfef80ce54ee2676
[ "Apache-2.0" ]
56
2019-10-18T07:56:28.000Z
2022-03-25T07:21:08.000Z
34.370166
189
0.674007
1,000,956
/** * Autogenerated by Thrift Compiler (0.12.0) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package com.ppdai.das.service; @SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"}) @javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.12.0)", date = "2020-11-13") public class DasBatchQueryBuilder implements org.apache.thrift.TBase<DasBatchQueryBuilder, DasBatchQueryBuilder._Fields>, java.io.Serializable, Cloneable, Comparable<DasBatchQueryBuilder> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("DasBatchQueryBuilder"); private static final org.apache.thrift.protocol.TField SQL_BUILDERS_FIELD_DESC = new org.apache.thrift.protocol.TField("sqlBuilders", org.apache.thrift.protocol.TType.LIST, (short)1); private static final org.apache.thrift.protocol.TField ENTITY_META_FIELD_DESC = new org.apache.thrift.protocol.TField("entityMeta", org.apache.thrift.protocol.TType.STRUCT, (short)2); private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new DasBatchQueryBuilderStandardSchemeFactory(); private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new DasBatchQueryBuilderTupleSchemeFactory(); public @org.apache.thrift.annotation.Nullable java.util.List<DasSqlBuilder> sqlBuilders; // optional public @org.apache.thrift.annotation.Nullable EntityMeta entityMeta; // optional /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SQL_BUILDERS((short)1, "sqlBuilders"), ENTITY_META((short)2, "entityMeta"); private static final java.util.Map<String, _Fields> byName = new java.util.HashMap<String, _Fields>(); static { for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ @org.apache.thrift.annotation.Nullable public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // SQL_BUILDERS return SQL_BUILDERS; case 2: // ENTITY_META return ENTITY_META; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ @org.apache.thrift.annotation.Nullable public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final _Fields optionals[] = {_Fields.SQL_BUILDERS,_Fields.ENTITY_META}; public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SQL_BUILDERS, new org.apache.thrift.meta_data.FieldMetaData("sqlBuilders", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, DasSqlBuilder.class)))); tmpMap.put(_Fields.ENTITY_META, new org.apache.thrift.meta_data.FieldMetaData("entityMeta", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, EntityMeta.class))); metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(DasBatchQueryBuilder.class, metaDataMap); } public DasBatchQueryBuilder() { } /** * Performs a deep copy on <i>other</i>. */ public DasBatchQueryBuilder(DasBatchQueryBuilder other) { if (other.isSetSqlBuilders()) { java.util.List<DasSqlBuilder> __this__sqlBuilders = new java.util.ArrayList<DasSqlBuilder>(other.sqlBuilders.size()); for (DasSqlBuilder other_element : other.sqlBuilders) { __this__sqlBuilders.add(new DasSqlBuilder(other_element)); } this.sqlBuilders = __this__sqlBuilders; } if (other.isSetEntityMeta()) { this.entityMeta = new EntityMeta(other.entityMeta); } } public DasBatchQueryBuilder deepCopy() { return new DasBatchQueryBuilder(this); } @Override public void clear() { this.sqlBuilders = null; this.entityMeta = null; } public int getSqlBuildersSize() { return (this.sqlBuilders == null) ? 0 : this.sqlBuilders.size(); } @org.apache.thrift.annotation.Nullable public java.util.Iterator<DasSqlBuilder> getSqlBuildersIterator() { return (this.sqlBuilders == null) ? null : this.sqlBuilders.iterator(); } public void addToSqlBuilders(DasSqlBuilder elem) { if (this.sqlBuilders == null) { this.sqlBuilders = new java.util.ArrayList<DasSqlBuilder>(); } this.sqlBuilders.add(elem); } @org.apache.thrift.annotation.Nullable public java.util.List<DasSqlBuilder> getSqlBuilders() { return this.sqlBuilders; } public DasBatchQueryBuilder setSqlBuilders(@org.apache.thrift.annotation.Nullable java.util.List<DasSqlBuilder> sqlBuilders) { this.sqlBuilders = sqlBuilders; return this; } public void unsetSqlBuilders() { this.sqlBuilders = null; } /** Returns true if field sqlBuilders is set (has been assigned a value) and false otherwise */ public boolean isSetSqlBuilders() { return this.sqlBuilders != null; } public void setSqlBuildersIsSet(boolean value) { if (!value) { this.sqlBuilders = null; } } @org.apache.thrift.annotation.Nullable public EntityMeta getEntityMeta() { return this.entityMeta; } public DasBatchQueryBuilder setEntityMeta(@org.apache.thrift.annotation.Nullable EntityMeta entityMeta) { this.entityMeta = entityMeta; return this; } public void unsetEntityMeta() { this.entityMeta = null; } /** Returns true if field entityMeta is set (has been assigned a value) and false otherwise */ public boolean isSetEntityMeta() { return this.entityMeta != null; } public void setEntityMetaIsSet(boolean value) { if (!value) { this.entityMeta = null; } } public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable Object value) { switch (field) { case SQL_BUILDERS: if (value == null) { unsetSqlBuilders(); } else { setSqlBuilders((java.util.List<DasSqlBuilder>)value); } break; case ENTITY_META: if (value == null) { unsetEntityMeta(); } else { setEntityMeta((EntityMeta)value); } break; } } @org.apache.thrift.annotation.Nullable public Object getFieldValue(_Fields field) { switch (field) { case SQL_BUILDERS: return getSqlBuilders(); case ENTITY_META: return getEntityMeta(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SQL_BUILDERS: return isSetSqlBuilders(); case ENTITY_META: return isSetEntityMeta(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof DasBatchQueryBuilder) return this.equals((DasBatchQueryBuilder)that); return false; } public boolean equals(DasBatchQueryBuilder that) { if (that == null) return false; if (this == that) return true; boolean this_present_sqlBuilders = true && this.isSetSqlBuilders(); boolean that_present_sqlBuilders = true && that.isSetSqlBuilders(); if (this_present_sqlBuilders || that_present_sqlBuilders) { if (!(this_present_sqlBuilders && that_present_sqlBuilders)) return false; if (!this.sqlBuilders.equals(that.sqlBuilders)) return false; } boolean this_present_entityMeta = true && this.isSetEntityMeta(); boolean that_present_entityMeta = true && that.isSetEntityMeta(); if (this_present_entityMeta || that_present_entityMeta) { if (!(this_present_entityMeta && that_present_entityMeta)) return false; if (!this.entityMeta.equals(that.entityMeta)) return false; } return true; } @Override public int hashCode() { int hashCode = 1; hashCode = hashCode * 8191 + ((isSetSqlBuilders()) ? 131071 : 524287); if (isSetSqlBuilders()) hashCode = hashCode * 8191 + sqlBuilders.hashCode(); hashCode = hashCode * 8191 + ((isSetEntityMeta()) ? 131071 : 524287); if (isSetEntityMeta()) hashCode = hashCode * 8191 + entityMeta.hashCode(); return hashCode; } @Override public int compareTo(DasBatchQueryBuilder other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSqlBuilders()).compareTo(other.isSetSqlBuilders()); if (lastComparison != 0) { return lastComparison; } if (isSetSqlBuilders()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.sqlBuilders, other.sqlBuilders); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEntityMeta()).compareTo(other.isSetEntityMeta()); if (lastComparison != 0) { return lastComparison; } if (isSetEntityMeta()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.entityMeta, other.entityMeta); if (lastComparison != 0) { return lastComparison; } } return 0; } @org.apache.thrift.annotation.Nullable public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { scheme(iprot).read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { scheme(oprot).write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("DasBatchQueryBuilder("); boolean first = true; if (isSetSqlBuilders()) { sb.append("sqlBuilders:"); if (this.sqlBuilders == null) { sb.append("null"); } else { sb.append(this.sqlBuilders); } first = false; } if (isSetEntityMeta()) { if (!first) sb.append(", "); sb.append("entityMeta:"); if (this.entityMeta == null) { sb.append("null"); } else { sb.append(this.entityMeta); } first = false; } sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (entityMeta != null) { entityMeta.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class DasBatchQueryBuilderStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { public DasBatchQueryBuilderStandardScheme getScheme() { return new DasBatchQueryBuilderStandardScheme(); } } private static class DasBatchQueryBuilderStandardScheme extends org.apache.thrift.scheme.StandardScheme<DasBatchQueryBuilder> { public void read(org.apache.thrift.protocol.TProtocol iprot, DasBatchQueryBuilder struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // SQL_BUILDERS if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list118 = iprot.readListBegin(); struct.sqlBuilders = new java.util.ArrayList<DasSqlBuilder>(_list118.size); @org.apache.thrift.annotation.Nullable DasSqlBuilder _elem119; for (int _i120 = 0; _i120 < _list118.size; ++_i120) { _elem119 = new DasSqlBuilder(); _elem119.read(iprot); struct.sqlBuilders.add(_elem119); } iprot.readListEnd(); } struct.setSqlBuildersIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // ENTITY_META if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.entityMeta = new EntityMeta(); struct.entityMeta.read(iprot); struct.setEntityMetaIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, DasBatchQueryBuilder struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.sqlBuilders != null) { if (struct.isSetSqlBuilders()) { oprot.writeFieldBegin(SQL_BUILDERS_FIELD_DESC); { oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.sqlBuilders.size())); for (DasSqlBuilder _iter121 : struct.sqlBuilders) { _iter121.write(oprot); } oprot.writeListEnd(); } oprot.writeFieldEnd(); } } if (struct.entityMeta != null) { if (struct.isSetEntityMeta()) { oprot.writeFieldBegin(ENTITY_META_FIELD_DESC); struct.entityMeta.write(oprot); oprot.writeFieldEnd(); } } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class DasBatchQueryBuilderTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { public DasBatchQueryBuilderTupleScheme getScheme() { return new DasBatchQueryBuilderTupleScheme(); } } private static class DasBatchQueryBuilderTupleScheme extends org.apache.thrift.scheme.TupleScheme<DasBatchQueryBuilder> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, DasBatchQueryBuilder struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; java.util.BitSet optionals = new java.util.BitSet(); if (struct.isSetSqlBuilders()) { optionals.set(0); } if (struct.isSetEntityMeta()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSqlBuilders()) { { oprot.writeI32(struct.sqlBuilders.size()); for (DasSqlBuilder _iter122 : struct.sqlBuilders) { _iter122.write(oprot); } } } if (struct.isSetEntityMeta()) { struct.entityMeta.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, DasBatchQueryBuilder struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; java.util.BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { { org.apache.thrift.protocol.TList _list123 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32()); struct.sqlBuilders = new java.util.ArrayList<DasSqlBuilder>(_list123.size); @org.apache.thrift.annotation.Nullable DasSqlBuilder _elem124; for (int _i125 = 0; _i125 < _list123.size; ++_i125) { _elem124 = new DasSqlBuilder(); _elem124.read(iprot); struct.sqlBuilders.add(_elem124); } } struct.setSqlBuildersIsSet(true); } if (incoming.get(1)) { struct.entityMeta = new EntityMeta(); struct.entityMeta.read(iprot); struct.setEntityMetaIsSet(true); } } } private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) { return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); } }
923ee5fbc3d3e2776bdbef6250d0540d0860ed1c
1,414
java
Java
src/main/java/com/wizzardo/http/framework/WebWorker.java
wizzardo/webery
00bbc4da690a7ca6afdd1a0c57513a9bc43dbf0b
[ "MIT" ]
119
2019-03-01T10:22:54.000Z
2022-03-28T08:44:53.000Z
src/main/java/com/wizzardo/http/framework/WebWorker.java
wizzardo/webery
00bbc4da690a7ca6afdd1a0c57513a9bc43dbf0b
[ "MIT" ]
2
2020-06-10T09:15:46.000Z
2021-05-25T12:44:03.000Z
src/main/java/com/wizzardo/http/framework/WebWorker.java
wizzardo/webery
00bbc4da690a7ca6afdd1a0c57513a9bc43dbf0b
[ "MIT" ]
10
2019-04-26T14:00:44.000Z
2021-11-10T06:53:11.000Z
22.09375
108
0.663366
1,000,957
package com.wizzardo.http.framework; import com.wizzardo.http.AbstractHttpServer; import com.wizzardo.http.HttpConnection; import com.wizzardo.http.HttpWorker; import java.util.concurrent.BlockingQueue; /** * Created by wizzardo on 28.04.15. */ public class WebWorker<T extends HttpConnection> extends HttpWorker<T> implements RequestContext { protected RequestHolder requestHolder = new RequestHolder(); protected String controller; protected String action; protected String handler; public WebWorker(AbstractHttpServer<T> server, ThreadGroup group, BlockingQueue<T> queue, String name) { super(server, group, queue, name); } @Override public RequestHolder getRequestHolder() { return requestHolder; } @Override public String controller() { return controller; } @Override public String action() { return action; } @Override public void setController(String controller) { this.controller = controller; } @Override public void setAction(String action) { this.action = action; } @Override public void reset() { action = null; controller = null; requestHolder.reset(); } @Override public void handler(String name) { this.handler = name; } @Override public String handler() { return handler; } }
923ee609bcc1b6d0e71d412fb7a147d8eb7cc491
1,499
java
Java
testing/fakedata/applib/src/main/java/org/apache/isis/testing/fakedata/applib/services/Floats.java
ecpnv-devops/isis
aeda00974e293e2792783090360b155a9d1a6624
[ "Apache-2.0" ]
665
2015-01-01T06:06:28.000Z
2022-03-27T01:11:56.000Z
testing/fakedata/applib/src/main/java/org/apache/isis/testing/fakedata/applib/services/Floats.java
jalexmelendez/isis
ddf3bd186cad585b959b7f20d8c9ac5e3f33263d
[ "Apache-2.0" ]
176
2015-02-07T11:29:36.000Z
2022-03-25T04:43:12.000Z
testing/fakedata/applib/src/main/java/org/apache/isis/testing/fakedata/applib/services/Floats.java
jalexmelendez/isis
ddf3bd186cad585b959b7f20d8c9ac5e3f33263d
[ "Apache-2.0" ]
337
2015-01-02T03:01:34.000Z
2022-03-21T15:56:28.000Z
34.068182
83
0.703803
1,000,958
/* * 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.isis.testing.fakedata.applib.services; import org.apache.commons.lang3.RandomUtils; /** * Returns random <code>float</code> values, optionally constrained within a range, * * @since 2.0 {@index} */ public class Floats extends AbstractRandomValueGenerator { public Floats(final FakeDataService fakeDataService) { super(fakeDataService); } public float any() { return fake.booleans().coinFlip() ? RandomUtils.nextFloat() * Float.MAX_VALUE : -RandomUtils.nextFloat() * Float.MAX_VALUE; } public float upTo(final float max) { return RandomUtils.nextFloat() * max; } }
923ee64918bd022199f08cac1a8e6cfa5b51f137
13,588
java
Java
itext/src/main/java/com/itextpdf/text/pdf/internal/PdfViewerPreferencesImp.java
luiguik2/itextpdf
88737e7182ee6829084f53e233145f8616b2e7ee
[ "RSA-MD" ]
1,459
2015-01-10T17:57:47.000Z
2022-03-27T19:07:45.000Z
itext/src/main/java/com/itextpdf/text/pdf/internal/PdfViewerPreferencesImp.java
zwdwww/itextpdf
43bf5b7cce6a7021ef6b44a992ac94d8df02db64
[ "RSA-MD" ]
42
2015-04-14T11:50:27.000Z
2022-01-12T22:17:57.000Z
itext/src/main/java/com/itextpdf/text/pdf/internal/PdfViewerPreferencesImp.java
zwdwww/itextpdf
43bf5b7cce6a7021ef6b44a992ac94d8df02db64
[ "RSA-MD" ]
527
2015-01-20T14:32:06.000Z
2022-03-21T06:05:16.000Z
38.064426
92
0.729193
1,000,959
/* * * This file is part of the iText (R) project. Copyright (c) 1998-2020 iText Group NV * Authors: Bruno Lowagie, Paulo Soares, et al. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License version 3 * as published by the Free Software Foundation with the addition of the * following permission added to Section 15 as permitted in Section 7(a): * FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY * ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT * OF THIRD PARTY RIGHTS * * 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 Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA, 02110-1301 USA, or download the license from the following URL: * http://itextpdf.com/terms-of-use/ * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License. * * In accordance with Section 7(b) of the GNU Affero General Public License, * a covered work must retain the producer line in every PDF that is created * or manipulated using iText. * * You can be released from the requirements of the license by purchasing * a commercial license. Buying such a license is mandatory as soon as you * develop commercial activities involving the iText software without * disclosing the source code of your own applications. * These activities include: offering paid services to customers as an ASP, * serving PDFs on the fly in a web application, shipping iText with a closed * source product. * * For more information, please contact iText Software Corp. at this * address: [email protected] */ package com.itextpdf.text.pdf.internal; import com.itextpdf.text.pdf.PdfArray; import com.itextpdf.text.pdf.PdfBoolean; import com.itextpdf.text.pdf.PdfDictionary; import com.itextpdf.text.pdf.PdfName; import com.itextpdf.text.pdf.PdfNumber; import com.itextpdf.text.pdf.PdfObject; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfWriter; import com.itextpdf.text.pdf.interfaces.PdfViewerPreferences; /** * Stores the information concerning viewer preferences, * and contains the business logic that allows you to set viewer preferences. */ public class PdfViewerPreferencesImp implements PdfViewerPreferences { public static final PdfName[] VIEWER_PREFERENCES = { PdfName.HIDETOOLBAR, // 0 PdfName.HIDEMENUBAR, // 1 PdfName.HIDEWINDOWUI, // 2 PdfName.FITWINDOW, // 3 PdfName.CENTERWINDOW, // 4 PdfName.DISPLAYDOCTITLE, // 5 PdfName.NONFULLSCREENPAGEMODE, // 6 PdfName.DIRECTION, // 7 PdfName.VIEWAREA, // 8 PdfName.VIEWCLIP, // 9 PdfName.PRINTAREA, // 10 PdfName.PRINTCLIP, // 11 PdfName.PRINTSCALING, // 12 PdfName.DUPLEX, // 13 PdfName.PICKTRAYBYPDFSIZE, // 14 PdfName.PRINTPAGERANGE, // 15 PdfName.NUMCOPIES // 16 }; /** A series of viewer preferences. */ public static final PdfName NONFULLSCREENPAGEMODE_PREFERENCES[] = { PdfName.USENONE, PdfName.USEOUTLINES, PdfName.USETHUMBS, PdfName.USEOC }; /** A series of viewer preferences. */ public static final PdfName DIRECTION_PREFERENCES[] = { PdfName.L2R, PdfName.R2L }; /** A series of viewer preferences. */ public static final PdfName PAGE_BOUNDARIES[] = { PdfName.MEDIABOX, PdfName.CROPBOX, PdfName.BLEEDBOX, PdfName.TRIMBOX, PdfName.ARTBOX }; /** A series of viewer preferences */ public static final PdfName PRINTSCALING_PREFERENCES[] = { PdfName.APPDEFAULT, PdfName.NONE }; /** A series of viewer preferences. */ public static final PdfName DUPLEX_PREFERENCES[] = { PdfName.SIMPLEX, PdfName.DUPLEXFLIPSHORTEDGE, PdfName.DUPLEXFLIPLONGEDGE }; /** This value will hold the viewer preferences for the page layout and page mode. */ private int pageLayoutAndMode = 0; /** This dictionary holds the viewer preferences (other than page layout and page mode). */ private PdfDictionary viewerPreferences = new PdfDictionary(); /** The mask to decide if a ViewerPreferences dictionary is needed */ private static final int viewerPreferencesMask = 0xfff000; /** * Returns the page layout and page mode value. */ public int getPageLayoutAndMode() { return pageLayoutAndMode; } /** * Returns the viewer preferences. */ public PdfDictionary getViewerPreferences() { return viewerPreferences; } /** * Sets the viewer preferences as the sum of several constants. * * @param preferences * the viewer preferences * @see PdfViewerPreferences#setViewerPreferences */ public void setViewerPreferences(int preferences) { this.pageLayoutAndMode |= preferences; // for backwards compatibility, it is also possible // to set the following viewer preferences with this method: if ((preferences & viewerPreferencesMask) != 0) { pageLayoutAndMode = ~viewerPreferencesMask & pageLayoutAndMode; if ((preferences & PdfWriter.HideToolbar) != 0) viewerPreferences.put(PdfName.HIDETOOLBAR, PdfBoolean.PDFTRUE); if ((preferences & PdfWriter.HideMenubar) != 0) viewerPreferences.put(PdfName.HIDEMENUBAR, PdfBoolean.PDFTRUE); if ((preferences & PdfWriter.HideWindowUI) != 0) viewerPreferences.put(PdfName.HIDEWINDOWUI, PdfBoolean.PDFTRUE); if ((preferences & PdfWriter.FitWindow) != 0) viewerPreferences.put(PdfName.FITWINDOW, PdfBoolean.PDFTRUE); if ((preferences & PdfWriter.CenterWindow) != 0) viewerPreferences.put(PdfName.CENTERWINDOW, PdfBoolean.PDFTRUE); if ((preferences & PdfWriter.DisplayDocTitle) != 0) viewerPreferences.put(PdfName.DISPLAYDOCTITLE, PdfBoolean.PDFTRUE); if ((preferences & PdfWriter.NonFullScreenPageModeUseNone) != 0) viewerPreferences.put(PdfName.NONFULLSCREENPAGEMODE, PdfName.USENONE); else if ((preferences & PdfWriter.NonFullScreenPageModeUseOutlines) != 0) viewerPreferences.put(PdfName.NONFULLSCREENPAGEMODE, PdfName.USEOUTLINES); else if ((preferences & PdfWriter.NonFullScreenPageModeUseThumbs) != 0) viewerPreferences.put(PdfName.NONFULLSCREENPAGEMODE, PdfName.USETHUMBS); else if ((preferences & PdfWriter.NonFullScreenPageModeUseOC) != 0) viewerPreferences.put(PdfName.NONFULLSCREENPAGEMODE, PdfName.USEOC); if ((preferences & PdfWriter.DirectionL2R) != 0) viewerPreferences.put(PdfName.DIRECTION, PdfName.L2R); else if ((preferences & PdfWriter.DirectionR2L) != 0) viewerPreferences.put(PdfName.DIRECTION, PdfName.R2L); if ((preferences & PdfWriter.PrintScalingNone) != 0) viewerPreferences.put(PdfName.PRINTSCALING, PdfName.NONE); } } /** * Given a key for a viewer preference (a PdfName object), * this method returns the index in the VIEWER_PREFERENCES array. * @param key a PdfName referring to a viewer preference * @return an index in the VIEWER_PREFERENCES array */ private int getIndex(PdfName key) { for (int i = 0; i < VIEWER_PREFERENCES.length; i++) { if (VIEWER_PREFERENCES[i].equals(key)) return i; } return -1; } /** * Checks if some value is valid for a certain key. */ private boolean isPossibleValue(PdfName value, PdfName[] accepted) { for (int i = 0; i < accepted.length; i++) { if (accepted[i].equals(value)) { return true; } } return false; } /** * Sets the viewer preferences for printing. */ public void addViewerPreference(PdfName key, PdfObject value) { switch(getIndex(key)) { case 0: // HIDETOOLBAR case 1: // HIDEMENUBAR case 2: // HIDEWINDOWUI case 3: // FITWINDOW case 4: // CENTERWINDOW case 5: // DISPLAYDOCTITLE case 14: // PICKTRAYBYPDFSIZE if (value instanceof PdfBoolean) { viewerPreferences.put(key, value); } break; case 6: // NONFULLSCREENPAGEMODE if (value instanceof PdfName && isPossibleValue((PdfName)value, NONFULLSCREENPAGEMODE_PREFERENCES)) { viewerPreferences.put(key, value); } break; case 7: // DIRECTION if (value instanceof PdfName && isPossibleValue((PdfName)value, DIRECTION_PREFERENCES)) { viewerPreferences.put(key, value); } break; case 8: // VIEWAREA case 9: // VIEWCLIP case 10: // PRINTAREA case 11: // PRINTCLIP if (value instanceof PdfName && isPossibleValue((PdfName)value, PAGE_BOUNDARIES)) { viewerPreferences.put(key, value); } break; case 12: // PRINTSCALING if (value instanceof PdfName && isPossibleValue((PdfName)value, PRINTSCALING_PREFERENCES)) { viewerPreferences.put(key, value); } break; case 13: // DUPLEX if (value instanceof PdfName && isPossibleValue((PdfName)value, DUPLEX_PREFERENCES)) { viewerPreferences.put(key, value); } break; case 15: // PRINTPAGERANGE if (value instanceof PdfArray) { viewerPreferences.put(key, value); } break; case 16: // NUMCOPIES if (value instanceof PdfNumber) { viewerPreferences.put(key, value); } break; } } /** * Adds the viewer preferences defined in the preferences parameter to a * PdfDictionary (more specifically the root or catalog of a PDF file). * * @param catalog */ public void addToCatalog(PdfDictionary catalog) { // Page Layout catalog.remove(PdfName.PAGELAYOUT); if ((pageLayoutAndMode & PdfWriter.PageLayoutSinglePage) != 0) catalog.put(PdfName.PAGELAYOUT, PdfName.SINGLEPAGE); else if ((pageLayoutAndMode & PdfWriter.PageLayoutOneColumn) != 0) catalog.put(PdfName.PAGELAYOUT, PdfName.ONECOLUMN); else if ((pageLayoutAndMode & PdfWriter.PageLayoutTwoColumnLeft) != 0) catalog.put(PdfName.PAGELAYOUT, PdfName.TWOCOLUMNLEFT); else if ((pageLayoutAndMode & PdfWriter.PageLayoutTwoColumnRight) != 0) catalog.put(PdfName.PAGELAYOUT, PdfName.TWOCOLUMNRIGHT); else if ((pageLayoutAndMode & PdfWriter.PageLayoutTwoPageLeft) != 0) catalog.put(PdfName.PAGELAYOUT, PdfName.TWOPAGELEFT); else if ((pageLayoutAndMode & PdfWriter.PageLayoutTwoPageRight) != 0) catalog.put(PdfName.PAGELAYOUT, PdfName.TWOPAGERIGHT); // Page Mode catalog.remove(PdfName.PAGEMODE); if ((pageLayoutAndMode & PdfWriter.PageModeUseNone) != 0) catalog.put(PdfName.PAGEMODE, PdfName.USENONE); else if ((pageLayoutAndMode & PdfWriter.PageModeUseOutlines) != 0) catalog.put(PdfName.PAGEMODE, PdfName.USEOUTLINES); else if ((pageLayoutAndMode & PdfWriter.PageModeUseThumbs) != 0) catalog.put(PdfName.PAGEMODE, PdfName.USETHUMBS); else if ((pageLayoutAndMode & PdfWriter.PageModeFullScreen) != 0) catalog.put(PdfName.PAGEMODE, PdfName.FULLSCREEN); else if ((pageLayoutAndMode & PdfWriter.PageModeUseOC) != 0) catalog.put(PdfName.PAGEMODE, PdfName.USEOC); else if ((pageLayoutAndMode & PdfWriter.PageModeUseAttachments) != 0) catalog.put(PdfName.PAGEMODE, PdfName.USEATTACHMENTS); // viewer preferences (Table 8.1 of the PDF Reference) catalog.remove(PdfName.VIEWERPREFERENCES); if (viewerPreferences.size() > 0) { catalog.put(PdfName.VIEWERPREFERENCES, viewerPreferences); } } public static PdfViewerPreferencesImp getViewerPreferences(PdfDictionary catalog) { PdfViewerPreferencesImp preferences = new PdfViewerPreferencesImp(); int prefs = 0; PdfName name = null; // page layout PdfObject obj = PdfReader.getPdfObjectRelease(catalog.get(PdfName.PAGELAYOUT)); if (obj != null && obj.isName()) { name = (PdfName) obj; if (name.equals(PdfName.SINGLEPAGE)) prefs |= PdfWriter.PageLayoutSinglePage; else if (name.equals(PdfName.ONECOLUMN)) prefs |= PdfWriter.PageLayoutOneColumn; else if (name.equals(PdfName.TWOCOLUMNLEFT)) prefs |= PdfWriter.PageLayoutTwoColumnLeft; else if (name.equals(PdfName.TWOCOLUMNRIGHT)) prefs |= PdfWriter.PageLayoutTwoColumnRight; else if (name.equals(PdfName.TWOPAGELEFT)) prefs |= PdfWriter.PageLayoutTwoPageLeft; else if (name.equals(PdfName.TWOPAGERIGHT)) prefs |= PdfWriter.PageLayoutTwoPageRight; } // page mode obj = PdfReader.getPdfObjectRelease(catalog.get(PdfName.PAGEMODE)); if (obj != null && obj.isName()) { name = (PdfName) obj; if (name.equals(PdfName.USENONE)) prefs |= PdfWriter.PageModeUseNone; else if (name.equals(PdfName.USEOUTLINES)) prefs |= PdfWriter.PageModeUseOutlines; else if (name.equals(PdfName.USETHUMBS)) prefs |= PdfWriter.PageModeUseThumbs; else if (name.equals(PdfName.FULLSCREEN)) prefs |= PdfWriter.PageModeFullScreen; else if (name.equals(PdfName.USEOC)) prefs |= PdfWriter.PageModeUseOC; else if (name.equals(PdfName.USEATTACHMENTS)) prefs |= PdfWriter.PageModeUseAttachments; } // set page layout and page mode preferences preferences.setViewerPreferences(prefs); // other preferences obj = PdfReader.getPdfObjectRelease(catalog .get(PdfName.VIEWERPREFERENCES)); if (obj != null && obj.isDictionary()) { PdfDictionary vp = (PdfDictionary) obj; for (int i = 0; i < VIEWER_PREFERENCES.length; i++) { obj = PdfReader.getPdfObjectRelease(vp.get(VIEWER_PREFERENCES[i])); preferences.addViewerPreference(VIEWER_PREFERENCES[i], obj); } } return preferences; } }
923ee6d9f2efa753002915304aa0788563898e31
2,728
java
Java
src/main/java/net/vpg/apex/clip/Toolkit.java
V-Play-Games/pm-apex
3ca8ace3f2253ae2b7094c4df77793e7479887b0
[ "Apache-2.0" ]
null
null
null
src/main/java/net/vpg/apex/clip/Toolkit.java
V-Play-Games/pm-apex
3ca8ace3f2253ae2b7094c4df77793e7479887b0
[ "Apache-2.0" ]
null
null
null
src/main/java/net/vpg/apex/clip/Toolkit.java
V-Play-Games/pm-apex
3ca8ace3f2253ae2b7094c4df77793e7479887b0
[ "Apache-2.0" ]
null
null
null
41.969231
165
0.686217
1,000,960
/* * Copyright (c) 1999, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package net.vpg.apex.clip; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; public class Toolkit { private Toolkit() { // Suppresses default constructor } /** * Throws an exception if the buffer size does not represent an integral * number of sample frames. */ public static void validateBuffer(int frameSize, int bufferSize) { if (bufferSize % frameSize != 0) throw new IllegalArgumentException(String.format("Buffer size (%d) does not represent an integral number of sample frames (%d)", bufferSize, frameSize)); } public static byte[] cache(AudioInputStream stream) throws IOException { int frameSize = stream.getFormat().getFrameSize(); if (stream.getFrameLength() != AudioSystem.NOT_SPECIFIED) { byte[] data = new byte[(int) stream.getFrameLength() * frameSize]; int off = 0, read; while ((read = stream.read(data, off, data.length)) != -1) off += read; return Arrays.copyOf(data, off); } else { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[512 * frameSize]; int read; while ((read = stream.read(buffer)) != -1) outputStream.write(buffer, 0, read); return outputStream.toByteArray(); } } }
923ee82ea9e5f8230c4674db4754a932bb10c743
4,945
java
Java
data/src/main/java/com/doggogram/backendsvc/services/impl/UserServiceImpl.java
LeError/Doggogram-Backend
e432ecc9845d564372b98eb806fd075376362b01
[ "Apache-2.0" ]
2
2019-11-11T14:05:13.000Z
2019-11-26T16:22:09.000Z
data/src/main/java/com/doggogram/backendsvc/services/impl/UserServiceImpl.java
LeError/Doggogram-Backend
e432ecc9845d564372b98eb806fd075376362b01
[ "Apache-2.0" ]
null
null
null
data/src/main/java/com/doggogram/backendsvc/services/impl/UserServiceImpl.java
LeError/Doggogram-Backend
e432ecc9845d564372b98eb806fd075376362b01
[ "Apache-2.0" ]
null
null
null
36.094891
123
0.71729
1,000,961
package com.doggogram.backendsvc.services.impl; import com.doggogram.backendsvc.domain.User; import com.doggogram.backendsvc.dto.UserDTO; import com.doggogram.backendsvc.mapper.Mapper; import com.doggogram.backendsvc.repositories.UserRepository; import com.doggogram.backendsvc.services.UserService; import com.doggogram.backendsvc.util.Util; import com.doggogram.backendsvc.util.exceptions.ImageCorruptedException; import com.doggogram.backendsvc.util.exceptions.PasswordDoesNotMatchException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import javax.persistence.EntityNotFoundException; import java.util.List; import java.util.stream.Collectors; @Service public class UserServiceImpl implements UserService { private final UserRepository userRepository; private final PasswordEncoder passwordEncoder; private final Mapper mapper; public UserServiceImpl (UserRepository userRepository, Mapper mapper, PasswordEncoder passwordEncoder) { this.userRepository = userRepository; this.mapper = mapper; this.passwordEncoder = passwordEncoder; } @Override public UserDTO findUserByUser (String user) { return mapper.userToUserDTO(userRepository.findUserByUser(user)); } @Override public List<UserDTO> findUsersByUser (String user) { user += "%"; return userRepository.findUsersByUser(user).stream().map(mapper::userToUserDTO).collect(Collectors.toList()); } @Override public void registerUser (String user, String pass) { userRepository.save(new User(user, passwordEncoder.encode(pass))); } @Override public Long count () { return userRepository.countEntities(); } @Override public List<UserDTO> getAllItems () { return userRepository.findAll().stream().map(mapper::userToUserDTO).collect(Collectors.toList()); } @Override public boolean followUser (String user, String followUser) throws EntityNotFoundException { User userEntity = userRepository.findUserByUser(user); User followUserEntity = userRepository.findUserByUser(followUser); Boolean following = false; if(userEntity == null || followUser == null) { throw new EntityNotFoundException("Cant find Entity!"); } if(userRepository.checkIfUserFollowsUser(user, followUser) == 0) { userEntity.getFollowing().add(followUserEntity); following = true; } else { userEntity.getFollowing().remove(followUserEntity); } userRepository.save(userEntity); return following; } @Override public List<UserDTO> getFollowers (String user) { return userRepository.findFollowersByUser(user).stream().map(mapper::userToUserDTO).collect(Collectors.toList()); } @Override public Long countFollowers (String user) { return userRepository.countFollowers(user); } @Override public List<UserDTO> getFollowing (String user) { return userRepository.findFollowingByUser(user).stream().map(mapper::userToUserDTO).collect(Collectors.toList()); } @Override public Long countFollowing (String user) { return userRepository.countFollowing(user); } @Override public void updatePassword (String user, String oldPassword, String newPassword) throws PasswordDoesNotMatchException { if(passwordEncoder.matches(oldPassword, userRepository.findUserByUser(user).getPass())) { User userEntity = userRepository.findUserByUser(user); userEntity.setPass(passwordEncoder.encode(newPassword)); userRepository.save(userEntity); } else { throw new PasswordDoesNotMatchException("Old Password does not Match Database!"); } } @Override public void updateBio (String user, String bio) { User userEntity = userRepository.findUserByUser(user); userEntity.setBio(bio); userRepository.save(userEntity); } @Override public void updateImage (String user, MultipartFile image) throws ImageCorruptedException { User userEntity = userRepository.findUserByUser(user); userEntity.setUserImage(Util.getEncodedImage(image)); userRepository.save(userEntity); } @Override public void removeImage (String user) { User userEntity = userRepository.findUserByUser(user); userEntity.setUserImage(null); userRepository.save(userEntity); } @Override public List<UserDTO> getImageLiker (long imageId) { return userRepository.findLikerByImageId(imageId).stream().map(mapper::userToUserDTO).collect(Collectors.toList()); } @Override public String getUserImage (String user) { return userRepository.findUserImageByUser(user); } }
923ee853f77a57b6a02819a09f87cf6614e27856
4,074
java
Java
spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/http/Response.java
mauricio-ikegami/spring-cloud-contract
dc9b19be6dbbb6d9654fa582e8ef14877ee29a16
[ "Apache-2.0" ]
664
2016-06-12T20:44:19.000Z
2022-03-24T19:00:10.000Z
spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/http/Response.java
mauricio-ikegami/spring-cloud-contract
dc9b19be6dbbb6d9654fa582e8ef14877ee29a16
[ "Apache-2.0" ]
1,561
2016-07-08T11:26:56.000Z
2022-03-29T12:50:39.000Z
spring-cloud-contract-verifier/src/main/java/org/springframework/cloud/contract/verifier/http/Response.java
mauricio-ikegami/spring-cloud-contract
dc9b19be6dbbb6d9654fa582e8ef14877ee29a16
[ "Apache-2.0" ]
466
2016-07-08T10:49:33.000Z
2022-03-24T21:02:26.000Z
21.670213
106
0.671085
1,000,962
/* * Copyright 2012-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.contract.verifier.http; import java.util.HashMap; import java.util.Map; /** * Abstraction over a HTTP response. * * Warning! This API is experimental and can change in time. * * @author Marcin Grzejszczak * @since 3.0.0 */ public class Response { private final int statusCode; private final Body body; private final Map<String, Object> headers; private final Map<String, Object> cookies; Response(int statusCode, Body body, Map<String, Object> headers, Map<String, Object> cookies) { this.statusCode = statusCode; this.body = body; this.headers = headers; this.cookies = cookies; } /** * @return numerical representation of a status code */ public int statusCode() { return this.statusCode; } /** * @param key header key * @return header value or null if not present */ public String header(String key) { return this.headers.entrySet().stream().filter(e -> e.getKey().equalsIgnoreCase(key)).findFirst() .map(e -> e.getValue().toString()).orElse(null); } /** * @param key cookie key * @return header value or null if not present */ public String cookie(String key) { return this.cookies.entrySet().stream().filter(e -> e.getKey().equalsIgnoreCase(key)).findFirst() .map(e -> e.getValue().toString()).orElse(null); } /** * @return response body */ public Body getBody() { return this.body; } /** * @return builder */ public static Response.Builder builder() { return new Response.Builder(); } /** * @return headers */ public Map<String, Object> headers() { return this.headers; } /** * @return cookies */ public Map<String, Object> cookies() { return this.cookies; } /** * @param response template of a response * @return builder filled with response data */ public static Builder from(Response response) { return new Builder().headers(response.headers).statusCode(response.statusCode).cookies(response.cookies) .body(response.body); } /** * Response builder. */ public static class Builder { int statusCode; Body body; Map<String, Object> headers = new HashMap<>(); Map<String, Object> cookies = new HashMap<>(); /** * @param status as int * @return builder */ public Response.Builder statusCode(int status) { this.statusCode = status; return this; } /** * @param body - response body * @return builder */ public Response.Builder body(Object body) { this.body = new Body(body); return this; } /** * @param headers - response headers * @return builder */ public Response.Builder headers(Map<String, Object> headers) { this.headers = headers; return this; } /** * @param key header key * @param value header value * @return builder */ public Response.Builder header(String key, Object value) { this.headers.put(key, value); return this; } /** * @param key cookie key * @param value cookie value * @return builder */ public Response.Builder cookie(String key, Object value) { this.cookies.put(key, value); return this; } /** * @param cookies - response cookies * @return builder */ public Response.Builder cookies(Map<String, Object> cookies) { this.cookies = cookies; return this; } /** * @return response */ public Response build() { return new Response(this.statusCode, this.body, this.headers, this.cookies); } } }
923ee86e8ba3a21e7566a3ab79205fa77ac04820
1,411
java
Java
app/dialogflowchatlibrary/src/main/java/com/tyagiabhinav/dialogflowchatlibrary/AlertReceiver.java
Nazar-Pa/Chatbot
2650836932b261c59ab29ce98f087e465c643a50
[ "Apache-2.0" ]
null
null
null
app/dialogflowchatlibrary/src/main/java/com/tyagiabhinav/dialogflowchatlibrary/AlertReceiver.java
Nazar-Pa/Chatbot
2650836932b261c59ab29ce98f087e465c643a50
[ "Apache-2.0" ]
null
null
null
app/dialogflowchatlibrary/src/main/java/com/tyagiabhinav/dialogflowchatlibrary/AlertReceiver.java
Nazar-Pa/Chatbot
2650836932b261c59ab29ce98f087e465c643a50
[ "Apache-2.0" ]
null
null
null
37.131579
111
0.759036
1,000,963
package com.tyagiabhinav.dialogflowchatlibrary; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.util.Log; import androidx.annotation.RequiresApi; import androidx.core.app.NotificationCompat; @RequiresApi(api = Build.VERSION_CODES.O) public class AlertReceiver extends BroadcastReceiver { private static final String TAG = AlertReceiver.class.getSimpleName(); ChatbotActivity chatbotActivity = new ChatbotActivity(); final String SHARED_PREFS = chatbotActivity.SHARED_PREFS; //boolean isFired = sharedPreferences.getBoolean("isFired", false); @Override public void onReceive(Context context, Intent intent) { SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFS, context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean("isFired", false); editor.apply(); // boolean isFired = sharedPreferences.getBoolean("isFired", false); // Log.d(TAG, "Nazar isFired issssssssss: "+ isFired); // NotificationHelper notificationHelper = new NotificationHelper(context); // NotificationCompat.Builder nb = notificationHelper.getChannelNotification(); // notificationHelper.getManager().notify(1, nb.build()); } }
923ee9115c45db91decedde93639c5e4f63a1b8a
7,013
java
Java
app/src/main/java/com/dahuoji/smstransfer/BoardAdapter.java
Dahuoji-Coder/SMSTransfer
fe26512e4a37d7761f512071b31bdf088a450b85
[ "Apache-2.0" ]
1
2021-09-01T02:47:55.000Z
2021-09-01T02:47:55.000Z
app/src/main/java/com/dahuoji/smstransfer/BoardAdapter.java
Dahuoji-Coder/SMSTransfer
fe26512e4a37d7761f512071b31bdf088a450b85
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/dahuoji/smstransfer/BoardAdapter.java
Dahuoji-Coder/SMSTransfer
fe26512e4a37d7761f512071b31bdf088a450b85
[ "Apache-2.0" ]
null
null
null
44.386076
166
0.66776
1,000,964
package com.dahuoji.smstransfer; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.media.Image; import android.os.Build; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import org.jetbrains.annotations.NotNull; import java.util.List; public class BoardAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private final Context context; private final List<CaseEntity> caseList; public static final int[] colors1 = new int[]{Color.parseColor("#F2CDCB"), Color.parseColor("#6C6C8C"), Color.parseColor("#62A8A1"), Color.parseColor("#81D1DD")}; public static final int[] colors2 = new int[]{Color.parseColor("#EDC382"), Color.parseColor("#355B94"), Color.parseColor("#C3CBD2"), Color.parseColor("#AA3B45")}; public static final int[] colors3 = new int[]{Color.parseColor("#44435F"), Color.parseColor("#B3B4B7"), Color.parseColor("#505F99"), Color.parseColor("#7396D1")}; public BoardAdapter(Context context, List<CaseEntity> caseList) { this.context = context; this.caseList = caseList; } @NonNull @org.jetbrains.annotations.NotNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull @org.jetbrains.annotations.NotNull ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(context).inflate(R.layout.item_board_layout, parent, false); return new BoardViewHolder(itemView); } @Override public void onBindViewHolder(@NonNull @NotNull RecyclerView.ViewHolder holder, int position) { holder = (BoardViewHolder) holder; CaseEntity caseEntity = caseList.get(position); StringBuilder filtersStr = new StringBuilder(); if (!TextUtils.isEmpty(caseEntity.getFiltersPhoneNumber())) { filtersStr.append(caseEntity.getFiltersPhoneNumber()).append(" | "); } if (!TextUtils.isEmpty(caseEntity.getFiltersKeyword1())) { filtersStr.append(caseEntity.getFiltersKeyword1()).append(" | "); } if (!TextUtils.isEmpty(caseEntity.getFiltersKeyword2())) { filtersStr.append(caseEntity.getFiltersKeyword2()).append(" | "); } if (filtersStr.length() > 0) { ((BoardViewHolder) holder).filtersTextView.setText(filtersStr.substring(0, filtersStr.length() - 3)); } else { ((BoardViewHolder) holder).filtersTextView.setText("转发所有信息"); } StringBuilder forwardStr = new StringBuilder(); if (caseEntity.getContact1() != null) { forwardStr.append(caseEntity.getContact1().getName() + " (" + caseEntity.getContact1().getPhoneNumber() + ")"); if (caseEntity.getContact2() != null) { forwardStr.append("\n").append(caseEntity.getContact2().getName() + " (" + caseEntity.getContact2().getPhoneNumber() + ")"); } } if (forwardStr.length() > 0) { ((BoardViewHolder) holder).transferTextView.setText(forwardStr); } else { ((BoardViewHolder) holder).transferTextView.setText("无转发人"); } if (caseEntity.isShowButtons()) { ((BoardViewHolder) holder).buttonsLayout.setVisibility(View.VISIBLE); } else { ((BoardViewHolder) holder).buttonsLayout.setVisibility(View.GONE); } ListActivity.setAlphaChange(((BoardViewHolder) holder).contentLayout, ((BoardViewHolder) holder).buttonEdit, ((BoardViewHolder) holder).buttonDelete); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { ((BoardViewHolder) holder).itemBoardRoot.setClipToOutline(true); } ((BoardViewHolder) holder).contentLayout.setBackgroundColor(caseEntity.getColor()); RecyclerView.@NotNull ViewHolder finalHolder = holder; ((BoardViewHolder) holder).contentLayout.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Log.d(">>>BoardAdapter", "=== on long click root"); if (((BoardViewHolder) finalHolder).buttonsLayout.getVisibility() == View.GONE) { ((BoardViewHolder) finalHolder).buttonsLayout.setVisibility(View.VISIBLE); caseEntity.setShowButtons(true); } return true; } }); ((BoardViewHolder) holder).buttonsLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v.setVisibility(View.GONE); } }); ((BoardViewHolder) holder).buttonEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBoardEventListener.onButtonEditClicked(caseEntity); } }); ((BoardViewHolder) holder).buttonDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBoardEventListener.onButtonDeleteClicked(caseEntity); Log.d(">>>BoardAdapter", "=== on click delete button"); } }); } @Override public int getItemCount() { return caseList == null ? 0 : caseList.size(); } static class BoardViewHolder extends RecyclerView.ViewHolder { public final View itemBoardRoot; public final RelativeLayout contentLayout; public final LinearLayout buttonsLayout; public final ImageView buttonEdit; public final ImageView buttonDelete; public final TextView filtersTextView; public final TextView transferTextView; public BoardViewHolder(@NonNull @NotNull View itemView) { super(itemView); itemBoardRoot = itemView.findViewById(R.id.itemBoardRoot); contentLayout = itemView.findViewById(R.id.contentLayout); buttonsLayout = itemView.findViewById(R.id.buttonsLayout); buttonEdit = itemView.findViewById(R.id.buttonEdit); buttonDelete = itemView.findViewById(R.id.buttonDelete); filtersTextView = itemView.findViewById(R.id.filtersTextView); transferTextView = itemView.findViewById(R.id.transferTextView); } } private OnBoardEventListener onBoardEventListener; public void setOnBoardEventListener(OnBoardEventListener onBoardEventListener) { this.onBoardEventListener = onBoardEventListener; } public interface OnBoardEventListener { void onButtonEditClicked(CaseEntity caseEntity); void onButtonDeleteClicked(CaseEntity caseEntity); } }
923ee956f26fb394b100cc4536fcdbf5236f3e45
306
java
Java
hawtio-git/src/test/java/io/hawt/git/VersionTest.java
paoloantinori/hawtio
6f903f56601f3be14512abb29dc55d56a302f597
[ "Apache-2.0" ]
1
2015-07-09T08:29:36.000Z
2015-07-09T08:29:36.000Z
hawtio-git/src/test/java/io/hawt/git/VersionTest.java
paoloantinori/hawtio
6f903f56601f3be14512abb29dc55d56a302f597
[ "Apache-2.0" ]
6
2015-05-12T10:59:35.000Z
2015-06-25T20:33:17.000Z
hawtio-git/src/test/java/io/hawt/git/VersionTest.java
paoloantinori/hawtio
6f903f56601f3be14512abb29dc55d56a302f597
[ "Apache-2.0" ]
3
2015-12-14T21:33:38.000Z
2022-03-19T08:53:18.000Z
19.125
66
0.669935
1,000,965
package io.hawt.git; import io.hawt.config.ConfigFacade; import org.junit.Test; /** */ public class VersionTest { @Test public void testVersion() throws Exception { String version = ConfigFacade.getSingleton().getVersion(); System.out.println("Version is: " + version); } }
923eea0541eacae9a0b2f8faefe2287eb2ba1806
20,021
java
Java
RMBTStatisticServer/src/at/rtr/rmbt/statisticServer/opendata/OpenTestSearchResource.java
RTR-Netztest/open-rmbt
0561c737e898ca7bf7849319cfc992898beb499e
[ "Apache-2.0" ]
32
2017-07-03T08:18:11.000Z
2022-03-22T06:05:05.000Z
RMBTStatisticServer/src/at/rtr/rmbt/statisticServer/opendata/OpenTestSearchResource.java
Rashadtr27/open-rmbt
159c8da7cceb8ac5d3f7b66d9ea500496fa872c6
[ "Apache-2.0" ]
19
2018-03-07T16:12:08.000Z
2022-02-28T14:02:54.000Z
RMBTStatisticServer/src/at/rtr/rmbt/statisticServer/opendata/OpenTestSearchResource.java
Rashadtr27/open-rmbt
159c8da7cceb8ac5d3f7b66d9ea500496fa872c6
[ "Apache-2.0" ]
12
2017-11-08T15:05:30.000Z
2021-12-16T01:51:14.000Z
67.410774
232
0.661805
1,000,966
/******************************************************************************* * Copyright 2013-2016 Thomas Schreiber * Copyright 2013-2016 Rundfunk und Telekom Regulierungs-GmbH (RTR-GmbH) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package at.rtr.rmbt.statisticServer.opendata; import at.rtr.rmbt.shared.cache.CacheHelper; import at.rtr.rmbt.statisticServer.ServerResource; import at.rtr.rmbt.statisticServer.opendata.dao.OpenTestDAO; import at.rtr.rmbt.statisticServer.opendata.dto.OpenTestDTO; import at.rtr.rmbt.statisticServer.opendata.dto.OpenTestSearchDTO; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.SequenceWriter; import com.fasterxml.jackson.dataformat.csv.CsvGenerator; import com.fasterxml.jackson.dataformat.csv.CsvMapper; import com.fasterxml.jackson.dataformat.csv.CsvSchema; import com.github.sett4.dataformat.xlsx.XlsxMapper; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.json.JSONException; import org.json.JSONObject; import org.restlet.data.*; import org.restlet.representation.OutputRepresentation; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.Get; import org.restlet.resource.Post; import javax.ws.rs.GET; import javax.ws.rs.Path; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; @Api(value="/opentests/search") public class OpenTestSearchResource extends ServerResource { private enum FieldType {STRING, DATE, LONG, DOUBLE, BOOLEAN, UUID, SORTBY, SORTORDER, IGNORE}; private static final int CACHE_EXP = 3600; private static final String CSV_FILENAME = "opentests.csv"; private static final String XLSX_FILENAME = "opentests.xlsx"; private final CacheHelper cache = CacheHelper.getInstance(); public final int MAXROWS = 10000; //maximum number of rows allowed, currently approx 1.5s response time at maximum public final int DEFAULTROWS = 100; //default number of rows (when max_results is not specified) public final int MAXQUERYFIELDS = 50; //to prevent database-server overload //all fields that should be displayed in a general request (e.g. all tests for one user) private final String[] openDataFieldsSummary = {"open_uuid", "open_test_uuid", "time", "lat", "long", "download_kbit", "upload_kbit", "ping_ms", "signal_strength", "lte_rsrp", "platform", "provider_name", "model", "loc_accuracy"}; //all fields that are numbers (and are formatted as numbers in json) private final HashSet<String> openDataNumberFields = new HashSet<>(Arrays.asList(new String[]{"time", "lat", "long", "download_kbit", "upload_kbit","ping_ms","signal_strength", "lte_rsrp", "test_duration","num_threads","ndt_download_kbit","ndt_upload_kbit","asn","loc_accuracy"})); //all fields for which the user can sort the result private final HashSet<String> openDataFieldsSortable = new HashSet<>(Arrays.asList(new String[]{"download_kbit","upload_kbit","time","signal_strength","ping_ms"})); //additional fields that the user is allowed to request private final HashSet<String> allowedAdditionalFields = new HashSet<>(Arrays.asList(new String[] {"download_classification","upload_classification","ping_classification","signal_classification"})); @Get @Post @GET @Path("/opentests/search") @ApiOperation(httpMethod = "GET", value = "Search for open data tests", response = OpenTestSearchDTO.class, nickname = "search", notes = "Date fields have to be submitted as a number, representing the number of milliseconds that have elapsed since midnight, January 1st, 1970 or " + "in the format “yyyy-MM-dd HH:mm:ss”. The time is given in UTC.\n\n" + "Decimal point (Full Stop “.”) is always used to separate the integer part from the fractional part of a number written in decimal form. " + "This is independent from the local or regional settings.\n\n" + "Numeric fields also allow using the comparators ‘>’ and ‘<’ (meaning ‘=>’ and ‘=<’ respectively). Dates have always to be queried as ranges " + "by using these comparators.\n\n" + "String fields allow using the wildcard ‘*’ for matching any literals and ‘?’ for matching one arbitrary literal.\n\n" + "It is possible, to begin each filter argument with an exclamation mark (!) to negate the filter. E.g. network_type=!LAN will yield all " + "tests where the network type was not LAN.\n\n" + "The criteria denoted with [] can be used more than once in a query. Data has to match all criteria. If an array for one criterion is given, " + "the data has to match each entry.\n\n" + "Generally a query on a parameter value ‘null’ is not possible, except for the parameter loc_accuracy, where the value -1 means ‘null’. " + "Non-‘null’ values are queried with any single or multiple values.") @ApiImplicitParams({ @ApiImplicitParam(name = "download_kbit", value = "Download speed in kilobit per second", dataType = "string", example = ">6903", paramType = "query"), @ApiImplicitParam(name = "upload_kbit", value = "Upload speed in kilobit per second.", dataType = "string", example = "<4670", paramType = "query"), @ApiImplicitParam(name = "ping_ms", value = "Median ping (round-trip time) in milliseconds, measured on the server side. In previous versions " + "(before June 3rd 2015) this was the minimum ping measured on the client side.", dataType = "string", example = "<16", paramType = "query"), @ApiImplicitParam(name = "gkz", value = "Community ID (Gemeindekennzahl, see <http://www.bev.gv.at/portal/page?_pageid=713,2601287&_dad=portal&_schema=PORTAL>).", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "gkz_sa", value = "Community ID (Gemeindekennzahl, see <http://www.statistik.at/web_de/klassifikationen/regionale_gliederungen/gemeinden/index.html>)", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "cat_technology", value = "Technology category of the network, e.g. “3G”, “4G”, “WLAN”.", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "client_version", value = "Software version number of the client.", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "model", value = "Name of the device used.", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "network_name", value = "Display name of the mobile network.", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "network_type", value = "Type of the network, e.g. MOBILE, LAN, WLAN.", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "platform", value = "Platform on which the test has been conducted", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "signal_strength", value = "Signal strength (RSSI) in dBm.", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "lte_rsrp", value = "LTE signal strength in dBm.", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "open_uuid", value = "Open-UUID: Identifies the client that conducted the test. The a new Open-UUID is assigned to the client on a regular basis.", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "open_test_uuid", value = "The UUID of the test.", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "client_uuid", value = "The private UUID of a client", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "loop_uuid", value = "The loop UUID of a single loop test", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "test_uuid", value = "The private UUID of a test", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "long", value = "Longitude of the client position.", dataType = "number", paramType = "query"), @ApiImplicitParam(name = "lat", value = "Latitude of the client position.", dataType = "number", paramType = "query"), @ApiImplicitParam(name = "radius", value = "Radius in meters defining based on lat/long parameters", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "mobile_provider_name", value = "mobile operator name", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "provider_name", value = "Name of the internet service provider.", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "sim_mcc_mnc", value = "Network identification of the SIM provider. The digits of MCC and MNC have the same meaning as described in “network_mcc_mnc”.", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "sim_country", value = "Home country of the SIM card in ISO 3166.", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "network_country", value = "Country of the network in ISO 3166.", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "country_geoip", value = "Country according client IP address.", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "country_location", value = "Country of geo-location.", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "user_server_selection", value = "Legacy", dataType = "boolean", paramType = "query"), @ApiImplicitParam(name = "loc_accuracy", value = "Estimation of accuracy of client location in meters", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "link_name", value = "Austrian road/raiway line identifier, e.g. 'A2'", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "public_ip_as_name", value = "Name of the AS of the clients public IP.", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "time", value = "UTC date and time when test was started.", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "radio_band", value = "Radio band used when conducting the test.", dataType = "long", paramType = "query"), @ApiImplicitParam(name = "cell_area_code", value = "Number describing the coarse location of a cell. E.g. the Tracking Area Code (TAC) in case of 4G " + "or the Location Area Code (LAC) in case of 2G or 3G", dataType = "long", paramType = "query"), @ApiImplicitParam(name = "cell_location_id", value = "Number identifying the location of a cell. E.g. the 28-bit Cell Identity (CI) in case of 4G, " + "the 28-bit UMTS Cell Identity (CID) in case of UMTS or the 16-bit GSM Cell Identity (CID) in case of GSM.", dataType = "long", paramType = "query"), @ApiImplicitParam(name = "additional_info", value = "additional properties to return", example = "download_classification", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "format", value="Desired output format, either 'csv' or 'json', default: json", example = "json", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "sort_by", value="The field for which the data are sorted. Valid fields are: “download_kbit\", \"upload_kbit\", \"time\", \"signal_strength\", \"lte_rsrp\" and \"ping_ms\"", example = "download_kbit", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "sort_order", value="The sort_by-Parameter specifies the field, the sort_order-Parameter specifies the direction ('asc' or 'desc').\n " + "Per Default, the results are sorted by the time of the test in descending order (i.e. sort_by=time&sort_order=desc).\n " + "If the sort parameters are specified, the value of the cursor is a multiple of the parameter max_results, otherwise it is an arbitrary number.", example = "asc", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "max_results", value="This is the page size, i.e. maximum number of result items that are returned per page.\n " + "The default value is 100 items per page. The page size limit is 10000 items, i.e. not more than 10000 results can be displayed in a page.", example = "10", dataType = "integer", paramType = "query"), @ApiImplicitParam(name = "cursor", value = "used for pagination if the query returns more than the number of items according to parameter max_results. " + "The value to be used for the display of the next page is given by the previous response in returned parameter next_cursor.", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "sender", value = "Sender ID", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "timestamp", value = "Alias '_'. Will be ignored and can be used to prevent caching of the response.", dataType = "string", paramType = "query") }) public Representation request(final Representation entity) throws JSONException { addAllowOrigin(); final JSONObject response = new JSONObject(); final Form getParameters; if (getRequest().getMethod().equals(Method.POST)) { // HTTP POST getParameters = new Form(entity); } else { // HTTP GET getParameters = getRequest().getResourceRef().getQueryAsForm(); } final QueryParser qp = new QueryParser(); final Set<String> additionalFields; final List<String> invalidElements = qp.parseQuery(getParameters); OpenTestSearchDTO ret = new OpenTestSearchDTO(); //calculate offset long offset = -1; if (getParameters.getNames().contains("cursor")) { //is always a valid LONG because it is checked with all other //parameters above offset = Long.parseLong(getParameters.getFirstValue("cursor")); } //get maximal results-parameter long maxrows = DEFAULTROWS; if (getParameters.getNames().contains("max_results")) { //is always a valid LONG because it is checked with all other //parameters above maxrows = Long.parseLong(getParameters.getFirstValue("max_results")); } //parse additional fields if (getParameters.getNames().contains("additional_info") || getParameters.getNames().contains("additional_info[]")) { String param = (getParameters.getNames().contains("additional_info")) ? "additional_info" : "additional_info[]"; for (String field : getParameters.getValuesArray(param)) { if (!allowedAdditionalFields.contains(field)) { invalidElements.add(param); } } additionalFields = new HashSet<>(Arrays.asList(getParameters.getValuesArray(param))); } else { additionalFields = new HashSet<>(); } String format = getParameters.getFirstValue("format", "json").toLowerCase();; //if there have been errors => inform the user if (invalidElements.size() > 0) { setStatus(Status.CLIENT_ERROR_BAD_REQUEST); response.put("invalid_fields", invalidElements); ret.getInvalidFields().addAll(invalidElements); } //if there are too many query elements (DoS-Attack?), don't let it //get to the database else if (qp.getWhereParams().keySet().size() > MAXQUERYFIELDS) { setStatus(Status.CLIENT_ERROR_BAD_REQUEST); ret.getInvalidFields().add("field limit exceeded"); } else { //if valid input, query the db OpenTestDAO dao = new OpenTestDAO(conn, settings, capabilities); ret = dao.getOpenTestSearchResults(qp, offset, maxrows, additionalFields); } Representation representation = null; //format, depending on output format try { if (format.equals("csv")) { CsvMapper cm = new CsvMapper(); cm.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); cm.enable(CsvGenerator.Feature.STRICT_CHECK_FOR_QUOTING); CsvSchema schema = CsvSchema.builder().setLineSeparator("\r\n").setUseHeader(true) .addColumnsFrom(cm.schemaFor(OpenTestDTO.class)).build(); representation = new StringRepresentation(cm.writer(schema).writeValueAsString(ret.getResults())); } else if (format.equals("xlsx")) { final OpenTestSearchDTO that = ret; OutputRepresentation or = new OutputRepresentation(MediaType.APPLICATION_MSOFFICE_XLSX) { @Override public void write(OutputStream outputStream) throws IOException { XlsxMapper mapper = new XlsxMapper(); mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); CsvSchema schema = mapper.schemaFor(OpenTestDTO.class).withHeader(); SequenceWriter sequenceWriter = mapper.writer(schema).writeValues(outputStream); sequenceWriter.writeAll(that.getResults()); sequenceWriter.flush(); sequenceWriter.close(); } }; representation = or; } else { ObjectMapper om = new ObjectMapper(); om.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); representation = new StringRepresentation(om.writer().writeValueAsString(ret)); } } catch (JsonProcessingException e) { e.printStackTrace(); setStatus(Status.SERVER_ERROR_INTERNAL); } if (format.equals("csv")) { Disposition disposition = new Disposition(Disposition.TYPE_ATTACHMENT); disposition.setFilename(CSV_FILENAME); representation.setMediaType(MediaType.TEXT_CSV); representation.setDisposition(disposition); representation.setCharacterSet(CharacterSet.UTF_8); } else if (format.equals("xlsx")) { Disposition disposition = new Disposition(Disposition.TYPE_ATTACHMENT); disposition.setFilename(XLSX_FILENAME); representation.setMediaType(MediaType.APPLICATION_MSOFFICE_XLSX); representation.setDisposition(disposition); } else { representation.setMediaType(MediaType.APPLICATION_JSON); representation.setCharacterSet(CharacterSet.UTF_8); } return representation; } }
923eeceeb02715c47bdff4b164d5ce5b89dadfb9
714
java
Java
app/src/main/java/com/nemesiss/dev/ianime/Model/Model/Response/Data/WorksInfo.java
iosTeamofFour/iAnime2
db8195a7359d91c83aef45c7f3ea81fbe1a3141a
[ "MIT" ]
null
null
null
app/src/main/java/com/nemesiss/dev/ianime/Model/Model/Response/Data/WorksInfo.java
iosTeamofFour/iAnime2
db8195a7359d91c83aef45c7f3ea81fbe1a3141a
[ "MIT" ]
null
null
null
app/src/main/java/com/nemesiss/dev/ianime/Model/Model/Response/Data/WorksInfo.java
iosTeamofFour/iAnime2
db8195a7359d91c83aef45c7f3ea81fbe1a3141a
[ "MIT" ]
null
null
null
18.307692
58
0.592437
1,000,967
package com.nemesiss.dev.ianime.Model.Model.Response.Data; public class WorksInfo { private int imageID; private String name; private String date; public WorksInfo(int imageID,String name,String date) { this.imageID=imageID; this.name=name; this.date=date; } public void setDate(String date) { this.date = date; } public void setImageID(int imageID) { this.imageID = imageID; } public void setName(String name) { this.name = name; } public String getDate() { return date; } public int getImageID() { return imageID; } public String getName() { return name; } }
923eed6ee89eb128686ead6cec0a293c4b012c8d
4,774
java
Java
stagemonitor-core/src/main/java/org/stagemonitor/core/StagemonitorPlugin.java
trampi/stagemonitor
3223ce539519650171a9ac3c9e492758fd6b7464
[ "Apache-2.0" ]
null
null
null
stagemonitor-core/src/main/java/org/stagemonitor/core/StagemonitorPlugin.java
trampi/stagemonitor
3223ce539519650171a9ac3c9e492758fd6b7464
[ "Apache-2.0" ]
null
null
null
stagemonitor-core/src/main/java/org/stagemonitor/core/StagemonitorPlugin.java
trampi/stagemonitor
3223ce539519650171a9ac3c9e492758fd6b7464
[ "Apache-2.0" ]
null
null
null
34.594203
124
0.780897
1,000,968
package org.stagemonitor.core; import org.stagemonitor.core.configuration.Configuration; import org.stagemonitor.core.configuration.ConfigurationOptionProvider; import org.stagemonitor.core.metrics.metrics2.Metric2Registry; import java.util.Collections; import java.util.List; /** * Base class for stagemonitor Plugins. * * The {@link #initializePlugin(InitArguments)} )} method serves as a initialisation callback * for plugins. */ public abstract class StagemonitorPlugin extends ConfigurationOptionProvider implements StagemonitorSPI { /** * Implementing classes have to initialize the plugin by registering their metrics the * {@link Metric2Registry} * @param initArguments */ public void initializePlugin(InitArguments initArguments) throws Exception { } /** * Implementing classes have to initialize the plugin by registering their metrics the * {@link Metric2Registry} * @deprecated use {@link #initializePlugin(InitArguments)} */ @Deprecated public void initializePlugin(Metric2Registry metricRegistry, Configuration configuration) throws Exception { } /** * This method is called when stagemonitor shuts down. * The shutdown is triggered by {@link org.stagemonitor.web.monitor.filter.HttpRequestMonitorFilter#destroy()}, * for example. In non-servlet applications this method has to be called manually. * <p> * Note that this method will be called even if {@link #initializePlugin(InitArguments)} has not been called. */ public void onShutDown() throws Exception { } /** * StagemonitorPlugins can add additional tabs to the in browser widget. * A tab plugin consists of a javascript file and a html file. * <p/> * The files should be placed under * <code>src/main/resources/stagemonitor/static/some/sub/folder/myPlugin[.js|.html]</code> * if you return the path <code>/stagemonitor/static/some/sub/folder/myPlugin</code> * <p/> * The FileServlet serves all files under /src/main/resources/stagemonitor/static and * src/main/resources/stagemonitor/public/static */ public void registerWidgetTabPlugins(WidgetTabPluginsRegistry widgetTabPluginsRegistry) { } @Deprecated public List<String> getPathsOfWidgetTabPlugins() { return Collections.emptyList(); } /** * StagemonitorPlugins can extend the metrics tab in the in browser widget. * A widget metrics tab plugin consists of a javascript file and a html file. * <p/> * The files should be placed under * <code>/src/main/resources/stagemonitor/static/some/sub/folder/{pluginId}[.js|.html]</code> * <p/> * The FileServlet serves all files under /src/main/resources/stagemonitor/static and * /src/main/resources/stagemonitor/public/static * <p/> * For documentation and a example of how a plugin should look like, see * <code>stagemonitor-ehcache/src/main/resources/stagemonitor/static/tabs/metrics</code> and * <code>stagemonitor-jvm/src/main/resources/stagemonitor/static/tabs/metrics</code> */ public void registerWidgetMetricTabPlugins(WidgetMetricTabPluginsRegistry widgetMetricTabPluginsRegistry) { } @Deprecated public List<String> getPathsOfWidgetMetricTabPlugins() { return Collections.emptyList(); } public static class InitArguments { private final Metric2Registry metricRegistry; private final Configuration configuration; private final MeasurementSession measurementSession; public InitArguments(Metric2Registry metricRegistry, Configuration configuration, MeasurementSession measurementSession) { this.metricRegistry = metricRegistry; this.configuration = configuration; this.measurementSession = measurementSession; } public Metric2Registry getMetricRegistry() { return metricRegistry; } public Configuration getConfiguration() { return configuration; } public <T extends StagemonitorPlugin> T getPlugin(Class<T> plugin) { return configuration.getConfig(plugin); } public MeasurementSession getMeasurementSession() { return measurementSession; } } public static class WidgetTabPluginsRegistry { private final List<String> pathsOfWidgetTabPlugins; WidgetTabPluginsRegistry(List<String> pathsOfWidgetTabPlugins) { this.pathsOfWidgetTabPlugins = pathsOfWidgetTabPlugins; } public void addWidgetTabPlugin(String pathOfWidgetTabPlugin) { pathsOfWidgetTabPlugins.add(pathOfWidgetTabPlugin); } } public static class WidgetMetricTabPluginsRegistry { private final List<String> pathsOfWidgetMetricTabPlugins; WidgetMetricTabPluginsRegistry(List<String> pathsOfWidgetMetricTabPlugins) { this.pathsOfWidgetMetricTabPlugins = pathsOfWidgetMetricTabPlugins; } public void addWidgetMetricTabPlugin(String pathOfWidgetMetricTabPlugin) { pathsOfWidgetMetricTabPlugins.add(pathOfWidgetMetricTabPlugin); } } }
923eee6bc9b27e771b3fc4d8babfc58ad913a3ac
112
java
Java
lang/lang-basic/src/main/java/com/zizhizhan/legacies/pattern/proxy/hybrid/Subject.java
zizhizhan/jvm-snippets
527070588e9388fec07045319aae61dc2a1560db
[ "MIT" ]
null
null
null
lang/lang-basic/src/main/java/com/zizhizhan/legacies/pattern/proxy/hybrid/Subject.java
zizhizhan/jvm-snippets
527070588e9388fec07045319aae61dc2a1560db
[ "MIT" ]
3
2022-03-20T12:30:21.000Z
2022-03-20T12:33:02.000Z
lang/lang-basic/src/main/java/com/zizhizhan/legacies/pattern/proxy/hybrid/Subject.java
zizhizhan/jvm-snippets
527070588e9388fec07045319aae61dc2a1560db
[ "MIT" ]
null
null
null
14
53
0.696429
1,000,969
package com.zizhizhan.legacies.pattern.proxy.hybrid; public interface Subject { void request(); }
923eef88cd13fc920be6f14ad2a30b9616e91268
2,409
java
Java
indexcity-report/src/main/java/io/indexcity/report/domain/Item.java
pierre-filliolaud/indexcity
503d54f63ed53ab358af443dcc7d08f422870a53
[ "Apache-2.0" ]
null
null
null
indexcity-report/src/main/java/io/indexcity/report/domain/Item.java
pierre-filliolaud/indexcity
503d54f63ed53ab358af443dcc7d08f422870a53
[ "Apache-2.0" ]
null
null
null
indexcity-report/src/main/java/io/indexcity/report/domain/Item.java
pierre-filliolaud/indexcity
503d54f63ed53ab358af443dcc7d08f422870a53
[ "Apache-2.0" ]
null
null
null
21.9
62
0.598589
1,000,970
package io.indexcity.report.domain; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Field; import java.io.Serializable; import java.math.BigDecimal; import java.time.LocalDate; import java.util.Objects; /** * A Item. */ @Document(collection = "item") public class Item implements Serializable { private static final long serialVersionUID = 1L; @Id private String id; @Field("price") private BigDecimal price; @Field("creation_date") private LocalDate creationDate; @Field("last_update_date") private LocalDate lastUpdateDate; public String getId() { return id; } public void setId(String id) { this.id = id; } public BigDecimal getPrice() { return price; } public Item price(BigDecimal price) { this.price = price; return this; } public void setPrice(BigDecimal price) { this.price = price; } public LocalDate getCreationDate() { return creationDate; } public Item creationDate(LocalDate creationDate) { this.creationDate = creationDate; return this; } public void setCreationDate(LocalDate creationDate) { this.creationDate = creationDate; } public LocalDate getLastUpdateDate() { return lastUpdateDate; } public Item lastUpdateDate(LocalDate lastUpdateDate) { this.lastUpdateDate = lastUpdateDate; return this; } public void setLastUpdateDate(LocalDate lastUpdateDate) { this.lastUpdateDate = lastUpdateDate; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Item item = (Item) o; if(item.id == null || id == null) { return false; } return Objects.equals(id, item.id); } @Override public int hashCode() { return Objects.hashCode(id); } @Override public String toString() { return "Item{" + "id=" + id + ", price='" + price + "'" + ", creationDate='" + creationDate + "'" + ", lastUpdateDate='" + lastUpdateDate + "'" + '}'; } }
923eefb9b5ef4059a88d3f5f7748ef82eba449b1
4,501
java
Java
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/components/YeetSystem.java
OverlakeRobotics/Nocturnal-2020-Ultimate-Goal
fa63b7baa452a99cad98ad97860a9552ebd31f1d
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/components/YeetSystem.java
OverlakeRobotics/Nocturnal-2020-Ultimate-Goal
fa63b7baa452a99cad98ad97860a9552ebd31f1d
[ "MIT" ]
1
2020-09-16T15:05:45.000Z
2020-09-17T12:54:10.000Z
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/components/YeetSystem.java
OverlakeRobotics/Nocturnal-2020-Ultimate-Goal
fa63b7baa452a99cad98ad97860a9552ebd31f1d
[ "MIT" ]
null
null
null
27.278788
89
0.593424
1,000,971
package org.firstinspires.ftc.teamcode.components; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorEx; import com.qualcomm.robotcore.hardware.Servo; import org.firstinspires.ftc.robotcore.internal.system.Deadline; import org.firstinspires.ftc.teamcode.helpers.Constants; import java.util.concurrent.TimeUnit; /** * YeetSystem is a conponent which * * ArmState */ public class YeetSystem { // Arm State private enum ArmState { IDLE, GRAB, RELEASE, START_ARM, MOVING_ARM } // Systems private final DcMotorEx motor; //one motor that we need private final Servo leftServo; private final Servo rightServo; private final Deadline elapsedTime; // Tracker fields private ArmState currentState; private Integer targetPosition; public YeetSystem(DcMotorEx motor, Servo leftServo, Servo rightServo) { //constructor this.motor = motor; //setting ArmSystem motor to whatever motor that is this.leftServo = leftServo; this.rightServo = rightServo; elapsedTime = new Deadline(Constants.SERVO_WAIT_TIME, TimeUnit.MILLISECONDS); motor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); currentState = ArmState.IDLE; grab(); } /** * Places the wobble goal down and releases it * @return if the wobble goal is placed on the ground * RIGHT BUMPER */ public boolean placed() { if (isComplete()) { release(); targetPosition = null; currentState = ArmState.IDLE; return true; } switch (currentState) { case IDLE: currentState = ArmState.START_ARM; break; case START_ARM: targetPosition = Constants.ARM_MOTOR_DOWN_POSITION; moveArm(); break; } return false; } /** * Picks up the wobble goal * @return If the wobble goal is picked up */ public boolean pickedUp(boolean closeServoOnPickup) { if (isComplete()) { shutDown(); targetPosition = null; currentState = ArmState.IDLE; return true; } switch (currentState) { case IDLE: elapsedTime.reset(); if (closeServoOnPickup) { grab(); } else { currentState = ArmState.START_ARM; } break; case GRAB: if (elapsedTime.hasExpired()) { currentState = ArmState.START_ARM; } break; case START_ARM: targetPosition = Constants.ARM_MOTOR_UP_POSITION; moveArm(); break; } return false; } /** * Checks if the system still needs to run * @return if the system still needs to run */ private boolean isComplete() { if (targetPosition == null) { return false; } return (Math.abs(targetPosition - motor.getCurrentPosition()) < 50); } /** * Shuts down the motor */ public void shutDown() { motor.setPower(0.0); } /** * Moves arm either up or down */ private void moveArm() { currentState = ArmState.MOVING_ARM; motor.setTargetPosition(targetPosition); motor.setMode(DcMotor.RunMode.RUN_TO_POSITION); if (targetPosition == Constants.ARM_MOTOR_UP_POSITION) { motor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); motor.setPower(-Constants.ARM_MOTOR_RAW_POWER); } else { motor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.FLOAT); motor.setPower(Constants.ARM_MOTOR_RAW_POWER); } } /** * Closes the servos to grab the wobble goal */ public void grab() { currentState = ArmState.GRAB; leftServo.setPosition(Constants.LEFT_ARM_SERVO_CLOSED_POSITION); rightServo.setPosition(Constants.RIGHT_ARM_SERVO_CLOSED_POSITION); } /** * Opens the servos to release the wobble goal */ public void release() { currentState = ArmState.RELEASE; leftServo.setPosition(Constants.LEFT_ARM_SERVO_OPEN_POSITION); rightServo.setPosition(Constants.RIGHT_ARM_SERVO_OPEN_POSITION); } }