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
3e150fec5bad62168eec14b6606bb1d53fe1bfa7
1,658
java
Java
sqldev/src/main/java/org/utplsql/sqldev/model/runner/PreRunEvent.java
utPLSQL/utPLSQL-SQLDeveloper
55f754056c3749985dc2de001bc40b8ce8f9cd30
[ "Apache-2.0" ]
52
2017-12-19T20:02:39.000Z
2022-01-04T16:21:33.000Z
sqldev/src/main/java/org/utplsql/sqldev/model/runner/PreRunEvent.java
utPLSQL/SQLDeveloper-plugin
edfcc5855ba9e571143712534ace212996b31588
[ "Apache-2.0" ]
92
2018-01-27T17:30:59.000Z
2022-02-27T10:01:56.000Z
sqldev/src/main/java/org/utplsql/sqldev/model/runner/PreRunEvent.java
utPLSQL/SQLDeveloper-plugin
edfcc5855ba9e571143712534ace212996b31588
[ "Apache-2.0" ]
19
2018-02-08T15:06:27.000Z
2022-03-28T06:26:22.000Z
29.857143
75
0.700359
8,937
/* * Copyright 2018 Philipp Salvisberg <upchh@example.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.utplsql.sqldev.model.runner; import java.util.ArrayList; import java.util.List; import org.springframework.core.style.ToStringCreator; import org.utplsql.sqldev.model.JsonToStringStyler; public class PreRunEvent extends RealtimeReporterEvent { private List<Item> items; private Integer totalNumberOfTests; @Override public String toString() { return new ToStringCreator(this, JsonToStringStyler.getInstance()) .append("items", items) .append("totalNumberOfTests", totalNumberOfTests) .toString(); } public PreRunEvent() { items = new ArrayList<>(); } public List<Item> getItems() { return items; } public void setItems(final List<Item> items) { this.items = items; } public Integer getTotalNumberOfTests() { return totalNumberOfTests; } public void setTotalNumberOfTests(final Integer totalNumberOfTests) { this.totalNumberOfTests = totalNumberOfTests; } }
3e15109cc510bb9d5517adc2d4bbaa0e6ba9f99d
972
java
Java
src/services/OtherFunctions.java
kananipratik/WebSearchEngine
34e0d2a9dfb2726dce479a20ef3ac33971b9ab78
[ "MIT" ]
null
null
null
src/services/OtherFunctions.java
kananipratik/WebSearchEngine
34e0d2a9dfb2726dce479a20ef3ac33971b9ab78
[ "MIT" ]
null
null
null
src/services/OtherFunctions.java
kananipratik/WebSearchEngine
34e0d2a9dfb2726dce479a20ef3ac33971b9ab78
[ "MIT" ]
null
null
null
22.604651
80
0.668724
8,938
/** * */ package services; import java.io.File; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.Map; import java.util.Map.Entry; /** * @author Harshit Singh * */ public class OtherFunctions { public static Map<File, Integer> sortCall(LinkedList<Entry<File,Integer>> abc){ return sortIt(abc); } private static Map<File, Integer> sortIt(LinkedList<Entry<File,Integer>> abc) { Collections.sort(abc, new Comparator<Entry<File,Integer>>() { @Override public int compare(Entry<File, Integer> o1, Entry<File, Integer> o2) { // TODO Auto-generated method stub return o2.getValue().compareTo(o1.getValue()); } }); Map<File, Integer> sortedMap = new LinkedHashMap<File, Integer>(); for (Entry<File, Integer> entry : abc) { sortedMap.put(entry.getKey(), entry.getValue()); } return sortedMap; } }
3e1511393c948b72c0d0f4a55c862f61d4535bfa
275
java
Java
src/main/java/com/langmy/terminal/modules/report/dao/OperLiftRecDao.java
RavinPatodia/terminal
c0b4baccaa6c4d0e56d08a6fc35b9ca7b86494e0
[ "Apache-2.0" ]
null
null
null
src/main/java/com/langmy/terminal/modules/report/dao/OperLiftRecDao.java
RavinPatodia/terminal
c0b4baccaa6c4d0e56d08a6fc35b9ca7b86494e0
[ "Apache-2.0" ]
null
null
null
src/main/java/com/langmy/terminal/modules/report/dao/OperLiftRecDao.java
RavinPatodia/terminal
c0b4baccaa6c4d0e56d08a6fc35b9ca7b86494e0
[ "Apache-2.0" ]
null
null
null
18.333333
63
0.716364
8,939
package com.langmy.terminal.modules.report.dao; import com.langmy.terminal.common.dao.BaseDao; import com.langmy.terminal.common.entity.OperLiftRec; /** * 手动抬杆记录Dao * * @author ZZD * */ public interface OperLiftRecDao extends BaseDao<OperLiftRec> { }
3e151149d25ea35069f67805db5e24f3ac3a2539
168
java
Java
src/main/java/com/activepersistence/repository/arel/nodes/Sum.java
lazaronixon/activepersistence
92e9fdaeae7b0fb4296742b7e7ce39ce54479027
[ "MIT" ]
14
2020-07-05T03:09:18.000Z
2022-03-09T17:40:56.000Z
src/main/java/com/activepersistence/repository/arel/nodes/Sum.java
lazaronixon/activepersistence
92e9fdaeae7b0fb4296742b7e7ce39ce54479027
[ "MIT" ]
20
2020-06-13T15:58:39.000Z
2020-11-18T14:21:31.000Z
src/main/java/com/activepersistence/repository/arel/nodes/Sum.java
lazaronixon/activepersistence
92e9fdaeae7b0fb4296742b7e7ce39ce54479027
[ "MIT" ]
2
2020-07-06T02:09:06.000Z
2020-07-06T14:05:19.000Z
16.8
52
0.714286
8,940
package com.activepersistence.repository.arel.nodes; public class Sum extends Function { public Sum(JpqlLiteral expression) { super(expression); } }
3e1511dc8fd9ba053c40d01f540a01eb1c4c20d8
1,538
java
Java
src/main/java/net/segoia/netcell/entities/CopyContextEntity.java
acionescu/netcell
439effa9413f5a4bcc18825b90dd36294b1d9400
[ "Apache-2.0" ]
null
null
null
src/main/java/net/segoia/netcell/entities/CopyContextEntity.java
acionescu/netcell
439effa9413f5a4bcc18825b90dd36294b1d9400
[ "Apache-2.0" ]
null
null
null
src/main/java/net/segoia/netcell/entities/CopyContextEntity.java
acionescu/netcell
439effa9413f5a4bcc18825b90dd36294b1d9400
[ "Apache-2.0" ]
null
null
null
36.619048
95
0.761378
8,941
/** * netcell - Java ESB with an embedded business process modeling engine * Copyright (C) 2009 Adrian Cristian Ionescu - https://github.com/acionescu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.segoia.netcell.entities; import java.util.List; import java.util.Map; import net.segoia.netcell.entities.GenericEntity; import net.segoia.util.data.GenericNameValueContext; public class CopyContextEntity extends GenericEntity<GenericNameValueContext> { public GenericNameValueContext execute(GenericNameValueContext input) throws Exception { Object source = input.getValue("source"); GenericNameValueContext destination = (GenericNameValueContext) input.getValue("destination"); if (source instanceof List) { destination.putAll((List) source); } else if (source instanceof GenericNameValueContext) { ((GenericNameValueContext) source).copyTo(destination); } else if (source instanceof Map) { destination.putAll((Map) source); } return new GenericNameValueContext(); } }
3e15126f9cf1fd11ff31f390b6af39a32374373b
4,923
java
Java
time4j-android/src/main/java/net/time4j/tz/TZID.java
mirfatif/Time4A
a068fd253d2a49939fd44ca8885f72862c71e4e6
[ "Apache-2.0" ]
67
2015-08-23T11:05:18.000Z
2022-02-04T02:29:07.000Z
time4j-android/src/main/java/net/time4j/tz/TZID.java
mirfatif/Time4A
a068fd253d2a49939fd44ca8885f72862c71e4e6
[ "Apache-2.0" ]
1
2020-01-08T13:14:55.000Z
2020-01-15T14:17:52.000Z
time4j-android/src/main/java/net/time4j/tz/TZID.java
mirfatif/Time4A
a068fd253d2a49939fd44ca8885f72862c71e4e6
[ "Apache-2.0" ]
12
2015-12-04T03:13:34.000Z
2021-07-14T08:37:51.000Z
43.955357
82
0.716027
8,942
/* * Licensed by the author of Time4J-project. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. The copyright owner * 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 net.time4j.tz; /** * <p>Identifies a timezone. </p> * * <p>In most cases, the timezone ID has the Olson-format * &quot;{region}/{city}&quot; or is an offset in the format * &quot;UTC&#x00B1;hh:mm&quot;. In latter case applications can * instead directly use an instance of type {@code ZonalOffset}, * especially if the timezone offset for a given timepoint is * already known. </p> * * <p><strong>Provider-specific keys</strong> have the * {@link ZoneModelProvider#getName() name} of the provider followed by the * separator char &quot;~&quot; and the normal canonical identifier. This * form can be used if a custom registered {@link ZoneModelProvider} shall be * used instead of the default provider for lookup of the zonal data. For * example following key will search the timezone data via the API of * {@code java.util.TimeZone} even if there is configured another default * zone provider: &quot;java.util.TimeZone~Europe/Berlin&quot; </p> * * <p>Lexical comparisons of IDs should always be done by the method * {@link #canonical()} because an object of type {@code TZID} is only * designed for encapsulating a canonical name. <strong>The comparison * using the method {@code equals()} is not allowed. </strong></p> * * <p>If a timezone offset is known for historical timezones before the year * 1970 then users should generally prefer the class {@code ZonalOffset} because * the timezone data associated with the enum constants are not necessarily * correct. </p> * * <p><strong>Specification:</strong> * All implementations must be immutable, thread-safe and serializable. </p> * * @author Meno Hochschild */ /*[deutsch] * <p>Identifiziert eine Zeitzone. </p> * * <p>Meistens liegt die ID im Olson-Format &quot;{region}/{city}&quot; oder * als Offset-Angabe im Format &quot;UTC&#x00B1;hh:mm&quot; vor. In letzterem * Fall kann und sollte auch direkt ein Objekt des Typs {@code ZonalOffset} * in Betracht gezogen werden, insbesondere dann, wenn eine Verschiebung * zu einem gegebenen Zeitpunkt schon bekannt ist. </p> * * <p><strong>Provider-spezifische Schl&uuml;ssel</strong> haben den * {@link ZoneModelProvider#getName() Namen} des {@code ZoneModelProvider} gefolgt * von der Tilde &quot;~&quot; und der normalen kanonischen ID. Diese * Form kann verwendet werden, wenn ein registrierter benutzerdefinierter * {@link ZoneModelProvider} an Stelle des Standard-Provider f&uuml;r die * Suche nach den Zeitzonendaten herangezogen werden soll. Zum Beispiel * wird folgender Schl&uuml;ssel die Zeitzonendaten &uuml;ber das API von * {@code java.util.TimeZone} suchen, sogar wenn ein anderer Standard-Provider * eingestellt ist: * &quot;java.util.TimeZone~Europe/Berlin&quot; </p> * * <p>Ein (lexikalischer) Vergleich von IDs sollte immer &uuml;ber die Methode * {@link #canonical()} gemacht werden, weil ein {@code TZID} nur dem Zweck * dient, einen kanonischen Namen zu kapseln. <strong>Der Vergleich &uuml;ber * die Objekt-Methode {@code equals()} ist nicht erlaubt. </strong></p> * * <p>Falls f&uuml;r historische Zeitangaben vor dem Jahr 1970 ein Offset * wohlbekannt ist, ist generell der Klasse {@code ZonalOffset} der Vorzug * vor den Enum-Konstanten zu geben, weil die mit den Enums verkn&uuml;pften * historischen Zeitzonendaten nicht notwendig korrekt sein m&uuml;ssen. </p> * * <p><strong>Specification:</strong> * All implementations must be immutable, thread-safe and serializable. </p> * * @author Meno Hochschild */ public interface TZID { //~ Methoden ---------------------------------------------------------- /** * <p>Represents the full canonical name of a timezone (for * example &quot;Europe/Paris&quot; or &quot;UTC+01:00&quot;). </p> * * @return String in TZDB format (Olson-ID) or in canonical offset format */ /*[deutsch] * <p>Repr&auml;sentiert den vollst&auml;ndigen kanonischen Namen * einer Zeitzone (zum Beispiel &quot;Europe/Paris&quot; oder * &quot;UTC+01:00&quot;). </p> * * @return String in TZDB format (Olson-ID) or in canonical offset format */ String canonical(); }
3e1513d70d866c6d7948255d42da978190bcfd63
530
java
Java
src/main/java/ch/hearc/ig/exercice2/live/Base.java
arnaudgeiser/heg-fp-java
7c7de43d80a08cf52ae2e3f5538f94eee127d3d0
[ "MIT" ]
null
null
null
src/main/java/ch/hearc/ig/exercice2/live/Base.java
arnaudgeiser/heg-fp-java
7c7de43d80a08cf52ae2e3f5538f94eee127d3d0
[ "MIT" ]
null
null
null
src/main/java/ch/hearc/ig/exercice2/live/Base.java
arnaudgeiser/heg-fp-java
7c7de43d80a08cf52ae2e3f5538f94eee127d3d0
[ "MIT" ]
null
null
null
20.384615
60
0.611321
8,943
package ch.hearc.ig.exercice2.live; import java.util.ArrayList; import java.util.List; public class Base { static List<Integer> divisibleBy2(List<Integer> numbers) { List<Integer> tmp = new ArrayList<>(); for (Integer number : numbers) { if (number % 2 == 0) { tmp.add(number); } } return tmp; } static List<Integer> triple(List<Integer> numbers) { List<Integer> tmp = new ArrayList<>(); for (Integer number : numbers) { tmp.add(number * 3); } return tmp; } }
3e1513fe157a1aa50f278357951cb52436452605
4,184
java
Java
cnd/mobility.end2end/src/org/netbeans/modules/mobility/end2end/profiles/alljava/AllJavaProfileProvider.java
leginee/netbeans
814ad30e2d0a094f4aa3813bcbb5323a95a0b1d6
[ "Apache-2.0" ]
null
null
null
cnd/mobility.end2end/src/org/netbeans/modules/mobility/end2end/profiles/alljava/AllJavaProfileProvider.java
leginee/netbeans
814ad30e2d0a094f4aa3813bcbb5323a95a0b1d6
[ "Apache-2.0" ]
null
null
null
cnd/mobility.end2end/src/org/netbeans/modules/mobility/end2end/profiles/alljava/AllJavaProfileProvider.java
leginee/netbeans
814ad30e2d0a094f4aa3813bcbb5323a95a0b1d6
[ "Apache-2.0" ]
null
null
null
44.989247
112
0.760755
8,944
/* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved. * * Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun * Microsystems, Inc. All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. */ package org.netbeans.modules.mobility.end2end.profiles.alljava; import java.util.ArrayList; import org.netbeans.modules.mobility.javon.JavonProfileProvider; import org.netbeans.modules.mobility.javon.JavonTemplate; import org.netbeans.modules.mobility.javon.JavonSerializer; import org.netbeans.modules.mobility.e2e.mapping.JavonMappingImpl; import org.netbeans.modules.mobility.e2e.mapping.RealTypeSerializer; import org.netbeans.modules.mobility.e2e.mapping.PrimitiveTypeSerializer; import org.netbeans.modules.mobility.e2e.mapping.ArrayTypeSerializer; import java.util.List; import java.util.Collections; import java.util.Arrays; import org.netbeans.modules.mobility.e2e.mapping.BeanTypeSerializer; import org.netbeans.modules.mobility.e2e.mapping.CollectionSerializer; import org.netbeans.modules.mobility.e2e.mapping.GenericTypeSerializer; /** * */ @org.openide.util.lookup.ServiceProvider(service=org.netbeans.modules.mobility.javon.JavonProfileProvider.class) public class AllJavaProfileProvider implements JavonProfileProvider { public String getName() { return "alljava"; //NOI18N } public String getDisplayName() { return "All Java Profile"; //NOI18N } public List<JavonTemplate> getTemplates(JavonMappingImpl mapping) { return Collections.<JavonTemplate>emptyList(); } public List<JavonSerializer> getSerializers() { List<JavonSerializer> serializers = new ArrayList<JavonSerializer>(); serializers.add( new PrimitiveTypeSerializer()); serializers.add( new RealTypeSerializer()); serializers.add( new ArrayTypeSerializer()); // serializers.add( new CollectionSerializer()); serializers.add( new GenericTypeSerializer()); serializers.add( new BeanTypeSerializer()); serializers.add( new AllJavaSerializer()); return Collections.unmodifiableList( serializers ); } }
3e1514257e27d27f6d320a606192f90b9cef34bd
395
java
Java
lightning.crawler/src/main/java/com/zhitianweilai/qing/template/engine/ORASTMatchNode.java
shangV2/lightning
144228bc26a601fd16503ab1c66d118f0addcfe7
[ "Apache-2.0" ]
null
null
null
lightning.crawler/src/main/java/com/zhitianweilai/qing/template/engine/ORASTMatchNode.java
shangV2/lightning
144228bc26a601fd16503ab1c66d118f0addcfe7
[ "Apache-2.0" ]
null
null
null
lightning.crawler/src/main/java/com/zhitianweilai/qing/template/engine/ORASTMatchNode.java
shangV2/lightning
144228bc26a601fd16503ab1c66d118f0addcfe7
[ "Apache-2.0" ]
null
null
null
20.789474
74
0.782278
8,945
package com.zhitianweilai.qing.template.engine; import java.util.ArrayList; import java.util.List; public class ORASTMatchNode { private List<ASTMatchNode> childrenNodes = new ArrayList<ASTMatchNode>(); public List<ASTMatchNode> getChildrenNodes() { return childrenNodes; } public void setChildrenNodes(List<ASTMatchNode> childrenNodes) { this.childrenNodes = childrenNodes; } }
3e15146e16b65b2c5e0526c096e711262f02e05e
127
java
Java
ver-05.01/KieaJpaRelation-05-OneToOne-01/src/main/java/org/tain/info/OrderInfo.java
grtlinux/KieaJpaRelation
b5ff34d04cdf5c734f15bc459646a7c4965d1ad8
[ "Apache-2.0" ]
null
null
null
ver-05.01/KieaJpaRelation-05-OneToOne-01/src/main/java/org/tain/info/OrderInfo.java
grtlinux/KieaJpaRelation
b5ff34d04cdf5c734f15bc459646a7c4965d1ad8
[ "Apache-2.0" ]
null
null
null
ver-05.01/KieaJpaRelation-05-OneToOne-01/src/main/java/org/tain/info/OrderInfo.java
grtlinux/KieaJpaRelation
b5ff34d04cdf5c734f15bc459646a7c4965d1ad8
[ "Apache-2.0" ]
null
null
null
11.545455
28
0.716535
8,946
package org.tain.info; public interface OrderInfo { String getOrderCode(); Integer getCount(); Integer getAmount(); }
3e1514b9f531dd2d0d795e4ad37c74a733e15f91
4,192
java
Java
src/com/nullpointerworks/util/file/textfile/TextFile.java
NullpointerWorks/libutil
3618b1e7ae97ed179cc0d14a40833751ef53bc09
[ "Unlicense" ]
null
null
null
src/com/nullpointerworks/util/file/textfile/TextFile.java
NullpointerWorks/libutil
3618b1e7ae97ed179cc0d14a40833751ef53bc09
[ "Unlicense" ]
null
null
null
src/com/nullpointerworks/util/file/textfile/TextFile.java
NullpointerWorks/libutil
3618b1e7ae97ed179cc0d14a40833751ef53bc09
[ "Unlicense" ]
null
null
null
23.418994
194
0.655534
8,947
/* * This is free and unencumbered software released into the public domain. * (http://unlicense.org/) * Nullpointer Works (2021) */ package com.nullpointerworks.util.file.textfile; import com.nullpointerworks.util.Log; import com.nullpointerworks.util.file.Encoding; import com.nullpointerworks.util.pack.Array; /** * Contains the information for a text file consisting of a list of {@code String} objects that represent each line of text. The default encoding is set to "UTF-16" but can be changed if needed. * @since 1.0.0 * @author Michiel Drost - Nullpointer Works * @see Encoding */ public class TextFile { private String encoding = Encoding.UTF16; private String name = ""; private Array<String> lines; /** * Creates an empty {@code TextFile} with UTF-16 encoding. * @since 1.0.0 */ public TextFile() { lines = new Array<String>(); } /** * Creates an empty {@code TextFile} with the specified encoding. * @param encoding - the encoding string, like {@code "UTF-8"}, {@code "UTF-16"}, etc * @since 1.0.0 * @see Encoding */ public TextFile(final String encoding) { this(); setEncoding(encoding); } /** * Returns the encoding string. * @return the encoding string * @since 1.0.0 */ public String getEncoding() { return encoding; } /** * Set the file encoding when writing to disc is desired. The JVM default encoding is {@code "UTF-16"}. * @param encoding - the encoding string, like {@code "UTF-8"}, {@code "UTF-16"}, etc * @since 1.0.0 * @see Encoding */ public void setEncoding(String encoding) { this.encoding = encoding; } /** * Returns the name of the file if available. * @return the name of the file if available * @since 1.0.0 */ public String getName() { return name; } /** * Set the name of the text file. This method is used when reading or writing to a storage device. * @param name - name of the text file * @since 1.0.0 */ public void setName(String name) { this.name = name; } /** * Add a line of text to the file. This line is added to the bottom of the text. * @param line - the text to place * @since 1.0.0 */ public void addLine(String line) { lines.add(line); } /** * Inserts the specified {@code String} at the given index in this list. The {@code String} at the given index is shifted down the list. * @param index - the specified index to place to * @param line - the text to insert * @since 1.0.0 */ public void insertLine(int index, String line) { lines.add(index, line); } /** * Returns the text at the given index if available, {@code null} otherwise. * @param index - the index to read from * @return the text at the given index if available, {@code null} otherwise * @since 1.0.0 */ public String getLine(int index) { if (index < 0 || index >= lines.size()) { Log.err("Error retrieving line from TextFile. Returning null."); return null; } return lines.get(index); } /** * Set the text at the given index to the text provided. If the index is invalid, the edit is cancelled. * @param index - the index to write to * @param line - the text to write * @since 1.0.0 */ public void setLine(int index, String line) { if (index < 0 || index >= lines.size()) { Log.err("Error overwriting index out of bounds. Cancelling edit."); return; } lines.set(index, line); } /** * Returns an array of {@code String} objects with the content of the text file. * @return an array of {@code String} objects with the content of the text file * @since 1.0.0 */ public String[] getLines() { return lines.toArray(new String[0]); } /** * Returns the amount of lines available in the text file. * @return the amount of lines available in the text file * @since 1.0.0 */ public int getSize() { return lines.size(); } /** * Removes all lines of text from the {@code TextFile}. * @since 1.0.0 */ public void clear() { lines.clear(); } /** * Frees all allocated memory for garbage collection and making this object unusable. * @since 1.0.0 */ public void free() { clear(); name = null; encoding = null; } }
3e1515669581b2663f85e9c14e5d1528f1a00508
10,263
java
Java
shared-source/src/edu/ucar/dls/xml/schema/action/AdvancedQueryAction.java
rhuan080/dls-repository-stack
8e19d6a9a3390ce3e3e1031ea8d0f4c5db6eb7d3
[ "ECL-2.0", "Apache-2.0" ]
2
2017-06-16T10:03:46.000Z
2017-07-05T11:15:10.000Z
shared-source/src/edu/ucar/dls/xml/schema/action/AdvancedQueryAction.java
rhuan080/dls-repository-stack
8e19d6a9a3390ce3e3e1031ea8d0f4c5db6eb7d3
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
shared-source/src/edu/ucar/dls/xml/schema/action/AdvancedQueryAction.java
rhuan080/dls-repository-stack
8e19d6a9a3390ce3e3e1031ea8d0f4c5db6eb7d3
[ "ECL-2.0", "Apache-2.0" ]
1
2019-12-03T17:18:43.000Z
2019-12-03T17:18:43.000Z
32.789137
110
0.685764
8,948
/* Copyright 2017 Digital Learning Sciences (DLS) at the University Corporation for Atmospheric Research (UCAR), P.O. Box 3000, Boulder, CO 80307 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package edu.ucar.dls.xml.schema.action; import edu.ucar.dls.schemedit.*; import edu.ucar.dls.xml.schema.*; import edu.ucar.dls.xml.schema.action.form.*; import edu.ucar.dls.xml.*; import edu.ucar.dls.repository.*; import edu.ucar.dls.index.*; import edu.ucar.dls.index.reader.*; import edu.ucar.dls.index.writer.*; import edu.ucar.dls.index.queryParser.*; import edu.ucar.dls.serviceclients.remotesearch.*; import org.apache.lucene.search.*; import org.apache.lucene.queryParser.QueryParser; import edu.ucar.dls.vocab.MetadataVocab; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.Node; import java.util.*; import java.io.*; import java.util.Hashtable; import java.util.Locale; import javax.servlet.*; import javax.servlet.http.*; import org.apache.struts.action.Action; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionServlet; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.util.MessageResources; import java.net.URLEncoder; import java.net.URLDecoder; /** * Just a minimal action that will set up a form bean and then forward to a jsp * page this action depends upon an action-mapping in the struts-config file! * *@author ostwald */ public final class AdvancedQueryAction extends Action { private static boolean debug = true; private FieldBean fieldBean = null; // --------------------------------------------------------- Public Methods /** * Processes the specified HTTP request and creates the corresponding HTTP * response by forwarding to a JSP that will create it. Returns an {@link * org.apache.struts.action.ActionForward} instance that maps to the Struts * forwarding name "xxx.xxx," which must be configured in struts-config.xml to * forward to the JSP page that will handle the request. * *@param mapping Description of the Parameter *@param form Description of the Parameter *@param request Description of the Parameter *@param response Description of the Parameter *@return Description of the Return Value *@exception IOException Description of the Exception *@exception ServletException Description of the Exception */ public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { /* * Design note: * Only one instance of this class gets created for the app and shared by * all threads. To be thread-safe, use only local variables, not instance * variables (the JVM will handle these properly using the stack). Pass * all variables via method signatures rather than instance vars. */ prtln ("\nexecuting"); ActionErrors errors = new ActionErrors(); ActionMessages messages = new ActionMessages(); AdvancedQueryForm aqf; MetaDataFramework framework = null; try { aqf = (AdvancedQueryForm) form; } catch (Throwable e) { prtln("AdvancedQueryAction caught exception. " + e); return null; } String errorMsg; FrameworkRegistry frameworkRegistry = getRegistry(); List xmlFormats = frameworkRegistry.getAllFormats(); aqf.setFrameworks(xmlFormats); try { fieldBean = new FieldBean (getFrameworks(xmlFormats)); } catch (Exception e) { throw new ServletException (e.getMessage()); } // RemoteSearcher rs = (RemoteSearcher) servlet.getServletContext().getAttribute("RemoteSearcher"); // Query Args String command = request.getParameter("command"); SchemEditUtils.showRequestParameters(request); if (command == null) { return mapping.findForward("advanced.query"); } if (command.equals("search")) { return doSearch (mapping, form, request, response); } if (command.equals("getChoices")) { String level = request.getParameter("level"); String parent = request.getParameter("parent"); aqf.setChoices (fieldBean.getChoices (Integer.parseInt(level), parent)); return mapping.findForward ("advanced.query.choices"); } return mapping.findForward("advanced.query"); } private ActionForward doSearch( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { prtln ("doSearch"); AdvancedQueryForm aqf = (AdvancedQueryForm) form; RepositoryManager rm = (RepositoryManager) servlet.getServletContext().getAttribute("repositoryManager"); ResultDocList results = ddsStandardQuery (request, rm, servlet.getServletContext()); prtln (results.size() + " results found"); aqf.setResults(results); return mapping.findForward("advanced.query"); } /** * Performs textual and field-based searches limited to discoverable items only and using pre-defined search * logic. Used by DDS search and DDSWebServices search. * * @param request The HTTP request * @param rm The RepositoryManager * @param vocab The MetadataVocab * @param context The ServletContext * @param searchType The searchType that gets logged * @param additionalQueryOrConstraint If the q parameter is empty, this value will be used as the search * query, if q is not empty this value will be ANDed with it * @return A DDSStandardSearchResult that contains the search results and a * String indicating which page to forward to for presentataion. */ public static ResultDocList ddsStandardQuery( HttpServletRequest request, RepositoryManager rm, ServletContext context) { String s = request.getParameter("s"); ResultDocList resultDocs = null; SimpleLuceneIndex index = rm.getIndex(); BooleanQuery booleanQuery = new BooleanQuery(); QueryParser qp = index.getQueryParser(); Enumeration paramEnum = request.getParameterNames(); while (paramEnum.hasMoreElements()) { String paramName = (String)paramEnum.nextElement(); prtln ("param: " + paramName); if (paramName.startsWith("field_")) { String num = paramName.substring("field_".length()); prtln ("num: " + num); String field = request.getParameter(paramName); String value = request.getParameter("value_"+num); if (value == null || value.trim().length() == 0) continue; //HARDCODE to do key matching for now // What kind of match are we doing?? String match = request.getParameter("match_"+num); if (match == null) match = "exact"; String fieldType = ("exact".equals(match) ? "key" : "text"); String clause = null; BooleanClause.Occur occur = BooleanClause.Occur.MUST; if (value.equals("ANY")) { clause = "indexedXpaths:\""+field+"\""; } else if (value.equals("NONE")) { clause = "indexedXpaths:\""+field+"\""; occur = BooleanClause.Occur.MUST_NOT; } else { clause = "/"+fieldType+"/"+field+":\""+value+"\""; } try { booleanQuery.add(qp.parse(clause), occur); } catch (Exception e) { prtln ("Parse Error: " + e.getMessage()); } } } prtln ("query: " + booleanQuery); resultDocs = index.searchDocs(booleanQuery); int numSearchResults = (resultDocs == null) ? 0 : resultDocs.size(); return resultDocs; } private List getFrameworks (List xmlFormats) throws Exception { FrameworkRegistry frameworkRegistry = getRegistry(); List frameworks = new ArrayList(); for (Iterator i=xmlFormats.iterator();i.hasNext();) { String xmlFormat = (String)i.next(); try { frameworks.add (frameworkRegistry.getFramework(xmlFormat)); } catch (Exception e) { prtln ("ERROR: could not get framework for \"" + xmlFormat + "\":" + e.getMessage()); } } return frameworks; } private FrameworkRegistry getRegistry () throws ServletException { FrameworkRegistry reg = (FrameworkRegistry)servlet.getServletContext() .getAttribute("frameworkRegistry"); if (reg == null) { throw new ServletException ("frameworkRegistry not found in servletContext"); } else { return reg; } } private ActionErrors setGlobalDef (String path, SchemaHelper schemaHelper, AdvancedQueryForm aqf) { ActionErrors errors = new ActionErrors (); GlobalDef globalDef = schemaHelper.getGlobalDefFromXPath(path); if (globalDef == null) { errors.add(errors.GLOBAL_ERROR, new ActionError("schemaviewer.def.notfound.error", path)); } else { aqf.setGlobalDef(globalDef); // aqf.setTypeName(globalDef.getName()); } return errors; } private MetaDataFramework getMetaDataFramework(String xmlFormat) throws ServletException { return getRegistry().getFramework (xmlFormat); } private void prtParam (String name, String value) { if (value == null) prtln(name + " is null"); else prtln(name + " is " + value); } /** * Print a line to standard out. * *@param s The String to print. */ private static void prtln(String s) { if (debug) { // System.out.println("AdvancedQueryAction: " + s); SchemEditUtils.prtln (s, "AdvancedQueryAction"); } } }
3e151586e14f5a8adcbd2e53b3fab8bb203d6200
2,892
java
Java
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/ContactHelper.java
margorud/learn
92796c85480f0a64deb929bccf9f7dc70e0b7329
[ "Apache-2.0" ]
null
null
null
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/ContactHelper.java
margorud/learn
92796c85480f0a64deb929bccf9f7dc70e0b7329
[ "Apache-2.0" ]
null
null
null
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/ContactHelper.java
margorud/learn
92796c85480f0a64deb929bccf9f7dc70e0b7329
[ "Apache-2.0" ]
null
null
null
30.765957
111
0.646957
8,949
package ru.stqa.pft.addressbook.appmanager; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.Select; import org.testng.Assert; import ru.stqa.pft.addressbook.model.ContactData; import java.util.ArrayList; import java.util.List; public class ContactHelper extends HelperBase { public ContactHelper(WebDriver wd) { super(wd); } public void fillContactForm(ContactData contactData, boolean creation) { type(By.name("firstname"), contactData.getFirstname()); type(By.name("middlename"), contactData.getMiddlename()); type(By.name("lastname"), contactData.getLastname()); type(By.name("nickname"), contactData.getNickname()); if (creation) { new Select(wd.findElement(By.name("new_group"))).selectByVisibleText(contactData.getGroup()); } else { Assert.assertFalse(isElementPresent(By.name("new_group"))); } } public void submitContactCreation() { click(By.name("submit")); } public void returnToHomePage() { click(By.linkText("home page")); } public void selectContact(int index) { wd.findElements(By.name("selected[]")).get(index).click(); } public void deleteSelectedContacts() { click(By.xpath("//div[2]/input")); } public void acceptDeleteContacts() { acceptAlert(); } public void initContactModification() { click(By.xpath("//table[@id='maintable']/tbody/tr[2]/td[8]/a/img")); } public void submitContactModification() { click(By.name("update")); } public void create(ContactData contact, Boolean creation) { fillContactForm(contact, creation); submitContactCreation(); returnToHomePage(); } public void modify(ContactData contact, int index) { selectContact(index); initContactModification(); fillContactForm(contact, false); submitContactModification(); returnToHomePage(); } public void delete(int index) { selectContact(index); deleteSelectedContacts(); acceptDeleteContacts(); } public List<ContactData> list() { List<ContactData> contacts = new ArrayList<>(); List<WebElement> elements = wd.findElements(By.name("entry")); for (WebElement element : elements) { String lastname = element.findElement(By.xpath("td[2]")).getText(); String firstname = element.findElement(By.xpath("td[3]")).getText(); int id = Integer.parseInt(element.findElement(By.tagName("input")).getAttribute("value")); ContactData contact = new ContactData().withId(id).withFirstname(firstname).withLastname(lastname); contacts.add(contact); } return contacts; } }
3e15159a4259e2e38439835b39e9133ed015160a
3,402
java
Java
test/File5.java
amanster82/SENG_371
0f527f0eb75b0877d29701d47e8ce63a6a509ec0
[ "MIT" ]
null
null
null
test/File5.java
amanster82/SENG_371
0f527f0eb75b0877d29701d47e8ce63a6a509ec0
[ "MIT" ]
null
null
null
test/File5.java
amanster82/SENG_371
0f527f0eb75b0877d29701d47e8ce63a6a509ec0
[ "MIT" ]
null
null
null
25.014706
100
0.743974
8,950
/** * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * This program 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 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * This software was written for the * Department of Family Medicine * McMaster University * Hamilton * Ontario, Canada */ package org.oscarehr.sharingcenter.model; import java.io.Serializable; import javax.persistence.*; import org.marc.shic.core.configuration.IheValueSetConfiguration; import org.oscarehr.common.model.AbstractModel; @Entity @Table(name = "sharing_value_set") public class ValueSetDataObject extends AbstractModel<Integer> implements Serializable { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "value_set_id") public String valueSetId; @Column(name = "description") public String description; @Column(name = "attribute") public String attribute; @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name = "domain_fk") public AffinityDomainDataObject sharing_affinity_domain; public ValueSetDataObject() { } public ValueSetDataObject(String valueSetId, String description, String attribute) { this.valueSetId = valueSetId; this.description = description; this.attribute = attribute; } public ValueSetDataObject(IheValueSetConfiguration valueSet) { this.valueSetId = valueSet.getId(); this.description = valueSet.getDescription(); this.attribute = valueSet.getAttribute(); } public Integer getId() { return id; } /** * @return the setId */ public String getValueSetId() { return valueSetId; } /** * @param setId the setId to set */ public void setSetId(String valueSetId) { this.valueSetId = valueSetId; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } /** * @return the attribute */ public String getAttribute() { return attribute; } /** * @param attribute the attribute to set */ public void setAttribute(String attribute) { this.attribute = attribute; } /** * @return the affinityDomain */ public AffinityDomainDataObject getAffinityDomain() { return affinityDomain; } /** * @param affinityDomain the affinityDomain to set */ public void setAffinityDomain(AffinityDomainDataObject affinityDomain) { this.affinityDomain = affinityDomain; } public IheValueSetConfiguration createIheValueSetConfiguration() { return new IheValueSetConfiguration(valueSetId, description, attribute); } }
3e1515da8166686d0a4ff277bb1fbeb86d8418c8
535
java
Java
src/main/java/pl/sdacademy/tarr2019java4/tdd/App.java
jakub-olszewski/tarr2019java4-tdd
4c2419c23191a58d323d41f8a51a2c327857850a
[ "MIT" ]
null
null
null
src/main/java/pl/sdacademy/tarr2019java4/tdd/App.java
jakub-olszewski/tarr2019java4-tdd
4c2419c23191a58d323d41f8a51a2c327857850a
[ "MIT" ]
null
null
null
src/main/java/pl/sdacademy/tarr2019java4/tdd/App.java
jakub-olszewski/tarr2019java4-tdd
4c2419c23191a58d323d41f8a51a2c327857850a
[ "MIT" ]
null
null
null
15.285714
63
0.547664
8,951
package pl.sdacademy.tarr2019java4.tdd; //generate test //alt + enter /** * App * * @author: Jakub Olszewski [http://github.com/jakub-olszewski] * @date: 23.11.2019 18:00 **/ public class App { //code format //ctrl+alt+L // alt + insert + enter // generate code //psvm + tab public static void main(String[] args) { String a = "3"; String b = "4"; int c = 5; int d = 6; System.out.println(a+b);// złączenie napisów System.out.println(c+d); } }
3e1517498d06a1b3481fc25e9eeead0869675a7d
831
java
Java
jsonapiadapter/src/main/java/com/nextmatch/vero/jsonapiadapter/retrofit/RetrofitJsonApiHelper.java
vero-amanda/GsonApiAdapter
7fe5bd56fe3e67ba10fba744f9614bdc45918c29
[ "Apache-2.0" ]
null
null
null
jsonapiadapter/src/main/java/com/nextmatch/vero/jsonapiadapter/retrofit/RetrofitJsonApiHelper.java
vero-amanda/GsonApiAdapter
7fe5bd56fe3e67ba10fba744f9614bdc45918c29
[ "Apache-2.0" ]
null
null
null
jsonapiadapter/src/main/java/com/nextmatch/vero/jsonapiadapter/retrofit/RetrofitJsonApiHelper.java
vero-amanda/GsonApiAdapter
7fe5bd56fe3e67ba10fba744f9614bdc45918c29
[ "Apache-2.0" ]
null
null
null
31.961538
118
0.776173
8,952
package com.nextmatch.vero.jsonapiadapter.retrofit; import com.google.gson.internal.Primitives; import com.nextmatch.vero.jsonapiadapter.internal.JsonApiResponseAdapter; import com.nextmatch.vero.jsonapiadapter.model.Resource; import retrofit2.Response; /** * @author vero * @since 2016. 11. 30. */ public final class RetrofitJsonApiHelper { @SuppressWarnings("unchecked") public static <T extends Resource> JsonApiResponseAdapter<T> getJsonApiAdapterFromResponse(Response<T> response) { return Primitives.wrap(JsonApiResponseAdapter.class).cast(response.body()); } @SuppressWarnings("unchecked") public static <T extends Resource> JsonApiResponseAdapter<T> getJsonApiAdapterFromResource(Resource resource) { return Primitives.wrap(JsonApiResponseAdapter.class).cast(resource); } }
3e15183cf7e635f87315063c635ca1708b9a5196
2,592
java
Java
src/main/java/com/cgomez/xml/Layout.java
andres1537/dl-java
a6768187c4c01430afc287d133cdb2592a5e7685
[ "MIT" ]
null
null
null
src/main/java/com/cgomez/xml/Layout.java
andres1537/dl-java
a6768187c4c01430afc287d133cdb2592a5e7685
[ "MIT" ]
null
null
null
src/main/java/com/cgomez/xml/Layout.java
andres1537/dl-java
a6768187c4c01430afc287d133cdb2592a5e7685
[ "MIT" ]
null
null
null
26.721649
112
0.61034
8,953
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // 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.08.11 at 12:47:19 AM ART // package com.cgomez.xml; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlMixed; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.w3c.dom.Element; /** * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "content" }) @XmlRootElement(name = "layout") public class Layout { @XmlAttribute(name = "logo") @XmlJavaTypeAdapter(NormalizedStringAdapter.class) protected String logo; @XmlMixed @XmlAnyElement protected List<Object> content; /** * Gets the value of the logo property. * * @return * possible object is * {@link String } * */ public String getLogo() { return logo; } /** * Sets the value of the logo property. * * @param value * allowed object is * {@link String } * */ public void setLogo(String value) { this.logo = value; } /** * Gets the value of the content property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the content property. * * <p> * For example, to add a new item, do as follows: * <pre> * getContent().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * {@link Element } * * */ public List<Object> getContent() { if (content == null) { content = new ArrayList<Object>(); } return this.content; } }
3e1518407ae07f8489994acaf610427886a0a4d9
2,227
java
Java
src/main/java/com/github/vioao/wechat/utils/signature/XmlParse.java
littlebadegg/wechat-sdk
c12e22d9d26913158fb8edbaeee8ed46fad7d78a
[ "Apache-2.0" ]
47
2018-01-21T02:01:57.000Z
2021-09-06T08:42:04.000Z
src/main/java/com/github/vioao/wechat/utils/signature/XmlParse.java
littlebadegg/wechat-sdk
c12e22d9d26913158fb8edbaeee8ed46fad7d78a
[ "Apache-2.0" ]
3
2018-05-06T14:45:53.000Z
2022-01-08T01:32:03.000Z
src/main/java/com/github/vioao/wechat/utils/signature/XmlParse.java
littlebadegg/wechat-sdk
c12e22d9d26913158fb8edbaeee8ed46fad7d78a
[ "Apache-2.0" ]
21
2018-03-16T06:10:57.000Z
2020-05-06T09:21:22.000Z
32.275362
101
0.591828
8,954
/** * 对公众平台发送给公众账号的消息加解密示例代码. * * @copyright Copyright (c) 1998-2014 Tencent Inc. */ // ------------------------------------------------------------------------ package com.github.vioao.wechat.utils.signature; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.StringReader; /** * 提供提取消息格式中的密文及生成回复消息格式的接口. */ public class XmlParse { /** * 提取出xml数据包中的加密消息. * * @param xml 待提取的xml字符串 * @return 提取出的加密消息字符串 */ public static String[] extractToUserNameAndEncrypt(String xml) { String[] result = new String[2]; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); StringReader sr = new StringReader(xml); InputSource is = new InputSource(sr); Document document = db.parse(is); Element root = document.getDocumentElement(); NodeList encryptNodeList = root.getElementsByTagName("Encrypt"); NodeList toUserNameNodeList = root.getElementsByTagName("ToUserName"); result[0] = toUserNameNodeList.item(0).getTextContent(); result[1] = ""; if (encryptNodeList.getLength() > 0) { result[1] = encryptNodeList.item(0).getTextContent(); } return result; } catch (Exception e) { throw new RuntimeException("xml解析失败", e); } } /** * 生成xml消息. * * @param encrypt 加密后的消息密文 * @param signature 安全签名 * @param timestamp 时间戳 * @param nonce 随机字符串 * @return 生成的xml字符串 */ public static String generate(String encrypt, String signature, String timestamp, String nonce) { String format = "<xml>\n" + "<Encrypt><![CDATA[%1$s]]></Encrypt>\n" + "<MsgSignature><![CDATA[%2$s]]></MsgSignature>\n" + "<TimeStamp>%3$s</TimeStamp>\n" + "<Nonce><![CDATA[%4$s]]></Nonce>\n" + "</xml>"; return String.format(format, encrypt, signature, timestamp, nonce); } }
3e15185cad63cb55cb9f4d97b13bd716a7737c49
260
java
Java
src/main/java/fr/isep/models/CategoryEventLog.java
PatWg/TangiSimu
86965727fc42739076c2dbda4e34ef6b144c7e78
[ "MIT" ]
null
null
null
src/main/java/fr/isep/models/CategoryEventLog.java
PatWg/TangiSimu
86965727fc42739076c2dbda4e34ef6b144c7e78
[ "MIT" ]
23
2018-11-21T21:32:51.000Z
2018-12-05T18:52:25.000Z
src/main/java/fr/isep/models/CategoryEventLog.java
PatWg/TangiSimu
86965727fc42739076c2dbda4e34ef6b144c7e78
[ "MIT" ]
null
null
null
17.333333
48
0.669231
8,955
package fr.isep.models; public class CategoryEventLog extends EventLog { private String newValue; public String getNewValue() { return newValue; } public void setNewValue(String newValue) { this.newValue = newValue; } }
3e1518beacc19c5c55d4fc718dcd30129b7466c6
1,000
java
Java
framework/tests/flow2/Equal.java
twistedsquare/checker-framework
35b682c252a390924fefe3e12f5dcc57971cf9eb
[ "MIT" ]
877
2015-07-04T19:51:28.000Z
2022-03-25T07:40:52.000Z
framework/tests/flow2/Equal.java
smonteiro/checker-framework
967490a52d69c4658b8cc2461c5dce06a016f1e7
[ "MIT" ]
2,468
2015-07-06T18:17:19.000Z
2022-03-31T16:56:39.000Z
framework/tests/flow2/Equal.java
smonteiro/checker-framework
967490a52d69c4658b8cc2461c5dce06a016f1e7
[ "MIT" ]
427
2015-07-07T15:52:48.000Z
2022-03-20T21:52:22.000Z
22.727273
76
0.545
8,956
import org.checkerframework.framework.testchecker.util.*; public class Equal { String f1, f2, f3; // annotation inference for equality void t1(@Odd String p1, String p2) { // :: error: (assignment) @Odd String l1 = f1; if (f1 == p1) { @Odd String l2 = f1; } else { // :: error: (assignment) @Odd String l3 = f1; } } // annotation inference for equality void t2(@Odd String p1, String p2) { // :: error: (assignment) @Odd String l1 = f1; if (f1 != p1) { // :: error: (assignment) @Odd String l2 = f1; } else { @Odd String l3 = f1; } } void t3(@Odd Long p1) { // :: error: (assignment) @Odd Long l1 = Long.valueOf(2L); if (Long.valueOf(2L) == p1) { // The result of valueOf is not deterministic, so it can't be refined. // :: error: (assignment) @Odd Long l2 = Long.valueOf(2L); } else { // :: error: (assignment) @Odd Long l3 = Long.valueOf(2L); } } }
3e1519aea7e1f545258b22300c1f8ad91680faff
549
java
Java
1232.check-if-it-is-a-straight-line.java
RobertSasak/leetcode
25926aa7c92b6be5633520debf8a714eaf9406f5
[ "MIT" ]
1
2020-03-09T17:41:39.000Z
2020-03-09T17:41:39.000Z
1232.check-if-it-is-a-straight-line.java
RobertSasak/leetcode
25926aa7c92b6be5633520debf8a714eaf9406f5
[ "MIT" ]
null
null
null
1232.check-if-it-is-a-straight-line.java
RobertSasak/leetcode
25926aa7c92b6be5633520debf8a714eaf9406f5
[ "MIT" ]
null
null
null
22.875
78
0.493625
8,957
/* * @lc app=leetcode id=1232 lang=java * * [1232] Check If It Is a Straight Line */ // @lc code=start class Solution { public boolean checkStraightLine(int[][] coordinates) { for (int i = 2; i < coordinates.length; i++) { if (!onLine(coordinates[0], coordinates[1], coordinates[i])) { return false; } } return true; } boolean onLine(int[] a, int[] b, int[] c) { return (a[0] - b[0]) * (a[1] - c[1]) == (a[0] - c[0]) * (a[1] - b[1]); } } // @lc code=end
3e151a2db63601744f0d2266c30a36258da5b0b0
3,005
java
Java
src/jean/peptide/PeptideConcentrationBuilder.java
tipplerow/jean
bd39b3a209bf9d78b89ea4c133f6b6669006cde3
[ "Apache-2.0" ]
null
null
null
src/jean/peptide/PeptideConcentrationBuilder.java
tipplerow/jean
bd39b3a209bf9d78b89ea4c133f6b6669006cde3
[ "Apache-2.0" ]
null
null
null
src/jean/peptide/PeptideConcentrationBuilder.java
tipplerow/jean
bd39b3a209bf9d78b89ea4c133f6b6669006cde3
[ "Apache-2.0" ]
null
null
null
30.353535
83
0.659235
8,958
package jean.peptide; import java.util.Collection; import java.util.HashMap; import java.util.Map; import jean.chem.Concentration; /** * Maps peptides to cellular concentrations. */ public final class PeptideConcentrationBuilder { private final Map<Peptide, Concentration> map = new HashMap<Peptide, Concentration>(); private PeptideConcentrationBuilder() { } /** * Creates a new (empty) profile builder. * * @return a new (empty) profile profile. */ public static PeptideConcentrationBuilder create() { return new PeptideConcentrationBuilder(); } /** * Adds a positive peptide concentration to this builder. * * <p>If the peptide is already present, the specified * concentration is added to the existing concentration. * * <p>Concentrations that are equal to zero (within the standard * floating-point tolerance) will <em>not</em> be added, so that * the profile will only contain peptides with a net positive * concentration. * * @param peptide the peptide to add. * * @param concentration the concentration of the peptide. */ public void add(Peptide peptide, Concentration concentration) { if (!concentration.isPositive()) return; Concentration existing = map.get(peptide); if (existing == null) map.put(peptide, concentration); else map.put(peptide, existing.plus(concentration)); } /** * Adds a positive peptide concentration to this builder. * * <p>If the peptide is already present, the specified * concentration is added to the existing concentration. * * <p>Concentrations that are equal to zero (within the standard * floating-point tolerance) will <em>not</em> be added, so that * the profile will only contain peptides with a net positive * concentration. * * @param record the concentration record to add. */ public void add(PeptideConcentration record) { add(record.getPeptide(), record.getConcentration()); } /** * Adds peptides to this profile. * * <p>If any peptide is already present in this profile, the * specified concentration is added to its existing concentration. * * @param peptides the peptides to add. * * @param concentration the uniform concentration of each peptide. */ public void addAll(Collection<Peptide> peptides, Concentration concentration) { for (Peptide peptide : peptides) add(peptide, concentration); } /** * Creates a new (read-only) peptide concentration profile * reflecting the current state of this builder. * * @return a new (read-only) peptide concentration profile * containing the concentrations currenly in this builder. */ public PeptideConcentrationProfile build() { return PeptideConcentrationProfile.create(map); } }
3e151aaa8655c15530e20ada90637884ddf17662
317
java
Java
src/main/java/be/gest/dao/FournisseurDAO.java
bellalDjam/hccmed
07e3cc66592fea98b55931188a16498bd2c43311
[ "Apache-2.0" ]
null
null
null
src/main/java/be/gest/dao/FournisseurDAO.java
bellalDjam/hccmed
07e3cc66592fea98b55931188a16498bd2c43311
[ "Apache-2.0" ]
null
null
null
src/main/java/be/gest/dao/FournisseurDAO.java
bellalDjam/hccmed
07e3cc66592fea98b55931188a16498bd2c43311
[ "Apache-2.0" ]
null
null
null
19.8125
66
0.794953
8,959
package be.gest.dao; import java.util.List; import be.gest.model.Facture; import be.gest.model.Fournisseur; public interface FournisseurDAO extends AbstractDao<Fournisseur> { List<Fournisseur> findAll(); Fournisseur findFournisseurById(Long id); List<Fournisseur> findImpayedFournisseur(Facture factur); }
3e151aafeefa34908fd1b935c9861ac8b9edb23f
2,812
java
Java
src/main/java/net/binaryvibrance/schematicmetablocks/blocks/InteriorAirMarker.java
AtomicBlom/SchematicaModderExtensions
d73686bbb1d1593690ad9caaa04373eb80b63f0c
[ "MIT" ]
5
2015-01-13T05:19:46.000Z
2016-12-10T23:32:46.000Z
src/main/java/net/binaryvibrance/schematicmetablocks/blocks/InteriorAirMarker.java
AtomicBlom/SchematicaModderExtensions
d73686bbb1d1593690ad9caaa04373eb80b63f0c
[ "MIT" ]
4
2015-02-14T15:10:20.000Z
2015-05-22T11:44:49.000Z
src/main/java/net/binaryvibrance/schematicmetablocks/blocks/InteriorAirMarker.java
AtomicBlom/SchematicaModderExtensions
d73686bbb1d1593690ad9caaa04373eb80b63f0c
[ "MIT" ]
1
2018-10-09T10:42:03.000Z
2018-10-09T10:42:03.000Z
27.841584
116
0.6867
8,960
package net.binaryvibrance.schematicmetablocks.blocks; import net.binaryvibrance.schematicmetablocks.jobs.ChunkToProcess; import net.binaryvibrance.schematicmetablocks.jobs.JobProcessor; import net.binaryvibrance.schematicmetablocks.jobs.JobType; import net.binaryvibrance.schematicmetablocks.library.ModBlock; import net.binaryvibrance.schematicmetablocks.proxy.ClientProxy; import net.binaryvibrance.schematicmetablocks.tileentity.InteriorAirMarkerTileEntity; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; public class InteriorAirMarker extends MetaBlock { public static final String NAME = "blockInteriorAirMarker"; public InteriorAirMarker() { super(Material.glass); this.setBlockName(NAME); this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.15F, 1.0F); } @Override public boolean renderAsNormalBlock() { return false; } @Override public int getRenderType() { return ClientProxy.insideMetadataBlockRendererId; } @Override public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) { ForgeDirection direction = ForgeDirection.getOrientation(side); Block b = world.getBlock(x + direction.offsetX, y + direction.offsetY, z + direction.offsetZ); if (b instanceof ImplicitAirBlock || b instanceof InteriorAirMarker) { return null; } return super.getIcon(world, x, y, z, side); } @Override public boolean isOpaqueCube() { return false; } @Override public void onBlockDestroyedByPlayer(World world, int x, int y, int z, int p_149664_5_) { world.setBlock(x, y, z, ModBlock.blockImplicitAir, 0, 3); } @Override public int getRenderBlockPass() { return 1; } @Override public int onBlockPlaced(World world, int x, int y, int z, int side, float tu, float tv, float tw, int metadata) { if (!world.isRemote) { ChunkToProcess chunkToProcess = new ChunkToProcess(world, x >> 4, z >> 4); JobProcessor.Instance.scheduleJob(JobType.BACKGROUND, chunkToProcess); } return metadata; } @Override public boolean hasTileEntity(int metadata) { return true; } @Override public TileEntity createTileEntity(World world, int metadata) { return new InteriorAirMarkerTileEntity(); } @Override public boolean canRenderInPass(int pass) { ClientProxy.renderPass = pass; return pass != 0; } }
3e151b5c417d4cffbd4f8c692e824546c04ade4c
13,441
java
Java
mas-foundation/src/androidTest/java/com/ca/mas/foundation/MASRegistrationTest.java
dnys1/Android-MAS-SDK
e8e5c3850c9566080457eb2344f911042435d130
[ "MIT" ]
13
2016-11-01T20:03:06.000Z
2020-01-09T19:52:37.000Z
mas-foundation/src/androidTest/java/com/ca/mas/foundation/MASRegistrationTest.java
dnys1/Android-MAS-SDK
e8e5c3850c9566080457eb2344f911042435d130
[ "MIT" ]
41
2016-09-28T19:54:23.000Z
2021-09-29T09:43:31.000Z
mas-foundation/src/androidTest/java/com/ca/mas/foundation/MASRegistrationTest.java
dnys1/Android-MAS-SDK
e8e5c3850c9566080457eb2344f911042435d130
[ "MIT" ]
31
2016-08-25T17:14:20.000Z
2022-01-28T07:14:54.000Z
46.890785
184
0.658782
8,961
/* * Copyright (c) 2016 CA. All rights reserved. * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ package com.ca.mas.foundation; import com.ca.mas.GatewayDefaultDispatcher; import com.ca.mas.MASCallbackFuture; import com.ca.mas.MASStartTestBase; import com.ca.mas.core.registration.RegistrationServerException; import com.ca.mas.core.store.ClientCredentialContainer; import com.ca.mas.core.store.OAuthTokenContainer; import com.ca.mas.core.store.StorageProvider; import com.ca.mas.core.store.TokenManager; import junit.framework.Assert; import org.json.JSONObject; import org.junit.Ignore; import org.junit.Test; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.util.concurrent.ExecutionException; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.RecordedRequest; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.assertTrue; public class MASRegistrationTest extends MASStartTestBase { @Test public void testRenewCertification() throws URISyntaxException, InterruptedException, IOException, ExecutionException { setDispatcher(new GatewayDefaultDispatcher() { @Override protected MockResponse registerDeviceResponse(RecordedRequest request) { // Expired cert to trigger renew String cert = "-----BEGIN CERTIFICATE-----\n" + "kgfhvu9qnh3mr6eel97y6fq2hezzol8z" + "9jnerlff23u8ed01np9g6ysbhsh0dvcs" + "MDEwNjMwWhcNMTYxMTE5MDEwNjMwWjAtMQswCQYDVQQGEwJHQjEPMA0GA1UEBxMG\n" + "ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6b" + "ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6b" + "caf86f4uutaoxfysmf7anj01xl6sv3ps" + "caf86f4uutaoxfysmf7anj01xl6sv3ps" + "kgfhvu9qnh3mr6eel97y6fq2hezzol8z" + "9jnerlff23u8ed01np9g6ysbhsh0dvcs" + "kgfhvu9qnh3mr6eel97y6fq2hezzol8z" + "-----END CERTIFICATE-----"; return new MockResponse() .setResponseCode(200) .setHeader("device-status", "activated") .setHeader("mag-identifier", "test-device") .setHeader("id-token", "dummy-idToken") .setHeader("id-token-type", "dummy-idTokenType") .setBody(cert); } }); MASRequest request = new MASRequest.MASRequestBuilder(new URI(GatewayDefaultDispatcher.PROTECTED_RESOURCE_PRODUCTS)).build(); MASCallbackFuture<MASResponse<JSONObject>> callback = new MASCallbackFuture<>(); MAS.invoke(request, callback); assertNotNull(callback.get()); assertEquals(HttpURLConnection.HTTP_OK, callback.get().getResponseCode()); // Repeat to trigger renew endpoint MASRequest request2 = new MASRequest.MASRequestBuilder(new URI(GatewayDefaultDispatcher.PROTECTED_RESOURCE_PRODUCTS)).build(); MASCallbackFuture<MASResponse<JSONObject>> callback2 = new MASCallbackFuture<>(); MAS.invoke(request2, callback2); assertNotNull(callback2.get()); assertEquals(HttpURLConnection.HTTP_OK, callback2.get().getResponseCode()); //Make sure it has invoke renew endpoint assertNotNull(getRecordRequest(GatewayDefaultDispatcher.CONNECT_DEVICE_RENEW)); } @Test public void testDeregisterDeviceSuccess() throws URISyntaxException, InterruptedException, IOException, ExecutionException { MASRequest request = new MASRequest.MASRequestBuilder(new URI(GatewayDefaultDispatcher.PROTECTED_RESOURCE_PRODUCTS)).build(); MASCallbackFuture<MASResponse<JSONObject>> callback = new MASCallbackFuture<>(); MAS.invoke(request, callback); assertNotNull(callback.get()); assertEquals(HttpURLConnection.HTTP_OK, callback.get().getResponseCode()); setDispatcher(new GatewayDefaultDispatcher() { @Override protected MockResponse deRegister() { return new MockResponse().setResponseCode(200); } }); MASCallbackFuture<Void> callback2 = new MASCallbackFuture<>(); MASDevice.getCurrentDevice().deregister(callback2); try { callback2.get(); } catch (Exception e) { assertNotNull(e); Throwable cause = e.getCause().getCause().getCause(); if (cause instanceof RegistrationServerException) { RegistrationServerException re = (RegistrationServerException) cause; assertEquals(re.getStatus(), 404); // Can't test the IOException portion, but we can verify the other failure case assertTrue(cause instanceof RegistrationServerException); } } // Verify the local credentials are cleared after a successful deregistration. StorageProvider sp = StorageProvider.getInstance(); ClientCredentialContainer ccc = sp.getClientCredentialContainer(); assertNotNull(ccc); assertNull(ccc.getMasterClientId()); assertNull(ccc.getClientId()); assertNull(ccc.getClientSecret()); assertTrue(ccc.getClientExpiration() == -1); OAuthTokenContainer otc = sp.getOAuthTokenContainer(); assertNotNull(otc); assertNull(otc.getAccessToken()); assertNull(otc.getRefreshToken()); assertTrue(otc.getExpiry() == 0); assertNull(otc.getGrantedScope()); TokenManager tm = sp.getTokenManager(); assertNotNull(tm); assertTrue(tm.getIdToken() == null && tm.getSecureIdToken() == null); assertNull(tm.getUserProfile()); assertNull(tm.getClientPublicKey()); assertNull(tm.getClientPrivateKey()); assertNull(tm.getClientCertificateChain()); assertNull(tm.getMagIdentifier()); } @Test public void testDeregisterDeviceWithExceptionResponse() throws URISyntaxException, InterruptedException, IOException, ExecutionException { MASRequest request = new MASRequest.MASRequestBuilder(new URI(GatewayDefaultDispatcher.PROTECTED_RESOURCE_PRODUCTS)).build(); MASCallbackFuture<MASResponse<JSONObject>> callback = new MASCallbackFuture<>(); MAS.invoke(request, callback); assertNotNull(callback.get()); assertEquals(HttpURLConnection.HTTP_OK, callback.get().getResponseCode()); setDispatcher(new GatewayDefaultDispatcher() { @Override protected MockResponse deRegister() { return new MockResponse() .setResponseCode(404); } }); MASCallbackFuture<Void> callback2 = new MASCallbackFuture<>(); MASDevice.getCurrentDevice().deregister(callback2); try { callback2.get(); } catch (Exception e) { assertNotNull(e); Throwable cause = e.getCause().getCause().getCause(); if (cause instanceof RegistrationServerException) { RegistrationServerException re = (RegistrationServerException) cause; assertEquals(re.getStatus(), 404); // Can't test the IOException portion, but we can verify the other failure case assertTrue(cause instanceof RegistrationServerException); } } // Verify the local credentials are still retained after a failed deregistration. StorageProvider sp = StorageProvider.getInstance(); ClientCredentialContainer ccc = sp.getClientCredentialContainer(); assertNotNull(ccc); assertFalse(ccc.getMasterClientId().isEmpty()); assertFalse(ccc.getClientId().isEmpty()); assertFalse(ccc.getClientSecret().isEmpty()); assertFalse(ccc.getClientExpiration() == -1); OAuthTokenContainer otc = sp.getOAuthTokenContainer(); assertNotNull(otc); assertFalse(otc.getAccessToken().isEmpty()); assertFalse(otc.getRefreshToken().isEmpty()); assertFalse(otc.getExpiry() == 0); assertFalse(otc.getGrantedScope().isEmpty()); TokenManager tm = sp.getTokenManager(); assertNotNull(tm); assertTrue(tm.getIdToken() != null || tm.getSecureIdToken() != null); assertNotNull(tm.getUserProfile()); assertNotNull(tm.getClientPublicKey()); assertNotNull(tm.getClientPrivateKey()); assertNotNull(tm.getClientCertificateChain()); assertNotNull(tm.getMagIdentifier()); } @Ignore(value = "Due to DE363094") public void testInvalidMAGIdentifierDuringRegistration() throws InterruptedException, ExecutionException { final boolean[] override = {true}; final int expectedErrorCode = 1000107; final String expectedErrorMessage = "{ \"error\":\"invalid_request\", \"error_description\":\"The given mag-identifier is either invalid or it points to an unknown device\" }"; final String CONTENT_TYPE = "Content-Type"; final String CONTENT_TYPE_VALUE = "application/json"; setDispatcher(new GatewayDefaultDispatcher() { @Override protected MockResponse registerDeviceResponse(RecordedRequest request) { if (override[0]) { override[0] = false; //for retry return new MockResponse().setResponseCode(HttpURLConnection.HTTP_BAD_REQUEST) .setHeader("x-ca-err", expectedErrorCode) .setHeader(CONTENT_TYPE, CONTENT_TYPE_VALUE).setBody(expectedErrorMessage); } else { return super.registerDeviceResponse(request); } } }); MASCallbackFuture<MASUser> callback = new MASCallbackFuture<>(); MASUser.login("test", "test".toCharArray(), callback); Assert.assertNotNull(callback.get()); } @Test public void testInvalidClientCredentialDuringRegistration() throws InterruptedException, ExecutionException { final boolean[] override = {true}; final int expectedErrorCode = 1000201; final String expectedErrorMessage = "{ \"error\":\"invalid_request\", \"error_description\":\"The given client credentials were not valid\" }"; final String CONTENT_TYPE = "Content-Type"; final String CONTENT_TYPE_VALUE = "application/json"; setDispatcher(new GatewayDefaultDispatcher() { @Override protected MockResponse registerDeviceResponse(RecordedRequest request) { if (override[0]) { override[0] = false; //for retry return new MockResponse().setResponseCode(HttpURLConnection.HTTP_UNAUTHORIZED) .setHeader("x-ca-err", expectedErrorCode) .setHeader(CONTENT_TYPE, CONTENT_TYPE_VALUE).setBody(expectedErrorMessage); } else { return super.registerDeviceResponse(request); } } }); MASCallbackFuture<MASUser> callback = new MASCallbackFuture<>(); MASUser.login("test", "test".toCharArray(), callback); Assert.assertNotNull(callback.get()); } @Test public void testInvalidClientCertificateDuringRegistration() throws InterruptedException, ExecutionException { final boolean[] override = {true}; final int expectedErrorCode = 1000206; final String expectedErrorMessage = "{ \"error\":\"invalid_request\", \"error_description\":\"The given client certificate has expired\" }"; final String CONTENT_TYPE = "Content-Type"; final String CONTENT_TYPE_VALUE = "application/json"; setDispatcher(new GatewayDefaultDispatcher() { @Override protected MockResponse registerDeviceResponse(RecordedRequest request) { if (override[0]) { override[0] = false; //for retry return new MockResponse().setResponseCode(HttpURLConnection.HTTP_UNAUTHORIZED) .setHeader("x-ca-err", expectedErrorCode) .setHeader(CONTENT_TYPE, CONTENT_TYPE_VALUE).setBody(expectedErrorMessage); } else { return super.registerDeviceResponse(request); } } }); MASCallbackFuture<MASUser> callback = new MASCallbackFuture<>(); MASUser.login("test", "test".toCharArray(), callback); Assert.assertNotNull(callback.get()); //Make sure it has invoke renew endpoint assertNotNull(getRecordRequest(GatewayDefaultDispatcher.CONNECT_DEVICE_RENEW)); } @Test public void testWithSpecialCharacterUserName() throws ExecutionException, InterruptedException { MASCallbackFuture<MASUser> callback = new MASCallbackFuture<>(); MASUser.login("admin!#$%&'*+-/=?^_`{|}~@ca.com\"", "test".toCharArray(), callback); assertNotNull(callback.get()); } }
3e151b8a5da88ed64c98ca3c8bbcd841e952063b
1,187
java
Java
src/main/java/edu/harvard/iq/dataverse/authorization/providers/AuthenticationProviderFactory.java
vishalbelsare/dataverse
823d0f95e9bdc2951816bfc31b7234accb66aa01
[ "Apache-2.0" ]
681
2015-01-07T14:18:29.000Z
2022-03-28T12:26:27.000Z
src/main/java/edu/harvard/iq/dataverse/authorization/providers/AuthenticationProviderFactory.java
vishalbelsare/dataverse
823d0f95e9bdc2951816bfc31b7234accb66aa01
[ "Apache-2.0" ]
7,286
2015-01-04T06:45:45.000Z
2022-03-31T22:57:24.000Z
src/main/java/edu/harvard/iq/dataverse/authorization/providers/AuthenticationProviderFactory.java
vishalbelsare/dataverse
823d0f95e9bdc2951816bfc31b7234accb66aa01
[ "Apache-2.0" ]
433
2015-01-14T10:21:20.000Z
2022-03-31T12:43:08.000Z
34.911765
110
0.725358
8,962
package edu.harvard.iq.dataverse.authorization.providers; import edu.harvard.iq.dataverse.authorization.AuthenticationProvider; import edu.harvard.iq.dataverse.authorization.exceptions.AuthorizationSetupException; /** * This factory creates {@link AuthenticationProvider}s from {@link AuthenticationProviderRow}s. * Each factory has an alias. The alias also appears in the rows, and is used * to hand a row to a factory object that can understand it. * * @author michael */ public interface AuthenticationProviderFactory { /** * The alias of a factory. Has to be unique in the system. * @return The alias of the factory. */ String getAlias(); /** * @return A human readable display string describing this factory. */ String getInfo(); /** * Instantiates an {@link AuthenticationProvider} based on the row passed. * @param aRow The row on which the created provider is based. * @return The provider * @throws AuthorizationSetupException If {@code aRow} contains malformed data. */ AuthenticationProvider buildProvider( AuthenticationProviderRow aRow ) throws AuthorizationSetupException; }
3e151c8b68dcb77c32cf2757a0b398009e4a500b
46,519
java
Java
hazelcast-client/src/main/java/com/hazelcast/client/proxy/ClientMapProxy.java
MachineShop-IOT/hazelcast
61ba52f2c6d5035d7588bef5eb046974585ece4a
[ "Apache-2.0" ]
1
2020-02-28T02:54:12.000Z
2020-02-28T02:54:12.000Z
hazelcast-client/src/main/java/com/hazelcast/client/proxy/ClientMapProxy.java
MachineShop-IOT/hazelcast
61ba52f2c6d5035d7588bef5eb046974585ece4a
[ "Apache-2.0" ]
null
null
null
hazelcast-client/src/main/java/com/hazelcast/client/proxy/ClientMapProxy.java
MachineShop-IOT/hazelcast
61ba52f2c6d5035d7588bef5eb046974585ece4a
[ "Apache-2.0" ]
null
null
null
39.25654
129
0.643243
8,963
/* * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.client.proxy; import com.hazelcast.client.impl.client.BaseClientRemoveListenerRequest; import com.hazelcast.client.impl.client.ClientRequest; import com.hazelcast.client.nearcache.ClientHeapNearCache; import com.hazelcast.client.nearcache.ClientNearCache; import com.hazelcast.client.spi.ClientProxy; import com.hazelcast.client.spi.EventHandler; import com.hazelcast.client.spi.impl.ClientCallFuture; import com.hazelcast.config.NearCacheConfig; import com.hazelcast.core.EntryEvent; import com.hazelcast.core.EntryListener; import com.hazelcast.core.EntryView; import com.hazelcast.core.ExecutionCallback; import com.hazelcast.core.HazelcastException; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.ICompletableFuture; import com.hazelcast.core.IMap; import com.hazelcast.core.MapEvent; import com.hazelcast.core.Member; import com.hazelcast.logging.Logger; import com.hazelcast.map.EntryProcessor; import com.hazelcast.map.MapInterceptor; import com.hazelcast.map.impl.MapEntrySet; import com.hazelcast.map.impl.MapKeySet; import com.hazelcast.map.impl.MapValueCollection; import com.hazelcast.map.impl.SimpleEntryView; import com.hazelcast.map.impl.client.MapAddEntryListenerRequest; import com.hazelcast.map.impl.client.MapAddIndexRequest; import com.hazelcast.map.impl.client.MapAddInterceptorRequest; import com.hazelcast.map.impl.client.MapClearRequest; import com.hazelcast.map.impl.client.MapContainsKeyRequest; import com.hazelcast.map.impl.client.MapContainsValueRequest; import com.hazelcast.map.impl.client.MapDeleteRequest; import com.hazelcast.map.impl.client.MapEntrySetRequest; import com.hazelcast.map.impl.client.MapEvictAllRequest; import com.hazelcast.map.impl.client.MapEvictRequest; import com.hazelcast.map.impl.client.MapExecuteOnAllKeysRequest; import com.hazelcast.map.impl.client.MapExecuteOnKeyRequest; import com.hazelcast.map.impl.client.MapExecuteOnKeysRequest; import com.hazelcast.map.impl.client.MapExecuteWithPredicateRequest; import com.hazelcast.map.impl.client.MapFlushRequest; import com.hazelcast.map.impl.client.MapGetAllRequest; import com.hazelcast.map.impl.client.MapGetEntryViewRequest; import com.hazelcast.map.impl.client.MapGetRequest; import com.hazelcast.map.impl.client.MapIsEmptyRequest; import com.hazelcast.map.impl.client.MapIsLockedRequest; import com.hazelcast.map.impl.client.MapKeySetRequest; import com.hazelcast.map.impl.client.MapLoadAllKeysRequest; import com.hazelcast.map.impl.client.MapLoadGivenKeysRequest; import com.hazelcast.map.impl.client.MapLockRequest; import com.hazelcast.map.impl.client.MapAddNearCacheEntryListenerRequest; import com.hazelcast.map.impl.client.MapPutAllRequest; import com.hazelcast.map.impl.client.MapPutIfAbsentRequest; import com.hazelcast.map.impl.client.MapPutRequest; import com.hazelcast.map.impl.client.MapPutTransientRequest; import com.hazelcast.map.impl.client.MapQueryRequest; import com.hazelcast.map.impl.client.MapRemoveEntryListenerRequest; import com.hazelcast.map.impl.client.MapRemoveIfSameRequest; import com.hazelcast.map.impl.client.MapRemoveInterceptorRequest; import com.hazelcast.map.impl.client.MapRemoveRequest; import com.hazelcast.map.impl.client.MapReplaceIfSameRequest; import com.hazelcast.map.impl.client.MapReplaceRequest; import com.hazelcast.map.impl.client.MapSetRequest; import com.hazelcast.map.impl.client.MapSizeRequest; import com.hazelcast.map.impl.client.MapTryPutRequest; import com.hazelcast.map.impl.client.MapTryRemoveRequest; import com.hazelcast.map.impl.client.MapUnlockRequest; import com.hazelcast.map.impl.client.MapValuesRequest; import com.hazelcast.mapreduce.Collator; import com.hazelcast.mapreduce.CombinerFactory; import com.hazelcast.mapreduce.Job; import com.hazelcast.mapreduce.JobTracker; import com.hazelcast.mapreduce.KeyValueSource; import com.hazelcast.mapreduce.Mapper; import com.hazelcast.mapreduce.MappingJob; import com.hazelcast.mapreduce.ReducerFactory; import com.hazelcast.mapreduce.ReducingSubmittableJob; import com.hazelcast.mapreduce.aggregation.Aggregation; import com.hazelcast.mapreduce.aggregation.Supplier; import com.hazelcast.monitor.LocalMapStats; import com.hazelcast.monitor.impl.LocalMapStatsImpl; import com.hazelcast.nio.serialization.Data; import com.hazelcast.query.PagingPredicate; import com.hazelcast.query.PagingPredicateAccessor; import com.hazelcast.query.Predicate; import com.hazelcast.spi.impl.PortableEntryEvent; import com.hazelcast.util.ExceptionUtil; import com.hazelcast.util.IterationType; import com.hazelcast.util.QueryResultSet; import com.hazelcast.util.SortedQueryResultSet; import com.hazelcast.util.SortingUtil; import com.hazelcast.util.ThreadUtil; import com.hazelcast.util.ValidationUtil; import com.hazelcast.util.executor.CompletedFuture; import com.hazelcast.util.executor.DelegatingFuture; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import static com.hazelcast.util.ValidationUtil.checkNotNull; public final class ClientMapProxy<K, V> extends ClientProxy implements IMap<K, V> { protected static final String NULL_KEY_IS_NOT_ALLOWED = "Null key is not allowed!"; protected static final String NULL_VALUE_IS_NOT_ALLOWED = "Null value is not allowed!"; private final String name; private final AtomicBoolean nearCacheInitialized = new AtomicBoolean(); private volatile ClientHeapNearCache<Data> nearCache; public ClientMapProxy(String serviceName, String name) { super(serviceName, name); this.name = name; } @Override public boolean containsKey(Object key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); initNearCache(); final Data keyData = toData(key); if (nearCache != null) { Object cached = nearCache.get(keyData); if (cached != null) { if (cached.equals(ClientNearCache.NULL_OBJECT)) { return false; } return true; } } MapContainsKeyRequest request = new MapContainsKeyRequest(name, keyData, ThreadUtil.getThreadId()); Boolean result = invoke(request, keyData); return result; } @Override public boolean containsValue(Object value) { checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); Data valueData = toData(value); MapContainsValueRequest request = new MapContainsValueRequest(name, valueData); Boolean result = invoke(request); return result; } @Override public V get(Object key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); initNearCache(); final Data keyData = toData(key); if (nearCache != null) { Object cached = nearCache.get(keyData); if (cached != null) { if (cached.equals(ClientHeapNearCache.NULL_OBJECT)) { return null; } return (V) cached; } } MapGetRequest request = new MapGetRequest(name, keyData, ThreadUtil.getThreadId()); final V result = invoke(request, keyData); if (nearCache != null) { nearCache.put(keyData, result); } return result; } @Override public V put(K key, V value) { return put(key, value, -1, TimeUnit.MILLISECONDS); } @Override public V remove(Object key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); final Data keyData = toData(key); invalidateNearCache(keyData); MapRemoveRequest request = new MapRemoveRequest(name, keyData, ThreadUtil.getThreadId()); return invoke(request, keyData); } @Override public boolean remove(Object key, Object value) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); // I do not why but findbugs does not like this null check: // value must be nonnull but is marked as nullable ["com.hazelcast.client.proxy.ClientMapProxy"] // At ClientMapProxy.java:[lines 131-1253] // checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); final Data keyData = toData(key); final Data valueData = toData(value); invalidateNearCache(keyData); MapRemoveIfSameRequest request = new MapRemoveIfSameRequest(name, keyData, valueData, ThreadUtil.getThreadId()); Boolean result = invoke(request, keyData); return result; } @Override public void delete(Object key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); final Data keyData = toData(key); invalidateNearCache(keyData); MapDeleteRequest request = new MapDeleteRequest(name, keyData, ThreadUtil.getThreadId()); invoke(request, keyData); } @Override public void flush() { MapFlushRequest request = new MapFlushRequest(name); invoke(request); } @Override public Future<V> getAsync(final K key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); initNearCache(); final Data keyData = toData(key); if (nearCache != null) { Object cached = nearCache.get(keyData); if (cached != null && !ClientNearCache.NULL_OBJECT.equals(cached)) { return new CompletedFuture(getContext().getSerializationService(), cached, getContext().getExecutionService().getAsyncExecutor()); } } final MapGetRequest request = new MapGetRequest(name, keyData, ThreadUtil.getThreadId()); request.setAsAsync(); try { final ICompletableFuture future = getContext().getInvocationService().invokeOnKeyOwner(request, keyData); final DelegatingFuture<V> delegatingFuture = new DelegatingFuture<V>(future, getContext().getSerializationService()); delegatingFuture.andThen(new ExecutionCallback<V>() { @Override public void onResponse(V response) { if (nearCache != null) { nearCache.put(keyData, response); } } @Override public void onFailure(Throwable t) { } }); return delegatingFuture; } catch (Exception e) { throw ExceptionUtil.rethrow(e); } } @Override public Future<V> putAsync(final K key, final V value) { return putAsync(key, value, -1, TimeUnit.MILLISECONDS); } @Override public Future<V> putAsync(final K key, final V value, final long ttl, final TimeUnit timeunit) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); final Data keyData = toData(key); final Data valueData = toData(value); invalidateNearCache(keyData); MapPutRequest request = new MapPutRequest(name, keyData, valueData, ThreadUtil.getThreadId(), getTimeInMillis(ttl, timeunit)); request.setAsAsync(); try { final ICompletableFuture future = getContext().getInvocationService().invokeOnKeyOwner(request, keyData); return new DelegatingFuture<V>(future, getContext().getSerializationService()); } catch (Exception e) { throw ExceptionUtil.rethrow(e); } } @Override public Future<V> removeAsync(final K key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); final Data keyData = toData(key); invalidateNearCache(keyData); MapRemoveRequest request = new MapRemoveRequest(name, keyData, ThreadUtil.getThreadId()); request.setAsAsync(); try { final ICompletableFuture future = getContext().getInvocationService().invokeOnKeyOwner(request, keyData); return new DelegatingFuture<V>(future, getContext().getSerializationService()); } catch (Exception e) { throw ExceptionUtil.rethrow(e); } } @Override public boolean tryRemove(K key, long timeout, TimeUnit timeunit) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); final Data keyData = toData(key); invalidateNearCache(keyData); MapTryRemoveRequest request = new MapTryRemoveRequest(name, keyData, ThreadUtil.getThreadId(), timeunit.toMillis(timeout)); Boolean result = invoke(request, keyData); return result; } @Override public boolean tryPut(K key, V value, long timeout, TimeUnit timeunit) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); final Data keyData = toData(key); final Data valueData = toData(value); invalidateNearCache(keyData); MapTryPutRequest request = new MapTryPutRequest(name, keyData, valueData, ThreadUtil.getThreadId(), timeunit.toMillis(timeout)); Boolean result = invoke(request, keyData); return result; } @Override public V put(K key, V value, long ttl, TimeUnit timeunit) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); final Data keyData = toData(key); final Data valueData = toData(value); invalidateNearCache(keyData); MapPutRequest request = new MapPutRequest(name, keyData, valueData, ThreadUtil.getThreadId(), getTimeInMillis(ttl, timeunit)); return invoke(request, keyData); } @Override public void putTransient(K key, V value, long ttl, TimeUnit timeunit) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); final Data keyData = toData(key); final Data valueData = toData(value); invalidateNearCache(keyData); MapPutTransientRequest request = new MapPutTransientRequest(name, keyData, valueData, ThreadUtil.getThreadId(), getTimeInMillis(ttl, timeunit)); invoke(request); } @Override public V putIfAbsent(K key, V value) { return putIfAbsent(key, value, -1, TimeUnit.MILLISECONDS); } @Override public V putIfAbsent(K key, V value, long ttl, TimeUnit timeunit) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); final Data keyData = toData(key); final Data valueData = toData(value); invalidateNearCache(keyData); MapPutIfAbsentRequest request = new MapPutIfAbsentRequest(name, keyData, valueData, ThreadUtil.getThreadId(), getTimeInMillis(ttl, timeunit)); return invoke(request, keyData); } @Override public boolean replace(K key, V oldValue, V newValue) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(oldValue, NULL_VALUE_IS_NOT_ALLOWED); checkNotNull(newValue, NULL_VALUE_IS_NOT_ALLOWED); final Data keyData = toData(key); final Data oldValueData = toData(oldValue); final Data newValueData = toData(newValue); invalidateNearCache(keyData); MapReplaceIfSameRequest request = new MapReplaceIfSameRequest(name, keyData, oldValueData, newValueData, ThreadUtil.getThreadId()); Boolean result = invoke(request, keyData); return result; } @Override public V replace(K key, V value) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); final Data keyData = toData(key); final Data valueData = toData(value); invalidateNearCache(keyData); MapReplaceRequest request = new MapReplaceRequest(name, keyData, valueData, ThreadUtil.getThreadId()); return invoke(request, keyData); } @Override public void set(K key, V value, long ttl, TimeUnit timeunit) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); final Data keyData = toData(key); final Data valueData = toData(value); invalidateNearCache(keyData); MapSetRequest request = new MapSetRequest(name, keyData, valueData, ThreadUtil.getThreadId(), getTimeInMillis(ttl, timeunit)); invoke(request, keyData); } @Override public void lock(K key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); final Data keyData = toData(key); MapLockRequest request = new MapLockRequest(name, keyData, ThreadUtil.getThreadId()); invoke(request, keyData); } @Override public void lock(K key, long leaseTime, TimeUnit timeUnit) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); final Data keyData = toData(key); MapLockRequest request = new MapLockRequest(name, keyData, ThreadUtil.getThreadId(), getTimeInMillis(leaseTime, timeUnit), -1); invoke(request, keyData); } @Override public boolean isLocked(K key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); final Data keyData = toData(key); MapIsLockedRequest request = new MapIsLockedRequest(name, keyData); Boolean result = invoke(request, keyData); return result; } @Override public boolean tryLock(K key) { try { return tryLock(key, 0, null); } catch (InterruptedException e) { return false; } } @Override public boolean tryLock(K key, long time, TimeUnit timeunit) throws InterruptedException { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); final Data keyData = toData(key); MapLockRequest request = new MapLockRequest(name, keyData, ThreadUtil.getThreadId(), Long.MAX_VALUE, getTimeInMillis(time, timeunit)); Boolean result = invoke(request, keyData); return result; } @Override public void unlock(K key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); final Data keyData = toData(key); MapUnlockRequest request = new MapUnlockRequest(name, keyData, ThreadUtil.getThreadId(), false); invoke(request, keyData); } @Override public void forceUnlock(K key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); final Data keyData = toData(key); MapUnlockRequest request = new MapUnlockRequest(name, keyData, ThreadUtil.getThreadId(), true); invoke(request, keyData); } @Override public String addLocalEntryListener(EntryListener<K, V> listener) { throw new UnsupportedOperationException("Locality is ambiguous for client!!!"); } @Override public String addLocalEntryListener(EntryListener<K, V> listener, Predicate<K, V> predicate, boolean includeValue) { throw new UnsupportedOperationException("Locality is ambiguous for client!!!"); } @Override public String addLocalEntryListener(EntryListener<K, V> listener, Predicate<K, V> predicate, K key, boolean includeValue) { throw new UnsupportedOperationException("Locality is ambiguous for client!!!"); } public String addInterceptor(MapInterceptor interceptor) { MapAddInterceptorRequest request = new MapAddInterceptorRequest(name, interceptor); return invoke(request); } @Override public void removeInterceptor(String id) { MapRemoveInterceptorRequest request = new MapRemoveInterceptorRequest(name, id); invoke(request); } @Override public String addEntryListener(EntryListener<K, V> listener, boolean includeValue) { MapAddEntryListenerRequest request = new MapAddEntryListenerRequest(name, includeValue); EventHandler<PortableEntryEvent> handler = createHandler(listener, includeValue); return listen(request, handler); } @Override public boolean removeEntryListener(String id) { final MapRemoveEntryListenerRequest request = new MapRemoveEntryListenerRequest(name, id); return stopListening(request, id); } @Override public String addEntryListener(EntryListener<K, V> listener, K key, boolean includeValue) { final Data keyData = toData(key); MapAddEntryListenerRequest request = new MapAddEntryListenerRequest(name, keyData, includeValue); EventHandler<PortableEntryEvent> handler = createHandler(listener, includeValue); return listen(request, keyData, handler); } @Override public String addEntryListener(EntryListener<K, V> listener, Predicate<K, V> predicate, K key, boolean includeValue) { final Data keyData = toData(key); MapAddEntryListenerRequest request = new MapAddEntryListenerRequest(name, keyData, includeValue, predicate); EventHandler<PortableEntryEvent> handler = createHandler(listener, includeValue); return listen(request, keyData, handler); } @Override public String addEntryListener(EntryListener<K, V> listener, Predicate<K, V> predicate, boolean includeValue) { MapAddEntryListenerRequest request = new MapAddEntryListenerRequest(name, null, includeValue, predicate); EventHandler<PortableEntryEvent> handler = createHandler(listener, includeValue); return listen(request, null, handler); } @Override public EntryView<K, V> getEntryView(K key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); final Data keyData = toData(key); MapGetEntryViewRequest request = new MapGetEntryViewRequest(name, keyData, ThreadUtil.getThreadId()); SimpleEntryView entryView = invoke(request, keyData); if (entryView == null) { return null; } final Data value = (Data) entryView.getValue(); entryView.setKey(key); entryView.setValue(toObject(value)); //TODO putCache return entryView; } @Override public boolean evict(K key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); final Data keyData = toData(key); MapEvictRequest request = new MapEvictRequest(name, keyData, ThreadUtil.getThreadId()); Boolean result = invoke(request); return result; } @Override public void evictAll() { clearNearCache(); MapEvictAllRequest request = new MapEvictAllRequest(name); invoke(request); } @Override public void loadAll(boolean replaceExistingValues) { if (replaceExistingValues) { clearNearCache(); } final MapLoadAllKeysRequest request = new MapLoadAllKeysRequest(name, replaceExistingValues); invoke(request); } @Override public void loadAll(Set<K> keys, boolean replaceExistingValues) { checkNotNull(keys, "Parameter keys should not be null."); if (keys.isEmpty()) { return; } final List<Data> dataKeys = convertKeysToData(keys); if (replaceExistingValues) { invalidateNearCache(dataKeys); } final MapLoadGivenKeysRequest request = new MapLoadGivenKeysRequest(name, dataKeys, replaceExistingValues); invoke(request); } // todo duplicate code. private <K> List<Data> convertKeysToData(Set<K> keys) { if (keys == null || keys.isEmpty()) { return Collections.emptyList(); } final List<Data> dataKeys = new ArrayList<Data>(keys.size()); for (K key : keys) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); final Data dataKey = toData(key); dataKeys.add(dataKey); } return dataKeys; } @Override public Set<K> keySet() { MapKeySetRequest request = new MapKeySetRequest(name); MapKeySet mapKeySet = invoke(request); Set<Data> keySetData = mapKeySet.getKeySet(); Set<K> keySet = new HashSet<K>(keySetData.size()); for (Data data : keySetData) { final K key = toObject(data); keySet.add(key); } return keySet; } @Override public Map<K, V> getAll(Set<K> keys) { initNearCache(); Set<Data> keySet = new HashSet(keys.size()); Map<K, V> result = new HashMap<K, V>(); for (Object key : keys) { keySet.add(toData(key)); } if (nearCache != null) { final Iterator<Data> iterator = keySet.iterator(); while (iterator.hasNext()) { Data key = iterator.next(); Object cached = nearCache.get(key); if (cached != null && !ClientHeapNearCache.NULL_OBJECT.equals(cached)) { result.put((K) toObject(key), (V) cached); iterator.remove(); } } } if (keySet.isEmpty()) { return result; } MapGetAllRequest request = new MapGetAllRequest(name, keySet); MapEntrySet mapEntrySet = invoke(request); Set<Entry<Data, Data>> entrySet = mapEntrySet.getEntrySet(); for (Entry<Data, Data> dataEntry : entrySet) { final V value = toObject(dataEntry.getValue()); final K key = toObject(dataEntry.getKey()); result.put(key, value); if (nearCache != null) { nearCache.put(dataEntry.getKey(), value); } } return result; } @Override public Collection<V> values() { MapValuesRequest request = new MapValuesRequest(name); MapValueCollection mapValueCollection = invoke(request); Collection<Data> collectionData = mapValueCollection.getValues(); Collection<V> collection = new ArrayList<V>(collectionData.size()); for (Data data : collectionData) { final V value = toObject(data); collection.add(value); } return collection; } @Override public Set<Entry<K, V>> entrySet() { MapEntrySetRequest request = new MapEntrySetRequest(name); MapEntrySet result = invoke(request); Set<Entry<K, V>> entrySet = new HashSet<Entry<K, V>>(); Set<Entry<Data, Data>> entries = result.getEntrySet(); for (Entry<Data, Data> dataEntry : entries) { Data keyData = dataEntry.getKey(); Data valueData = dataEntry.getValue(); K key = toObject(keyData); V value = toObject(valueData); entrySet.add(new AbstractMap.SimpleEntry<K, V>(key, value)); } return entrySet; } @Override public Set<K> keySet(Predicate predicate) { PagingPredicate pagingPredicate = null; if (predicate instanceof PagingPredicate) { pagingPredicate = (PagingPredicate) predicate; pagingPredicate.setIterationType(IterationType.KEY); if (pagingPredicate.getPage() > 0 && pagingPredicate.getAnchor() == null) { pagingPredicate.previousPage(); keySet(pagingPredicate); pagingPredicate.nextPage(); } } MapQueryRequest request = new MapQueryRequest(name, predicate, IterationType.KEY); QueryResultSet result = invoke(request); if (pagingPredicate == null) { final HashSet<K> keySet = new HashSet<K>(); for (Object o : result) { final K key = toObject(o); keySet.add(key); } return keySet; } final Comparator<Entry> comparator = SortingUtil.newComparator(pagingPredicate.getComparator(), IterationType.KEY); final SortedQueryResultSet sortedResult = new SortedQueryResultSet(comparator, IterationType.KEY, pagingPredicate.getPageSize()); final Iterator<Entry> iterator = result.rawIterator(); while (iterator.hasNext()) { final Entry entry = iterator.next(); final K key = toObject(entry.getKey()); final V value = toObject(entry.getValue()); sortedResult.add(new AbstractMap.SimpleImmutableEntry<K, V>(key, value)); } PagingPredicateAccessor.setPagingPredicateAnchor(pagingPredicate, sortedResult.last()); return (Set<K>) sortedResult; } @Override public Set<Entry<K, V>> entrySet(Predicate predicate) { PagingPredicate pagingPredicate = null; if (predicate instanceof PagingPredicate) { pagingPredicate = (PagingPredicate) predicate; pagingPredicate.setIterationType(IterationType.ENTRY); if (pagingPredicate.getPage() > 0 && pagingPredicate.getAnchor() == null) { pagingPredicate.previousPage(); entrySet(pagingPredicate); pagingPredicate.nextPage(); } } MapQueryRequest request = new MapQueryRequest(name, predicate, IterationType.ENTRY); QueryResultSet result = invoke(request); Set entrySet; if (pagingPredicate == null) { entrySet = new HashSet<Entry<K, V>>(result.size()); } else { entrySet = new SortedQueryResultSet(pagingPredicate.getComparator(), IterationType.ENTRY, pagingPredicate.getPageSize()); } for (Object data : result) { AbstractMap.SimpleImmutableEntry<Data, Data> dataEntry = (AbstractMap.SimpleImmutableEntry<Data, Data>) data; K key = toObject(dataEntry.getKey()); V value = toObject(dataEntry.getValue()); entrySet.add(new AbstractMap.SimpleEntry<K, V>(key, value)); } if (pagingPredicate != null) { PagingPredicateAccessor.setPagingPredicateAnchor(pagingPredicate, ((SortedQueryResultSet) entrySet).last()); } return entrySet; } @Override public Collection<V> values(Predicate predicate) { PagingPredicate pagingPredicate = null; if (predicate instanceof PagingPredicate) { pagingPredicate = (PagingPredicate) predicate; pagingPredicate.setIterationType(IterationType.VALUE); if (pagingPredicate.getPage() > 0 && pagingPredicate.getAnchor() == null) { pagingPredicate.previousPage(); values(pagingPredicate); pagingPredicate.nextPage(); } } MapQueryRequest request = new MapQueryRequest(name, predicate, IterationType.VALUE); QueryResultSet result = invoke(request); if (pagingPredicate == null) { final ArrayList<V> values = new ArrayList<V>(result.size()); for (Object data : result) { V value = toObject(data); values.add(value); } return values; } List<Entry<Object, V>> valueEntryList = new ArrayList<Entry<Object, V>>(result.size()); final Iterator<Entry> iterator = result.rawIterator(); while (iterator.hasNext()) { final Entry entry = iterator.next(); K key = toObject(entry.getKey()); V value = toObject(entry.getValue()); valueEntryList.add(new AbstractMap.SimpleImmutableEntry<Object, V>(key, value)); } Collections.sort(valueEntryList, SortingUtil.newComparator(pagingPredicate.getComparator(), IterationType.VALUE)); if (valueEntryList.size() > pagingPredicate.getPageSize()) { valueEntryList = valueEntryList.subList(0, pagingPredicate.getPageSize()); } Entry anchor = null; if (valueEntryList.size() != 0) { anchor = valueEntryList.get(valueEntryList.size() - 1); } PagingPredicateAccessor.setPagingPredicateAnchor(pagingPredicate, anchor); final ArrayList<V> values = new ArrayList<V>(valueEntryList.size()); for (Entry<Object, V> objectVEntry : valueEntryList) { values.add(objectVEntry.getValue()); } return values; } @Override public Set<K> localKeySet() { throw new UnsupportedOperationException("Locality is ambiguous for client!!!"); } @Override public Set<K> localKeySet(Predicate predicate) { throw new UnsupportedOperationException("Locality is ambiguous for client!!!"); } @Override public void addIndex(String attribute, boolean ordered) { MapAddIndexRequest request = new MapAddIndexRequest(name, attribute, ordered); invoke(request); } @Override public LocalMapStats getLocalMapStats() { initNearCache(); LocalMapStatsImpl localMapStats = new LocalMapStatsImpl(); if (nearCache != null) { localMapStats.setNearCacheStats(nearCache.getNearCacheStats()); } return localMapStats; } @Override public Object executeOnKey(K key, EntryProcessor entryProcessor) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); final Data keyData = toData(key); MapExecuteOnKeyRequest request = new MapExecuteOnKeyRequest(name, entryProcessor, keyData); return invoke(request, keyData); } public void submitToKey(K key, EntryProcessor entryProcessor, final ExecutionCallback callback) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); final Data keyData = toData(key); final MapExecuteOnKeyRequest request = new MapExecuteOnKeyRequest(name, entryProcessor, keyData); request.setAsSubmitToKey(); try { final ClientCallFuture future = (ClientCallFuture) getContext().getInvocationService(). invokeOnKeyOwner(request, keyData); future.andThen(callback); } catch (Exception e) { throw ExceptionUtil.rethrow(e); } } public Future submitToKey(K key, EntryProcessor entryProcessor) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); final Data keyData = toData(key); final MapExecuteOnKeyRequest request = new MapExecuteOnKeyRequest(name, entryProcessor, keyData); request.setAsSubmitToKey(); try { final ICompletableFuture future = getContext().getInvocationService().invokeOnKeyOwner(request, keyData); return new DelegatingFuture(future, getContext().getSerializationService()); } catch (Exception e) { throw ExceptionUtil.rethrow(e); } } @Override public Map<K, Object> executeOnEntries(EntryProcessor entryProcessor) { MapExecuteOnAllKeysRequest request = new MapExecuteOnAllKeysRequest(name, entryProcessor); MapEntrySet entrySet = invoke(request); Map<K, Object> result = new HashMap<K, Object>(); for (Entry<Data, Data> dataEntry : entrySet.getEntrySet()) { final Data keyData = dataEntry.getKey(); final Data valueData = dataEntry.getValue(); K key = toObject(keyData); result.put(key, toObject(valueData)); } return result; } @Override public Map<K, Object> executeOnEntries(EntryProcessor entryProcessor, Predicate predicate) { MapExecuteWithPredicateRequest request = new MapExecuteWithPredicateRequest(name, entryProcessor, predicate); MapEntrySet entrySet = invoke(request); Map<K, Object> result = new HashMap<K, Object>(); for (Entry<Data, Data> dataEntry : entrySet.getEntrySet()) { final Data keyData = dataEntry.getKey(); final Data valueData = dataEntry.getValue(); K key = toObject(keyData); result.put(key, toObject(valueData)); } return result; } @Override public <SuppliedValue, Result> Result aggregate(Supplier<K, V, SuppliedValue> supplier, Aggregation<K, SuppliedValue, Result> aggregation) { HazelcastInstance hazelcastInstance = getContext().getHazelcastInstance(); JobTracker jobTracker = hazelcastInstance.getJobTracker("hz::aggregation-map-" + getName()); return aggregate(supplier, aggregation, jobTracker); } @Override public <SuppliedValue, Result> Result aggregate(Supplier<K, V, SuppliedValue> supplier, Aggregation<K, SuppliedValue, Result> aggregation, JobTracker jobTracker) { try { ValidationUtil.isNotNull(jobTracker, "jobTracker"); KeyValueSource<K, V> keyValueSource = KeyValueSource.fromMap(this); Job<K, V> job = jobTracker.newJob(keyValueSource); Mapper mapper = aggregation.getMapper(supplier); CombinerFactory combinerFactory = aggregation.getCombinerFactory(); ReducerFactory reducerFactory = aggregation.getReducerFactory(); Collator collator = aggregation.getCollator(); MappingJob mappingJob = job.mapper(mapper); ReducingSubmittableJob reducingJob; if (combinerFactory != null) { reducingJob = mappingJob.combiner(combinerFactory).reducer(reducerFactory); } else { reducingJob = mappingJob.reducer(reducerFactory); } ICompletableFuture<Result> future = reducingJob.submit(collator); return future.get(); } catch (Exception e) { throw new HazelcastException(e); } } @Override public Map<K, Object> executeOnKeys(Set<K> keys, EntryProcessor entryProcessor) { Set<Data> dataKeys = new HashSet<Data>(keys.size()); for (K key : keys) { dataKeys.add(toData(key)); } MapExecuteOnKeysRequest request = new MapExecuteOnKeysRequest(name, entryProcessor, dataKeys); MapEntrySet entrySet = invoke(request); Map<K, Object> result = new HashMap<K, Object>(); for (Entry<Data, Data> dataEntry : entrySet.getEntrySet()) { final Data keyData = dataEntry.getKey(); final Data valueData = dataEntry.getValue(); K key = toObject(keyData); result.put(key, toObject(valueData)); } return result; } @Override public void set(K key, V value) { set(key, value, -1, TimeUnit.MILLISECONDS); } @Override public int size() { MapSizeRequest request = new MapSizeRequest(name); Integer result = invoke(request); return result; } @Override public boolean isEmpty() { MapIsEmptyRequest request = new MapIsEmptyRequest(name); Boolean result = invoke(request); return result; } @Override public void putAll(Map<? extends K, ? extends V> m) { MapEntrySet entrySet = new MapEntrySet(); for (Entry<? extends K, ? extends V> entry : m.entrySet()) { final Data keyData = toData(entry.getKey()); invalidateNearCache(keyData); entrySet.add(new AbstractMap.SimpleImmutableEntry<Data, Data>(keyData, toData(entry.getValue()))); } MapPutAllRequest request = new MapPutAllRequest(name, entrySet); invoke(request); } @Override public void clear() { MapClearRequest request = new MapClearRequest(name); invalidateNearCache(); invoke(request); } @Override protected void onDestroy() { destroyNearCache(); } private void destroyNearCache() { if (nearCache != null) { removeNearCacheInvalidationListener(); nearCache.destroy(); } } @Override protected void onShutdown() { destroyNearCache(); } protected long getTimeInMillis(final long time, final TimeUnit timeunit) { return timeunit != null ? timeunit.toMillis(time) : time; } private EventHandler<PortableEntryEvent> createHandler(final EntryListener<K, V> listener, final boolean includeValue) { return new EventHandler<PortableEntryEvent>() { public void handle(PortableEntryEvent event) { Member member = getContext().getClusterService().getMember(event.getUuid()); switch (event.getEventType()) { case ADDED: listener.entryAdded(createEntryEvent(event, member)); break; case REMOVED: listener.entryRemoved(createEntryEvent(event, member)); break; case UPDATED: listener.entryUpdated(createEntryEvent(event, member)); break; case EVICTED: listener.entryEvicted(createEntryEvent(event, member)); break; case EVICT_ALL: listener.mapEvicted(createMapEvent(event, member)); break; case CLEAR_ALL: listener.mapCleared(createMapEvent(event, member)); break; default: throw new IllegalArgumentException("Not a known event type " + event.getEventType()); } } private MapEvent createMapEvent(PortableEntryEvent event, Member member) { return new MapEvent(name, member, event.getEventType().getType(), event.getNumberOfAffectedEntries()); } private EntryEvent<K, V> createEntryEvent(PortableEntryEvent event, Member member) { V value = null; V oldValue = null; if (includeValue) { value = toObject(event.getValue()); oldValue = toObject(event.getOldValue()); } K key = toObject(event.getKey()); return new EntryEvent<K, V>(name, member, event.getEventType().getType(), key, oldValue, value); } @Override public void beforeListenerRegister() { } @Override public void onListenerRegister() { } }; } private void invalidateNearCache(Data key) { if (nearCache != null) { nearCache.invalidate(key); } } private void invalidateNearCache() { if (nearCache != null) { nearCache.clear(); } } private void invalidateNearCache(Collection<Data> keys) { if (nearCache != null) { if (keys == null || keys.isEmpty()) { return; } for (Data key : keys) { nearCache.invalidate(key); } } } private void clearNearCache() { if (nearCache != null) { nearCache.clear(); } } private void initNearCache() { if (nearCacheInitialized.compareAndSet(false, true)) { final NearCacheConfig nearCacheConfig = getContext().getClientConfig().getNearCacheConfig(name); if (nearCacheConfig == null) { return; } nearCache = new ClientHeapNearCache<Data>(name, getContext(), nearCacheConfig); if (nearCache.isInvalidateOnChange()) { addNearCacheInvalidateListener(); } } } private void addNearCacheInvalidateListener() { try { ClientRequest request = new MapAddNearCacheEntryListenerRequest(name, false); EventHandler handler = new EventHandler<PortableEntryEvent>() { @Override public void handle(PortableEntryEvent event) { switch (event.getEventType()) { case ADDED: case REMOVED: case UPDATED: case EVICTED: final Data key = event.getKey(); nearCache.remove(key); break; case CLEAR_ALL: case EVICT_ALL: nearCache.clear(); break; default: throw new IllegalArgumentException("Not a known event type " + event.getEventType()); } } @Override public void beforeListenerRegister() { nearCache.clear(); } @Override public void onListenerRegister() { nearCache.clear(); } }; String registrationId = getContext().getListenerService().listen(request, null, handler); nearCache.setId(registrationId); } catch (Exception e) { Logger.getLogger(ClientHeapNearCache.class).severe( "-----------------\n Near Cache is not initialized!!! \n-----------------", e); } } private void removeNearCacheInvalidationListener() { if (nearCache != null && nearCache.getId() != null) { String registrationId = nearCache.getId(); BaseClientRemoveListenerRequest request = new MapRemoveEntryListenerRequest(name, registrationId); getContext().getListenerService().stopListening(request, registrationId); } } @Override public String toString() { return "IMap{" + "name='" + getName() + '\'' + '}'; } }
3e151c8d2122df9b191e6d848a5d1dc704685ca0
5,081
java
Java
src/main/java/org/rublin/controller/EmailController.java
rublin/SmartSpace
196fce7f3e013cda03f03dcce6f5dcc31ca1c6ab
[ "MIT" ]
2
2016-11-03T11:22:47.000Z
2017-12-21T16:07:28.000Z
src/main/java/org/rublin/controller/EmailController.java
rublin/SmartSpace
196fce7f3e013cda03f03dcce6f5dcc31ca1c6ab
[ "MIT" ]
1
2019-06-16T08:38:18.000Z
2019-06-16T08:38:18.000Z
src/main/java/org/rublin/controller/EmailController.java
rublin/SmartSpace
196fce7f3e013cda03f03dcce6f5dcc31ca1c6ab
[ "MIT" ]
null
null
null
37.360294
105
0.583153
8,964
package org.rublin.controller; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import java.io.File; import java.util.List; import java.util.Properties; /** * Created by Sheremet on 21.08.2016. */ @Slf4j @Controller public class EmailController { @Value("${mail.smtp}") private String smtp; @Value("${mail.port}") private String port; @Value("${mail.login}") private String login; @Value("${mail.password}") private String password; @Value("${mail.from}") private String from; private Properties getMailProperties() { Properties mailProperties = new Properties(); mailProperties.put("mail.smtp.auth", "true"); mailProperties.put("mail.smtp.socketFactory.port", port); mailProperties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); mailProperties.put("mail.smtp.host", smtp); mailProperties.put("mail.smtp.port", port); mailProperties.put("mail.smtp.login", login); mailProperties.put("mail.smtp.password", password); mailProperties.put("mail.smtp.from", from); return mailProperties; } public void sendMailWithAttach(String subject, String text, List<File> photos, List<String> emails) { Session session = Session.getInstance(getMailProperties(), new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(login, password); } }); try{ // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(String.join(", ", emails))); // Set Subject: header field message.setSubject(subject); // This mail has 2 part, the BODY and the embedded image MimeMultipart multipart = new MimeMultipart("related"); // first part (the html) BodyPart messageBodyPart = new MimeBodyPart(); String htmlText = text + "<img src=\"cid:image\">"; messageBodyPart.setContent(htmlText, "text/html"); // add it multipart.addBodyPart(messageBodyPart); // second part (the image) messageBodyPart = new MimeBodyPart(); for (File photo : photos) { String filename = photo.getPath(); DataSource fds = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setHeader("Content-ID", "<image>"); // add image to the multipart multipart.addBodyPart(messageBodyPart); } // Send the complete message parts message.setContent(multipart ); // Send message Transport.send(message); log.info("Mail {} send success", subject); }catch (MessagingException e) { log.error("Mail {} send error. Exception is: {}", subject, e.getMessage()); } } public void sendMail(String subject, String text, List<String> emails) { Session session = Session.getInstance(getMailProperties(), new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(login, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(String.join(", ", emails))); message.setSubject(subject); message.setContent(text, "text/html; charset=UTF-8"); Transport.send(message); log.info("Mail {} to {} send success", subject, message.getAllRecipients()); } catch (MessagingException e) { log.error("Mail {} send error. Exception is: {}", subject, e.getMessage()); throw new RuntimeException(e); } } }
3e151cc46619631abc5a4277879609e1500a6829
931
java
Java
src/main/java/com/gmrodrigues/js/sandbox/util/XmlToJsonConverter.java
gmrodrigues/JsSandbox
01926b5a052638e0f2a354bdce2fe03e00a5167c
[ "MIT" ]
2
2016-03-28T18:39:19.000Z
2019-02-03T19:45:38.000Z
src/main/java/com/gmrodrigues/js/sandbox/util/XmlToJsonConverter.java
gmrodrigues/JsSandbox
01926b5a052638e0f2a354bdce2fe03e00a5167c
[ "MIT" ]
null
null
null
src/main/java/com/gmrodrigues/js/sandbox/util/XmlToJsonConverter.java
gmrodrigues/JsSandbox
01926b5a052638e0f2a354bdce2fe03e00a5167c
[ "MIT" ]
null
null
null
23.871795
75
0.633727
8,965
package com.gmrodrigues.js.sandbox.util; import net.sf.json.JSON; import net.sf.json.JSONArray; import net.sf.json.xml.XMLSerializer; import java.io.File; public class XmlToJsonConverter { private static final XMLSerializer xmlSerializer = new XMLSerializer(); private XmlToJsonConverter(){} public static JSON getJsonFromXmlFile(File fromFile) { JSON json = xmlSerializer.readFromFile(fromFile); return getJSONObject(json); } public static JSON getJsonFromXmlString(String xml) { JSON json = xmlSerializer.read(xml); return getJSONObject(json); } private static JSON getJSONObject(JSON json) { if (json instanceof JSONArray) { JSONArray ja = (JSONArray) json; if (ja.size() == 1) { JSON element = ja.getJSONObject(0); return element; } } return json; } }
3e151e3e902552d27de5bbb218a81315e4305e23
2,538
java
Java
server/src/main/java/edp/davinci/dao/StarMapper.java
freefly310/davinci
2a89c946b656c341230d9f19dbcb29cf1ad00ffd
[ "Apache-2.0" ]
4,442
2017-09-03T17:38:06.000Z
2022-03-29T18:08:05.000Z
server/src/main/java/edp/davinci/dao/StarMapper.java
zhangsean/davinci
21c32b14ee9e6219c17f120d1b1c3142e78cdfc3
[ "Apache-2.0" ]
1,037
2017-10-16T03:16:33.000Z
2022-03-26T10:48:25.000Z
server/src/main/java/edp/davinci/dao/StarMapper.java
zhangsean/davinci
21c32b14ee9e6219c17f120d1b1c3142e78cdfc3
[ "Apache-2.0" ]
1,769
2017-09-05T06:58:11.000Z
2022-03-30T13:51:23.000Z
38.454545
198
0.663515
8,966
/* * << * Davinci * == * Copyright (C) 2016 - 2019 EDP * == * 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 edp.davinci.dao; import edp.davinci.dto.projectDto.ProjectWithCreateBy; import edp.davinci.dto.starDto.StarUser; import edp.davinci.model.Star; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Component; import java.util.List; @Component public interface StarMapper { int insert(Star star); @Delete({ "delete from star", "where id = #{id,jdbcType=BIGINT}" }) int deleteById(Long id); @Delete({ "delete from star", "where target = #{target} and target_id = #{targetId} and user_id = #{userId}" }) int delete(@Param("userId") Long userId, @Param("targetId") Long targetId, @Param("target") String target); @Select({ "select * from star", "where target = #{target} and target_id = #{targetId} and user_id = #{userId}" }) Star select(@Param("userId") Long userId, @Param("targetId") Long targetId, @Param("target") String target); @Select({ "select p.*, u.id as 'createBy.id', IF(u.`name` is NULL,u.username,u.`name`) as 'createBy.username', u.avatar as 'createBy.avatar' from project p left join user u on u.id = p.user_id ", "where p.id in (select target_id from star where target = #{target} and user_id = #{userId})" }) List<ProjectWithCreateBy> getStarProjectListByUser(@Param("userId") Long userId, @Param("target") String target); @Select({ "select u.id, IF(u.`name` is NULL,u.username,u.`name`) as username, u.email, u.avatar, s.star_time from star s left join user u on u.id = s.user_id", "where s.target = #{target} and s.target_id = #{targetId}" }) List<StarUser> getStarUserListByTarget(@Param("targetId") Long targetId, @Param("target") String target); }
3e151ea14f9e638a6f353fa6c25b905303fa4e6d
8,942
java
Java
src/main/java/elsevier/jaxb/math/mathml/Mi.java
fanavarro/biotea-utilities
a4d88b6d672d452d2775e388d4988c61a69a187e
[ "Apache-2.0" ]
1
2016-02-18T13:17:23.000Z
2016-02-18T13:17:23.000Z
src/main/java/elsevier/jaxb/math/mathml/Mi.java
fanavarro/biotea-utilities
a4d88b6d672d452d2775e388d4988c61a69a187e
[ "Apache-2.0" ]
null
null
null
src/main/java/elsevier/jaxb/math/mathml/Mi.java
fanavarro/biotea-utilities
a4d88b6d672d452d2775e388d4988c61a69a187e
[ "Apache-2.0" ]
3
2016-05-13T20:33:45.000Z
2020-06-26T10:18:39.000Z
24.701657
147
0.577388
8,967
// // This file was pubmed.openAccess.jaxb.generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // 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: 2011.06.04 at 07:58:30 PM BST // package elsevier.jaxb.math.mathml; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyAttribute; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlElementRefs; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlIDREF; import javax.xml.bind.annotation.XmlMixed; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import javax.xml.namespace.QName; /** * <p>Java class for mi.type complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="mi.type"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;group ref="{http://www.w3.org/1998/Math/MathML}Glyph-alignmark.class" maxOccurs="unbounded" minOccurs="0"/> * &lt;attGroup ref="{http://www.w3.org/1998/Math/MathML}mi.attlist"/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "mi.type", propOrder = { "content" }) @XmlRootElement(name = "mi") public class Mi { @XmlElementRefs({ @XmlElementRef(name = "malignmark", namespace = "http://www.w3.org/1998/Math/MathML", type = Malignmark.class), @XmlElementRef(name = "mglyph", namespace = "http://www.w3.org/1998/Math/MathML", type = Mglyph.class) }) @XmlMixed protected List<Object> content; @XmlAttribute(name = "class") @XmlSchemaType(name = "NMTOKENS") protected List<String> clazzs; @XmlAttribute protected String style; @XmlAttribute @XmlIDREF @XmlSchemaType(name = "IDREF") protected Object xref; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected String id; @XmlAttribute(namespace = "http://www.w3.org/1999/xlink") @XmlSchemaType(name = "anyURI") protected String href; @XmlAttribute protected String mathvariant; @XmlAttribute protected String mathsize; @XmlAttribute protected String mathcolor; @XmlAttribute protected String mathbackground; @XmlAnyAttribute private Map<QName, String> otherAttributes = new HashMap<QName, String>(); /** * Gets the value of the content property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the content property. * * <p> * For example, to add a new item, do as follows: * <pre> * getContent().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Malignmark } * {@link String } * {@link Mglyph } * * */ public List<Object> getContent() { if (content == null) { content = new ArrayList<Object>(); } return this.content; } /** * Gets the value of the clazzs property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the clazzs property. * * <p> * For example, to add a new item, do as follows: * <pre> * getClazzs().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getClazzs() { if (clazzs == null) { clazzs = new ArrayList<String>(); } return this.clazzs; } /** * Gets the value of the style property. * * @return * possible object is * {@link String } * */ public String getStyle() { return style; } /** * Sets the value of the style property. * * @param value * allowed object is * {@link String } * */ public void setStyle(String value) { this.style = value; } /** * Gets the value of the xref property. * * @return * possible object is * {@link Object } * */ public Object getXref() { return xref; } /** * Sets the value of the xref property. * * @param value * allowed object is * {@link Object } * */ public void setXref(Object value) { this.xref = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the href property. * * @return * possible object is * {@link String } * */ public String getHref() { return href; } /** * Sets the value of the href property. * * @param value * allowed object is * {@link String } * */ public void setHref(String value) { this.href = value; } /** * Gets the value of the mathvariant property. * * @return * possible object is * {@link String } * */ public String getMathvariant() { return mathvariant; } /** * Sets the value of the mathvariant property. * * @param value * allowed object is * {@link String } * */ public void setMathvariant(String value) { this.mathvariant = value; } /** * Gets the value of the mathsize property. * * @return * possible object is * {@link String } * */ public String getMathsize() { return mathsize; } /** * Sets the value of the mathsize property. * * @param value * allowed object is * {@link String } * */ public void setMathsize(String value) { this.mathsize = value; } /** * Gets the value of the mathcolor property. * * @return * possible object is * {@link String } * */ public String getMathcolor() { return mathcolor; } /** * Sets the value of the mathcolor property. * * @param value * allowed object is * {@link String } * */ public void setMathcolor(String value) { this.mathcolor = value; } /** * Gets the value of the mathbackground property. * * @return * possible object is * {@link String } * */ public String getMathbackground() { return mathbackground; } /** * Sets the value of the mathbackground property. * * @param value * allowed object is * {@link String } * */ public void setMathbackground(String value) { this.mathbackground = value; } /** * Gets a map that contains attributes that aren't bound to any typed property on this class. * * <p> * the map is keyed by the name of the attribute and * the value is the string value of the attribute. * * the map returned by this method is live, and you can add new attribute * by updating the map directly. Because of this design, there's no setter. * * * @return * always non-null */ public Map<QName, String> getOtherAttributes() { return otherAttributes; } }
3e151f59fc5a16989001a036e988d22a168975c7
3,653
java
Java
diana/diana-column/src/main/java/org/eclipse/jnosql/diana/column/query/DefaultDeleteQueryBuilder.java
joao0212/jnosql
fcc6b7d20bbfc22e767100f3308654733abf7f5e
[ "Apache-2.0" ]
2
2020-09-01T17:30:37.000Z
2020-09-01T22:47:51.000Z
diana/diana-column/src/main/java/org/eclipse/jnosql/diana/column/query/DefaultDeleteQueryBuilder.java
joao0212/jnosql
fcc6b7d20bbfc22e767100f3308654733abf7f5e
[ "Apache-2.0" ]
null
null
null
diana/diana-column/src/main/java/org/eclipse/jnosql/diana/column/query/DefaultDeleteQueryBuilder.java
joao0212/jnosql
fcc6b7d20bbfc22e767100f3308654733abf7f5e
[ "Apache-2.0" ]
null
null
null
25.193103
99
0.673693
8,968
/* * * Copyright (c) 2017 Otávio Santana and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php. * * You may elect to redistribute this code under either of these licenses. * * Contributors: * * Otavio Santana * */ package org.eclipse.jnosql.diana.column.query; import jakarta.nosql.column.ColumnDeleteQuery; import jakarta.nosql.column.ColumnDeleteQuery.ColumnDelete; import jakarta.nosql.column.ColumnDeleteQuery.ColumnDeleteFrom; import jakarta.nosql.column.ColumnDeleteQuery.ColumnDeleteNotCondition; import jakarta.nosql.column.ColumnDeleteQuery.ColumnDeleteWhere; import jakarta.nosql.column.ColumnFamilyManager; import java.util.List; import static java.util.Objects.requireNonNull; /** * The default implementation to Delete query */ class DefaultDeleteQueryBuilder extends BaseQueryBuilder implements ColumnDelete, ColumnDeleteFrom, ColumnDeleteWhere, ColumnDeleteNotCondition { private String columnFamily; private final List<String> columns; DefaultDeleteQueryBuilder(List<String> columns) { this.columns = columns; } @Override public ColumnDeleteFrom from(String columnFamily) { requireNonNull(columnFamily, "columnFamily is required"); this.columnFamily = columnFamily; return this; } @Override public ColumnDeleteQuery.ColumnDeleteNameCondition where(String name) { requireNonNull(name, "name is required"); this.name = name; return this; } @Override public ColumnDeleteQuery.ColumnDeleteNameCondition and(String name) { requireNonNull(name, "name is required"); this.name = name; this.and = true; return this; } @Override public ColumnDeleteQuery.ColumnDeleteNameCondition or(String name) { requireNonNull(name, "name is required"); this.name = name; this.and = false; return this; } @Override public ColumnDeleteNotCondition not() { this.negate = true; return this; } @Override public <T> ColumnDeleteWhere eq(T value) { eqImpl(value); return this; } @Override public ColumnDeleteWhere like(String value) { likeImpl(value); return this; } @Override public <T> ColumnDeleteWhere gt(T value) { gtImpl(value); return this; } @Override public <T> ColumnDeleteWhere gte(T value) { gteImpl(value); return this; } @Override public <T> ColumnDeleteWhere lt(T value) { ltImpl(value); return this; } @Override public <T> ColumnDeleteWhere lte(T value) { lteImpl(value); return this; } @Override public <T> ColumnDeleteWhere between(T valueA, T valueB) { betweenImpl(valueA, valueB); return this; } @Override public <T> ColumnDeleteWhere in(Iterable<T> values) { inImpl(values); return this; } @Override public ColumnDeleteQuery build() { return new DefaultColumnDeleteQuery(columnFamily, condition, columns); } @Override public void delete(ColumnFamilyManager manager) { requireNonNull(manager, "manager is required"); manager.delete(this.build()); } }
3e1520ade815a4a0e4efcf483993e32fc7690972
7,271
java
Java
ControleAcesso/src/br/ufsc/ine5605/controleacesso/View/TelaSwingGestaoPermissaoSala.java
caionoguerol/controlador-acesso
8c59a5fcbe86d6fc0c2aa3ece2f0fc4e59abdd7d
[ "MIT" ]
null
null
null
ControleAcesso/src/br/ufsc/ine5605/controleacesso/View/TelaSwingGestaoPermissaoSala.java
caionoguerol/controlador-acesso
8c59a5fcbe86d6fc0c2aa3ece2f0fc4e59abdd7d
[ "MIT" ]
null
null
null
ControleAcesso/src/br/ufsc/ine5605/controleacesso/View/TelaSwingGestaoPermissaoSala.java
caionoguerol/controlador-acesso
8c59a5fcbe86d6fc0c2aa3ece2f0fc4e59abdd7d
[ "MIT" ]
null
null
null
34.13615
126
0.641315
8,969
/* * 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 br.ufsc.ine5605.controleacesso.View; import br.ufsc.ine5605.controleacesso.Controller.CtrlSala; import br.ufsc.ine5605.controleacesso.Model.Pessoa; import br.ufsc.ine5605.controleacesso.Persistencia.SalaDAO; import br.ufsc.ine5605.controleacesso.validadores.ValidaERetorna; import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; /** * * @author Linnety3 */ public class TelaSwingGestaoPermissaoSala extends JFrame { private JLabel label; private JButton permitirAcesso; private JButton removerAcesso; private JButton voltar; private JTable table; private String codSala; private ValidaERetorna validador = new ValidaERetorna(); public TelaSwingGestaoPermissaoSala(String codigo) { super("Gerenciamento das liberações de salas"); codSala = codigo; //criação do painel JPanel panelPermissaoSala = new JPanel(new GridBagLayout()); GridBagConstraints gbcPanel = new GridBagConstraints(); gbcPanel.anchor = GridBagConstraints.WEST; gbcPanel.insets = new Insets(5, 5, 5, 5); panelPermissaoSala.setBackground(Color.WHITE); setSize(680, 300); panelPermissaoSala.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Gerenciamento das liberações de acesso | Número da sala selecionada: " + CtrlSala.getInstancia().findSalaByCodigoSala(codigo).getNumero())); setLocationRelativeTo(null); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); getContentPane().add(panelPermissaoSala); //COMPONENTES TELASWINGPERMISSAOSALA GridBagConstraints gbc = new GridBagConstraints(); gbc.insets = new Insets(5, 5, 5, 5); // Label label = new JLabel(); label.setText("Selecione uma das opções"); //adicionar Sala a pessoa permitirAcesso = new JButton("Permitir Acesso"); permitirAcesso.setActionCommand("permitirAcesso"); gbc.gridx = 1; gbc.gridy = 3; gbc.gridwidth = 1; gbc.fill = GridBagConstraints.HORIZONTAL; panelPermissaoSala.add(permitirAcesso, gbc); //Botao Remover acesso //tira sala da pessoa removerAcesso = new JButton("Remover Acesso"); removerAcesso.setActionCommand("removerAcesso"); gbc.gridx = 2; gbc.gridy = 3; gbc.gridwidth = 1; gbc.fill = GridBagConstraints.HORIZONTAL; panelPermissaoSala.add(removerAcesso, gbc); //Botao voltar voltar = new JButton("Voltar"); voltar.setActionCommand("voltar"); gbc.gridx = 3; gbc.gridy = 3; gbc.gridwidth = 1; gbc.fill = GridBagConstraints.HORIZONTAL; panelPermissaoSala.add(voltar, gbc); TelaSwingGestaoPermissaoSala.GerenciadorBotoes btManager = new TelaSwingGestaoPermissaoSala.GerenciadorBotoes(); permitirAcesso.addActionListener(btManager); removerAcesso.addActionListener(btManager); voltar.addActionListener(btManager); //CONFIGURACOES TABELA table = new JTable(); JScrollPane scroll = new JScrollPane(table); GridBagConstraints gbcTable = new GridBagConstraints(); scroll.setPreferredSize(new Dimension(650, 200)); gbcTable.gridx = 0; gbcTable.gridy = 0; gbcTable.gridheight = 2; gbcTable.gridwidth = 8; gbcTable.fill = GridBagConstraints.CENTER; table.setFillsViewportHeight(true); table.setPreferredScrollableViewportSize(new Dimension(650, 200)); panelPermissaoSala.add(scroll, gbcTable); updateTable(codSala); } private class GerenciadorBotoes implements ActionListener { @Override public void actionPerformed(ActionEvent e) { try { switch (e.getActionCommand()) { case ("permitirAcesso"): permitirAcesso(); updateTable(codSala); break; case ("removerAcesso"): removerAcesso(); updateTable(codSala); break; case ("voltar"): setVisible(false); CtrlSala.getInstancia().abreTelaSwingSala(); break; } } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Opcao Invalida! Escolha uma opcao dentre das opcoes na lista ."); } } } private void updateTable(String codSala) { DefaultTableModel modelo = new DefaultTableModel(); modelo.setNumRows(0); modelo.addColumn("matricula"); modelo.addColumn("nome"); modelo.addColumn("telefone"); modelo.addColumn("email"); ArrayList<Pessoa> listaPessoasCadastradas = SalaDAO.getInstancia().getSala(codSala).getPessoasCadastradas(); if (listaPessoasCadastradas == null) { modelo.addRow(new Object[]{"Sem Pessoa cadastrada", "N/A", "N/A", "N/A", "N/A"}); } else { for (Pessoa pessoa : listaPessoasCadastradas) { modelo.addRow(new Object[]{pessoa.getMatricula(), pessoa.getNome(), pessoa.getTelefone(), pessoa.getEmail()}); } } table.setModel(modelo); this.repaint(); } private void permitirAcesso() { int matricula = validador.recebeValorInteiro("Digite a matricula: "); try { CtrlSala.getInstancia().cadastraPessoaNaSala(matricula, codSala); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage()); } } private void removerAcesso() { System.out.println("entra no remove acesso da tela seing getstao de permissao sala"); int linhaSelecionada = table.getSelectedRow(); System.out.println(linhaSelecionada); try { if (linhaSelecionada >= 0) { int matricula = (int) table.getValueAt(linhaSelecionada, 0); System.out.println("A matricula capturada é: " + matricula); CtrlSala.getInstancia().deletaPessoaNaSala(matricula, codSala); } else { JOptionPane.showMessageDialog(null, "É necesário selecionar uma linha."); } } catch (Exception exception) { System.out.println("entrou no catch. a mensagem da exception é: " + exception.getMessage()); JOptionPane.showMessageDialog(null, exception.getMessage()); } } }
3e1520c46f7feded7d9e6d718c72f1a7cd146990
3,365
java
Java
src/main/java/com/wanhutong/backend/modules/sys/web/attribute/AttributeValueController.java
fengyonghui/wanhugou_bg
a5d7579b331ef6d81f367be34967652fcb848da7
[ "Apache-2.0" ]
null
null
null
src/main/java/com/wanhutong/backend/modules/sys/web/attribute/AttributeValueController.java
fengyonghui/wanhugou_bg
a5d7579b331ef6d81f367be34967652fcb848da7
[ "Apache-2.0" ]
null
null
null
src/main/java/com/wanhutong/backend/modules/sys/web/attribute/AttributeValueController.java
fengyonghui/wanhugou_bg
a5d7579b331ef6d81f367be34967652fcb848da7
[ "Apache-2.0" ]
1
2019-12-17T03:09:56.000Z
2019-12-17T03:09:56.000Z
39.588235
126
0.803566
8,970
/** * Copyright &copy; 2017 <a href="www.wanhutong.com">wanhutong</a> All rights reserved. */ package com.wanhutong.backend.modules.sys.web.attribute; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.wanhutong.backend.modules.sys.entity.attribute.AttributeValueV2; import com.wanhutong.backend.modules.sys.service.attribute.AttributeValueV2Service; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.wanhutong.backend.common.config.Global; import com.wanhutong.backend.common.persistence.Page; import com.wanhutong.backend.common.web.BaseController; import com.wanhutong.backend.common.utils.StringUtils; import com.wanhutong.backend.modules.sys.entity.attribute.AttributeValue; import com.wanhutong.backend.modules.sys.service.attribute.AttributeValueService; /** * 标签属性值Controller * @author zx * @version 2018-03-21 */ @Controller @RequestMapping(value = "${adminPath}/sys/attribute/attributeValue") public class AttributeValueController extends BaseController { @Autowired private AttributeValueV2Service attributeValueService; @ModelAttribute public AttributeValueV2 get(@RequestParam(required=false) Integer id) { AttributeValueV2 entity = null; if (id!=null){ entity = attributeValueService.get(id); } if (entity == null){ entity = new AttributeValueV2(); } return entity; } @RequiresPermissions("sys:attribute:attributeValue:view") @RequestMapping(value = {"list", ""}) public String list(AttributeValueV2 attributeValue, HttpServletRequest request, HttpServletResponse response, Model model) { Page<AttributeValueV2> page = attributeValueService.findPage(new Page<AttributeValueV2>(request, response), attributeValue); model.addAttribute("page", page); return "modules/sys/attribute/attributeValueList"; } @RequiresPermissions("sys:attribute:attributeValue:view") @RequestMapping(value = "form") public String form(AttributeValueV2 attributeValue, Model model) { model.addAttribute("attributeValue", attributeValue); return "modules/sys/attribute/attributeValueForm"; } @RequiresPermissions("sys:attribute:attributeValue:edit") @RequestMapping(value = "save") public String save(AttributeValueV2 attributeValue, Model model, RedirectAttributes redirectAttributes) { if (!beanValidator(model, attributeValue)){ return form(attributeValue, model); } attributeValueService.save(attributeValue); addMessage(redirectAttributes, "保存标签属性值成功"); return "redirect:"+Global.getAdminPath()+"/sys/attribute/attributeValue/?repage"; } @RequiresPermissions("sys:attribute:attributeValue:edit") @RequestMapping(value = "delete") public String delete(AttributeValueV2 attributeValue, RedirectAttributes redirectAttributes) { attributeValueService.delete(attributeValue); addMessage(redirectAttributes, "删除标签属性值成功"); return "redirect:"+Global.getAdminPath()+"/sys/attribute/attributeValue/?repage"; } }
3e15218dff24aaf61c2a8175c0ba7711de4d92d8
6,576
java
Java
impl/src/main/java/com/webguys/ponzu/impl/set/fixed/QuadrupletonSet.java
Webguys/ponzu
959d6a8a4e19524e33dd3f0889b7ef9a39f30119
[ "Apache-2.0" ]
1
2015-10-03T16:57:48.000Z
2015-10-03T16:57:48.000Z
impl/src/main/java/com/webguys/ponzu/impl/set/fixed/QuadrupletonSet.java
Webguys/ponzu
959d6a8a4e19524e33dd3f0889b7ef9a39f30119
[ "Apache-2.0" ]
null
null
null
impl/src/main/java/com/webguys/ponzu/impl/set/fixed/QuadrupletonSet.java
Webguys/ponzu
959d6a8a4e19524e33dd3f0889b7ef9a39f30119
[ "Apache-2.0" ]
null
null
null
27.982979
98
0.620438
8,971
/* * Copyright 2011 Goldman Sachs. * * 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.webguys.ponzu.impl.set.fixed; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; import com.webguys.ponzu.api.block.procedure.ObjectIntProcedure; import com.webguys.ponzu.api.block.procedure.Procedure; import com.webguys.ponzu.api.block.procedure.Procedure2; import com.webguys.ponzu.api.set.MutableSet; import com.webguys.ponzu.impl.block.factory.Comparators; import com.webguys.ponzu.impl.set.mutable.UnifiedSet; import net.jcip.annotations.NotThreadSafe; @NotThreadSafe final class QuadrupletonSet<T> extends AbstractMemoryEfficientMutableSet<T> implements Externalizable { private static final long serialVersionUID = 1L; private T element1; private T element2; private T element3; private T element4; @SuppressWarnings("UnusedDeclaration") public QuadrupletonSet() { // For Externalizable use only } QuadrupletonSet(T obj1, T obj2, T obj3, T obj4) { this.element1 = obj1; this.element2 = obj2; this.element3 = obj3; this.element4 = obj4; } @Override public int size() { return 4; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof Set)) { return false; } Set<?> collection = (Set<?>) o; return collection.size() == this.size() && collection.contains(this.element1) && collection.contains(this.element2) && collection.contains(this.element3) && collection.contains(this.element4); } @Override public int hashCode() { return this.nullSafeHashCode(this.element1) + this.nullSafeHashCode(this.element2) + this.nullSafeHashCode(this.element3) + this.nullSafeHashCode(this.element4); } // Weird implementation of clone() is ok on final classes @Override public QuadrupletonSet<T> clone() { return new QuadrupletonSet<T>(this.element1, this.element2, this.element3, this.element4); } @Override public boolean contains(Object obj) { return Comparators.nullSafeEquals(obj, this.element1) || Comparators.nullSafeEquals(obj, this.element2) || Comparators.nullSafeEquals(obj, this.element3) || Comparators.nullSafeEquals(obj, this.element4); } @Override public Iterator<T> iterator() { return new QuadrupletonSetIterator(); } @Override public T getFirst() { return this.element1; } T getSecond() { return this.element2; } T getThird() { return this.element3; } @Override public T getLast() { return this.element4; } @Override public void forEach(Procedure<? super T> procedure) { procedure.value(this.element1); procedure.value(this.element2); procedure.value(this.element3); procedure.value(this.element4); } @Override public void forEachWithIndex(ObjectIntProcedure<? super T> objectIntProcedure) { objectIntProcedure.value(this.element1, 0); objectIntProcedure.value(this.element2, 1); objectIntProcedure.value(this.element3, 2); objectIntProcedure.value(this.element4, 3); } @Override public <P> void forEachWith(Procedure2<? super T, ? super P> procedure, P parameter) { procedure.value(this.element1, parameter); procedure.value(this.element2, parameter); procedure.value(this.element3, parameter); procedure.value(this.element4, parameter); } public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(this.element1); out.writeObject(this.element2); out.writeObject(this.element3); out.writeObject(this.element4); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.element1 = (T) in.readObject(); this.element2 = (T) in.readObject(); this.element3 = (T) in.readObject(); this.element4 = (T) in.readObject(); } protected class QuadrupletonSetIterator extends MemoryEfficientSetIterator { @Override protected T getElement(int i) { if (i == 0) { return QuadrupletonSet.this.element1; } if (i == 1) { return QuadrupletonSet.this.element2; } if (i == 2) { return QuadrupletonSet.this.element3; } if (i == 3) { return QuadrupletonSet.this.element4; } throw new NoSuchElementException("i=" + i); } } public MutableSet<T> with(T element) { return this.contains(element) ? this : UnifiedSet.newSet(this).with(element); } public MutableSet<T> without(T element) { if (Comparators.nullSafeEquals(element, this.element1)) { return new TripletonSet<T>(this.element2, this.element3, this.element4); } if (Comparators.nullSafeEquals(element, this.element2)) { return new TripletonSet<T>(this.element1, this.element3, this.element4); } if (Comparators.nullSafeEquals(element, this.element3)) { return new TripletonSet<T>(this.element1, this.element2, this.element4); } if (Comparators.nullSafeEquals(element, this.element4)) { return new TripletonSet<T>(this.element1, this.element2, this.element3); } return this; } }
3e15221fab225624ae09ba038054da1faffe3055
1,863
java
Java
polocloud-modules/serverselector-module/src/main/java/de/polocloud/modules/serverselector/pluginside/SignPlugin.java
PoloCloud-official/cloudsystem
3a93c4849ad5bd14c7112e1c4586721229b5b77c
[ "MIT" ]
12
2021-08-08T19:46:14.000Z
2022-01-03T12:49:28.000Z
polocloud-modules/serverselector-module/src/main/java/de/polocloud/modules/serverselector/pluginside/SignPlugin.java
PoloCloud-official/cloudsystem
3a93c4849ad5bd14c7112e1c4586721229b5b77c
[ "MIT" ]
15
2021-09-02T22:33:28.000Z
2022-01-16T22:51:07.000Z
polocloud-modules/serverselector-module/src/main/java/de/polocloud/modules/serverselector/pluginside/SignPlugin.java
PoloCloud-official/cloudsystem
3a93c4849ad5bd14c7112e1c4586721229b5b77c
[ "MIT" ]
20
2021-08-09T08:55:38.000Z
2022-01-03T12:49:04.000Z
44.357143
139
0.764895
8,972
package de.polocloud.modules.serverselector.pluginside; import de.polocloud.api.PoloCloudAPI; import de.polocloud.modules.serverselector.api.SignAPI; import de.polocloud.modules.serverselector.pluginside.api.BukkitBukkitAPI; import de.polocloud.modules.serverselector.pluginside.api.BukkitGlobalAPI; import de.polocloud.modules.serverselector.pluginside.command.SignCommand; import de.polocloud.modules.serverselector.pluginside.api.updater.BukkitSignUpdater; import de.polocloud.modules.serverselector.pluginside.listener.PluginGameServerListener; import de.polocloud.modules.serverselector.pluginside.listener.PluginPlayerSignListener; import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; public class SignPlugin extends JavaPlugin { @Override public void onEnable() { SignAPI signAPI = new SignAPI(new BukkitBukkitAPI(new BukkitSignUpdater(this)), new BukkitGlobalAPI()); //Registering command PoloCloudAPI.getInstance().getCommandManager().registerCommand(new SignCommand()); //Registering listener Bukkit.getPluginManager().registerEvents(new PluginPlayerSignListener(), this); PoloCloudAPI.getInstance().getEventManager().registerListener(signAPI.getEntity(), new PluginGameServerListener()); System.out.println("======= Enabled SignPlugin ======="); //Starting sign updating Thread thread = new Thread(SignAPI.getInstance().getBukkitSideAPI().getSignUpdater()); thread.setName("module-sign-updater"); thread.setDaemon(true); thread.start(); } @Override public void onDisable() { PoloCloudAPI.getInstance().unregisterInstance(SignAPI.getInstance().getEntity()); PoloCloudAPI.getInstance().getEventManager().unregisterListener(SignAPI.getInstance().getEntity(), PluginGameServerListener.class); } }
3e15225671c9e10fa876a6598bcc667bbc13ec9f
334
java
Java
src/main/java/br/gov/inmetro/beacon/engine/domain/certificate/Certificate.java
leandrofpk/beacon-engine
9f2a1cde40789df2f48791c83b58a3f0a3fb8830
[ "MIT" ]
3
2020-03-30T20:48:25.000Z
2022-01-09T23:58:53.000Z
src/main/java/br/gov/inmetro/beacon/engine/domain/certificate/Certificate.java
leandrofpk/beacon-engine
9f2a1cde40789df2f48791c83b58a3f0a3fb8830
[ "MIT" ]
14
2020-12-04T20:10:59.000Z
2021-11-10T13:29:13.000Z
beacon-engine/src/main/java/br/gov/inmetro/beacon/engine/domain/certificate/Certificate.java
siccciber/RandBeacon
cb99a1a461a25d0a5c1130f3f66507d49e05d93e
[ "MIT" ]
null
null
null
19.647059
87
0.736527
8,973
package br.gov.inmetro.beacon.engine.domain.certificate; /** * Controlar o certificado * A última linha do BD é o ativo * Implementar uma interface para decidir se o certificado vem do file system ou do HSM */ public class Certificate { private String hash; private long chainIndex; private String certificate; }
3e1522b0cd3921b69aabd50f4b1a10e8513f918e
836
java
Java
app/src/main/java/com/odin/link/demo/MainActivity.java
odindata/LinkSDK-for-Android
de67d4d6c8f3ab8cbd8cc2c51924f7f15b2d59d9
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/odin/link/demo/MainActivity.java
odindata/LinkSDK-for-Android
de67d4d6c8f3ab8cbd8cc2c51924f7f15b2d59d9
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/odin/link/demo/MainActivity.java
odindata/LinkSDK-for-Android
de67d4d6c8f3ab8cbd8cc2c51924f7f15b2d59d9
[ "Apache-2.0" ]
null
null
null
23.222222
92
0.694976
8,974
package com.odin.link.demo; import android.view.View; import com.gyf.immersionbar.ImmersionBar; import com.odin.link.demo.ui.OneKeyWakeupActivity; import com.odin.link.demo.ui.ScenarioReductionActivity; public class MainActivity extends BaseActivity { @Override public int getLayoutId() { return R.layout.activity_main; } @Override public void initView() { ImmersionBar.with(this).barColor(R.color.colorWhite).statusBarDarkFont(true).init(); checkPermission(); } public void oneKeyWakeup(View view) { startToActivity(OneKeyWakeupActivity.class); } public void scenarioReduction(View view) { startToActivity(ScenarioReductionActivity.class); } @Override public void onBackPressed() { super.onBackPressed(); finish(); } }
3e1522dcdabab105fa882c5689e6ed4556457c58
2,839
java
Java
src/main/java/cn/shaoxiongdu/controller/productmodule/ProductController.java
shaoxiongdu/SupermarketCashRegisterSystem
a1e843cda7ee91b478ff17566d297434fbbb34a1
[ "MIT" ]
4
2021-09-14T02:20:13.000Z
2022-02-28T08:34:01.000Z
stage1-project/src/main/java/cn/shaoxiongdu/controller/productmodule/ProductController.java
shaoxiongdu/weixin-javase
233191efe825563a622af573e17947820e92fbd9
[ "MIT" ]
null
null
null
stage1-project/src/main/java/cn/shaoxiongdu/controller/productmodule/ProductController.java
shaoxiongdu/weixin-javase
233191efe825563a622af573e17947820e92fbd9
[ "MIT" ]
null
null
null
28.138614
140
0.475018
8,975
/* * Copyright (c) 2021. 杜少雄 AllRightsReserved */ package cn.shaoxiongdu.controller.productmodule; import cn.shaoxiongdu.bean.Product; import cn.shaoxiongdu.bean.ProductType; import cn.shaoxiongdu.service.ProductService; import cn.shaoxiongdu.service.ProductTypeService; import cn.shaoxiongdu.utils.InputUtils; import java.util.ArrayList; import java.util.Scanner; /** * @作者: 杜少雄 <dycjh@example.com> * @日期: 2021年09月13日 | 17:25 * @描述: 产品 */ public class ProductController { public static void menu() { boolean isEnd = false; while (!isEnd) { System.out.println("---------- 商 品 管 理 模 块 --------------------"); System.out.println("1.商 品 列 表\n2.新 增 商 品 \n3.移 除 商 品 \n4.返 回 上 一 级"); System.out.println("-------------------------------------------------"); System.out.print("\n 请 输 入 您 的 选 择:"); int select = InputUtils.inputInt(1, 4); switch (select) { case 1: printAll(); break; case 2: add(); break; case 3: remove(); break; case 4: isEnd = true; break; } } } private static void remove() { printAll(); System.out.print("请输入要移除的类型ID: "); int id = new Scanner(System.in).nextInt(); ProductTypeService.remove(id); } /** * 商品列表 */ public static void printAll() { ArrayList<Product> all = ProductService.getAll(); System.out.println("--------------------------------------- 商 品 列 表 -------------------------------------------------------------"); System.out.println("\t编号\t\t名称\t\t价格\t\t所属类别"); for (Product product : all) { System.out.println(product); } System.out.println("---------------------------------------- 商 品 列 表 ------------------------------------------------------------"); System.out.println("\t共计" + all.size() + "条数据。"); } public static void add() { System.out.println("------------- 新 增 商 品 ---------------"); Scanner scanner = new Scanner(System.in); System.out.print("请输入商品名称:"); String name = scanner.next(); System.out.print("请输入商品价格:"); Double price = scanner.nextDouble(); ArrayList<ProductType> all = ProductTypeService.getAll(); for (ProductType productType : all) { System.out.println(productType); } System.out.print("请输入商品类型编号:"); int typeId = scanner.nextInt(); Product product = new Product(name, price, typeId); ProductService.add(product); System.out.println(name + " 添加成功! "); } }
3e152398cee6d4d93ec12bee245d8af39c1dcf9c
404
java
Java
components/inspectit-ocelot-configurationserver/src/main/java/rocks/inspectit/ocelot/rest/alert/kapacitor/model/KapacitorState.java
inspectIT/inspectit-oce
cc6f1ed2795f69ba244562d4b8a57437db45c784
[ "Apache-2.0" ]
12
2018-12-20T07:05:30.000Z
2019-03-23T17:47:29.000Z
components/inspectit-ocelot-configurationserver/src/main/java/rocks/inspectit/ocelot/rest/alert/kapacitor/model/KapacitorState.java
inspectIT/inspectit-oce
cc6f1ed2795f69ba244562d4b8a57437db45c784
[ "Apache-2.0" ]
80
2018-12-03T07:43:47.000Z
2019-03-25T08:14:45.000Z
components/inspectit-ocelot-configurationserver/src/main/java/rocks/inspectit/ocelot/rest/alert/kapacitor/model/KapacitorState.java
inspectIT/inspectit-oce
cc6f1ed2795f69ba244562d4b8a57437db45c784
[ "Apache-2.0" ]
6
2018-12-03T14:40:05.000Z
2019-03-15T07:52:05.000Z
17.565217
64
0.675743
8,977
package rocks.inspectit.ocelot.rest.alert.kapacitor.model; import lombok.Builder; import lombok.Value; /** * Response Object for the state of Kapacitor. */ @Value @Builder public class KapacitorState { /** * True, if the connection to kapacitor has been configured. */ boolean enabled; /** * True, if a ping to Kapacitor succeeded. */ boolean kapacitorOnline; }
3e1523a2338f93bce0ae864317ab9c1b71c4134e
6,892
java
Java
cooper-webserver/src/main/java/jdepend/webserver/web/ResultController.java
jdepend/cooper
baac23d8372a4ece5c103a815b2a573a55ee59cb
[ "Apache-2.0" ]
9
2015-01-30T06:55:28.000Z
2019-11-28T08:47:14.000Z
cooper-webserver/src/main/java/jdepend/webserver/web/ResultController.java
jdepend/cooper
baac23d8372a4ece5c103a815b2a573a55ee59cb
[ "Apache-2.0" ]
3
2015-08-12T23:09:51.000Z
2018-12-07T06:10:44.000Z
cooper-webserver/src/main/java/jdepend/webserver/web/ResultController.java
jdepend/cooper
baac23d8372a4ece5c103a815b2a573a55ee59cb
[ "Apache-2.0" ]
7
2015-03-05T07:33:55.000Z
2021-12-14T07:17:40.000Z
40.541176
114
0.754498
8,978
package jdepend.webserver.web; import java.util.List; import javax.servlet.http.HttpServletRequest; import jdepend.framework.exception.JDependException; import jdepend.util.todolist.TODOItem; import jdepend.webserver.model.WebAnalysisResult; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping(value = "result") public class ResultController { @RequestMapping(value = "/component/{componentId}/classes/view.ajax", method = RequestMethod.GET) public String componentDetails(Model model, @PathVariable String componentId, HttpServletRequest request) throws JDependException { WebAnalysisResult result = (WebAnalysisResult) request.getSession().getAttribute(WebConstants.SESSION_RESULT); if (result == null) { throw new JDependException("Session 过期,或者非法进入该页。"); } model.addAttribute("classes", result.getTheComponent(componentId).getClasses()); return "class_list"; } @RequestMapping(value = "/component/{componentId}/ca/view.ajax", method = RequestMethod.GET) public String componentCa(Model model, @PathVariable String componentId, HttpServletRequest request) throws JDependException { WebAnalysisResult result = (WebAnalysisResult) request.getSession().getAttribute(WebConstants.SESSION_RESULT); if (result == null) { throw new JDependException("Session 过期,或者非法进入该页。"); } model.addAttribute("components", result.getTheComponent(componentId).getAfferents()); return "component_list"; } @RequestMapping(value = "/component/{componentId}/ce/view.ajax", method = RequestMethod.GET) public String componentCe(Model model, @PathVariable String componentId, HttpServletRequest request) throws JDependException { WebAnalysisResult result = (WebAnalysisResult) request.getSession().getAttribute(WebConstants.SESSION_RESULT); if (result == null) { throw new JDependException("Session 过期,或者非法进入该页。"); } model.addAttribute("components", result.getTheComponent(componentId).getEfferents()); return "component_list"; } @RequestMapping(value = "/methods/{javaClassId}/view.ajax", method = RequestMethod.GET) public String methodlist(Model model, @PathVariable String javaClassId, HttpServletRequest request) throws JDependException { WebAnalysisResult result = (WebAnalysisResult) request.getSession().getAttribute(WebConstants.SESSION_RESULT); if (result == null) { throw new JDependException("Session 过期,或者非法进入该页。"); } model.addAttribute("methods", result.getTheClass(javaClassId).getJavaClass().getMethods()); return "method_list"; } @RequestMapping(value = "/invokedItems/{javaClassId}/{methodInfo}/view.ajax", method = RequestMethod.GET) public String invokedItemList(Model model, @PathVariable String javaClassId, @PathVariable String methodInfo, HttpServletRequest request) throws JDependException { WebAnalysisResult result = (WebAnalysisResult) request.getSession().getAttribute(WebConstants.SESSION_RESULT); if (result == null) { throw new JDependException("Session 过期,或者非法进入该页。"); } model.addAttribute("invokeitems", result.getTheClass(javaClassId).getJavaClass().getTheMethod(methodInfo) .getInvokedItems()); return "invokeitem_list"; } @RequestMapping(value = "/cascadeInvokedItems/{javaClassId}/{methodInfo}/view.ajax", method = RequestMethod.GET) public String cascadeInvokedItemList(Model model, @PathVariable String javaClassId, @PathVariable String methodInfo, HttpServletRequest request) throws JDependException { WebAnalysisResult result = (WebAnalysisResult) request.getSession().getAttribute(WebConstants.SESSION_RESULT); if (result == null) { throw new JDependException("Session 过期,或者非法进入该页。"); } model.addAttribute("invokeitems", result.getTheClass(javaClassId).getJavaClass().getTheMethod(methodInfo) .getCascadeInvokedItems()); return "invokeitem_list"; } @RequestMapping(value = "/invokeItems/{javaClassId}/{methodInfo}/view.ajax", method = RequestMethod.GET) public String invokeItemList(Model model, @PathVariable String javaClassId, @PathVariable String methodInfo, HttpServletRequest request) throws JDependException { WebAnalysisResult result = (WebAnalysisResult) request.getSession().getAttribute(WebConstants.SESSION_RESULT); if (result == null) { throw new JDependException("Session 过期,或者非法进入该页。"); } model.addAttribute("invokeitems", result.getTheClass(javaClassId).getJavaClass().getTheMethod(methodInfo) .getInvokeItems()); return "invokeitem_list"; } @RequestMapping(value = "/classes/view.ajax", method = RequestMethod.GET) public String classeslist(Model model, HttpServletRequest request) throws JDependException { WebAnalysisResult result = (WebAnalysisResult) request.getSession().getAttribute(WebConstants.SESSION_RESULT); if (result == null) { throw new JDependException("Session 过期,或者非法进入该页。"); } model.addAttribute("classes", result.getClasses()); return "class_list"; } @RequestMapping(value = "/methods/view.ajax", method = RequestMethod.GET) public String methodslist(Model model, HttpServletRequest request) throws JDependException { WebAnalysisResult result = (WebAnalysisResult) request.getSession().getAttribute(WebConstants.SESSION_RESULT); if (result == null) { throw new JDependException("Session 过期,或者非法进入该页。"); } model.addAttribute("methods", result.getMethods()); return "method_list"; } @RequestMapping(value = "/relation/{current}/{depend}/view.ajax", method = RequestMethod.GET) public String relationDetails(Model model, @PathVariable String current, @PathVariable String depend, HttpServletRequest request) throws JDependException { WebAnalysisResult result = (WebAnalysisResult) request.getSession().getAttribute(WebConstants.SESSION_RESULT); if (result == null) { throw new JDependException("Session 过期,或者非法进入该页。"); } model.addAttribute("relation", result.getTheRelation(current, depend)); return "relation_details"; } @RequestMapping(value = "/todoItem/{id}/view.ajax", method = RequestMethod.GET) public String todoItemDetails(Model model, @PathVariable String id, HttpServletRequest request) throws JDependException { List<TODOItem> todoList = (List<TODOItem>) request.getSession().getAttribute( WebConstants.SESSION_RESULT_TODOLIST); if (todoList == null) { throw new JDependException("Session 过期,或者非法进入该页。"); } for (TODOItem item : todoList) { if (item.getId().equals(id)) { model.addAttribute("todoItem", item); } } return "todo_item"; } }
3e1523c7c3766d5829ad4f1d198ee9f83bcf84cb
482
java
Java
LACCPlus/Hive/10022_2.java
sgholamian/log-aware-clone-detection
9993cb081c420413c231d1807bfff342c39aa69a
[ "MIT" ]
null
null
null
LACCPlus/Hive/10022_2.java
sgholamian/log-aware-clone-detection
9993cb081c420413c231d1807bfff342c39aa69a
[ "MIT" ]
null
null
null
LACCPlus/Hive/10022_2.java
sgholamian/log-aware-clone-detection
9993cb081c420413c231d1807bfff342c39aa69a
[ "MIT" ]
null
null
null
37.076923
83
0.715768
8,979
//,temp,MultiOutputFormat.java,575,582,temp,MultiOutputFormat.java,532,539 //,2 public class xxx { @Override public void setupJob(JobContext jobContext) throws IOException { for (String alias : outputCommitters.keySet()) { LOGGER.info("Calling setupJob for alias: " + alias); BaseOutputCommitterContainer outputContainer = outputCommitters.get(alias); outputContainer.getBaseCommitter().setupJob(outputContainer.getContext()); } } };
3e152499ffb77150e0e19a0345ff16705097aec0
3,280
java
Java
app/src/main/java/com/moviz/lib/sessionexport/ZephyrHxMSessionExporter.java
p3g4asus/moviz
83887ba6c36fc7ce76ab305aee4a8cb7c56b47ce
[ "MIT" ]
null
null
null
app/src/main/java/com/moviz/lib/sessionexport/ZephyrHxMSessionExporter.java
p3g4asus/moviz
83887ba6c36fc7ce76ab305aee4a8cb7c56b47ce
[ "MIT" ]
null
null
null
app/src/main/java/com/moviz/lib/sessionexport/ZephyrHxMSessionExporter.java
p3g4asus/moviz
83887ba6c36fc7ce76ab305aee4a8cb7c56b47ce
[ "MIT" ]
null
null
null
38.588235
120
0.55122
8,980
package com.moviz.lib.sessionexport; import com.jmatio.io.MatFileWriter; import com.jmatio.types.MLArray; import com.jmatio.types.MLDouble; import com.jmatio.types.MLInt16; import com.jmatio.types.MLUInt64; import com.jmatio.types.MLUInt8; import com.moviz.lib.comunication.plus.holder.PZephyrHxMHolder; import com.moviz.lib.plot.ProgressPub; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class ZephyrHxMSessionExporter implements SessionExporter { @Override public ArrayList<MLArray> export(com.moviz.lib.comunication.holder.SessionHolder ses, double offsetms, String path, ProgressPub<Integer[]> pp) throws IOException { ArrayList<MLArray> rv = new ArrayList<MLArray>(); List<com.moviz.lib.comunication.holder.DeviceUpdate> vals = ses.getValues(); double offs = offsetms / 1000.0; int ssize = 0, psize = 0; Integer[] progInt = new Integer[2]; progInt[1] = vals.size(); int i = 0; for (com.moviz.lib.comunication.holder.DeviceUpdate ww : vals) { PZephyrHxMHolder w = (PZephyrHxMHolder) ww; if (w.distance < 0) psize++; else ssize++; if (pp != null) { progInt[0] = ++i; pp.calcProgress(progInt, progInt[0], progInt[1]); } } Double[] distance_a = new Double[ssize]; Double[] speed_a = new Double[ssize]; Byte[] pulse_a = new Byte[ssize]; Byte[] battery_a = new Byte[ssize]; Long[] strides_a = new Long[ssize]; Long[] nbeats_a = new Long[ssize]; Short[] time_a = new Short[ssize]; Double[] cardio_a = new Double[psize]; int s = 0, p = 0; i = 0; for (com.moviz.lib.comunication.holder.DeviceUpdate ww : vals) { PZephyrHxMHolder w = (PZephyrHxMHolder) ww; if (w.distance < 0) cardio_a[p++] = w.timeRAbsms / 1000.0 + offs; else { distance_a[s] = w.distanceR; speed_a[s] = w.speed; nbeats_a[s] = (long) w.nBeatsR; time_a[s] = (short) ((w.timeRAbsms / 1000.0 + 0.5) + offs); strides_a[s] = (long) w.stridesR; battery_a[s] = w.battery; pulse_a[s++] = (byte) w.pulse; } if (pp != null) { progInt[0] = ++i; pp.calcProgress(progInt, progInt[0], progInt[1]); } } rv.add(new MLDouble("distance", distance_a, 1)); rv.add(new MLDouble("speed", speed_a, 1)); rv.add(new MLUInt8("pulse", pulse_a, 1)); rv.add(new MLUInt8("battery", battery_a, 1)); rv.add(new MLUInt64("strides", strides_a, 1)); rv.add(new MLUInt64("nbeats", nbeats_a, 1)); rv.add(new MLDouble("cardio", cardio_a, 1)); rv.add(new MLInt16("time", time_a, 1)); com.moviz.lib.comunication.holder.DeviceHolder devh = ses.getDevice(); new MatFileWriter(path + "/" + devh.getType().name() + "." + devh.getAlias() + ".mat", rv); return rv; } }
3e1524a3abe666229ecb42fce58097576a239ab6
1,625
java
Java
hoot-compiler/src/main/java/Hoot/Compiler/Constants/LiteralSymbol.java
nikboyd/hoot-smalltalk
08f20a84ba63a5ec54bf972d7665c5ac97616a6e
[ "MIT" ]
3
2022-01-20T22:44:45.000Z
2022-03-07T15:00:42.000Z
hoot-compiler/src/main/java/Hoot/Compiler/Constants/LiteralSymbol.java
nikboyd/hoot-smalltalk
08f20a84ba63a5ec54bf972d7665c5ac97616a6e
[ "MIT" ]
null
null
null
hoot-compiler/src/main/java/Hoot/Compiler/Constants/LiteralSymbol.java
nikboyd/hoot-smalltalk
08f20a84ba63a5ec54bf972d7665c5ac97616a6e
[ "MIT" ]
1
2022-01-20T22:44:50.000Z
2022-01-20T22:44:50.000Z
37.790698
113
0.681846
8,981
package Hoot.Compiler.Constants; import Hoot.Runtime.Emissions.Emission; import static Hoot.Runtime.Names.Keyword.*; import static Hoot.Runtime.Names.Primitive.*; import static Hoot.Runtime.Emissions.Emission.*; import static Hoot.Runtime.Behaviors.HootRegistry.*; /** * A literal Symbol. * * @author nik <efpyi@example.com> * @see "Copyright 1999,2021 Nikolas S Boyd." * @see "Permission is granted to copy this work provided this copyright statement is retained in all copies." */ public class LiteralSymbol extends LiteralString { public LiteralSymbol() { super(); } public LiteralSymbol(String value) { super(symbolize(value)); } public static LiteralSymbol with(String value, int line) { return new LiteralSymbol(value).withLine(line); } public static String symbolize(String contents) { if (contents.startsWith(Pound)) { contents = contents.substring(1); } if (contents.length() > 0 && contents.charAt(0) != SingleQuote.charAt(0)) { contents = SingleQuote + contents + SingleQuote; } return contents; } @Override public Emission emitOperand() { return emit(Symbol).value(encodedValue()); } @Override public Emission emitPrimitive() { return emitOperand(); } @Override public Class primitiveType() { return java.lang.String.class; } @Override public String primitiveFactoryName() { return Symbol; } @Override public String resolvedTypeName() { return (file().needsCollections() ? RootType().fullName() : SymbolType().fullName()); } } // LiteralSymbol
3e1524bb97834b615319b1e2dbfca0c196d0e367
5,201
java
Java
spock-core/src/main/java/org/spockframework/mock/EmptyOrDummyResponse.java
milo2048/spock
567b8b0ae792b0389ae874c02e827da39446b943
[ "Apache-2.0" ]
2,863
2015-01-02T07:08:15.000Z
2022-03-31T16:38:09.000Z
spock-core/src/main/java/org/spockframework/mock/EmptyOrDummyResponse.java
i32jiprd/spock
d222bd2f805ed93369a9acde8b1c75bc69377d76
[ "Apache-2.0" ]
989
2015-01-12T20:20:15.000Z
2022-03-29T10:19:25.000Z
spock-core/src/main/java/org/spockframework/mock/EmptyOrDummyResponse.java
i32jiprd/spock
d222bd2f805ed93369a9acde8b1c75bc69377d76
[ "Apache-2.0" ]
465
2015-01-22T22:55:53.000Z
2022-03-27T06:39:23.000Z
38.525926
109
0.707172
8,982
/* * Copyright 2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.spockframework.mock; import org.spockframework.util.ReflectionUtil; import spock.lang.Specification; import java.lang.reflect.*; import java.math.*; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.stream.*; import groovy.lang.*; /** * A response strategy that returns zero, an "empty" object, or a "dummy" object, * depending on the method's declared return type. */ public class EmptyOrDummyResponse implements IDefaultResponse { public static final EmptyOrDummyResponse INSTANCE = new EmptyOrDummyResponse(); private EmptyOrDummyResponse() {} @Override @SuppressWarnings("rawtypes") public Object respond(IMockInvocation invocation) { IMockInteraction interaction = DefaultJavaLangObjectInteractions.INSTANCE.match(invocation); if (interaction != null) return interaction.accept(invocation); Class<?> returnType = invocation.getMethod().getReturnType(); if (returnType == void.class || returnType == Void.class) { return null; } if (returnType.isPrimitive()) { return ReflectionUtil.getDefaultValue(returnType); } if (returnType != Object.class && returnType.isAssignableFrom(invocation.getMockObject().getType())) { return invocation.getMockObject().getInstance(); } if (returnType.isInterface()) { if (returnType == Iterable.class) return new ArrayList(); if (returnType == Collection.class) return new ArrayList(); if (returnType == List.class) return new ArrayList(); if (returnType == Set.class) return new HashSet(); if (returnType == Map.class) return new HashMap(); if (returnType == Queue.class) return new LinkedList(); if (returnType == SortedSet.class) return new TreeSet(); if (returnType == SortedMap.class) return new TreeMap(); if (returnType == CharSequence.class) return ""; if (returnType == Stream.class) return Stream.empty(); if (returnType == IntStream.class) return IntStream.empty(); if (returnType == DoubleStream.class) return DoubleStream.empty(); if (returnType == LongStream.class) return LongStream.empty(); return createDummy(invocation); } if (returnType.isArray()) { return Array.newInstance(returnType.getComponentType(), 0); } if (returnType.isEnum()) { Object[] enumConstants = returnType.getEnumConstants(); return enumConstants.length > 0 ? enumConstants[0] : null; // null is only permissible value } if (CharSequence.class.isAssignableFrom(returnType)) { if (returnType == String.class) return ""; if (returnType == StringBuilder.class) return new StringBuilder(); if (returnType == StringBuffer.class) return new StringBuffer(); if (returnType == GString.class) return GString.EMPTY; // continue on } if (returnType == Optional.class) return Optional.empty(); if (returnType == CompletableFuture.class) return CompletableFuture.completedFuture(null); Object emptyWrapper = createEmptyWrapper(returnType); if (emptyWrapper != null) return emptyWrapper; Object emptyObject = createEmptyObject(returnType); if (emptyObject != null) return emptyObject; return createDummy(invocation); } // also handles some numeric types which aren't primitive wrapper types private Object createEmptyWrapper(Class<?> type) { if (Number.class.isAssignableFrom(type)) { Method method = ReflectionUtil.getDeclaredMethodBySignature(type, "valueOf", String.class); if (method != null && method.getReturnType() == type) { return ReflectionUtil.invokeMethod(type, method, "0"); } if (type == BigInteger.class) return BigInteger.ZERO; if (type == BigDecimal.class) return BigDecimal.ZERO; return null; } if (type == Boolean.class) return false; if (type == Character.class) return (char) 0; // better return something else? return null; } private Object createEmptyObject(Class<?> type) { try { return type.newInstance(); } catch (Exception e) { return null; } } private Object createDummy(IMockInvocation invocation) { Class<?> type = invocation.getMethod().getReturnType(); Type genericType = invocation.getMethod().getExactReturnType(); Specification spec = invocation.getMockObject().getSpecification(); return spec.createMock("dummy", genericType, MockNature.STUB, GroovyObject.class.isAssignableFrom(type) ? MockImplementation.GROOVY : MockImplementation.JAVA, Collections.<String, Object>emptyMap(), null); } }
3e1525355cefdd496e2e3b4b58b8d6ee1aa507c4
1,405
java
Java
clapi/src/main/java/com/clapi/protocol/UpdateAssetRequestOrBuilder.java
ericpinet/connectlife
261720426dfbf5e667cd29d727bc7c8f6a21e315
[ "MIT" ]
3
2016-01-10T06:19:25.000Z
2021-06-19T06:28:34.000Z
clapi/src/main/java/com/clapi/protocol/UpdateAssetRequestOrBuilder.java
ericpinet/ConnectLife
261720426dfbf5e667cd29d727bc7c8f6a21e315
[ "MIT" ]
58
2016-01-09T19:05:42.000Z
2016-10-16T18:04:18.000Z
clapi/src/main/java/com/clapi/protocol/UpdateAssetRequestOrBuilder.java
ericpinet/ConnectLife
261720426dfbf5e667cd29d727bc7c8f6a21e315
[ "MIT" ]
null
null
null
21.615385
75
0.619217
8,983
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: clapi.proto package com.clapi.protocol; public interface UpdateAssetRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:clapi.UpdateAssetRequest) com.google.protobuf.MessageOrBuilder { /** * <code>required string uid = 1;</code> */ boolean hasUid(); /** * <code>required string uid = 1;</code> */ java.lang.String getUid(); /** * <code>required string uid = 1;</code> */ com.google.protobuf.ByteString getUidBytes(); /** * <code>required string label = 2;</code> */ boolean hasLabel(); /** * <code>required string label = 2;</code> */ java.lang.String getLabel(); /** * <code>required string label = 2;</code> */ com.google.protobuf.ByteString getLabelBytes(); /** * <code>required .clapi.AssetType type = 3;</code> */ boolean hasType(); /** * <code>required .clapi.AssetType type = 3;</code> */ com.clapi.protocol.AssetType getType(); /** * <code>required .clapi.AssetMode mode = 4;</code> */ boolean hasMode(); /** * <code>required .clapi.AssetMode mode = 4;</code> */ com.clapi.protocol.AssetMode getMode(); /** * <code>required bytes data = 5;</code> */ boolean hasData(); /** * <code>required bytes data = 5;</code> */ com.google.protobuf.ByteString getData(); }
3e15257f39ca109124383846494a4e16e4395405
3,615
java
Java
orderservice/src/main/java/com/odenktools/orderservice/controllers/CartController.java
Riyanp/spring-camel
a17177b94b7ff79e211c2a364a2581a7c458b87c
[ "MIT" ]
null
null
null
orderservice/src/main/java/com/odenktools/orderservice/controllers/CartController.java
Riyanp/spring-camel
a17177b94b7ff79e211c2a364a2581a7c458b87c
[ "MIT" ]
null
null
null
orderservice/src/main/java/com/odenktools/orderservice/controllers/CartController.java
Riyanp/spring-camel
a17177b94b7ff79e211c2a364a2581a7c458b87c
[ "MIT" ]
null
null
null
33.785047
107
0.767082
8,984
package com.odenktools.orderservice.controllers; import com.odenktools.common.dto.CreateCartItemCommand; import com.odenktools.common.dto.ProductDto; import com.odenktools.common.response.ApiResponse; import com.odenktools.common.response.DataObjectResponse; import com.odenktools.common.response.RestApiResponse; import com.odenktools.orderservice.repository.CartRepository; import com.odenktools.orderservice.service.CartService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import java.util.Objects; @RestController @RequestMapping("/api/v1") public class CartController { private static final Logger LOG = LoggerFactory.getLogger(CartController.class); private final CartService cartService; private final CartRepository cartRepository; private final RestTemplate restTemplate; @Autowired public CartController(CartService cartService, CartRepository cartRepository, RestTemplate restTemplate) { this.cartService = cartService; this.cartRepository = cartRepository; this.restTemplate = restTemplate; } @PostMapping( value = "/cart/add", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE ) public ResponseEntity createCartItem( @RequestHeader(value = "customerId") String customerId, @RequestBody @Valid CreateCartItemCommand createCartItemCommand, HttpServletRequest httpServletRequest) { DataObjectResponse<CreateCartItemCommand> content = new DataObjectResponse<>(); ResponseEntity<RestApiResponse<ProductDto>> productResponse = null; String messages = ""; try { productResponse = this.restTemplate.exchange( String.format("http://localhost:6010/api/v1/product?id=%s", createCartItemCommand.getProductId()), HttpMethod.GET, HttpEntity.EMPTY, new ParameterizedTypeReference<RestApiResponse<ProductDto>>() { }); LOG.info(productResponse.getBody().getApiVersion()); //String productId = Objects.requireNonNull(productResponse.getBody().getResults().getData().getId()); String productName = Objects.requireNonNull(productResponse .getBody() .getResults() .getData() .getProductName()); createCartItemCommand.setProductName(productName); messages = "Add to cart success."; content.setContent(null); content.setCode(HttpStatus.OK.value()); content.setMessage(messages); content.setData(this.cartService.createCartItem(createCartItemCommand, customerId)); return ResponseEntity.status(HttpStatus.OK).body(ApiResponse.builder() .status(HttpStatus.OK) .code(HttpStatus.OK.value()) .message(messages) .params(null) .method(httpServletRequest.getMethod()) .path(httpServletRequest.getRequestURI()) .results(content) .build()); } catch (HttpClientErrorException e) { LOG.error("ERROR {}", e.getMessage()); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body( ApiResponse.builder() .status(HttpStatus.BAD_REQUEST) .code(HttpStatus.BAD_REQUEST.value()) .message("Product Not Found.") .params(null) .method(httpServletRequest.getMethod()) .path(httpServletRequest.getRequestURI()) .results(content) .build()); } } }
3e15259c8a9556e6d9cb27867c3bf7c468dfd199
2,477
java
Java
src/main/java/org/openstreetmap/atlas/geography/atlas/items/complex/water/ComplexWaterway.java
Huyuntj/atlas
bb1545ed2da7a1d51f133a4bb686c064c63892eb
[ "BSD-3-Clause" ]
188
2017-08-08T17:26:54.000Z
2022-03-29T07:59:30.000Z
src/main/java/org/openstreetmap/atlas/geography/atlas/items/complex/water/ComplexWaterway.java
Huyuntj/atlas
bb1545ed2da7a1d51f133a4bb686c064c63892eb
[ "BSD-3-Clause" ]
403
2017-08-09T16:15:25.000Z
2022-02-16T19:33:42.000Z
src/main/java/org/openstreetmap/atlas/geography/atlas/items/complex/water/ComplexWaterway.java
Huyuntj/atlas
bb1545ed2da7a1d51f133a4bb686c064c63892eb
[ "BSD-3-Clause" ]
79
2017-08-08T17:55:01.000Z
2021-11-10T20:51:57.000Z
30.580247
98
0.668147
8,985
package org.openstreetmap.atlas.geography.atlas.items.complex.water; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.openstreetmap.atlas.exception.CoreException; import org.openstreetmap.atlas.geography.PolyLine; import org.openstreetmap.atlas.geography.atlas.items.AtlasEntity; import org.openstreetmap.atlas.geography.atlas.items.Line; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A waterway (usually flowing ex : rivers, streams) typically has linear geometry. This contrasts * with waterbody which usually refers to an area of (standing) water and typically has polygonal * geometry * * @author Sid */ public class ComplexWaterway extends ComplexWaterEntity { private static final long serialVersionUID = -5567739097914423531L; private static final Logger logger = LoggerFactory.getLogger(ComplexWaterway.class); private PolyLine geometry; public ComplexWaterway(final AtlasEntity source, final WaterType type) { super(source, type); } @Override public boolean equals(final Object other) { if (other instanceof ComplexWaterbody) { final ComplexWaterbody that = (ComplexWaterbody) other; return new EqualsBuilder().append(this.getWaterType(), that.getWaterType()) .append(this.getSource(), that.getSource()) .append(this.getGeometry().toWkt(), that.getGeometry().toWkt()).build(); } return false; } public PolyLine getGeometry() { return this.geometry; } @Override public int hashCode() { return new HashCodeBuilder().append(this.getSource()).append(this.getWaterType()) .append(this.getGeometry().toWkb()).build(); } @Override protected Logger getLogger() { return logger; } @Override protected void populateGeometry() { final AtlasEntity source = getSource(); /* * We currently don't process waterway relations. So if it is a way and it is part of * relation where it is a side stream, main stream or tributary, we process them. */ if (source instanceof Line) { final Line line = (Line) source; this.geometry = line.asPolyLine(); return; } throw new CoreException("Geometry is not set for {}", source); } }
3e1526184ff93905f0d4a9c89f7c7f049bcbb8aa
2,489
java
Java
artemis-dto/src/main/java/org/apache/activemq/artemis/dto/WebServerDTO.java
ingo1121/activemq-artemis
30c4b0de89a2e30edd1b1798ae5297b8af4fdeab
[ "Apache-2.0" ]
null
null
null
artemis-dto/src/main/java/org/apache/activemq/artemis/dto/WebServerDTO.java
ingo1121/activemq-artemis
30c4b0de89a2e30edd1b1798ae5297b8af4fdeab
[ "Apache-2.0" ]
1
2018-01-09T20:00:38.000Z
2018-01-10T16:43:02.000Z
artemis-dto/src/main/java/org/apache/activemq/artemis/dto/WebServerDTO.java
ingo1121/activemq-artemis
30c4b0de89a2e30edd1b1798ae5297b8af4fdeab
[ "Apache-2.0" ]
null
null
null
29.987952
86
0.764966
8,986
/* * 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.activemq.artemis.dto; import org.apache.activemq.artemis.utils.PasswordMaskingUtil; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlRootElement; import java.util.List; @XmlRootElement(name = "web") @XmlAccessorType(XmlAccessType.FIELD) public class WebServerDTO extends ComponentDTO { @XmlAttribute public String bind; @XmlAttribute(required = true) public String path; @XmlAttribute public Boolean clientAuth; @XmlAttribute public String passwordCodec; @XmlAttribute public String keyStorePath; @XmlAttribute public String trustStorePath; @XmlElementRef public List<AppDTO> apps; @XmlAttribute private String keyStorePassword; @XmlAttribute private String trustStorePassword; public WebServerDTO() { componentClassName = "org.apache.activemq.artemis.component.WebServerComponent"; } public String getKeyStorePassword() throws Exception { return getPassword(this.keyStorePassword); } private String getPassword(String password) throws Exception { return PasswordMaskingUtil.resolveMask(null, password, this.passwordCodec); } public void setKeyStorePassword(String keyStorePassword) { this.keyStorePassword = keyStorePassword; } public String getTrustStorePassword() throws Exception { return getPassword(this.trustStorePassword); } public void setTrustStorePassword(String trustStorePassword) { this.trustStorePassword = trustStorePassword; } }
3e1526e4d34f4794e8e3e387b71df9a222aa4131
12,996
java
Java
mod_xalan/src/main/java/org/apache/xalan/extensions/ExtensionHandlerGeneral.java
zhanyanjie6796/JFugue-for-Android
61b1cc52fe97e70af3e868b8a8d5398deff094c0
[ "Apache-2.0" ]
67
2015-01-03T22:34:54.000Z
2021-07-07T12:11:40.000Z
mod_xalan/src/main/java/org/apache/xalan/extensions/ExtensionHandlerGeneral.java
zhanyanjie6796/JFugue-for-Android
61b1cc52fe97e70af3e868b8a8d5398deff094c0
[ "Apache-2.0" ]
10
2015-01-01T20:38:17.000Z
2021-06-27T18:02:14.000Z
mod_xalan/src/main/java/org/apache/xalan/extensions/ExtensionHandlerGeneral.java
zhanyanjie6796/JFugue-for-Android
61b1cc52fe97e70af3e868b8a8d5398deff094c0
[ "Apache-2.0" ]
24
2015-04-01T16:21:11.000Z
2022-02-15T07:26:36.000Z
32.830808
200
0.63549
8,987
/* * Copyright 1999-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: ExtensionHandlerGeneral.java,v 1.26 2005/01/23 00:10:05 mcnamara Exp $ */ package org.apache.xalan.extensions; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.net.URL; import java.net.URLConnection; import java.util.Hashtable; import java.util.Vector; import javax.xml.transform.TransformerException; import org.apache.xml.res.XMLErrorResources; import org.apache.xml.res.XMLMessages; import org.apache.xalan.res.XSLMessages; import org.apache.xalan.res.XSLTErrorResources; import org.apache.xalan.templates.ElemTemplateElement; import org.apache.xalan.templates.Stylesheet; import org.apache.xalan.transformer.TransformerImpl; import org.apache.xml.dtm.DTMIterator; import org.apache.xml.dtm.ref.DTMNodeList; import org.apache.xml.utils.StringVector; import org.apache.xml.utils.SystemIDResolver; import org.apache.xpath.XPathProcessorException; import org.apache.xpath.functions.FuncExtFunction; import org.apache.xpath.objects.XObject; /** * Class handling an extension namespace for XPath. Provides functions * to test a function's existence and call a function * * @author Sanjiva Weerawarana (kenaa@example.com) * @xsl.usage internal */ public class ExtensionHandlerGeneral extends ExtensionHandler { /** script source to run (if any) */ private String m_scriptSrc; /** URL of source of script (if any) */ private String m_scriptSrcURL; /** functions of namespace */ private Hashtable m_functions = new Hashtable(); /** elements of namespace */ private Hashtable m_elements = new Hashtable(); // BSF objects used to invoke BSF by reflection. Do not import the BSF classes // since we don't want a compile dependency on BSF. /** BSF manager used to run scripts */ private Object m_engine; /** Engine call to invoke scripts */ private Method m_engineCall = null; // static fields /** BSFManager package name */ private static String BSF_MANAGER ; /** Default BSFManager name */ private static final String DEFAULT_BSF_MANAGER = "org.apache.bsf.BSFManager"; /** Property name to load the BSFManager class */ private static final String propName = "org.apache.xalan.extensions.bsf.BSFManager"; /** Integer Zero */ private static final Integer ZEROINT = new Integer(0); static{ BSF_MANAGER = ObjectFactory.lookUpFactoryClassName(propName, null, null); if (BSF_MANAGER == null){ BSF_MANAGER = DEFAULT_BSF_MANAGER; } } /** * Construct a new extension namespace handler given all the information * needed. * * @param namespaceUri the extension namespace URI that I'm implementing * @param elemNames Vector of element names * @param funcNames string containing list of functions of extension NS * @param scriptLang Scripting language of implementation * @param scriptSrcURL URL of source script * @param scriptSrc the actual script code (if any) * @param systemId * * @throws javax.xml.transform.TransformerException */ public ExtensionHandlerGeneral( String namespaceUri, StringVector elemNames, StringVector funcNames, String scriptLang, String scriptSrcURL, String scriptSrc, String systemId) throws TransformerException { super(namespaceUri, scriptLang); if (elemNames != null) { Object junk = new Object(); int n = elemNames.size(); for (int i = 0; i < n; i++) { String tok = elemNames.elementAt(i); m_elements.put(tok, junk); // just stick it in there basically } } if (funcNames != null) { Object junk = new Object(); int n = funcNames.size(); for (int i = 0; i < n; i++) { String tok = funcNames.elementAt(i); m_functions.put(tok, junk); // just stick it in there basically } } m_scriptSrcURL = scriptSrcURL; m_scriptSrc = scriptSrc; if (m_scriptSrcURL != null) { URL url = null; try{ url = new URL(m_scriptSrcURL); } catch (java.net.MalformedURLException mue) { int indexOfColon = m_scriptSrcURL.indexOf(':'); int indexOfSlash = m_scriptSrcURL.indexOf('/'); if ((indexOfColon != -1) && (indexOfSlash != -1) && (indexOfColon < indexOfSlash)) { // The url is absolute. url = null; throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_COULD_NOT_FIND_EXTERN_SCRIPT, new Object[]{m_scriptSrcURL}), mue); //"src attribute not yet supported for " //+ scriptLang); } else { try{ url = new URL(new URL(SystemIDResolver.getAbsoluteURI(systemId)), m_scriptSrcURL); } catch (java.net.MalformedURLException mue2) { throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_COULD_NOT_FIND_EXTERN_SCRIPT, new Object[]{m_scriptSrcURL}), mue2); //"src attribute not yet supported for " //+ scriptLang); } } } if (url != null) { try { URLConnection uc = url.openConnection(); InputStream is = uc.getInputStream(); byte []bArray = new byte[uc.getContentLength()]; is.read(bArray); m_scriptSrc = new String(bArray); } catch (IOException ioe) { throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_COULD_NOT_FIND_EXTERN_SCRIPT, new Object[]{m_scriptSrcURL}), ioe); //"src attribute not yet supported for " //+ scriptLang); } } } Object manager = null; try { manager = ObjectFactory.newInstance( BSF_MANAGER, ObjectFactory.findClassLoader(), true); } catch (ObjectFactory.ConfigurationError e) { e.printStackTrace(); } if (manager == null) { throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_CANNOT_INIT_BSFMGR, null)); //"Could not initialize BSF manager"); } try { Method loadScriptingEngine = manager.getClass() .getMethod("loadScriptingEngine", new Class[]{ String.class }); m_engine = loadScriptingEngine.invoke(manager, new Object[]{ scriptLang }); Method engineExec = m_engine.getClass().getMethod("exec", new Class[]{ String.class, Integer.TYPE, Integer.TYPE, Object.class }); // "Compile" the program engineExec.invoke(m_engine, new Object[]{ "XalanScript", ZEROINT, ZEROINT, m_scriptSrc }); } catch (Exception e) { e.printStackTrace(); throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_CANNOT_CMPL_EXTENSN, null), e); //"Could not compile extension", e); } } /** * Tests whether a certain function name is known within this namespace. * @param function name of the function being tested * @return true if its known, false if not. */ public boolean isFunctionAvailable(String function) { return (m_functions.get(function) != null); } /** * Tests whether a certain element name is known within this namespace. * @param element name of the element being tested * @return true if its known, false if not. */ public boolean isElementAvailable(String element) { return (m_elements.get(element) != null); } /** * Process a call to a function. * * @param funcName Function name. * @param args The arguments of the function call. * @param methodKey A key that uniquely identifies this class and method call. * @param exprContext The context in which this expression is being executed. * * @return the return value of the function evaluation. * * @throws javax.xml.transform.TransformerException if parsing trouble */ public Object callFunction( String funcName, Vector args, Object methodKey, ExpressionContext exprContext) throws TransformerException { Object[] argArray; try { argArray = new Object[args.size()]; for (int i = 0; i < argArray.length; i++) { Object o = args.elementAt(i); argArray[i] = (o instanceof XObject) ? ((XObject) o).object() : o; o = argArray[i]; if(null != o && o instanceof DTMIterator) { argArray[i] = new DTMNodeList((DTMIterator)o); } } if (m_engineCall == null) { m_engineCall = m_engine.getClass().getMethod("call", new Class[]{ Object.class, String.class, Object[].class }); } return m_engineCall.invoke(m_engine, new Object[]{ null, funcName, argArray }); } catch (Exception e) { e.printStackTrace(); String msg = e.getMessage(); if (null != msg) { if (msg.startsWith("Stopping after fatal error:")) { msg = msg.substring("Stopping after fatal error:".length()); } // System.out.println("Call to extension function failed: "+msg); throw new TransformerException(e); } else { // Should probably make a TRaX Extension Exception. throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_CANNOT_CREATE_EXTENSN, new Object[]{funcName, e })); //"Could not create extension: " + funcName //+ " because of: " + e); } } } /** * Process a call to an XPath extension function * * @param extFunction The XPath extension function * @param args The arguments of the function call. * @param exprContext The context in which this expression is being executed. * @return the return value of the function evaluation. * @throws javax.xml.transform.TransformerException */ public Object callFunction(FuncExtFunction extFunction, Vector args, ExpressionContext exprContext) throws TransformerException { return callFunction(extFunction.getFunctionName(), args, extFunction.getMethodKey(), exprContext); } /** * Process a call to this extension namespace via an element. As a side * effect, the results are sent to the TransformerImpl's result tree. * * @param localPart Element name's local part. * @param element The extension element being processed. * @param transformer Handle to TransformerImpl. * @param stylesheetTree The compiled stylesheet tree. * @param methodKey A key that uniquely identifies this class and method call. * * @throws XSLProcessorException thrown if something goes wrong * while running the extension handler. * @throws MalformedURLException if loading trouble * @throws FileNotFoundException if loading trouble * @throws java.io.IOException if loading trouble * @throws javax.xml.transform.TransformerException if parsing trouble */ public void processElement( String localPart, ElemTemplateElement element, TransformerImpl transformer, Stylesheet stylesheetTree, Object methodKey) throws TransformerException, IOException { Object result = null; XSLProcessorContext xpc = new XSLProcessorContext(transformer, stylesheetTree); try { Vector argv = new Vector(2); argv.addElement(xpc); argv.addElement(element); result = callFunction(localPart, argv, methodKey, transformer.getXPathContext().getExpressionContext()); } catch (XPathProcessorException e) { // e.printStackTrace (); throw new TransformerException(e.getMessage(), e); } if (result != null) { xpc.outputToResultTree(stylesheetTree, result); } } }
3e1526e6103e0343ab67d9ba8716239bee8525c0
1,787
java
Java
src/main/java/com/mk/portal/framework/page/html/tags/DocTypeDeclaration.java
Busy-Brain/Portal
8ea6ba6f074ede544f8df9129b9dd86838facaed
[ "Apache-2.0" ]
null
null
null
src/main/java/com/mk/portal/framework/page/html/tags/DocTypeDeclaration.java
Busy-Brain/Portal
8ea6ba6f074ede544f8df9129b9dd86838facaed
[ "Apache-2.0" ]
null
null
null
src/main/java/com/mk/portal/framework/page/html/tags/DocTypeDeclaration.java
Busy-Brain/Portal
8ea6ba6f074ede544f8df9129b9dd86838facaed
[ "Apache-2.0" ]
null
null
null
22.910256
78
0.720761
8,988
package com.mk.portal.framework.page.html.tags; import java.util.ArrayList; import java.util.List; import com.mk.portal.framework.html.objects.Attribute; import com.mk.portal.framework.html.objects.HTMLVersion; import com.mk.portal.framework.html.objects.Tag; /** * The <!DOCTYPE> declaration must be the very first thing in your HTML * document, before the <html> tag. * * The <!DOCTYPE> declaration is not an HTML tag; it is an instruction to the * web browser about what version of HTML the page is written in. * * In HTML 4.01, the <!DOCTYPE> declaration refers to a DTD, because HTML 4.01 * was based on SGML. The DTD specifies the rules for the markup language, so * that the browsers render the content correctly. * * HTML5 is not based on SGML, and therefore does not require a reference to a * DTD. * * Tip: Always add the <!DOCTYPE> declaration to your HTML documents, so that * the browser knows what type of document to expect. * * @author mohit * */ public class DocTypeDeclaration extends Tag { private HTMLVersion htmlVersion = null; public DocTypeDeclaration(){ this.htmlVersion=HTMLVersion.HTML_5; } public DocTypeDeclaration(HTMLVersion phtmlVersion){ this.htmlVersion=phtmlVersion; } @Override public List<Attribute> getAttributes() { return new ArrayList<Attribute>(); } @Override public String getStartTag() { return htmlVersion.getDoctype(); } @Override public boolean hasEndTag() { return false; } @Override public String getEndTag() { return null; } @Override public String toString() { return "<!"+getStartTag()+">"; } @Override public String toFormattedString(int tabcount) { return "<!"+getStartTag()+">\n"; } @Override public String getTagName() { return "DOCTYPE"; } }
3e152700c8710cebb439fca7b6b36355fef2ac72
159
java
Java
HW04DLREP/src/model/factory/IShapeFactory.java
git-malu/OOP-Projects
8a44e4acf60111acdc946dc8bcd39478cfa20621
[ "MIT" ]
null
null
null
HW04DLREP/src/model/factory/IShapeFactory.java
git-malu/OOP-Projects
8a44e4acf60111acdc946dc8bcd39478cfa20621
[ "MIT" ]
null
null
null
HW04DLREP/src/model/factory/IShapeFactory.java
git-malu/OOP-Projects
8a44e4acf60111acdc946dc8bcd39478cfa20621
[ "MIT" ]
null
null
null
17.666667
74
0.773585
8,989
package model.factory; import java.awt.Shape; public interface IShapeFactory { public Shape makeShape(double x, double y, double xScale, double yScale); }
3e15290d6a9a2110beae0536797fb01d33cb39e0
901
java
Java
netty-demo-im/src/main/java/com/joe/im/server/hanlder/AuthHandler.java
JoeMendezCKH/netty-learn
fce57c8d92ca80331a6d361a537335ab797bbcdd
[ "Apache-2.0" ]
null
null
null
netty-demo-im/src/main/java/com/joe/im/server/hanlder/AuthHandler.java
JoeMendezCKH/netty-learn
fce57c8d92ca80331a6d361a537335ab797bbcdd
[ "Apache-2.0" ]
null
null
null
netty-demo-im/src/main/java/com/joe/im/server/hanlder/AuthHandler.java
JoeMendezCKH/netty-learn
fce57c8d92ca80331a6d361a537335ab797bbcdd
[ "Apache-2.0" ]
null
null
null
27.30303
85
0.63707
8,990
package com.joe.im.server.hanlder; import com.joe.im.utils.LoginUtil; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; /** * @author ckh * @create 10/27/20 5:06 PM */ public class AuthHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (!LoginUtil.hasLogin(ctx.channel())) { ctx.channel().close(); } else { // 第一次验证过后, 后面就不再重复验证 ctx.pipeline().remove(this); super.channelRead(ctx, msg); } } @Override public void handlerRemoved(ChannelHandlerContext ctx) { if (LoginUtil.hasLogin(ctx.channel())) { System.out.println("当前连接登录验证完毕,无需再次验证, AuthHandler 被移除"); } else { System.out.println("无登录验证,强制关闭连接!"); } } }
3e152aedf0d91812a598d0642f2660cbb5663e68
5,582
java
Java
ExtractedJars/PACT_com.pactforcure.app/javafiles/com/itextpdf/tool/xml/html/head/XML.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
3
2019-05-01T09:22:08.000Z
2019-07-06T22:21:59.000Z
ExtractedJars/PACT_com.pactforcure.app/javafiles/com/itextpdf/tool/xml/html/head/XML.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
null
null
null
ExtractedJars/PACT_com.pactforcure.app/javafiles/com/itextpdf/tool/xml/html/head/XML.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
1
2020-11-26T12:22:02.000Z
2020-11-26T12:22:02.000Z
43.609375
105
0.615729
8,991
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.itextpdf.tool.xml.html.head; import com.itextpdf.text.log.*; import com.itextpdf.tool.xml.*; import com.itextpdf.tool.xml.exceptions.LocaleMessages; import com.itextpdf.tool.xml.exceptions.RuntimeWorkerException; import com.itextpdf.tool.xml.html.AbstractTagProcessor; import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext; import java.nio.charset.Charset; import java.util.*; public class XML extends AbstractTagProcessor { public XML() { // 0 0:aload_0 // 1 1:invokespecial #20 <Method void AbstractTagProcessor()> // 2 4:return } public List start(WorkerContext workercontext, Tag tag) { tag = ((Tag) ((String)tag.getAttributes().get("encoding"))); // 0 0:aload_2 // 1 1:invokevirtual #30 <Method Map Tag.getAttributes()> // 2 4:ldc1 #32 <String "encoding"> // 3 6:invokeinterface #38 <Method Object Map.get(Object)> // 4 11:checkcast #40 <Class String> // 5 14:astore_2 if(tag == null) goto _L2; else goto _L1 // 6 15:aload_2 // 7 16:ifnull 80 _L1: if(!Charset.isSupported(((String) (tag)))) goto _L4; else goto _L3 // 8 19:aload_2 // 9 20:invokestatic #46 <Method boolean Charset.isSupported(String)> // 10 23:ifeq 89 _L3: getHtmlPipelineContext(workercontext).charSet(Charset.forName(((String) (tag)))); // 11 26:aload_0 // 12 27:aload_1 // 13 28:invokevirtual #50 <Method HtmlPipelineContext getHtmlPipelineContext(WorkerContext)> // 14 31:aload_2 // 15 32:invokestatic #54 <Method Charset Charset.forName(String)> // 16 35:invokevirtual #60 <Method HtmlPipelineContext HtmlPipelineContext.charSet(Charset)> // 17 38:pop if(LOGGER.isLogging(Level.DEBUG)) //* 18 39:getstatic #16 <Field Logger LOGGER> //* 19 42:getstatic #66 <Field Level Level.DEBUG> //* 20 45:invokeinterface #72 <Method boolean Logger.isLogging(Level)> //* 21 50:ifeq 80 LOGGER.debug(String.format(LocaleMessages.getInstance().getMessage("html.tag.meta.cc"), new Object[] { tag })); // 22 53:getstatic #16 <Field Logger LOGGER> // 23 56:invokestatic #78 <Method LocaleMessages LocaleMessages.getInstance()> // 24 59:ldc1 #80 <String "html.tag.meta.cc"> // 25 61:invokevirtual #84 <Method String LocaleMessages.getMessage(String)> // 26 64:iconst_1 // 27 65:anewarray Object[] // 28 68:dup // 29 69:iconst_0 // 30 70:aload_2 // 31 71:aastore // 32 72:invokestatic #90 <Method String String.format(String, Object[])> // 33 75:invokeinterface #94 <Method void Logger.debug(String)> _L2: return ((List) (new ArrayList(0))); // 34 80:new #96 <Class ArrayList> // 35 83:dup // 36 84:iconst_0 // 37 85:invokespecial #99 <Method void ArrayList(int)> // 38 88:areturn _L4: if(!LOGGER.isLogging(Level.DEBUG)) goto _L2; else goto _L5 // 39 89:getstatic #16 <Field Logger LOGGER> // 40 92:getstatic #66 <Field Level Level.DEBUG> // 41 95:invokeinterface #72 <Method boolean Logger.isLogging(Level)> // 42 100:ifeq 80 _L5: LOGGER.debug(String.format(LocaleMessages.getInstance().getMessage("html.tag.meta.404"), new Object[] { getHtmlPipelineContext(workercontext).charSet() })); // 43 103:getstatic #16 <Field Logger LOGGER> // 44 106:invokestatic #78 <Method LocaleMessages LocaleMessages.getInstance()> // 45 109:ldc1 #101 <String "html.tag.meta.404"> // 46 111:invokevirtual #84 <Method String LocaleMessages.getMessage(String)> // 47 114:iconst_1 // 48 115:anewarray Object[] // 49 118:dup // 50 119:iconst_0 // 51 120:aload_0 // 52 121:aload_1 // 53 122:invokevirtual #50 <Method HtmlPipelineContext getHtmlPipelineContext(WorkerContext)> // 54 125:invokevirtual #104 <Method Charset HtmlPipelineContext.charSet()> // 55 128:aastore // 56 129:invokestatic #90 <Method String String.format(String, Object[])> // 57 132:invokeinterface #94 <Method void Logger.debug(String)> goto _L2 //* 58 137:goto 80 workercontext; // 59 140:astore_1 throw new RuntimeWorkerException(LocaleMessages.getInstance().getMessage("customcontext.404")); // 60 141:new #106 <Class RuntimeWorkerException> // 61 144:dup // 62 145:invokestatic #78 <Method LocaleMessages LocaleMessages.getInstance()> // 63 148:ldc1 #108 <String "customcontext.404"> // 64 150:invokevirtual #84 <Method String LocaleMessages.getMessage(String)> // 65 153:invokespecial #110 <Method void RuntimeWorkerException(String)> // 66 156:athrow } private static final Logger LOGGER = LoggerFactory.getLogger(com/itextpdf/tool/xml/html/head/XML); static { // 0 0:ldc1 #2 <Class XML> // 1 2:invokestatic #14 <Method Logger LoggerFactory.getLogger(Class)> // 2 5:putstatic #16 <Field Logger LOGGER> //* 3 8:return } }
3e152b8ea25fdfa6a18402fc5e6ea481280ab559
915
java
Java
src/slides/slide01/lista01/Exercicio06.java
lordjack/poo_aula
5894dfaf32ee1337cad50744340c46e240750918
[ "MIT" ]
null
null
null
src/slides/slide01/lista01/Exercicio06.java
lordjack/poo_aula
5894dfaf32ee1337cad50744340c46e240750918
[ "MIT" ]
null
null
null
src/slides/slide01/lista01/Exercicio06.java
lordjack/poo_aula
5894dfaf32ee1337cad50744340c46e240750918
[ "MIT" ]
null
null
null
27.727273
97
0.644809
8,992
package slides.slide01.lista01; import java.util.Scanner; /* Q06 - Escreva um algoritmo que pergunte o nome a altura (em metros) e a massa (em Kg) do usuário. Em seguida, o programa deverá exibir uma mensagem dizendo o nome do usuário e a sua densidade corporal Densidade = massa / metros */ public class Exercicio06 { public static void main(String[] args) { String nome; double altura, massa, densidade; Scanner teclado = new Scanner(System.in); System.out.println("Informe um Nome"); nome = teclado.nextLine(); System.out.println("Informe uma altura"); altura = teclado.nextDouble(); System.out.println("Informe uma massa"); massa = teclado.nextDouble(); densidade = massa / altura; System.out.println("O nome é: " + nome); System.out.println("A densidade é: " + densidade + " parabéns!"); } }
3e152bdc72e9e302cd64352c4a2ad6057e1c8198
3,977
java
Java
simple/simple-http/src/main/java/org/simpleframework/http/core/Controller.java
djsuw88/simple-server
3d34ac3003cd6a6f892aecc682091133bab67b4a
[ "Apache-2.0" ]
177
2015-01-03T18:04:55.000Z
2021-08-08T17:53:58.000Z
simple/simple-http/src/main/java/org/simpleframework/http/core/Controller.java
djsuw88/simple-server
3d34ac3003cd6a6f892aecc682091133bab67b4a
[ "Apache-2.0" ]
371
2020-03-04T21:51:56.000Z
2022-03-31T20:59:11.000Z
simple/simple-http/src/main/java/org/simpleframework/http/core/Controller.java
djsuw88/simple-server
3d34ac3003cd6a6f892aecc682091133bab67b4a
[ "Apache-2.0" ]
54
2015-01-17T21:15:34.000Z
2021-09-16T15:24:04.000Z
39.39604
70
0.721287
8,993
/* * Controller.java February 2007 * * Copyright (C) 2007, Niall Gallagher <lyhxr@example.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package org.simpleframework.http.core; import java.io.IOException; import org.simpleframework.transport.Channel; /** * The <code>Controller</code> interface represents an object which * is used to process collection events. The sequence of events that * typically take place is for the collection to start, if not all * of the bytes can be consumed it selects, and finally when all of * the bytes within the entity have been consumed it is ready. * <p> * The start event is used to immediately consume bytes form the * underlying transport, it does not require a select to determine * if the socket is read ready which provides an initial performance * enhancement. Also when a response has been delivered the next * request from the pipeline is consumed immediately. * <p> * The select event is used to register the connected socket with a * Java NIO selector which can efficiently determine when there are * bytes ready to read from the socket. Finally, the ready event * is used when a full HTTP entity has been collected from the * underlying transport. On such an event the request and response * can be handled by a container. * * @author Niall Gallagher * * @see org.simpleframework.http.core.Collector */ interface Controller { /** * This is used to initiate the processing of the channel. Once * the channel is passed in to the initiator any bytes ready on * the HTTP pipeline will be processed and parsed in to a HTTP * request. When the request has been built a callback is made * to the <code>Container</code> to process the request. Also * when the request is completed the channel is passed back in * to the initiator so that the next request can be dealt with. * * @param channel the channel to process the request from */ void start(Channel channel) throws IOException; /** * The start event is used to immediately consume bytes form the * underlying transport, it does not require a select to check * if the socket is read ready which improves performance. Also, * when a response has been delivered the next request from the * pipeline is consumed immediately. * * @param collector this is the collector used to collect data */ void start(Collector collector) throws IOException; /** * The select event is used to register the connected socket with * a Java NIO selector which can efficiently determine when there * are bytes ready to read from the socket. * * @param collector this is the collector used to collect data */ void select(Collector collector) throws IOException; /** * The ready event is used when a full HTTP entity has been * collected from the underlying transport. On such an event the * request and response can be handled by a container. * * @param collector this is the collector used to collect data */ void ready(Collector collector) throws IOException; /** * This method is used to stop the <code>Selector</code> so that * all resources are released. As well as freeing occupied memory * this will also stop all threads, which means that is can no * longer be used to collect data from the pipelines. */ void stop() throws IOException; }
3e152c05b70e1d62398a898ebb4e347f21b34c84
14,065
java
Java
servlet-src/src/pupil/command/cmd_cloneproject.java
MIUNPsychology/PUPIL
b1f39e19869149198a670b269617d9cd6e2381a9
[ "Apache-2.0" ]
null
null
null
servlet-src/src/pupil/command/cmd_cloneproject.java
MIUNPsychology/PUPIL
b1f39e19869149198a670b269617d9cd6e2381a9
[ "Apache-2.0" ]
null
null
null
servlet-src/src/pupil/command/cmd_cloneproject.java
MIUNPsychology/PUPIL
b1f39e19869149198a670b269617d9cd6e2381a9
[ "Apache-2.0" ]
null
null
null
28.299799
225
0.59225
8,994
package pupil.command; import pupil.*; import pupil.sql.*; import pupil.core.*; import pupil.util.*; import java.io.*; import java.sql.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.*; import org.xml.sax.*; import org.apache.commons.io.*; import org.apache.commons.lang.*; public class cmd_cloneproject extends Command { //private static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(cmd_cloneproject.class); private static LogWrapper log = new LogWrapper(); public cmd_cloneproject(DBManager dbm, StaticInfoBlob info) { super(dbm,info); } public void process(RequestInfoBlob rib,XMLInfoBlob xib,XMLCommand cmd) throws IOException, ServletException, SAXException, ParserConfigurationException, TransformerConfigurationException, TransformerException, DOMException { log.trace("Enter cmd_cloneproject()"); Pupil pupil = (Pupil)rib.servlet(); String name = cmd.getParameter("name"); String description = cmd.getParameter("description"); String oldname = cmd.getParameter("oldname"); log.debug("name is: " + name); log.debug("description is: " + description); log.debug("oldname is: " + oldname); PreparedStatement ps; ResultSet r; HashMap<String,String> originalProject; String sql; /* project_id teacher_id name description displaywelcome displaythanks welcometop welcomemid welcomebottom thankstop thanksmid thanksbottom urlredirect maxwidth maxheight flashright flashwrong flashwhite whitemin whitemax hideopts displaypolicy splicearray subsetsize pauseimage_id wrongimage_id rightimage_id */ try { sql = "select * FROM project where name = ?"; ps = db.getPreparedStatement(sql); ps.setString(1,oldname); originalProject = db.getResultAsHash(ps,true); } catch(SQLException e) { log.error(e.getMessage(),e); xib.setErrorResponse("SQLException: " + e.getMessage()); return; } try { sql = "INSERT INTO project("; sql = sql + "teacher_id,"; sql = sql + "name,"; sql = sql + "description,"; sql = sql + "displaywelcome,"; sql = sql + "displaythanks,"; sql = sql + "welcometop,"; sql = sql + "welcomemid,"; sql = sql + "welcomebottom,"; sql = sql + "thankstop,"; sql = sql + "thanksmid,"; sql = sql + "thanksbottom,"; sql = sql + "urlredirect,"; sql = sql + "maxwidth,"; sql = sql + "maxheight,"; sql = sql + "flashright,"; sql = sql + "flashwrong,"; sql = sql + "flashwhite,"; sql = sql + "whitemin,"; sql = sql + "whitemax,"; sql = sql + "hideopts,"; sql = sql + "displaypolicy,"; sql = sql + "splicearray,"; sql = sql + "subsetsize"; sql = sql + ") VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);"; log.debug(sql); ps = db.getPreparedStatement(sql); ps.setString(1,originalProject.get("teacher_id")); ps.setString(2,name); ps.setString(3,description); ps.setString(4,originalProject.get("displaywelcome")); ps.setString(5,originalProject.get("displaythanks")); ps.setString(6,originalProject.get("welcometop")); ps.setString(7,originalProject.get("welcomemid")); ps.setString(8,originalProject.get("welcomebottom")); ps.setString(9,originalProject.get("thankstop")); ps.setString(10,originalProject.get("thanksmid")); ps.setString(11,originalProject.get("thanksbottom")); ps.setString(12,originalProject.get("urlredirect")); ps.setString(13,originalProject.get("maxwidth")); ps.setString(14,originalProject.get("maxheight")); ps.setString(15,originalProject.get("flashright")); ps.setString(16,originalProject.get("flashwrong")); ps.setString(17,originalProject.get("flashwhite")); ps.setString(18,originalProject.get("whitemin")); ps.setString(19,originalProject.get("whitemax")); ps.setString(20,originalProject.get("hideopts")); ps.setString(21,originalProject.get("displaypolicy")); ps.setString(22,originalProject.get("splicearray")); ps.setString(23,originalProject.get("subsetsize")); db.executeAsUpdate(ps,true); } catch(SQLException e) { log.error(e.getMessage(),e); xib.setErrorResponse("SQLException: " + e.getMessage()); } log.trace("Leave cmd_cloneproject()"); String newProjectID, oldProjectID; try { sql = "select max(project_id) as prid FROM project where name = ? and description = ?"; ps = db.getPreparedStatement(sql); ps.setString(1,name); ps.setString(2,description); newProjectID = db.getSingleString(ps,"prid",true); oldProjectID = originalProject.get("project_id"); } catch(SQLException e) { log.error(e.getMessage(),e); xib.setErrorResponse("SQLException: " + e.getMessage()); return; } log.debug("old project id: " + oldProjectID); log.debug("new project id: " + newProjectID); HashMap<String,String> categoryReplacement = new HashMap<String,String>(); try { sql = "select * from category where project_id = ?"; ps = db.getPreparedStatement(sql); ps.setString(1,oldProjectID); Vector<HashMap<String,String>> categoryHash = db.getResultAsHashVector(ps,true); String category_id, project_id, catname, newcatid; for(HashMap<String,String> row : categoryHash) { category_id = row.get("category_id"); project_id = row.get("project_id"); catname = row.get("name"); log.debug("category_id: " + category_id); log.debug("project_id: " + project_id); log.debug("name: " + catname); String newCatName = StringUtils.remove(catname,oldname + "_"); newCatName = name + "_" + newCatName; log.debug("newname: " + newCatName); sql = "INSERT INTO category (project_id,name) VALUES(?,?);"; ps = db.getPreparedStatement(sql); ps.setString(1,newProjectID); ps.setString(2,newCatName); db.executeAsUpdate(ps,true); sql = "SELECT max(category_id) as catid FROM category WHERE project_id = ? and name = ?"; ps = db.getPreparedStatement(sql); ps.setString(1,newProjectID); ps.setString(2,newCatName); newcatid = db.getSingleString(ps,"catid",true); categoryReplacement.put(category_id,newcatid); log.debug("Category " + category_id + " is replaced by " + newcatid + " (" + catname + ")"); pupil.copyCategory(catname,newCatName); } log.debug("There were " + categoryHash.size() + " categories in the old project"); } catch(SQLException e) { log.error(e.getMessage(),e); xib.setErrorResponse("SQLException: " + e.getMessage()); return; } catch(IOException e) { log.error(e.getMessage(),e); xib.setErrorResponse("IOException: " + e.getMessage()); return; } HashMap<String,String> imageReplacements = new HashMap<String,String>(); try { sql = "select image.image_id as image_id, image.file_name as file_name, category.category_id as category_id "; sql = sql + "from image, category WHERE image.category_id = category.category_id and category.project_id = ?"; ps = db.getPreparedStatement(sql); ps.setString(1,oldProjectID); Vector<HashMap<String,String>> imageTable = db.getResultAsHashVector(ps,true); String oldImgID, newImgID, oldCatID, filename, newCatID; for(HashMap<String,String> row : imageTable) { oldImgID = row.get("image_id"); oldCatID = row.get("category_id"); filename = row.get("file_name"); newCatID = categoryReplacement.get(oldCatID); log.debug("oldImgID:" + oldImgID); log.debug("oldCatID:" + oldCatID); log.debug("filename:" + filename); log.debug("newCatID:" + newCatID); sql = "INSERT INTO image(category_id,file_name) VALUES(?,?)"; ps = db.getPreparedStatement(sql); ps.setString(1,newCatID); ps.setString(2,filename); db.executeAsUpdate(ps,true); sql = "SELECT max(image_id) as imgid from image where category_id = ? AND file_name = ?"; ps = db.getPreparedStatement(sql); ps.setString(1,newCatID); ps.setString(2,filename); newImgID = db.getSingleString(ps,"imgid",true); log.debug("newImgID:" + newImgID); imageReplacements.put(oldImgID,newImgID); log.debug("Image " + oldImgID + " is replaced by " + newImgID + " (" + filename + ")"); } } catch(SQLException e) { log.error(e.getMessage(),e); xib.setErrorResponse("SQLException: " + e.getMessage()); return; } // scene_id | scenetype_id | pattern_id | project_id | timeout | description | lead | correctkey HashMap<String,String> sceneReplacements = new HashMap<String,String>(); try { sql = "select * from scene WHERE project_id = ?"; ps = db.getPreparedStatement(sql); ps.setString(1,oldProjectID); Vector<HashMap<String,String>> sceneTable = db.getResultAsHashVector(ps,true); String scene_id; String scenetype_id; String pattern_id; String timeout; String scenedesc; String lead; String correctkey; String newSceneID; for(HashMap<String,String> row : sceneTable) { scene_id = row.get("scene_id"); scenetype_id = row.get("scenetype_id"); pattern_id = row.get("pattern_id"); timeout = row.get("timeout"); scenedesc = row.get("description"); lead = row.get("lead"); correctkey = row.get("correctkey"); sql = "INSERT INTO scene (scenetype_id,pattern_id,project_id,timeout,description,lead,correctkey) "; sql = sql + "VALUES(?,?,?,?,?,?,?);"; ps = db.getPreparedStatement(sql); ps.setString(1,scenetype_id); ps.setString(2,pattern_id); ps.setString(3,newProjectID); ps.setString(4,timeout); ps.setString(5,scenedesc); ps.setString(6,lead); ps.setString(7,correctkey); db.executeAsUpdate(ps,true); sql = "SELECT max(scene_id) as scid from scene where project_id = ? and description = ?"; ps = db.getPreparedStatement(sql); ps.setString(1,newProjectID); ps.setString(2,scenedesc); newSceneID = db.getSingleString(ps,"scid",true); log.debug("Scene " + scene_id + " is replaced by " + newSceneID + " (" + scenedesc + ")"); sceneReplacements.put(scene_id,newSceneID); } } catch(SQLException e) { log.error(e.getMessage(),e); xib.setErrorResponse("SQLException: " + e.getMessage()); return; } String originalsceneid, clonesceneid; for(String key : sceneReplacements.keySet()) { originalsceneid = key; clonesceneid = sceneReplacements.get(key); log.debug("clone scene_id is: " + clonesceneid); log.debug("orig. scene_id is: " + originalsceneid); String[] tables = new String[] { "ssi", "sri", "scri", "scriscene", "sosiimg", "sosiopt", "soricat", "soriopt" }; String colname; ResultSetMetaData meta; Vector<String> columns; PreparedStatement updateps; for (String table : tables) { try { log.debug("Table: " + table); sql = "SELECT * FROM " + table + " WHERE scene_id = ?"; ps = db.getPreparedStatement(sql); ps.setString(1,originalsceneid); r = ps.executeQuery(); r.beforeFirst(); meta = ps.getMetaData(); columns = new Vector<String>(); int colNum = meta.getColumnCount(); for(int i = 2; i <= colNum; i++) { colname = meta.getColumnLabel(i); if(!colname.equals("scene_id")) { columns.add(colname); log.debug("Column: " + colname); } } log.debug("number of columns: " + columns.size()); sql = "INSERT INTO " + table + "(scene_id"; for (String col : columns) { sql = sql + "," + col; } sql = sql + ") VALUES(?"; for (String col : columns) { sql = sql + ",?"; } sql = sql + ")"; log.debug(sql); updateps = db.getPreparedStatement(sql); String orig; while(r.next()) { int colno = 2; updateps.setString(1, clonesceneid); log.debug("number of columns: " + columns.size()); for (String col : columns) { log.debug(colno + " (" + col + ")"); if(col.equals("category_id") || col.equals("image_id")) { orig = r.getString(col); if(col.equals("category_id")) { updateps.setString(colno++, categoryReplacement.get(orig)); } if(col.equals("image_id")) { updateps.setString(colno++, imageReplacements.get(orig)); } } else { updateps.setString(colno++, r.getString(col)); } } updateps.executeUpdate(); } updateps.close(); r.close(); ps.close(); } catch(SQLException e) { log.error(e.getMessage(),e); xib.setErrorResponse("SQLException: " + e.getMessage()); return; } } } } }
3e152c28a1e8a981765a9aa772a7168d927b8c5f
67,644
java
Java
marklogic-client-api-functionaltests/src/test/java/com/marklogic/client/functionaltest/TestSemanticsGraphManager.java
andreas-felix/java-client-api
c6544ce9220ea12c534ac09df9795d64cadae529
[ "Apache-2.0" ]
46
2015-05-06T19:30:30.000Z
2021-09-30T20:50:35.000Z
marklogic-client-api-functionaltests/src/test/java/com/marklogic/client/functionaltest/TestSemanticsGraphManager.java
andreas-felix/java-client-api
c6544ce9220ea12c534ac09df9795d64cadae529
[ "Apache-2.0" ]
1,075
2015-01-02T05:33:02.000Z
2022-03-15T15:48:17.000Z
marklogic-client-api-functionaltests/src/test/java/com/marklogic/client/functionaltest/TestSemanticsGraphManager.java
andreas-felix/java-client-api
c6544ce9220ea12c534ac09df9795d64cadae529
[ "Apache-2.0" ]
77
2015-05-07T17:37:52.000Z
2022-03-14T07:10:32.000Z
42.48995
179
0.69613
8,995
/* * Copyright (c) 2019 MarkLogic Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.marklogic.client.functionaltest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.InputStream; import java.io.Reader; import java.util.Iterator; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.marklogic.client.DatabaseClient; import com.marklogic.client.ResourceNotFoundException; import com.marklogic.client.Transaction; import com.marklogic.client.io.BytesHandle; import com.marklogic.client.io.FileHandle; import com.marklogic.client.io.InputStreamHandle; import com.marklogic.client.io.JacksonHandle; import com.marklogic.client.io.ReaderHandle; import com.marklogic.client.io.StringHandle; import com.marklogic.client.io.marker.TriplesReadHandle; import com.marklogic.client.semantics.Capability; import com.marklogic.client.semantics.GraphManager; import com.marklogic.client.semantics.GraphPermissions; import com.marklogic.client.semantics.RDFMimeTypes; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestSemanticsGraphManager extends BasicJavaClientREST { // private static final String DEFAULT_GRAPH = // "http://replace.defaultGraphValue.here/"; private static GraphManager gmWriter; private static GraphManager gmReader; private static String dbName = "SemanticsDB-JavaAPI"; private static String[] fNames = { "SemanticsDB-JavaAPI-1" }; private static String appServerHostname = null; private DatabaseClient adminClient = null; private DatabaseClient writerClient = null; private DatabaseClient readerClient = null; private static String datasource = "src/test/java/com/marklogic/client/functionaltest/data/semantics/"; @BeforeClass public static void setUpBeforeClass() throws Exception { System.out.println("In setup"); configureRESTServer(dbName, fNames); setupAppServicesConstraint(dbName); enableCollectionLexicon(dbName); enableTripleIndex(dbName); appServerHostname = getRestAppServerHostName(); } @AfterClass public static void tearDownAfterClass() throws Exception { System.out.println("In tear down"); // Delete database first. Otherwise axis and collection cannot be // deleted cleanupRESTServer(dbName, fNames); deleteRESTUser("eval-user"); deleteUserRole("test-eval"); deleteUserRole("test-perm2"); } @After public void testCleanUp() throws Exception { clearDB(); adminClient.release(); writerClient.release(); readerClient.release(); System.out.println("Running clear script"); } @Before public void setUp() throws Exception { createUserRolesWithPrevilages("test-eval", "xdbc:eval", "xdbc:eval-in", "xdmp:eval-in", "any-uri", "xdbc:invoke"); createRESTUser("eval-user", "x", "test-eval", "rest-admin", "rest-writer", "rest-reader"); int restPort = getRestServerPort(); adminClient = getDatabaseClientOnDatabase(appServerHostname, restPort, dbName, "rest-admin", "x", getConnType()); writerClient = getDatabaseClientOnDatabase(appServerHostname, restPort, dbName, "rest-writer", "x", getConnType()); readerClient = getDatabaseClientOnDatabase(appServerHostname, restPort, dbName, "rest-reader", "x", getConnType()); gmWriter = writerClient.newGraphManager(); gmReader = readerClient.newGraphManager(); } /* * Write Triples using Write user & StringHandle with mime-Type = n-triples * Get the list of Graphs from the DB with Read User Iterate through the list * of graphs to validate the Graph Delete Graph using URI Validate the graph * doesn't exist in DB */ @Test public void testListUris_readUser() throws Exception { Exception exp = null; String ntriple5 = "<http://example.org/s5> <http://example.com/p2> <http://example.org/o2> ."; gmWriter.write("htp://test.sem.graph/G1", new StringHandle(ntriple5).withMimetype("application/n-triples")); Iterator<String> iter = gmReader.listGraphUris(); while (iter.hasNext()) { String uri = iter.next(); assertNotNull(uri); assertNotEquals("", uri); System.out.println("DEBUG: [GraphsTest] uri =[" + uri + "]"); } try { gmWriter.delete("htp://test.sem.graph/G1"); gmWriter.read("htp://test.sem.graph/G1", new StringHandle()); } catch (Exception e) { exp = e; } assertTrue("Read after detele did not throw expected Exception, Received ::" + exp, exp.toString().contains("Could not read resource at graphs.")); // Delete non existing graph try { gmWriter.delete("htp://test.sem.graph/G1"); } catch (Exception e) { exp = e; } assertTrue( "Deleting non-existing Graph did not throw expected Exception:: http://bugtrack.marklogic.com/35064 , Received ::" + exp, exp.toString().contains("Could not delete resource at graphs")); } /* * Write Triples using Write user & StringHandle with mime-Type = n-triples * Get the list of Graphs from the DB with Write User Iterate through the list * of graphs to validate the Graph */ @Test public void testListUris_writeUser() throws Exception { String ntriple5 = "<http://example.org/s22> <http://example.com/p22> <http://example.org/o22> ."; gmWriter.write("htp://test.sem.graph/G2", new StringHandle(ntriple5) .withMimetype("application/n-triples")); try { Iterator<String> iter = gmWriter.listGraphUris(); while (iter.hasNext()) { String uri = iter.next(); assertNotNull(uri); assertNotEquals("", uri); System.out.println("DEBUG: [GraphsTest] uri =[" + uri + "]"); } } catch (Exception e) { } } /* * Write Triples using Read user & StringHandle with mime-Type = n-triples * Catch the Exception and validate ForbiddenUser Exception with the Message. */ @Test public void testWriteTriples_ReadUser() throws Exception { Exception exp = null; String ntriple5 = "<http://example.org/s33> <http://example.com/p33> <http://example.org/o33> ."; try { gmReader.write("htp://test.sem.graph/G3", new StringHandle(ntriple5).withMimetype("application/n-triples")); } catch (Exception e) { exp = e; } assertTrue( "Unexpected Error Message, \n Expecting:: com.marklogic.client.ForbiddenUserException: Local message: User is not allowed to write resource at graphs. Server Message: " + "You do not have permission to this method and URL \n BUT Received :: " + exp.toString(), exp.toString() .contains( "com.marklogic.client.ForbiddenUserException: Local message: User is not allowed to write resource at graphs. Server Message: " + "You do not have permission to this method and URL")); } /* * Write Triples using Write user,Delete Graph using Read User Catch exception * and validate the correct Error message can also use RDFMimeTypes.NTRIPLES */ @Test public void testWriteTriples_DeletereadUser() throws Exception { Exception exp = null; boolean exceptionThrown = false; String ntriple5 = "<http://example.org/s44> <http://example.com/p44> <http://example.org/o44> ."; try { gmWriter.write("htp://test.sem.graph/G4", new StringHandle(ntriple5).withMimetype("application/n-triples")); gmReader.delete("htp://test.sem.graph/G4"); } catch (Exception e) { exp = e; exceptionThrown = true; } if (exceptionThrown) assertTrue( "Unexpected Error Message, \n Expecting:: com.marklogic.client.ForbiddenUserException: Local message: User is not allowed to delete resource at graphs. Server Message: " + "You do not have permission to this method and URL \n BUT Received :: " + exp.toString(), exp.toString() .contains( "com.marklogic.client.ForbiddenUserException: Local message: User is not allowed to delete resource at graphs. Server Message: " + "You do not have permission to this method and URL")); assertTrue("Expected Exception but Received NullPointer", exceptionThrown); } /* * Write & Read triples of type N-Triples using File & String handles */ @Test public void testWrite_nTriples_FileHandle() throws Exception { File file = new File(datasource + "5triples.nt"); FileHandle filehandle = new FileHandle(); filehandle.set(file); gmWriter.write("htp://test.sem.graph/n", filehandle.withMimetype("application/n-triples")); StringHandle handle = gmWriter.read("htp://test.sem.graph/n", new StringHandle().withMimetype(RDFMimeTypes.NTRIPLES)); assertTrue("Did not insert document or inserted empty doc", handle.toString().contains("<http://jibbering.com/foaf/santa.rdf#bod>")); } /* * Write & Read RDF using ReaderHandle Validate the content in DB by * converting into String. */ @Test public void testWrite_rdfxml_FileHandle() throws Exception { BufferedReader buffreader = new BufferedReader(new FileReader(datasource + "semantics.rdf")); ReaderHandle handle = new ReaderHandle(); handle.set(buffreader); gmWriter.write("http://test.reader.handle/bufferreadtrig", handle.withMimetype(RDFMimeTypes.RDFXML)); buffreader.close(); ReaderHandle read = gmWriter.read("http://test.reader.handle/bufferreadtrig", new ReaderHandle().withMimetype(RDFMimeTypes.RDFXML)); Reader readFile = read.get(); String readContent = convertReaderToString(readFile); assertTrue("Did not get receive expected string content, Received:: " + readContent, readContent.contains("http://www.daml.org/2001/12/factbook/vi#A113932")); handle.close(); read.close(); } /* * Write & Read triples of type ttl using bytehandle */ @Test public void testWrite_ttl_FileHandle() throws Exception { File file = new File(datasource + "relative3.ttl"); FileInputStream fileinputstream = new FileInputStream(file); ByteArrayOutputStream byteoutputstream = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; // Get triples into bytes from file for (int readNum; (readNum = fileinputstream.read(buf)) != -1;) { byteoutputstream.write(buf, 0, readNum); } byte[] bytes = byteoutputstream.toByteArray(); fileinputstream.close(); byteoutputstream.close(); BytesHandle contentHandle = new BytesHandle(); contentHandle.set(bytes); // write triples in bytes to DB gmWriter.write("http://test.turtle.com/byteHandle", contentHandle.withMimetype(RDFMimeTypes.TURTLE)); BytesHandle byteHandle = gmWriter.read("http://test.turtle.com/byteHandle", new BytesHandle().withMimetype(RDFMimeTypes.TURTLE)); byte[] readInBytes = byteHandle.get(); String readInString = new String(readInBytes); assertTrue("Did not insert document or inserted empty doc", readInString.contains("#relativeIRI")); } /* * Read & Write triples using File Handle and parse the read results into json * using Jackson json node. */ @Test public void testWrite_rdfjson_FileHandle() throws Exception { ObjectMapper mapper = new ObjectMapper(); new ObjectMapper(); File file = new File(datasource + "relative6.json"); FileHandle filehandle = new FileHandle(); filehandle.set(file); gmWriter.write("htp://test.sem.graph/rdfjson", filehandle.withMimetype("application/rdf+json")); FileHandle handle = new FileHandle(); handle.setMimetype(RDFMimeTypes.RDFJSON); handle = gmWriter.read("htp://test.sem.graph/rdfjson", handle); File readFile = handle.get(); JsonNode readContent = mapper.readTree(readFile); // Verify read content with inserted content assertTrue("Did not insert document or inserted empty doc", readContent.toString() .contains("http://purl.org/dc/elements/1.1/title")); } // Write & Read triples of type N3 using ByteHandle @Test public void testWrite_n3_BytesHandle() throws Exception { File file = new File(datasource + "relative7.n3"); FileInputStream fileinputstream = new FileInputStream(file); ByteArrayOutputStream byteoutputstream = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; // Get triples into bytes from file for (int readNum; (readNum = fileinputstream.read(buf)) != -1;) { byteoutputstream.write(buf, 0, readNum); } byte[] bytes = byteoutputstream.toByteArray(); fileinputstream.close(); byteoutputstream.close(); BytesHandle contentHandle = new BytesHandle(); contentHandle.set(bytes); // write triples in bytes to DB gmWriter.write("http://test.n3.com/byte", contentHandle.withMimetype(RDFMimeTypes.N3)); InputStreamHandle read = null; InputStream fileRead = null; InputStreamHandle ins = null; try { ins = new InputStreamHandle().withMimetype(RDFMimeTypes.N3); read = gmWriter.read("http://test.n3.com/byte", ins); fileRead = read.get(); String readContent = convertInputStreamToString(fileRead); assertTrue("Did not find expected content after inserting the triples:: Found: " + readContent, readContent.contains("/publications/journals/Journal1/1940")); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (read != null) read.close(); if (ins != null) ins.close(); if (fileRead != null) fileRead.close(); } } @Test public void testWrite_nquads_FileHandle() throws Exception { File file = new File(datasource + "relative2.nq"); FileHandle filehandle = new FileHandle(); filehandle.set(file); gmWriter.write("htp://test.sem.graph/nquads", filehandle.withMimetype("application/n-quads")); StringHandle handle = gmWriter.read("htp://test.sem.graph/nquads", new StringHandle().withMimetype(RDFMimeTypes.NQUADS)); assertTrue("Did not insert document or inserted empty doc", handle.toString().contains("<#electricVehicle2>")); } /* * Write same Triples into same graph twice & Read Triples of type Trig using * FileHandle Should not insert duplicate and Read should not result in * duplicates */ @Test public void testWrite_trig_FileHandle() throws Exception { File file = new File(datasource + "semantics.trig"); FileHandle filehandle = new FileHandle(); filehandle.set(file); gmWriter.write("htp://test.sem.graph/trig", filehandle.withMimetype("application/trig")); gmWriter.write("htp://test.sem.graph/trig", filehandle.withMimetype("application/trig")); FileHandle handle = gmWriter.read("htp://test.sem.graph/trig", new FileHandle()); File readFile = handle.get(); String expectedContent = convertFileToString(readFile); assertTrue("Did not insert document or inserted empty doc", expectedContent.contains("http://www.example.org/exampleDocument#Monica")); } /* * Open a Transaction Write tripleXML into DB using FileHandle & rest-writer * using the transaction Read the Graph and validate Graph exists in DB using * the same transaction Delete the Graph within the same transaction Read and * validate the delete by catching the exception Finally if the Transaction is * open Perform Rollback */ @Test public void testWrite_triplexml_FileHandle() throws Exception { Transaction trx = writerClient.openTransaction(); GraphManager gmWriter = writerClient.newGraphManager(); File file = new File(datasource + "relative5.xml"); FileHandle filehandle = new FileHandle(); filehandle.set(file); // Write Graph using transaction gmWriter.write("htp://test.sem.graph/tripxml", filehandle.withMimetype(RDFMimeTypes.TRIPLEXML), trx); // Validate graph written to DB by reading within the same transaction StringHandle handle = gmWriter.read("htp://test.sem.graph/tripxml", new StringHandle().withMimetype(RDFMimeTypes.TRIPLEXML), trx); assertTrue("Did not insert document or inserted empty doc", handle.toString().contains("Anna's Homepage")); // Delete Graph in the same transaction gmWriter.delete("htp://test.sem.graph/tripxml", trx); // Validate Graph is deleted try { gmWriter.read("htp://test.sem.graph/tripxml", new StringHandle(), trx); trx.commit(); trx = null; } catch (ResourceNotFoundException e) { System.out.println(e); } finally { if (trx != null) { trx.rollback(); trx = null; } } } /* * Insert rdf triples intoDB which does not have base URI defined validate * Undeclared base URI exception is thrown */ @Test // GitIssue #319 public void testWrite_rdfxml_WrongTriplesSchema() throws Exception { Exception exp = null; File file = new File(datasource + "relative4.rdf"); FileHandle filehandle = new FileHandle(); filehandle.set(file); try { gmWriter.write("htp://test.sem.graph/rdf", filehandle.withMimetype(RDFMimeTypes.RDFXML)); } catch (Exception e) { exp = e; } assertTrue("Did not throw expected Exception, Expecting ::XDMP-BASEURI (err:FOER0000): Undeclared base URI " + "\n Received::" + exp, exp.toString().contains("XDMP-BASEURI (err:FOER0000): Undeclared base URI")); } /* * -ve case to validate non-iri triples insert and read should throw * SEM-NOTRDF exception Note:: In RDF, the subject and predicate can only be * of type IRI */ // Git issue #322 , server returns 500 error code @Test public void testRead_nonirirdfxml_FileHandle() throws Exception { StringHandle handle = new StringHandle(); File file = new File(datasource + "non-iri.xml"); FileHandle filehandle = new FileHandle(); filehandle.set(file); gmWriter.write("htp://test.sem.graph/tripxmlnoniri", filehandle.withMimetype(RDFMimeTypes.TRIPLEXML)); try { handle = gmWriter.read("htp://test.sem.graph/tripxmlnoniri", new StringHandle()); } catch (Exception e) { assertTrue("Did not receive expected Error message, Expecting ::SEM-NOTRDF \n Received::" + e, e.toString().contains("SEM-NOTRDF") && e != null); } assertTrue("Read content has un-expected content ", handle.get().toString().contains("5.11")); } /* * Write & Read NON -RDF format triples */ @Test public void testRead_nonirin3_FileHandle() throws Exception { StringHandle handle = new StringHandle(); File file = new File(datasource + "non-iri.n3"); FileHandle filehandle = new FileHandle(); filehandle.set(file); gmWriter.write("htp://test.sem.graph/n3noniri", filehandle.withMimetype(RDFMimeTypes.N3)); try { handle = gmWriter.read("htp://test.sem.graph/n3noniri", new StringHandle().withMimetype(RDFMimeTypes.N3)); } catch (Exception e) { assertTrue("Did not receive expected Error message, Expecting ::SEM-NOTRDF \n Received::" + e, e.toString().contains("SEM-NOTRDF") && e != null); } assertTrue("Read content has un-expected content ", handle.get().toString().contains("p0:named_graph")); } /* * ReadAs & WriteAs N-Triples using File Type */ @Test public void testReadAs_WriteAs() throws Exception { File file = new File(datasource + "semantics.nt"); FileHandle filehandle = new FileHandle(); filehandle.set(file); gmWriter.writeAs("htp://test.sem.graph/ntAs", filehandle.withMimetype(RDFMimeTypes.NTRIPLES)); File read = gmWriter.readAs("htp://test.sem.graph/ntAs", File.class); String expectedContent = convertFileToString(read); assertTrue("writeAs & readAs test did not return expected content", expectedContent.contains("http://www.w3.org/2001/sw/RDFCore/ntriples/")); } /* * ReadAs & WriteAs N-Triples using File Type within a Transaction */ @Test public void testWriteAs_ReadAs_FileHandle() throws Exception { Transaction trx = writerClient.openTransaction(); GraphManager gmWriter = writerClient.newGraphManager(); File file = new File(datasource + "semantics.ttl"); FileHandle filehandle = new FileHandle(); filehandle.set(file); // Write Graph using transaction gmWriter.writeAs("htp://test.sem.graph/ttlas", filehandle.withMimetype(RDFMimeTypes.TURTLE), trx); // Validate graph written to DB by reading within the same transaction File readFile = gmWriter.readAs("htp://test.sem.graph/ttlas", File.class, trx); String expectedContent = convertFileToString(readFile); assertTrue("Did not insert document or inserted empty doc", expectedContent.contains("http://www.w3.org/2004/02/skos/core#Concept")); // Delete Graph in the same transaction gmWriter.delete("htp://test.sem.graph/ttlas", trx); trx.commit(); // Validate Graph is deleted try { trx = writerClient.openTransaction(); String readContent = gmWriter.readAs("htp://test.sem.graph/ttlas", String.class, trx); trx.commit(); trx = null; assertTrue("Unexpected content read, expecting Resource not found exception", readContent == null); } catch (ResourceNotFoundException e) { System.out.println(e); } finally { if (trx != null) { trx.rollback(); trx = null; } } } /* * Merge Triples of same mime type Validate the triples are inserted correctly * & MergeAs & QuadsWriteHandle */ @Test public void testMerge_trig_FileHandle() throws Exception { File file = new File(datasource + "trig.trig"); FileHandle filehandle = new FileHandle(); filehandle.set(file); File file2 = new File(datasource + "semantics.trig"); FileHandle filehandle2 = new FileHandle(); filehandle2.set(file2); gmWriter.write("htp://test.sem.graph/trigMerge", filehandle.withMimetype(RDFMimeTypes.TRIG)); gmWriter.merge("htp://test.sem.graph/trigMerge", filehandle2.withMimetype(RDFMimeTypes.TRIG)); FileHandle handle = gmWriter.read("htp://test.sem.graph/trigMerge", new FileHandle()); File readFile = handle.get(); String expectedContent = convertFileToString(readFile); assertTrue( "Did not insert document or inserted empty doc", expectedContent.contains("http://www.example.org/exampleDocument#Monica") && expectedContent.contains("http://purl.org/dc/elements/1.1/publisher")); } /* * Merge Triples of different mime type's Validate the triples are inserted * correctly */ @Test public void testMerge_jsonxml_FileHandle() throws Exception { File file = new File(datasource + "bug25348.json"); FileHandle filehandle = new FileHandle(); filehandle.set(file); File file2 = new File(datasource + "relative5.xml"); FileHandle filehandle2 = new FileHandle(); filehandle2.set(file2); gmWriter.write("htp://test.sem.graph/trigM", filehandle.withMimetype(RDFMimeTypes.RDFJSON)); gmWriter.merge("htp://test.sem.graph/trigM", filehandle2.withMimetype(RDFMimeTypes.TRIPLEXML)); FileHandle handle = gmWriter.read("htp://test.sem.graph/trigM", new FileHandle().withMimetype(RDFMimeTypes.RDFJSON)); File readFile = handle.get(); String expectedContent = convertFileToString(readFile); assertTrue("Did not insert document or inserted empty doc", expectedContent.contains("http://example.com/ns/person#firstName") && expectedContent.contains("Anna's Homepage")); } /* * WriteAs,MergeAs & ReadAs Triples of different mimetypes */ @Test public void testMergeAs_jsonxml_FileHandle() throws Exception { gmWriter.setDefaultMimetype(RDFMimeTypes.RDFJSON); File file = new File(datasource + "bug25348.json"); FileInputStream fis = new FileInputStream(file); Object graphData = convertInputStreamToString(fis); fis.close(); gmWriter.writeAs("htp://test.sem.graph/jsonMergeAs", graphData); gmWriter.setDefaultMimetype(RDFMimeTypes.TRIPLEXML); File file2 = new File(datasource + "relative5.xml"); Object graphData2 = convertFileToString(file2); gmWriter.mergeAs("htp://test.sem.graph/jsonMergeAs", graphData2); File readFile = gmWriter.readAs("htp://test.sem.graph/jsonMergeAs", File.class); String expectedContent = convertFileToString(readFile); assertTrue("Did not insert document or inserted empty doc", expectedContent.contains("http://example.com/ns/person#firstName") && expectedContent.contains("Anna's Homepage")); } /* * WriteAs,MergeAs & ReadAs Triples of different mimetypes within a * Transaction & QuadsWriteHandle */ @Test public void testMergeAs_jsonxml_Trx_FileHandle() throws Exception { Transaction trx = writerClient.openTransaction(); GraphManager gmWriter = writerClient.newGraphManager(); gmWriter.setDefaultMimetype(RDFMimeTypes.RDFJSON); File file = new File(datasource + "bug25348.json"); FileInputStream fis = new FileInputStream(file); Object graphData = convertInputStreamToString(fis); fis.close(); gmWriter.writeAs("htp://test.sem.graph/jsonMergeAsTrx", graphData, trx); File file2 = new File(datasource + "relative6.json"); Object graphData2 = convertFileToString(file2); gmWriter.mergeAs("htp://test.sem.graph/jsonMergeAsTrx", graphData2, trx); File readFile = gmWriter.readAs("htp://test.sem.graph/jsonMergeAsTrx", File.class, trx); String expectedContent = convertFileToString(readFile); assertTrue("Did not insert document or inserted empty doc", expectedContent.contains("http://example.com/ns/person#firstName") && expectedContent.contains("Anna's Homepage")); try { trx.commit(); trx = null; } catch (Exception e) { System.out.println(e); } finally { if (trx != null) { trx.rollback(); trx = null; } } } /* * Merge Triples into Graph which already has the same triples Inserts two * documents into DB Read the graph , should not contain duplicate triples */ @Test public void testMergeSameDoc_jsonxml_FileHandle() throws Exception { gmWriter.setDefaultMimetype(RDFMimeTypes.RDFJSON); File file = new File(datasource + "bug25348.json"); FileHandle filehandle = new FileHandle(); filehandle.set(file); gmWriter.write("htp://test.sem.graph/trigMSameDoc", filehandle); gmWriter.merge("htp://test.sem.graph/trigMSameDoc", filehandle); FileHandle handle = gmWriter.read("htp://test.sem.graph/trigMSameDoc", new FileHandle()); File readFile = handle.get(); String expectedContent = convertFileToString(readFile); assertTrue( "Did not insert document or inserted empty doc", expectedContent .equals("{\"http://example.com/ns/directory#m\":{\"http://example.com/ns/person#firstName\":[{\"value\":\"Michelle\", \"" + "type\":\"literal\", \"datatype\":\"http://www.w3.org/2001/XMLSchema#string\"}]}}")); } /* * Merge & Delete With in Transaction */ @Test public void testWriteMergeDelete_Trx() throws Exception { Transaction trx = writerClient.openTransaction(); GraphManager gmWriter = writerClient.newGraphManager(); File file = new File(datasource + "triplexml1.xml"); gmWriter.write("htp://test.sem.graph/mergetrx", new FileHandle(file).withMimetype(RDFMimeTypes.TRIPLEXML), trx); file = new File(datasource + "bug25348.json"); gmWriter.merge("htp://test.sem.graph/mergetrx", new FileHandle(file).withMimetype(RDFMimeTypes.RDFJSON), trx); FileHandle handle = gmWriter.read("htp://test.sem.graph/mergetrx", new FileHandle(), trx); File readFile = handle.get(); String expectedContent = convertFileToString(readFile); try { assertTrue("Did not Merge document or inserted empty doc", expectedContent.contains("Michelle") && expectedContent.contains("Anna's Homepage")); gmWriter.delete("htp://test.sem.graph/mergetrx", trx); trx.commit(); trx = null; StringHandle readContent = gmWriter.read("htp://test.sem.graph/mergetrx", new StringHandle(), trx); assertTrue("Unexpected Content from read, expecting null", readContent == null); } catch (Exception e) { assertTrue("Unexpected Exception Thrown", e.toString().contains("ResourceNotFoundException")); } finally { if (trx != null) trx.commit(); trx = null; } } /* * Write and read triples into ML default graph */ @Test public void testWriteRead_defaultGraph() throws FileNotFoundException { File file = new File(datasource + "semantics.trig"); FileHandle filehandle = new FileHandle(); filehandle.set(file); gmWriter.write(GraphManager.DEFAULT_GRAPH, filehandle.withMimetype(RDFMimeTypes.TRIG)); FileHandle handle = gmWriter.read(GraphManager.DEFAULT_GRAPH, new FileHandle()); GraphPermissions permissions = gmWriter.getPermissions(GraphManager.DEFAULT_GRAPH); System.out.println(permissions); assertEquals(Capability.UPDATE, permissions.get("rest-writer").iterator().next()); assertEquals(Capability.READ, permissions.get("rest-reader").iterator().next()); gmWriter.deletePermissions(GraphManager.DEFAULT_GRAPH); permissions = gmWriter.getPermissions(GraphManager.DEFAULT_GRAPH); System.out.println(permissions); assertEquals(Capability.UPDATE, permissions.get("rest-writer").iterator().next()); File readFile = handle.get(); String expectedContent = convertFileToString(readFile); System.out.println(gmWriter.listGraphUris().next().toString()); assertTrue("" + gmWriter.listGraphUris().next().toString(), gmWriter.listGraphUris().next().toString().equals("http://marklogic.com/semantics#default-graph")); assertTrue("Did not insert document or inserted empty doc", expectedContent.contains("http://www.example.org/exampleDocument#Monica")); } /* * Write Triples of Type JSON Merge NTriples into the same graph and validate * ReplaceGraphs with File handle & Nquads mime-type and validate & * DeleteGraphs and validate ResourceNotFound Exception */ @Test public void testMergeReplace_quads() throws FileNotFoundException, InterruptedException { String uri = "http://test.sem.quads/json-quads"; String ntriple6 = "<http://example.org/s6> <http://example.com/mergeQuadP> <http://example.org/o2> <http://test.sem.quads/json-quads>."; File file = new File(datasource + "bug25348.json"); FileHandle filehandle = new FileHandle(); filehandle.set(file); gmWriter.write(uri, filehandle.withMimetype(RDFMimeTypes.RDFJSON)); gmWriter.mergeGraphs(new StringHandle(ntriple6).withMimetype(RDFMimeTypes.NQUADS)); FileHandle handle = gmWriter.read(uri, new FileHandle()); File readFile = handle.get(); String expectedContent = convertFileToString(readFile); assertTrue("Did not merge Quad", expectedContent.contains("<http://example.com/mergeQuadP")); file = new File(datasource + "relative2.nq"); gmWriter.replaceGraphs(new FileHandle(file).withMimetype(RDFMimeTypes.NQUADS)); uri = "http://originalGraph"; StringHandle readQuads = gmWriter.read(uri, new StringHandle()); assertTrue("Did not Replace Quads", readQuads.toString().contains("#electricVehicle2")); gmWriter.deleteGraphs(); try { StringHandle readContent = gmWriter.read(uri, new StringHandle()); assertTrue("Unexpected content read, expecting Resource not found exception", readContent.get() == null); } catch (Exception e) { assertTrue("Unexpected Exception Thrown", e.toString().contains("ResourceNotFoundException")); } } /* * Replace with Large Number(600+) of Graphs of type nquads and validate Merge * different quads with different graph and validate deletegraphs and validate * resourcenotfound exception */ @Test public void testMergeReplaceAs_Quads() throws Exception { gmWriter.setDefaultMimetype(RDFMimeTypes.NQUADS); File file = new File(datasource + "semantics.nq"); gmWriter.replaceGraphsAs(file); String uri = "http://en.wikipedia.org/wiki/Alexander_I_of_Serbia?oldid=492189987#absolute-line=1"; StringHandle readQuads = gmWriter.read(uri, new StringHandle()); assertTrue("Did not Replace Quads", readQuads.toString().contains("http://dbpedia.org/ontology/Monarch")); file = new File(datasource + "relative2.nq"); gmWriter.mergeGraphsAs(file); uri = "http://originalGraph"; readQuads = gmWriter.read(uri, new StringHandle()); assertTrue("Did not Replace Quads", readQuads.toString().contains("#electricVehicle2")); gmWriter.deleteGraphs(); try { StringHandle readContent = gmWriter.read(uri, new StringHandle()); assertTrue("Unexpected content read, expecting Resource not found exception", readContent.get() == null); } catch (Exception e) { assertTrue("Unexpected Exception Thrown", e.toString().contains("ResourceNotFoundException")); } } @Test public void testThingsAs() throws Exception { gmWriter.setDefaultMimetype(RDFMimeTypes.NTRIPLES); File file = new File(datasource + "relative1.nt"); FileHandle filehandle = new FileHandle(); filehandle.set(file); gmWriter.write("http://test.things.com/", filehandle); String things = gmWriter.thingsAs(String.class, "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"); assertTrue( "Did not return Expected graph Uri's", things.equals("<#electricVehicle2> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://people.aifb.kit.edu/awa/2011/smartgrid/schema/smartgrid#ElectricVehicle> .")); } @Test public void testThings_file() throws Exception { gmWriter.setDefaultMimetype(RDFMimeTypes.TRIPLEXML); String tripleGraphUri = "http://test.things.com/file"; File file = new File(datasource + "relative5.xml"); gmWriter.write(tripleGraphUri, new FileHandle(file)); TriplesReadHandle things = gmWriter.things(new StringHandle(), "about"); assertTrue("Things did not return expected Uri's", things.toString().contains("<about> <http://purl.org/dc/elements/1.1/title> \"Anna's Homepage\" .")); gmWriter.delete(tripleGraphUri); } @Test public void testWrite_rdfjson_JacksonHandle() throws Exception { File file = new File(datasource + "relative6.json"); FileHandle filehandle = new FileHandle(); filehandle.set(file); gmWriter.write("htp://test.sem.graph/rdfjson", filehandle.withMimetype("application/rdf+json")); JacksonHandle handle1 = gmWriter.read("htp://test.sem.graph/rdfjson", new JacksonHandle()); JsonNode readFile = handle1.get(); assertTrue("Did not insert document or inserted empty doc", readFile.toString().contains("http://purl.org/dc/elements/1.1/title")); } @Test public void testWrite_rdfjson_TripleReadHandle() throws Exception { File file = new File(datasource + "relative6.json"); FileHandle filehandle = new FileHandle(); filehandle.set(file); gmWriter.write("htp://test.sem.graph/rdfjson", filehandle.withMimetype("application/rdf+json")); TriplesReadHandle handle1 = gmWriter.read("htp://test.sem.graph/rdfjson", new JacksonHandle()); assertTrue("Did not insert document or inserted empty doc", handle1.toString().contains("http://purl.org/dc/elements/1.1/title")); } @Test public void testThings_fileNomatch() throws Exception { gmWriter.setDefaultMimetype(RDFMimeTypes.TRIPLEXML); String tripleGraphUri = "http://test.things.com/file"; File file = new File(datasource + "relative5.xml"); gmWriter.write(tripleGraphUri, new FileHandle(file)); Exception exp = null; try { TriplesReadHandle things = gmWriter.things(new StringHandle(), "noMatch"); assertTrue("Things did not return expected Uri's", things == null); } catch (Exception e) { exp = e; } assertTrue(exp.toString().contains("ResourceNotFoundException")); gmWriter.delete(tripleGraphUri); } @Test public void testThings_Differentmimetypes() throws Exception { gmWriter.setDefaultMimetype(RDFMimeTypes.TRIPLEXML); String tripleGraphUri = "http://test.things.com/multiple"; File file = new File(datasource + "relative5.xml"); gmWriter.write(tripleGraphUri, new FileHandle(file)); file = new File(datasource + "semantics.ttl"); gmWriter.merge(tripleGraphUri, new FileHandle(file).withMimetype(RDFMimeTypes.TURTLE)); StringHandle things = gmWriter.things(new StringHandle(), "http://dbpedia.org/resource/Hadoop"); assertTrue("Things did not return expected Uri's", things.get().contains("Apache Hadoop")); gmWriter.delete(tripleGraphUri); } // TODO:: Re-write this Method into multiple tests after 8.0-4 release @Test public void testPermissions_noTrx() throws Exception { File file = new File(datasource + "semantics.rdf"); FileHandle handle = new FileHandle(); handle.set(file); String uri = "test_permissions11"; // Create Role createUserRolesWithPrevilages("test-perm"); // Create User with Above Role createRESTUser("perm-user", "x", "test-perm"); // Create Client with above User int restPort = getRestServerPort(); DatabaseClient permUser = getDatabaseClientOnDatabase(appServerHostname, restPort, dbName, "perm-user", "x", getConnType()); // Create GraphManager with Above client GraphManager gmTestPerm = permUser.newGraphManager(); // Set Update Capability for the Created User GraphPermissions perms = gmTestPerm.permission("test-perm", Capability.UPDATE); // Write Graph with triples into DB gmTestPerm.write(uri, handle.withMimetype(RDFMimeTypes.RDFXML), perms); waitForPropertyPropagate(); // Get PErmissions for the User and Validate System.out.println("Permissions after create , Should not see Execute" + gmTestPerm.getPermissions(uri)); perms = gmTestPerm.getPermissions(uri); for (Capability capability : perms.get("test-perm")) { assertTrue("capability should be UPDATE, not [" + capability + "]", capability == Capability.UPDATE); } // Create another Role to check for builder style permissions support. createUserRolesWithPrevilages("test-perm2"); // Set Capability for the User perms = gmTestPerm.permission("test-perm", Capability.EXECUTE).permission("test-perm2", Capability.EXECUTE).permission("test-perm2", Capability.READ); // Merge Permissions gmTestPerm.mergePermissions(uri, perms); // gmTestPerm.writePermissions(uri, perms); // Get Permissions And Validate perms = gmTestPerm.getPermissions(uri); System.out.println("Permissions after setting execute , Should see Execute & Update" + gmTestPerm.getPermissions(uri)); for (Capability capability : perms.get("test-perm")) { assertTrue("capability for role test-perm should be UPDATE && Execute, not [" + capability + "]", capability == Capability.UPDATE || capability == Capability.EXECUTE); } for (Capability capability : perms.get("test-perm2")) { assertTrue("capability for role test-perm2 should be EXECUTE && READ, not [" + capability + "]", capability == Capability.READ || capability == Capability.EXECUTE); } assertTrue("Did not have expected capabilities", perms.get("test-perm").size() == 2); assertTrue("Did not have expected capabilities", perms.get("test-perm2").size() == 2); // Write Read permission to uri and validate permissions are overwritten // with write perms = gmTestPerm.permission("test-perm", Capability.READ); gmTestPerm.write(uri, handle.withMimetype(RDFMimeTypes.RDFXML), perms); for (Capability capability : perms.get("test-perm")) { assertTrue("capability should be READ, not [" + capability + "]", capability == Capability.READ); } assertTrue("Did not have expected capabilities", perms.get("test-perm").size() == 1); // Delete Permissions and Validate gmTestPerm.deletePermissions(uri); perms = gmTestPerm.getPermissions(uri); assertNull(perms.get("test-perm")); assertNull(perms.get("test-perm2")); // Set and Write Execute Permission perms = gmTestPerm.permission("test-perm", Capability.EXECUTE); gmTestPerm.writePermissions(uri, perms); // Read and Validate triples try { gmTestPerm.read(uri, handle.withMimetype(RDFMimeTypes.RDFXML)); ReaderHandle read = gmTestPerm.read(uri, new ReaderHandle()); Reader readFile = read.get(); String readContent = convertReaderToString(readFile); assertTrue("Did not get receive expected string content, Received:: " + readContent, readContent.contains("http://www.daml.org/2001/12/factbook/vi#A113932")); } catch (Exception e) { System.out.println("Tried to Read and validate triples, should see this exception ::" + e); } System.out.println("Permissions after setting execute , Should see Execute & Update & Read " + gmTestPerm.getPermissions(uri)); // delete all capabilities gmTestPerm.deletePermissions(uri); System.out.println("Capabilities after delete , Should not see Execute" + gmTestPerm.getPermissions(uri)); // set Update and perform Read perms = gmTestPerm.permission("test-perm", Capability.UPDATE); gmTestPerm.mergePermissions(uri, perms); try { gmTestPerm.read(uri, new ReaderHandle()); } catch (Exception e) { System.out.println(" Should receive unauthorized exception ::" + e); } // Delete gmTestPerm.deletePermissions(uri); // Set to Read and Perform Merge perms = gmTestPerm.permission("test-perm", Capability.READ); gmTestPerm.mergePermissions(uri, perms); try { gmTestPerm.merge(uri, handle); } catch (Exception e) { System.out.println(" Should receive unauthorized exception ::" + e); } // Read and validate triples ReaderHandle read = gmTestPerm.read(uri, new ReaderHandle()); Reader readFile = read.get(); String readContent = convertReaderToString(readFile); assertTrue("Did not get receive expected string content, Received:: " + readContent, readContent.contains("http://www.daml.org/2001/12/factbook/vi#A113932")); // Delete the role deleteUserRole("test-perm2"); } /* * -ve cases for permission outside transaction and after rollback of * transaction */ @Test public void testPermissions_withtrxNeg() throws Exception { File file = new File(datasource + "semantics.rdf"); FileHandle handle = new FileHandle(); handle.set(file); String uri = "test_permissions12"; // Create Role createUserRolesWithPrevilages("test-perm"); // Create User with Above Role createRESTUser("perm-user", "x", "test-perm"); // Create Client with above User int restPort = getRestServerPort(); DatabaseClient permUser = getDatabaseClientOnDatabase(appServerHostname, restPort, dbName, "perm-user", "x", getConnType()); // Create GraphManager with Above client Transaction trx = permUser.openTransaction(); try { GraphManager gmTestPerm = permUser.newGraphManager(); // Set Update Capability for the Created User GraphPermissions perms = gmTestPerm.permission("test-perm", Capability.UPDATE); gmTestPerm.write(uri, handle.withMimetype(RDFMimeTypes.RDFXML), trx); trx.commit(); trx = permUser.openTransaction(); gmTestPerm.mergePermissions(uri, perms, trx); // Validate test-perm role not available outside transaction GraphPermissions perm = gmTestPerm.getPermissions(uri); System.out.println("OUTSIDE TRX , SHOULD NOT SEE test-perm EXECUTE" + perm); assertNull(perm.get("test-perm")); perms = gmTestPerm.getPermissions(uri, trx); assertTrue("Permission within trx should have Update capability", perms.get("test-perm").contains(Capability.UPDATE)); trx.rollback(); trx = null; perms = gmTestPerm.getPermissions(uri); assertNull(perm.get("test-perm")); } catch (Exception e) { } finally { if (trx != null) { trx.commit(); trx = null; } } } // TODO:: Re-write this Method into multiple tests after 8.0-4 release @Test public void testPermissions_withTrx() throws Exception { File file = new File(datasource + "semantics.rdf"); FileHandle handle = new FileHandle(); handle.set(file); String uri = "test_permissions12"; // Create Role createUserRolesWithPrevilages("test-perm"); // Create User with Above Role createRESTUser("perm-user", "x", "test-perm"); // Create Client with above User int restPort = getRestServerPort(); DatabaseClient permUser = getDatabaseClientOnDatabase(appServerHostname, restPort, dbName, "perm-user", "x", getConnType()); // Create GraphManager with Above client Transaction trx = permUser.openTransaction(); GraphManager gmTestPerm = permUser.newGraphManager(); // Set Update Capability for the Created User GraphPermissions perms = gmTestPerm.permission("test-perm", Capability.UPDATE); // Write Graph with triples into DB try { gmTestPerm.write(uri, handle.withMimetype(RDFMimeTypes.RDFXML), perms, trx); // Get PErmissions for the User and Validate System.out.println("Permissions after create , Should not see Execute" + gmTestPerm.getPermissions(uri, trx)); perms = gmTestPerm.getPermissions(uri, trx); for (Capability capability : perms.get("test-perm")) { assertTrue("capability should be UPDATE, not [" + capability + "]", capability == Capability.UPDATE); } // Set Capability for the User perms = gmTestPerm.permission("test-perm", Capability.EXECUTE); // Merge Permissions gmTestPerm.mergePermissions(uri, perms, trx); // Get Permissions And Validate perms = gmTestPerm.getPermissions(uri, trx); System.out.println("Permissions after setting execute , Should see Execute & Update" + gmTestPerm.getPermissions(uri, trx)); for (Capability capability : perms.get("test-perm")) { assertTrue("capability should be UPDATE && Execute, not [" + capability + "]", capability == Capability.UPDATE || capability == Capability.EXECUTE); } // Validate write with Update and Execute permissions try { gmTestPerm.write(uri, handle.withMimetype(RDFMimeTypes.RDFXML), perms, trx); } catch (Exception e) { System.out.println("Tried to Write Here ::" + e);// } System.out.println("Permissions after setting execute , Should see Execute & Update" + gmTestPerm.getPermissions(uri, trx)); // Delete Permissions and Validate gmTestPerm.deletePermissions(uri, trx); try { perms = gmTestPerm.getPermissions(uri, trx); } catch (Exception e) { System.out .println("Permissions after setting execute , Should see Execute & Update" + gmTestPerm.getPermissions(uri, trx)); } assertNull(perms.get("test-perm")); // Set and Write Execute Permission perms = gmTestPerm.permission("test-perm", Capability.EXECUTE, Capability.READ); gmTestPerm.writePermissions(uri, perms, trx); gmTestPerm.write(uri, handle.withMimetype(RDFMimeTypes.RDFXML), perms, trx); waitForPropertyPropagate(); // Read and Validate triples try { ReaderHandle read = gmTestPerm.read(uri, new ReaderHandle().withMimetype(RDFMimeTypes.RDFXML), trx); Reader readFile = read.get(); StringBuilder readContentSB = new StringBuilder(); BufferedReader br = null; try { br = new BufferedReader(readFile); String line = null; while ((line = br.readLine()) != null) readContentSB.append(line); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { br.close(); } String readContent = readContentSB.toString(); System.out.println("Triples read back from Server is " + readContent); assertTrue("Did not get receive expected string content, Received:: " + readContent, readContent.contains("http://www.daml.org/2001/12/factbook/vi#A113932")); } catch (Exception e) { System.out.println("Tried to Read and validate triples, should not see this exception ::" + e); } System.out.println("Permissions after setting execute , Should see Execute & Read " + gmTestPerm.getPermissions(uri, trx)); // delete all capabilities gmTestPerm.deletePermissions(uri, trx); System.out.println("Capabilities after delete , Should not see Execute" + gmTestPerm.getPermissions(uri, trx)); // set Update and perform Read perms = gmTestPerm.permission("test-perm", Capability.UPDATE); gmTestPerm.mergePermissions(uri, perms, trx); try { gmTestPerm.read(uri, new ReaderHandle(), trx); } catch (Exception e) { System.out.println(" Should receive unauthorized exception ::" + e); } // Delete gmTestPerm.deletePermissions(uri, trx); // Set to Read and Perform Merge perms = gmTestPerm.permission("test-perm", Capability.READ); gmTestPerm.mergePermissions(uri, perms, trx); perms = gmTestPerm.permission("test-perm", Capability.READ); gmTestPerm.mergePermissions(uri, perms, trx); try { gmTestPerm.merge(uri, handle, trx); } catch (Exception e) { System.out.println(" Should receive unauthorized exception ::" + e); } // Read and validate triples ReaderHandle read = gmTestPerm.read(uri, new ReaderHandle(), trx); Reader readFile = read.get(); String readContent = convertReaderToString(readFile); assertTrue("Did not get receive expected string content, Received:: " + readContent, readContent.contains("http://www.daml.org/2001/12/factbook/vi#A113932")); trx.commit(); trx = null; } catch (Exception e) { } finally { if (trx != null) { trx.commit(); trx = null; } } } /* * Write Triples of Type JSON Merge NTriples into the same graph and validate * mergeGraphs with transactions. * * Merge within same write transaction Write and merge Triples within * different transactions. Commit the merge transaction Write and merge * Triples within different transactions. Rollback the merge transaction Write * and merge Triples within different transactions. Rollback the merge * transaction and then commit. */ @Test public void testMergeGraphWithTransaction() throws FileNotFoundException, InterruptedException { String uri = "http://test.sem.quads/json-quads"; Transaction trxIn = writerClient.openTransaction(); Transaction trxInMergeGraph = null; Transaction trxDelIn = null; try { String ntriple6 = "<http://example.org/s6> <http://example.com/mergeQuadP> <http://example.org/o2> <http://test.sem.quads/json-quads>."; File file = new File(datasource + "bug25348.json"); FileHandle filehandle = new FileHandle(); filehandle.set(file); // Using client write and merge Triples within same transaction. gmWriter.write(uri, filehandle.withMimetype(RDFMimeTypes.RDFJSON), trxIn); // Merge Graphs inside the transaction. gmWriter.mergeGraphs(new StringHandle(ntriple6).withMimetype(RDFMimeTypes.NQUADS), trxIn); trxIn.commit(); FileHandle handle = gmWriter.read(uri, new FileHandle()); File readFile = handle.get(); String expectedContent = convertFileToString(readFile); assertTrue("Did not write Quad in transaction", expectedContent.contains("<http://example.com/ns/person#firstName")); assertTrue("Did not merge Quad", expectedContent.contains("<http://example.com/mergeQuadP")); trxIn = null; handle = null; readFile = null; expectedContent = null; // Delete Graphs inside the transaction. trxDelIn = writerClient.openTransaction(); gmWriter.delete(uri, trxDelIn); trxDelIn.commit(); trxDelIn = null; // Using client write and merge Triples within different transactions. // Commit the merge transaction trxIn = writerClient.openTransaction(); trxInMergeGraph = writerClient.openTransaction(); gmWriter.write(uri, filehandle.withMimetype(RDFMimeTypes.RDFJSON), trxIn); trxIn.commit(); // Make sure that original triples are available. handle = gmWriter.read(uri, new FileHandle()); readFile = handle.get(); expectedContent = convertFileToString(readFile); assertTrue("Did not write Quad in transaction", expectedContent.contains("<http://example.com/ns/person#firstName")); handle = null; readFile = null; expectedContent = null; // Merge Graphs inside another transaction. gmWriter.mergeGraphs(new StringHandle(ntriple6).withMimetype(RDFMimeTypes.NQUADS), trxInMergeGraph); trxInMergeGraph.commit(); handle = gmWriter.read(uri, new FileHandle()); readFile = handle.get(); expectedContent = convertFileToString(readFile); assertTrue("Merge corrupted original Quad in transaction", expectedContent.contains("<http://example.com/ns/person#firstName")); assertTrue("Did not merge Quad in separate transaction", expectedContent.contains("<http://example.com/mergeQuadP")); trxIn = null; trxInMergeGraph = null; handle = null; readFile = null; expectedContent = null; trxDelIn = null; // Delete Graphs inside the transaction. trxDelIn = writerClient.openTransaction(); gmWriter.delete(uri, trxDelIn); trxDelIn.commit(); trxDelIn = null; // Using client write and merge Triples within different transaction. // Rollback the merge transaction. trxIn = writerClient.openTransaction(); trxInMergeGraph = writerClient.openTransaction(); gmWriter.write(uri, filehandle.withMimetype(RDFMimeTypes.RDFJSON), trxIn); trxIn.commit(); // Make sure that original triples are available. handle = gmWriter.read(uri, new FileHandle()); readFile = handle.get(); expectedContent = convertFileToString(readFile); assertTrue("Did not write Quad in transaction", expectedContent.contains("<http://example.com/ns/person#firstName")); handle = null; readFile = null; expectedContent = null; // Merge Graphs inside the transaction. gmWriter.mergeGraphs(new StringHandle(ntriple6).withMimetype(RDFMimeTypes.NQUADS), trxInMergeGraph); trxInMergeGraph.rollback(); handle = gmWriter.read(uri, new FileHandle()); readFile = handle.get(); expectedContent = convertFileToString(readFile); // Verify if original quad is available. assertTrue("Merge corrupted original Quad in transaction", expectedContent.contains("<http://example.com/ns/person#firstName")); assertFalse("Did merge Quad when it should not have, since transaction was rolled back", expectedContent.contains("<http://example.com/mergeQuadP")); trxIn = null; trxInMergeGraph = null; handle = null; readFile = null; expectedContent = null; // Delete Graphs inside the transaction. trxDelIn = writerClient.openTransaction(); gmWriter.delete(uri, trxDelIn); trxDelIn.commit(); trxDelIn = null; // Using client write and merge Triples within different transaction. // Rollback the merge transaction and then commit. trxIn = writerClient.openTransaction(); trxInMergeGraph = writerClient.openTransaction(); gmWriter.write(uri, filehandle.withMimetype(RDFMimeTypes.RDFJSON), trxIn); trxIn.commit(); // Make sure that original triples are available. handle = gmWriter.read(uri, new FileHandle()); readFile = handle.get(); expectedContent = convertFileToString(readFile); assertTrue("Did not write Quad in transaction", expectedContent.contains("<http://example.com/ns/person#firstName")); handle = null; readFile = null; expectedContent = null; // Merge Graphs inside the transaction. gmWriter.mergeGraphs(new StringHandle(ntriple6).withMimetype(RDFMimeTypes.NQUADS), trxInMergeGraph); // Rollback the merge. trxInMergeGraph.rollback(); handle = gmWriter.read(uri, new FileHandle()); readFile = handle.get(); expectedContent = convertFileToString(readFile); // Verify if original quad is available. assertTrue("Merge corrupted original Quad in transaction", expectedContent.contains("<http://example.com/ns/person#firstName")); assertFalse("Did merge Quad when it should not have, since transaction was rolled back", expectedContent.contains("<http://example.com/mergeQuadP")); trxIn = null; trxInMergeGraph = null; handle = null; readFile = null; expectedContent = null; trxInMergeGraph = writerClient.openTransaction(); gmWriter.mergeGraphs(new StringHandle(ntriple6).withMimetype(RDFMimeTypes.NQUADS), trxInMergeGraph); // Commit the merge. trxInMergeGraph.commit(); handle = gmWriter.read(uri, new FileHandle()); readFile = handle.get(); expectedContent = convertFileToString(readFile); // Verify if original quad is available. assertTrue("Merge corrupted original Quad in transaction", expectedContent.contains("<http://example.com/ns/person#firstName")); assertTrue("Did not merge Quad in second commit transaction", expectedContent.contains("<http://example.com/mergeQuadP")); // Delete Graphs inside the transaction. trxDelIn = writerClient.openTransaction(); gmWriter.delete(uri, trxDelIn); trxDelIn.commit(); waitForPropertyPropagate(); trxDelIn = null; trxIn = null; trxInMergeGraph = null; handle = null; readFile = null; expectedContent = null; } catch (Exception e) { e.printStackTrace(); } finally { if (trxIn != null) { trxIn.rollback(); trxIn = null; } if (trxDelIn != null) { trxDelIn.rollback(); trxDelIn = null; } if (trxInMergeGraph != null) { trxInMergeGraph.rollback(); trxInMergeGraph = null; } } } /* * Write Triples of Type JSON replace NTriples into the same graph and * validate replaceGraphs with transactions. * * Replace within same write transaction Write and replace Triples within * different transactions. Commit the replace transaction Write and replace * Triples within different transactions. Rollback the replace transaction * Write and replace Triples within different transactions. Rollback the * replace transaction and then commit. */ @Test public void testReplaceGraphWithTransaction() throws FileNotFoundException, InterruptedException { String uri = "http://test.sem.quads/json-quads"; Transaction trxIn = writerClient.openTransaction(); Transaction trxDelIn = null; Transaction trxInReplaceGraph = null; try { String ntriple6 = "<http://example.org/s6> <http://example.com/mergeQuadP> <http://example.org/o2> <http://test.sem.quads/json-quads>."; File file = new File(datasource + "bug25348.json"); FileHandle filehandle = new FileHandle(); filehandle.set(file); // Using client write and replace Triples within same transaction. gmWriter.write(uri, filehandle.withMimetype(RDFMimeTypes.RDFJSON), trxIn); // Replace Graphs inside the transaction. gmWriter.replaceGraphs(new StringHandle(ntriple6).withMimetype(RDFMimeTypes.NQUADS), trxIn); trxIn.commit(); FileHandle handle = gmWriter.read(uri, new FileHandle()); File readFile = handle.get(); String expectedContent = convertFileToString(readFile); // Should not contain original triples assertFalse("Did not replace Quad", expectedContent.contains("http://example.com/ns/person#firstName")); // Should contain new triples assertTrue("Did not replace Quad", expectedContent.contains("<http://example.com/mergeQuadP")); trxIn = null; handle = null; readFile = null; expectedContent = null; // Delete Graphs inside the transaction. trxDelIn = writerClient.openTransaction(); gmWriter.delete(uri, trxDelIn); trxDelIn.commit(); trxDelIn = null; // Using client write and replace Triples within different transactions. // Commit the replace transaction trxIn = writerClient.openTransaction(); gmWriter.write(uri, filehandle.withMimetype(RDFMimeTypes.RDFJSON), trxIn); trxIn.commit(); handle = gmWriter.read(uri, new FileHandle()); readFile = handle.get(); expectedContent = convertFileToString(readFile); // Should contain original triples assertTrue("Write Quad not successful", expectedContent.contains("http://example.com/ns/person#firstName")); // Replace Graphs inside another transaction. trxInReplaceGraph = writerClient.openTransaction(); gmWriter.replaceGraphs(new StringHandle(ntriple6).withMimetype(RDFMimeTypes.NQUADS), trxInReplaceGraph); trxInReplaceGraph.commit(); handle = null; readFile = null; expectedContent = null; handle = gmWriter.read(uri, new FileHandle()); readFile = handle.get(); expectedContent = convertFileToString(readFile); // Should not contain original triples assertFalse("Did not replace Quad", expectedContent.contains("http://example.com/ns/person#firstName")); // Should contain new triples assertTrue("Did not replace Quad", expectedContent.contains("<http://example.com/mergeQuadP")); trxIn = null; trxInReplaceGraph = null; handle = null; readFile = null; expectedContent = null; trxDelIn = null; // Delete Graphs inside the transaction. trxDelIn = writerClient.openTransaction(); gmWriter.delete(uri, trxDelIn); trxDelIn.commit(); // Using client write and replace Triples within different transaction. // Rollback the replace transaction. trxIn = writerClient.openTransaction(); trxInReplaceGraph = writerClient.openTransaction(); gmWriter.write(uri, filehandle.withMimetype(RDFMimeTypes.RDFJSON), trxIn); trxIn.commit(); handle = gmWriter.read(uri, new FileHandle()); readFile = handle.get(); expectedContent = convertFileToString(readFile); // Should contain original triples assertTrue("Write Quad not successful", expectedContent.contains("http://example.com/ns/person#firstName")); handle = null; readFile = null; expectedContent = null; // Replace Graphs inside the transaction. gmWriter.replaceGraphs(new StringHandle(ntriple6).withMimetype(RDFMimeTypes.NQUADS), trxInReplaceGraph); trxInReplaceGraph.rollback(); handle = gmWriter.read(uri, new FileHandle()); readFile = handle.get(); expectedContent = convertFileToString(readFile); // Should not contain original triples assertTrue("Original Quad not available after transaction rolled back", expectedContent.contains("http://example.com/ns/person#firstName")); // Should contain new triples assertFalse("Did not replace Quad", expectedContent.contains("<http://example.com/mergeQuadP")); trxIn = null; trxInReplaceGraph = null; handle = null; readFile = null; expectedContent = null; // Delete Graphs inside the transaction. trxDelIn = writerClient.openTransaction(); gmWriter.delete(uri, trxDelIn); trxDelIn.commit(); trxDelIn = null; // Using client write and replace Triples within different transaction. // Rollback the replace transaction and then commit. trxIn = writerClient.openTransaction(); trxInReplaceGraph = writerClient.openTransaction(); gmWriter.write(uri, filehandle.withMimetype(RDFMimeTypes.RDFJSON), trxIn); trxIn.commit(); handle = gmWriter.read(uri, new FileHandle()); readFile = handle.get(); expectedContent = convertFileToString(readFile); // Should contain original triples assertTrue("Write Quad not successful", expectedContent.contains("http://example.com/ns/person#firstName")); handle = null; readFile = null; expectedContent = null; // Replace Graphs inside the transaction. gmWriter.replaceGraphs(new StringHandle(ntriple6).withMimetype(RDFMimeTypes.NQUADS), trxInReplaceGraph); trxInReplaceGraph.rollback(); handle = gmWriter.read(uri, new FileHandle()); readFile = handle.get(); expectedContent = convertFileToString(readFile); // Should not contain original triples assertTrue("Original Quad not available after transaction rolled back", expectedContent.contains("http://example.com/ns/person#firstName")); // Should contain new triples assertFalse("Did not replace Quad", expectedContent.contains("<http://example.com/mergeQuadP")); trxIn = null; trxInReplaceGraph = null; handle = null; readFile = null; expectedContent = null; trxInReplaceGraph = writerClient.openTransaction(); gmWriter.replaceGraphs(new StringHandle(ntriple6).withMimetype(RDFMimeTypes.NQUADS), trxInReplaceGraph); trxInReplaceGraph.commit(); handle = gmWriter.read(uri, new FileHandle()); readFile = handle.get(); expectedContent = convertFileToString(readFile); // Should not contain original triples assertFalse("Did not replace Quad", expectedContent.contains("http://example.com/ns/person#firstName")); // Should contain new triples assertTrue("Did not replace Quad", expectedContent.contains("<http://example.com/mergeQuadP")); // Delete Graphs inside the transaction. trxDelIn = writerClient.openTransaction(); gmWriter.delete(uri, trxDelIn); trxDelIn.commit(); waitForPropertyPropagate(); trxDelIn = null; handle = null; readFile = null; expectedContent = null; trxInReplaceGraph = null; } catch (Exception e) { e.printStackTrace(); } finally { if (trxIn != null) { trxIn.rollback(); trxIn = null; } if (trxDelIn != null) { trxDelIn.rollback(); trxDelIn = null; } if (trxInReplaceGraph != null) { trxInReplaceGraph.rollback(); trxInReplaceGraph = null; } } } }
3e152c5ee7c1734a6b3ad770d2fed34e3633971d
546
java
Java
settings-api/src/main/java/com/networkedassets/autodoc/transformer/settings/SettingsException.java
NetworkedAssets/autodoc
c84fafd441283309302aa5841e10d0879f81f4bb
[ "Apache-2.0" ]
null
null
null
settings-api/src/main/java/com/networkedassets/autodoc/transformer/settings/SettingsException.java
NetworkedAssets/autodoc
c84fafd441283309302aa5841e10d0879f81f4bb
[ "Apache-2.0" ]
null
null
null
settings-api/src/main/java/com/networkedassets/autodoc/transformer/settings/SettingsException.java
NetworkedAssets/autodoc
c84fafd441283309302aa5841e10d0879f81f4bb
[ "Apache-2.0" ]
null
null
null
21
68
0.686813
8,996
package com.networkedassets.autodoc.transformer.settings; /** * Exception used in settings-api module */ public class SettingsException extends Exception { private static final long serialVersionUID = -6940807414905117174L; public SettingsException() { super(); } public SettingsException(String message) { super(message); } public SettingsException(String message, Throwable cause) { super(message, cause); } public SettingsException(Throwable cause) { super(cause); } }
3e152d152e0a38ba1db6ab8dad013550e7065544
666
java
Java
client/src/class224.java
EtherealCrip/TestServer1
30d5298b471b94daddb7531c13aa069ed5e1b4bd
[ "Apache-2.0" ]
null
null
null
client/src/class224.java
EtherealCrip/TestServer1
30d5298b471b94daddb7531c13aa069ed5e1b4bd
[ "Apache-2.0" ]
null
null
null
client/src/class224.java
EtherealCrip/TestServer1
30d5298b471b94daddb7531c13aa069ed5e1b4bd
[ "Apache-2.0" ]
null
null
null
30.272727
84
0.687688
8,997
public class class224 { public static String field2811 = "Please visit the support page for assistance."; public static String field2961 = "Please visit the support page for assistance."; public static String field2942 = ""; public static String field3027 = "Page has opened in a new window."; public static String field2768 = "(Please check your popup blocker.)"; static void method4120(class217 class217_0, int i_1) { if (class217_0.field2702 == client.field741) { client.field843[class217_0.field2701] = true; } } static void method4121(int i_0) { client.field791 = 0; client.field674 = false; } }
3e152d927219cf0bdcfda291527aa09a919ff451
1,082
java
Java
service/service_edu/src/main/java/com/atguigu/eduservice/controller/EduSubjectController.java
guoyd000/guli_parent
30fc7308be858dd88c8f0ec23052cd6156272bdd
[ "Apache-2.0" ]
1
2022-02-08T07:51:42.000Z
2022-02-08T07:51:42.000Z
service/service_edu/src/main/java/com/atguigu/eduservice/controller/EduSubjectController.java
AltonHuo/guli_parent
30fc7308be858dd88c8f0ec23052cd6156272bdd
[ "Apache-2.0" ]
null
null
null
service/service_edu/src/main/java/com/atguigu/eduservice/controller/EduSubjectController.java
AltonHuo/guli_parent
30fc7308be858dd88c8f0ec23052cd6156272bdd
[ "Apache-2.0" ]
1
2022-02-08T07:51:41.000Z
2022-02-08T07:51:41.000Z
22.541667
69
0.711645
8,998
package com.atguigu.eduservice.controller; import com.atguigu.commonutils.R; import com.atguigu.eduservice.entity.subject.OneSubject; import com.atguigu.eduservice.service.EduSubjectService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.util.List; /** * <p> * 课程科目 前端控制器 * </p> * * @author 王柳 * @since 2020-06-10 */ @RestController @RequestMapping("/eduservice/subject") //@CrossOrigin public class EduSubjectController { @Autowired private EduSubjectService subjectService; //添加课程分类 //获取上传过来文件,把文件内容读取出来 @PostMapping("addSubject") public R addSubject(MultipartFile file) { //上传过来excel文件 subjectService.saveSubject(file, subjectService); return R.ok(); } //课程分类列表(树形) @GetMapping("getAllSubject") public R getAllSubject() { //list集合泛型是一级分类 List<OneSubject> list = subjectService.getAllOneTwoSubject(); return R.ok().data("list",list); } }
3e152da190341b6dcf5ac6b143bedfc9872e962c
7,120
java
Java
netreflected/bouncycastle_netcore_1_8_3_0/src/net6.0/bouncycastle.crypto_version_1.8.2.0_culture_neutral_publickeytoken_null/org/bouncycastle/crypto/tls/TlsClient.java
masesdevelopers/NuReflector
bf25df84c211e66821a503d4588ab22c99e26c7f
[ "MIT" ]
null
null
null
netreflected/bouncycastle_netcore_1_8_3_0/src/net6.0/bouncycastle.crypto_version_1.8.2.0_culture_neutral_publickeytoken_null/org/bouncycastle/crypto/tls/TlsClient.java
masesdevelopers/NuReflector
bf25df84c211e66821a503d4588ab22c99e26c7f
[ "MIT" ]
7
2021-11-14T02:18:03.000Z
2022-03-30T17:38:29.000Z
netreflected/bouncycastle_netcore_1_8_3_0/src/net6.0/bouncycastle.crypto_version_1.8.2.0_culture_neutral_publickeytoken_null/org/bouncycastle/crypto/tls/TlsClient.java
masesdevelopers/NuReflector
bf25df84c211e66821a503d4588ab22c99e26c7f
[ "MIT" ]
1
2021-11-16T00:08:00.000Z
2021-11-16T00:08:00.000Z
38.27957
199
0.732725
8,999
/* * MIT License * * Copyright (c) 2022 MASES s.r.l. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /************************************************************************************** * <auto-generated> * This code was generated from a template using JCOReflector * * Manual changes to this file may cause unexpected behavior in your application. * Manual changes to this file will be overwritten if the code is regenerated. * </auto-generated> *************************************************************************************/ package org.bouncycastle.crypto.tls; import org.mases.jcobridge.*; import org.mases.jcobridge.netreflection.*; // Import section import org.bouncycastle.crypto.tls.TlsPeer; import org.bouncycastle.crypto.tls.TlsPeerImplementation; import org.bouncycastle.crypto.tls.TlsAuthentication; import org.bouncycastle.crypto.tls.TlsAuthenticationImplementation; import org.bouncycastle.crypto.tls.TlsCipher; import org.bouncycastle.crypto.tls.TlsCipherImplementation; import org.bouncycastle.crypto.tls.TlsCompression; import org.bouncycastle.crypto.tls.TlsCompressionImplementation; import org.bouncycastle.crypto.tls.TlsKeyExchange; import org.bouncycastle.crypto.tls.TlsKeyExchangeImplementation; import org.bouncycastle.crypto.tls.TlsSession; import org.bouncycastle.crypto.tls.TlsSessionImplementation; import system.collections.IDictionary; import system.collections.IDictionaryImplementation; import system.collections.IList; import system.collections.IListImplementation; import org.bouncycastle.crypto.tls.TlsClientContext; import org.bouncycastle.crypto.tls.TlsClientContextImplementation; import org.bouncycastle.crypto.tls.NewSessionTicket; import org.bouncycastle.crypto.tls.ProtocolVersion; /** * The base .NET class managing Org.BouncyCastle.Crypto.Tls.TlsClient, BouncyCastle.Crypto, Version=1.8.2.0, Culture=neutral, PublicKeyToken=null. * <p> * * See: <a href="https://docs.microsoft.com/en-us/dotnet/api/Org.BouncyCastle.Crypto.Tls.TlsClient" target="_top">https://docs.microsoft.com/en-us/dotnet/api/Org.BouncyCastle.Crypto.Tls.TlsClient</a> */ public interface TlsClient extends IJCOBridgeReflected, TlsPeer { /** * Fully assembly qualified name: BouncyCastle.Crypto, Version=1.8.2.0, Culture=neutral, PublicKeyToken=null */ public static final String assemblyFullName = "BouncyCastle.Crypto, Version=1.8.2.0, Culture=neutral, PublicKeyToken=null"; /** * Assembly name: BouncyCastle.Crypto */ public static final String assemblyShortName = "BouncyCastle.Crypto"; /** * Qualified class name: Org.BouncyCastle.Crypto.Tls.TlsClient */ public static final String className = "Org.BouncyCastle.Crypto.Tls.TlsClient"; /** * Try to cast the {@link IJCOBridgeReflected} instance into {@link TlsClient}, a cast assert is made to check if types are compatible. * @param from {@link IJCOBridgeReflected} instance to be casted * @return {@link TlsClient} instance * @throws java.lang.Throwable in case of error during cast operation */ public static TlsClient ToTlsClient(IJCOBridgeReflected from) throws Throwable { JCOBridge bridge = JCOBridgeInstance.getInstance("BouncyCastle.Crypto, Version=1.8.2.0, Culture=neutral, PublicKeyToken=null"); JCType classType = bridge.GetType(className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName)); NetType.AssertCast(classType, from); return new TlsClientImplementation(from.getJCOInstance()); } /** * Returns the reflected Assembly name * * @return A {@link String} representing the Fullname of reflected Assembly */ public String getJCOAssemblyName(); /** * Returns the reflected Class name * * @return A {@link String} representing the Fullname of reflected Class */ public String getJCOClassName(); /** * Returns the reflected Class name used to build the object * * @return A {@link String} representing the name used to allocated the object * in CLR context */ public String getJCOObjectName(); /** * Returns the instantiated class * * @return An {@link java.lang.Object} representing the instance of the instantiated Class */ public java.lang.Object getJCOInstance(); /** * Returns the instantiated class Type * * @return A {@link JCType} representing the Type of the instantiated Class */ public JCType getJCOType(); // Methods section public byte[] GetCompressionMethods() throws Throwable; public int[] GetCipherSuites() throws Throwable; public TlsAuthentication GetAuthentication() throws Throwable; public TlsKeyExchange GetKeyExchange() throws Throwable; public TlsSession GetSessionToResume() throws Throwable; public IDictionary GetClientExtensions() throws Throwable; public IList GetClientSupplementalData() throws Throwable; public void Init(TlsClientContext context) throws Throwable; public void NotifyNewSessionTicket(NewSessionTicket newSessionTicket) throws Throwable; public void NotifySelectedCipherSuite(int selectedCipherSuite) throws Throwable; public void NotifySelectedCompressionMethod(byte selectedCompressionMethod) throws Throwable; public void NotifyServerVersion(ProtocolVersion selectedVersion) throws Throwable; public void NotifySessionID(byte[] sessionID) throws Throwable; public void NotifySessionID(JCORefOut dupParam0) throws Throwable; public void ProcessServerExtensions(IDictionary serverExtensions) throws Throwable; public void ProcessServerSupplementalData(IList serverSupplementalData) throws Throwable; // Properties section public boolean getIsFallback() throws Throwable; public ProtocolVersion getClientHelloRecordLayerVersion() throws Throwable; public ProtocolVersion getClientVersion() throws Throwable; // Instance Events section }
3e152ec3ecd0148087a7fde2e09379cf51fd57f4
5,794
java
Java
src/main/java/com/timic/excel2sql/Main.java
Timic3/Excel2SQL
ec0e6b0e80513d9675cbd98286d301e1cd7f2089
[ "Apache-2.0" ]
null
null
null
src/main/java/com/timic/excel2sql/Main.java
Timic3/Excel2SQL
ec0e6b0e80513d9675cbd98286d301e1cd7f2089
[ "Apache-2.0" ]
null
null
null
src/main/java/com/timic/excel2sql/Main.java
Timic3/Excel2SQL
ec0e6b0e80513d9675cbd98286d301e1cd7f2089
[ "Apache-2.0" ]
null
null
null
31.835165
120
0.612358
9,000
package com.timic.excel2sql; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.net.URLDecoder; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import com.timic.excel2sql.components.Column; import com.timic.excel2sql.components.Data; import com.timic.excel2sql.components.Table; public class Main { public static void main(String[] args) { if (args.length < 1) { System.err.println("Argument for path to Excel not found."); System.exit(0); } InputStream excelFile; try { excelFile = new FileInputStream(args[0]); Workbook excel = new XSSFWorkbook(excelFile); ArrayList<Table> tables = new ArrayList<Table>(); for (int i = 0; i < excel.getNumberOfSheets(); i++) { Sheet sheet = excel.getSheetAt(i); String sheetName = sheet.getSheetName(); Table table = new Table(sheetName); tables.add(table); if (!sheetName.isEmpty()) { Iterator<Row> rows = sheet.rowIterator(); boolean canGo = false; int realRowIndex = 0; while (rows.hasNext()) { Row row = rows.next(); Iterator<Cell> cells = row.cellIterator(); Data data = new Data(); while (cells.hasNext()) { canGo = true; Cell cell = cells.next(); String cellName; if (cell.getCellTypeEnum() == CellType.NUMERIC) { // Decimal support double numericCell = cell.getNumericCellValue(); if (numericCell == Math.floor(numericCell)) { cellName = String.valueOf((int) cell.getNumericCellValue()); } else { cellName = String.valueOf(cell.getNumericCellValue()); } } else if (cell.getCellTypeEnum() == CellType.STRING) { cellName = cell.getStringCellValue(); } else if (cell.getCellTypeEnum() == CellType.BOOLEAN) { cellName = String.valueOf(cell.getBooleanCellValue()); } else { cellName = cell.getStringCellValue(); } if (!cellName.isEmpty()) { if (realRowIndex == 0) { // Column names String columnType = sheet.getRow(row.getRowNum() + 1) .getCell(cell.getColumnIndex()) .getStringCellValue(); table.addColumn(cellName, columnType); } else if (realRowIndex == 1) { // Column types continue; } else { // Data data.addData(cellName); } } } if (canGo) { realRowIndex++; if (data.data.size() != 0) { table.rows.add(data); } } } } } excel.close(); // Generate SQL code String path = Main.class.getProtectionDomain().getCodeSource().getLocation().getPath(); String decodedPath = URLDecoder.decode(path.substring(1, path.lastIndexOf("/") + 1), "UTF-8"); File outFile = new File(decodedPath + args[0].substring(0, args[0].lastIndexOf(".")) + ".sql"); System.out.println("SQL code extracted to " + decodedPath + args[0].substring(0, args[0].lastIndexOf(".")) + ".sql"); outFile.createNewFile(); PrintWriter writer = new PrintWriter(outFile); for (int tableIndex = 0; tableIndex < tables.size(); tableIndex++) { Table table = tables.get(tableIndex); String tableQuery = ""; tableQuery += "CREATE TABLE " + table.getName() + " (\n"; for (int columnIndex = 0; columnIndex < table.columns.size(); columnIndex++) { Column column = table.columns.get(columnIndex); tableQuery += "\t" + column.getName() + " " + column.getType(); if (column.getSize() != -1) { tableQuery += "(" + column.getSize() + ")"; } if (columnIndex < table.columns.size() - 1) { tableQuery += ",\n"; } } tableQuery += "\n);"; writer.println(tableQuery); writer.println(); for (int rowIndex = 0; rowIndex < table.rows.size(); rowIndex++) { String insertQuery = "INSERT INTO " + table.getName() + "\n("; for (int columnIndex = 0; columnIndex < table.columns.size(); columnIndex++) { Column column = table.columns.get(columnIndex); insertQuery += column.getName(); if (columnIndex < table.columns.size() - 1) { insertQuery += ", "; } } insertQuery += ")"; insertQuery += " VALUES\n("; Data data = table.rows.get(rowIndex); for (int dataIndex = 0; dataIndex < data.data.size(); dataIndex++) { String rowData = data.data.get(dataIndex); if (table.columns.get(dataIndex).isNumeric()) { insertQuery += rowData; } else if (table.columns.get(dataIndex).isDate()) { Date date = DateUtil.getJavaDate(Double.valueOf(rowData)); String formattedDate = new SimpleDateFormat("dd.MM.yyyy").format(date); insertQuery += "TO_DATE('" + formattedDate + "', 'dd.MM.yyyy')"; } else { insertQuery += "'" + rowData + "'"; } if (dataIndex < table.columns.size() - 1) { insertQuery += ", "; } } insertQuery += ");"; writer.println(insertQuery); writer.println(); } writer.println(); writer.println(); writer.println(); } writer.flush(); writer.close(); } catch (FileNotFoundException e) { System.err.println("File not found."); } catch (IOException e) { System.err.println("Unknown IO error."); } } }
3e152f62f8df0c08b3d662cf03479d011a7cd2d3
617
java
Java
ruoyi-common/src/main/java/com/ruoyi/common/exception/life/system/ChartDateException.java
tabbbbb/life_classroom
3f24c6594a070381eecfa6a283c1c43f9c6990ad
[ "MIT" ]
null
null
null
ruoyi-common/src/main/java/com/ruoyi/common/exception/life/system/ChartDateException.java
tabbbbb/life_classroom
3f24c6594a070381eecfa6a283c1c43f9c6990ad
[ "MIT" ]
2
2021-04-22T17:01:07.000Z
2021-09-20T20:54:12.000Z
ruoyi-common/src/main/java/com/ruoyi/common/exception/life/system/ChartDateException.java
tabbbbb/life_classroom
3f24c6594a070381eecfa6a283c1c43f9c6990ad
[ "MIT" ]
null
null
null
20.566667
62
0.602917
9,001
/** * Copyright (C), 2019, 蓝煌信息科技公司 * FileName: ChartDateException * Author: Administrator * Date: 2019/12/27 0027 15:46 * Description: * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ package com.ruoyi.common.exception.life.system; import com.ruoyi.common.response.UserResponse; /** * 〈一句话功能简述〉<br> * 〈〉 * * @author Administrator * @create 2019/12/27 0027 * @since 1.0.0 */ public class ChartDateException extends RuntimeException { public ChartDateException(String errmsg){ super(errmsg); } }
3e1530fa8daa010954c78ac02234cd1c2510d1d2
8,829
java
Java
sources/zafira-web/src/main/java/com/qaprosoft/zafira/web/LauncherController.java
VVmartseniuk/zafira
3ef62d09228257e0cda2cd8c7398601aa7e9d058
[ "Apache-2.0" ]
null
null
null
sources/zafira-web/src/main/java/com/qaprosoft/zafira/web/LauncherController.java
VVmartseniuk/zafira
3ef62d09228257e0cda2cd8c7398601aa7e9d058
[ "Apache-2.0" ]
null
null
null
sources/zafira-web/src/main/java/com/qaprosoft/zafira/web/LauncherController.java
VVmartseniuk/zafira
3ef62d09228257e0cda2cd8c7398601aa7e9d058
[ "Apache-2.0" ]
null
null
null
48.779006
181
0.697587
9,002
/******************************************************************************* * Copyright 2013-2019 Qaprosoft (http://www.qaprosoft.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.qaprosoft.zafira.web; import com.qaprosoft.zafira.models.db.JenkinsJob; import com.qaprosoft.zafira.models.db.Launcher; import com.qaprosoft.zafira.models.db.LauncherWebHookPayload; import com.qaprosoft.zafira.models.dto.JenkinsJobsScanResultDTO; import com.qaprosoft.zafira.models.dto.JobResult; import com.qaprosoft.zafira.models.dto.LauncherDTO; import com.qaprosoft.zafira.models.dto.LauncherScannerType; import com.qaprosoft.zafira.models.push.LauncherPush; import com.qaprosoft.zafira.models.push.LauncherRunPush; import com.qaprosoft.zafira.service.LauncherService; import com.qaprosoft.zafira.web.documented.LauncherDocumentedController; import org.dozer.Mapper; import org.springframework.http.MediaType; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; @CrossOrigin @RequestMapping(path = "api/launchers", produces = MediaType.APPLICATION_JSON_VALUE) @RestController public class LauncherController extends AbstractController implements LauncherDocumentedController { private final LauncherService launcherService; private final Mapper mapper; private final SimpMessagingTemplate websocketTemplate; public LauncherController(LauncherService launcherService, Mapper mapper, SimpMessagingTemplate websocketTemplate) { this.launcherService = launcherService; this.mapper = mapper; this.websocketTemplate = websocketTemplate; } @PreAuthorize("hasPermission('MODIFY_LAUNCHERS')") @PostMapping() @Override public LauncherDTO createLauncher(@RequestBody @Valid LauncherDTO launcherDTO, @RequestParam(name = "automationServerId", required = false) Long automationServerId) { Launcher launcher = mapper.map(launcherDTO, Launcher.class); Long principalId = getPrincipalId(); launcher = launcherService.createLauncher(launcher, principalId, automationServerId); return mapper.map(launcher, LauncherDTO.class); } @PreAuthorize("hasAnyPermission('MODIFY_LAUNCHERS', 'VIEW_LAUNCHERS')") @GetMapping("/{id}") @Override public LauncherDTO getLauncherById(@PathVariable("id") Long id) { Launcher launcher = launcherService.getLauncherById(id); return mapper.map(launcher, LauncherDTO.class); } @PreAuthorize("hasAnyPermission('MODIFY_LAUNCHERS', 'VIEW_LAUNCHERS')") @GetMapping() @Override public List<LauncherDTO> getAllLaunchers() { List<Launcher> launchers = launcherService.getAllLaunchers(); return launchers.stream() .map(launcher -> mapper.map(launcher, LauncherDTO.class)) .collect(Collectors.toList()); } @PreAuthorize("hasPermission('MODIFY_LAUNCHERS')") @PutMapping() @Override public LauncherDTO updateLauncher(@RequestBody @Valid LauncherDTO launcherDTO) { Launcher launcher = mapper.map(launcherDTO, Launcher.class); launcher = launcherService.updateLauncher(launcher); return mapper.map(launcher, LauncherDTO.class); } @PreAuthorize("hasPermission('MODIFY_LAUNCHERS')") @DeleteMapping("/{id}") @Override public void deleteLauncherById(@PathVariable("id") Long id) { launcherService.deleteLauncherById(id); } @PreAuthorize("hasAnyPermission('MODIFY_LAUNCHERS', 'VIEW_LAUNCHERS')") @PostMapping("/build") @Override public void build(@RequestBody @Valid LauncherDTO launcherDTO, @RequestParam(name = "providerId", required = false) Long providerId) throws IOException { Launcher launcher = mapper.map(launcherDTO, Launcher.class); String ciRunId = launcherService.buildLauncherJob(launcher, getPrincipalId(), providerId); websocketTemplate.convertAndSend(getLauncherRunsWebsocketPath(), new LauncherRunPush(launcher, ciRunId)); } @PreAuthorize("hasAnyPermission('MODIFY_LAUNCHERS', 'VIEW_LAUNCHERS')") @PostMapping("/{id}/build/{ref}") @Override public String buildByWebHook( @RequestBody @Valid LauncherWebHookPayload payload, @PathVariable("id") Long id, @PathVariable("ref") String ref, @RequestParam(name = "providerId", required = false) Long providerId ) throws IOException { return launcherService.buildLauncherJobByPresetRef(id, ref, payload, getPrincipalId(), providerId); } @PreAuthorize("hasAnyPermission('MODIFY_LAUNCHERS', 'VIEW_LAUNCHERS')") @GetMapping("/build/number") @Override public Integer getBuildNumber(@RequestParam("queueItemUrl") String queueItemUrl, @RequestParam(name = "automationServerId", required = false) Long automationServerId) { return launcherService.getBuildNumber(queueItemUrl, automationServerId); } @PreAuthorize("hasPermission('MODIFY_LAUNCHERS')") @PostMapping("/scanner") @Override public JobResult runScanner(@RequestBody @Valid LauncherScannerType launcherScannerType, @RequestParam(name = "automationServerId", required = false) Long automationServerId) { return launcherService.buildScannerJob( getPrincipalId(), launcherScannerType.getBranch(), launcherScannerType.getScmAccountId(), launcherScannerType.isRescan(), automationServerId ); } @PreAuthorize("hasPermission('MODIFY_LAUNCHERS')") @DeleteMapping("/scanner/{buildNumber}") @Override public void cancelScanner(@PathVariable("buildNumber") int buildNumber, @RequestParam("scmAccountId") Long scmAccountId, @RequestParam("rescan") boolean rescan, @RequestParam(name = "automationServerId", required = false) Long automationServerId) { launcherService.abortScannerJob(scmAccountId, buildNumber, rescan, automationServerId); } @PreAuthorize("hasPermission('MODIFY_LAUNCHERS')") @PostMapping("/create") @Override public List<LauncherDTO> scanLaunchersFromJenkins(@RequestBody @Valid JenkinsJobsScanResultDTO jenkinsJobsScanResultDTO) { Long principalId = getPrincipalId(); List<JenkinsJob> jenkinsJobs = jenkinsJobsScanResultDTO.getJenkinsJobs() .stream() .map(jenkinsLauncher -> mapper.map(jenkinsLauncher, JenkinsJob.class)) .collect(Collectors.toList()); List<Launcher> launchers = launcherService.createLaunchersForJenkinsJobs(jenkinsJobs, jenkinsJobsScanResultDTO.getRepo(), jenkinsJobsScanResultDTO.isSuccess(), principalId); List<LauncherDTO> launcherDTOS = launchers.stream() .map(launcher -> mapper.map(launcher, LauncherDTO.class)) .collect(Collectors.toList()); websocketTemplate.convertAndSend(getLaunchersWebsocketPath(), new LauncherPush(launcherDTOS, jenkinsJobsScanResultDTO.getUserId(), jenkinsJobsScanResultDTO.isSuccess())); return launcherDTOS; } }
3e1531c4a4bcce5222062c5ef23609fa82fbe347
7,797
java
Java
xdl-algorithm-solution/ESMM/data/third_party/protobuf/protobuf-3.5.0/java/core/src/main/java/com/google/protobuf/LazyStringList.java
whuaxiom/xdl
44127fa2935d3fbeabb8d88f83dad597f7f50eb0
[ "Apache-2.0" ]
4,071
2018-12-13T04:17:38.000Z
2022-03-30T03:29:35.000Z
xdl-algorithm-solution/ESMM/data/third_party/protobuf/protobuf-3.5.0/java/core/src/main/java/com/google/protobuf/LazyStringList.java
whuaxiom/xdl
44127fa2935d3fbeabb8d88f83dad597f7f50eb0
[ "Apache-2.0" ]
359
2018-12-21T01:14:57.000Z
2022-02-15T07:18:02.000Z
xdl-algorithm-solution/ESMM/data/third_party/protobuf/protobuf-3.5.0/java/core/src/main/java/com/google/protobuf/LazyStringList.java
whuaxiom/xdl
44127fa2935d3fbeabb8d88f83dad597f7f50eb0
[ "Apache-2.0" ]
1,054
2018-12-20T09:57:42.000Z
2022-03-29T07:16:53.000Z
41.026316
80
0.708788
9,003
/* Copyright (C) 2016-2018 Alibaba Group Holding Limited 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. ==============================================================================*/ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. 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.google.protobuf; import java.util.Collection; import java.util.List; /** * An interface extending {@code List<String>} that also provides access to the * items of the list as UTF8-encoded ByteString or byte[] objects. This is * used by the protocol buffer implementation to support lazily converting bytes * parsed over the wire to String objects until needed and also increases the * efficiency of serialization if the String was never requested as the * ByteString or byte[] is already cached. The ByteString methods are used in * immutable API only and byte[] methods used in mutable API only for they use * different representations for string/bytes fields. * * @author ychag@example.com (Jon Perlow) */ public interface LazyStringList extends ProtocolStringList { /** * Returns the element at the specified position in this list as a ByteString. * * @param index index of the element to return * @return the element at the specified position in this list * @throws IndexOutOfBoundsException if the index is out of range * ({@code index < 0 || index >= size()}) */ ByteString getByteString(int index); /** * Returns the element at the specified position in this list as an Object * that will either be a String or a ByteString. * * @param index index of the element to return * @return the element at the specified position in this list * @throws IndexOutOfBoundsException if the index is out of range * ({@code index < 0 || index >= size()}) */ Object getRaw(int index); /** * Returns the element at the specified position in this list as byte[]. * * @param index index of the element to return * @return the element at the specified position in this list * @throws IndexOutOfBoundsException if the index is out of range * ({@code index < 0 || index >= size()}) */ byte[] getByteArray(int index); /** * Appends the specified element to the end of this list (optional * operation). * * @param element element to be appended to this list * @throws UnsupportedOperationException if the <tt>add</tt> operation * is not supported by this list */ void add(ByteString element); /** * Appends the specified element to the end of this list (optional * operation). * * @param element element to be appended to this list * @throws UnsupportedOperationException if the <tt>add</tt> operation * is not supported by this list */ void add(byte[] element); /** * Replaces the element at the specified position in this list with the * specified element (optional operation). * * @param index index of the element to replace * @param element the element to be stored at the specified position * @throws UnsupportedOperationException if the <tt>set</tt> operation * is not supported by this list * IndexOutOfBoundsException if the index is out of range * ({@code index < 0 || index >= size()}) */ void set(int index, ByteString element); /** * Replaces the element at the specified position in this list with the * specified element (optional operation). * * @param index index of the element to replace * @param element the element to be stored at the specified position * @throws UnsupportedOperationException if the <tt>set</tt> operation * is not supported by this list * IndexOutOfBoundsException if the index is out of range * ({@code index < 0 || index >= size()}) */ void set(int index, byte[] element); /** * Appends all elements in the specified ByteString collection to the end of * this list. * * @param c collection whose elements are to be added to this list * @return true if this list changed as a result of the call * @throws UnsupportedOperationException if the <tt>addAllByteString</tt> * operation is not supported by this list */ boolean addAllByteString(Collection<? extends ByteString> c); /** * Appends all elements in the specified byte[] collection to the end of * this list. * * @param c collection whose elements are to be added to this list * @return true if this list changed as a result of the call * @throws UnsupportedOperationException if the <tt>addAllByteArray</tt> * operation is not supported by this list */ boolean addAllByteArray(Collection<byte[]> c); /** * Returns an unmodifiable List of the underlying elements, each of which is * either a {@code String} or its equivalent UTF-8 encoded {@code ByteString} * or byte[]. It is an error for the caller to modify the returned * List, and attempting to do so will result in an * {@link UnsupportedOperationException}. */ List<?> getUnderlyingElements(); /** * Merges all elements from another LazyStringList into this one. This method * differs from {@link #addAll(Collection)} on that underlying byte arrays are * copied instead of reference shared. Immutable API doesn't need to use this * method as byte[] is not used there at all. */ void mergeFrom(LazyStringList other); /** * Returns a mutable view of this list. Changes to the view will be made into * the original list. This method is used in mutable API only. */ List<byte[]> asByteArrayList(); /** Returns an unmodifiable view of the list. */ LazyStringList getUnmodifiableView(); }
3e1532670936b266cd105181a7231c74588cc266
2,947
java
Java
jbpm-console-ng-process-runtime/jbpm-console-ng-process-runtime-client/src/main/java/org/jbpm/console/ng/pr/client/editors/definition/details/multi/basic/BasicProcessDefDetailsMultiViewImpl.java
livthomas/jbpm-console-ng
986ff075e93ffa192070ce418bc12a7135595da2
[ "Apache-2.0" ]
null
null
null
jbpm-console-ng-process-runtime/jbpm-console-ng-process-runtime-client/src/main/java/org/jbpm/console/ng/pr/client/editors/definition/details/multi/basic/BasicProcessDefDetailsMultiViewImpl.java
livthomas/jbpm-console-ng
986ff075e93ffa192070ce418bc12a7135595da2
[ "Apache-2.0" ]
null
null
null
jbpm-console-ng-process-runtime/jbpm-console-ng-process-runtime-client/src/main/java/org/jbpm/console/ng/pr/client/editors/definition/details/multi/basic/BasicProcessDefDetailsMultiViewImpl.java
livthomas/jbpm-console-ng
986ff075e93ffa192070ce418bc12a7135595da2
[ "Apache-2.0" ]
null
null
null
31.351064
105
0.721072
9,004
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jbpm.console.ng.pr.client.editors.definition.details.multi.basic; import javax.enterprise.context.Dependent; import com.google.gwt.core.client.GWT; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Widget; import org.gwtbootstrap3.client.ui.NavTabs; import org.gwtbootstrap3.client.ui.TabContent; import org.gwtbootstrap3.client.ui.TabListItem; import org.gwtbootstrap3.client.ui.TabPane; import org.jbpm.console.ng.pr.client.editors.definition.details.multi.BaseProcessDefDetailsMultiViewImpl; import org.jbpm.console.ng.pr.client.i18n.Constants; @Dependent public class BasicProcessDefDetailsMultiViewImpl extends BaseProcessDefDetailsMultiViewImpl implements BasicProcessDefDetailsMultiPresenter.BasicProcessDefDetailsMultiView { interface Binder extends UiBinder<Widget, BasicProcessDefDetailsMultiViewImpl> { } @UiField NavTabs navTabs; @UiField TabContent tabContent; private static Binder uiBinder = GWT.create( Binder.class ); private BasicProcessDefDetailsMultiPresenter presenter; private TabPane definitionDetailsPane; private TabListItem definitionDetailsTab; @Override public void init( final BasicProcessDefDetailsMultiPresenter presenter ) { this.presenter = presenter; initWidget( uiBinder.createAndBindUi( this ) ); initTabs(); } protected void initTabs() { definitionDetailsPane = new TabPane() {{ add( getTabView() ); setActive( true ); }}; definitionDetailsTab = new TabListItem( Constants.INSTANCE.Definition_Details() ) {{ setDataTargetWidget( definitionDetailsPane ); addStyleName( "uf-dropdown-tab-list-item" ); setActive( true ); }}; navTabs.add( definitionDetailsTab ); tabContent.add( definitionDetailsPane ); } @Override protected IsWidget getTabView() { return presenter.getTabView(); } @Override protected void closeDetails() { presenter.closeDetails(); } @Override protected void createNewProcessInstance() { presenter.createNewProcessInstance(); } }
3e1532c60f8a46efa23332bbdc8bc865af64ab88
891
java
Java
superman-workflow-api/src/main/java/com/codi/superman/workflow/domain/SysBizWorkFlow.java
xiaobxiaWarehouse/superman-base
45f3941414556d3a5c703efef93e003b98df708b
[ "MIT" ]
null
null
null
superman-workflow-api/src/main/java/com/codi/superman/workflow/domain/SysBizWorkFlow.java
xiaobxiaWarehouse/superman-base
45f3941414556d3a5c703efef93e003b98df708b
[ "MIT" ]
null
null
null
superman-workflow-api/src/main/java/com/codi/superman/workflow/domain/SysBizWorkFlow.java
xiaobxiaWarehouse/superman-base
45f3941414556d3a5c703efef93e003b98df708b
[ "MIT" ]
2
2017-09-01T13:52:54.000Z
2019-04-13T03:41:12.000Z
19.369565
52
0.719416
9,005
package com.codi.superman.workflow.domain; import com.alibaba.fastjson.annotation.JSONField; import com.codi.base.domain.BaseDomain; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import java.util.Date; /** * 工作流总表 * * @author spy * @date 2017-05-08 15:07 */ @Accessors(chain = true) @NoArgsConstructor @Data public class SysBizWorkFlow extends BaseDomain { private Long id; private Long userId; private String userCode; private Integer state; private String bizType; private String bizKey; @JSONField(format = "yyyy-MM-dd HH:mm:ss") private Date stateDate; @JSONField(format = "yyyy-MM-dd HH:mm:ss") private Date createDate; @JSONField(format = "yyyy-MM-dd HH:mm:ss") private Date updateDate; private String description; private static final long serialVersionUID = 1L; }
3e1532d1701e6a656e61bfc626b536a23927561f
410
java
Java
services/analytics/src/main/java/com/eshop/analytics/AnalyticsApplication.java
velinovskav/e-shop-1
16646131ab3a4d12898d7a5170e6f0e1ab65c2b7
[ "MIT" ]
31
2021-08-17T09:09:22.000Z
2022-03-26T00:36:15.000Z
services/analytics/src/main/java/com/eshop/analytics/AnalyticsApplication.java
velinovskav/e-shop-1
16646131ab3a4d12898d7a5170e6f0e1ab65c2b7
[ "MIT" ]
1
2022-01-04T08:13:43.000Z
2022-01-04T19:36:23.000Z
services/analytics/src/main/java/com/eshop/analytics/AnalyticsApplication.java
velinovskav/e-shop-1
16646131ab3a4d12898d7a5170e6f0e1ab65c2b7
[ "MIT" ]
18
2021-08-06T06:43:32.000Z
2022-02-25T17:26:53.000Z
25.625
68
0.829268
9,006
package com.eshop.analytics; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; @SpringBootApplication @EnableEurekaClient public class AnalyticsApplication { public static void main(String[] args) { SpringApplication.run(AnalyticsApplication.class, args); } }
3e1532d74c891dffb2a84dedde6c016434cdb1fc
24,855
java
Java
compat/src/main/java/androidx/core/app/JobIntentService.java
aosp-caf-upstream/platform_frameworks_support
46bd3eb63bba8f52560a41db3cca3ff607edb7e4
[ "Apache-2.0" ]
992
2015-01-05T03:03:25.000Z
2017-10-10T12:24:28.000Z
compat/src/main/java/androidx/core/app/JobIntentService.java
aosp-caf-upstream/platform_frameworks_support
46bd3eb63bba8f52560a41db3cca3ff607edb7e4
[ "Apache-2.0" ]
22
2018-11-05T22:59:25.000Z
2021-10-17T18:03:34.000Z
compat/src/main/java/androidx/core/app/JobIntentService.java
aosp-caf-upstream/platform_frameworks_support
46bd3eb63bba8f52560a41db3cca3ff607edb7e4
[ "Apache-2.0" ]
499
2015-01-05T02:36:32.000Z
2017-10-09T07:19:05.000Z
38.121166
128
0.608248
9,007
/* * Copyright (C) 2017 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 androidx.core.app; import android.app.Service; import android.app.job.JobInfo; import android.app.job.JobParameters; import android.app.job.JobScheduler; import android.app.job.JobServiceEngine; import android.app.job.JobWorkItem; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Build; import android.os.IBinder; import android.os.PowerManager; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import java.util.ArrayList; import java.util.HashMap; /** * Helper for processing work that has been enqueued for a job/service. When running on * {@link android.os.Build.VERSION_CODES#O Android O} or later, the work will be dispatched * as a job via {@link android.app.job.JobScheduler#enqueue JobScheduler.enqueue}. When running * on older versions of the platform, it will use * {@link android.content.Context#startService Context.startService}. * * <p>You must publish your subclass in your manifest for the system to interact with. This * should be published as a {@link android.app.job.JobService}, as described for that class, * since on O and later platforms it will be executed that way.</p> * * <p>Use {@link #enqueueWork(Context, Class, int, Intent)} to enqueue new work to be * dispatched to and handled by your service. It will be executed in * {@link #onHandleWork(Intent)}.</p> * * <p>You do not need to use {@link androidx.legacy.content.WakefulBroadcastReceiver} * when using this class. When running on {@link android.os.Build.VERSION_CODES#O Android O}, * the JobScheduler will take care of wake locks for you (holding a wake lock from the time * you enqueue work until the job has been dispatched and while it is running). When running * on previous versions of the platform, this wake lock handling is emulated in the class here * by directly calling the PowerManager; this means the application must request the * {@link android.Manifest.permission#WAKE_LOCK} permission.</p> * * <p>There are a few important differences in behavior when running on * {@link android.os.Build.VERSION_CODES#O Android O} or later as a Job vs. pre-O:</p> * * <ul> * <li><p>When running as a pre-O service, the act of enqueueing work will generally start * the service immediately, regardless of whether the device is dozing or in other * conditions. When running as a Job, it will be subject to standard JobScheduler * policies for a Job with a {@link android.app.job.JobInfo.Builder#setOverrideDeadline(long)} * of 0: the job will not run while the device is dozing, it may get delayed more than * a service if the device is under strong memory pressure with lots of demand to run * jobs.</p></li> * <li><p>When running as a pre-O service, the normal service execution semantics apply: * the service can run indefinitely, though the longer it runs the more likely the system * will be to outright kill its process, and under memory pressure one should expect * the process to be killed even of recently started services. When running as a Job, * the typical {@link android.app.job.JobService} execution time limit will apply, after * which the job will be stopped (cleanly, not by killing the process) and rescheduled * to continue its execution later. Job are generally not killed when the system is * under memory pressure, since the number of concurrent jobs is adjusted based on the * memory state of the device.</p></li> * </ul> * * <p>Here is an example implementation of this class:</p> * * {@sample frameworks/support/samples/Support4Demos/src/main/java/com/example/android/supportv4/app/SimpleJobIntentService.java * complete} */ public abstract class JobIntentService extends Service { static final String TAG = "JobIntentService"; static final boolean DEBUG = false; CompatJobEngine mJobImpl; WorkEnqueuer mCompatWorkEnqueuer; CommandProcessor mCurProcessor; boolean mInterruptIfStopped = false; boolean mStopped = false; boolean mDestroyed = false; final ArrayList<CompatWorkItem> mCompatQueue; static final Object sLock = new Object(); static final HashMap<ComponentName, WorkEnqueuer> sClassWorkEnqueuer = new HashMap<>(); /** * Base class for the target service we can deliver work to and the implementation of * how to deliver that work. */ abstract static class WorkEnqueuer { final ComponentName mComponentName; boolean mHasJobId; int mJobId; WorkEnqueuer(Context context, ComponentName cn) { mComponentName = cn; } void ensureJobId(int jobId) { if (!mHasJobId) { mHasJobId = true; mJobId = jobId; } else if (mJobId != jobId) { throw new IllegalArgumentException("Given job ID " + jobId + " is different than previous " + mJobId); } } abstract void enqueueWork(Intent work); public void serviceStartReceived() { } public void serviceProcessingStarted() { } public void serviceProcessingFinished() { } } /** * Get rid of lint warnings about API levels. */ interface CompatJobEngine { IBinder compatGetBinder(); GenericWorkItem dequeueWork(); } /** * An implementation of WorkEnqueuer that works for pre-O (raw Service-based). */ static final class CompatWorkEnqueuer extends WorkEnqueuer { private final Context mContext; private final PowerManager.WakeLock mLaunchWakeLock; private final PowerManager.WakeLock mRunWakeLock; boolean mLaunchingService; boolean mServiceProcessing; CompatWorkEnqueuer(Context context, ComponentName cn) { super(context, cn); mContext = context.getApplicationContext(); // Make wake locks. We need two, because the launch wake lock wants to have // a timeout, and the system does not do the right thing if you mix timeout and // non timeout (or even changing the timeout duration) in one wake lock. PowerManager pm = ((PowerManager) context.getSystemService(Context.POWER_SERVICE)); mLaunchWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, cn.getClassName() + ":launch"); mLaunchWakeLock.setReferenceCounted(false); mRunWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, cn.getClassName() + ":run"); mRunWakeLock.setReferenceCounted(false); } @Override void enqueueWork(Intent work) { Intent intent = new Intent(work); intent.setComponent(mComponentName); if (DEBUG) Log.d(TAG, "Starting service for work: " + work); if (mContext.startService(intent) != null) { synchronized (this) { if (!mLaunchingService) { mLaunchingService = true; if (!mServiceProcessing) { // If the service is not already holding the wake lock for // itself, acquire it now to keep the system running until // we get this work dispatched. We use a timeout here to // protect against whatever problem may cause it to not get // the work. mLaunchWakeLock.acquire(60 * 1000); } } } } } @Override public void serviceStartReceived() { synchronized (this) { // Once we have started processing work, we can count whatever last // enqueueWork() that happened as handled. mLaunchingService = false; } } @Override public void serviceProcessingStarted() { synchronized (this) { // We hold the wake lock as long as the service is processing commands. if (!mServiceProcessing) { mServiceProcessing = true; // Keep the device awake, but only for at most 10 minutes at a time // (Similar to JobScheduler.) mRunWakeLock.acquire(10 * 60 * 1000L); mLaunchWakeLock.release(); } } } @Override public void serviceProcessingFinished() { synchronized (this) { if (mServiceProcessing) { // If we are transitioning back to a wakelock with a timeout, do the same // as if we had enqueued work without the service running. if (mLaunchingService) { mLaunchWakeLock.acquire(60 * 1000); } mServiceProcessing = false; mRunWakeLock.release(); } } } } /** * Implementation of a JobServiceEngine for interaction with JobIntentService. */ @RequiresApi(26) static final class JobServiceEngineImpl extends JobServiceEngine implements JobIntentService.CompatJobEngine { static final String TAG = "JobServiceEngineImpl"; static final boolean DEBUG = false; final JobIntentService mService; final Object mLock = new Object(); JobParameters mParams; final class WrapperWorkItem implements JobIntentService.GenericWorkItem { final JobWorkItem mJobWork; WrapperWorkItem(JobWorkItem jobWork) { mJobWork = jobWork; } @Override public Intent getIntent() { return mJobWork.getIntent(); } @Override public void complete() { synchronized (mLock) { if (mParams != null) { mParams.completeWork(mJobWork); } } } } JobServiceEngineImpl(JobIntentService service) { super(service); mService = service; } @Override public IBinder compatGetBinder() { return getBinder(); } @Override public boolean onStartJob(JobParameters params) { if (DEBUG) Log.d(TAG, "onStartJob: " + params); mParams = params; // We can now start dequeuing work! mService.ensureProcessorRunningLocked(false); return true; } @Override public boolean onStopJob(JobParameters params) { if (DEBUG) Log.d(TAG, "onStartJob: " + params); boolean result = mService.doStopCurrentWork(); synchronized (mLock) { // Once we return, the job is stopped, so its JobParameters are no // longer valid and we should not be doing anything with them. mParams = null; } return result; } /** * Dequeue some work. */ @Override public JobIntentService.GenericWorkItem dequeueWork() { JobWorkItem work; synchronized (mLock) { if (mParams == null) { return null; } work = mParams.dequeueWork(); } if (work != null) { work.getIntent().setExtrasClassLoader(mService.getClassLoader()); return new WrapperWorkItem(work); } else { return null; } } } @RequiresApi(26) static final class JobWorkEnqueuer extends JobIntentService.WorkEnqueuer { private final JobInfo mJobInfo; private final JobScheduler mJobScheduler; JobWorkEnqueuer(Context context, ComponentName cn, int jobId) { super(context, cn); ensureJobId(jobId); JobInfo.Builder b = new JobInfo.Builder(jobId, mComponentName); mJobInfo = b.setOverrideDeadline(0).build(); mJobScheduler = (JobScheduler) context.getApplicationContext().getSystemService( Context.JOB_SCHEDULER_SERVICE); } @Override void enqueueWork(Intent work) { if (DEBUG) Log.d(TAG, "Enqueueing work: " + work); mJobScheduler.enqueue(mJobInfo, new JobWorkItem(work)); } } /** * Abstract definition of an item of work that is being dispatched. */ interface GenericWorkItem { Intent getIntent(); void complete(); } /** * An implementation of GenericWorkItem that dispatches work for pre-O platforms: intents * received through a raw service's onStartCommand. */ final class CompatWorkItem implements GenericWorkItem { final Intent mIntent; final int mStartId; CompatWorkItem(Intent intent, int startId) { mIntent = intent; mStartId = startId; } @Override public Intent getIntent() { return mIntent; } @Override public void complete() { if (DEBUG) Log.d(TAG, "Stopping self: #" + mStartId); stopSelf(mStartId); } } /** * This is a task to dequeue and process work in the background. */ final class CommandProcessor extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { GenericWorkItem work; if (DEBUG) Log.d(TAG, "Starting to dequeue work..."); while ((work = dequeueWork()) != null) { if (DEBUG) Log.d(TAG, "Processing next work: " + work); onHandleWork(work.getIntent()); if (DEBUG) Log.d(TAG, "Completing work: " + work); work.complete(); } if (DEBUG) Log.d(TAG, "Done processing work!"); return null; } @Override protected void onCancelled(Void aVoid) { processorFinished(); } @Override protected void onPostExecute(Void aVoid) { processorFinished(); } } /** * Default empty constructor. */ public JobIntentService() { if (Build.VERSION.SDK_INT >= 26) { mCompatQueue = null; } else { mCompatQueue = new ArrayList<>(); } } @Override public void onCreate() { super.onCreate(); if (DEBUG) Log.d(TAG, "CREATING: " + this); if (Build.VERSION.SDK_INT >= 26) { mJobImpl = new JobServiceEngineImpl(this); mCompatWorkEnqueuer = null; } else { mJobImpl = null; ComponentName cn = new ComponentName(this, this.getClass()); mCompatWorkEnqueuer = getWorkEnqueuer(this, cn, false, 0); } } /** * Processes start commands when running as a pre-O service, enqueueing them to be * later dispatched in {@link #onHandleWork(Intent)}. */ @Override public int onStartCommand(@Nullable Intent intent, int flags, int startId) { if (mCompatQueue != null) { mCompatWorkEnqueuer.serviceStartReceived(); if (DEBUG) Log.d(TAG, "Received compat start command #" + startId + ": " + intent); synchronized (mCompatQueue) { mCompatQueue.add(new CompatWorkItem(intent != null ? intent : new Intent(), startId)); ensureProcessorRunningLocked(true); } return START_REDELIVER_INTENT; } else { if (DEBUG) Log.d(TAG, "Ignoring start command: " + intent); return START_NOT_STICKY; } } /** * Returns the IBinder for the {@link android.app.job.JobServiceEngine} when * running as a JobService on O and later platforms. */ @Override public IBinder onBind(@NonNull Intent intent) { if (mJobImpl != null) { IBinder engine = mJobImpl.compatGetBinder(); if (DEBUG) Log.d(TAG, "Returning engine: " + engine); return engine; } else { return null; } } @Override public void onDestroy() { super.onDestroy(); if (mCompatQueue != null) { synchronized (mCompatQueue) { mDestroyed = true; mCompatWorkEnqueuer.serviceProcessingFinished(); } } } /** * Call this to enqueue work for your subclass of {@link JobIntentService}. This will * either directly start the service (when running on pre-O platforms) or enqueue work * for it as a job (when running on O and later). In either case, a wake lock will be * held for you to ensure you continue running. The work you enqueue will ultimately * appear at {@link #onHandleWork(Intent)}. * * @param context Context this is being called from. * @param cls The concrete class the work should be dispatched to (this is the class that * is published in your manifest). * @param jobId A unique job ID for scheduling; must be the same value for all work * enqueued for the same class. * @param work The Intent of work to enqueue. */ public static void enqueueWork(@NonNull Context context, @NonNull Class cls, int jobId, @NonNull Intent work) { enqueueWork(context, new ComponentName(context, cls), jobId, work); } /** * Like {@link #enqueueWork(Context, Class, int, Intent)}, but supplies a ComponentName * for the service to interact with instead of its class. * * @param context Context this is being called from. * @param component The published ComponentName of the class this work should be * dispatched to. * @param jobId A unique job ID for scheduling; must be the same value for all work * enqueued for the same class. * @param work The Intent of work to enqueue. */ public static void enqueueWork(@NonNull Context context, @NonNull ComponentName component, int jobId, @NonNull Intent work) { if (work == null) { throw new IllegalArgumentException("work must not be null"); } synchronized (sLock) { WorkEnqueuer we = getWorkEnqueuer(context, component, true, jobId); we.ensureJobId(jobId); we.enqueueWork(work); } } static WorkEnqueuer getWorkEnqueuer(Context context, ComponentName cn, boolean hasJobId, int jobId) { WorkEnqueuer we = sClassWorkEnqueuer.get(cn); if (we == null) { if (Build.VERSION.SDK_INT >= 26) { if (!hasJobId) { throw new IllegalArgumentException("Can't be here without a job id"); } we = new JobWorkEnqueuer(context, cn, jobId); } else { we = new CompatWorkEnqueuer(context, cn); } sClassWorkEnqueuer.put(cn, we); } return we; } /** * Called serially for each work dispatched to and processed by the service. This * method is called on a background thread, so you can do long blocking operations * here. Upon returning, that work will be considered complete and either the next * pending work dispatched here or the overall service destroyed now that it has * nothing else to do. * * <p>Be aware that when running as a job, you are limited by the maximum job execution * time and any single or total sequential items of work that exceeds that limit will * cause the service to be stopped while in progress and later restarted with the * last unfinished work. (There is currently no limit on execution duration when * running as a pre-O plain Service.)</p> * * @param intent The intent describing the work to now be processed. */ protected abstract void onHandleWork(@NonNull Intent intent); /** * Control whether code executing in {@link #onHandleWork(Intent)} will be interrupted * if the job is stopped. By default this is false. If called and set to true, any * time {@link #onStopCurrentWork()} is called, the class will first call * {@link AsyncTask#cancel(boolean) AsyncTask.cancel(true)} to interrupt the running * task. * * @param interruptIfStopped Set to true to allow the system to interrupt actively * running work. */ public void setInterruptIfStopped(boolean interruptIfStopped) { mInterruptIfStopped = interruptIfStopped; } /** * Returns true if {@link #onStopCurrentWork()} has been called. You can use this, * while executing your work, to see if it should be stopped. */ public boolean isStopped() { return mStopped; } /** * This will be called if the JobScheduler has decided to stop this job. The job for * this service does not have any constraints specified, so this will only generally happen * if the service exceeds the job's maximum execution time. * * @return True to indicate to the JobManager whether you'd like to reschedule this work, * false to drop this and all following work. Regardless of the value returned, your service * must stop executing or the system will ultimately kill it. The default implementation * returns true, and that is most likely what you want to return as well (so no work gets * lost). */ public boolean onStopCurrentWork() { return true; } boolean doStopCurrentWork() { if (mCurProcessor != null) { mCurProcessor.cancel(mInterruptIfStopped); } mStopped = true; return onStopCurrentWork(); } void ensureProcessorRunningLocked(boolean reportStarted) { if (mCurProcessor == null) { mCurProcessor = new CommandProcessor(); if (mCompatWorkEnqueuer != null && reportStarted) { mCompatWorkEnqueuer.serviceProcessingStarted(); } if (DEBUG) Log.d(TAG, "Starting processor: " + mCurProcessor); mCurProcessor.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } void processorFinished() { if (mCompatQueue != null) { synchronized (mCompatQueue) { mCurProcessor = null; // The async task has finished, but we may have gotten more work scheduled in the // meantime. If so, we need to restart the new processor to execute it. If there // is no more work at this point, either the service is in the process of being // destroyed (because we called stopSelf on the last intent started for it), or // someone has already called startService with a new Intent that will be // arriving shortly. In either case, we want to just leave the service // waiting -- either to get destroyed, or get a new onStartCommand() callback // which will then kick off a new processor. if (mCompatQueue != null && mCompatQueue.size() > 0) { ensureProcessorRunningLocked(false); } else if (!mDestroyed) { mCompatWorkEnqueuer.serviceProcessingFinished(); } } } } GenericWorkItem dequeueWork() { if (mJobImpl != null) { return mJobImpl.dequeueWork(); } else { synchronized (mCompatQueue) { if (mCompatQueue.size() > 0) { return mCompatQueue.remove(0); } else { return null; } } } } }
3e153465063cbdf23609293d3871c5c8203509de
1,582
java
Java
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ops/impl/reduce/bp/Norm1Bp.java
zhangy10/deeplearning4j
9d31156ce600dee6ce4a7fac28286ebbaa211164
[ "Apache-2.0" ]
13,006
2015-02-13T18:35:31.000Z
2022-03-18T12:11:44.000Z
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ops/impl/reduce/bp/Norm1Bp.java
zhangy10/deeplearning4j
9d31156ce600dee6ce4a7fac28286ebbaa211164
[ "Apache-2.0" ]
5,319
2015-02-13T08:21:46.000Z
2019-06-12T14:56:50.000Z
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ops/impl/reduce/bp/Norm1Bp.java
zhangy10/deeplearning4j
9d31156ce600dee6ce4a7fac28286ebbaa211164
[ "Apache-2.0" ]
4,719
2015-02-13T22:48:55.000Z
2022-03-22T07:25:36.000Z
33.659574
123
0.663085
9,008
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.nd4j.linalg.api.ops.impl.reduce.bp; import org.nd4j.autodiff.samediff.SDVariable; import org.nd4j.autodiff.samediff.SameDiff; import org.nd4j.linalg.api.ndarray.INDArray; /** * Backprop op for Norm1 reduction operation * * @author Alex Black */ public class Norm1Bp extends BaseReductionBp { public Norm1Bp(SameDiff sameDiff, SDVariable origInput, SDVariable gradAtOutput, boolean keepDims, int... dimensions) { super(sameDiff, origInput, gradAtOutput, keepDims, dimensions); } public Norm1Bp(INDArray origInput, INDArray gradAtOutput, INDArray output, boolean keepDims, int... dimensions){ super(origInput, gradAtOutput, output, keepDims, dimensions); } public Norm1Bp(){} @Override public String opName() { return "reduce_norm1_bp"; } }
3e1534a155dab56a8ed514d2370807bbf4c9fed6
985
java
Java
src/main/java/org/retro/common/impl/c64/C64VirtualDisk.java
marcelschoen/retro-io
7e25edd1eac700b72d6ad97f351267a20564fed5
[ "Apache-2.0" ]
1
2019-02-28T22:29:13.000Z
2019-02-28T22:29:13.000Z
src/main/java/org/retro/common/impl/c64/C64VirtualDisk.java
marcelschoen/retro-io
7e25edd1eac700b72d6ad97f351267a20564fed5
[ "Apache-2.0" ]
null
null
null
src/main/java/org/retro/common/impl/c64/C64VirtualDisk.java
marcelschoen/retro-io
7e25edd1eac700b72d6ad97f351267a20564fed5
[ "Apache-2.0" ]
null
null
null
31.774194
76
0.73401
9,009
/* * (C) Copyright ${year} retro-io (https://github.com/marcelschoen/retro-io) * * 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.retro.common.impl.c64; import org.retro.common.ImageType; import org.retro.common.impl.AbstractBaseVirtualDisk; /** * A virtual C64 floppy disk. * * @author Marcel Schoen */ public class C64VirtualDisk extends AbstractBaseVirtualDisk { public C64VirtualDisk(String name) { super(ImageType.c64_D64, name); } }
3e15351cc98b42805d3a0a3281d5cb87b934e654
6,479
java
Java
src/test/java/org/orekit/data/NetworkCrawlerTest.java
rtubio/Orekit
5c1b2540905248f94e85cb240c140545feb859c3
[ "Apache-2.0" ]
null
null
null
src/test/java/org/orekit/data/NetworkCrawlerTest.java
rtubio/Orekit
5c1b2540905248f94e85cb240c140545feb859c3
[ "Apache-2.0" ]
null
null
null
src/test/java/org/orekit/data/NetworkCrawlerTest.java
rtubio/Orekit
5c1b2540905248f94e85cb240c140545feb859c3
[ "Apache-2.0" ]
null
null
null
39.266667
124
0.643309
9,010
/* Copyright 2002-2019 CS Systèmes d'Information * Licensed to CS Systèmes d'Information (CS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * CS 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.orekit.data; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import java.util.regex.Pattern; import org.junit.Assert; import org.junit.Test; import org.junit.Before; import org.orekit.errors.OrekitException; public class NetworkCrawlerTest { @Before public void setUp() { // Clear any filters that another test may have left DataProvidersManager.getInstance().clearFilters(); } @Test(expected=OrekitException.class) public void noElement() throws MalformedURLException { File existing = new File(url("regular-data").getPath()); File inexistent = new File(existing.getParent(), "inexistant-directory"); new NetworkCrawler(inexistent.toURI().toURL()).feed(Pattern.compile(".*"), new CountingLoader()); } // WARNING! // the following test is commented out by default, as it does connect to the web // if you want to enable it, you will have uncomment it and to either set the proxy // settings according to your local network or remove the proxy authentication // settings if you have a transparent connection to internet // @Test // public void remote() throws java.net.MalformedURLException, OrekitException, URISyntaxException { // // System.setProperty("http.proxyHost", "proxy.your.domain.com"); // System.setProperty("http.proxyPort", "8080"); // System.setProperty("http.nonProxyHosts", "localhost|*.your.domain.com"); // java.net.Authenticator.setDefault(new AuthenticatorDialog()); // CountingLoader loader = new CountingLoader(); // NetworkCrawler crawler = // new NetworkCrawler(new URL("http://hpiers.obspm.fr/eoppc/bul/bulc/UTC-TAI.history")); // crawler.setTimeout(1000); // crawler.feed(Pattern.compile(".*\\.history"), loader); // Assert.assertEquals(1, loader.getCount()); // // } @Test public void local() { CountingLoader crawler = new CountingLoader(); NetworkCrawler nc = new NetworkCrawler(url("regular-data/UTC-TAI.history"), url("regular-data/de405-ephemerides/unxp0000.405"), url("regular-data/de405-ephemerides/unxp0001.405"), url("regular-data/de406-ephemerides/unxp0000.406"), url("regular-data/Earth-orientation-parameters/monthly/bulletinb_IAU2000-216.txt"), url("no-data")); nc.setTimeout(20); nc.feed(Pattern.compile(".*"), crawler); Assert.assertEquals(6, crawler.getCount()); } @Test public void compressed() { CountingLoader crawler = new CountingLoader(); new NetworkCrawler(url("compressed-data/UTC-TAI.history.gz"), url("compressed-data/eopc04_08_IAU2000.00.gz"), url("compressed-data/eopc04_08_IAU2000.02.gz")).feed(Pattern.compile("^eopc04.*"), crawler); Assert.assertEquals(2, crawler.getCount()); } @Test public void multiZip() { CountingLoader crawler = new CountingLoader(); new NetworkCrawler(url("zipped-data/multizip.zip")).feed(Pattern.compile(".*\\.txt$"), crawler); Assert.assertEquals(6, crawler.getCount()); } @Test(expected=OrekitException.class) public void ioException() { try { new NetworkCrawler(url("regular-data/UTC-TAI.history")).feed(Pattern.compile(".*"), new IOExceptionLoader()); } catch (OrekitException oe) { // expected behavior Assert.assertNotNull(oe.getCause()); Assert.assertEquals(IOException.class, oe.getCause().getClass()); Assert.assertEquals("dummy error", oe.getMessage()); throw oe; } } @Test(expected=OrekitException.class) public void parseException() { try { new NetworkCrawler(url("regular-data/UTC-TAI.history")).feed(Pattern.compile(".*"), new ParseExceptionLoader()); } catch (OrekitException oe) { // expected behavior Assert.assertNotNull(oe.getCause()); Assert.assertEquals(ParseException.class, oe.getCause().getClass()); Assert.assertEquals("dummy error", oe.getMessage()); throw oe; } } private static class CountingLoader implements DataLoader { private int count = 0; public boolean stillAcceptsData() { return true; } public void loadData(InputStream input, String name) { ++count; } public int getCount() { return count; } } private static class IOExceptionLoader implements DataLoader { public boolean stillAcceptsData() { return true; } public void loadData(InputStream input, String name) throws IOException { if (name.endsWith("UTC-TAI.history")) { throw new IOException("dummy error"); } } } private static class ParseExceptionLoader implements DataLoader { public boolean stillAcceptsData() { return true; } public void loadData(InputStream input, String name) throws ParseException { if (name.endsWith("UTC-TAI.history")) { throw new ParseException("dummy error", 0); } } } private URL url(String resource) { return DirectoryCrawlerTest.class.getClassLoader().getResource(resource); } }
3e1535ce394c0665142dbf94b2029146468a1a33
1,171
java
Java
server/src/main/java/com/voxelwind/server/game/serializer/CoalSerializer.java
lukeeey/voxelwind
3f88aff790f99a461839fe1b42fab51c9244331e
[ "MIT" ]
76
2016-07-23T18:54:53.000Z
2016-10-05T19:08:43.000Z
server/src/main/java/com/voxelwind/server/game/serializer/CoalSerializer.java
lukeeey/voxelwind
3f88aff790f99a461839fe1b42fab51c9244331e
[ "MIT" ]
35
2016-08-06T23:44:07.000Z
2016-10-09T00:09:41.000Z
server/src/main/java/com/voxelwind/server/game/serializer/CoalSerializer.java
voxelwind/voxelwind
5da4c4edd5cfc6569e9b3ca451fd98a699bf111f
[ "MIT" ]
30
2016-11-01T23:50:16.000Z
2021-09-20T20:50:08.000Z
27.232558
72
0.699402
9,011
package com.voxelwind.server.game.serializer; import com.voxelwind.api.game.Metadata; import com.voxelwind.api.game.item.ItemStack; import com.voxelwind.api.game.item.ItemType; import com.voxelwind.api.game.item.data.Coal; import com.voxelwind.api.game.level.block.BlockState; import com.voxelwind.api.game.level.blockentities.BlockEntity; import com.voxelwind.nbt.tags.CompoundTag; public class CoalSerializer implements Serializer { @Override public CompoundTag readNBT(BlockState block) { return null; } @Override public short readMetadata(BlockState block) { return 0; } @Override public CompoundTag readNBT(ItemStack itemStack) { return null; } @Override public short readMetadata(ItemStack itemStack) { Coal coal = getItemData(itemStack); return (short) (coal != null ? (coal.isCharcoal() ? 1 : 0) : 0); } @Override public Metadata writeMetadata(ItemType block, short metadata) { return (metadata == 0) ? Coal.REGULAR : Coal.CHARCOAL; } @Override public BlockEntity writeNBT(ItemType block, CompoundTag nbtTag) { return null; } }
3e15370845e8f3c69bb5c3f8a592ab7dfdc40569
8,151
java
Java
src/main/java/com/u8/server/sdk/APPStoeAndWXAndAl/APPStoreWXAliSDK.java
game-platform-awaresome/sdkserver
109c5070b68d0aa8de97fb217e1e14feecc17d66
[ "Apache-2.0" ]
1
2019-03-20T08:27:20.000Z
2019-03-20T08:27:20.000Z
src/main/java/com/u8/server/sdk/APPStoeAndWXAndAl/APPStoreWXAliSDK.java
game-platform-awaresome/sdkserver
109c5070b68d0aa8de97fb217e1e14feecc17d66
[ "Apache-2.0" ]
null
null
null
src/main/java/com/u8/server/sdk/APPStoeAndWXAndAl/APPStoreWXAliSDK.java
game-platform-awaresome/sdkserver
109c5070b68d0aa8de97fb217e1e14feecc17d66
[ "Apache-2.0" ]
1
2019-03-20T08:27:22.000Z
2019-03-20T08:27:22.000Z
38.814286
155
0.567415
9,012
package com.u8.server.sdk.APPStoeAndWXAndAl; import com.thoughtworks.xstream.XStream; import com.u8.server.data.UChannel; import com.u8.server.data.UOrder; import com.u8.server.data.UUser; import com.u8.server.log.Log; import com.u8.server.sdk.*; import com.u8.server.sdk.appstore.AppStoreSDK; import com.u8.server.sdk.wx.WXOrderInfo; import com.u8.server.sdk.wx.WXSDK; import com.u8.server.service.UChannelLoginTypeManager; import com.u8.server.service.UChannelPayTypeManager; import com.u8.server.utils.EncryptUtils; import net.sf.json.JSONObject; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.util.TextUtils; import java.net.InetAddress; import java.nio.charset.Charset; import java.util.*; /** * 都玩(易乐) * Created by ant on 2016/9/1. * 已废弃 */ public class APPStoreWXAliSDK implements ISDKScriptExt { public static final String createOrderURL="https://api.mch.weixin.qq.com/pay/unifiedorder"; public static final String callBackURL = "/pay/wxpay/payCallback"; @Override public void verify(final UChannel channel, String extension, final ISDKVerifyListener callback) { JSONObject json = JSONObject.fromObject(extension); final String loginType = json.getString("loginType"); if(loginType.equals("1")){ WXSDK.WxVerivy(channel,extension,true,callback); } if(loginType.equals("2")){//游客登录 final String accesstoken = json.getString("accesstoken"); Log.d("The result of yile verify is :" + accesstoken); if (!TextUtils.isEmpty(accesstoken)){ callback.onSuccess(new SDKVerifyResult(true, accesstoken, "", "")); return; }else{ callback.onFailed(channel.getMaster().getSdkName() + " guest verify failed. the get result is " + accesstoken); } } } @Override public void onGetOrderID(UUser user, UOrder order, ISDKOrderListener callback) { try{ } catch (Exception e){ } if(callback != null){ callback.onSuccess(""); } } public void verifyByType(UChannel channel, String extension, UChannelLoginTypeManager manager, ISDKVerifyListener callback){ } //根据宝石风暴的参数 payType = 3 是为微信支付 payType = 2 是阿里支付 public void onGetOrderIDByType(UUser user, UOrder order, int payType, UChannelPayTypeManager manager, ISDKOrderListener callback){ if(payType==1){ AppstoreGetOrder(user,order,callback); }else if(payType==2){ //AliSDK.AliGetOrder(user, order,true, callback); }else if(payType==3){ WXSDK.WxGetOrder(user, order,true, callback); } } public void AppstoreGetOrder(UUser user, UOrder order, ISDKOrderListener callback) { AppStoreSDK.AppStoreGetOrder(user,order,callback); } public void WXGetOrder(UUser user, UOrder order, final ISDKOrderListener callback) { try{ final String appid = order.getChannel().getCpAppID(); final String appKey = order.getChannel().getCpAppKey(); String attach = "bsfb"; String body = order.getChannel().getCpConfig(); final String mch_id = order.getChannel().getCpPayID(); final String nonce_str = UUID.randomUUID().toString().replace("-",""); String notify_url = UHttpAgent.ServerHost+callBackURL; String out_trade_no = order.getOrderID().toString(); String spbill_create_ip = InetAddress.getLocalHost().getHostAddress(); String total_fee = order.getMoney().toString(); String trade_type = "APP"; SortedMap<Object, Object> parameters = new TreeMap<Object, Object>(); parameters.put("appid", appid); parameters.put("mch_id", mch_id); parameters.put("nonce_str", nonce_str); parameters.put("body", body);//购买支付信息 parameters.put("out_trade_no", out_trade_no);//订单号 parameters.put("total_fee", total_fee);// 总金额单位为分 parameters.put("spbill_create_ip", spbill_create_ip); parameters.put("notify_url", notify_url); parameters.put("trade_type", trade_type); String sign = createSign("UTF-8", parameters,appKey); parameters.put("sign", sign); String requestXML = getRequestXml(parameters); UHttpAgent.getInstance().post(createOrderURL,null,new ByteArrayEntity(requestXML.getBytes(Charset.forName("UTF-8"))),new UHttpFutureCallback(){ @Override public void completed(String result) { try { Log.d("the result is "+result); XStream xStream = new XStream(); xStream.alias("xml", WXOrderInfo.class); WXOrderInfo authInfo = (WXOrderInfo)xStream.fromXML(result); if(authInfo.getReturn_code().equals("FAIL")){ callback.onFailed(authInfo.getReturn_msg()); }else{ SortedMap<Object, Object> params = new TreeMap<Object, Object>(); params.put("appid", appid); params.put("partnerid",mch_id); params.put("prepayid",authInfo.getPrepay_id()); params.put("package", "Sign=WXPay"); params.put("nonceStr", nonce_str); params.put("timeStamp", "\""+new Date().getTime()+"\""); String paySign = createSign("UTF-8", params,appKey); params.put("paySign", paySign); // paySign的生成规则和Sign的生成规则一致 String json = JSONObject.fromObject(params).toString(); Log.d("the json is "+json); callback.onSuccess(json); } } catch (Exception e) { e.printStackTrace(); } } public void failed(String e) { callback.onFailed(e); } }); } catch(Exception e){ } } /** * @author lwz * @date 2014-12-8 * @Description:sign签名 * @param characterEncoding * 编码格式 * @param parameters * 请求参数 * @return */ public static String createSign(String characterEncoding,SortedMap<Object, Object> parameters,String API_KEY) { StringBuffer sb = new StringBuffer(); Set es = parameters.entrySet(); Iterator it = es.iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); String k = (String) entry.getKey(); Object v = entry.getValue(); if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) { sb.append(k + "=" + v + "&"); } } sb.append("key=" + API_KEY); String sign = EncryptUtils.md5(sb.toString()).toUpperCase(); return sign; } /** * @author 老妖 * @date 2014-12-5下午2:32:05 * @Description:将请求参数转换为xml格式的string * @param parameters * 请求参数 * @return */ public static String getRequestXml(SortedMap<Object, Object> parameters) { StringBuffer sb = new StringBuffer(); sb.append("<xml>"); Set es = parameters.entrySet(); Iterator it = es.iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); String k = (String) entry.getKey(); String v = (String) entry.getValue(); if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k)|| "sign".equalsIgnoreCase(k)) { sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">"); } else { sb.append("<" + k + ">" + v + "</" + k + ">"); } } sb.append("</xml>"); return sb.toString(); } }
3e15374b061db6727d12015a559ae24a5c7f77de
12,421
java
Java
net.sourceforge.texlipse/source/net/sourceforge/texlipse/editor/TexlipseAnnotationUpdater.java
alaplums/TeXlipse
44b755c3a7bdb7bcd9ba6b2be45d7aa7b977cd61
[ "MIT" ]
null
null
null
net.sourceforge.texlipse/source/net/sourceforge/texlipse/editor/TexlipseAnnotationUpdater.java
alaplums/TeXlipse
44b755c3a7bdb7bcd9ba6b2be45d7aa7b977cd61
[ "MIT" ]
null
null
null
net.sourceforge.texlipse/source/net/sourceforge/texlipse/editor/TexlipseAnnotationUpdater.java
alaplums/TeXlipse
44b755c3a7bdb7bcd9ba6b2be45d7aa7b977cd61
[ "MIT" ]
1
2020-05-17T14:20:07.000Z
2020-05-17T14:20:07.000Z
44.360714
137
0.61863
9,013
/* * $Id$ * * Copyright (c) 2007-2008 by the TeXlipse team. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package net.sourceforge.texlipse.editor; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.sourceforge.texlipse.TexlipsePlugin; import net.sourceforge.texlipse.properties.TexlipseProperties; import net.sourceforge.texlipse.texparser.LatexParserUtils; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.IPostSelectionProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.ui.texteditor.AbstractTextEditor; /** * This class implements a PostSelectionChangeListener which creates annotations * to highlight * <ul> * <li>associated begin or end</li> * <li>all references of a label</li> * </ul> * in the current document. * * @author Boris von Loesch * */ public class TexlipseAnnotationUpdater implements ISelectionChangedListener { private final List<Annotation> fOldAnnotations= new LinkedList<Annotation>(); private AbstractTextEditor fEditor; private Job fUpdateJob; private final static String ANNOTATION_TYPE = "net.sourceforge.texlipse.defAnnotation"; private boolean fEnabled; /** * Creates a new TexlipseAnnotationUpdater and adds itself to the TexEditor via * <code>addPostSelectionChangedListener</code> * @param editor The TexEditor */ public TexlipseAnnotationUpdater (AbstractTextEditor editor) { //Add this listener to the current editors IPostSelectionListener (lazy update) ((IPostSelectionProvider) editor.getSelectionProvider()).addPostSelectionChangedListener(this); fEditor = editor; fEnabled = TexlipsePlugin.getDefault().getPreferenceStore().getBoolean( TexlipseProperties.TEX_EDITOR_ANNOTATATIONS); //Add a PropertyChangeListener TexlipsePlugin.getDefault().getPreferenceStore().addPropertyChangeListener(new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { String property = event.getProperty(); if (TexlipseProperties.TEX_EDITOR_ANNOTATATIONS.equals(property)) { boolean enabled = TexlipsePlugin.getDefault().getPreferenceStore().getBoolean( TexlipseProperties.TEX_EDITOR_ANNOTATATIONS); fEnabled = enabled; } } }); } public void selectionChanged(SelectionChangedEvent event) { update((ISourceViewer) event.getSource()); } /** * Updates the annotations. It first checks if the current selection is * already annotated, if not it clears all annotations and tries to detect * if the current selection is part of a \[a-zA-Z]*ref, \label, \begin{...} * or \end{...} string. If the last is true, it searches with regular expressions * to find the associated part(s) and highlights them (The last uses a non UI-Job * which do not influence the responsiveness of the editor). * * @param viewer */ private void update(ISourceViewer viewer) { final IDocument document = viewer.getDocument(); final IAnnotationModel model = viewer.getAnnotationModel(); ISelection selection = fEditor.getSelectionProvider().getSelection(); if (testSelection(selection, model)) return; if (fUpdateJob != null) { fUpdateJob.cancel(); } removeOldAnnotations(model); if (!fEnabled) { //Feature is turned off, but we have to delete the old annotations return; } if (selection instanceof ITextSelection) { try { //TODO Split this and create new classes for the different annotations final ITextSelection textSelection = (ITextSelection) selection; final int offset = textSelection.getOffset(); final int lineNr = document.getLineOfOffset(offset); final int lineOff = document.getLineOffset(lineNr); final String line = document.get(lineOff, document.getLineLength(lineNr)); IRegion r = LatexParserUtils.getCommand(line, offset - lineOff); if (r == null) return; final String command = line.substring(r.getOffset(), r.getOffset() + r.getLength()).trim(); if ("\\begin".equals(command) || "\\end".equals(command)) { //TODO Its maybe better/faster to use the AST here IRegion r2 = LatexParserUtils.getCommandArgument(line, r.getOffset()); if (r2 == null) return; final IRegion startRegion = new Region(lineOff + r.getOffset(), r2.getOffset() + r2.getLength() - r.getOffset() + 1); final String refName = line.substring(r2.getOffset(), r2.getOffset() + r2.getLength()); //Create a job to update the annotations in the background fUpdateJob = createMatchEnvironmentJob(document, model, offset, command, startRegion, refName); fUpdateJob.setPriority(Job.DECORATE); fUpdateJob.setSystem(true); fUpdateJob.schedule(); } else if (command.endsWith("ref") || "\\label".equals(command)) { //TODO Its maybe better/faster to use the AST here IRegion r2 = LatexParserUtils.getCommandArgument(line, r.getOffset()); if (r2 == null) return; final String refName = line.substring(r2.getOffset(), r2.getOffset() + r2.getLength()); //Create a job to update the annotations in the background fUpdateJob = createMatchReferenceJob(document, model, refName); fUpdateJob.setPriority(Job.DECORATE); fUpdateJob.setSystem(true); fUpdateJob.schedule(); } } catch (BadLocationException ex) { //Do not inform the user cause this is only a decorator } } } /** * Creates and returns a background job which searches and highlights all \label and \*ref. * @param document * @param model * @param refName The name of the reference * @return The job */ private Job createMatchReferenceJob(final IDocument document, final IAnnotationModel model, final String refName) { return new Job("Update Annotations") { public IStatus run(IProgressMonitor monitor) { String text = document.get(); String refNameRegExp = refName.replaceAll("\\*", "\\\\*"); final String simpleRefRegExp = "\\\\([a-zA-Z]*ref|label)\\s*\\{" + refNameRegExp + "\\}"; Matcher m = (Pattern.compile(simpleRefRegExp)).matcher(text); while (m.find()) { if (monitor.isCanceled()) return Status.CANCEL_STATUS; IRegion match = LatexParserUtils.getCommand(text, m.start()); //Test if it is a real LaTeX command if (match != null) { IRegion fi = new Region(m.start(), m.end()-m.start()); createNewAnnotation(fi, "References", model); } } return Status.OK_STATUS; } }; } /** * Creates and returns a new background job which searches and highlights the matching \end or \begin environment. * @param document * @param model * @param offset The offset of the selection (cursor) * @param command \begin or \end * @param startRegion A region which contains the command and the argument (e.g \begin{environment}) * @param envName The name of the environment * @return The Job */ private Job createMatchEnvironmentJob(final IDocument document, final IAnnotationModel model, final int offset, final String command, final IRegion startRegion, final String envName) { return new Job("Update Annotations") { public IStatus run(IProgressMonitor monitor) { String text = document.get(); boolean forward = false; if ("\\begin".equals(command)) forward = true; if (forward) { IRegion endRegion = LatexParserUtils.findMatchingEndEnvironment(text, envName, startRegion.getOffset()); if (endRegion != null) { createNewAnnotation(endRegion, "Environment", model); createNewAnnotation(startRegion, "Environment", model); } } else { IRegion endRegion = LatexParserUtils.findMatchingBeginEnvironment(text, envName, startRegion.getOffset()); if (endRegion != null) { createNewAnnotation(endRegion, "Environment", model); createNewAnnotation(startRegion, "Environment", model); } } return Status.OK_STATUS; } }; } /** * Tests if the selection is already annotated * @param selection current selection * @param model The AnnotationModel * @return true, if selection is already annotated */ private boolean testSelection (ISelection selection, IAnnotationModel model) { if (selection instanceof ITextSelection) { final ITextSelection textSelection = (ITextSelection) selection; //Iterate over all existing annotations for (Iterator<Annotation> iter = fOldAnnotations.iterator(); iter.hasNext();) { Annotation anno = iter.next(); Position p = model.getPosition(anno); if (p != null && p.offset <= textSelection.getOffset() && p.offset+p.length >= textSelection.getOffset()) { return true; } } } return false; } /** * Removes all existing annotations * @param model AnnotationModel */ private void removeOldAnnotations(IAnnotationModel model) { for (Iterator<Annotation> it= fOldAnnotations.iterator(); it.hasNext();) { Annotation annotation= (Annotation) it.next(); model.removeAnnotation(annotation); } fOldAnnotations.clear(); } /** * Creates a new annotation * @param r The IRegion which should be highlighted * @param annString The name of the annotation (not important) * @param model The AnnotationModel */ private void createNewAnnotation(IRegion r, String annString, IAnnotationModel model) { Annotation annotation= new Annotation(ANNOTATION_TYPE, false, annString); Position position= new Position(r.getOffset(), r.getLength()); model.addAnnotation(annotation, position); fOldAnnotations.add(annotation); } }
3e15379553c0cd3006ffb80376e4ae063dbbd2d6
37
java
Java
flypush-api/src/main/java/io/opensw/flypush/api/utils/package-info.java
luismpcosta/flypush
bbc9917a6aa169bd5b11abee63cfeff3554dafdc
[ "Apache-2.0" ]
null
null
null
flypush-api/src/main/java/io/opensw/flypush/api/utils/package-info.java
luismpcosta/flypush
bbc9917a6aa169bd5b11abee63cfeff3554dafdc
[ "Apache-2.0" ]
null
null
null
flypush-api/src/main/java/io/opensw/flypush/api/utils/package-info.java
luismpcosta/flypush
bbc9917a6aa169bd5b11abee63cfeff3554dafdc
[ "Apache-2.0" ]
null
null
null
18.5
36
0.810811
9,014
package io.opensw.flypush.api.utils;
3e15379cb01fb3761c4cec4962efe3e31bd4fbe3
12,661
java
Java
src/test/org/apache/hadoop/hdfs/server/namenode/TestStartup.java
Mingcong/hadoop-1.2.1-cpu-gpu
da1c60956e548502a5964232fff406a606b964e1
[ "Apache-2.0" ]
1
2018-05-05T08:44:52.000Z
2018-05-05T08:44:52.000Z
src/test/org/apache/hadoop/hdfs/server/namenode/TestStartup.java
Mingcong/hadoop-1.2.1-cpu-gpu
da1c60956e548502a5964232fff406a606b964e1
[ "Apache-2.0" ]
null
null
null
src/test/org/apache/hadoop/hdfs/server/namenode/TestStartup.java
Mingcong/hadoop-1.2.1-cpu-gpu
da1c60956e548502a5964232fff406a606b964e1
[ "Apache-2.0" ]
1
2019-10-18T01:00:08.000Z
2019-10-18T01:00:08.000Z
35.664789
126
0.674907
9,015
/** * 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.hadoop.hdfs.server.namenode; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.Random; import junit.framework.TestCase; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FileUtil; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.hdfs.DFSClient; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.hdfs.protocol.DatanodeInfo; import org.apache.hadoop.hdfs.server.common.HdfsConstants.StartupOption; import org.apache.hadoop.hdfs.server.common.Storage.StorageDirectory; import org.apache.hadoop.hdfs.server.namenode.FSImage.NameNodeDirType; import org.apache.hadoop.hdfs.server.namenode.FSImage.NameNodeFile; import org.apache.hadoop.util.StringUtils; import org.junit.Test; /** * Startup and checkpoint tests * */ public class TestStartup extends TestCase { public static final String NAME_NODE_HOST = "localhost:"; public static final String WILDCARD_HTTP_HOST = "0.0.0.0:"; private static final Log LOG = LogFactory.getLog(TestStartup.class.getName()); private Configuration config; private File hdfsDir=null; static final long seed = 0xAAAAEEFL; static final int blockSize = 4096; static final int fileSize = 8192; private long editsLength=0, fsimageLength=0; private void writeFile(FileSystem fileSys, Path name, int repl) throws IOException { FSDataOutputStream stm = fileSys.create(name, true, fileSys.getConf().getInt("io.file.buffer.size", 4096), (short)repl, (long)blockSize); byte[] buffer = new byte[fileSize]; Random rand = new Random(seed); rand.nextBytes(buffer); stm.write(buffer); stm.close(); } protected void setUp() throws Exception { config = new Configuration(); String baseDir = System.getProperty("test.build.data", "/tmp"); hdfsDir = new File(baseDir, "dfs"); if ( hdfsDir.exists() && !FileUtil.fullyDelete(hdfsDir) ) { throw new IOException("Could not delete hdfs directory '" + hdfsDir + "'"); } LOG.info("--hdfsdir is " + hdfsDir.getAbsolutePath()); config.set("dfs.name.dir", new File(hdfsDir, "name").getPath()); config.set("dfs.data.dir", new File(hdfsDir, "data").getPath()); config.set("fs.checkpoint.dir",new File(hdfsDir, "secondary").getPath()); config.set("dfs.secondary.http.address", WILDCARD_HTTP_HOST + "0"); //config.set("fs.default.name", "hdfs://"+ NAME_NODE_HOST + "0"); FileSystem.setDefaultUri(config, "hdfs://"+NAME_NODE_HOST + "0"); } /** * clean up */ public void tearDown() throws Exception { if ( hdfsDir.exists() && !FileUtil.fullyDelete(hdfsDir) ) { throw new IOException("Could not delete hdfs directory in tearDown '" + hdfsDir + "'"); } } /** * start MiniDFScluster, create a file (to create edits) and do a checkpoint * @throws IOException */ public void createCheckPoint() throws IOException { LOG.info("--starting mini cluster"); // manage dirs parameter set to false MiniDFSCluster cluster = null; SecondaryNameNode sn = null; try { cluster = new MiniDFSCluster(0, config, 1, true, false, false, null, null, null, null); cluster.waitActive(); LOG.info("--starting Secondary Node"); // start secondary node sn = new SecondaryNameNode(config); assertNotNull(sn); // create a file FileSystem fileSys = cluster.getFileSystem(); Path file1 = new Path("t1"); this.writeFile(fileSys, file1, 1); LOG.info("--doing checkpoint"); sn.doCheckpoint(); // this shouldn't fail LOG.info("--done checkpoint"); } catch (IOException e) { fail(StringUtils.stringifyException(e)); System.err.println("checkpoint failed"); throw e; } finally { if(sn!=null) sn.shutdown(); if(cluster!=null) cluster.shutdown(); LOG.info("--file t1 created, cluster shutdown"); } } /* * corrupt files by removing and recreating the directory */ private void corruptNameNodeFiles() throws IOException { // now corrupt/delete the directrory List<File> nameDirs = (List<File>)FSNamesystem.getNamespaceDirs(config); List<File> nameEditsDirs = (List<File>)FSNamesystem.getNamespaceEditsDirs(config); // get name dir and its length, then delete and recreate the directory File dir = nameDirs.get(0); // has only one this.fsimageLength = new File(new File(dir, "current"), NameNodeFile.IMAGE.getName()).length(); if(dir.exists() && !(FileUtil.fullyDelete(dir))) throw new IOException("Cannot remove directory: " + dir); LOG.info("--removed dir "+dir + ";len was ="+ this.fsimageLength); if (!dir.mkdirs()) throw new IOException("Cannot create directory " + dir); dir = nameEditsDirs.get(0); //has only one this.editsLength = new File(new File(dir, "current"), NameNodeFile.EDITS.getName()).length(); if(dir.exists() && !(FileUtil.fullyDelete(dir))) throw new IOException("Cannot remove directory: " + dir); if (!dir.mkdirs()) throw new IOException("Cannot create directory " + dir); LOG.info("--removed dir and recreated "+dir + ";len was ="+ this.editsLength); } /** * start with -importCheckpoint option and verify that the files are in separate directories and of the right length * @throws IOException */ private void checkNameNodeFiles() throws IOException{ // start namenode with import option LOG.info("-- about to start DFS cluster"); MiniDFSCluster cluster = null; try { cluster = new MiniDFSCluster(0, config, 1, false, false, false, StartupOption.IMPORT, null, null, null); cluster.waitActive(); LOG.info("--NN started with checkpoint option"); NameNode nn = cluster.getNameNode(); assertNotNull(nn); // Verify that image file sizes did not change. FSImage image = nn.getFSImage(); verifyDifferentDirs(image, this.fsimageLength, this.editsLength); } finally { if(cluster != null) cluster.shutdown(); } } /** * verify that edits log and fsimage are in different directories and of a correct size */ private void verifyDifferentDirs(FSImage img, long expectedImgSize, long expectedEditsSize) { StorageDirectory sd =null; for (Iterator<StorageDirectory> it = img.dirIterator(); it.hasNext();) { sd = it.next(); if(sd.getStorageDirType().isOfType(NameNodeDirType.IMAGE)) { File imf = FSImage.getImageFile(sd, NameNodeFile.IMAGE); LOG.info("--image file " + imf.getAbsolutePath() + "; len = " + imf.length() + "; expected = " + expectedImgSize); assertEquals(expectedImgSize, imf.length()); } else if(sd.getStorageDirType().isOfType(NameNodeDirType.EDITS)) { File edf = FSImage.getImageFile(sd, NameNodeFile.EDITS); LOG.info("-- edits file " + edf.getAbsolutePath() + "; len = " + edf.length() + "; expected = " + expectedEditsSize); assertEquals(expectedEditsSize, edf.length()); } else { fail("Image/Edits directories are not different"); } } } /** * secnn-6 * checkpoint for edits and image is the same directory * @throws IOException */ public void testChkpointStartup2() throws IOException{ LOG.info("--starting checkpointStartup2 - same directory for checkpoint"); // different name dirs config.set("dfs.name.dir", new File(hdfsDir, "name").getPath()); config.set("dfs.name.edits.dir", new File(hdfsDir, "edits").getPath()); // same checkpoint dirs config.set("fs.checkpoint.edits.dir", new File(hdfsDir, "chkpt").getPath()); config.set("fs.checkpoint.dir", new File(hdfsDir, "chkpt").getPath()); createCheckPoint(); corruptNameNodeFiles(); checkNameNodeFiles(); } /** * seccn-8 * checkpoint for edits and image are different directories * @throws IOException */ public void testChkpointStartup1() throws IOException{ //setUpConfig(); LOG.info("--starting testStartup Recovery"); // different name dirs config.set("dfs.name.dir", new File(hdfsDir, "name").getPath()); config.set("dfs.name.edits.dir", new File(hdfsDir, "edits").getPath()); // same checkpoint dirs config.set("fs.checkpoint.edits.dir", new File(hdfsDir, "chkpt_edits").getPath()); config.set("fs.checkpoint.dir", new File(hdfsDir, "chkpt").getPath()); createCheckPoint(); corruptNameNodeFiles(); checkNameNodeFiles(); } /** * secnn-7 * secondary node copies fsimage and edits into correct separate directories. * @throws IOException */ public void testSNNStartup() throws IOException{ //setUpConfig(); LOG.info("--starting SecondNN startup test"); // different name dirs config.set("dfs.name.dir", new File(hdfsDir, "name").getPath()); config.set("dfs.name.edits.dir", new File(hdfsDir, "name").getPath()); // same checkpoint dirs config.set("fs.checkpoint.edits.dir", new File(hdfsDir, "chkpt_edits").getPath()); config.set("fs.checkpoint.dir", new File(hdfsDir, "chkpt").getPath()); LOG.info("--starting NN "); MiniDFSCluster cluster = null; SecondaryNameNode sn = null; NameNode nn = null; try { cluster = new MiniDFSCluster(0, config, 1, true, false, false, null, null, null, null); cluster.waitActive(); nn = cluster.getNameNode(); assertNotNull(nn); // start secondary node LOG.info("--starting SecondNN"); sn = new SecondaryNameNode(config); assertNotNull(sn); LOG.info("--doing checkpoint"); sn.doCheckpoint(); // this shouldn't fail LOG.info("--done checkpoint"); // now verify that image and edits are created in the different directories FSImage image = nn.getFSImage(); StorageDirectory sd = image.getStorageDir(0); //only one assertEquals(sd.getStorageDirType(), NameNodeDirType.IMAGE_AND_EDITS); File imf = FSImage.getImageFile(sd, NameNodeFile.IMAGE); File edf = FSImage.getImageFile(sd, NameNodeFile.EDITS); LOG.info("--image file " + imf.getAbsolutePath() + "; len = " + imf.length()); LOG.info("--edits file " + edf.getAbsolutePath() + "; len = " + edf.length()); FSImage chkpImage = sn.getFSImage(); verifyDifferentDirs(chkpImage, imf.length(), edf.length()); } catch (IOException e) { fail(StringUtils.stringifyException(e)); System.err.println("checkpoint failed"); throw e; } finally { if(sn!=null) sn.shutdown(); if(cluster!=null) cluster.shutdown(); } } /** Test SafeMode counts only complete blocks */ @Test(timeout=60000) public void testGetBlocks() throws Exception { final Configuration CONF = new Configuration(); config.set(DFSConfigKeys.DFS_NAMENODE_SAFEMODE_THRESHOLD_PCT_KEY, "1.0f"); MiniDFSCluster cluster = new MiniDFSCluster(CONF, 2, true, null); try { cluster.waitActive(); // Create a file and add one block, but not write to DataNode DFSClient client = new DFSClient(CONF); client.namenode.create("/tmp1.txt", new FsPermission("755"), "clientName", false, (short) 2, 1024); client.namenode.addBlock("/tmp1.txt", "clientName", new DatanodeInfo[0]); // Restart NameNode waiting for exiting safemode, ensure NameNode doesn't // get stuck in safemode cluster.restartNameNode(); } finally { cluster.shutdown(); } } }
3e1537bcb3a264a37a0e8d74be041bcc234a49e0
690
java
Java
actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/viewmodel/UploadFileVMCallback.java
qinFamily/dangchat-sdk
fd0f55a13aeb618bc0c5af47fd5ee11f6709c914
[ "Apache-2.0" ]
1
2016-12-31T07:15:15.000Z
2016-12-31T07:15:15.000Z
actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/viewmodel/UploadFileVMCallback.java
qinFamily/dangchat-sdk
fd0f55a13aeb618bc0c5af47fd5ee11f6709c914
[ "Apache-2.0" ]
null
null
null
actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/viewmodel/UploadFileVMCallback.java
qinFamily/dangchat-sdk
fd0f55a13aeb618bc0c5af47fd5ee11f6709c914
[ "Apache-2.0" ]
16
2016-07-23T05:22:42.000Z
2019-05-25T23:37:21.000Z
20.909091
74
0.607246
9,016
/* * Copyright (C) 2015 Actor LLC. <https://actor.im> */ package im.actor.core.viewmodel; import com.google.j2objc.annotations.ObjectiveCName; /** * Upload file View Model callback. Methods always called on Main thread. */ public interface UploadFileVMCallback { /** * On File not uploading */ @ObjectiveCName("onNotUploaded") void onNotUploaded(); /** * On File upload in progress * * @param progress progress value in [0..1] */ @ObjectiveCName("onUploading:") void onUploading(float progress); /** * On file uploaded */ @ObjectiveCName("onUploaded") void onUploaded(); }
3e15388255b5b7689e2ebb73a62257b54257839d
2,258
java
Java
src/test/java/seedu/address/model/interviews/InterviewsTest.java
DanielDSSim/main
bf6ec4aa0b11cfcd3d30fd1bbe3ed437bc785001
[ "MIT" ]
null
null
null
src/test/java/seedu/address/model/interviews/InterviewsTest.java
DanielDSSim/main
bf6ec4aa0b11cfcd3d30fd1bbe3ed437bc785001
[ "MIT" ]
null
null
null
src/test/java/seedu/address/model/interviews/InterviewsTest.java
DanielDSSim/main
bf6ec4aa0b11cfcd3d30fd1bbe3ed437bc785001
[ "MIT" ]
null
null
null
33.701493
79
0.65279
9,017
package seedu.address.model.interviews; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static seedu.address.testutil.TypicalObjects.getTypicalPersons; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Set; import org.junit.Test; public class InterviewsTest { @Test public void generateNoWeekdays() { Interviews interviews = new Interviews(); interviews.generate(getTypicalPersons()); Set<Calendar> calendars = interviews.getInterviewsHashMap().keySet(); for (Calendar calendar : calendars) { assertFalse(calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY); } } @Test public void generateExcludeBlockOutOneDay() { Interviews interviews = new Interviews(); List<Calendar> dates = new ArrayList<>(); Calendar date = Calendar.getInstance(); date.add(Calendar.DATE, 2); interviews.setBlockOutDates(dates); interviews.generate(getTypicalPersons()); Set<Calendar> calendars = interviews.getInterviewsHashMap().keySet(); for (Calendar calendar : calendars) { assertFalse(Interviews.containsDate(dates, calendar)); } } @Test public void generateExcludeBlockOutDates() { Interviews interviews = new Interviews(); List<Calendar> dates = new ArrayList<>(); Calendar date = Calendar.getInstance(); for (int i = 0; i < 3; i++) { date.add(Calendar.DATE, 1); dates.add(date); date = (Calendar) date.clone(); } interviews.setBlockOutDates(dates); interviews.generate(getTypicalPersons()); Set<Calendar> calendars = interviews.getInterviewsHashMap().keySet(); for (Calendar calendar : calendars) { assertFalse(Interviews.containsDate(dates, calendar)); } } @Test public void clear() { Interviews interviews = new Interviews(); interviews.generate(getTypicalPersons()); interviews.clear(); assertTrue(interviews.getInterviewsHashMap().isEmpty()); } }
3e1539fd3a121024b432c3ca5db87dac3a34106f
4,309
java
Java
docstore-java/src/main/java/org/kuali/ole/docstore/model/bagit/BagCreator.java
ostephens/KBPlus
e57d79ac490036d3b2c6bfc7e903ddec667ef380
[ "CC-BY-3.0" ]
4
2015-05-27T15:21:22.000Z
2016-05-07T00:27:34.000Z
docstore-java/src/main/java/org/kuali/ole/docstore/model/bagit/BagCreator.java
ostephens/KBPlus
e57d79ac490036d3b2c6bfc7e903ddec667ef380
[ "CC-BY-3.0" ]
222
2015-01-14T13:26:52.000Z
2022-03-17T22:53:44.000Z
docstore-java/src/main/java/org/kuali/ole/docstore/model/bagit/BagCreator.java
ostephens/KBPlus
e57d79ac490036d3b2c6bfc7e903ddec667ef380
[ "CC-BY-3.0" ]
6
2015-02-19T15:54:59.000Z
2019-08-16T02:49:13.000Z
31.224638
108
0.640752
9,018
/** * Copyright 2012 Trustees of the University of Pennsylvania * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.ole.docstore.model.bagit; import gov.loc.repository.bagit.BagFactory; import gov.loc.repository.bagit.PreBag; import org.apache.commons.compress.utils.IOUtils; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * @author upennlib */ public class BagCreator { public static final BagFactory bf = new BagFactory(); private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(BagCreator.class); public static void main(String[] args) throws IOException { // File input = new File(args[0]); //File input=new File("C://InterviewQuestions.txt"); File input = new File("C:\\projects\\KB+\\documents\\save\\input"); // File input=new File("\\java\\drivers\\ojdbc14.jar"); //File input=new File("org\\kuali\\ole\\bulkhandler\\nar.xml"); BagCreator bagCreator = new BagCreator(); File file=BagCreator.createBag(input); System.out.println("file "+file.getAbsolutePath()); bagCreator.test(); System.out.println(""); } public void test() { URL resource = getClass().getResource("/org/kuali/ole/repository/requestKBPlus.xml"); } /** * * @param bagSource * @return * @throws IOException */ public static File createBag(File bagSource) throws IOException { LOG.info("in createBag "); File tempDir = File.createTempFile("bag.", ".dir"); LOG.info("in createBag tempDir "+tempDir); FileUtils.deleteQuietly(tempDir); LOG.info("in createBag after deleteQuietly"); File bagDir = new File(tempDir, "bag_dir"); bagDir.mkdirs(); LOG.info("in createBag bagDir "+bagDir.getAbsolutePath()); FileUtils.copyDirectory(bagSource, bagDir); PreBag preBag; synchronized (bf) { preBag = bf.createPreBag(bagDir); } preBag.makeBagInPlace(BagFactory.Version.V0_96, false); File zipFile = zipDirectory(tempDir); FileUtils.deleteQuietly(tempDir); LOG.info("in createBag bagDir after deleteQuietly again "); LOG.info("zipFile "+zipFile.getAbsolutePath()); return zipFile; } /** * * @param directory * @return * @throws IOException */ private static File zipDirectory(File directory) throws IOException { File testZip = File.createTempFile("bag.", ".zip"); String path = directory.getAbsolutePath(); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(testZip)); ArrayList<File> fileList = getFileList(directory); for (File file : fileList) { ZipEntry ze = new ZipEntry(file.getAbsolutePath().substring(path.length() + 1)); zos.putNextEntry(ze); FileInputStream fis = new FileInputStream(file); IOUtils.copy(fis, zos); fis.close(); zos.closeEntry(); } zos.close(); return testZip; } /** * * @param file * @return */ private static ArrayList<File> getFileList(File file) { ArrayList<File> fileList = new ArrayList<File>(); if (file.isFile()) { fileList.add(file); } else if (file.isDirectory()) { for (File innerFile : file.listFiles()) { fileList.addAll(getFileList(innerFile)); } } return fileList; } }
3e153c8b145a2fc2bff36357d65a863c8009d7dc
552
java
Java
src/main/java/me/memerator/api/client/entities/Rating.java
Memerator/memerator-sdk-java
825e6fdfce6ed63052057a80c523e7d6a1a319c2
[ "MIT" ]
null
null
null
src/main/java/me/memerator/api/client/entities/Rating.java
Memerator/memerator-sdk-java
825e6fdfce6ed63052057a80c523e7d6a1a319c2
[ "MIT" ]
null
null
null
src/main/java/me/memerator/api/client/entities/Rating.java
Memerator/memerator-sdk-java
825e6fdfce6ed63052057a80c523e7d6a1a319c2
[ "MIT" ]
null
null
null
18.4
56
0.594203
9,019
package me.memerator.api.client.entities; import java.time.OffsetDateTime; public interface Rating { /** * Get the user who rated this meme * @return the user */ User getUser(); /** * Get the rating the user gave * @return the rating */ int getRating(); /** * The timestamp of this rating as an OffsetDateTime * @return the timestamp */ OffsetDateTime getTimestamp(); /** * Get the meme associated with this Rating * @return the meme */ Meme getMeme(); }
3e153d7cdf7c5333d123b65e96a52de296b8602f
4,971
java
Java
protocols/openflow/api/src/main/java/org/onosproject/openflow/controller/OpenFlowController.java
mary-grace/onos
c0e351f8b84537bb7562e148d4cb2b9f06e8a727
[ "Apache-2.0" ]
1,091
2015-01-06T11:10:40.000Z
2022-03-30T09:09:05.000Z
protocols/openflow/api/src/main/java/org/onosproject/openflow/controller/OpenFlowController.java
mary-grace/onos
c0e351f8b84537bb7562e148d4cb2b9f06e8a727
[ "Apache-2.0" ]
39
2015-02-13T19:58:32.000Z
2022-03-02T02:38:07.000Z
protocols/openflow/api/src/main/java/org/onosproject/openflow/controller/OpenFlowController.java
mary-grace/onos
c0e351f8b84537bb7562e148d4cb2b9f06e8a727
[ "Apache-2.0" ]
914
2015-01-05T19:42:35.000Z
2022-03-30T09:25:18.000Z
29.241176
87
0.676524
9,020
/* * Copyright 2015-present Open Networking Foundation * * 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.onosproject.openflow.controller; import org.projectfloodlight.openflow.protocol.OFMessage; import java.util.concurrent.CompletableFuture; /** * Abstraction of an OpenFlow controller. Serves as a one stop * shop for obtaining OpenFlow devices and (un)register listeners * on OpenFlow events */ public interface OpenFlowController { /** * Returns all switches known to this OF controller. * @return Iterable of dpid elements */ Iterable<OpenFlowSwitch> getSwitches(); /** * Returns all master switches known to this OF controller. * @return Iterable of dpid elements */ Iterable<OpenFlowSwitch> getMasterSwitches(); /** * Returns all equal switches known to this OF controller. * @return Iterable of dpid elements */ Iterable<OpenFlowSwitch> getEqualSwitches(); /** * Returns the actual switch for the given Dpid. * @param dpid the switch to fetch * @return the interface to this switch */ OpenFlowSwitch getSwitch(Dpid dpid); /** * Returns the actual master switch for the given Dpid, if one exists. * @param dpid the switch to fetch * @return the interface to this switch */ OpenFlowSwitch getMasterSwitch(Dpid dpid); /** * Returns the actual equal switch for the given Dpid, if one exists. * @param dpid the switch to fetch * @return the interface to this switch */ OpenFlowSwitch getEqualSwitch(Dpid dpid); /** * Register a listener for meta events that occur to OF * devices. * @param listener the listener to notify */ void addListener(OpenFlowSwitchListener listener); /** * Unregister a listener. * * @param listener the listener to unregister */ void removeListener(OpenFlowSwitchListener listener); /** * Register a listener for all OF msg types. * * @param listener the listener to notify */ void addMessageListener(OpenFlowMessageListener listener); /** * Unregister a listener for all OF msg types. * * @param listener the listener to notify */ void removeMessageListener(OpenFlowMessageListener listener); /** * Register a listener for packet events. * @param priority the importance of this listener, lower values are more important * @param listener the listener to notify */ void addPacketListener(int priority, PacketListener listener); /** * Unregister a listener. * * @param listener the listener to unregister */ void removePacketListener(PacketListener listener); /** * Register a listener for OF msg events. * * @param listener the listener to notify */ void addEventListener(OpenFlowEventListener listener); /** * Unregister a listener. * * @param listener the listener to unregister */ void removeEventListener(OpenFlowEventListener listener); /** * Send a message to a particular switch. * @param dpid the switch to send to. * @param msg the message to send */ void write(Dpid dpid, OFMessage msg); /** * Send a message to a particular switch and return the future response. * * @param dpid the switch to send to * @param msg the message to send * @return future for response message */ CompletableFuture<OFMessage> writeResponse(Dpid dpid, OFMessage msg); /** * Process a message and notify the appropriate listeners. * * @param dpid the dpid the message arrived on * @param msg the message to process. */ void processPacket(Dpid dpid, OFMessage msg); /** * Sets the role for a given switch. * @param role the desired role * @param dpid the switch to set the role for. */ void setRole(Dpid dpid, RoleState role); /** * Remove OpenFlow classifier listener from runtime store of classifiers listener. * * @param listener the OpenFlow classifier to remove */ void removeClassifierListener(OpenFlowClassifierListener listener); /** * Add OpenFlow classifier listener to runtime store of classifiers listener. * * @param listener the OpenFlow classifier listener */ void addClassifierListener(OpenFlowClassifierListener listener); }
3e153e818596a931d9777392d4536fb457a250f5
1,519
java
Java
src/com/facebook/buck/apple/AppleBinaryDescription.java
mread/buck
389ade2a0713a8b852f0935eab26d680cf40944b
[ "Apache-2.0" ]
null
null
null
src/com/facebook/buck/apple/AppleBinaryDescription.java
mread/buck
389ade2a0713a8b852f0935eab26d680cf40944b
[ "Apache-2.0" ]
null
null
null
src/com/facebook/buck/apple/AppleBinaryDescription.java
mread/buck
389ade2a0713a8b852f0935eab26d680cf40944b
[ "Apache-2.0" ]
null
null
null
31.645833
93
0.75576
9,021
/* * Copyright 2013-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.apple; import com.facebook.buck.rules.BuildRuleParams; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.BuildRuleType; import com.facebook.buck.rules.Description; public class AppleBinaryDescription implements Description<AppleNativeTargetDescriptionArg> { public static final BuildRuleType TYPE = new BuildRuleType("apple_binary"); @Override public BuildRuleType getBuildRuleType() { return TYPE; } @Override public AppleNativeTargetDescriptionArg createUnpopulatedConstructorArg() { return new AppleNativeTargetDescriptionArg(); } @Override public <A extends AppleNativeTargetDescriptionArg> AppleBinary createBuildRule( BuildRuleParams params, BuildRuleResolver resolver, A args) { return new AppleBinary( params, args, TargetSources.ofAppleSources(args.srcs.get())); } }
3e153eccd38e172ce2f52e3084e57d006f8302f6
2,508
java
Java
src/test/java/com/jrj/test/TrainPrepared.java
1621740748/HanLP
c6683f97ee65cb6a632a2fefea4f25c192b2191c
[ "Apache-2.0" ]
null
null
null
src/test/java/com/jrj/test/TrainPrepared.java
1621740748/HanLP
c6683f97ee65cb6a632a2fefea4f25c192b2191c
[ "Apache-2.0" ]
null
null
null
src/test/java/com/jrj/test/TrainPrepared.java
1621740748/HanLP
c6683f97ee65cb6a632a2fefea4f25c192b2191c
[ "Apache-2.0" ]
null
null
null
24.115385
83
0.618421
9,022
package com.jrj.test; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.List; import com.alibaba.fastjson.JSON; import com.hankcs.hanlp.HanLP; import com.hankcs.hanlp.dictionary.stopword.CoreStopWordDictionary; import com.hankcs.hanlp.seg.common.Term; public class TrainPrepared { public static void main(String[] args) { String f = "/data/baidu1/news2016zh_train.json"; FileInputStream fi = null; BufferedReader fp = null; String fo="/data/baidu1/news2016zh_train.txt"; BufferedWriter fw=null; try { fw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fo),"utf-8")); fi = new FileInputStream(f); InputStreamReader fileReader = new InputStreamReader(fi, "utf-8"); fp = new BufferedReader(fileReader); String line=null; int i = 0; StringBuilder ww=new StringBuilder(); do { try { line = fp.readLine(); String l=null; if(line==null) { break; } try { l = JSON.parseObject(line).getString("content"); } catch (Exception e) { e.printStackTrace(); } if(l==null||l.equals("")) { continue; } List<Term> termList = HanLP.segment(l); for(Term t:termList) { if(CoreStopWordDictionary.contains(t.word)) { continue; } System.out.print(t.word+" "); ww.append(t.word).append(" "); } // JiebaSegmenter segmenter = new JiebaSegmenter(); // List<String> aa = segmenter.sentenceProcess(l); // for (String s : aa) { // if (CoreStopWordDictionary.contains(s)) { // continue; // } // System.out.print(s+" "); // } System.out.println(); ww.append("\n"); i++; if (i>0&&i%10000==0) { String s=ww.toString(); fw.write(s); ww.setLength(0); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } while (line != null); //写入剩余的数据 if(ww.length()>0) { String s=ww.toString(); fw.write(s); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { fp.close(); fi.close(); fw.close(); } catch (IOException e) { e.printStackTrace(); } } } }
3e153f31b3c5be5c84e47a680f10e0182492fdab
1,730
java
Java
src/main/java/de/gre90r/DreamAudioRecorder/controller/Stopwatch.java
gre90r/Audio-Recorder
9cad2f2970fb1766dcb1ec9f18ec086236e9b943
[ "MIT" ]
null
null
null
src/main/java/de/gre90r/DreamAudioRecorder/controller/Stopwatch.java
gre90r/Audio-Recorder
9cad2f2970fb1766dcb1ec9f18ec086236e9b943
[ "MIT" ]
null
null
null
src/main/java/de/gre90r/DreamAudioRecorder/controller/Stopwatch.java
gre90r/Audio-Recorder
9cad2f2970fb1766dcb1ec9f18ec086236e9b943
[ "MIT" ]
null
null
null
25.441176
93
0.633526
9,023
package de.gre90r.DreamAudioRecorder.controller; import javax.swing.*; /** * counts the recording time and displays * it on UI. */ public class Stopwatch implements Runnable { // controls the termination of the stopwatch thread private boolean isRunning = true; // UI element which displays recording time private JLabel labelStatus; private JLabel labelRecordingTime; /** * create stopwatch. Needs labelStatus to write * current time passed. * @param labelStatus the label which displays the current * recording time. */ public Stopwatch(JLabel labelStatus, JLabel labelRecordingTime) { this.labelStatus = labelStatus; this.labelRecordingTime = labelRecordingTime; } /** * stopwatch thread counts recording time * and writes to the label which displays * the recording time. */ @Override public void run() { int seconds = 0; int minutes = 0; while (isRunning) { // display recording time this.labelStatus.setText("Status: recording"); this.labelRecordingTime.setText("Recording time: " + minutes + ":" + ((seconds < 10) ? "0" : "") + seconds); // always display seconds as two digits // thread sleep try { Thread.sleep(1000); } catch (InterruptedException e) { System.err.println("interrupted exception occurred in stopwatch thread. " + "will terminate stopwatch"); this.isRunning = false; } // increase time seconds++; if (seconds >= 60) { seconds = 0; minutes++; } } } /** * safely stops the stopwatch thread */ public void stopStopwatch() { this.isRunning = false; } }
3e153f6d3fa2c45b78b58d99a4b58efdc41de0ad
2,281
java
Java
gulimall-product/src/main/java/site/wanjiahao/gulimall/product/app/SpuImagesController.java
1725136424/gulimall
79a766c338cbd652a24a3985a431a2edc75da384
[ "Apache-2.0" ]
null
null
null
gulimall-product/src/main/java/site/wanjiahao/gulimall/product/app/SpuImagesController.java
1725136424/gulimall
79a766c338cbd652a24a3985a431a2edc75da384
[ "Apache-2.0" ]
null
null
null
gulimall-product/src/main/java/site/wanjiahao/gulimall/product/app/SpuImagesController.java
1725136424/gulimall
79a766c338cbd652a24a3985a431a2edc75da384
[ "Apache-2.0" ]
null
null
null
25.065934
64
0.698378
9,024
package site.wanjiahao.gulimall.product.app; import java.util.Arrays; import java.util.Map; // import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import site.wanjiahao.gulimall.product.entity.SpuImagesEntity; import site.wanjiahao.gulimall.product.service.SpuImagesService; import site.wanjiahao.common.utils.PageUtils; import site.wanjiahao.common.utils.R; /** * spu图片 * * @author haodada * @email ychag@example.com * @date 2020-10-15 21:07:35 */ @RestController @RequestMapping("product/spuimages") public class SpuImagesController { @Autowired private SpuImagesService spuImagesService; /** * 列表 */ @RequestMapping("/list") // @RequiresPermissions("product:spuimages:list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = spuImagesService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") // @RequiresPermissions("product:spuimages:info") public R info(@PathVariable("id") Long id){ SpuImagesEntity spuImages = spuImagesService.getById(id); return R.ok().put("spuImages", spuImages); } /** * 保存 */ @RequestMapping("/save") // @RequiresPermissions("product:spuimages:save") public R save(@RequestBody SpuImagesEntity spuImages){ spuImagesService.save(spuImages); return R.ok(); } /** * 修改 */ @RequestMapping("/update") // @RequiresPermissions("product:spuimages:update") public R update(@RequestBody SpuImagesEntity spuImages){ spuImagesService.updateById(spuImages); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") // @RequiresPermissions("product:spuimages:delete") public R delete(@RequestBody Long[] ids){ spuImagesService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
3e154036abe2f5d6209d24010d0d7bf9b8d0ae44
12,036
java
Java
RapidViewDemo/app/src/main/java/com/tencent/rapidview/lua/interfaceimpl/LuaJavaViewWrapper.java
Tencent/RapidView
768bc686d6f7f314022e6ec9e27331f0f0f69c22
[ "MIT" ]
1,045
2017-10-30T07:42:12.000Z
2022-03-30T11:55:06.000Z
rapidview/lua/interfaceimpl/LuaJavaViewWrapper.java
Tencent/RapidView
768bc686d6f7f314022e6ec9e27331f0f0f69c22
[ "MIT" ]
14
2017-10-31T05:44:23.000Z
2019-09-05T10:20:06.000Z
rapidview/lua/interfaceimpl/LuaJavaViewWrapper.java
Tencent/RapidView
768bc686d6f7f314022e6ec9e27331f0f0f69c22
[ "MIT" ]
111
2017-10-30T11:45:36.000Z
2021-02-23T20:55:14.000Z
32.706522
191
0.589398
9,025
/*************************************************************************************************** Tencent is pleased to support the open source community by making RapidView available. Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MITLicense (the "License"); you may not use this file except in compliance withthe License. You mayobtain a copy of the License at http://opensource.org/licenses/MIT 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.tencent.rapidview.lua.interfaceimpl; import android.view.ViewGroup; import com.tencent.rapidview.RapidLoader; import com.tencent.rapidview.deobfuscated.IRapidActionListener; import com.tencent.rapidview.data.RapidDataBinder; import com.tencent.rapidview.data.Var; import com.tencent.rapidview.deobfuscated.IRapidNode; import com.tencent.rapidview.deobfuscated.IRapidView; import com.tencent.rapidview.deobfuscated.IRapidViewGroup; import com.tencent.rapidview.framework.RapidConfig; import com.tencent.rapidview.framework.RapidObject; import com.tencent.rapidview.framework.RapidRuntimeCachePool; import com.tencent.rapidview.param.ParamsChooser; import com.tencent.rapidview.parser.RapidParserObject; import com.tencent.rapidview.utils.RapidDataUtils; import com.tencent.rapidview.utils.RapidStringUtils; import com.tencent.rapidview.utils.XLog; import org.luaj.vm2.LuaTable; import org.luaj.vm2.LuaValue; import org.luaj.vm2.lib.jse.CoerceJavaToLua; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @Class LuaJavaViewWrapper * @Desc 添加View到指定的位置 * * @author arlozhang * @date 2017.02.20 */ public class LuaJavaViewWrapper extends RapidLuaJavaObject{ public LuaJavaViewWrapper(String rapidID, IRapidView rapidView){ super(rapidID, rapidView); } public LuaValue loadView(String viewName, String params, Object data, IRapidActionListener listener){ IRapidView view = null; LuaValue ret = null; Map<String, Var> map = null; if( data instanceof LuaTable ){ map = RapidDataUtils.translateData((LuaTable) data); } if( data instanceof Map ){ map = (Map<String, Var>)data; } if( map == null ){ map = new ConcurrentHashMap<String, Var>(); } try{ view = _loadView(viewName, params, map, listener); } catch (Exception e){ e.printStackTrace(); } if( view != null ){ ret = CoerceJavaToLua.coerce(view); } return ret; } public LuaValue loadView(String viewName, String params, Map<String, Var> data, IRapidActionListener listener){ IRapidView view = null; LuaValue ret = null; try{ view = _loadView(viewName, params, data, listener); } catch (Exception e){ e.printStackTrace(); } if( view != null ){ ret = CoerceJavaToLua.coerce(view); } return ret; } public LuaValue addView(String xmlName, String parentID, String above, RapidDataBinder binder, Object data, IRapidActionListener listener){ LuaValue value = null; Map<String, Var> map = null; if( data instanceof LuaTable ){ map = RapidDataUtils.translateData((LuaTable) data); } if( data instanceof Map ){ map = (Map<String, Var>)data; } if( map == null ){ map = new ConcurrentHashMap<String, Var>(); } try{ value = _addView(xmlName, parentID, above, binder, map, listener); } catch (Exception e){ e.printStackTrace(); } return value; } public LuaValue removeView(String id){ IRapidView rmView = mRapidView.getParser().getChildView(id); IRapidView parent = null; if( rmView == null ){ return null; } parent = rmView.getParser().getParentView(); if( parent == null ){ return null; } parent.getParser().mMapChild.remove(rmView.getParser().getID()); parent.getParser().mArrayChild = removeArrayView(parent.getParser().mArrayChild, rmView); ((ViewGroup)parent.getView()).removeView(rmView.getView()); return CoerceJavaToLua.coerce(rmView); } private IRapidView[] removeArrayView(IRapidView[] arrayView, IRapidView rmView){ IRapidView[] arrayNewView; int index = 0; if( rmView == null ){ return arrayView; } if( arrayView == null ){ return new IRapidView[0]; } else{ arrayNewView = new IRapidView[arrayView.length - 1]; } for( int i = 0; i < arrayNewView.length; i++ ){ if( arrayView[i] == rmView ){ index++; } arrayNewView[i] = arrayView[index]; index++; } return arrayNewView; } private IRapidView _loadView(String view, String params, Map<String, Var> map, IRapidActionListener listener){ IRapidView loadView = null; RapidParserObject parser = getParser(); if( parser == null || RapidStringUtils.isEmpty(view) ){ return null; } if( view.contains(".")){ RapidObject object = RapidRuntimeCachePool.getInstance().get(mRapidID, view, parser.isLimitLevel()); loadView = object.load(parser.getUIHandler(), parser.getContext(), ParamsChooser.getParamsClass(params), map, listener == null ? parser.getActionListener() : listener); } else{ loadView = RapidLoader.load(view, parser.getUIHandler(), parser.getContext(), ParamsChooser.getParamsClass(params), map, listener == null ? parser.getActionListener() : listener); } return loadView; } private LuaValue _addView(String xmlName, String parentID, String above, RapidDataBinder binder, Map<String, Var> map, IRapidActionListener listener){ IRapidView addView = null; int indexOfAbove = -1; IRapidViewGroup parentView = null; IRapidView aboveView = null; ViewGroup parent = null; RapidObject object = null; RapidParserObject parser = getParser(); if( parser == null || RapidStringUtils.isEmpty(xmlName) || RapidStringUtils.isEmpty(parentID) ){ return null; } if( mRapidView == null ){ XLog.d(RapidConfig.RAPID_ERROR_TAG, "AddView接口原有视图为空"); return null; } if( !RapidStringUtils.isEmpty(parentID) ){ IRapidView view = null; view = mRapidView.getParser().getChildView(parentID); if( view instanceof IRapidViewGroup ){ parentView = (IRapidViewGroup) view; } } object = RapidRuntimeCachePool.getInstance().get(mRapidID, xmlName, parser.isLimitLevel()); addView = object.load( parser.getUIHandler(), parser.getContext(), parentView == null ? parser.getParams().getClass() : parentView.createParams(getParser().getContext()).getClass(), new ConcurrentHashMap<String, Var>(), listener == null ? parser.getActionListener() : listener ); if( addView == null ){ XLog.d(RapidConfig.RAPID_ERROR_TAG, "AddView接口需要添加的视图加载失败:" + xmlName + "(photonID:" + mRapidID + ")"); return null; } addView.getParser().getTaskCenter().notify(IRapidNode.HOOK_TYPE.enum_data_start, ""); addView.getParser().getBinder().update(map); addView.getParser().getTaskCenter().notify(IRapidNode.HOOK_TYPE.enum_data_end, ""); if( RapidStringUtils.isEmpty(parentID) && RapidStringUtils.isEmpty(above) ){ XLog.d(RapidConfig.RAPID_ERROR_TAG, "未指定父视图(parent)或底视图(above)"); return null; } if( !RapidStringUtils.isEmpty(above) ){ IRapidViewGroup aboveParentView = null; aboveView = mRapidView.getParser().getChildView(above); if( aboveView != null ){ aboveParentView = aboveView.getParser().getParentView(); if( aboveParentView == null ){ XLog.d(RapidConfig.RAPID_ERROR_TAG, "above视图处于根节点,无法向根节点添加View"); return null; } if( parentView == null ){ parentView = aboveParentView; } else if( parentView.getParser().getID().compareTo(aboveParentView.getParser().getID()) != 0 ){ XLog.d(RapidConfig.RAPID_ERROR_TAG, "指定的parentView和aboveView的父视图不相同"); return null; } } else{ XLog.d(RapidConfig.RAPID_ERROR_TAG, "找不到aboveView:" + above); } } if ( parentView == null ){ XLog.d(RapidConfig.RAPID_ERROR_TAG, "AddViewAction获取光子父视图视图失败"); return null; } parent = (ViewGroup) parentView.getView(); if( parent == null || !(parentView instanceof IRapidViewGroup) || !(parentView.getView() instanceof ViewGroup) ){ XLog.d(RapidConfig.RAPID_ERROR_TAG, "AddViewAction父视图为空"); return null; } if( aboveView != null ){ if( aboveView.getView() == null ){ XLog.d(RapidConfig.RAPID_ERROR_TAG, "AboveView为空"); return null; } indexOfAbove = parent.indexOfChild(aboveView.getView()); } if( indexOfAbove == -1 || indexOfAbove >= parent.getChildCount() ){ parent.addView(addView.getView(), addView.getParser().getParams().getLayoutParams()); } else{ parent.addView(addView.getView(), indexOfAbove, addView.getParser().getParams().getLayoutParams()); } addView.getParser().mBrotherMap = parentView.getParser().mMapChild; parentView.getParser().mArrayChild = addArrayView(parentView.getParser().mArrayChild, addView); if( parentView.getParser().mMapChild.get(addView.getParser().getID()) != null ){ XLog.d(RapidConfig.RAPID_ERROR_TAG, "AddViewAction父视图ID冲突:" + addView.getParser().getID()); } parentView.getParser().mMapChild.put(addView.getParser().getID(), addView); addView.getParser().setParentView(parentView); addView.getParser().setIndexInParent(parent.indexOfChild(addView.getView())); return CoerceJavaToLua.coerce(addView); } private IRapidView[] addArrayView(IRapidView[] arrayView, IRapidView addView){ IRapidView[] arrayNewView; int originArrayLenth = 0; if( addView == null ){ return arrayView; } if( arrayView == null ){ arrayNewView = new IRapidView[1]; originArrayLenth = 0; } else{ arrayNewView = new IRapidView[arrayView.length + 1]; originArrayLenth = arrayView.length; } for( int i = 0; i < originArrayLenth; i++ ){ arrayNewView[i] = arrayView[i]; } arrayNewView[originArrayLenth] = addView; return arrayNewView; } }
3e154141a3c3b156e09eb8fdbb3711aad86148a2
1,948
java
Java
engine/src/main/java/org/terasology/rendering/dag/ConditionDependentNode.java
4Denthusiast/Terasology
0a13602a2966d800e591e9b944d3908cda092205
[ "Apache-2.0" ]
3
2016-05-14T22:55:53.000Z
2017-06-13T17:20:13.000Z
engine/src/main/java/org/terasology/rendering/dag/ConditionDependentNode.java
4Denthusiast/Terasology
0a13602a2966d800e591e9b944d3908cda092205
[ "Apache-2.0" ]
16
2016-05-01T03:22:35.000Z
2016-05-02T00:16:43.000Z
engine/src/main/java/org/terasology/rendering/dag/ConditionDependentNode.java
4Denthusiast/Terasology
0a13602a2966d800e591e9b944d3908cda092205
[ "Apache-2.0" ]
1
2015-10-30T02:42:44.000Z
2015-10-30T02:42:44.000Z
30.920635
101
0.73152
9,026
/* * Copyright 2017 MovingBlocks * * 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.terasology.rendering.dag; import com.google.common.collect.Lists; import org.terasology.context.Context; import org.terasology.rendering.world.WorldRenderer; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.List; import java.util.function.Supplier; /** * TODO: Add javadocs */ public abstract class ConditionDependentNode extends AbstractNode implements PropertyChangeListener { private List<Supplier<Boolean>> conditions = Lists.newArrayList(); protected WorldRenderer worldRenderer; protected ConditionDependentNode(String nodeUri, Context context) { super(nodeUri, context); worldRenderer = context.get(WorldRenderer.class); } protected void requiresCondition(Supplier<Boolean> condition) { conditions.add(condition); } private boolean checkConditions() { boolean conditionsAreSatisfied = true; for (Supplier<Boolean> condition : conditions) { conditionsAreSatisfied = conditionsAreSatisfied && condition.get(); } return conditionsAreSatisfied; } @Override public boolean isEnabled() { return enabled && checkConditions(); } @Override public void propertyChange(PropertyChangeEvent event) { worldRenderer.requestTaskListRefresh(); } }
3e1542b003849e469322da5c55447c5d7b462b49
327
java
Java
demo/src/main/java/com/davita/nonreactivedemo/DemoApplication.java
alephzed/baeldung-tutorials
37bd40380cf9f5e8458cd3f0dbffbd62f8025d9e
[ "MIT" ]
null
null
null
demo/src/main/java/com/davita/nonreactivedemo/DemoApplication.java
alephzed/baeldung-tutorials
37bd40380cf9f5e8458cd3f0dbffbd62f8025d9e
[ "MIT" ]
null
null
null
demo/src/main/java/com/davita/nonreactivedemo/DemoApplication.java
alephzed/baeldung-tutorials
37bd40380cf9f5e8458cd3f0dbffbd62f8025d9e
[ "MIT" ]
1
2021-09-17T19:43:10.000Z
2021-09-17T19:43:10.000Z
23.357143
68
0.792049
9,027
package com.davita.nonreactivedemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
3e1542c825d561c3747717b385549b5ab26807f5
4,105
java
Java
nginious-eclipse/src/main/java/com/nginious/http/plugin/HttpServerProcess.java
bojanp/Nginious
47924e4cc22aec1aaabf267a0011ccb2006e729a
[ "Apache-2.0" ]
null
null
null
nginious-eclipse/src/main/java/com/nginious/http/plugin/HttpServerProcess.java
bojanp/Nginious
47924e4cc22aec1aaabf267a0011ccb2006e729a
[ "Apache-2.0" ]
null
null
null
nginious-eclipse/src/main/java/com/nginious/http/plugin/HttpServerProcess.java
bojanp/Nginious
47924e4cc22aec1aaabf267a0011ccb2006e729a
[ "Apache-2.0" ]
null
null
null
27.006579
125
0.723995
9,028
package com.nginious.http.plugin; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; class HttpServerProcess { private Process process; private String projectName; private int listenPort; private int minMemory; private int maxMemory; private String adminPassword; private File webappPath; private String accessLogPath; private String serverLogPath; private Logger logger; HttpServerProcess(String projectName, int listenPort, String adminPassword, int minMemory, int maxMemory, File webappPath, Logger logger) { super(); this.projectName = projectName; this.listenPort = listenPort; this.minMemory = minMemory; this.maxMemory = maxMemory; this.adminPassword = adminPassword; this.webappPath = webappPath; this.accessLogPath = buildAccessLogPath(); this.serverLogPath = buildServerLogPath(); this.logger = logger; } String getAccessLogPath() { return this.accessLogPath; } String getServerLogPath() { return this.serverLogPath; } void start() throws IOException { String classPath = buildClasspath(); String javaRuntime = buildJavaRuntime(); String accessLog = this.accessLogPath; String serverLog = this.serverLogPath; String minMemoryArg = "-Xms" + this.minMemory + "m"; String maxMemoryArg = "-Xmx" + this.maxMemory + "m"; String[] cmd = { javaRuntime, minMemoryArg, maxMemoryArg, "-cp", classPath, "com.nginious.http.server.Main", "-p", Integer.toString(this.listenPort), "-a", this.adminPassword, "-w", this.webappPath.getAbsolutePath(), "-S", serverLog, "-A", accessLog }; Object[] params = { javaRuntime, classPath, this.webappPath.getAbsolutePath(), accessLog, serverLog }; logger.log("HttpServerProcess.start javaRuntime={0}, classpath={1}, webappPath={2}, accessLog={3}, serverLog={4}", params); this.process = Runtime.getRuntime().exec(cmd); } void stop() { logger.log("HttpServerProcess.stop"); if(this.process != null) { process.destroy(); try { process.waitFor(); } catch(InterruptedException e) {} } this.process = null; } private String buildAccessLogPath() { return buildLogPath("access"); } private String buildServerLogPath() { return buildLogPath("server"); } private String buildLogPath(String type) { String tmpDirPath = System.getProperty("java.io.tmpdir"); StringBuffer path = new StringBuffer(tmpDirPath); path.append(File.separator); path.append(this.projectName); path.append("_"); path.append(type); path.append(".log"); return path.toString(); } private String buildJavaRuntime() { String javaHome = System.getProperty("java.home"); File javaRuntime = new File(javaHome, "bin/java"); return javaRuntime.getAbsolutePath(); } private String buildClasspath() throws IOException { StringBuffer classPath = new StringBuffer(); URL serverURL = NginiousPlugin.getJar("nginious-server.jar"); String serverElement = createClasspathElement(serverURL); classPath.append(serverElement); URL apiURL = NginiousPlugin.getJar("nginious-api.jar"); String apiElement = createClasspathElement(apiURL); classPath.append(File.pathSeparator); classPath.append(apiElement); URL jsonURL = NginiousPlugin.getJar("json.jar"); String jsonElement = createClasspathElement(jsonURL); classPath.append(File.pathSeparator); classPath.append(jsonElement); URL asmURL = NginiousPlugin.getJar("asm-3.3.1.jar"); String asmElement = createClasspathElement(asmURL); classPath.append(File.pathSeparator); classPath.append(asmElement); URL log4jURL = NginiousPlugin.getJar("log4j-1.2.17.jar"); String log4jElement = createClasspathElement(log4jURL); classPath.append(File.pathSeparator); classPath.append(log4jElement); return classPath.toString(); } private String createClasspathElement(URL jarElement) { try { return new File(jarElement.toURI()).getAbsolutePath(); } catch(URISyntaxException e) { return new File(jarElement.getPath()).getAbsolutePath(); } } }
3e15431c0dfc545ba018834e7b485ed43c4c31a2
142
java
Java
core/src/main/java/com/github/gl8080/metagrid/core/domain/upload/csv/CsvRecordProcessor.java
opengl-8080/metagrid
d20ff4179376eb1f0714141ae8068bc87971b231
[ "MIT" ]
null
null
null
core/src/main/java/com/github/gl8080/metagrid/core/domain/upload/csv/CsvRecordProcessor.java
opengl-8080/metagrid
d20ff4179376eb1f0714141ae8068bc87971b231
[ "MIT" ]
11
2016-01-17T14:32:33.000Z
2016-02-13T11:32:59.000Z
core/src/main/java/com/github/gl8080/metagrid/core/domain/upload/csv/CsvRecordProcessor.java
opengl-8080/metagrid
d20ff4179376eb1f0714141ae8068bc87971b231
[ "MIT" ]
null
null
null
20.285714
59
0.711268
9,029
package com.github.gl8080.metagrid.core.domain.upload.csv; public interface CsvRecordProcessor<T> { void process(T record); }
3e1543c7ca13b7dc31680b23b31fddc309d17bb5
4,081
java
Java
java/src/com/pubnub/api/PubnubSync.java
palmzeed/JAVA-3.7.2
5a2c747a485ecbe068252984f6ac12756557bd80
[ "MIT" ]
1
2020-12-28T18:00:35.000Z
2020-12-28T18:00:35.000Z
java/src/com/pubnub/api/PubnubSync.java
chenguang89/java
5a2c747a485ecbe068252984f6ac12756557bd80
[ "MIT" ]
2
2020-12-28T20:10:27.000Z
2020-12-28T21:46:09.000Z
java/src/com/pubnub/api/PubnubSync.java
admdev8/java
a764fb2458f15d0d543d27dc56df4923a784a6c5
[ "MIT" ]
1
2020-12-23T14:49:12.000Z
2020-12-23T14:49:12.000Z
28.340278
119
0.620681
9,030
package com.pubnub.api; import org.json.JSONObject; import java.util.UUID; /** * PubnubSync object facilitates querying channels for messages and listening on * channels for presence/message events * * @author Pubnub * */ public class PubnubSync extends PubnubCoreSync implements PubnubSyncInterfacePam, PubnubSyncInterfacePush { /** * Pubnub Constructor * * @param publish_key * Publish Key * @param subscribe_key * Subscribe Key * @param secret_key * Secret Key * @param cipher_key * Cipher Key * @param ssl_on * SSL on ? */ public PubnubSync(String publish_key, String subscribe_key, String secret_key, String cipher_key, boolean ssl_on) { super(publish_key, subscribe_key, secret_key, cipher_key, ssl_on); } /** * Pubnub Constructor * * @param publish_key * Publish key * @param subscribe_key * Subscribe Key * @param secret_key * Secret Key * @param ssl_on * SSL on ? */ public PubnubSync(String publish_key, String subscribe_key, String secret_key, boolean ssl_on) { super(publish_key, subscribe_key, secret_key, "", ssl_on); } /** * Pubnub Constructor * * @param publish_key * Publish Key * @param subscribe_key * Subscribe Key */ public PubnubSync(String publish_key, String subscribe_key) { super(publish_key, subscribe_key, "", "", false); } /** * @param publish_key * Publish Key * @param subscribe_key * Subscribe Key * @param ssl */ public PubnubSync(String publish_key, String subscribe_key, boolean ssl) { super(publish_key, subscribe_key, "", "", ssl); } /** * @param publish_key * @param subscribe_key * @param secret_key */ public PubnubSync(String publish_key, String subscribe_key, String secret_key) { super(publish_key, subscribe_key, secret_key, "", false); } /** * * Constructor for Pubnub Class * * @param publish_key * Publish Key * @param subscribe_key * Subscribe Key * @param secret_key * Secret Key * @param cipher_key * Cipher Key * @param ssl_on * SSL enabled ? * @param initialization_vector * Initialization vector */ public PubnubSync(String publish_key, String subscribe_key, String secret_key, String cipher_key, boolean ssl_on, String initialization_vector) { super(publish_key, subscribe_key, secret_key, cipher_key, ssl_on, initialization_vector); } @Override public Object enablePushNotificationsOnChannel(String channel, String gcmRegistrationId) { return _enablePushNotificationsOnChannels(new String[] { channel }, gcmRegistrationId, null, true); } @Override public Object enablePushNotificationsOnChannels(String[] channels, String gcmRegistrationId) { return _enablePushNotificationsOnChannels(channels, gcmRegistrationId, null, true); } @Override public Object disablePushNotificationsOnChannel(String channel, String gcmRegistrationId) { return _disablePushNotificationsOnChannels(new String[] { channel }, gcmRegistrationId, null, true); } @Override public Object disablePushNotificationsOnChannels(String[] channels, String gcmRegistrationId) { return _disablePushNotificationsOnChannels(channels, gcmRegistrationId, null, true); } protected String getUserAgent() { return "Java-Sync/" + VERSION; } /** * Sets value for UUID * * @param uuid * UUID value for Pubnub client */ public void setUUID(UUID uuid) { this.UUID = uuid.toString(); } public String uuid() { return java.util.UUID.randomUUID().toString(); } }
3e15443d1367fff8c824b14795b5cc12a91686f3
6,748
java
Java
persistence/src/test/java/edu/softserve/zoo/persistence/test/repository/AnimalRepositoryTest.java
skyfenko/Kv-014
d09755194a16d6dd1c9db57a475163ac93b66f9d
[ "MIT" ]
3
2016-05-24T11:13:40.000Z
2016-06-26T21:54:09.000Z
persistence/src/test/java/edu/softserve/zoo/persistence/test/repository/AnimalRepositoryTest.java
skyfenko/Kv-014
d09755194a16d6dd1c9db57a475163ac93b66f9d
[ "MIT" ]
55
2016-04-14T10:36:35.000Z
2016-07-05T11:53:02.000Z
persistence/src/test/java/edu/softserve/zoo/persistence/test/repository/AnimalRepositoryTest.java
skyfenko/Kv-014
d09755194a16d6dd1c9db57a475163ac93b66f9d
[ "MIT" ]
7
2016-06-01T22:30:49.000Z
2020-11-19T10:18:56.000Z
37.910112
143
0.733106
9,031
package edu.softserve.zoo.persistence.test.repository; import edu.softserve.zoo.exceptions.ValidationException; import edu.softserve.zoo.model.Animal; import edu.softserve.zoo.model.House; import edu.softserve.zoo.model.Species; import edu.softserve.zoo.persistence.exception.PersistenceProviderException; import edu.softserve.zoo.persistence.exception.SpecificationException; import edu.softserve.zoo.persistence.repository.AnimalRepository; import edu.softserve.zoo.persistence.repository.Repository; import edu.softserve.zoo.persistence.specification.hibernate.impl.GetByIdSpecification; import edu.softserve.zoo.persistence.specification.hibernate.impl.animal.AnimalFindOneWithBirthdayHouseAndSpeciesSpecification; import edu.softserve.zoo.persistence.specification.hibernate.impl.animal.AnimalGetAllByHouseIdSpecification; import edu.softserve.zoo.persistence.specification.hibernate.impl.animal.AnimalGetAllBySpeciesIdSpecification; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import java.time.LocalDate; import static org.junit.Assert.*; /** * @author Serhii Alekseichenko */ @Transactional public class AnimalRepositoryTest extends AbstractRepositoryTest<Animal> { private static final Long EXISTENT_ANIMAL_ID = 1L; private static final Long EXISTENT_HOUSE_ID = 1L; private static final Long EXISTENT_SPECIES_ID = 161130L; private static final Long NONEXISTENT_ANIMAL_ID = 100L; private static final Long ANIMALS_AMOUNT = 17L; private static final Long NEXT_ANIMAL_ID = 18L; @Autowired private AnimalRepository animalRepository; @Test public void findOne() throws Exception { Animal expectedAnimal = getValidAnimal(); Animal actualAnimal = super.findOne(new GetByIdSpecification<>(Animal.class, EXISTENT_ANIMAL_ID), EXISTENT_ANIMAL_ID); assertByPrimaryFields(expectedAnimal, actualAnimal); } @Test public void findOneWithBirthdayHouseAndSpecies() throws Exception { Animal actualAnimal = super.findOne(new AnimalFindOneWithBirthdayHouseAndSpeciesSpecification(EXISTENT_ANIMAL_ID), EXISTENT_ANIMAL_ID); Assert.assertNotNull(actualAnimal.getBirthday()); Assert.assertNotNull(actualAnimal.getHouse()); Assert.assertNotNull(actualAnimal.getSpecies()); Assert.assertNull(actualAnimal.getNickname()); Assert.assertNull(actualAnimal.getFoodConsumption()); } @Test(expected = SpecificationException.class) public void findOneWithNullId() throws Exception { super.findOne(new GetByIdSpecification<>(Animal.class, null), null); } @Test public void findOneWithWrongId() throws Exception { Animal actual = animalRepository.findOne(new GetByIdSpecification<>(getType(), NONEXISTENT_ANIMAL_ID)); assertNull(actual); } @Test public void count() throws Exception { Long actualAmount = animalRepository.count(); assertEquals(ANIMALS_AMOUNT, actualAmount); } @Test public void save() throws Exception { Animal expectedAnimal = getValidAnimal(); Animal actualAnimal = super.save(expectedAnimal, NEXT_ANIMAL_ID); assertByPrimaryFields(expectedAnimal, actualAnimal); } @Test(expected = PersistenceProviderException.class) public void saveWithNullFields() throws Exception { Animal expectedAnimal = getValidAnimal(); expectedAnimal.setFoodConsumption(null); expectedAnimal.setHouse(null); expectedAnimal.setSpecies(null); super.save(expectedAnimal, NEXT_ANIMAL_ID); } @Test(expected = ValidationException.class) public void saveNullAnimal() throws Exception { animalRepository.save(null); } @Test public void delete() throws Exception { super.delete(EXISTENT_ANIMAL_ID); } @Test public void deleteWithWrongId() throws Exception { assertFalse(animalRepository.delete(NONEXISTENT_ANIMAL_ID, getType())); } @Test(expected = ValidationException.class) public void deleteWithNullId() throws Exception { super.delete(null); } @Test public void update() throws Exception { Animal expectedAnimal = findOne(new GetByIdSpecification<>(getType(), EXISTENT_ANIMAL_ID), EXISTENT_ANIMAL_ID); expectedAnimal.setNickname("Testy"); expectedAnimal.setFoodConsumption(42); Animal actualAnimal = super.update(expectedAnimal); assertByPrimaryFields(expectedAnimal, actualAnimal); } @Test(expected = PersistenceProviderException.class) public void updateWithNullFields() throws Exception { Animal expectedAnimal = findOne(new GetByIdSpecification<>(getType(), EXISTENT_ANIMAL_ID), EXISTENT_ANIMAL_ID); expectedAnimal.setFoodConsumption(null); expectedAnimal.setHouse(null); expectedAnimal.setSpecies(null); super.update(expectedAnimal); } @Test public void findBySpeciesId() throws Exception { super.find(new AnimalGetAllBySpeciesIdSpecification(EXISTENT_SPECIES_ID), 1); } @Test public void findByHouseIdId() throws Exception { super.find(new AnimalGetAllByHouseIdSpecification(EXISTENT_HOUSE_ID), 4); } @Test(expected = ValidationException.class) public void findWithNullSpecification() throws Exception { animalRepository.find(null); } @Override protected Repository<Animal> getRepository() { return animalRepository; } @Override protected Class<Animal> getType() { return Animal.class; } private Animal getValidAnimal() { Animal animal = new Animal(); animal.setId(EXISTENT_ANIMAL_ID); animal.setNickname("Locuroumee"); Species species = new Species(); species.setId(EXISTENT_SPECIES_ID); animal.setSpecies(species); House house = new House(); house.setId(EXISTENT_HOUSE_ID); animal.setHouse(house); animal.setBirthday(LocalDate.of(2015, 5, 15)); animal.setFoodConsumption(10); return animal; } private void assertByPrimaryFields(Animal expected, Animal actual) { assertEquals(expected.getNickname(), actual.getNickname()); assertNotNull(actual.getSpecies()); assertEquals(expected.getSpecies().getId(), actual.getSpecies().getId()); assertNotNull(actual.getHouse()); assertEquals(expected.getHouse().getId(), actual.getHouse().getId()); assertEquals(expected.getBirthday(), actual.getBirthday()); assertEquals(expected.getFoodConsumption(), actual.getFoodConsumption()); } }
3e15454a43c969dd1dcd11750e8cb008bf911c10
600
java
Java
src/main/java/graph/backend/Repository/EventsRepository.java
BrentonPoke/GraphBackend
cdb4f878b4e1641fd135a4c6e0b0fe30ce56d0fd
[ "Apache-2.0" ]
null
null
null
src/main/java/graph/backend/Repository/EventsRepository.java
BrentonPoke/GraphBackend
cdb4f878b4e1641fd135a4c6e0b0fe30ce56d0fd
[ "Apache-2.0" ]
null
null
null
src/main/java/graph/backend/Repository/EventsRepository.java
BrentonPoke/GraphBackend
cdb4f878b4e1641fd135a4c6e0b0fe30ce56d0fd
[ "Apache-2.0" ]
null
null
null
42.857143
119
0.803333
9,032
package graph.backend.Repository; import org.springframework.data.neo4j.annotation.Query; import org.springframework.data.neo4j.repository.Neo4jRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import graph.backend.Beans.Events; @Repository public interface EventsRepository extends Neo4jRepository<Events, Long> { @Query("MATCH (event:Events {name:$eventName}), (emp:Employee {username:$empname}) CREATE (emp)-[:PRESENTS]->(event)") void assignEventToEmployee(@Param("eventName") String event, @Param("empname") String emp); }
3e1545d24ccae54c0ec618d347b6850ed3bd5392
5,185
java
Java
samples/petclinic-jpa/src/test/java/org/springframework/samples/petclinic/owner/PetControllerTests.java
ellkrauze/spring-native
e5a0ef8b4befe689529cc26d64b7eeb94f292383
[ "Apache-2.0" ]
1,702
2021-01-06T10:02:54.000Z
2022-03-29T17:51:08.000Z
samples/petclinic-jpa/src/test/java/org/springframework/samples/petclinic/owner/PetControllerTests.java
ellkrauze/spring-native
e5a0ef8b4befe689529cc26d64b7eeb94f292383
[ "Apache-2.0" ]
1,032
2021-01-06T08:10:57.000Z
2022-03-31T15:55:11.000Z
samples/petclinic-jpa/src/test/java/org/springframework/samples/petclinic/owner/PetControllerTests.java
ellkrauze/spring-native
e5a0ef8b4befe689529cc26d64b7eeb94f292383
[ "Apache-2.0" ]
216
2021-01-09T10:13:54.000Z
2022-03-31T03:14:56.000Z
33.025478
112
0.731148
9,033
/* * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.samples.petclinic.owner; import java.util.Collection; import java.util.List; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; import org.assertj.core.util.Lists; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.FilterType; import org.springframework.test.web.servlet.MockMvc; /** * Test class for the {@link PetController} * * @author Colin But */ @WebMvcTest(value = PetController.class, includeFilters = @ComponentScan.Filter(value = PetTypeFormatter.class, type = FilterType.ASSIGNABLE_TYPE)) class PetControllerTests { private static final int TEST_OWNER_ID = 1; private static final int TEST_PET_ID = 1; @Autowired private MockMvc mockMvc; @Autowired private PetRepository pets; @Autowired private OwnerRepository owners; @Test void testInitCreationForm() throws Exception { mockMvc.perform(get("/owners/{ownerId}/pets/new", TEST_OWNER_ID)).andExpect(status().isOk()) .andExpect(view().name("pets/createOrUpdatePetForm")).andExpect(model().attributeExists("pet")); } @Test void testProcessCreationFormSuccess() throws Exception { mockMvc.perform(post("/owners/{ownerId}/pets/new", TEST_OWNER_ID).param("name", "Betty") .param("type", "hamster").param("birthDate", "2015-02-12")).andExpect(status().is3xxRedirection()) .andExpect(view().name("redirect:/owners/{ownerId}")); } @Test void testProcessCreationFormHasErrors() throws Exception { mockMvc.perform(post("/owners/{ownerId}/pets/new", TEST_OWNER_ID).param("name", "Betty").param("birthDate", "2015-02-12")).andExpect(model().attributeHasNoErrors("owner")) .andExpect(model().attributeHasErrors("pet")).andExpect(model().attributeHasFieldErrors("pet", "type")) .andExpect(model().attributeHasFieldErrorCode("pet", "type", "required")).andExpect(status().isOk()) .andExpect(view().name("pets/createOrUpdatePetForm")); } @Test void testInitUpdateForm() throws Exception { mockMvc.perform(get("/owners/{ownerId}/pets/{petId}/edit", TEST_OWNER_ID, TEST_PET_ID)) .andExpect(status().isOk()).andExpect(model().attributeExists("pet")) .andExpect(view().name("pets/createOrUpdatePetForm")); } @Test void testProcessUpdateFormSuccess() throws Exception { mockMvc.perform(post("/owners/{ownerId}/pets/{petId}/edit", TEST_OWNER_ID, TEST_PET_ID).param("name", "Betty") .param("type", "hamster").param("birthDate", "2015-02-12")).andExpect(status().is3xxRedirection()) .andExpect(view().name("redirect:/owners/{ownerId}")); } @Test void testProcessUpdateFormHasErrors() throws Exception { mockMvc.perform(post("/owners/{ownerId}/pets/{petId}/edit", TEST_OWNER_ID, TEST_PET_ID).param("name", "Betty") .param("birthDate", "2015/02/12")).andExpect(model().attributeHasNoErrors("owner")) .andExpect(model().attributeHasErrors("pet")).andExpect(status().isOk()) .andExpect(view().name("pets/createOrUpdatePetForm")); } @TestConfiguration static class PetControllerTestConfiguration { @Bean PetRepository pets() { PetType cat = new PetType(); cat.setId(3); cat.setName("hamster"); return new PetRepository() { @Override public List<PetType> findPetTypes() { return Lists.newArrayList(cat); } @Override public Pet findById(Integer id) { if (id.equals(TEST_PET_ID)) { return new Pet(); } return null; } @Override public void save(Pet pet) { } }; } @Bean OwnerRepository owners() { return new OwnerRepository() { @Override public Collection<Owner> findByLastName(String lastName) { return Lists.emptyList(); } @Override public Owner findById(Integer id) { if (id.equals(TEST_OWNER_ID)) { return new Owner(); } return null; } @Override public void save(Owner owner) { } }; } } }
3e15461c5d815809a702c343c7caf3db5089c280
1,434
java
Java
src/Puzzle.java
praktikum-tiunpad-2021/oop-final-kelompok-a-04
49d83c875bd6bf142675fa8f7958628a464614cb
[ "MIT" ]
null
null
null
src/Puzzle.java
praktikum-tiunpad-2021/oop-final-kelompok-a-04
49d83c875bd6bf142675fa8f7958628a464614cb
[ "MIT" ]
null
null
null
src/Puzzle.java
praktikum-tiunpad-2021/oop-final-kelompok-a-04
49d83c875bd6bf142675fa8f7958628a464614cb
[ "MIT" ]
1
2021-12-07T15:20:16.000Z
2021-12-07T15:20:16.000Z
28.117647
65
0.467225
9,034
import java.util.Random; public class Puzzle { private static final int grid = 9; private static final int subgrid = 3; private static Random random = new Random(); private static int[][] puzzle = { { 5, 9, 8, 2, 7, 4, 3, 6, 1 }, { 4, 7, 2, 1, 6, 3, 9, 5, 8 }, { 1, 3, 6, 8, 5, 9, 2, 4, 7 }, { 7, 2, 3, 5, 1, 8, 6, 9, 4 }, { 8, 1, 9, 3, 4, 6, 5, 7, 2 }, { 6, 5, 4, 7, 9, 2, 8, 1, 3 }, { 3, 6, 1, 9, 2, 7, 4, 8, 5 }, { 2, 4, 7, 6, 8, 5, 1, 3, 9 }, { 9, 8, 5, 4, 3, 1, 7, 2, 6 } }; private static int[][] generateSudoku() { int[] rowTemplate; for(int i=0; i<10; i++) { // acak nomor baris 1-9 // utk i=0. misal dirandom dan didapat rowNumber = 1 // utk i=1. misal dirandom dan didapat rowNumber = 2 int rowNumber = (random.nextInt(subgrid)); int newRow = (rowNumber*subgrid) / grid; // tukar baris rowTemplate = puzzle[rowNumber]; puzzle[rowNumber] = puzzle[newRow]; puzzle[newRow] = rowTemplate; } return puzzle; } public static int[][] getPuzzle() { //mereturn puzzle sudoku return generateSudoku(); } public static int getGrid() { return grid; } public static int getSubgrid() { return subgrid; } }
3e15478a079377562926531d37e1ccecce15af98
4,719
java
Java
app/src/test/java/com/sample/news/web/HttpTest.java
sharaf31/exquisite
c6d676924d3b27c3982cb0321315832655052940
[ "Apache-2.0" ]
null
null
null
app/src/test/java/com/sample/news/web/HttpTest.java
sharaf31/exquisite
c6d676924d3b27c3982cb0321315832655052940
[ "Apache-2.0" ]
null
null
null
app/src/test/java/com/sample/news/web/HttpTest.java
sharaf31/exquisite
c6d676924d3b27c3982cb0321315832655052940
[ "Apache-2.0" ]
null
null
null
40.681034
180
0.699513
9,035
package com.sample.news.web; import com.sample.news.model.Article; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; import java.util.Arrays; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; /** * Created by sharaf on 4/23/18. */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class HttpTest { @LocalServerPort private int port; @Autowired private TestRestTemplate restTemplate; private Article article, article2, article3; @Before public void setUp() { article = new Article(); article.setHeader("KFC prank"); article.setShortDescription("local boys prank gone wrong at kfc"); article.setText("Local boy has a prank setup at KFC gone wrong , causing delay in eating chicken"); article.setPublishDate("01/04/2018"); article.setAuthor(Arrays.asList("Ozil")); article2 = new Article(); article2.setHeader("Mc prank"); article2.setShortDescription("local girls prank gone crazy at Mc"); article2.setText("Local girls has a prank setup at MC gone wrong , causing delay in eating burgers"); article2.setPublishDate("02/04/2018"); article2.setAuthor(Arrays.asList("Ozil")); article3 = new Article(); article3.setHeader("Pizza prank"); article3.setShortDescription("local teens prank gone crazy at Pizzeria"); article3.setText("Local teens has a prank setup at Pizzeria gone wrong , causing delay in eating pizza"); article3.setPublishDate("04/04/2018"); article3.setAuthor(Arrays.asList("Ozil")); this.restTemplate.postForEntity("http://localhost:" + port + "/articles", article3, String.class); this.restTemplate.postForEntity("http://localhost:" + port + "/articles", article2, String.class); } @After public void tearDown() { this.restTemplate.delete("http://localhost:" + port + "/articles/Mc prank"); this.restTemplate.delete("http://localhost:" + port + "/articles/Mc prank"); } @Test public void findoneTest() throws Exception { ResponseEntity<Article> responseEntity = this.restTemplate.getForEntity("http://localhost:" + port + "/articles/Mc prank", Article.class); assertTrue(responseEntity.getBody().getHeader().equalsIgnoreCase("Mc prank")); } @Test public void createArticleTest() throws Exception { ResponseEntity<String> responseEntity = this.restTemplate.postForEntity("http://localhost:" + port + "/articles", article, String.class); assertTrue(responseEntity.getBody().equals("Success")); } @Test public void findByKeyWordTest() throws Exception { ResponseEntity<Article[]> responseEntity = this.restTemplate.getForEntity("http://localhost:" + port + "/articles/keyword/prank", Article[].class); assertTrue(Arrays.asList(responseEntity.getBody()).size() > 0); } @Test public void findByfindAllTest() throws Exception { ResponseEntity<Article[]> responseEntity = this.restTemplate.getForEntity("http://localhost:" + port + "/articles/", Article[].class); assertTrue(Arrays.asList(responseEntity.getBody()).size() > 2); } @Test public void findByAuthorTest() throws Exception { ResponseEntity<Article[]> responseEntity = this.restTemplate.getForEntity("http://localhost:" + port + "/articles/author/Ozil", Article[].class); assertTrue(Arrays.asList(responseEntity.getBody()).size() > 0); } @Test public void findArticleOnGivenPeriodTest() throws Exception { ResponseEntity<Article[]> responseEntity = this.restTemplate.getForEntity("http://localhost:" + port + "/articles/period?begin=01/04/2018&end=20/04/2018", Article[].class); assertTrue(Arrays.asList(responseEntity.getBody()).size() > 0); } @Test public void deleteOneTest() throws Exception { this.restTemplate.delete("http://localhost:" + port + "/articles/Pizza prank", String.class); ResponseEntity<Article> responseEntity = this.restTemplate.getForEntity("http://localhost:" + port + "/articles/Pizza prank", Article.class); assertNull(responseEntity.getBody()); } }
3e15482c2cff51223026f82a78783d1732ecd629
2,687
java
Java
hw08-0036480046/src/main/java/hr/fer/zemris/java/hw06/shell/commands/TreeCommand.java
Daria2002/Java_hw
017b245c622753ad56fe03be1aa099b6a8f7e140
[ "MIT" ]
null
null
null
hw08-0036480046/src/main/java/hr/fer/zemris/java/hw06/shell/commands/TreeCommand.java
Daria2002/Java_hw
017b245c622753ad56fe03be1aa099b6a8f7e140
[ "MIT" ]
8
2020-09-14T19:45:12.000Z
2021-12-14T20:56:42.000Z
hw08-0036480046/src/main/java/hr/fer/zemris/java/hw06/shell/commands/TreeCommand.java
Daria2002/Java_hw
017b245c622753ad56fe03be1aa099b6a8f7e140
[ "MIT" ]
null
null
null
27.418367
92
0.690361
9,036
package hr.fer.zemris.java.hw06.shell.commands; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import hr.fer.zemris.java.hw06.shell.Environment; import hr.fer.zemris.java.hw06.shell.ShellCommand; import hr.fer.zemris.java.hw06.shell.ShellStatus; /** * This class implements tree command. Tree command prints a tree for given directory. * @author Daria Matković * */ public class TreeCommand implements ShellCommand { /** tree command name **/ public final static String TREE_COMMAND = "tree"; @Override public ShellStatus executeCommand(Environment env, String arguments) { if(arguments == null) { env.writeln("Insert only one argument"); return ShellStatus.CONTINUE; } String[] args = CommandUtilityClass.checkArguments(arguments, 1); if(args.length != 1) { env.writeln("Arguments are not valid"); return ShellStatus.CONTINUE; } arguments = args[0].toString(); if(arguments == null) { env.writeln("Insert only one argument"); return ShellStatus.CONTINUE; } File directory = new File(CommandUtilityClass.resolvePath(arguments, env)); if(!directory.isDirectory()) { env.writeln("Please enter one argument - path to dir"); return ShellStatus.CONTINUE; } int startIndent = 0; try { listStructure(startIndent, directory); } catch (IOException e) { env.writeln("Error occured, so command didn't execute."); } return ShellStatus.CONTINUE; } /** * This method lists structure of given path, structure prints with given indent * @param indent given indent * @param file file whose structure needs to be printed * @throws IOException throws exception if error occurs */ static void listStructure(int indent, File file) throws IOException { // add indent for (int i = 0; i < indent; i++) { System.out.print(' '); } // current directory name System.out.println(file.getName()); // if current element is directory list structure of directory, otherwise continue if (file.isDirectory()) { File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) listStructure(indent + 2, files[i]); } } @Override public String getCommandName() { return TREE_COMMAND; } @Override public List<String> getCommandDescription() { List<String> list = new ArrayList<String>(); list.add("The tree command expects a single argument: directory name."); list.add("Command prints a tree (each dir level shifts output two spaces to the right)."); return Collections.unmodifiableList(list); } }
3e15487d410df92df25575f87fbf574d2d27ceeb
2,070
java
Java
src/ru/greenpix/civilization/buildings/common/Mine.java
GreenpixDev/civilization
0d1b5accf403438fc31036382660ad7585df05f6
[ "Apache-2.0" ]
null
null
null
src/ru/greenpix/civilization/buildings/common/Mine.java
GreenpixDev/civilization
0d1b5accf403438fc31036382660ad7585df05f6
[ "Apache-2.0" ]
null
null
null
src/ru/greenpix/civilization/buildings/common/Mine.java
GreenpixDev/civilization
0d1b5accf403438fc31036382660ad7585df05f6
[ "Apache-2.0" ]
null
null
null
31.846154
88
0.730435
9,037
package ru.greenpix.civilization.buildings.common; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import ru.greenpix.civilization.buildings.Building; import ru.greenpix.civilization.buildings.GuiseBuilding; import ru.greenpix.civilization.buildings.Structure; import ru.greenpix.civilization.buildings.Style; import ru.greenpix.civilization.guises.GuiseContainer; import ru.greenpix.civilization.guises.GuiseContainerBuilder; import ru.greenpix.civilization.items.CustomItems; import ru.greenpix.civilization.objects.Town; import ru.greenpix.developer.utils.guises.GuiseInterface; import ru.greenpix.developer.utils.items.Item; import ru.greenpix.mysql.api.Result; public class Mine extends Building implements Runnable, GuiseBuilding { private final GuiseContainer container = new GuiseContainerBuilder(6) .title(getDisplayName()) .defaultInteractionZone() .defaultFrame() .addItem(4, 5, new Item(Material.ANVIL), i -> { i.setDisplayName("&f&lМолоточков: &e&l" + getTown().getHammersPerMinute() + "/мин"); i.setLore("&fЧем больше молоточков, тем больше добычи", "&aКликни, чтобы &lОБНОВИТЬ"); }) .build(); public Mine(Town town, Location location, Style style) { super(town, location, style); } public Mine(Result result, Structure str) { super(result, str); } int ticks = 0; @Override public void run() { ticks++; if(ticks != 20) return; ticks = 0; if(Math.random() > getTown().getHammersPerMinute() / 2500D) return; double d = Math.random(); container.getContainer().addItem( d > 0.7 ? new ItemStack(Material.COBBLESTONE) : d > 0.55 ? new ItemStack(Material.COAL) : d > 0.4 ? CustomItems.COPPER_ORE.getCopy() : d > 0.3 ? new ItemStack(Material.REDSTONE) : d > 0.2 ? new ItemStack(Material.INK_SACK, 0, (byte) 4) : d > 0.05 ? new ItemStack(Material.IRON_ORE) : d > 0.025 ? new ItemStack(Material.DIAMOND) : CustomItems.TUNGSTEN_ORE.getCopy()); } @Override public GuiseInterface getGuise() { return container; } }