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
3e1da24d875c9ad8d9077cd0bb3208468bbc0634
1,052
java
Java
app/src/main/java/com/holasoft/launchking/A1.java
HolaMan/android-sample-launchking
a5b2670b66f118f5a367fe327bdbce5011909f29
[ "Apache-2.0" ]
3
2015-08-26T16:50:54.000Z
2017-05-24T03:19:57.000Z
app/src/main/java/com/holasoft/launchking/A1.java
HolaMan/android-sample-launchking
a5b2670b66f118f5a367fe327bdbce5011909f29
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/holasoft/launchking/A1.java
HolaMan/android-sample-launchking
a5b2670b66f118f5a367fe327bdbce5011909f29
[ "Apache-2.0" ]
null
null
null
28.432432
80
0.669202
12,552
package com.holasoft.launchking; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class A1 extends Base { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
3e1da2c15cb0fd5f5669f3c2ec410f412cdf52fa
1,067
java
Java
Java-DB-Fundamentals/DatabasesFrameworks-Hibernate&SpringData/EXAMS/weddings_planner_exam/src/main/java/softuni/io/JsonParser.java
yangra/SoftUni
2fe8ac059fe398f8bf229200c5406840f026fb88
[ "MIT" ]
null
null
null
Java-DB-Fundamentals/DatabasesFrameworks-Hibernate&SpringData/EXAMS/weddings_planner_exam/src/main/java/softuni/io/JsonParser.java
yangra/SoftUni
2fe8ac059fe398f8bf229200c5406840f026fb88
[ "MIT" ]
null
null
null
Java-DB-Fundamentals/DatabasesFrameworks-Hibernate&SpringData/EXAMS/weddings_planner_exam/src/main/java/softuni/io/JsonParser.java
yangra/SoftUni
2fe8ac059fe398f8bf229200c5406840f026fb88
[ "MIT" ]
null
null
null
28.078947
62
0.637301
12,553
package softuni.io; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class JsonParser { private Gson gson; private final FileParser fileParser; @Autowired public JsonParser(FileParser fileParser) { this.fileParser = fileParser; this.gson = new GsonBuilder() .excludeFieldsWithoutExposeAnnotation() .setPrettyPrinting() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss") .serializeNulls() .disableHtmlEscaping() .create(); } public <T> T deserialize(Class<T> clazz, String path){ T obj = null; String json = this.fileParser.readFile(path); obj = this.gson.fromJson(json,clazz); return obj; } public <T> void serialize(T object, String path){ String content = this.gson.toJson(object); this.fileParser.writeFile(path, content); } }
3e1da3b90f4a87704d3336e1367c0cd5711e456a
176
java
Java
app/src/main/java/net/burakuyar/relatify/dao/UserDao.java
uyarburak/relatify
15f1c8e30e56936efabcb75a069ce3e7dd63b605
[ "Apache-2.0" ]
null
null
null
app/src/main/java/net/burakuyar/relatify/dao/UserDao.java
uyarburak/relatify
15f1c8e30e56936efabcb75a069ce3e7dd63b605
[ "Apache-2.0" ]
null
null
null
app/src/main/java/net/burakuyar/relatify/dao/UserDao.java
uyarburak/relatify
15f1c8e30e56936efabcb75a069ce3e7dd63b605
[ "Apache-2.0" ]
null
null
null
16
41
0.710227
12,554
package net.burakuyar.relatify.dao; import net.burakuyar.relatify.model.User; /** * Created by burak on 2/25/2018. */ public interface UserDao { int save(User user); }
3e1da3cef61ffd782d217d3dbdda796129faad2b
3,675
java
Java
components/camel-ignite/src/main/java/org/apache/camel/component/ignite/idgen/IgniteIdGenEndpoint.java
carlos-lacerda/camel
bd1274ce4e38c0c500a7f0d2c873e091d39f5538
[ "Apache-2.0" ]
3
2016-10-31T14:14:30.000Z
2017-10-16T03:21:42.000Z
components/camel-ignite/src/main/java/org/apache/camel/component/ignite/idgen/IgniteIdGenEndpoint.java
kravinderreddy/camel_splunk
200e097d9df501724b4e7681768562daef3e4359
[ "Apache-2.0" ]
12
2019-11-13T03:09:32.000Z
2022-02-01T01:05:20.000Z
components/camel-ignite/src/main/java/org/apache/camel/component/ignite/idgen/IgniteIdGenEndpoint.java
kravinderreddy/camel_splunk
200e097d9df501724b4e7681768562daef3e4359
[ "Apache-2.0" ]
3
2017-08-16T14:26:57.000Z
2019-10-24T06:47:18.000Z
31.410256
152
0.71483
12,555
/** * 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.camel.component.ignite.idgen; import java.net.URI; import java.util.Map; import org.apache.camel.Consumer; import org.apache.camel.Processor; import org.apache.camel.Producer; import org.apache.camel.component.ignite.AbstractIgniteEndpoint; import org.apache.camel.component.ignite.IgniteComponent; import org.apache.camel.spi.Metadata; import org.apache.camel.spi.UriEndpoint; import org.apache.camel.spi.UriParam; import org.apache.camel.util.ObjectHelper; import org.apache.ignite.IgniteAtomicSequence; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Ignite ID Generator endpoint. */ @UriEndpoint(scheme = "ignite:idgen", title = "Ignite ID Generator", syntax = "ignite:idgen:[name]", label = "nosql,cache,compute", producerOnly = true) public class IgniteIdGenEndpoint extends AbstractIgniteEndpoint { private static final Logger LOG = LoggerFactory.getLogger(IgniteIdGenEndpoint.class); @UriParam @Metadata(required = "true") private String name; @UriParam private Integer batchSize; @UriParam(defaultValue = "0") private Long initialValue = 0L; @UriParam private IgniteIdGenOperation operation; public IgniteIdGenEndpoint(String endpointUri, URI remainingUri, Map<String, Object> parameters, IgniteComponent igniteComponent) throws Exception { super(endpointUri, igniteComponent); name = remainingUri.getHost(); ObjectHelper.notNull(name, "ID Generator name"); } @Override public Producer createProducer() throws Exception { IgniteAtomicSequence atomicSeq = ignite().atomicSequence(name, initialValue, false); if (atomicSeq == null) { atomicSeq = ignite().atomicSequence(name, initialValue, true); LOG.info("Created AtomicSequence of ID Generator with name {}.", name); } if (batchSize != null) { atomicSeq.batchSize(batchSize); } return new IgniteIdGenProducer(this, atomicSeq); } @Override public Consumer createConsumer(Processor processor) throws Exception { throw new UnsupportedOperationException("The Ignite Id Generator endpoint doesn't support consumers."); } public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getInitialValue() { return initialValue; } public void setInitialValue(Long initialValue) { this.initialValue = initialValue; } public IgniteIdGenOperation getOperation() { return operation; } public void setOperation(IgniteIdGenOperation operation) { this.operation = operation; } public Integer getBatchSize() { return batchSize; } public void setBatchSize(Integer batchSize) { this.batchSize = batchSize; } }
3e1da4077ea41ddd9495132fa0c3bfdbe8755729
597
java
Java
memberinfo/src/main/java/com/nisoft/memberinfo/bean/PartCompany.java
NewIdeaSoft/ManagerTools
fe59e64beae277b84b6fceb7ba664efd1bf8a1f9
[ "Apache-2.0" ]
null
null
null
memberinfo/src/main/java/com/nisoft/memberinfo/bean/PartCompany.java
NewIdeaSoft/ManagerTools
fe59e64beae277b84b6fceb7ba664efd1bf8a1f9
[ "Apache-2.0" ]
null
null
null
memberinfo/src/main/java/com/nisoft/memberinfo/bean/PartCompany.java
NewIdeaSoft/ManagerTools
fe59e64beae277b84b6fceb7ba664efd1bf8a1f9
[ "Apache-2.0" ]
null
null
null
16.583333
48
0.596315
12,556
package com.nisoft.memberinfo.bean; /** * Created by Administrator on 2017/5/21. */ public class PartCompany { private String mName; private String mId; private String mCompanyId; public String getName() { return mName; } public void setName(String name) { mName = name; } public String getId() { return mId; } public void setId(String id) { mId = id; } public String getCompanyId() { return mCompanyId; } public void setCompanyId(String companyId) { mCompanyId = companyId; } }
3e1da4e8273d1e804aef93d96b31e9b28a869f78
1,720
java
Java
graphs/trees/TreeDiameter.java
KattisMaster/Java-Competitive-Programming-Library
183320eac1b1f69ae105dd5a01ccab0db3409453
[ "CC-BY-4.0" ]
2,338
2016-05-30T21:04:59.000Z
2022-03-30T16:53:30.000Z
graphs/trees/TreeDiameter.java
KareemMohamedFathy/Competitive-programming-library
78c2270a2b711715b23ba4a42fb4ba8dfac1174a
[ "CC-BY-4.0" ]
14
2017-06-20T13:57:42.000Z
2022-02-04T15:27:10.000Z
graphs/trees/TreeDiameter.java
KareemMohamedFathy/Competitive-programming-library
78c2270a2b711715b23ba4a42fb4ba8dfac1174a
[ "CC-BY-4.0" ]
550
2016-09-08T08:34:26.000Z
2022-03-26T18:03:34.000Z
18.494624
69
0.54186
12,557
package graphs.trees; //1. Calculate the height of the tree rooted at node u for all nodes //2. find the proper root of a given tree import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; public class TreeDiameter { static ArrayList<Integer>[] adjList; static int N, dp_down[][], dp_up[]; static boolean[] visited; //Part 1 static void dfs1(int u) { visited[u] = true; for(int i = 0; i < adjList[u].size(); ++i) { int v = adjList[u].get(i); if(!visited[v]) { dfs1(v); if(dp_down[v][0] + 1> dp_down[u][1]) dp_down[u][1] = dp_down[v][0] + 1; if(dp_down[u][1] > dp_down[u][0]) swap(u); } } } static void dfs2(int u, int h) { visited[u] = true; dp_up[u] = h; for(int i = 0; i < adjList[u].size(); ++i) { int v = adjList[u].get(i); if(!visited[v]) { int h_nxt; if(dp_down[v][0] + 1 == dp_down[u][0]) h_nxt = dp_down[u][1] + 1; else h_nxt = dp_down[u][0] + 1; dfs2(v, Math.max(h + 1, h_nxt)); } } } static void swap(int u) { int x = dp_down[u][0], y = dp_down[u][1]; dp_down[u][0] = y; dp_down[u][1] = x; } static void go() { dp_down = new int[N][2]; dp_up = new int[N]; visited = new boolean[N]; dfs1(0); visited = new boolean[N]; dfs2(0, 0); } //Part 2 static int findRoot() { int[] deg = new int[N]; Queue<Integer> q = new LinkedList<Integer>(); for(int i = 0; i < N; ++i) if((deg[i] = adjList[i].size()) == 1) q.add(i); int root = -1; while(!q.isEmpty()) { root = q.remove(); for(int i = 0; i < adjList[root].size(); ++i) { int v = adjList[root].get(i); if(--deg[v] == 1) q.add(v); } } return root; } }
3e1da503fe6e7e563f49eb20f10b81d838332e54
2,513
java
Java
src/trebes/rollplay/app/RollplayApp.java
nicktrebes/rollplay
7cf0a327330b517b721952b663eb1c4b021f1526
[ "MIT" ]
null
null
null
src/trebes/rollplay/app/RollplayApp.java
nicktrebes/rollplay
7cf0a327330b517b721952b663eb1c4b021f1526
[ "MIT" ]
null
null
null
src/trebes/rollplay/app/RollplayApp.java
nicktrebes/rollplay
7cf0a327330b517b721952b663eb1c4b021f1526
[ "MIT" ]
null
null
null
30.277108
81
0.752089
12,558
/* * MIT License * * RollPlay Character Sheet Editor * Copyright (c) 2020 Nick Trebes * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package trebes.rollplay.app; import java.awt.Toolkit; import javax.swing.JFrame; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import trebes.rollplay.menu.RollplayMenuBar; public class RollplayApp { private JFrame frame; private RollplayContent content; private RollplayMenuBar menuBar; public RollplayApp() { content = new RollplayContent(this); menuBar = new RollplayMenuBar(this); content.addTab(new RollplayWelcome(this)); frame = new JFrame(getAppTitle()); frame.setContentPane(content); frame.setJMenuBar(menuBar); frame.setSize(Toolkit.getDefaultToolkit().getScreenSize()); frame.setVisible(true); } public RollplayContent getContent() { return content; } public JFrame getFrame() { return frame; } public RollplayMenuBar getMenuBar() { return menuBar; } public static final int VERSION_MAJOR = 0; public static final int VERSION_MINOR = 1; public static String getAppTitle() { return ("RollPlay " + VERSION_MAJOR + "." + VERSION_MINOR); } public static void main(String[] args) { try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException exception) {} new RollplayApp(); } }
3e1da563253a1a50e82a8794717a5c63b7adf6f8
1,149
java
Java
practical-ajax-projects-with-java-technology/Chapter07/photoshare/WEB-INF/src/com/apress/ajaxprojects/photoshare/actions/DownloadPhoto.java
portal-webstore/books
689eb33ca0ef96d459e7cf3f3b15f35383b8c601
[ "MIT" ]
null
null
null
practical-ajax-projects-with-java-technology/Chapter07/photoshare/WEB-INF/src/com/apress/ajaxprojects/photoshare/actions/DownloadPhoto.java
portal-webstore/books
689eb33ca0ef96d459e7cf3f3b15f35383b8c601
[ "MIT" ]
null
null
null
practical-ajax-projects-with-java-technology/Chapter07/photoshare/WEB-INF/src/com/apress/ajaxprojects/photoshare/actions/DownloadPhoto.java
portal-webstore/books
689eb33ca0ef96d459e7cf3f3b15f35383b8c601
[ "MIT" ]
null
null
null
22.98
73
0.669278
12,559
package com.apress.ajaxprojects.photoshare.actions; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * This class rotates a specified photo 90 degrees clockwise. After this * executes, the RetrievePhoto Action will be executed to return the * rotated photo. */ public class DownloadPhoto extends Action { /** * Log instance. */ private static Log log = LogFactory.getLog(RotatePhoto.class); /** * Called by ActionDispatched to download a photo. * * @return Result. */ public String execute() { log.info("Entry..."); // Display incoming parameters. String filename = (String)(getRequest().getParameter("filename")); log.info("filename = " + filename); // Just set the Content-Disposition to attachment, with a filename // matching that of the photo the user wants to download, and then // forward to the photo file itself. Done! getResponse().setHeader("Content-Disposition", "attachment;" + "filename=\"" + filename + "\""); log.info("Exit..."); return "/photos/" + filename; } // End execute(). } // End class.
3e1da5c7ce942be51cef227e2ae32c429c6dabd4
2,686
java
Java
pharmacys/src/model/Pharmacy.java
romanarranz/FarmaciaDS
4960211af33dc8187269983d67b6f818cd2c1807
[ "MIT" ]
1
2019-04-30T14:50:05.000Z
2019-04-30T14:50:05.000Z
pharmacys/src/model/Pharmacy.java
romanarranz/FarmaciaDS
4960211af33dc8187269983d67b6f818cd2c1807
[ "MIT" ]
null
null
null
pharmacys/src/model/Pharmacy.java
romanarranz/FarmaciaDS
4960211af33dc8187269983d67b6f818cd2c1807
[ "MIT" ]
1
2019-01-02T20:13:11.000Z
2019-01-02T20:13:11.000Z
18.524138
48
0.72003
12,560
package model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; @Entity @Table(name="PHARMACY") @XmlRootElement(name="pharmacy") @XmlType(propOrder={ "cif", "name", "description", "phoneNumber", "startSchedule", "endSchedule" }) public class Pharmacy { @Id @Column(name="CIF") private String cif; @Column(name="NAME") private String name; @Column(name="PHONE_NUMBER") private int phoneNumber; @Column(name="DESCRIPTION") private String description; @Column(name="START_SCHEDULE") private int startShedule; @Column(name="END_SCHEDULE") private int endtShedule; @Column(name="LATITUDE") private double latitude; @Column(name="LONGITUDE") private double longitude; @Column(name="ADDRESS") private String address; @Column(name="URL_IMG") private String urlImg; // CIF @XmlElement(required=true) public String getCif(){ return this.cif; } public void setCif(String cif){ this.cif = cif; } // NAME @XmlElement(required=true) public String getName(){ return this.name; } public void setName(String name){ this.name = name; } //PHONE_NUMBER @XmlElement(required=true) public int getPhoneNumber(){ return this.phoneNumber; } public void setPhoneNumber(int phoneN){ this.phoneNumber = phoneN; } // DESCRIPTION @XmlElement(required=true) public String getDescription(){ return this.description; } public void setDescription(String descr){ this.description = descr; } // START_SCHEDULE @XmlElement(required=true) public int getStartSchedule(){ return this.startShedule; } public void setStartSchedule(int h){ this.startShedule = h; } // END_SCHEDULE @XmlElement(required=true) public int getEndSchedule(){ return this.endtShedule; } public void setEndSchedule(int h){ this.endtShedule = h; } // LATITUDE @XmlElement(required=true) public double getLatitude(){ return this.latitude; } public void setLatitude(double lat){ this.latitude = lat; } // LONGITUDE @XmlElement(required=true) public double getLongitude(){ return this.longitude; } public void setLongitude(double lng){ this.longitude = lng; } // ADDRESS @XmlElement(required=true) public String getAddress(){ return this.address; } public void setAddress(String address){ this.address = address; } // URL_IMG @XmlElement(required=true) public String getUrlImg(){ return this.urlImg; } public void setUrlImg(String uri){ this.urlImg = uri; } }
3e1da91442d5fdcf32aef9fd651f44b40b2075c7
947
java
Java
avek-model/src/test/observation/event/AEntityChanged.java
JustificationFactory/JustificationFactory-ClinicalStudies
8da551ab1b44e915f48279893645c1a1572b8cc1
[ "Apache-2.0" ]
null
null
null
avek-model/src/test/observation/event/AEntityChanged.java
JustificationFactory/JustificationFactory-ClinicalStudies
8da551ab1b44e915f48279893645c1a1572b8cc1
[ "Apache-2.0" ]
null
null
null
avek-model/src/test/observation/event/AEntityChanged.java
JustificationFactory/JustificationFactory-ClinicalStudies
8da551ab1b44e915f48279893645c1a1572b8cc1
[ "Apache-2.0" ]
null
null
null
23.097561
79
0.674762
12,561
package fr.axonic.observation.event; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by cboinaud on 18/07/2016. */ public class AEntityChanged { private List<AEntityEvent> events; private ChangedEventType type = ChangedEventType.MIXED; public AEntityChanged(AEntityEvent... entityEvents){ this.events = new ArrayList<>(Arrays.asList(entityEvents)); } public AEntityChanged(List<AEntityEvent> events){ this.events = new ArrayList<>(events); } public AEntityChanged(ChangedEventType type, AEntityEvent... entityEvents){ this(entityEvents); this.type = type; } public AEntityChanged(ChangedEventType type, List<AEntityEvent> events){ this(events); this.type = type; } public List<AEntityEvent> getEvents(){ return events; } public ChangedEventType getType() { return type; } }
3e1da974847edd81a80f4439d0b31d014d6d8b58
1,289
java
Java
core/src/test/java/io/nixer/nixerplugin/core/detection/registry/CredentialStuffingRegistryTest.java
smifun/nixer-spring-plugin
b323866583bc40f1f75829186df30d24c34d1582
[ "Apache-2.0" ]
null
null
null
core/src/test/java/io/nixer/nixerplugin/core/detection/registry/CredentialStuffingRegistryTest.java
smifun/nixer-spring-plugin
b323866583bc40f1f75829186df30d24c34d1582
[ "Apache-2.0" ]
null
null
null
core/src/test/java/io/nixer/nixerplugin/core/detection/registry/CredentialStuffingRegistryTest.java
smifun/nixer-spring-plugin
b323866583bc40f1f75829186df30d24c34d1582
[ "Apache-2.0" ]
null
null
null
27.425532
89
0.731575
12,562
package io.nixer.nixerplugin.core.detection.registry; import java.time.Instant; import java.time.temporal.ChronoUnit; import io.nixer.nixerplugin.core.detection.events.GlobalCredentialStuffingEvent; import io.nixer.nixerplugin.core.detection.events.GlobalCredentialStuffingEvent; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; class CredentialStuffingRegistryTest { private final CredentialStuffingRegistry registry = new CredentialStuffingRegistry(); @Test void shouldReturnActiveOnEvent() { registry.onApplicationEvent(new GlobalCredentialStuffingEvent()); final boolean isActive = registry.hasHappenDuringCredentialStuffing(now()); assertTrue(isActive); } @Test void credentialStuffingShouldExpire() { registry.onApplicationEvent(new GlobalCredentialStuffingEvent()); final boolean isActive = registry.hasHappenDuringCredentialStuffing(future()); assertFalse(isActive); } private long future() { return Instant.now() .plus(1, ChronoUnit.DAYS) .toEpochMilli(); } private long now() { return Instant.now().toEpochMilli(); } }
3e1da9e9747629a173458c27de9b0409ed4ad737
934
java
Java
app/src/main/java/com/example/srikant/philomath/Category_spinner.java
srikantvadrevu/philomath-android
9db17826e9f785f5a3379a1f95d9b3838294641c
[ "MIT" ]
null
null
null
app/src/main/java/com/example/srikant/philomath/Category_spinner.java
srikantvadrevu/philomath-android
9db17826e9f785f5a3379a1f95d9b3838294641c
[ "MIT" ]
null
null
null
app/src/main/java/com/example/srikant/philomath/Category_spinner.java
srikantvadrevu/philomath-android
9db17826e9f785f5a3379a1f95d9b3838294641c
[ "MIT" ]
null
null
null
25.243243
94
0.748394
12,563
package com.example.srikant.philomath; import android.app.Activity; import android.view.View; import android.widget.AdapterView; import android.widget.Toast; /** * Created by Srikant on 2/14/2016. */ public class Category_spinner extends Activity implements AdapterView.OnItemSelectedListener { private RegisterDB registration; private Category c; private int i; public Category_spinner(RegisterDB registration) { this.registration = registration; i = 1; } public Category_spinner(Category c) { this.c = c; i = 2; } public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { // An item was selected. You can retrieve the selected item using if (i == 1) registration.setCategory(parent.getItemAtPosition(pos).toString()); else c.Category = parent.getItemAtPosition(pos).toString(); } public void onNothingSelected(AdapterView<?> parent) { // Another interface callback } }
3e1daa88ff9280b3248a9736eb98214051b486ae
159
java
Java
_demo/_demo.solon_feign/src/main/java/webapp/controller/test/Contributor.java
addstone/solon
6043edabf34a356e2ee28f9fb427a1f846a3680e
[ "Apache-2.0" ]
232
2019-02-15T03:44:00.000Z
2022-03-27T08:44:51.000Z
_demo/_demo.solon_feign/src/main/java/webapp/controller/test/Contributor.java
addstone/solon
6043edabf34a356e2ee28f9fb427a1f846a3680e
[ "Apache-2.0" ]
26
2019-11-21T04:47:38.000Z
2022-03-15T13:44:21.000Z
_demo/_demo.solon_feign/src/main/java/webapp/controller/test/Contributor.java
addstone/solon
6043edabf34a356e2ee28f9fb427a1f846a3680e
[ "Apache-2.0" ]
31
2019-07-15T14:36:27.000Z
2022-03-13T09:59:25.000Z
15.9
33
0.704403
12,564
package webapp.controller.test; /** * @author noear 2021/1/1 created */ public class Contributor { public String login; public int contributions; }
3e1daaa7c5086c2d91e70e44a0dfcd5dd192680a
2,134
java
Java
src/test/java/dev/hbeck/kdl/TestUtil.java
hkolbeck/kdl4j
14c2cb8f6bef35e040be73e7bd87ddec6f164e6b
[ "CC-BY-4.0", "CC0-1.0" ]
16
2021-01-06T18:39:39.000Z
2021-11-14T20:27:08.000Z
src/test/java/dev/hbeck/kdl/TestUtil.java
sthagen/kdl4j
14c2cb8f6bef35e040be73e7bd87ddec6f164e6b
[ "CC0-1.0", "CC-BY-4.0" ]
3
2021-01-22T00:23:51.000Z
2021-09-20T03:07:21.000Z
src/test/java/dev/hbeck/kdl/TestUtil.java
sthagen/kdl4j
14c2cb8f6bef35e040be73e7bd87ddec6f164e6b
[ "CC0-1.0", "CC-BY-4.0" ]
3
2021-01-06T23:03:34.000Z
2021-08-25T10:10:18.000Z
27.012658
81
0.691659
12,565
package dev.hbeck.kdl; import dev.hbeck.kdl.parse.KDLParseContext; import dev.hbeck.kdl.parse.KDLParser; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import org.hamcrest.Description; import java.io.IOException; import java.io.StringReader; @SuppressWarnings("rawtypes") public class TestUtil { public static final KDLParser parser = new KDLParser(); public static KDLParseContext strToContext(String str) { final StringReader reader = new StringReader(str); return new KDLParseContext(reader); } public static String readRemainder(KDLParseContext context) { final StringBuilder stringBuilder = new StringBuilder(); try { int read = context.read(); while (read != KDLParser.EOF) { stringBuilder.appendCodePoint(read); read = context.read(); } } catch (IOException e) { throw new RuntimeException(e); } return stringBuilder.toString(); } public static Matcher<Runnable> throwsException(Class exceptionClass) { return new ThrowsExceptionMatcher(exceptionClass); } } @SuppressWarnings("rawtypes") class ThrowsExceptionMatcher extends TypeSafeMatcher<Runnable> { private final Class exceptionClass; private Exception actualException; public ThrowsExceptionMatcher(Class exceptionClass) { this.exceptionClass = exceptionClass; } @Override protected boolean matchesSafely(Runnable fn) { try { fn.run(); return false; } catch (Exception e) { actualException = e; return e.getClass() == exceptionClass; } } @Override public void describeTo(Description description) { description.appendText("throws exception "); description.appendValue(exceptionClass.toString()); } @Override protected void describeMismatchSafely(Runnable item, Description description) { if (actualException != null) { description.appendText("threw exception "); description.appendValue(actualException); } else { description.appendText("threw no exception"); } } }
3e1dab17fde3ccfffcf5bd85804574f17e6851f9
4,112
java
Java
modules/clients/src/test/java/org/apache/ignite/internal/client/TaskSingleJobSplitAdapter.java
DirectXceriD/gridgain
093e512a9147e266f83f6fe1cf088c0b037b501c
[ "Apache-2.0", "CC0-1.0" ]
1
2019-03-11T08:52:37.000Z
2019-03-11T08:52:37.000Z
modules/clients/src/test/java/org/apache/ignite/internal/client/TaskSingleJobSplitAdapter.java
DirectXceriD/gridgain
093e512a9147e266f83f6fe1cf088c0b037b501c
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
modules/clients/src/test/java/org/apache/ignite/internal/client/TaskSingleJobSplitAdapter.java
DirectXceriD/gridgain
093e512a9147e266f83f6fe1cf088c0b037b501c
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
45.186813
147
0.719844
12,566
/* * GridGain Community Edition Licensing * Copyright 2019 GridGain Systems, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") modified with Commons Clause * Restriction; you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. * * Commons Clause Restriction * * The Software is provided to you by the Licensor under the License, as defined below, subject to * the following condition. * * Without limiting other conditions in the License, the grant of rights under the License will not * include, and the License does not grant to you, the right to Sell the Software. * For purposes of the foregoing, “Sell” means practicing any or all of the rights granted to you * under the License to provide to third parties, for a fee or other consideration (including without * limitation fees for hosting or consulting/ support services related to the Software), a product or * service whose value derives, entirely or substantially, from the functionality of the Software. * Any license notice or attribution required by the License must also include this Commons Clause * License Condition notice. * * For purposes of the clause above, the “Licensor” is Copyright 2019 GridGain Systems, Inc., * the “License” is the Apache License, Version 2.0, and the Software is the GridGain Community * Edition software provided with this notice. */ package org.apache.ignite.internal.client; import java.util.Collection; import java.util.Collections; import java.util.List; import org.apache.ignite.IgniteException; import org.apache.ignite.compute.ComputeJob; import org.apache.ignite.compute.ComputeJobAdapter; import org.apache.ignite.compute.ComputeJobResult; import org.apache.ignite.compute.ComputeTaskSplitAdapter; /** * Adapter for {@link org.apache.ignite.compute.ComputeTaskSplitAdapter} * overriding {@code split(...)} method to return singleton with self instance. * This adapter should be used for tasks that always splits to a single task. * @param <T> Type of the task execution argument. * @param <R> Type of the task result returning from {@link org.apache.ignite.compute.ComputeTask#reduce(List)} method. */ public abstract class TaskSingleJobSplitAdapter<T, R> extends ComputeTaskSplitAdapter<T, R> { /** Empty constructor. */ protected TaskSingleJobSplitAdapter() { // No-op. } /** {@inheritDoc} */ @Override protected Collection<? extends ComputeJob> split(final int gridSize, final T arg) { return Collections.singleton(new ComputeJobAdapter() { @Override public Object execute() { return executeJob(gridSize, arg); } }); } /** {@inheritDoc} */ @Override public R reduce(List<ComputeJobResult> results) { assert results.size() == 1; ComputeJobResult res = results.get(0); if (res.isCancelled()) throw new IgniteException("Reduce receives failed job."); return res.getData(); } /** * Executes this task's job. * * @param gridSize Number of available grid nodes. Note that returned number of * jobs can be less, equal or greater than this grid size. * @param arg Task execution argument. Can be {@code null}. * @return Job execution result (possibly {@code null}). This result will be returned * in {@link org.apache.ignite.compute.ComputeJobResult#getData()} method passed into * {@link org.apache.ignite.compute.ComputeTask#result(org.apache.ignite.compute.ComputeJobResult, List)} method into task on caller node. */ protected abstract Object executeJob(int gridSize, T arg); }
3e1dabcfdd345d6ac9e553d3863a09e3efb279b0
1,015
java
Java
multitenant/src/main/java/crusader/multitenant/providers/SimpleTenant.java
arcane-io/crusader
6bc0912a1601524f3f30296a8bf823f345b6c1f8
[ "Apache-2.0" ]
null
null
null
multitenant/src/main/java/crusader/multitenant/providers/SimpleTenant.java
arcane-io/crusader
6bc0912a1601524f3f30296a8bf823f345b6c1f8
[ "Apache-2.0" ]
null
null
null
multitenant/src/main/java/crusader/multitenant/providers/SimpleTenant.java
arcane-io/crusader
6bc0912a1601524f3f30296a8bf823f345b6c1f8
[ "Apache-2.0" ]
null
null
null
22.173913
103
0.602941
12,567
package crusader.multitenant.providers; import crusader.multitenant.Tenant; /** * Base implementation of {@link crusader.multitenant.Tenant}. * * @author Catalin Manolescu <kenaa@example.com> */ public class SimpleTenant implements Tenant { private Object identity = null; public SimpleTenant(Object identity) { this.identity = identity; } @Override public Object getIdentity() { return identity; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Tenant)) { return false; } Tenant that = (Tenant) o; return !(identity != null ? !identity.equals(that.getIdentity()) : that.getIdentity() != null); } @Override public int hashCode() { return identity != null ? identity.hashCode() : super.hashCode(); } @Override public String toString() { return "SimpleTenant{identity=" + identity + '}'; } }
3e1dabd2d345d549e2ff5964f818f5662b342b26
420
java
Java
gnall-ums/src/main/java/com/java/gmall/ums/service/MemberCollectSpuService.java
dingzichaogit/gmall
aa821ca6fb7e65f378f7b9236b576fcf5d41bcf4
[ "Apache-2.0" ]
null
null
null
gnall-ums/src/main/java/com/java/gmall/ums/service/MemberCollectSpuService.java
dingzichaogit/gmall
aa821ca6fb7e65f378f7b9236b576fcf5d41bcf4
[ "Apache-2.0" ]
null
null
null
gnall-ums/src/main/java/com/java/gmall/ums/service/MemberCollectSpuService.java
dingzichaogit/gmall
aa821ca6fb7e65f378f7b9236b576fcf5d41bcf4
[ "Apache-2.0" ]
null
null
null
22.105263
77
0.77381
12,568
package com.java.gmall.ums.service; import com.baomidou.mybatisplus.extension.service.IService; import com.java.gmall.ums.entity.MemberCollectSpu; import com.java.core.bean.PageVo; import com.java.core.bean.QueryCondition; /** * 会员收藏的商品 * * @author dzc * @since 2021-09-09 17:59:25 */ public interface MemberCollectSpuService extends IService<MemberCollectSpu> { PageVo queryPage(QueryCondition params); }
3e1dac010b1c963053e42edf17eca816e32375ea
892
java
Java
eps-api/src/main/java/com/decade/eps/model/vo/ResultVo.java
DL1232/eps
91bc97c11f6a758946486af9a04920549bc94717
[ "Apache-2.0" ]
null
null
null
eps-api/src/main/java/com/decade/eps/model/vo/ResultVo.java
DL1232/eps
91bc97c11f6a758946486af9a04920549bc94717
[ "Apache-2.0" ]
null
null
null
eps-api/src/main/java/com/decade/eps/model/vo/ResultVo.java
DL1232/eps
91bc97c11f6a758946486af9a04920549bc94717
[ "Apache-2.0" ]
null
null
null
21.756098
105
0.684978
12,569
package com.decade.eps.model.vo; import com.decade.eps.constant.ResultCodeEnum; import lombok.Data; import java.io.Serializable; /** * 统一定义返回类 * * @author lidongjie * @since 2020/3/20 */ @Data public class ResultVo implements Serializable { private Integer code; private String message; private Object data; private ResultVo(Integer code, String message, Object data) { this.code = code; this.message = message; this.data = data; } public static ResultVo success() { return success(null); } public static ResultVo success(Object data) { return new ResultVo(ResultCodeEnum.SUCCESS.getCode(), ResultCodeEnum.SUCCESS.getMessage(), data); } public static ResultVo error(ResultCodeEnum resultCodeEnum) { return new ResultVo(resultCodeEnum.getCode(), resultCodeEnum.getMessage(), null); } }
3e1dad86cd17b8c545e720abad80ef0093a92f6e
23,502
java
Java
src/android/Notification.java
watnow-developer/plugin-dialog
07f93297207c85724585650f273d9ebdf6d0529f
[ "Apache-2.0" ]
null
null
null
src/android/Notification.java
watnow-developer/plugin-dialog
07f93297207c85724585650f273d9ebdf6d0529f
[ "Apache-2.0" ]
null
null
null
src/android/Notification.java
watnow-developer/plugin-dialog
07f93297207c85724585650f273d9ebdf6d0529f
[ "Apache-2.0" ]
null
null
null
46.91018
198
0.541911
12,570
/* 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 jp.watnow.plugins.dialog; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.ProgressDialog; import android.content.DialogInterface; import android.text.InputType; import android.util.Log; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; /** * This class provides access to notifications on the device. * * Be aware that this implementation gets called on * navigator.notification.{alert|confirm|prompt}, and that there is a separate * implementation in org.apache.cordova.CordovaChromeClient that gets * called on a simple window.{alert|confirm|prompt}. */ public class Notification extends CordovaPlugin { public int confirmResult = -1; public ProgressDialog spinnerDialog = null; public ProgressDialog progressDialog = null; final static String INPUT_SECURE = "secure"; final static String INPUT_NORMAL = "normal"; /** * Constructor. */ public Notification() { } /** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArray of arguments for the plugin. * @param callbackContext The callback context used when calling back into JavaScript. * @return True when the action was valid, false otherwise. */ public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { /* * Don't run any of these if the current activity is finishing * in order to avoid android.view.WindowManager$BadTokenException * crashing the app. Just return true here since false should only * be returned in the event of an invalid action. */ if(this.cordova.getActivity().isFinishing()) return true; if (action.equals("alert")) { this.alert(args.getString(0), args.getString(1), args.getString(2), callbackContext); return true; } else if (action.equals("confirm")) { this.confirm(args.getString(0), args.getString(1), args.getJSONArray(2), callbackContext); return true; } else if (action.equals("prompt")) { String type = INPUT_NORMAL; if(args.getString(4).equals(INPUT_SECURE)){ type = INPUT_SECURE; } this.prompt(args.getString(0), args.getString(1), args.getJSONArray(2), args.getString(3),type, callbackContext); return true; } else if (action.equals("list")) { this.list(args.getString(0), args.getJSONArray(1), callbackContext); return true; } else if (action.equals("login")) { this.login(args.getString(0), args.getString(1), args.getJSONArray(2), args.getJSONArray(3), callbackContext); return true; } else { return false; } // Only alert and confirm are async. //callbackContext.success(); //return true; } //-------------------------------------------------------------------------- // LOCAL METHODS //-------------------------------------------------------------------------- /** * Builds and shows a native Android alert with given Strings * @param message The message the alert should display * @param title The title of the alert * @param buttonLabel The label of the button * @param callbackContext The callback context */ public synchronized void alert(final String message, final String title, final String buttonLabel, final CallbackContext callbackContext) { final CordovaInterface cordova = this.cordova; Runnable runnable = new Runnable() { public void run() { AlertDialog.Builder dlg = createDialog(cordova); // new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT); dlg.setMessage(message); dlg.setTitle(title); dlg.setCancelable(false); dlg.setPositiveButton(buttonLabel, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0)); } }); dlg.setOnCancelListener(new AlertDialog.OnCancelListener() { public void onCancel(DialogInterface dialog) { dialog.dismiss(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0)); } }); changeTextDirection(dlg); }; }; this.cordova.getActivity().runOnUiThread(runnable); } /** * Builds and shows a native Android confirm dialog with given title, message, buttons. * This dialog only shows up to 3 buttons. Any labels after that will be ignored. * The index of the button pressed will be returned to the JavaScript callback identified by callbackId. * * @param message The message the dialog should display * @param title The title of the dialog * @param buttonLabels A comma separated list of button labels (Up to 3 buttons) * @param callbackContext The callback context. */ public synchronized void confirm(final String message, final String title, final JSONArray buttonLabels, final CallbackContext callbackContext) { final CordovaInterface cordova = this.cordova; Runnable runnable = new Runnable() { public void run() { AlertDialog.Builder dlg = createDialog(cordova); // new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT); dlg.setMessage(message); dlg.setTitle(title); dlg.setCancelable(false); // First button if (buttonLabels.length() > 0) { try { dlg.setNegativeButton(buttonLabels.getString(0), new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 1)); } }); } catch (JSONException e) { } } // Second button if (buttonLabels.length() > 1) { try { dlg.setNeutralButton(buttonLabels.getString(1), new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 2)); } }); } catch (JSONException e) { } } // Third button if (buttonLabels.length() > 2) { try { dlg.setPositiveButton(buttonLabels.getString(2), new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 3)); } }); } catch (JSONException e) { } } dlg.setOnCancelListener(new AlertDialog.OnCancelListener() { public void onCancel(DialogInterface dialog) { dialog.dismiss(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0)); } }); changeTextDirection(dlg); }; }; this.cordova.getActivity().runOnUiThread(runnable); } /** * Builds and shows a native Android prompt dialog with given title, message, buttons. * This dialog only shows up to 3 buttons. Any labels after that will be ignored. * The following results are returned to the JavaScript callback identified by callbackId: * buttonIndex Index number of the button selected * input1 The text entered in the prompt dialog box * * @param message The message the dialog should display * @param title The title of the dialog * @param buttonLabels A comma separated list of button labels (Up to 3 buttons) * @param callbackContext The callback context. */ public synchronized void prompt(final String message, final String title, final JSONArray buttonLabels, final String defaultText,final String dialogType, final CallbackContext callbackContext) { final CordovaInterface cordova = this.cordova; Runnable runnable = new Runnable() { public void run() { final EditText promptInput = new EditText(cordova.getActivity()); promptInput.setHint(defaultText); Log.d("DialogPlugin",dialogType); if(dialogType.equals(INPUT_SECURE)){ promptInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); } AlertDialog.Builder dlg = createDialog(cordova); // new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT); dlg.setMessage(message); dlg.setTitle(title); dlg.setCancelable(false); dlg.setView(promptInput); final JSONObject result = new JSONObject(); // First button if (buttonLabels.length() > 0) { try { dlg.setNegativeButton(buttonLabels.getString(0), new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); try { result.put("buttonIndex",1); result.put("input1", promptInput.getText().toString().trim().length()==0 ? defaultText : promptInput.getText()); } catch (JSONException e) { e.printStackTrace(); } callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result)); } }); } catch (JSONException e) { } } // Second button if (buttonLabels.length() > 1) { try { dlg.setNeutralButton(buttonLabels.getString(1), new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); try { result.put("buttonIndex",2); result.put("input1", promptInput.getText().toString().trim().length()==0 ? defaultText : promptInput.getText()); } catch (JSONException e) { e.printStackTrace(); } callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result)); } }); } catch (JSONException e) { } } // Third button if (buttonLabels.length() > 2) { try { dlg.setPositiveButton(buttonLabels.getString(2), new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); try { result.put("buttonIndex",3); result.put("input1", promptInput.getText().toString().trim().length()==0 ? defaultText : promptInput.getText()); } catch (JSONException e) { e.printStackTrace(); } callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result)); } }); } catch (JSONException e) { } } dlg.setOnCancelListener(new AlertDialog.OnCancelListener() { public void onCancel(DialogInterface dialog){ dialog.dismiss(); try { result.put("buttonIndex",0); result.put("input1", promptInput.getText().toString().trim().length()==0 ? defaultText : promptInput.getText()); } catch (JSONException e) { e.printStackTrace(); } callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result)); } }); changeTextDirection(dlg); }; }; this.cordova.getActivity().runOnUiThread(runnable); } /** * Builds and shows a native Android alert with given Strings * @param message The message the alert should display * @param title The title of the alert * @param buttonLabel The label of the button * @param callbackContext The callback context */ public synchronized void list(final String title, final JSONArray data, final CallbackContext callbackContext) { final CordovaInterface cordova = this.cordova; final String[] options = new String[data.length()]; for(int i = 0;i < data.length();i++){ try { options[i] = data.getString(i); } catch (JSONException e) { e.printStackTrace(); } } Runnable runnable = new Runnable() { public void run() { final JSONObject result = new JSONObject(); AlertDialog.Builder dlg = createDialog(cordova); // new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT); dlg.setTitle(title); dlg.setCancelable(false); dlg.setItems(options, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); try { result.put("buttonIndex", 1); result.put("selectedIndex", which); } catch (JSONException e) { e.printStackTrace(); } callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result)); } }); dlg.setNegativeButton("Cancel", new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); try { result.put("buttonIndex", 0); } catch (JSONException e) { e.printStackTrace(); } callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result)); } }); dlg.setOnCancelListener(new AlertDialog.OnCancelListener() { public void onCancel(DialogInterface dialog) { dialog.dismiss(); try { result.put("buttonIndex", 0); } catch (JSONException e) { e.printStackTrace(); } callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result)); } }); changeTextDirection(dlg); }; }; this.cordova.getActivity().runOnUiThread(runnable); } /** * * @param message * @param title * @param buttonLabels * @param defaultTexts * @param callbackContext */ public synchronized void login(final String title, final String message, final JSONArray buttonLabels, final JSONArray defaultTexts,final CallbackContext callbackContext) { final CordovaInterface cordova = this.cordova; Runnable runnable = new Runnable() { public void run() { LinearLayout layout = new LinearLayout(cordova.getActivity()); layout.setOrientation(LinearLayout.VERTICAL); layout.setPadding(10, 0, 10, 0); final EditText usernameInput = new EditText(cordova.getActivity()); usernameInput.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_NORMAL); final EditText passwordInput = new EditText(cordova.getActivity()); passwordInput.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PASSWORD); try { usernameInput.setHint("ID"); usernameInput.setText(defaultTexts.getString(0)); passwordInput.setHint("PASSWORD"); passwordInput.setText(defaultTexts.getString(1)); } catch (JSONException e1){} layout.addView(usernameInput, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT)); layout.addView(passwordInput, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT)); AlertDialog.Builder dlg = createDialog(cordova); // new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT); dlg.setMessage(message); dlg.setTitle(title); dlg.setCancelable(false); dlg.setView(layout); final JSONObject result = new JSONObject(); try { dlg.setNegativeButton(buttonLabels.getString(0), new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); try { result.put("buttonIndex",1); result.put("input1", usernameInput.getText()); result.put("input2", passwordInput.getText()); } catch (JSONException e) { e.printStackTrace(); } callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result)); } }); } catch (JSONException e) { } try { dlg.setPositiveButton(buttonLabels.getString(1), new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); try { result.put("buttonIndex",3); } catch (JSONException e) { e.printStackTrace(); } callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result)); } }); } catch (JSONException e) { } dlg.setOnCancelListener(new AlertDialog.OnCancelListener() { public void onCancel(DialogInterface dialog){ dialog.dismiss(); try { result.put("buttonIndex",0); } catch (JSONException e) { e.printStackTrace(); } callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result)); } }); changeTextDirection(dlg); }; }; this.cordova.getActivity().runOnUiThread(runnable); } @SuppressLint("NewApi") private AlertDialog.Builder createDialog(CordovaInterface cordova) { int currentapiVersion = android.os.Build.VERSION.SDK_INT; if (currentapiVersion >= android.os.Build.VERSION_CODES.HONEYCOMB) { return new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT); } else { return new AlertDialog.Builder(cordova.getActivity()); } } @SuppressLint("NewApi") private void changeTextDirection(Builder dlg){ int currentapiVersion = android.os.Build.VERSION.SDK_INT; dlg.create(); AlertDialog dialog = dlg.show(); if (currentapiVersion >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) { TextView messageview = (TextView)dialog.findViewById(android.R.id.message); if(messageview != null) messageview.setTextDirection(android.view.View.TEXT_DIRECTION_LOCALE); } } }
3e1dada5875de59faffc3526d4ebf32b89fa15fb
6,422
java
Java
hedera-node/src/main/java/com/hedera/services/ServicesApp.java
buidler-labs/hedera-services
3e3c6e1815ecb545d5a65e5ff4d87c46d365112e
[ "Apache-2.0" ]
null
null
null
hedera-node/src/main/java/com/hedera/services/ServicesApp.java
buidler-labs/hedera-services
3e3c6e1815ecb545d5a65e5ff4d87c46d365112e
[ "Apache-2.0" ]
null
null
null
hedera-node/src/main/java/com/hedera/services/ServicesApp.java
buidler-labs/hedera-services
3e3c6e1815ecb545d5a65e5ff4d87c46d365112e
[ "Apache-2.0" ]
null
null
null
37.776471
89
0.824665
12,571
package com.hedera.services; /*- * ‌ * Hedera Services Node * ​ * Copyright (C) 2018 - 2021 Hedera Hashgraph, LLC * ​ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ‍ */ import com.hedera.services.context.ContextModule; import com.hedera.services.context.CurrentPlatformStatus; import com.hedera.services.context.NodeInfo; import com.hedera.services.context.annotations.BootstrapProps; import com.hedera.services.context.annotations.StaticAccountMemo; import com.hedera.services.context.init.ServicesInitFlow; import com.hedera.services.context.properties.GlobalDynamicProperties; import com.hedera.services.context.properties.NodeLocalProperties; import com.hedera.services.context.properties.PropertiesModule; import com.hedera.services.context.properties.PropertySource; import com.hedera.services.contracts.ContractsModule; import com.hedera.services.fees.FeesModule; import com.hedera.services.files.FilesModule; import com.hedera.services.grpc.GrpcModule; import com.hedera.services.grpc.GrpcServerManager; import com.hedera.services.grpc.GrpcStarter; import com.hedera.services.keys.KeysModule; import com.hedera.services.ledger.LedgerModule; import com.hedera.services.ledger.backing.BackingStore; import com.hedera.services.queries.QueriesModule; import com.hedera.services.records.RecordsModule; import com.hedera.services.sigs.SigsModule; import com.hedera.services.sigs.order.SigReqsManager; import com.hedera.services.state.DualStateAccessor; import com.hedera.services.state.StateAccessor; import com.hedera.services.state.StateModule; import com.hedera.services.state.annotations.WorkingState; import com.hedera.services.state.exports.AccountsExporter; import com.hedera.services.state.exports.BalancesExporter; import com.hedera.services.state.forensics.HashLogger; import com.hedera.services.state.initialization.SystemAccountsCreator; import com.hedera.services.state.initialization.SystemFilesManager; import com.hedera.services.state.logic.NetworkCtxManager; import com.hedera.services.state.merkle.MerkleAccount; import com.hedera.services.state.validation.LedgerValidator; import com.hedera.services.state.virtual.VirtualMapFactory; import com.hedera.services.stats.ServicesStatsManager; import com.hedera.services.stats.StatsModule; import com.hedera.services.store.StoresModule; import com.hedera.services.stream.RecordStreamManager; import com.hedera.services.throttling.ThrottlingModule; import com.hedera.services.txns.ProcessLogic; import com.hedera.services.txns.TransactionsModule; import com.hedera.services.txns.network.UpgradeActions; import com.hedera.services.txns.prefetch.PrefetchProcessor; import com.hedera.services.txns.span.ExpandHandleSpan; import com.hedera.services.txns.submission.SubmissionModule; import com.hedera.services.utils.NamedDigestFactory; import com.hedera.services.utils.Pause; import com.hedera.services.utils.SystemExits; import com.hederahashgraph.api.proto.java.AccountID; import com.swirlds.common.InvalidSignedStateListener; import com.swirlds.common.NodeId; import com.swirlds.common.Platform; import com.swirlds.common.crypto.Hash; import com.swirlds.common.notification.NotificationEngine; import com.swirlds.common.notification.listeners.ReconnectCompleteListener; import com.swirlds.common.notification.listeners.StateWriteToDiskCompleteListener; import dagger.BindsInstance; import dagger.Component; import javax.inject.Singleton; import java.io.PrintStream; import java.nio.charset.Charset; import java.util.Optional; import java.util.function.Supplier; /** * The infrastructure used to implement the platform contract for a Hedera Services node. */ @Singleton @Component(modules = { FeesModule.class, KeysModule.class, SigsModule.class, GrpcModule.class, StatsModule.class, StateModule.class, FilesModule.class, LedgerModule.class, StoresModule.class, ContextModule.class, RecordsModule.class, QueriesModule.class, ContractsModule.class, PropertiesModule.class, ThrottlingModule.class, SubmissionModule.class, TransactionsModule.class }) public interface ServicesApp { /* Needed by ServicesState */ HashLogger hashLogger(); ProcessLogic logic(); ExpandHandleSpan expandHandleSpan(); ServicesInitFlow initializationFlow(); DualStateAccessor dualStateAccessor(); VirtualMapFactory virtualMapFactory(); SigReqsManager sigReqsManager(); RecordStreamManager recordStreamManager(); NodeLocalProperties nodeLocalProperties(); GlobalDynamicProperties globalDynamicProperties(); @WorkingState StateAccessor workingState(); PrefetchProcessor prefetchProcessor(); /* Needed by ServicesMain */ Pause pause(); NodeId nodeId(); Platform platform(); NodeInfo nodeInfo(); SystemExits systemExits(); GrpcStarter grpcStarter(); UpgradeActions upgradeActions(); LedgerValidator ledgerValidator(); AccountsExporter accountsExporter(); BalancesExporter balancesExporter(); Supplier<Charset> nativeCharset(); NetworkCtxManager networkCtxManager(); GrpcServerManager grpc(); NamedDigestFactory digestFactory(); SystemFilesManager sysFilesManager(); ServicesStatsManager statsManager(); CurrentPlatformStatus platformStatus(); SystemAccountsCreator sysAccountsCreator(); Optional<PrintStream> consoleOut(); ReconnectCompleteListener reconnectListener(); StateWriteToDiskCompleteListener stateWriteToDiskListener(); InvalidSignedStateListener issListener(); Supplier<NotificationEngine> notificationEngine(); BackingStore<AccountID, MerkleAccount> backingAccounts(); @Component.Builder interface Builder { @BindsInstance Builder initialHash(Hash initialHash); @BindsInstance Builder platform(Platform platform); @BindsInstance Builder selfId(long selfId); @BindsInstance Builder staticAccountMemo(@StaticAccountMemo String accountMemo); @BindsInstance Builder bootstrapProps(@BootstrapProps PropertySource bootstrapProps); ServicesApp build(); } }
3e1daea2c102bdc9bbccde8b8b8fe33e9b23c95f
7,015
java
Java
back-end 1.4/biblioteca-web funzionante/src/main/java/com/primas/javaee/bibliotecafinale/controllers/BibliotecaController.java
picpaco/biblioteca
e08ef72643e35113a5cc3a137c28004f100c357f
[ "MIT" ]
null
null
null
back-end 1.4/biblioteca-web funzionante/src/main/java/com/primas/javaee/bibliotecafinale/controllers/BibliotecaController.java
picpaco/biblioteca
e08ef72643e35113a5cc3a137c28004f100c357f
[ "MIT" ]
null
null
null
back-end 1.4/biblioteca-web funzionante/src/main/java/com/primas/javaee/bibliotecafinale/controllers/BibliotecaController.java
picpaco/biblioteca
e08ef72643e35113a5cc3a137c28004f100c357f
[ "MIT" ]
null
null
null
32.031963
103
0.688382
12,572
package com.primas.javaee.bibliotecafinale.controllers; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; 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.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.RestController; import com.primas.javaee.bibliotecafinale.jwt.JwtUtils; import com.primas.javaee.bibliotecafinale.models.Copia; import com.primas.javaee.bibliotecafinale.models.Libro; import com.primas.javaee.bibliotecafinale.playload.CopiaRequest; import com.primas.javaee.bibliotecafinale.playload.LibroRequest; import com.primas.javaee.bibliotecafinale.playload.MessageResponse; import com.primas.javaee.bibliotecafinale.repository.CopiaRepository; import com.primas.javaee.bibliotecafinale.repository.LibroRepository; @CrossOrigin(origins = "*", maxAge = 3600) @RestController @RequestMapping("/libri") public class BibliotecaController { @Autowired JwtUtils jwtUtils; @Autowired LibroRepository libroRepository; @Autowired CopiaRepository copiaRepository; @GetMapping("/") @PreAuthorize("hasRole('USER') or hasRole('ADMIN')") public List<Libro> getLibri() { return libroRepository.findAll(); } @PutMapping("/prestito") @PreAuthorize("hasRole('ADMIN')") public ResponseEntity<?> prestito(@RequestBody LibroRequest libro) { String codice = libro.getCodice(); Set<Copia> copieDalDb = new HashSet<>(); Optional<Libro> lib; if (existsByCodice(codice)) { // Integer numeroCopie = (libro.getNumeroCopie()+1); lib = findByCodice(codice); // copie = libroRepository.copieLibro(codice); copieDalDb = lib.get().getCopie(); for(Copia copiaRequest : libro.getCopie()) { for(Iterator<Copia> iterator = copieDalDb.iterator(); iterator.hasNext();) { Copia c = iterator.next(); if( c.getCodice().equals(copiaRequest.getCodice())) { //System.out.println("Trovata copia:"+copiaRequest.getCodice()); c.setInPrestito(copiaRequest.isInPrestito()); //System.out.println(""); } } } libroRepository.flush(); copiaRepository.saveAll(copieDalDb); return ResponseEntity.ok(new MessageResponse("Stato prestito della copia aggiornato" )); }else { return ResponseEntity.badRequest().body(new MessageResponse("Errore il libro non esiste")); } } @PutMapping("/aggiorna") @PreAuthorize("hasRole('ADMIN')") public ResponseEntity<?> aggiornaCopiaLibro(@RequestBody LibroRequest libro) { String codice = libro.getCodice(); Set<Copia> copie = new HashSet<>(); Optional<Libro> lib; if (existsByCodice(codice)) { // Integer numeroCopie = (libro.getNumeroCopie()+1); lib = findByCodice(codice); // copie = libroRepository.copieLibro(codice); copie = lib.get().getCopie(); // libroRepository.copieLibro(codice); // libro.getCopie(); System.out.println("Libro: " + lib); Integer numeroCopie = lib.get().getNumeroCopie(); System.out.println("Numero copie: " + numeroCopie); // for (int i = 0; i < numeroCo) String numCopie = libro.getCodice(); for (Integer i = 0; i < libro.getCopie().size(); i++) { if ( i == 0) { numCopie = numCopie.concat("0"); } if ( i == 9) { numCopie = numCopie.replace('0', ' ').replace(" ", ""); } Copia copia = new Copia(numCopie.concat((new Integer (i+1)).toString()), lib.get()); copie.add(copia); //copiaRepository.save(copia); } lib.get().setCopie(copie); lib.get().setNumeroCopie(numeroCopie); libroRepository.flush(); copiaRepository.saveAll(copie); System.out.println("Codice copia: " + libro.getCopie().size()); // Copia copia = new Copia(codiceCopia, lib.get()); // copie.add(copia); // lib.get().setCopie(copie); // lib.get().setNumeroCopie(numeroCopie); // libroRepository.flush(); // libroRepository.save(lib); return ResponseEntity.ok(new MessageResponse("Libro esistente, aggiunta una copia: " + lib + ", ")); } else { return ResponseEntity.badRequest().body(new MessageResponse("Error: Il libro non esiste")); } } @PostMapping("/aggiungi") public ResponseEntity<?> aggiungiCopiaLibro(@RequestBody LibroRequest libro) { String codice = libro.getCodice(); if (!existsByCodice(codice)) { Libro lib; lib = new Libro(libro.getCodice(), libro.getTitolo(), libro.getAutore()); lib.setNumeroCopie(libro.getNumeroCopie()); Set<Copia> copie = new HashSet<>(); System.out.println("Numero copie della request:------->" + libro.getNumeroCopie()); String codiceCopia = libro.getCodice(); //for (Integer i = 0; i < libro.getCopie().size(); i++) { for (Integer i = 0; i < libro.getNumeroCopie(); i++) { if ( i == 0) { codiceCopia = codiceCopia.concat("0"); } if ( i == 9) { codiceCopia = codiceCopia.replace('0', ' ').replace(" ", ""); } Copia copia = new Copia(codiceCopia.concat((new Integer (i+1)).toString()), lib); copie.add(copia); //copiaRepository.save(copia); } lib.setCopie(copie); //lib.setNumeroCopie(libro.getCopie().size()); libroRepository.save(lib); copiaRepository.saveAll(copie); // copiaRepository.flush(); // libroRepository.flush(); return ResponseEntity.ok(new MessageResponse("Nuovo libro: " + libro + " Copie: " + copie)); } else { return ResponseEntity.badRequest().body(new MessageResponse("Error: Il libro già esiste")); } } private Optional<Libro> findByCodice(String codice) { List<Libro> listaLibri = getLibri(); for (Libro libro : listaLibri) { if (codice.equals(libro.getCodice())) { return Optional.of(libro); } } return Optional.empty(); } private boolean existsByCodice(String codice) { List<Libro> listaLibri = getLibri(); for (Libro libro : listaLibri) { if (codice.equals(libro.getCodice())) { return true; } } return false; } @DeleteMapping("/copia/{id}") @PreAuthorize("hasRole('ADMIN')") public void rimuoviCopia(@RequestBody String codiceCopia) { if (!libroRepository.existsByCodice(codiceCopia)) { ResponseEntity.ok(new MessageResponse("Copia non esistente. " + codiceCopia)); } else { Copia copia = copiaRepository.findByCodice(codiceCopia).get(); copiaRepository.delete(copia); ResponseEntity.ok(new MessageResponse("Copia cancellata. " + copia)); } } }
3e1dafcc0fe8d108bd8912d191eca176ddb33f18
1,625
java
Java
platform-emf/src/main/java/com/softicar/platform/emf/token/parser/converter/EmfTokenToForeignConverter.java
softicar/platform
d4cf99f3e3537272af23bf60f6b088891bd271ff
[ "MIT" ]
1
2021-11-25T09:58:31.000Z
2021-11-25T09:58:31.000Z
platform-emf/src/main/java/com/softicar/platform/emf/token/parser/converter/EmfTokenToForeignConverter.java
softicar/platform
d4cf99f3e3537272af23bf60f6b088891bd271ff
[ "MIT" ]
22
2021-11-10T13:59:22.000Z
2022-03-04T16:38:33.000Z
platform-emf/src/main/java/com/softicar/platform/emf/token/parser/converter/EmfTokenToForeignConverter.java
softicar/platform
d4cf99f3e3537272af23bf60f6b088891bd271ff
[ "MIT" ]
null
null
null
37.790698
137
0.780923
12,573
package com.softicar.platform.emf.token.parser.converter; import com.softicar.platform.common.core.exceptions.SofticarNotImplementedYetException; import com.softicar.platform.common.core.i18n.IDisplayString; import com.softicar.platform.common.core.utils.CastUtils; import com.softicar.platform.db.runtime.field.IDbForeignField; import com.softicar.platform.db.runtime.logic.IDbObject; import com.softicar.platform.db.runtime.table.IDbTable; import com.softicar.platform.emf.EmfI18n; class EmfTokenToForeignConverter extends AbstractEmfTokenConverter<IDbObject<?>, IDbForeignField<?, ?>> { @Override protected EmfTokenConverterResult<IDbObject<?>> convertToken(IDbForeignField<?, ?> field, String token) { IDbTable<?, ?> targetTable = field.getTargetTable(); if (hasIntegerPrimaryKey(targetTable)) { int id = Integer.parseInt(token); IDbObject<?> value = CastUtils.cast(targetTable.get(CastUtils.cast(id))); if (value != null) { return EmfTokenConverterResult.okay(value); } else { return EmfTokenConverterResult .failed(EmfI18n.THE_RECORD_WITH_ID_ARG1_COULD_NOT_BE_FOUND_IN_TABLE_ARG2.toDisplay(id, targetTable.getFullName())); } } else { // TODO later-on: support this throw new SofticarNotImplementedYetException("Foreign key references to tables with non-integer primary keys are not yet supported."); } } @Override public IDisplayString getTypeDescription() { return createTypeDescriptionWithExample(EmfI18n.FOREIGN_ID, "128"); } private boolean hasIntegerPrimaryKey(IDbTable<?, ?> targetTable) { return targetTable.getPrimaryKey().getIdField() != null; } }
3e1db0def0c118c02e9ce032a0faeb597bedfc12
720
java
Java
app/utils/jooq/converters/TimestampToLocalDateTimeConverter.java
D4v1X/workentry.server
5d617fc50ae35f88f6f5dbb53c1f2115c2570191
[ "Apache-2.0" ]
null
null
null
app/utils/jooq/converters/TimestampToLocalDateTimeConverter.java
D4v1X/workentry.server
5d617fc50ae35f88f6f5dbb53c1f2115c2570191
[ "Apache-2.0" ]
null
null
null
app/utils/jooq/converters/TimestampToLocalDateTimeConverter.java
D4v1X/workentry.server
5d617fc50ae35f88f6f5dbb53c1f2115c2570191
[ "Apache-2.0" ]
null
null
null
23.225806
96
0.665278
12,574
package utils.jooq.converters; import org.jooq.Converter; import java.sql.Timestamp; import java.time.LocalDateTime; public class TimestampToLocalDateTimeConverter implements Converter<Timestamp, LocalDateTime> { @Override public LocalDateTime from(Timestamp t) { return t == null ? null : t.toLocalDateTime(); } @Override public Timestamp to(LocalDateTime localDateTime) { return localDateTime == null ? null : Timestamp.valueOf(localDateTime); } @Override public Class<Timestamp> fromType() { return Timestamp.class; } @Override public Class<LocalDateTime> toType() { return LocalDateTime.class; } }
3e1db13999550f410a223cc026423ff7aa4c5d62
1,725
java
Java
reorganizing-messages/src/test/java/org/apache/camel/howto/ReorganizingMessagesTest.java
rampoon/camel-message-routing-examples
60738b66dfdbd648c7e9b25dda59a33f3d27be85
[ "Apache-2.0" ]
2
2018-12-28T16:39:48.000Z
2018-12-29T16:56:15.000Z
reorganizing-messages/src/test/java/org/apache/camel/howto/ReorganizingMessagesTest.java
rampoon/camel-message-routing-examples
60738b66dfdbd648c7e9b25dda59a33f3d27be85
[ "Apache-2.0" ]
null
null
null
reorganizing-messages/src/test/java/org/apache/camel/howto/ReorganizingMessagesTest.java
rampoon/camel-message-routing-examples
60738b66dfdbd648c7e9b25dda59a33f3d27be85
[ "Apache-2.0" ]
null
null
null
32.54717
85
0.742029
12,575
/* * Copyright (C) Bilgin Ibryam http://www.ofbizian.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.apache.camel.howto; import org.apache.camel.EndpointInject; import org.apache.camel.Produce; import org.apache.camel.ProducerTemplate; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; public class ReorganizingMessagesTest extends CamelTestSupport { @Override protected RouteBuilder createRouteBuilder() throws Exception { return new ReorganizingMessages(); } @Produce(uri = "direct:start") protected ProducerTemplate start; @EndpointInject(uri = "mock:result") private MockEndpoint mockResult; @Test public void ordersOutOfOrderMessages() throws Exception { mockResult.expectedMessageCount(3); mockResult.expectsAscending(header("message_index").convertTo(Number.class)); start.sendBodyAndHeader(null, "message_index", 3); start.sendBodyAndHeader(null, "message_index", 1); start.sendBodyAndHeader(null, "message_index", 2); assertMockEndpointsSatisfied(); } }
3e1db1a151c2cd84c10402488b51486f4e4b1024
118
java
Java
src/main/java/edu/fiuba/algo3/modelo/general/CantidadInvalidaDeJugadoresException.java
szwtomas/algo3_tp2_TEG
b907f29e7fde8f00d3bc9f697a8b3d8e68e51fbd
[ "MIT" ]
null
null
null
src/main/java/edu/fiuba/algo3/modelo/general/CantidadInvalidaDeJugadoresException.java
szwtomas/algo3_tp2_TEG
b907f29e7fde8f00d3bc9f697a8b3d8e68e51fbd
[ "MIT" ]
null
null
null
src/main/java/edu/fiuba/algo3/modelo/general/CantidadInvalidaDeJugadoresException.java
szwtomas/algo3_tp2_TEG
b907f29e7fde8f00d3bc9f697a8b3d8e68e51fbd
[ "MIT" ]
null
null
null
29.5
76
0.872881
12,576
package edu.fiuba.algo3.modelo.general; public class CantidadInvalidaDeJugadoresException extends RuntimeException{}
3e1db1edc8242fe1399f932d0d7abfea43966f13
9,871
java
Java
src/main/java/com/mdSolutions/myPhoto/gui/FbActionsModal.java
mollidrivdahl/myPhoto
932c8d67cfc7e05bc873df68349d3c9f890cc009
[ "MIT" ]
null
null
null
src/main/java/com/mdSolutions/myPhoto/gui/FbActionsModal.java
mollidrivdahl/myPhoto
932c8d67cfc7e05bc873df68349d3c9f890cc009
[ "MIT" ]
null
null
null
src/main/java/com/mdSolutions/myPhoto/gui/FbActionsModal.java
mollidrivdahl/myPhoto
932c8d67cfc7e05bc873df68349d3c9f890cc009
[ "MIT" ]
null
null
null
36.424354
133
0.598622
12,577
package com.mdSolutions.myPhoto.gui; import com.mdSolutions.myPhoto.FbMediaUploader; import com.mdSolutions.myPhoto.PhotoMedia; import com.mdSolutions.myPhoto.VideoMedia; import com.restfb.*; import com.restfb.types.Album; import com.restfb.types.GraphResponse; import javafx.application.Platform; import javafx.concurrent.Worker; import javafx.embed.swing.JFXPanel; import javafx.scene.Scene; import javafx.scene.web.WebEngine; import javafx.scene.web.WebView; import javax.swing.*; import java.awt.*; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.net.URL; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.json.*; import netscape.javascript.JSObject; public class FbActionsModal { private static final Color FB_LIGHT_BLUE = new Color(141, 160, 199); private JFrame fbFrame; private JDialog fbDialog; private JFXPanel fbJFXPanel; //content pane of dialog - will hold webview private WebView webView; private Scene scene; private WebEngine engine; private String curUrl; private BridgeFromJavaScriptToJavaFx bridgeWebToJava; public FbActionsModal() { initializeFbModalComponents(); } private void initializeFbModalComponents() { fbFrame = new JFrame(); fbDialog = new JDialog(fbFrame, "Facebook Actions", true); fbJFXPanel = new JFXPanel(); bridgeWebToJava = new BridgeFromJavaScriptToJavaFx(); setupFbJFXPanelAndWebView(); setupFbDialog(); } private void setupFbJFXPanelAndWebView() { fbJFXPanel.setPreferredSize(new Dimension(700, 775)); fbJFXPanel.setBackground(FB_LIGHT_BLUE); } private void startJfxPlatformRunnable() { Platform.runLater(() -> { webView = new WebView(); scene = new Scene(webView); fbJFXPanel.setScene(scene); engine = webView.getEngine(); // Enable Javascript. engine.setJavaScriptEnabled(true); //TODO: display progress bar while webpages load if (!FbMediaUploader.getInstance().isLoggedIn()) loginToFacebook(); else { //redirect to custom html screen try { File file = new File(getCustomHtmlScreen()); URL url = file.toURI().toURL(); engine.load(url.toString()); } catch (Exception ex) { System.out.println(ex.getMessage()); } } engine.getLoadWorker().stateProperty().addListener((observable, oldValue, newValue) -> { if (Worker.State.SUCCEEDED.equals(newValue)) { //get current url curUrl = engine.getLocation(); //url of custom html page if (curUrl.contains(getCustomHtmlScreen())) { webView.setVisible(true); // Get window object of page. JSObject jsobj = (JSObject) engine.executeScript("window"); // Set member for 'window' object. // In Javascript access: window.javaBridgeMember.... jsobj.setMember("javaBridgeMember", bridgeWebToJava); } //redirect from login, returning app code else if (curUrl.contains("https://www.facebook.com/connect/login_success.html?code")) { webView.setVisible(false); parseLoginRedirect(curUrl, engine); } //getting http request for access token json else if (curUrl.contains("https://graph.facebook.com/v2.12/oauth/access_token")) { String html = (String) engine.executeScript("document.documentElement.outerHTML"); parseAccessTokenJSON(html, engine); } //getting http request for user id else if (curUrl.contains("https://graph.facebook.com/me?fields=id&access_token=")) { String html = (String) engine.executeScript("document.documentElement.outerHTML"); parseUserIdJSON(html); } } }); }); } private void setupFbDialog() { fbDialog.setContentPane(fbJFXPanel); fbDialog.setPreferredSize(new Dimension(700, 900)); fbDialog.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); } private void loginToFacebook() { String loginDialogEnpoint = "https://www.facebook.com/v2.12/dialog/oauth?" + "client_id=" + FbMediaUploader.APP_ID + "&redirect_uri=https://www.facebook.com/connect/login_success.html" + "&state=" + FbMediaUploader.APP_STATE + "&auth_type=rerequest" + "&scope=publish_actions,user_photos,user_videos"; if (engine != null) { engine.load(loginDialogEnpoint); } } private void parseLoginRedirect(String url, WebEngine engine) { Pattern pattern = Pattern.compile("=(.*?)&"); Matcher matcher = pattern.matcher(url); if (matcher.find()) { FbMediaUploader.getInstance().setAppCode(matcher.group(1)); getAccessToken(engine); } } private void getAccessToken(WebEngine engine) { String exchangeCodeForAccessTokenUrl = "https://graph.facebook.com/v2.12/oauth/access_token?" + "client_id=" + FbMediaUploader.APP_ID + "&redirect_uri=https://www.facebook.com/connect/login_success.html" + "&client_secret=" + FbMediaUploader.APP_SECRET + "&code=" + FbMediaUploader.getInstance().getAppCode() ; engine.load(exchangeCodeForAccessTokenUrl); } private void parseAccessTokenJSON(String html, WebEngine engine) { Pattern pattern = Pattern.compile("\\{(.*?)}", Pattern.DOTALL); Matcher matcher = pattern.matcher(html); if (matcher.find()) { String innerJSON = matcher.group(1); JSONObject fullJSON = new JSONObject("{" + innerJSON + "}"); FbMediaUploader.getInstance().setAccessToken(fullJSON.get("access_token").toString()); getUserId(engine); } } private void getUserId(WebEngine engine) { String userIdUrl = "https://graph.facebook.com/me?fields=id&access_token=" + FbMediaUploader.getInstance().getAccessToken(); engine.load(userIdUrl); } private void parseUserIdJSON(String html) { Pattern pattern = Pattern.compile("\\{(.*?)}", Pattern.DOTALL); Matcher matcher = pattern.matcher(html); if (matcher.find()) { String innerJSON = matcher.group(1); JSONObject fullJSON = new JSONObject("{" + innerJSON + "}"); FbMediaUploader.getInstance().setUserId(fullJSON.get("id").toString()); //redirect to custom html screen try { File file = new File(getCustomHtmlScreen()); URL url = file.toURI().toURL(); engine.load(url.toString()); } catch (Exception ex) { System.out.println(ex.getMessage()); } finalizeLoginDetails(); } } private void finalizeLoginDetails() { FbMediaUploader fbUploader = FbMediaUploader.getInstance(); fbUploader.setLoggedIn(true); FacebookClient client = new DefaultFacebookClient(FbMediaUploader.getInstance().getAccessToken(), com.restfb.Version.LATEST); fbUploader.setFbClient(client); } private String getCustomHtmlScreen() { String htmlUploadPhotos = "src/main/web/uploadPhotos.html"; String htmlUploadVideos = "src/main/web/uploadVideos.html"; if (FbMediaUploader.getInstance().getUploadType() == FbMediaUploader.MEDIA_TYPE.PHOTOS) return htmlUploadPhotos; else return htmlUploadVideos; } public void display() { startJfxPlatformRunnable(); //ensures webview stuff runs on a separate javafx thread fbDialog.pack(); fbDialog.setLocationRelativeTo(null); fbDialog.setVisible(true); } public class BridgeFromJavaScriptToJavaFx { BridgeFromJavaScriptToJavaFx() {} //called from uploadPhotos.html public void uploadPhotos(String albumName, String message) { //redirect to upload custom html loading screen try { File file = new File("src/main/web/uploadingMedia.html"); URL url = file.toURI().toURL(); engine.load(url.toString()); } catch (Exception ex) { System.out.println(ex.getMessage()); } Thread uploadThread = new Thread(() -> { FbMediaUploader.getInstance().uploadPhotos(albumName, message); //close webview fbDialog.setVisible(false); }); uploadThread.start(); } //called from uploadVideos.html public void uploadVideos(String message) { //redirect to upload custom html loading screen try { File file = new File("src/main/web/uploadingMedia.html"); URL url = file.toURI().toURL(); engine.load(url.toString()); } catch (Exception ex) { System.out.println(ex.getMessage()); } Thread uploadThread = new Thread(() -> { FbMediaUploader.getInstance().uploadVideos(message); //close webview fbDialog.setVisible(false); }); uploadThread.start(); } } }
3e1db234702b69df4a9217dadc023ae7a92efa4b
4,145
java
Java
src/main/java/org/apache/expreval/expr/compare/DelegateCompare.java
pambrose/HBql
14109d012d25d2e9a3fdda7b9015981bd9a239ae
[ "Apache-2.0" ]
6
2016-08-30T06:26:47.000Z
2021-06-05T03:07:55.000Z
src/main/java/org/apache/expreval/expr/compare/DelegateCompare.java
pambrose/HBql
14109d012d25d2e9a3fdda7b9015981bd9a239ae
[ "Apache-2.0" ]
null
null
null
src/main/java/org/apache/expreval/expr/compare/DelegateCompare.java
pambrose/HBql
14109d012d25d2e9a3fdda7b9015981bd9a239ae
[ "Apache-2.0" ]
6
2015-01-24T03:54:58.000Z
2020-01-16T08:25:36.000Z
48.197674
113
0.707117
12,578
/* * Copyright (c) 2011. The Apache Software Foundation * * 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.expreval.expr.compare; import org.apache.expreval.client.NullColumnValueException; import org.apache.expreval.client.ResultMissingColumnException; import org.apache.expreval.expr.Operator; import org.apache.expreval.expr.TypeSupport; import org.apache.expreval.expr.node.BooleanValue; import org.apache.expreval.expr.node.ByteValue; import org.apache.expreval.expr.node.DateValue; import org.apache.expreval.expr.node.GenericValue; import org.apache.expreval.expr.node.NumberValue; import org.apache.expreval.expr.node.StringValue; import org.apache.hadoop.hbase.filter.Filter; import org.apache.hadoop.hbase.hbql.client.HBqlException; import org.apache.hadoop.hbase.hbql.impl.HConnectionImpl; import org.apache.hadoop.hbase.hbql.impl.InvalidTypeException; public class DelegateCompare extends GenericCompare { private GenericCompare typedExpr = null; public DelegateCompare(final GenericValue arg0, final Operator operator, final GenericValue arg1) { super(arg0, operator, arg1); } private GenericCompare getTypedExpr() { return this.typedExpr; } public Class<? extends GenericValue> validateTypes(final GenericValue parentExpr, final boolean allowCollections) throws HBqlException { final Class<? extends GenericValue> type0 = this.getExprArg(0).validateTypes(this, false); final Class<? extends GenericValue> type1 = this.getExprArg(1).validateTypes(this, false); if (TypeSupport.isParentClass(StringValue.class, type0, type1)) this.typedExpr = new StringCompare(this.getExprArg(0), this.getOperator(), this.getExprArg(1)); else if (TypeSupport.isParentClass(NumberValue.class, type0, type1)) this.typedExpr = new NumberCompare(this.getExprArg(0), this.getOperator(), this.getExprArg(1)); else if (TypeSupport.isParentClass(DateValue.class, type0, type1)) this.typedExpr = new DateCompare(this.getExprArg(0), this.getOperator(), this.getExprArg(1)); else if (TypeSupport.isParentClass(BooleanValue.class, type0, type1)) this.typedExpr = new BooleanCompare(this.getExprArg(0), this.getOperator(), this.getExprArg(1)); else if (TypeSupport.isParentClass(ByteValue.class, type0, type1)) this.typedExpr = new ByteCompare(this.getExprArg(0), this.getOperator(), this.getExprArg(1)); else throw new InvalidTypeException(this.getInvalidTypeMsg(type0, type1)); return this.getTypedExpr().validateTypes(parentExpr, false); } public GenericValue getOptimizedValue() throws HBqlException { this.optimizeAllArgs(); return !this.isAConstant() ? this : this.getTypedExpr().getOptimizedValue(); } public Boolean getValue(final HConnectionImpl conn, final Object object) throws HBqlException, ResultMissingColumnException, NullColumnValueException { return this.getTypedExpr().getValue(conn, object); } public Filter getFilter() throws HBqlException { return this.getTypedExpr().getFilter(); } }
3e1db443829e50c31dc112b412e7042f49904d2d
1,305
java
Java
docker-java-api/src/main/java/com/github/dockerjava/api/model/PropagationMode.java
ziminghua/docker-java
c61da29a09517c43f8ea2255f9abf26b2f3deba6
[ "Apache-2.0" ]
2,381
2015-01-01T15:08:18.000Z
2022-03-31T07:11:55.000Z
docker-java-api/src/main/java/com/github/dockerjava/api/model/PropagationMode.java
ziminghua/docker-java
c61da29a09517c43f8ea2255f9abf26b2f3deba6
[ "Apache-2.0" ]
1,479
2015-01-01T22:39:08.000Z
2022-03-30T04:59:50.000Z
docker-java-api/src/main/java/com/github/dockerjava/api/model/PropagationMode.java
xjc90s/docker-java
8253a999825d430df35148da835b37f1d731df0f
[ "Apache-2.0" ]
1,134
2015-01-07T08:41:06.000Z
2022-03-31T07:11:57.000Z
19.772727
114
0.537931
12,579
package com.github.dockerjava.api.model; /** * The propagation mode of a file system or file: <code>shared</code>, <code>slave</code> or <code>private</code>. * * @see https://github.com/docker/docker/pull/17034 * @since 1.22 */ public enum PropagationMode { /** default */ DEFAULT(""), /** shared */ SHARED("shared"), /** rshared */ RSHARED("rshared"), /** slave */ SLAVE("slave"), /** rslave */ RSLAVE("rslave"), /** private */ PRIVATE("private"), /** rprivate */ RPRIVATE("rprivate"); /** * The default {@link PropagationMode}: {@link #DEFAULT} */ public static final PropagationMode DEFAULT_MODE = DEFAULT; private String value; PropagationMode(String v) { value = v; } @Override public String toString() { return value; } public static PropagationMode fromString(String v) { switch (v) { case "shared": return SHARED; case "rshared": return RSHARED; case "slave": return SLAVE; case "rslave": return RSLAVE; case "private": return PRIVATE; case "rprivate": return RPRIVATE; default: return DEFAULT; } } }
3e1db4bfc167b552fb2a93033c0030bf7c37cb2e
19,863
java
Java
word8/src/main/java/eu/doppel_helix/jna/tlb/word8/_Global.java
matthiasblaesing/COMTypelibraries
c17acfca689305c0e23d4ff9d8ee437e0ee3d437
[ "MIT" ]
15
2016-11-30T17:25:43.000Z
2021-07-10T22:32:06.000Z
word8/src/main/java/eu/doppel_helix/jna/tlb/word8/_Global.java
matthiasblaesing/COMTypelibraries
c17acfca689305c0e23d4ff9d8ee437e0ee3d437
[ "MIT" ]
null
null
null
word8/src/main/java/eu/doppel_helix/jna/tlb/word8/_Global.java
matthiasblaesing/COMTypelibraries
c17acfca689305c0e23d4ff9d8ee437e0ee3d437
[ "MIT" ]
1
2019-09-10T02:40:33.000Z
2019-09-10T02:40:33.000Z
28.703757
87
0.54015
12,580
package eu.doppel_helix.jna.tlb.word8; import com.sun.jna.platform.win32.COM.util.annotation.ComInterface; import com.sun.jna.platform.win32.COM.util.annotation.ComMethod; import com.sun.jna.platform.win32.COM.util.annotation.ComProperty; import com.sun.jna.platform.win32.COM.util.IDispatch; import com.sun.jna.platform.win32.COM.util.IUnknown; import com.sun.jna.platform.win32.COM.util.IRawDispatchHandle; import com.sun.jna.platform.win32.Variant.VARIANT; /** * <p>uuid({000209B9-0000-0000-C000-000000000046})</p> */ @ComInterface(iid="{000209B9-0000-0000-C000-000000000046}") public interface _Global extends IUnknown, IRawDispatchHandle, IDispatch { /** * <p>id(0x3e8)</p> * <p>vtableId(7)</p> */ @ComProperty(name = "Application", dispId = 0x3e8) Application getApplication(); /** * <p>id(0x3e9)</p> * <p>vtableId(8)</p> */ @ComProperty(name = "Creator", dispId = 0x3e9) Integer getCreator(); /** * <p>id(0x3ea)</p> * <p>vtableId(9)</p> */ @ComProperty(name = "Parent", dispId = 0x3ea) com.sun.jna.platform.win32.COM.util.IDispatch getParent(); /** * <p>id(0x0)</p> * <p>vtableId(10)</p> */ @ComProperty(name = "Name", dispId = 0x0) String getName(); /** * <p>id(0x1)</p> * <p>vtableId(11)</p> */ @ComProperty(name = "Documents", dispId = 0x1) Documents getDocuments(); /** * <p>id(0x2)</p> * <p>vtableId(12)</p> */ @ComProperty(name = "Windows", dispId = 0x2) Windows getWindows(); /** * <p>id(0x3)</p> * <p>vtableId(13)</p> */ @ComProperty(name = "ActiveDocument", dispId = 0x3) Document getActiveDocument(); /** * <p>id(0x4)</p> * <p>vtableId(14)</p> */ @ComProperty(name = "ActiveWindow", dispId = 0x4) Window getActiveWindow(); /** * <p>id(0x5)</p> * <p>vtableId(15)</p> */ @ComProperty(name = "Selection", dispId = 0x5) Selection getSelection(); /** * <p>id(0x6)</p> * <p>vtableId(16)</p> */ @ComProperty(name = "WordBasic", dispId = 0x6) com.sun.jna.platform.win32.COM.util.IDispatch getWordBasic(); /** * <p>id(0x1b)</p> * <p>vtableId(17)</p> */ @ComProperty(name = "PrintPreview", dispId = 0x1b) Boolean getPrintPreview(); /** * <p>id(0x1b)</p> * <p>vtableId(18)</p> * @param param0 [in] {@code Boolean} */ @ComProperty(name = "PrintPreview", dispId = 0x1b) void setPrintPreview(Boolean param0); /** * <p>id(0x7)</p> * <p>vtableId(19)</p> */ @ComProperty(name = "RecentFiles", dispId = 0x7) RecentFiles getRecentFiles(); /** * <p>id(0x8)</p> * <p>vtableId(20)</p> */ @ComProperty(name = "NormalTemplate", dispId = 0x8) Template getNormalTemplate(); /** * <p>id(0x9)</p> * <p>vtableId(21)</p> */ @ComProperty(name = "System", dispId = 0x9) System getSystem(); /** * <p>id(0xa)</p> * <p>vtableId(22)</p> */ @ComProperty(name = "AutoCorrect", dispId = 0xa) AutoCorrect getAutoCorrect(); /** * <p>id(0xb)</p> * <p>vtableId(23)</p> */ @ComProperty(name = "FontNames", dispId = 0xb) FontNames getFontNames(); /** * <p>id(0xc)</p> * <p>vtableId(24)</p> */ @ComProperty(name = "LandscapeFontNames", dispId = 0xc) FontNames getLandscapeFontNames(); /** * <p>id(0xd)</p> * <p>vtableId(25)</p> */ @ComProperty(name = "PortraitFontNames", dispId = 0xd) FontNames getPortraitFontNames(); /** * <p>id(0xe)</p> * <p>vtableId(26)</p> */ @ComProperty(name = "Languages", dispId = 0xe) Languages getLanguages(); /** * <p>id(0xf)</p> * <p>vtableId(27)</p> */ @ComProperty(name = "Assistant", dispId = 0xf) eu.doppel_helix.jna.tlb.office2.Assistant getAssistant(); /** * <p>id(0x11)</p> * <p>vtableId(28)</p> */ @ComProperty(name = "FileConverters", dispId = 0x11) FileConverters getFileConverters(); /** * <p>id(0x13)</p> * <p>vtableId(29)</p> */ @ComProperty(name = "Dialogs", dispId = 0x13) Dialogs getDialogs(); /** * <p>id(0x14)</p> * <p>vtableId(30)</p> */ @ComProperty(name = "CaptionLabels", dispId = 0x14) CaptionLabels getCaptionLabels(); /** * <p>id(0x15)</p> * <p>vtableId(31)</p> */ @ComProperty(name = "AutoCaptions", dispId = 0x15) AutoCaptions getAutoCaptions(); /** * <p>id(0x16)</p> * <p>vtableId(32)</p> */ @ComProperty(name = "AddIns", dispId = 0x16) AddIns getAddIns(); /** * <p>id(0x1c)</p> * <p>vtableId(33)</p> */ @ComProperty(name = "Tasks", dispId = 0x1c) Tasks getTasks(); /** * <p>id(0x37)</p> * <p>vtableId(34)</p> */ @ComProperty(name = "MacroContainer", dispId = 0x37) com.sun.jna.platform.win32.COM.util.IDispatch getMacroContainer(); /** * <p>id(0x39)</p> * <p>vtableId(35)</p> */ @ComProperty(name = "CommandBars", dispId = 0x39) eu.doppel_helix.jna.tlb.office2.CommandBars getCommandBars(); /** * <p>id(0x3b)</p> * <p>vtableId(36)</p> * @param Word [in] {@code String} * @param LanguageID [in, optional] {@code Object} */ @ComProperty(name = "SynonymInfo", dispId = 0x3b) SynonymInfo getSynonymInfo(String Word, Object LanguageID); /** * <p>id(0x3d)</p> * <p>vtableId(37)</p> */ @ComProperty(name = "VBE", dispId = 0x3d) eu.doppel_helix.jna.tlb.vbide5.VBE getVBE(); /** * <p>id(0x41)</p> * <p>vtableId(38)</p> */ @ComProperty(name = "ListGalleries", dispId = 0x41) ListGalleries getListGalleries(); /** * <p>id(0x42)</p> * <p>vtableId(39)</p> */ @ComProperty(name = "ActivePrinter", dispId = 0x42) String getActivePrinter(); /** * <p>id(0x42)</p> * <p>vtableId(40)</p> * @param param0 [in] {@code String} */ @ComProperty(name = "ActivePrinter", dispId = 0x42) void setActivePrinter(String param0); /** * <p>id(0x43)</p> * <p>vtableId(41)</p> */ @ComProperty(name = "Templates", dispId = 0x43) Templates getTemplates(); /** * <p>id(0x44)</p> * <p>vtableId(42)</p> */ @ComProperty(name = "CustomizationContext", dispId = 0x44) com.sun.jna.platform.win32.COM.util.IDispatch getCustomizationContext(); /** * <p>id(0x44)</p> * <p>vtableId(43)</p> * @param param0 [in] {@code com.sun.jna.platform.win32.COM.util.IDispatch} */ @ComProperty(name = "CustomizationContext", dispId = 0x44) void setCustomizationContext(com.sun.jna.platform.win32.COM.util.IDispatch param0); /** * <p>id(0x45)</p> * <p>vtableId(44)</p> */ @ComProperty(name = "KeyBindings", dispId = 0x45) KeyBindings getKeyBindings(); /** * <p>id(0x46)</p> * <p>vtableId(45)</p> * @param KeyCategory [in] {@code WdKeyCategory} * @param Command [in] {@code String} * @param CommandParameter [in, optional] {@code Object} */ @ComProperty(name = "KeysBoundTo", dispId = 0x46) KeysBoundTo getKeysBoundTo(WdKeyCategory KeyCategory, String Command, Object CommandParameter); /** * <p>id(0x47)</p> * <p>vtableId(46)</p> * @param KeyCode [in] {@code Integer} * @param KeyCode2 [in, optional] {@code Object} */ @ComProperty(name = "FindKey", dispId = 0x47) KeyBinding getFindKey(Integer KeyCode, Object KeyCode2); /** * <p>id(0x5d)</p> * <p>vtableId(47)</p> */ @ComProperty(name = "Options", dispId = 0x5d) Options getOptions(); /** * <p>id(0x5f)</p> * <p>vtableId(48)</p> */ @ComProperty(name = "CustomDictionaries", dispId = 0x5f) Dictionaries getCustomDictionaries(); /** * <p>id(0x61)</p> * <p>vtableId(49)</p> * @param param0 [in] {@code String} */ @ComProperty(name = "StatusBar", dispId = 0x61) void setStatusBar(String param0); /** * <p>id(0x68)</p> * <p>vtableId(50)</p> */ @ComProperty(name = "ShowVisualBasicEditor", dispId = 0x68) Boolean getShowVisualBasicEditor(); /** * <p>id(0x68)</p> * <p>vtableId(51)</p> * @param param0 [in] {@code Boolean} */ @ComProperty(name = "ShowVisualBasicEditor", dispId = 0x68) void setShowVisualBasicEditor(Boolean param0); /** * <p>id(0x6d)</p> * <p>vtableId(52)</p> * @param Object [in] {@code com.sun.jna.platform.win32.COM.util.IDispatch} */ @ComProperty(name = "IsObjectValid", dispId = 0x6d) Boolean getIsObjectValid(com.sun.jna.platform.win32.COM.util.IDispatch Object); /** * <p>id(0x6e)</p> * <p>vtableId(53)</p> */ @ComProperty(name = "HangulHanjaDictionaries", dispId = 0x6e) HangulHanjaConversionDictionaries getHangulHanjaDictionaries(); /** * <p>id(0x131)</p> * <p>vtableId(54)</p> * @param Times [in, optional] {@code Object} */ @ComMethod(name = "Repeat", dispId = 0x131) Boolean Repeat(Object Times); /** * <p>id(0x136)</p> * <p>vtableId(55)</p> * @param Channel [in] {@code Integer} * @param Command [in] {@code String} */ @ComMethod(name = "DDEExecute", dispId = 0x136) void DDEExecute(Integer Channel, String Command); /** * <p>id(0x137)</p> * <p>vtableId(56)</p> * @param App [in] {@code String} * @param Topic [in] {@code String} */ @ComMethod(name = "DDEInitiate", dispId = 0x137) Integer DDEInitiate(String App, String Topic); /** * <p>id(0x138)</p> * <p>vtableId(57)</p> * @param Channel [in] {@code Integer} * @param Item [in] {@code String} * @param Data [in] {@code String} */ @ComMethod(name = "DDEPoke", dispId = 0x138) void DDEPoke(Integer Channel, String Item, String Data); /** * <p>id(0x139)</p> * <p>vtableId(58)</p> * @param Channel [in] {@code Integer} * @param Item [in] {@code String} */ @ComMethod(name = "DDERequest", dispId = 0x139) String DDERequest(Integer Channel, String Item); /** * <p>id(0x13a)</p> * <p>vtableId(59)</p> * @param Channel [in] {@code Integer} */ @ComMethod(name = "DDETerminate", dispId = 0x13a) void DDETerminate(Integer Channel); /** * <p>id(0x13b)</p> * <p>vtableId(60)</p> */ @ComMethod(name = "DDETerminateAll", dispId = 0x13b) void DDETerminateAll(); /** * <p>id(0x13c)</p> * <p>vtableId(61)</p> * @param Arg1 [in] {@code WdKey} * @param Arg2 [in, optional] {@code Object} * @param Arg3 [in, optional] {@code Object} * @param Arg4 [in, optional] {@code Object} */ @ComMethod(name = "BuildKeyCode", dispId = 0x13c) Integer BuildKeyCode(WdKey Arg1, Object Arg2, Object Arg3, Object Arg4); /** * <p>id(0x13d)</p> * <p>vtableId(62)</p> * @param KeyCode [in] {@code Integer} * @param KeyCode2 [in, optional] {@code Object} */ @ComMethod(name = "KeyString", dispId = 0x13d) String KeyString(Integer KeyCode, Object KeyCode2); /** * <p>id(0x144)</p> * <p>vtableId(63)</p> * @param Word [in] {@code String} * @param CustomDictionary [in, optional] {@code Object} * @param IgnoreUppercase [in, optional] {@code Object} * @param MainDictionary [in, optional] {@code Object} * @param CustomDictionary2 [in, optional] {@code Object} * @param CustomDictionary3 [in, optional] {@code Object} * @param CustomDictionary4 [in, optional] {@code Object} * @param CustomDictionary5 [in, optional] {@code Object} * @param CustomDictionary6 [in, optional] {@code Object} * @param CustomDictionary7 [in, optional] {@code Object} * @param CustomDictionary8 [in, optional] {@code Object} * @param CustomDictionary9 [in, optional] {@code Object} * @param CustomDictionary10 [in, optional] {@code Object} */ @ComMethod(name = "CheckSpelling", dispId = 0x144) Boolean CheckSpelling(String Word, Object CustomDictionary, Object IgnoreUppercase, Object MainDictionary, Object CustomDictionary2, Object CustomDictionary3, Object CustomDictionary4, Object CustomDictionary5, Object CustomDictionary6, Object CustomDictionary7, Object CustomDictionary8, Object CustomDictionary9, Object CustomDictionary10); /** * <p>id(0x147)</p> * <p>vtableId(64)</p> * @param Word [in] {@code String} * @param CustomDictionary [in, optional] {@code Object} * @param IgnoreUppercase [in, optional] {@code Object} * @param MainDictionary [in, optional] {@code Object} * @param SuggestionMode [in, optional] {@code Object} * @param CustomDictionary2 [in, optional] {@code Object} * @param CustomDictionary3 [in, optional] {@code Object} * @param CustomDictionary4 [in, optional] {@code Object} * @param CustomDictionary5 [in, optional] {@code Object} * @param CustomDictionary6 [in, optional] {@code Object} * @param CustomDictionary7 [in, optional] {@code Object} * @param CustomDictionary8 [in, optional] {@code Object} * @param CustomDictionary9 [in, optional] {@code Object} * @param CustomDictionary10 [in, optional] {@code Object} */ @ComMethod(name = "GetSpellingSuggestions", dispId = 0x147) SpellingSuggestions GetSpellingSuggestions(String Word, Object CustomDictionary, Object IgnoreUppercase, Object MainDictionary, Object SuggestionMode, Object CustomDictionary2, Object CustomDictionary3, Object CustomDictionary4, Object CustomDictionary5, Object CustomDictionary6, Object CustomDictionary7, Object CustomDictionary8, Object CustomDictionary9, Object CustomDictionary10); /** * <p>id(0x149)</p> * <p>vtableId(65)</p> * @param HelpType [in] {@code Object} */ @ComMethod(name = "Help", dispId = 0x149) void Help(Object HelpType); /** * <p>id(0x159)</p> * <p>vtableId(66)</p> */ @ComMethod(name = "NewWindow", dispId = 0x159) Window NewWindow(); /** * <p>id(0x162)</p> * <p>vtableId(67)</p> * @param String [in] {@code String} */ @ComMethod(name = "CleanString", dispId = 0x162) String CleanString(String String); /** * <p>id(0x163)</p> * <p>vtableId(68)</p> * @param Path [in] {@code String} */ @ComMethod(name = "ChangeFileOpenDirectory", dispId = 0x163) void ChangeFileOpenDirectory(String Path); /** * <p>id(0x172)</p> * <p>vtableId(69)</p> * @param Inches [in] {@code Float} */ @ComMethod(name = "InchesToPoints", dispId = 0x172) Float InchesToPoints(Float Inches); /** * <p>id(0x173)</p> * <p>vtableId(70)</p> * @param Centimeters [in] {@code Float} */ @ComMethod(name = "CentimetersToPoints", dispId = 0x173) Float CentimetersToPoints(Float Centimeters); /** * <p>id(0x174)</p> * <p>vtableId(71)</p> * @param Millimeters [in] {@code Float} */ @ComMethod(name = "MillimetersToPoints", dispId = 0x174) Float MillimetersToPoints(Float Millimeters); /** * <p>id(0x175)</p> * <p>vtableId(72)</p> * @param Picas [in] {@code Float} */ @ComMethod(name = "PicasToPoints", dispId = 0x175) Float PicasToPoints(Float Picas); /** * <p>id(0x176)</p> * <p>vtableId(73)</p> * @param Lines [in] {@code Float} */ @ComMethod(name = "LinesToPoints", dispId = 0x176) Float LinesToPoints(Float Lines); /** * <p>id(0x17c)</p> * <p>vtableId(74)</p> * @param Points [in] {@code Float} */ @ComMethod(name = "PointsToInches", dispId = 0x17c) Float PointsToInches(Float Points); /** * <p>id(0x17d)</p> * <p>vtableId(75)</p> * @param Points [in] {@code Float} */ @ComMethod(name = "PointsToCentimeters", dispId = 0x17d) Float PointsToCentimeters(Float Points); /** * <p>id(0x17e)</p> * <p>vtableId(76)</p> * @param Points [in] {@code Float} */ @ComMethod(name = "PointsToMillimeters", dispId = 0x17e) Float PointsToMillimeters(Float Points); /** * <p>id(0x17f)</p> * <p>vtableId(77)</p> * @param Points [in] {@code Float} */ @ComMethod(name = "PointsToPicas", dispId = 0x17f) Float PointsToPicas(Float Points); /** * <p>id(0x180)</p> * <p>vtableId(78)</p> * @param Points [in] {@code Float} */ @ComMethod(name = "PointsToLines", dispId = 0x180) Float PointsToLines(Float Points); /** * <p>id(0x181)</p> * <p>vtableId(79)</p> * @param Points [in] {@code Float} * @param fVertical [in, optional] {@code Object} */ @ComMethod(name = "PointsToPixels", dispId = 0x181) Float PointsToPixels(Float Points, Object fVertical); /** * <p>id(0x182)</p> * <p>vtableId(80)</p> * @param Pixels [in] {@code Float} * @param fVertical [in, optional] {@code Object} */ @ComMethod(name = "PixelsToPoints", dispId = 0x182) Float PixelsToPoints(Float Pixels, Object fVertical); /** * <p>id(0x6f)</p> * <p>vtableId(81)</p> */ @ComProperty(name = "LanguageSettings", dispId = 0x6f) eu.doppel_helix.jna.tlb.office2.LanguageSettings getLanguageSettings(); /** * <p>id(0x70)</p> * <p>vtableId(82)</p> */ @ComProperty(name = "AnswerWizard", dispId = 0x70) eu.doppel_helix.jna.tlb.office2.AnswerWizard getAnswerWizard(); /** * <p>id(0x71)</p> * <p>vtableId(83)</p> */ @ComProperty(name = "AutoCorrectEmail", dispId = 0x71) AutoCorrect getAutoCorrectEmail(); /** * <p>id(0x72)</p> * <p>vtableId(84)</p> */ @ComProperty(name = "ProtectedViewWindows", dispId = 0x72) ProtectedViewWindows getProtectedViewWindows(); /** * <p>id(0x73)</p> * <p>vtableId(85)</p> */ @ComProperty(name = "ActiveProtectedViewWindow", dispId = 0x73) ProtectedViewWindow getActiveProtectedViewWindow(); /** * <p>id(0x74)</p> * <p>vtableId(86)</p> */ @ComProperty(name = "IsSandboxed", dispId = 0x74) Boolean getIsSandboxed(); }
3e1db4c776375102a48a0190d1a25ef2de332872
318
java
Java
Cicada-Parent/Distributed-Transaction-B/src/main/java/com/mn/b/BSystemApplication.java
mning628/Cicada
8ce9d49f8a97bb3d13126efe8c90c7d35fc63634
[ "MIT" ]
1
2019-08-02T02:45:09.000Z
2019-08-02T02:45:09.000Z
Cicada-Parent/Distributed-Transaction-B/src/main/java/com/mn/b/BSystemApplication.java
mning628/Cicada
8ce9d49f8a97bb3d13126efe8c90c7d35fc63634
[ "MIT" ]
null
null
null
Cicada-Parent/Distributed-Transaction-B/src/main/java/com/mn/b/BSystemApplication.java
mning628/Cicada
8ce9d49f8a97bb3d13126efe8c90c7d35fc63634
[ "MIT" ]
null
null
null
21.2
68
0.77673
12,581
package com.mn.b; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class BSystemApplication { public static void main(String[] args) { SpringApplication.run(BSystemApplication.class, args); } }
3e1db5c59f269dabeda33de9ed18eb583877ac92
2,511
java
Java
api/pacman-api-compliance/src/main/java/com/tmobile/pacman/api/compliance/repository/FAQRepository.java
janitha09/pacbot
045cc1181a416d8cc4c9ca41b9cf43635f875002
[ "Apache-2.0" ]
1,165
2018-10-05T19:07:34.000Z
2022-03-28T19:34:27.000Z
api/pacman-api-compliance/src/main/java/com/tmobile/pacman/api/compliance/repository/FAQRepository.java
janitha09/pacbot
045cc1181a416d8cc4c9ca41b9cf43635f875002
[ "Apache-2.0" ]
334
2018-10-10T14:00:41.000Z
2022-03-19T16:32:08.000Z
api/pacman-api-compliance/src/main/java/com/tmobile/pacman/api/compliance/repository/FAQRepository.java
janitha09/pacbot
045cc1181a416d8cc4c9ca41b9cf43635f875002
[ "Apache-2.0" ]
268
2018-10-05T19:53:25.000Z
2022-03-31T07:39:47.000Z
35.871429
80
0.646356
12,582
/******************************************************************************* * Copyright 2018 T Mobile, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. 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. ******************************************************************************/ /** Copyright (C) 2017 T Mobile Inc - All Rights Reserve Purpose: Author :santoshi Modified Date: Jan 31, 2018 **/ package com.tmobile.pacman.api.compliance.repository; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import com.tmobile.pacman.api.commons.exception.DataException; /** * The Interface FAQRepository. */ @Repository public interface FAQRepository { /** * If method receives widgetId, it gives the * list of map details from the ES.If method * receives widgetId and domainId, it gives the list of map details * from the ES for the given widgetId and domainId. * * @param widgetId the widget id * @param domainId the domain id * @return List<Map<String, Object>> * @throws DataException the data exception */ public List<Map<String, Object>> getFAQSFromEs(String widgetId, String domainId) throws DataException; /** * Gets the relevant FAQS from es.If method receives * widgetId,domainId,tag,faqId,then it gives the list of map faqName * and faqAnswer. * * @param widgetId the widget id * @param domainId the domain id * @param tags the tags * @param faqId the faq id * @param releventfaqsByWidgetIdList the releventfaqs by widget id list * @return List<Map<String, Object>> * @throws DataException the data exception */ public List<Map<String, Object>> getRelevantFAQSFromEs(String widgetId, String domainId, List<String> tags, List<String> faqId, List<Map<String, Object>> releventfaqsByWidgetIdList) throws DataException; }
3e1db6386db4e0bd16c8197a7b6adae47e3fbdd5
776
java
Java
src/main/java/org/oddjob/net/ftp/FTPRmDir.java
robjg/oj-net
8b5124802d080e38c952c2a45196554bc671a185
[ "Apache-2.0" ]
null
null
null
src/main/java/org/oddjob/net/ftp/FTPRmDir.java
robjg/oj-net
8b5124802d080e38c952c2a45196554bc671a185
[ "Apache-2.0" ]
null
null
null
src/main/java/org/oddjob/net/ftp/FTPRmDir.java
robjg/oj-net
8b5124802d080e38c952c2a45196554bc671a185
[ "Apache-2.0" ]
null
null
null
16.510638
67
0.685567
12,583
package org.oddjob.net.ftp; import org.apache.commons.net.ftp.FTPClient; import java.io.IOException; /** * @oddjob.description FTP command to remove a remote directory. * * @author rob * */ public class FTPRmDir implements FTPCommand { /** * @oddjob.property * @oddjob.description The path of the remote directory to remove. * @oddjob.required Yes. */ private String path; @Override public boolean executeWith(FTPClient client) throws IOException { if (path == null) { throw new IllegalStateException("No path"); } return client.removeDirectory(path); } @Override public String toString() { return "rmdir " + path; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } }
3e1db664aa50a64270b30552b2ebd188b7a91c71
2,625
java
Java
designer/src/com/android/tools/idea/uibuilder/handlers/AppBarLayoutHandler.java
Ret-Mode/android
5b427d1fc6a66ff4db09a9e2f02ae61292ccd797
[ "Apache-2.0" ]
831
2016-06-09T06:55:34.000Z
2022-03-30T11:17:10.000Z
designer/src/com/android/tools/idea/uibuilder/handlers/AppBarLayoutHandler.java
Ret-Mode/android
5b427d1fc6a66ff4db09a9e2f02ae61292ccd797
[ "Apache-2.0" ]
19
2017-10-27T00:36:35.000Z
2021-02-04T13:59:45.000Z
designer/src/com/android/tools/idea/uibuilder/handlers/AppBarLayoutHandler.java
Ret-Mode/android
5b427d1fc6a66ff4db09a9e2f02ae61292ccd797
[ "Apache-2.0" ]
210
2016-07-05T12:22:36.000Z
2022-03-19T09:07:15.000Z
37.5
143
0.748571
12,584
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.uibuilder.handlers; import com.android.tools.idea.uibuilder.handlers.linear.LinearLayoutHandler; import com.google.common.collect.ImmutableList; import com.intellij.openapi.application.ApplicationManager; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import com.android.tools.idea.common.api.InsertType; import com.android.tools.idea.uibuilder.api.ViewEditor; import com.android.tools.idea.uibuilder.handlers.ui.AppBarConfigurationDialog; import com.android.tools.idea.common.model.NlComponent; import java.util.Collections; import java.util.List; import static com.android.SdkConstants.*; public class AppBarLayoutHandler extends LinearLayoutHandler { @Override @NotNull public List<String> getInspectorProperties() { return ImmutableList.of( ATTR_THEME, ATTR_FITS_SYSTEM_WINDOWS, ATTR_EXPANDED); } @NotNull @Override public List<String> getLayoutInspectorProperties() { return Collections.singletonList(ATTR_LAYOUT_SCROLL_FLAGS); } @Override public boolean onCreate(@NotNull ViewEditor editor, @Nullable NlComponent parent, @NotNull NlComponent newChild, @NotNull InsertType insertType) { if (insertType == InsertType.CREATE) { // The AppBarConfigurationDialog replaces the root XML node in the current file. AppBarConfigurationDialog dialog = new AppBarConfigurationDialog(editor, APP_BAR_LAYOUT.newName().equals(newChild.getTagName())); ApplicationManager.getApplication().invokeLater(() -> dialog.open()); return false; } return true; } @Override public boolean isVertical(@NotNull NlComponent component) { // AppBarLayout is always vertical and does not support horizontal orientation // https://android.googlesource.com/platform/frameworks/support.git/+/master/design/src/android/support/design/widget/AppBarLayout.java#279 return true; } }
3e1db6adbfe0a4f6406b4386fe50a28f77a8ce73
63,732
java
Java
cascading-platform/src/test/java/cascading/JoinFieldedPipesPlatformTest.java
gerashegalov/cascading
b697e4e45971b4df6be96c5768bec9945cfe4a15
[ "Apache-2.0" ]
null
null
null
cascading-platform/src/test/java/cascading/JoinFieldedPipesPlatformTest.java
gerashegalov/cascading
b697e4e45971b4df6be96c5768bec9945cfe4a15
[ "Apache-2.0" ]
null
null
null
cascading-platform/src/test/java/cascading/JoinFieldedPipesPlatformTest.java
gerashegalov/cascading
b697e4e45971b4df6be96c5768bec9945cfe4a15
[ "Apache-2.0" ]
null
null
null
35.172185
220
0.626844
12,585
/* * Copyright (c) 2007-2014 Concurrent, Inc. All Rights Reserved. * * Project and contact information: http://www.cascading.org/ * * This file is part of the Cascading 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 cascading; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import cascading.flow.Flow; import cascading.flow.FlowDef; import cascading.operation.Aggregator; import cascading.operation.Function; import cascading.operation.Identity; import cascading.operation.aggregator.Count; import cascading.operation.aggregator.First; import cascading.operation.expression.ExpressionFunction; import cascading.operation.regex.RegexFilter; import cascading.operation.regex.RegexSplitter; import cascading.pipe.CoGroup; import cascading.pipe.Each; import cascading.pipe.Every; import cascading.pipe.GroupBy; import cascading.pipe.HashJoin; import cascading.pipe.Merge; import cascading.pipe.Pipe; import cascading.pipe.joiner.InnerJoin; import cascading.pipe.joiner.Joiner; import cascading.pipe.joiner.LeftJoin; import cascading.pipe.joiner.MixedJoin; import cascading.pipe.joiner.OuterJoin; import cascading.pipe.joiner.RightJoin; import cascading.tap.SinkMode; import cascading.tap.Tap; import cascading.tuple.Fields; import cascading.tuple.Hasher; import cascading.tuple.Tuple; import org.junit.Test; import static data.InputData.*; public class JoinFieldedPipesPlatformTest extends PlatformTestCase { public JoinFieldedPipesPlatformTest() { super( true, 4, 1 ); // leave cluster testing enabled } @Test public void testCross() throws Exception { getPlatform().copyFromLocal( inputFileLhs ); getPlatform().copyFromLocal( inputFileRhs ); Map sources = new HashMap(); sources.put( "lhs", getPlatform().getTextFile( inputFileLhs ) ); sources.put( "rhs", getPlatform().getTextFile( inputFileRhs ) ); Tap sink = getPlatform().getTextFile( new Fields( "line" ), getOutputPath( "cross" ), SinkMode.REPLACE ); Pipe pipeLower = new Each( "lhs", new Fields( "line" ), new RegexSplitter( new Fields( "numLHS", "charLHS" ), " " ) ); Pipe pipeUpper = new Each( "rhs", new Fields( "line" ), new RegexSplitter( new Fields( "numRHS", "charRHS" ), " " ) ); Pipe cross = new HashJoin( pipeLower, new Fields( "numLHS" ), pipeUpper, new Fields( "numRHS" ), new InnerJoin() ); Flow flow = getPlatform().getFlowConnector().connect( sources, sink, cross ); flow.complete(); validateLength( flow, 37, null ); List<Tuple> values = getSinkAsList( flow ); assertTrue( values.contains( new Tuple( "1\ta\t1\tA" ) ) ); assertTrue( values.contains( new Tuple( "1\ta\t1\tB" ) ) ); } @Test public void testJoin() throws Exception { getPlatform().copyFromLocal( inputFileLower ); getPlatform().copyFromLocal( inputFileUpper ); Tap sourceLower = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLower ); Tap sourceUpper = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileUpper ); Map sources = new HashMap(); sources.put( "lower", sourceLower ); sources.put( "upper", sourceUpper ); Tap sink = getPlatform().getTextFile( new Fields( "line" ), getOutputPath( "join" ), SinkMode.REPLACE ); Function splitter = new RegexSplitter( new Fields( "num", "char" ), " " ); Pipe pipeLower = new Each( new Pipe( "lower" ), new Fields( "line" ), splitter ); Pipe pipeUpper = new Each( new Pipe( "upper" ), new Fields( "line" ), splitter ); Pipe splice = new HashJoin( pipeLower, new Fields( "num" ), pipeUpper, new Fields( "num" ), Fields.size( 4 ) ); Map<Object, Object> properties = getProperties(); Flow flow = getPlatform().getFlowConnector( properties ).connect( sources, sink, splice ); flow.complete(); validateLength( flow, 5 ); List<Tuple> values = getSinkAsList( flow ); assertTrue( values.contains( new Tuple( "1\ta\t1\tA" ) ) ); assertTrue( values.contains( new Tuple( "2\tb\t2\tB" ) ) ); } @Test public void testJoinSamePipeName() throws Exception { getPlatform().copyFromLocal( inputFileLower ); getPlatform().copyFromLocal( inputFileUpper ); Tap sourceLower = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLower ); Tap sourceUpper = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileUpper ); Map sources = new HashMap(); sources.put( "lower", sourceLower ); sources.put( "upper", sourceUpper ); Tap sink = getPlatform().getTextFile( new Fields( "line" ), getOutputPath( "renamedpipes" ), SinkMode.REPLACE ); Function splitter = new RegexSplitter( new Fields( "num", "char" ), " " ); Pipe pipeLower = new Pipe( "lower" ); Pipe pipeUpper = new Pipe( "upper" ); // these pipes will hide the source name, and could cause one to be lost pipeLower = new Pipe( "same", pipeLower ); pipeUpper = new Pipe( "same", pipeUpper ); pipeLower = new Each( pipeLower, new Fields( "line" ), splitter ); pipeUpper = new Each( pipeUpper, new Fields( "line" ), splitter ); // pipeLower = new Each( pipeLower, new Fields( "num", "char" ), new Identity( new Fields( "num", "char" ) ) ); // pipeUpper = new Each( pipeUpper, new Fields( "num", "char" ), new Identity( new Fields( "num", "char" ) ) ); pipeLower = new Pipe( "left", pipeLower ); pipeUpper = new Pipe( "right", pipeUpper ); // pipeLower = new Each( pipeLower, new Debug( true ) ); // pipeUpper = new Each( pipeUpper, new Debug( true ) ); Pipe splice = new HashJoin( pipeLower, new Fields( "num" ), pipeUpper, new Fields( "num" ), Fields.size( 4 ) ); // splice = new Each( splice, new Debug( true ) ); splice = new Pipe( "splice", splice ); splice = new Pipe( "tail", splice ); Flow flow = getPlatform().getFlowConnector().connect( sources, sink, splice ); flow.complete(); validateLength( flow, 5 ); List<Tuple> values = getSinkAsList( flow ); assertTrue( values.contains( new Tuple( "1\ta\t1\tA" ) ) ); assertTrue( values.contains( new Tuple( "2\tb\t2\tB" ) ) ); } @Test public void testJoinWithUnknowns() throws Exception { getPlatform().copyFromLocal( inputFileLower ); getPlatform().copyFromLocal( inputFileUpper ); Tap sourceLower = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLower ); Tap sourceUpper = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileUpper ); Map sources = new HashMap(); sources.put( "lower", sourceLower ); sources.put( "upper", sourceUpper ); Tap sink = getPlatform().getTextFile( new Fields( "line" ), getOutputPath( "unknown" ), SinkMode.REPLACE ); Function splitter = new RegexSplitter( Fields.UNKNOWN, " " ); Pipe pipeLower = new Each( new Pipe( "lower" ), new Fields( "line" ), splitter ); Pipe pipeUpper = new Each( new Pipe( "upper" ), new Fields( "line" ), splitter ); Pipe splice = new HashJoin( pipeLower, new Fields( 0 ), pipeUpper, new Fields( 0 ), Fields.size( 4 ) ); Flow flow = getPlatform().getFlowConnector().connect( sources, sink, splice ); flow.complete(); validateLength( flow, 5 ); List<Tuple> values = getSinkAsList( flow ); assertTrue( values.contains( new Tuple( "1\ta\t1\tA" ) ) ); assertTrue( values.contains( new Tuple( "2\tb\t2\tB" ) ) ); } /** * this test intentionally filters out all values so the intermediate tap is empty. this tap is cogrouped with * a new stream using an outerjoin. * * @throws Exception */ @Test public void testJoinFilteredBranch() throws Exception { getPlatform().copyFromLocal( inputFileLower ); getPlatform().copyFromLocal( inputFileUpper ); Tap sourceLower = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLower ); Tap sourceUpper = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileUpper ); Map sources = new HashMap(); sources.put( "lower", sourceLower ); sources.put( "upper", sourceUpper ); Tap sink = getPlatform().getTextFile( new Fields( "line" ), getOutputPath( "joinfilteredbranch" ), SinkMode.REPLACE ); Function splitter = new RegexSplitter( new Fields( "num", "char" ), " " ); Pipe pipeLower = new Each( new Pipe( "lower" ), new Fields( "line" ), splitter ); Pipe pipeUpper = new Each( new Pipe( "upper" ), new Fields( "line" ), splitter ); pipeUpper = new Each( pipeUpper, new Fields( "num" ), new RegexFilter( "^fobar" ) ); // intentionally filtering all pipeUpper = new GroupBy( pipeUpper, new Fields( "num" ) ); Pipe splice = new HashJoin( pipeLower, new Fields( "num" ), pipeUpper, new Fields( "num" ), Fields.size( 4 ), new OuterJoin() ); Flow flow = getPlatform().getFlowConnector().connect( sources, sink, splice ); flow.complete(); validateLength( flow, 5 ); List<Tuple> values = getSinkAsList( flow ); assertTrue( values.contains( new Tuple( "1\ta\tnull\tnull" ) ) ); assertTrue( values.contains( new Tuple( "2\tb\tnull\tnull" ) ) ); } @Test public void testJoinSelf() throws Exception { getPlatform().copyFromLocal( inputFileLower ); Tap sourceLower = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLower ); Tap sourceUpper = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLower ); Map sources = new HashMap(); sources.put( "lower", sourceLower ); sources.put( "upper", sourceUpper ); Tap sink = getPlatform().getTextFile( new Fields( "line" ), getOutputPath( "joinself" ), SinkMode.REPLACE ); Function splitter = new RegexSplitter( new Fields( "num", "char" ), " " ); Pipe pipeLower = new Each( new Pipe( "lower" ), new Fields( "line" ), splitter ); Pipe pipeUpper = new Each( new Pipe( "upper" ), new Fields( "line" ), splitter ); Pipe splice = new HashJoin( pipeLower, new Fields( "num" ), pipeUpper, new Fields( "num" ), Fields.size( 4 ) ); Flow flow = getPlatform().getFlowConnector().connect( sources, sink, splice ); flow.complete(); validateLength( flow, 5 ); List<Tuple> values = getSinkAsList( flow ); assertTrue( values.contains( new Tuple( "1\ta\t1\ta" ) ) ); assertTrue( values.contains( new Tuple( "2\tb\t2\tb" ) ) ); } /** * Method testCoGroupAfterEvery tests that a tmp tap is inserted after the Every in the cogroup join * * @throws Exception when */ @Test public void testJoinAfterEvery() throws Exception { getPlatform().copyFromLocal( inputFileLower ); getPlatform().copyFromLocal( inputFileUpper ); Tap sourceLower = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLower ); Tap sourceUpper = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileUpper ); Map sources = new HashMap(); sources.put( "lower", sourceLower ); sources.put( "upper", sourceUpper ); Tap sink = getPlatform().getTextFile( new Fields( "line" ), getOutputPath( "afterevery" ), SinkMode.REPLACE ); Function splitter = new RegexSplitter( new Fields( "num", "char" ), " " ); Pipe pipeLower = new Each( new Pipe( "lower" ), new Fields( "line" ), splitter ); pipeLower = new GroupBy( pipeLower, new Fields( "num" ) ); pipeLower = new Every( pipeLower, new Fields( "char" ), new First(), Fields.ALL ); Pipe pipeUpper = new Each( new Pipe( "upper" ), new Fields( "line" ), splitter ); pipeUpper = new GroupBy( pipeUpper, new Fields( "num" ) ); pipeUpper = new Every( pipeUpper, new Fields( "char" ), new First(), Fields.ALL ); Pipe splice = new HashJoin( pipeLower, new Fields( "num" ), pipeUpper, new Fields( "num" ), Fields.size( 4 ) ); Flow flow = getPlatform().getFlowConnector().connect( sources, sink, splice ); flow.complete(); validateLength( flow, 5, null ); List<Tuple> values = getSinkAsList( flow ); assertTrue( values.contains( new Tuple( "1\ta\t1\tA" ) ) ); assertTrue( values.contains( new Tuple( "2\tb\t2\tB" ) ) ); } @Test public void testJoinInnerSingleField() throws Exception { getPlatform().copyFromLocal( inputFileLowerOffset ); getPlatform().copyFromLocal( inputFileUpper ); Tap sourceLower = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLowerOffset ); Tap sourceUpper = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileUpper ); Map sources = new HashMap(); sources.put( "lower", sourceLower ); sources.put( "upper", sourceUpper ); Tap sink = getPlatform().getTextFile( new Fields( "line" ), getOutputPath( "joininnersingle" ), SinkMode.REPLACE ); Pipe pipeLower = new Each( new Pipe( "lower" ), new Fields( "line" ), new RegexSplitter( new Fields( "num1", "char" ), " " ), new Fields( "num1" ) ); Pipe pipeUpper = new Each( new Pipe( "upper" ), new Fields( "line" ), new RegexSplitter( new Fields( "num2", "char" ), " " ), new Fields( "num2" ) ); Pipe join = new HashJoin( pipeLower, new Fields( "num1" ), pipeUpper, new Fields( "num2" ) ); Flow flow = getPlatform().getFlowConnector().connect( sources, sink, join ); flow.complete(); validateLength( flow, 3, null ); Set<Tuple> results = new HashSet<Tuple>(); results.add( new Tuple( "1\t1" ) ); results.add( new Tuple( "5\t5" ) ); List<Tuple> actual = getSinkAsList( flow ); results.removeAll( actual ); assertEquals( 0, results.size() ); } /** * 1 a1 * 1 a2 * 1 a3 * 2 b1 * 3 c1 * 4 d1 * 4 d2 * 4 d3 * 5 e1 * 5 e2 * 5 e3 * 7 g1 * 7 g2 * 7 g3 * 7 g4 * 7 g5 * null h1 * <p/> * 1 A1 * 1 A2 * 1 A3 * 2 B1 * 2 B2 * 2 B3 * 4 D1 * 6 F1 * 6 F2 * null H1 * <p/> * 1 a1 1 A1 * 1 a1 1 A2 * 1 a1 1 A3 * 1 a2 1 A1 * 1 a2 1 A2 * 1 a2 1 A3 * 1 a3 1 A1 * 1 a3 1 A2 * 1 a3 1 A3 * 2 b1 2 B1 * 2 b1 2 B2 * 2 b1 2 B3 * 4 d1 4 D1 * 4 d2 4 D1 * 4 d3 4 D1 * null h1 null H1 * * @throws Exception */ @Test public void testJoinInner() throws Exception { HashSet<Tuple> results = new HashSet<Tuple>(); results.add( new Tuple( "1", "a1", "1", "A1" ) ); results.add( new Tuple( "1", "a1", "1", "A2" ) ); results.add( new Tuple( "1", "a1", "1", "A3" ) ); results.add( new Tuple( "1", "a2", "1", "A1" ) ); results.add( new Tuple( "1", "a2", "1", "A2" ) ); results.add( new Tuple( "1", "a2", "1", "A3" ) ); results.add( new Tuple( "1", "a3", "1", "A1" ) ); results.add( new Tuple( "1", "a3", "1", "A2" ) ); results.add( new Tuple( "1", "a3", "1", "A3" ) ); results.add( new Tuple( "2", "b1", "2", "B1" ) ); results.add( new Tuple( "2", "b1", "2", "B2" ) ); results.add( new Tuple( "2", "b1", "2", "B3" ) ); results.add( new Tuple( "4", "d1", "4", "D1" ) ); results.add( new Tuple( "4", "d2", "4", "D1" ) ); results.add( new Tuple( "4", "d3", "4", "D1" ) ); results.add( new Tuple( null, "h1", null, "H1" ) ); handleJoins( "joininner", new InnerJoin(), results ); } /** * /** * 1 a1 * 1 a2 * 1 a3 * 2 b1 * 3 c1 * 4 d1 * 4 d2 * 4 d3 * 5 e1 * 5 e2 * 5 e3 * 7 g1 * 7 g2 * 7 g3 * 7 g4 * 7 g5 * null h1 * <p/> * 1 A1 * 1 A2 * 1 A3 * 2 B1 * 2 B2 * 2 B3 * 4 D1 * 6 F1 * 6 F2 * null H1 * <p/> * 1 a1 1 A1 * 1 a1 1 A2 * 1 a1 1 A3 * 1 a2 1 A1 * 1 a2 1 A2 * 1 a2 1 A3 * 1 a3 1 A1 * 1 a3 1 A2 * 1 a3 1 A3 * 2 b1 2 B1 * 2 b1 2 B2 * 2 b1 2 B3 * 3 c1 null null * 4 d1 4 D1 * 4 d2 4 D1 * 4 d3 4 D1 * 5 e1 null null * 5 e2 null null * 5 e3 null null * null null 6 F1 * null null 6 F2 * 7 g1 null null * 7 g2 null null * 7 g3 null null * 7 g4 null null * 7 g5 null null * null h1 null H1 * * @throws Exception */ @Test public void testJoinOuter() throws Exception { // skip if hadoop cluster mode, outer joins don't behave the same if( getPlatform().isMapReduce() && getPlatform().isUseCluster() ) return; Set<Tuple> results = new HashSet<Tuple>(); results.add( new Tuple( "1", "a1", "1", "A1" ) ); results.add( new Tuple( "1", "a1", "1", "A2" ) ); results.add( new Tuple( "1", "a1", "1", "A3" ) ); results.add( new Tuple( "1", "a2", "1", "A1" ) ); results.add( new Tuple( "1", "a2", "1", "A2" ) ); results.add( new Tuple( "1", "a2", "1", "A3" ) ); results.add( new Tuple( "1", "a3", "1", "A1" ) ); results.add( new Tuple( "1", "a3", "1", "A2" ) ); results.add( new Tuple( "1", "a3", "1", "A3" ) ); results.add( new Tuple( "2", "b1", "2", "B1" ) ); results.add( new Tuple( "2", "b1", "2", "B2" ) ); results.add( new Tuple( "2", "b1", "2", "B3" ) ); results.add( new Tuple( "3", "c1", null, null ) ); results.add( new Tuple( "4", "d1", "4", "D1" ) ); results.add( new Tuple( "4", "d2", "4", "D1" ) ); results.add( new Tuple( "4", "d3", "4", "D1" ) ); results.add( new Tuple( "5", "e1", null, null ) ); results.add( new Tuple( "5", "e2", null, null ) ); results.add( new Tuple( "5", "e3", null, null ) ); results.add( new Tuple( null, null, "6", "F1" ) ); results.add( new Tuple( null, null, "6", "F2" ) ); results.add( new Tuple( "7", "g1", null, null ) ); results.add( new Tuple( "7", "g2", null, null ) ); results.add( new Tuple( "7", "g3", null, null ) ); results.add( new Tuple( "7", "g4", null, null ) ); results.add( new Tuple( "7", "g5", null, null ) ); results.add( new Tuple( null, "h1", null, "H1" ) ); handleJoins( "joinouter", new OuterJoin(), results ); } /** * 1 a1 * 1 a2 * 1 a3 * 2 b1 * 3 c1 * 4 d1 * 4 d2 * 4 d3 * 5 e1 * 5 e2 * 5 e3 * 7 g1 * 7 g2 * 7 g3 * 7 g4 * 7 g5 * null h1 * <p/> * 1 A1 * 1 A2 * 1 A3 * 2 B1 * 2 B2 * 2 B3 * 4 D1 * 6 F1 * 6 F2 * null H1 * <p/> * 1 a1 1 A1 * 1 a1 1 A2 * 1 a1 1 A3 * 1 a2 1 A1 * 1 a2 1 A2 * 1 a2 1 A3 * 1 a3 1 A1 * 1 a3 1 A2 * 1 a3 1 A3 * 2 b1 2 B1 * 2 b1 2 B2 * 2 b1 2 B3 * 3 c1 null null * 4 d1 4 D1 * 4 d2 4 D1 * 4 d3 4 D1 * 5 e1 null null * 5 e2 null null * 5 e3 null null * 7 g1 null null * 7 g2 null null * 7 g3 null null * 7 g4 null null * 7 g5 null null * null h1 null H1 * * @throws Exception */ @Test public void testJoinInnerOuter() throws Exception { Set<Tuple> results = new HashSet<Tuple>(); results.add( new Tuple( "1", "a1", "1", "A1" ) ); results.add( new Tuple( "1", "a1", "1", "A2" ) ); results.add( new Tuple( "1", "a1", "1", "A3" ) ); results.add( new Tuple( "1", "a2", "1", "A1" ) ); results.add( new Tuple( "1", "a2", "1", "A2" ) ); results.add( new Tuple( "1", "a2", "1", "A3" ) ); results.add( new Tuple( "1", "a3", "1", "A1" ) ); results.add( new Tuple( "1", "a3", "1", "A2" ) ); results.add( new Tuple( "1", "a3", "1", "A3" ) ); results.add( new Tuple( "2", "b1", "2", "B1" ) ); results.add( new Tuple( "2", "b1", "2", "B2" ) ); results.add( new Tuple( "2", "b1", "2", "B3" ) ); results.add( new Tuple( "3", "c1", null, null ) ); results.add( new Tuple( "4", "d1", "4", "D1" ) ); results.add( new Tuple( "4", "d2", "4", "D1" ) ); results.add( new Tuple( "4", "d3", "4", "D1" ) ); results.add( new Tuple( "5", "e1", null, null ) ); results.add( new Tuple( "5", "e2", null, null ) ); results.add( new Tuple( "5", "e3", null, null ) ); results.add( new Tuple( "7", "g1", null, null ) ); results.add( new Tuple( "7", "g2", null, null ) ); results.add( new Tuple( "7", "g3", null, null ) ); results.add( new Tuple( "7", "g4", null, null ) ); results.add( new Tuple( "7", "g5", null, null ) ); results.add( new Tuple( null, "h1", null, "H1" ) ); handleJoins( "joininnerouter", new LeftJoin(), results ); } /** * 1 a1 * 1 a2 * 1 a3 * 2 b1 * 3 c1 * 4 d1 * 4 d2 * 4 d3 * 5 e1 * 5 e2 * 5 e3 * 7 g1 * 7 g2 * 7 g3 * 7 g4 * 7 g5 * null h1 * <p/> * 1 A1 * 1 A2 * 1 A3 * 2 B1 * 2 B2 * 2 B3 * 4 D1 * 6 F1 * 6 F2 * null H1 * <p/> * 1 a1 1 A1 * 1 a1 1 A2 * 1 a1 1 A3 * 1 a2 1 A1 * 1 a2 1 A2 * 1 a2 1 A3 * 1 a3 1 A1 * 1 a3 1 A2 * 1 a3 1 A3 * 2 b1 2 B1 * 2 b1 2 B2 * 2 b1 2 B3 * 4 d1 4 D1 * 4 d2 4 D1 * 4 d3 4 D1 * null null 6 F1 * null null 6 F2 * null h1 null H1 * * @throws Exception */ @Test public void testJoinOuterInner() throws Exception { // skip if hadoop cluster mode, outer joins don't behave the same if( getPlatform().isMapReduce() && getPlatform().isUseCluster() ) return; Set<Tuple> results = new HashSet<Tuple>(); results.add( new Tuple( "1", "a1", "1", "A1" ) ); results.add( new Tuple( "1", "a1", "1", "A2" ) ); results.add( new Tuple( "1", "a1", "1", "A3" ) ); results.add( new Tuple( "1", "a2", "1", "A1" ) ); results.add( new Tuple( "1", "a2", "1", "A2" ) ); results.add( new Tuple( "1", "a2", "1", "A3" ) ); results.add( new Tuple( "1", "a3", "1", "A1" ) ); results.add( new Tuple( "1", "a3", "1", "A2" ) ); results.add( new Tuple( "1", "a3", "1", "A3" ) ); results.add( new Tuple( "2", "b1", "2", "B1" ) ); results.add( new Tuple( "2", "b1", "2", "B2" ) ); results.add( new Tuple( "2", "b1", "2", "B3" ) ); results.add( new Tuple( "4", "d1", "4", "D1" ) ); results.add( new Tuple( "4", "d2", "4", "D1" ) ); results.add( new Tuple( "4", "d3", "4", "D1" ) ); results.add( new Tuple( null, null, "6", "F1" ) ); results.add( new Tuple( null, null, "6", "F2" ) ); results.add( new Tuple( null, "h1", null, "H1" ) ); handleJoins( "joinouterinner", new RightJoin(), results ); } private void handleJoins( String path, Joiner joiner, Set<Tuple> results ) throws Exception { getPlatform().copyFromLocal( inputFileLhsSparse ); getPlatform().copyFromLocal( inputFileRhsSparse ); Fields fields = new Fields( "num", "char" ).applyTypes( Integer.class, String.class ); Tap sourceLower = getPlatform().getDelimitedFile( fields, " ", inputFileLhsSparse ); Tap sourceUpper = getPlatform().getDelimitedFile( fields, " ", inputFileRhsSparse ); Map sources = new HashMap(); sources.put( "lower", sourceLower ); sources.put( "upper", sourceUpper ); Tap sink = getPlatform().getDelimitedFile( Fields.size( 4, String.class ), "\t", getOutputPath( path ), SinkMode.REPLACE ); Pipe pipeLower = new Pipe( "lower" ); Pipe pipeUpper = new Pipe( "upper" ); Fields declaredFields = new Fields( "num", "char", "num2", "char2" ); Fields groupingFields = new Fields( "num" ); Pipe splice = new HashJoin( pipeLower, groupingFields, pipeUpper, groupingFields, declaredFields, joiner ); splice = new Each( splice, Fields.ALL, new Identity(), Fields.RESULTS ); Flow flow = getPlatform().getFlowConnector().connect( sources, sink, splice ); flow.complete(); validateLength( flow, results.size() ); List<Tuple> actual = getSinkAsList( flow ); results.removeAll( actual ); assertEquals( 0, results.size() ); } /** * 1 a * 5 b * 6 c * 5 b * 5 e * <p/> * 1 A * 2 B * 3 C * 4 D * 5 E * <p/> * 1 a * 2 b * 3 c * 4 d * 5 e * <p/> * 1 a 1 A 1 a * - - 2 B 2 b * - - 3 C 3 c * - - 4 D 4 d * 5 b 5 E 5 e * 5 e 5 E 5 e * * @throws Exception */ @Test public void testJoinMixed() throws Exception { // skip if hadoop cluster mode, outer joins don't behave the same if( getPlatform().isMapReduce() && getPlatform().isUseCluster() ) return; getPlatform().copyFromLocal( inputFileLowerOffset ); getPlatform().copyFromLocal( inputFileLower ); getPlatform().copyFromLocal( inputFileUpper ); Tap sourceLowerOffset = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLowerOffset ); Tap sourceUpper = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileUpper ); Tap sourceLower = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLower ); Map sources = new HashMap(); sources.put( "loweroffset", sourceLowerOffset ); sources.put( "lower", sourceLower ); sources.put( "upper", sourceUpper ); Tap sink = getPlatform().getTextFile( new Fields( "line" ), getOutputPath( "joinmixed" ), SinkMode.REPLACE ); Function splitter = new RegexSplitter( new Fields( "num", "char" ), " " ); Pipe pipeLowerOffset = new Each( new Pipe( "loweroffset" ), new Fields( "line" ), splitter ); Pipe pipeLower = new Each( new Pipe( "lower" ), new Fields( "line" ), splitter ); Pipe pipeUpper = new Each( new Pipe( "upper" ), new Fields( "line" ), splitter ); Pipe[] pipes = Pipe.pipes( pipeLowerOffset, pipeUpper, pipeLower ); Fields[] fields = Fields.fields( new Fields( "num" ), new Fields( "num" ), new Fields( "num" ) ); MixedJoin join = new MixedJoin( new boolean[]{MixedJoin.OUTER, MixedJoin.INNER, MixedJoin.OUTER} ); Pipe splice = new HashJoin( pipes, fields, Fields.size( 6 ), join ); Flow flow = getPlatform().getFlowConnector().connect( sources, sink, splice ); flow.complete(); validateLength( flow, 6 ); Set<Tuple> results = new HashSet<Tuple>(); results.add( new Tuple( "1\ta\t1\tA\t1\ta" ) ); results.add( new Tuple( "null\tnull\t2\tB\t2\tb" ) ); results.add( new Tuple( "null\tnull\t3\tC\t3\tc" ) ); results.add( new Tuple( "null\tnull\t4\tD\t4\td" ) ); results.add( new Tuple( "5\tb\t5\tE\t5\te" ) ); results.add( new Tuple( "5\te\t5\tE\t5\te" ) ); List<Tuple> actual = getSinkAsList( flow ); results.removeAll( actual ); assertEquals( 0, results.size() ); } @Test public void testJoinDiffFields() throws Exception { getPlatform().copyFromLocal( inputFileLower ); getPlatform().copyFromLocal( inputFileUpper ); Tap sourceLower = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLower ); Tap sourceUpper = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileUpper ); Map sources = new HashMap(); sources.put( "lower", sourceLower ); sources.put( "upper", sourceUpper ); Tap sink = getPlatform().getTextFile( new Fields( "line" ), getOutputPath( "difffields" ), SinkMode.REPLACE ); Function splitterLower = new RegexSplitter( new Fields( "numA", "lower" ), " " ); Function splitterUpper = new RegexSplitter( new Fields( "numB", "upper" ), " " ); Pipe pipeLower = new Each( new Pipe( "lower" ), new Fields( "line" ), splitterLower ); Pipe pipeUpper = new Each( new Pipe( "upper" ), new Fields( "line" ), splitterUpper ); Pipe pipe = new HashJoin( pipeLower, new Fields( "numA" ), pipeUpper, new Fields( "numB" ) ); Flow flow = getPlatform().getFlowConnector().connect( sources, sink, pipe ); flow.complete(); validateLength( flow, 5 ); List<Tuple> actual = getSinkAsList( flow ); assertTrue( actual.contains( new Tuple( "1\ta\t1\tA" ) ) ); assertTrue( actual.contains( new Tuple( "2\tb\t2\tB" ) ) ); } @Test public void testJoinGroupBy() throws Exception { getPlatform().copyFromLocal( inputFileLower ); getPlatform().copyFromLocal( inputFileUpper ); Tap sourceLower = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLower ); Tap sourceUpper = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileUpper ); Map sources = new HashMap(); sources.put( "lower", sourceLower ); sources.put( "upper", sourceUpper ); Tap sink = getPlatform().getTextFile( new Fields( "line" ), getOutputPath( "joingroupby" ), SinkMode.REPLACE ); Function splitterLower = new RegexSplitter( new Fields( "numA", "lower" ), " " ); Function splitterUpper = new RegexSplitter( new Fields( "numB", "upper" ), " " ); Pipe pipeLower = new Each( new Pipe( "lower" ), new Fields( "line" ), splitterLower ); Pipe pipeUpper = new Each( new Pipe( "upper" ), new Fields( "line" ), splitterUpper ); Pipe pipe = new HashJoin( pipeLower, new Fields( "numA" ), pipeUpper, new Fields( "numB" ) ); Pipe groupby = new GroupBy( pipe, new Fields( "numA" ) ); Flow flow = getPlatform().getFlowConnector().connect( sources, sink, groupby ); flow.complete(); validateLength( flow, 5, null ); List<Tuple> actual = getSinkAsList( flow ); assertTrue( actual.contains( new Tuple( "1\ta\t1\tA" ) ) ); assertTrue( actual.contains( new Tuple( "2\tb\t2\tB" ) ) ); } @Test public void testJoinSamePipe() throws Exception { getPlatform().copyFromLocal( inputFileLower ); Tap source = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLower ); Map sources = new HashMap(); sources.put( "lower", source ); Tap sink = getPlatform().getTextFile( new Fields( "line" ), getOutputPath( "samepipe" ), SinkMode.REPLACE ); Function splitter = new RegexSplitter( new Fields( "num", "char" ), " " ); Pipe pipeLower = new Each( new Pipe( "lower" ), new Fields( "line" ), splitter ); Pipe pipe = new HashJoin( pipeLower, new Fields( "num" ), 1, new Fields( "num1", "char1", "num2", "char2" ) ); Flow flow = getPlatform().getFlowConnector().connect( sources, sink, pipe ); flow.complete(); validateLength( flow, 5, null ); List<Tuple> actual = getSinkAsList( flow ); assertTrue( actual.contains( new Tuple( "1\ta\t1\ta" ) ) ); assertTrue( actual.contains( new Tuple( "2\tb\t2\tb" ) ) ); } @Test public void testJoinSamePipe2() throws Exception { getPlatform().copyFromLocal( inputFileLower ); Tap source = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLower ); Map sources = new HashMap(); sources.put( "lower", source ); Tap sink = getPlatform().getTextFile( new Fields( "line" ), getOutputPath( "samepipe2" ), SinkMode.REPLACE ); Function splitter = new RegexSplitter( new Fields( "num", "char" ), " " ); Pipe pipeLower = new Each( new Pipe( "lower" ), new Fields( "line" ), splitter ); Pipe join = new HashJoin( pipeLower, new Fields( "num" ), pipeLower, new Fields( "num" ), new Fields( "num1", "char1", "num2", "char2" ) ); Flow flow = getPlatform().getFlowConnector().connect( sources, sink, join ); flow.complete(); validateLength( flow, 5, null ); List<Tuple> actual = getSinkAsList( flow ); assertTrue( actual.contains( new Tuple( "1\ta\t1\ta" ) ) ); assertTrue( actual.contains( new Tuple( "2\tb\t2\tb" ) ) ); } @Test public void testJoinSamePipe3() throws Exception { getPlatform().copyFromLocal( inputFileLower ); Tap source = getPlatform().getDelimitedFile( new Fields( "num", "char" ), " ", inputFileLower ); Map sources = new HashMap(); sources.put( "lower", source ); Tap sink = getPlatform().getTextFile( new Fields( "line" ), getOutputPath( "samepipe3" ), SinkMode.REPLACE ); Pipe pipe = new Pipe( "lower" ); Pipe lhs = new Pipe( "lhs", pipe ); Pipe rhs = new Pipe( "rhs", pipe ); Pipe join = new HashJoin( lhs, new Fields( "num" ), rhs, new Fields( "num" ), new Fields( "num1", "char1", "num2", "char2" ) ); Flow flow = getPlatform().getFlowConnector().connect( sources, sink, join ); flow.complete(); validateLength( flow, 5, null ); List<Tuple> actual = getSinkAsList( flow ); assertTrue( actual.contains( new Tuple( "1\ta\t1\ta" ) ) ); assertTrue( actual.contains( new Tuple( "2\tb\t2\tb" ) ) ); } /** * Same source as rightmost * <p/> * should be a single job as the same file accumulates into the joins * * @throws Exception */ @Test public void testJoinAroundJoinRightMost() throws Exception { getPlatform().copyFromLocal( inputFileLower ); getPlatform().copyFromLocal( inputFileUpper ); Tap sourceLower = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLower ); Tap sourceUpper = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileUpper ); Map sources = new HashMap(); sources.put( "lower", sourceLower ); sources.put( "upper1", sourceUpper ); sources.put( "upper2", sourceUpper ); Tap sink = getPlatform().getTextFile( new Fields( "line" ), getOutputPath( "joinaroundjoinrightmost" ), SinkMode.REPLACE ); Function splitter = new RegexSplitter( new Fields( "num", "char" ), " " ); Pipe pipeLower = new Each( new Pipe( "lower" ), new Fields( "line" ), splitter ); Pipe pipeUpper1 = new Each( new Pipe( "upper1" ), new Fields( "line" ), splitter ); Pipe pipeUpper2 = new Each( new Pipe( "upper2" ), new Fields( "line" ), splitter ); Pipe splice1 = new HashJoin( pipeLower, new Fields( "num" ), pipeUpper1, new Fields( "num" ), new Fields( "num1", "char1", "num2", "char2" ) ); splice1 = new Each( splice1, new Identity() ); Pipe splice2 = new HashJoin( splice1, new Fields( "num1" ), pipeUpper2, new Fields( "num" ), new Fields( "num1", "char1", "num2", "char2", "num3", "char3" ) ); Flow flow = getPlatform().getFlowConnector().connect( sources, sink, splice2 ); // flow.writeDOT( "joinaroundrightmost.dot" ); if( getPlatform().isMapReduce() ) assertEquals( "wrong number of steps", 1, flow.getFlowSteps().size() ); flow.complete(); validateLength( flow, 5, null ); List<Tuple> actual = getSinkAsList( flow ); assertTrue( actual.contains( new Tuple( "1\ta\t1\tA\t1\tA" ) ) ); assertTrue( actual.contains( new Tuple( "2\tb\t2\tB\t2\tB" ) ) ); } /** * Same source as leftmost * * @throws Exception */ @Test public void testJoinAroundJoinLeftMost() throws Exception { getPlatform().copyFromLocal( inputFileLower ); getPlatform().copyFromLocal( inputFileUpper ); Tap sourceLower = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLower ); Tap sourceUpper = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileUpper ); Map sources = new HashMap(); sources.put( "lower", sourceLower ); sources.put( "upper1", sourceUpper ); sources.put( "upper2", sourceUpper ); Tap sink = getPlatform().getTextFile( new Fields( "line" ), getOutputPath( "joinaroundjoinleftmost" ), SinkMode.REPLACE ); Function splitter = new RegexSplitter( new Fields( "num", "char" ), " " ); Pipe pipeLower = new Each( new Pipe( "lower" ), new Fields( "line" ), splitter ); Pipe pipeUpper1 = new Each( new Pipe( "upper1" ), new Fields( "line" ), splitter ); Pipe pipeUpper2 = new Each( new Pipe( "upper2" ), new Fields( "line" ), splitter ); Pipe splice1 = new HashJoin( pipeUpper1, new Fields( "num" ), pipeUpper2, new Fields( "num" ), new Fields( "num1", "char1", "num2", "char2" ) ); splice1 = new Each( splice1, new Identity() ); Pipe splice2 = new HashJoin( splice1, new Fields( "num1" ), pipeLower, new Fields( "num" ), new Fields( "num1", "char1", "num2", "char2", "num3", "char3" ) ); Flow flow = getPlatform().getFlowConnector().connect( sources, sink, splice2 ); // flow.writeDOT( "joinaroundleftmost.dot" ); if( getPlatform().isMapReduce() ) assertEquals( "wrong number of steps", 2, flow.getFlowSteps().size() ); flow.complete(); validateLength( flow, 5, null ); List<Tuple> actual = getSinkAsList( flow ); assertTrue( actual.contains( new Tuple( "1\tA\t1\tA\t1\ta" ) ) ); assertTrue( actual.contains( new Tuple( "2\tB\t2\tB\t2\tb" ) ) ); } /** * Upper as leftmost and rightmost forcing two jobs * * @throws Exception */ @Test public void testJoinAroundJoinRightMostSwapped() throws Exception { getPlatform().copyFromLocal( inputFileLower ); getPlatform().copyFromLocal( inputFileUpper ); Tap sourceLower = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLower ); Tap sourceUpper = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileUpper ); Map sources = new HashMap(); sources.put( "lower", sourceLower ); sources.put( "upper1", sourceUpper ); sources.put( "upper2", sourceUpper ); Tap sink = getPlatform().getTextFile( new Fields( "line" ), getOutputPath( "joinaroundjoinswapped" ), SinkMode.REPLACE ); Function splitter = new RegexSplitter( new Fields( "num", "char" ), " " ); Pipe pipeLower = new Each( new Pipe( "lower" ), new Fields( "line" ), splitter ); Pipe pipeUpper1 = new Each( new Pipe( "upper1" ), new Fields( "line" ), splitter ); Pipe pipeUpper2 = new Each( new Pipe( "upper2" ), new Fields( "line" ), splitter ); Pipe splice1 = new HashJoin( pipeLower, new Fields( "num" ), pipeUpper1, new Fields( "num" ), new Fields( "num1", "char1", "num2", "char2" ) ); splice1 = new Each( splice1, new Identity() ); // upper2 becomes leftmost, forcing a tap between the joins Pipe splice2 = new HashJoin( pipeUpper2, new Fields( "num" ), splice1, new Fields( "num1" ), new Fields( "num1", "char1", "num2", "char2", "num3", "char3" ) ); Flow flow = getPlatform().getFlowConnector().connect( sources, sink, splice2 ); if( getPlatform().isMapReduce() ) assertEquals( "wrong number of steps", 2, flow.getFlowSteps().size() ); flow.complete(); validateLength( flow, 5, null ); List<Tuple> actual = getSinkAsList( flow ); assertTrue( actual.contains( new Tuple( "1\tA\t1\ta\t1\tA" ) ) ); assertTrue( actual.contains( new Tuple( "2\tB\t2\tb\t2\tB" ) ) ); } @Test public void testJoinGroupByJoin() throws Exception { getPlatform().copyFromLocal( inputFileLower ); getPlatform().copyFromLocal( inputFileUpper ); getPlatform().copyFromLocal( inputFileJoined ); Tap sourceLower = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLower ); Tap sourceUpper = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileUpper ); Tap sourceJoined = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileJoined ); Map sources = new HashMap(); sources.put( "lower", sourceLower ); sources.put( "upper", sourceUpper ); sources.put( "joined", sourceJoined ); Tap sink = getPlatform().getTextFile( new Fields( "line" ), getOutputPath( "joingroupbyjoin" ), SinkMode.REPLACE ); Function splitterLower = new RegexSplitter( new Fields( "numA", "lower" ), " " ); Function splitterUpper = new RegexSplitter( new Fields( "numB", "upper" ), " " ); Function splitterJoined = new RegexSplitter( new Fields( "numC", "lowerC", "upperC" ), "\t" ); Pipe pipeLower = new Each( new Pipe( "lower" ), new Fields( "line" ), splitterLower ); Pipe pipeUpper = new Each( new Pipe( "upper" ), new Fields( "line" ), splitterUpper ); Pipe pipeJoined = new Each( new Pipe( "joined" ), new Fields( "line" ), splitterJoined ); Pipe pipe = new HashJoin( pipeLower, new Fields( "numA" ), pipeUpper, new Fields( "numB" ) ); pipe = new GroupBy( pipe, new Fields( "numA" ) ); pipe = new HashJoin( pipe, new Fields( "numA" ), pipeJoined, new Fields( "numC" ) ); Flow flow = getPlatform().getFlowConnector().connect( sources, sink, pipe ); if( getPlatform().isMapReduce() ) assertEquals( "wrong number of steps", 2, flow.getFlowSteps().size() ); flow.complete(); validateLength( flow, 5, null ); List<Tuple> actual = getSinkAsList( flow ); assertTrue( actual.contains( new Tuple( "1\ta\t1\tA\t1\ta\tA" ) ) ); assertTrue( actual.contains( new Tuple( "2\tb\t2\tB\t2\tb\tB" ) ) ); } /** * here the same file is fed into the same HashJoin. * <p/> * This is three jobs. * <p/> * a temp tap is inserted before the accumulated branch for two reasons on the common HashJoin * <p/> * it is assumed the accumulated side is filtered down, so pushing to disk will preserve io * if accumulated side was streamed instead via a fork, only part of the file will accumulate into the HashJoin * <p/> * /-T-\ <-- accumulated * T HJ * \---/ <-- streamed * * @throws Exception */ @Test public void testJoinSameSourceIntoJoin() throws Exception { getPlatform().copyFromLocal( inputFileLower ); getPlatform().copyFromLocal( inputFileUpper ); Tap sourceLower = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLower ); Tap sourceUpper = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileUpper ); Map sources = new HashMap(); sources.put( "lower", sourceLower ); sources.put( "upper1", sourceUpper ); sources.put( "upper2", sourceUpper ); Tap sink = getPlatform().getTextFile( new Fields( "line" ), getOutputPath( "joinsamesourceintojoin" ), SinkMode.REPLACE ); Function splitter = new RegexSplitter( new Fields( "num", "char" ), " " ); Pipe pipeLower = new Each( new Pipe( "lower" ), new Fields( "line" ), splitter ); Pipe pipeUpper1 = new Each( new Pipe( "upper1" ), new Fields( "line" ), splitter ); Pipe pipeUpper2 = new Each( new Pipe( "upper2" ), new Fields( "line" ), splitter ); Pipe splice1 = new HashJoin( pipeUpper1, new Fields( "num" ), pipeUpper2, new Fields( "num" ), new Fields( "num1", "char1", "num2", "char2" ) ); splice1 = new Each( splice1, new Identity() ); Pipe splice2 = new HashJoin( pipeLower, new Fields( "num" ), splice1, new Fields( "num1" ), new Fields( "num1", "char1", "num2", "char2", "num3", "char3" ) ); Flow flow = getPlatform().getFlowConnector().connect( sources, sink, splice2 ); // flow.writeDOT( "joinsamesourceintojoin.dot" ); if( getPlatform().isMapReduce() ) assertEquals( "wrong number of steps", 3, flow.getFlowSteps().size() ); flow.complete(); validateLength( flow, 5, null ); List<Tuple> actual = getSinkAsList( flow ); assertTrue( actual.contains( new Tuple( "1\ta\t1\tA\t1\tA" ) ) ); assertTrue( actual.contains( new Tuple( "2\tb\t2\tB\t2\tB" ) ) ); } /** * Tests that two independent streamed sources with loadable tributaries properly plan into a GroupBy * without loading unused sources * * @throws Exception */ @Test public void testJoinsIntoGroupBy() throws Exception { getPlatform().copyFromLocal( inputFileLower ); getPlatform().copyFromLocal( inputFileUpper ); getPlatform().copyFromLocal( inputFileLhs ); getPlatform().copyFromLocal( inputFileRhs ); Tap sourceLower = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLower ); Tap sourceUpper = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileUpper ); Tap sourceLhs = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLhs ); Tap sourceRhs = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileRhs ); Map sources = new HashMap(); sources.put( "lower", sourceLower ); sources.put( "upper", sourceUpper ); sources.put( "lhs", sourceLhs ); sources.put( "rhs", sourceRhs ); Tap sink = getPlatform().getTextFile( new Fields( "line" ), getOutputPath( "joinsintogroupby" ), SinkMode.REPLACE ); Function splitter = new RegexSplitter( new Fields( "num", "char" ), " " ); Pipe pipeLower = new Each( new Pipe( "lower" ), new Fields( "line" ), splitter ); Pipe pipeUpper = new Each( new Pipe( "upper" ), new Fields( "line" ), splitter ); Pipe pipeLhs = new Each( new Pipe( "lhs" ), new Fields( "line" ), splitter ); Pipe pipeRhs = new Each( new Pipe( "rhs" ), new Fields( "line" ), splitter ); Pipe upperLower = new HashJoin( pipeLower, new Fields( "num" ), pipeUpper, new Fields( "num" ), new Fields( "num1", "char1", "num2", "char2" ) ); upperLower = new Each( upperLower, new Identity() ); Pipe lhsRhs = new HashJoin( pipeLhs, new Fields( "num" ), pipeRhs, new Fields( "num" ), new Fields( "num1", "char1", "num2", "char2" ) ); lhsRhs = new Each( lhsRhs, new Identity() ); Pipe grouped = new GroupBy( "merging", Pipe.pipes( upperLower, lhsRhs ), new Fields( "num1" ) ); Flow flow = getPlatform().getFlowConnector().connect( sources, sink, grouped ); if( getPlatform().isMapReduce() ) assertEquals( "wrong number of steps", 1, flow.getFlowSteps().size() ); flow.complete(); validateLength( flow, 42, null ); List<Tuple> actual = getSinkAsList( flow ); assertTrue( actual.contains( new Tuple( "1\ta\t1\tA" ) ) ); assertTrue( actual.contains( new Tuple( "5\te\t5\tE" ) ) ); } @Test public void testJoinSamePipeAroundGroupBy() throws Exception { getPlatform().copyFromLocal( inputFileLower ); Tap source = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLower ); Tap sink = getPlatform().getTextFile( new Fields( "line" ), getOutputPath( "samepipearoundgroupby" ), SinkMode.REPLACE ); Function splitter = new RegexSplitter( new Fields( "num", "char" ), " " ); Pipe pipeLower = new Each( new Pipe( "lower" ), new Fields( "line" ), splitter ); Pipe lhsPipe = new Each( new Pipe( "lhs", pipeLower ), new Identity() ); Pipe rhsPipe = new Each( new Pipe( "rhs", pipeLower ), new Identity() ); rhsPipe = new GroupBy( rhsPipe, new Fields( "num" ) ); rhsPipe = new Each( rhsPipe, new Identity() ); Pipe pipe = new HashJoin( lhsPipe, new Fields( "num" ), rhsPipe, new Fields( "num" ), new Fields( "num1", "char1", "num2", "char2" ) ); Flow flow = getPlatform().getFlowConnector().connect( source, sink, pipe ); flow.complete(); validateLength( flow, 5, null ); List<Tuple> actual = getSinkAsList( flow ); assertTrue( actual.contains( new Tuple( "1\ta\t1\ta" ) ) ); assertTrue( actual.contains( new Tuple( "2\tb\t2\tb" ) ) ); } /** * This test results in two MR jobs because one join feeds into the accumulated side of the second. A mapper * can only stream on branch at a time forcing a temp file between the mappers. see next test for swapped join * * @throws Exception */ @Test public void testJoinsIntoCoGroupLhs() throws Exception { getPlatform().copyFromLocal( inputFileLower ); getPlatform().copyFromLocal( inputFileUpper ); getPlatform().copyFromLocal( inputFileLhs ); getPlatform().copyFromLocal( inputFileRhs ); Tap sourceLower = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLower ); Tap sourceUpper = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileUpper ); Tap sourceLhs = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLhs ); Tap sourceRhs = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileRhs ); Map sources = new HashMap(); sources.put( "lower", sourceLower ); sources.put( "upper", sourceUpper ); sources.put( "lhs", sourceLhs ); sources.put( "rhs", sourceRhs ); Tap sink = getPlatform().getTextFile( new Fields( "line" ), getOutputPath( "joinsintocogrouplhs" ), SinkMode.REPLACE ); Function splitter = new RegexSplitter( new Fields( "num", "char" ), " " ); Pipe pipeLower = new Each( new Pipe( "lower" ), new Fields( "line" ), splitter ); Pipe pipeUpper = new Each( new Pipe( "upper" ), new Fields( "line" ), splitter ); Pipe pipeLhs = new Each( new Pipe( "lhs" ), new Fields( "line" ), splitter ); Pipe pipeRhs = new Each( new Pipe( "rhs" ), new Fields( "line" ), splitter ); Pipe upperLower = new HashJoin( pipeLower, new Fields( "num" ), pipeUpper, new Fields( "num" ), new Fields( "numUpperLower", "charUpperLower", "num2UpperLower", "char2UpperLower" ) ); upperLower = new Each( upperLower, new Identity() ); Pipe lhsUpperLower = new HashJoin( pipeLhs, new Fields( "num" ), upperLower, new Fields( "numUpperLower" ), new Fields( "numLhs", "charLhs", "numUpperLower", "charUpperLower", "num2UpperLower", "char2UpperLower" ) ); lhsUpperLower = new Each( lhsUpperLower, new Identity() ); Pipe grouped = new CoGroup( "cogrouping", lhsUpperLower, new Fields( "numLhs" ), pipeRhs, new Fields( "num" ) ); Flow flow = getPlatform().getFlowConnector().connect( sources, sink, grouped ); if( getPlatform().isMapReduce() ) assertEquals( "wrong number of steps", 2, flow.getFlowSteps().size() ); flow.complete(); validateLength( flow, 37, null ); List<Tuple> actual = getSinkAsList( flow ); assertTrue( actual.contains( new Tuple( "1\ta\t1\ta\t1\tA\t1\tA" ) ) ); assertTrue( actual.contains( new Tuple( "5\ta\t5\te\t5\tE\t5\tA" ) ) ); } /** * This test results in one MR jobs because one join feeds into the streamed side of the second. * * @throws Exception */ @Test public void testJoinsIntoCoGroupLhsSwappedJoin() throws Exception { getPlatform().copyFromLocal( inputFileLower ); getPlatform().copyFromLocal( inputFileUpper ); getPlatform().copyFromLocal( inputFileLhs ); getPlatform().copyFromLocal( inputFileRhs ); Tap sourceLower = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLower ); Tap sourceUpper = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileUpper ); Tap sourceLhs = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLhs ); Tap sourceRhs = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileRhs ); Map sources = new HashMap(); sources.put( "lower", sourceLower ); sources.put( "upper", sourceUpper ); sources.put( "lhs", sourceLhs ); sources.put( "rhs", sourceRhs ); Tap sink = getPlatform().getTextFile( new Fields( "line" ), getOutputPath( "joinsintocogrouplhsswappedjoin" ), SinkMode.REPLACE ); Function splitter = new RegexSplitter( new Fields( "num", "char" ), " " ); Pipe pipeLower = new Each( new Pipe( "lower" ), new Fields( "line" ), splitter ); Pipe pipeUpper = new Each( new Pipe( "upper" ), new Fields( "line" ), splitter ); Pipe pipeLhs = new Each( new Pipe( "lhs" ), new Fields( "line" ), splitter ); Pipe pipeRhs = new Each( new Pipe( "rhs" ), new Fields( "line" ), splitter ); Pipe upperLower = new HashJoin( pipeLower, new Fields( "num" ), pipeUpper, new Fields( "num" ), new Fields( "numUpperLower", "charUpperLower", "num2UpperLower", "char2UpperLower" ) ); upperLower = new Each( upperLower, new Identity() ); Pipe lhsUpperLower = new HashJoin( upperLower, new Fields( "numUpperLower" ), pipeLhs, new Fields( "num" ), new Fields( "numUpperLower", "charUpperLower", "num2UpperLower", "char2UpperLower", "numLhs", "charLhs" ) ); lhsUpperLower = new Each( lhsUpperLower, new Identity() ); Pipe grouped = new CoGroup( "cogrouping", lhsUpperLower, new Fields( "numLhs" ), pipeRhs, new Fields( "num" ) ); Flow flow = getPlatform().getFlowConnector().connect( sources, sink, grouped ); if( getPlatform().isMapReduce() ) assertEquals( "wrong number of steps", 1, flow.getFlowSteps().size() ); flow.complete(); validateLength( flow, 37, null ); List<Tuple> actual = getSinkAsList( flow ); assertTrue( actual.contains( new Tuple( "1\ta\t1\tA\t1\ta\t1\tA" ) ) ); assertTrue( actual.contains( new Tuple( "5\te\t5\tE\t5\te\t5\tE" ) ) ); } @Test public void testJoinsIntoCoGroupRhs() throws Exception { getPlatform().copyFromLocal( inputFileLower ); getPlatform().copyFromLocal( inputFileUpper ); getPlatform().copyFromLocal( inputFileLhs ); getPlatform().copyFromLocal( inputFileRhs ); Tap sourceLower = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLower ); Tap sourceUpper = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileUpper ); Tap sourceLhs = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLhs ); Tap sourceRhs = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileRhs ); Map sources = new HashMap(); sources.put( "lower", sourceLower ); sources.put( "upper", sourceUpper ); sources.put( "lhs", sourceLhs ); sources.put( "rhs", sourceRhs ); Tap sink = getPlatform().getTextFile( new Fields( "line" ), getOutputPath( "joinsintocogrouprhs" ), SinkMode.REPLACE ); Function splitter = new RegexSplitter( new Fields( "num", "char" ), " " ); Pipe pipeLower = new Each( new Pipe( "lower" ), new Fields( "line" ), splitter ); Pipe pipeUpper = new Each( new Pipe( "upper" ), new Fields( "line" ), splitter ); Pipe pipeLhs = new Each( new Pipe( "lhs" ), new Fields( "line" ), splitter ); Pipe pipeRhs = new Each( new Pipe( "rhs" ), new Fields( "line" ), splitter ); Pipe upperLower = new HashJoin( pipeLower, new Fields( "num" ), pipeUpper, new Fields( "num" ), new Fields( "numUpperLower", "charUpperLower", "num2UpperLower", "char2UpperLower" ) ); upperLower = new Each( upperLower, new Identity() ); Pipe lhsUpperLower = new HashJoin( pipeLhs, new Fields( "num" ), upperLower, new Fields( "numUpperLower" ), new Fields( "numLhs", "charLhs", "numUpperLower", "charUpperLower", "num2UpperLower", "char2UpperLower" ) ); lhsUpperLower = new Each( lhsUpperLower, new Identity() ); Pipe grouped = new CoGroup( "cogrouping", pipeRhs, new Fields( "num" ), lhsUpperLower, new Fields( "numLhs" ) ); Flow flow = getPlatform().getFlowConnector().connect( sources, sink, grouped ); if( getPlatform().isMapReduce() ) assertEquals( "wrong number of steps", 2, flow.getFlowSteps().size() ); flow.complete(); validateLength( flow, 37, null ); List<Tuple> actual = getSinkAsList( flow ); assertTrue( actual.contains( new Tuple( "1\tA\t1\ta\t1\ta\t1\tA" ) ) ); assertTrue( actual.contains( new Tuple( "5\tE\t5\te\t5\te\t5\tE" ) ) ); } @Test public void testJoinsIntoCoGroup() throws Exception { getPlatform().copyFromLocal( inputFileLower ); getPlatform().copyFromLocal( inputFileUpper ); getPlatform().copyFromLocal( inputFileLhs ); getPlatform().copyFromLocal( inputFileRhs ); Tap sourceLower = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLower ); Tap sourceUpper = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileUpper ); Tap sourceLhs = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLhs ); Tap sourceRhs = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileRhs ); Map sources = new HashMap(); sources.put( "lower", sourceLower ); sources.put( "upper", sourceUpper ); sources.put( "lhs", sourceLhs ); sources.put( "rhs", sourceRhs ); Tap sink = getPlatform().getTextFile( new Fields( "line" ), getOutputPath( "joinsintocogroup" ), SinkMode.REPLACE ); Function splitter = new RegexSplitter( new Fields( "num", "char" ), " " ); Pipe pipeLower = new Each( new Pipe( "lower" ), new Fields( "line" ), splitter ); Pipe pipeUpper = new Each( new Pipe( "upper" ), new Fields( "line" ), splitter ); Pipe pipeLhs = new Each( new Pipe( "lhs" ), new Fields( "line" ), splitter ); Pipe pipeRhs = new Each( new Pipe( "rhs" ), new Fields( "line" ), splitter ); Pipe upperLower = new HashJoin( pipeLower, new Fields( "num" ), pipeUpper, new Fields( "num" ), new Fields( "numUpperLower1", "charUpperLower1", "numUpperLower2", "charUpperLower2" ) ); upperLower = new Each( upperLower, new Identity() ); Pipe lhsRhs = new HashJoin( pipeLhs, new Fields( "num" ), pipeRhs, new Fields( "num" ), new Fields( "numLhsRhs1", "charLhsRhs1", "numLhsRhs2", "charLhsRhs2" ) ); lhsRhs = new Each( lhsRhs, new Identity() ); Pipe grouped = new CoGroup( "cogrouping", upperLower, new Fields( "numUpperLower1" ), lhsRhs, new Fields( "numLhsRhs1" ) ); Flow flow = getPlatform().getFlowConnector().connect( sources, sink, grouped ); if( getPlatform().isMapReduce() ) assertEquals( "wrong number of steps", 1, flow.getFlowSteps().size() ); flow.complete(); validateLength( flow, 37, null ); List<Tuple> actual = getSinkAsList( flow ); assertTrue( actual.contains( new Tuple( "1\ta\t1\tA\t1\ta\t1\tA" ) ) ); assertTrue( actual.contains( new Tuple( "5\te\t5\tE\t5\te\t5\tE" ) ) ); } public static class AllComparator implements Comparator<Comparable>, Hasher<Comparable>, Serializable { @Override public int compare( Comparable lhs, Comparable rhs ) { return lhs.toString().compareTo( rhs.toString() ); } @Override public int hashCode( Comparable value ) { if( value == null ) return 0; return value.toString().hashCode(); } } /** * Tests Hasher being honored even if default comparator is null. * * @throws Exception */ @Test public void testJoinWithHasher() throws Exception { getPlatform().copyFromLocal( inputFileLower ); getPlatform().copyFromLocal( inputFileUpper ); Tap sourceLower = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLower ); Tap sourceUpper = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileUpper ); Map sources = new HashMap(); sources.put( "lower", sourceLower ); sources.put( "upper", sourceUpper ); Tap sink = getPlatform().getTextFile( new Fields( "line" ), getOutputPath( "joinhasher" ), SinkMode.REPLACE ); Function splitter = new RegexSplitter( new Fields( "num", "char" ), " " ); Pipe pipeLower = new Each( new Pipe( "lower" ), new Fields( "line" ), splitter ); pipeLower = new Each( pipeLower, new Fields( "num" ), new ExpressionFunction( Fields.ARGS, "Integer.parseInt( num )", String.class ), Fields.REPLACE ); Pipe pipeUpper = new Each( new Pipe( "upper" ), new Fields( "line" ), splitter ); Fields num = new Fields( "num" ); num.setComparator( "num", new AllComparator() ); Pipe splice = new HashJoin( pipeLower, num, pipeUpper, new Fields( "num" ), Fields.size( 4 ) ); Map<Object, Object> properties = getProperties(); Flow flow = getPlatform().getFlowConnector( properties ).connect( sources, sink, splice ); flow.complete(); validateLength( flow, 5 ); List<Tuple> values = getSinkAsList( flow ); assertTrue( values.contains( new Tuple( "1\ta\t1\tA" ) ) ); assertTrue( values.contains( new Tuple( "2\tb\t2\tB" ) ) ); } @Test public void testJoinNone() throws Exception { getPlatform().copyFromLocal( inputFileLower ); getPlatform().copyFromLocal( inputFileUpper ); Tap sourceLower = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileLower ); Tap sourceUpper = getPlatform().getTextFile( new Fields( "offset", "line" ), inputFileUpper ); Map sources = new HashMap(); sources.put( "lower", sourceLower ); sources.put( "upper", sourceUpper ); Tap sink = getPlatform().getTextFile( new Fields( "line" ), getOutputPath( "joinnone" ), SinkMode.REPLACE ); Function splitter = new RegexSplitter( new Fields( "num", "char" ), " " ); Pipe pipeLower = new Each( new Pipe( "lower" ), new Fields( "line" ), splitter ); Pipe pipeUpper = new Each( new Pipe( "upper" ), new Fields( "line" ), splitter ); Pipe splice = new HashJoin( pipeLower, Fields.NONE, pipeUpper, Fields.NONE, Fields.size( 4 ) ); Map<Object, Object> properties = getProperties(); Flow flow = getPlatform().getFlowConnector( properties ).connect( sources, sink, splice ); flow.complete(); validateLength( flow, 25 ); List<Tuple> values = getSinkAsList( flow ); assertTrue( values.contains( new Tuple( "1\ta\t1\tA" ) ) ); assertTrue( values.contains( new Tuple( "1\ta\t2\tB" ) ) ); assertTrue( values.contains( new Tuple( "2\tb\t2\tB" ) ) ); } /** * When run against a cluster a Merge before a GroupBy can hide the streamed/accumulated nature of a branch. * * commented code is for troubleshooting. * @throws Exception */ @Test public void testJoinMergeGroupBy() throws Exception { getPlatform().copyFromLocal( inputFileNums10 ); getPlatform().copyFromLocal( inputFileNums20 ); Tap lhsTap = getPlatform().getTextFile( new Fields( "id" ), inputFileNums10 ); Tap rhsTap = getPlatform().getTextFile( new Fields( "id2" ), inputFileNums20 ); Pipe lhs = new Pipe( "lhs" ); Pipe rhs = new Pipe( "rhs" ); // Pipe joined = new CoGroup( messages, new Fields( "id" ), people, new Fields( "id2" ) ); Pipe joined = new HashJoin( lhs, new Fields( "id" ), rhs, new Fields( "id2" ) ); Pipe pruned = new Each( joined, new Fields( "id2" ), new Identity(), Fields.RESULTS ); // pruned = new Checkpoint( pruned ); Pipe merged = new Merge( pruned, rhs ); Pipe grouped = new GroupBy( merged, new Fields( "id2" ) ); // Pipe grouped = new GroupBy( Pipe.pipes( pruned, people ), new Fields( "id2" ) ); Aggregator count = new Count( new Fields( "count" ) ); Pipe counted = new Every( grouped, count ); String testJoinMerge = "testJoinMergeGroupBy/" + ( ( joined instanceof CoGroup ) ? "cogroup" : "hashjoin" ); Tap sink = getPlatform().getDelimitedFile( Fields.ALL, true, "\t", null, getOutputPath( testJoinMerge ), SinkMode.REPLACE ); FlowDef flowDef = FlowDef.flowDef() .addSource( rhs, rhsTap ) .addSource( lhs, lhsTap ) .addTailSink( counted, sink ); Flow flow = getPlatform().getFlowConnector().connect( flowDef ); // flow.writeDOT( "joinmerge.dot" ); // flow.writeStepsDOT( "joinmerge-steps.dot" ); flow.complete(); validateLength( flow, 20 ); List<Tuple> values = getSinkAsList( flow ); List<Tuple> expected = new ArrayList<Tuple>(); expected.add( new Tuple( "1", "2" ) ); expected.add( new Tuple( "10", "2" ) ); expected.add( new Tuple( "11", "1" ) ); expected.add( new Tuple( "12", "1" ) ); expected.add( new Tuple( "13", "1" ) ); expected.add( new Tuple( "14", "1" ) ); expected.add( new Tuple( "15", "1" ) ); expected.add( new Tuple( "16", "1" ) ); expected.add( new Tuple( "17", "1" ) ); expected.add( new Tuple( "18", "1" ) ); expected.add( new Tuple( "19", "1" ) ); expected.add( new Tuple( "2", "2" ) ); expected.add( new Tuple( "20", "1" ) ); expected.add( new Tuple( "3", "2" ) ); expected.add( new Tuple( "4", "2" ) ); expected.add( new Tuple( "5", "2" ) ); expected.add( new Tuple( "6", "2" ) ); expected.add( new Tuple( "7", "2" ) ); expected.add( new Tuple( "8", "2" ) ); expected.add( new Tuple( "9", "2" ) ); Collections.sort(values); Collections.sort(expected); assertEquals( expected, values ); } }
3e1db744ae409653fb6b353b73921f02115ee256
670
java
Java
e3-portal-web/src/main/java/cn/e3mall/portal/controller/IndexController.java
guo846773272/e3mall
26dc50da631907059bf7e42b24cd5cdaa6d64f1a
[ "Apache-2.0" ]
null
null
null
e3-portal-web/src/main/java/cn/e3mall/portal/controller/IndexController.java
guo846773272/e3mall
26dc50da631907059bf7e42b24cd5cdaa6d64f1a
[ "Apache-2.0" ]
null
null
null
e3-portal-web/src/main/java/cn/e3mall/portal/controller/IndexController.java
guo846773272/e3mall
26dc50da631907059bf7e42b24cd5cdaa6d64f1a
[ "Apache-2.0" ]
null
null
null
23.928571
67
0.798507
12,586
package cn.e3mall.portal.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import cn.e3mall.content.service.ContentService; import cn.e3mall.pojo.TbContent; @Controller public class IndexController { @Autowired private ContentService contentService; @RequestMapping(value="/index") public String showIndex(Model model) { List<TbContent> ad1List = contentService.getContentListByCid(89); model.addAttribute("ad1List", ad1List); return "index"; } }
3e1db7d5ca81020eaa0550675fe2e03c8c0d39ac
12,390
java
Java
CiroFitness/app/build/generated/not_namespaced_r_class_sources/debug/r/androidx/fragment/R.java
cmadrid19/CiroFitness
d5b5433ba297c784071636e0657cd0cc482ac309
[ "CC0-1.0" ]
null
null
null
CiroFitness/app/build/generated/not_namespaced_r_class_sources/debug/r/androidx/fragment/R.java
cmadrid19/CiroFitness
d5b5433ba297c784071636e0657cd0cc482ac309
[ "CC0-1.0" ]
null
null
null
CiroFitness/app/build/generated/not_namespaced_r_class_sources/debug/r/androidx/fragment/R.java
cmadrid19/CiroFitness
d5b5433ba297c784071636e0657cd0cc482ac309
[ "CC0-1.0" ]
null
null
null
58.443396
185
0.739952
12,587
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * gradle plugin from the resource data it found. It * should not be modified by hand. */ package androidx.fragment; public final class R { private R() {} public static final class attr { private attr() {} public static final int alpha = 0x7f03002c; public static final int coordinatorLayoutStyle = 0x7f0300a9; public static final int font = 0x7f0300dc; public static final int fontProviderAuthority = 0x7f0300de; public static final int fontProviderCerts = 0x7f0300df; public static final int fontProviderFetchStrategy = 0x7f0300e0; public static final int fontProviderFetchTimeout = 0x7f0300e1; public static final int fontProviderPackage = 0x7f0300e2; public static final int fontProviderQuery = 0x7f0300e3; public static final int fontStyle = 0x7f0300e4; public static final int fontVariationSettings = 0x7f0300e5; public static final int fontWeight = 0x7f0300e6; public static final int keylines = 0x7f030112; public static final int layout_anchor = 0x7f030117; public static final int layout_anchorGravity = 0x7f030118; public static final int layout_behavior = 0x7f030119; public static final int layout_dodgeInsetEdges = 0x7f030145; public static final int layout_insetEdge = 0x7f03014e; public static final int layout_keyline = 0x7f03014f; public static final int statusBarBackground = 0x7f0301ab; public static final int ttcIndex = 0x7f03020d; } public static final class color { private color() {} public static final int notification_action_color_filter = 0x7f050070; public static final int notification_icon_bg_color = 0x7f050071; public static final int ripple_material_light = 0x7f05007b; public static final int secondary_text_default_material_light = 0x7f05007d; } public static final class dimen { private dimen() {} public static final int compat_button_inset_horizontal_material = 0x7f06005d; public static final int compat_button_inset_vertical_material = 0x7f06005e; public static final int compat_button_padding_horizontal_material = 0x7f06005f; public static final int compat_button_padding_vertical_material = 0x7f060060; public static final int compat_control_corner_material = 0x7f060061; public static final int compat_notification_large_icon_max_height = 0x7f060062; public static final int compat_notification_large_icon_max_width = 0x7f060063; public static final int notification_action_icon_size = 0x7f0600d2; public static final int notification_action_text_size = 0x7f0600d3; public static final int notification_big_circle_margin = 0x7f0600d4; public static final int notification_content_margin_start = 0x7f0600d5; public static final int notification_large_icon_height = 0x7f0600d6; public static final int notification_large_icon_width = 0x7f0600d7; public static final int notification_main_column_padding_top = 0x7f0600d8; public static final int notification_media_narrow_margin = 0x7f0600d9; public static final int notification_right_icon_size = 0x7f0600da; public static final int notification_right_side_padding_top = 0x7f0600db; public static final int notification_small_icon_background_padding = 0x7f0600dc; public static final int notification_small_icon_size_as_large = 0x7f0600dd; public static final int notification_subtext_size = 0x7f0600de; public static final int notification_top_pad = 0x7f0600df; public static final int notification_top_pad_large_text = 0x7f0600e0; } public static final class drawable { private drawable() {} public static final int notification_action_background = 0x7f070070; public static final int notification_bg = 0x7f070071; public static final int notification_bg_low = 0x7f070072; public static final int notification_bg_low_normal = 0x7f070073; public static final int notification_bg_low_pressed = 0x7f070074; public static final int notification_bg_normal = 0x7f070075; public static final int notification_bg_normal_pressed = 0x7f070076; public static final int notification_icon_background = 0x7f070077; public static final int notification_template_icon_bg = 0x7f070078; public static final int notification_template_icon_low_bg = 0x7f070079; public static final int notification_tile_bg = 0x7f07007a; public static final int notify_panel_notification_icon_bg = 0x7f07007b; } public static final class id { private id() {} public static final int action_container = 0x7f08000f; public static final int action_divider = 0x7f080011; public static final int action_image = 0x7f080012; public static final int action_text = 0x7f080018; public static final int actions = 0x7f080019; public static final int async = 0x7f080020; public static final int blocking = 0x7f080024; public static final int bottom = 0x7f080025; public static final int chronometer = 0x7f080036; public static final int end = 0x7f08004c; public static final int forever = 0x7f080059; public static final int icon = 0x7f080061; public static final int icon_group = 0x7f080062; public static final int info = 0x7f080066; public static final int italic = 0x7f080068; public static final int left = 0x7f08006d; public static final int line1 = 0x7f08006e; public static final int line3 = 0x7f08006f; public static final int none = 0x7f08007c; public static final int normal = 0x7f08007d; public static final int notification_background = 0x7f08007e; public static final int notification_main_column = 0x7f08007f; public static final int notification_main_column_container = 0x7f080080; public static final int right = 0x7f08008d; public static final int right_icon = 0x7f08008e; public static final int right_side = 0x7f08008f; public static final int start = 0x7f0800b6; public static final int tag_transition_group = 0x7f0800bb; public static final int tag_unhandled_key_event_manager = 0x7f0800bc; public static final int tag_unhandled_key_listeners = 0x7f0800bd; public static final int text = 0x7f0800be; public static final int text2 = 0x7f0800bf; public static final int time = 0x7f0800c7; public static final int title = 0x7f0800c8; public static final int top = 0x7f0800cb; } public static final class integer { private integer() {} public static final int status_bar_notification_info_maxnum = 0x7f09000e; } public static final class layout { private layout() {} public static final int notification_action = 0x7f0b0031; public static final int notification_action_tombstone = 0x7f0b0032; public static final int notification_template_custom_big = 0x7f0b0033; public static final int notification_template_icon_group = 0x7f0b0034; public static final int notification_template_part_chronometer = 0x7f0b0035; public static final int notification_template_part_time = 0x7f0b0036; } public static final class string { private string() {} public static final int status_bar_notification_info_overflow = 0x7f0d0041; } public static final class style { private style() {} public static final int TextAppearance_Compat_Notification = 0x7f0e011b; public static final int TextAppearance_Compat_Notification_Info = 0x7f0e011c; public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0e011d; public static final int TextAppearance_Compat_Notification_Time = 0x7f0e011e; public static final int TextAppearance_Compat_Notification_Title = 0x7f0e011f; public static final int Widget_Compat_NotificationActionContainer = 0x7f0e01c5; public static final int Widget_Compat_NotificationActionText = 0x7f0e01c6; public static final int Widget_Support_CoordinatorLayout = 0x7f0e01f5; } public static final class styleable { private styleable() {} public static final int[] ColorStateListItem = { 0x10101a5, 0x101031f, 0x7f03002c }; public static final int ColorStateListItem_android_color = 0; public static final int ColorStateListItem_android_alpha = 1; public static final int ColorStateListItem_alpha = 2; public static final int[] CoordinatorLayout = { 0x7f030112, 0x7f0301ab }; public static final int CoordinatorLayout_keylines = 0; public static final int CoordinatorLayout_statusBarBackground = 1; public static final int[] CoordinatorLayout_Layout = { 0x10100b3, 0x7f030117, 0x7f030118, 0x7f030119, 0x7f030145, 0x7f03014e, 0x7f03014f }; public static final int CoordinatorLayout_Layout_android_layout_gravity = 0; public static final int CoordinatorLayout_Layout_layout_anchor = 1; public static final int CoordinatorLayout_Layout_layout_anchorGravity = 2; public static final int CoordinatorLayout_Layout_layout_behavior = 3; public static final int CoordinatorLayout_Layout_layout_dodgeInsetEdges = 4; public static final int CoordinatorLayout_Layout_layout_insetEdge = 5; public static final int CoordinatorLayout_Layout_layout_keyline = 6; public static final int[] FontFamily = { 0x7f0300de, 0x7f0300df, 0x7f0300e0, 0x7f0300e1, 0x7f0300e2, 0x7f0300e3 }; public static final int FontFamily_fontProviderAuthority = 0; public static final int FontFamily_fontProviderCerts = 1; public static final int FontFamily_fontProviderFetchStrategy = 2; public static final int FontFamily_fontProviderFetchTimeout = 3; public static final int FontFamily_fontProviderPackage = 4; public static final int FontFamily_fontProviderQuery = 5; public static final int[] FontFamilyFont = { 0x1010532, 0x1010533, 0x101053f, 0x101056f, 0x1010570, 0x7f0300dc, 0x7f0300e4, 0x7f0300e5, 0x7f0300e6, 0x7f03020d }; public static final int FontFamilyFont_android_font = 0; public static final int FontFamilyFont_android_fontWeight = 1; public static final int FontFamilyFont_android_fontStyle = 2; public static final int FontFamilyFont_android_ttcIndex = 3; public static final int FontFamilyFont_android_fontVariationSettings = 4; public static final int FontFamilyFont_font = 5; public static final int FontFamilyFont_fontStyle = 6; public static final int FontFamilyFont_fontVariationSettings = 7; public static final int FontFamilyFont_fontWeight = 8; public static final int FontFamilyFont_ttcIndex = 9; public static final int[] GradientColor = { 0x101019d, 0x101019e, 0x10101a1, 0x10101a2, 0x10101a3, 0x10101a4, 0x1010201, 0x101020b, 0x1010510, 0x1010511, 0x1010512, 0x1010513 }; public static final int GradientColor_android_startColor = 0; public static final int GradientColor_android_endColor = 1; public static final int GradientColor_android_type = 2; public static final int GradientColor_android_centerX = 3; public static final int GradientColor_android_centerY = 4; public static final int GradientColor_android_gradientRadius = 5; public static final int GradientColor_android_tileMode = 6; public static final int GradientColor_android_centerColor = 7; public static final int GradientColor_android_startX = 8; public static final int GradientColor_android_startY = 9; public static final int GradientColor_android_endX = 10; public static final int GradientColor_android_endY = 11; public static final int[] GradientColorItem = { 0x10101a5, 0x1010514 }; public static final int GradientColorItem_android_color = 0; public static final int GradientColorItem_android_offset = 1; } }
3e1db7f55e69dcfceec166a6836df815993b6a1e
1,068
java
Java
buildSrc/src/main/java/com/debughelper/tools/r8/cf/code/CfConstNull.java
howardpang/androiddebughelper
becf780a81ea0f7f0c00510075700c6b04eb9fef
[ "Apache-2.0", "BSD-3-Clause" ]
11
2019-05-07T11:11:34.000Z
2021-01-21T10:28:40.000Z
buildSrc/src/main/java/com/debughelper/tools/r8/cf/code/CfConstNull.java
howardpang/androiddebughelper
becf780a81ea0f7f0c00510075700c6b04eb9fef
[ "Apache-2.0", "BSD-3-Clause" ]
3
2019-05-09T03:44:00.000Z
2019-08-20T02:58:54.000Z
buildSrc/src/main/java/com/debughelper/tools/r8/cf/code/CfConstNull.java
howardpang/androiddebughelper
becf780a81ea0f7f0c00510075700c6b04eb9fef
[ "Apache-2.0", "BSD-3-Clause" ]
3
2019-05-13T09:32:08.000Z
2020-04-16T00:16:02.000Z
32.363636
77
0.779026
12,588
// Copyright (c) 2017, the R8 project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. package com.debughelper.tools.r8.cf.code; import com.debughelper.tools.r8.ir.conversion.CfSourceCode; import com.debughelper.tools.r8.ir.conversion.CfState; import com.debughelper.tools.r8.ir.conversion.IRBuilder; import com.debughelper.tools.r8.naming.NamingLens; import com.debughelper.tools.r8.cf.CfPrinter; import com.debughelper.tools.r8.ir.code.ValueType; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; public class CfConstNull extends CfInstruction { @Override public void write(MethodVisitor visitor, NamingLens lens) { visitor.visitInsn(Opcodes.ACONST_NULL); } @Override public void print(CfPrinter printer) { printer.print(this); } @Override public void buildIR(IRBuilder builder, CfState state, CfSourceCode code) { builder.addNullConst(state.push(ValueType.OBJECT).register); } }
3e1db83ccf38ff853292b8deaf86877cd8862209
2,518
java
Java
app/src/main/java/com/codepath/apps/restclienttemplate/TweetAdapter.java
dia-bolix/Tweee
5515a15de15a573e23f95d5bc8023c41f790196e
[ "MIT" ]
null
null
null
app/src/main/java/com/codepath/apps/restclienttemplate/TweetAdapter.java
dia-bolix/Tweee
5515a15de15a573e23f95d5bc8023c41f790196e
[ "MIT" ]
1
2019-02-22T05:48:32.000Z
2019-02-22T05:48:32.000Z
app/src/main/java/com/codepath/apps/restclienttemplate/TweetAdapter.java
dia-bolix/Tweee
5515a15de15a573e23f95d5bc8023c41f790196e
[ "MIT" ]
null
null
null
29.27907
96
0.69579
12,589
package com.codepath.apps.restclienttemplate; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.codepath.apps.restclienttemplate.models.Tweet; import java.util.List; public class TweetAdapter extends RecyclerView.Adapter<TweetAdapter.ViewHolder>{ //pass in context and list of tweets private Context context; private List<Tweet> tweets; public TweetAdapter(Context context, List<Tweet> tweets) { this.context = context; this.tweets = tweets; } //for each row inflate the layout @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view = LayoutInflater.from(context).inflate(R.layout.item_tweet, viewGroup, false); return new ViewHolder(view); } //bind value based on pos of element @Override public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) { Tweet tweet = tweets.get(i); viewHolder.tweet_content.setText(tweet.body); viewHolder.handle.setText(tweet.user.screenname); viewHolder.relativedate.setText(tweet.createdDate); Glide.with(context).load(tweet.user.profileImgUrl).into(viewHolder.ivProfileImg); } @Override public int getItemCount() { return tweets.size(); } //add methods to replace when swipe to refresh //clear the list of tweets public void clear() { tweets.clear(); notifyDataSetChanged(); } //add the new list in public void addTweets(List<Tweet> tweetlist) { tweets.addAll(tweetlist); notifyDataSetChanged(); } //define a viewholder to be displayed in recycler view public class ViewHolder extends RecyclerView.ViewHolder { public ImageView ivProfileImg; public TextView handle; public TextView tweet_content; public TextView relativedate; public ViewHolder(@NonNull View itemView) { super(itemView); ivProfileImg = itemView.findViewById(R.id.ivProfile); handle = itemView.findViewById(R.id.tvHandle); tweet_content = itemView.findViewById(R.id.tvUserTweet); relativedate = itemView.findViewById(R.id.tvTime); } } }
3e1db863407cfed37700415119f5449018546bbf
1,290
java
Java
src/main/java/com/github/vboiko/dropwizard/docs/model/PageInfoBuilder.java
v-boyko/dropwizard-docs-bundle
12abd009e474fafc99a31c597553a6b1530d9742
[ "Apache-2.0" ]
1
2016-09-03T11:06:34.000Z
2016-09-03T11:06:34.000Z
src/main/java/com/github/vboiko/dropwizard/docs/model/PageInfoBuilder.java
v-boyko/dropwizard-docs-bundle
12abd009e474fafc99a31c597553a6b1530d9742
[ "Apache-2.0" ]
null
null
null
src/main/java/com/github/vboiko/dropwizard/docs/model/PageInfoBuilder.java
v-boyko/dropwizard-docs-bundle
12abd009e474fafc99a31c597553a6b1530d9742
[ "Apache-2.0" ]
null
null
null
25.8
72
0.686047
12,590
package com.github.vboiko.dropwizard.docs.model; import com.google.common.collect.ImmutableMap; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.io.FilenameUtils; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; public final class PageInfoBuilder { private PageInfo pageInfo = new PageInfo(); private Map<String, Object> fields = new HashMap<>(); public static PageInfoBuilder pageInfo() { return new PageInfoBuilder(); } public PageInfoBuilder withData(Map<String, Object> fields) { this.fields.putAll(fields); return this; } public PageInfoBuilder withContent(String content) { this.fields.put("content", content); return this; } public PageInfoBuilder withFileName(String fileName) { pageInfo.setFileName(fileName); pageInfo.setPermalink(FilenameUtils.getBaseName(fileName)); return this; } public PageInfo build() { try { BeanUtils.populate(pageInfo, fields); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } pageInfo.setDataFields(ImmutableMap.copyOf(fields)); return pageInfo; } }
3e1db8bc75b760965e075f96fb99d35dc6a80300
22,154
java
Java
lognition-convert/src/main/java/com/redsaz/lognition/convert/model/HttpSample.java
redsaz/lognition
587d865de2c09250df98e6e4f1db467063ba4929
[ "Apache-2.0" ]
3
2018-11-26T05:16:21.000Z
2019-08-23T08:30:34.000Z
lognition-convert/src/main/java/com/redsaz/lognition/convert/model/HttpSample.java
redsaz/lognition
587d865de2c09250df98e6e4f1db467063ba4929
[ "Apache-2.0" ]
34
2018-12-06T19:38:42.000Z
2022-02-09T19:16:41.000Z
lognition-convert/src/main/java/com/redsaz/lognition/convert/model/HttpSample.java
redsaz/lognition
587d865de2c09250df98e6e4f1db467063ba4929
[ "Apache-2.0" ]
2
2021-03-10T23:36:14.000Z
2021-06-16T19:12:35.000Z
32.579412
693
0.645798
12,591
/** * Autogenerated by Avro * * DO NOT EDIT DIRECTLY */ package com.redsaz.lognition.convert.model; import org.apache.avro.specific.SpecificData; @SuppressWarnings("all") @org.apache.avro.specific.AvroGenerated public class HttpSample extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord { private static final long serialVersionUID = 7561328620427167856L; public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"HttpSample\",\"namespace\":\"com.redsaz.lognition.convert.model\",\"fields\":[{\"name\":\"millisOffset\",\"type\":\"long\",\"default\":0},{\"name\":\"millisElapsed\",\"type\":\"long\",\"default\":-1},{\"name\":\"labelRef\",\"type\":\"int\",\"default\":0},{\"name\":\"threadNameRef\",\"type\":\"int\",\"default\":0},{\"name\":\"responseCodeRef\",\"type\":\"int\",\"default\":0},{\"name\":\"success\",\"type\":\"boolean\",\"default\":true},{\"name\":\"responseBytes\",\"type\":\"long\",\"default\":-1},{\"name\":\"totalThreads\",\"type\":\"int\",\"default\":0}]}"); public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; } @Deprecated public long millisOffset; @Deprecated public long millisElapsed; @Deprecated public int labelRef; @Deprecated public int threadNameRef; @Deprecated public int responseCodeRef; @Deprecated public boolean success; @Deprecated public long responseBytes; @Deprecated public int totalThreads; /** * Default constructor. Note that this does not initialize fields * to their default values from the schema. If that is desired then * one should use <code>newBuilder()</code>. */ public HttpSample() {} /** * All-args constructor. * @param millisOffset The new value for millisOffset * @param millisElapsed The new value for millisElapsed * @param labelRef The new value for labelRef * @param threadNameRef The new value for threadNameRef * @param responseCodeRef The new value for responseCodeRef * @param success The new value for success * @param responseBytes The new value for responseBytes * @param totalThreads The new value for totalThreads */ public HttpSample(java.lang.Long millisOffset, java.lang.Long millisElapsed, java.lang.Integer labelRef, java.lang.Integer threadNameRef, java.lang.Integer responseCodeRef, java.lang.Boolean success, java.lang.Long responseBytes, java.lang.Integer totalThreads) { this.millisOffset = millisOffset; this.millisElapsed = millisElapsed; this.labelRef = labelRef; this.threadNameRef = threadNameRef; this.responseCodeRef = responseCodeRef; this.success = success; this.responseBytes = responseBytes; this.totalThreads = totalThreads; } public org.apache.avro.Schema getSchema() { return SCHEMA$; } // Used by DatumWriter. Applications should not call. public java.lang.Object get(int field$) { switch (field$) { case 0: return millisOffset; case 1: return millisElapsed; case 2: return labelRef; case 3: return threadNameRef; case 4: return responseCodeRef; case 5: return success; case 6: return responseBytes; case 7: return totalThreads; default: throw new org.apache.avro.AvroRuntimeException("Bad index"); } } // Used by DatumReader. Applications should not call. @SuppressWarnings(value="unchecked") public void put(int field$, java.lang.Object value$) { switch (field$) { case 0: millisOffset = (java.lang.Long)value$; break; case 1: millisElapsed = (java.lang.Long)value$; break; case 2: labelRef = (java.lang.Integer)value$; break; case 3: threadNameRef = (java.lang.Integer)value$; break; case 4: responseCodeRef = (java.lang.Integer)value$; break; case 5: success = (java.lang.Boolean)value$; break; case 6: responseBytes = (java.lang.Long)value$; break; case 7: totalThreads = (java.lang.Integer)value$; break; default: throw new org.apache.avro.AvroRuntimeException("Bad index"); } } /** * Gets the value of the 'millisOffset' field. * @return The value of the 'millisOffset' field. */ public java.lang.Long getMillisOffset() { return millisOffset; } /** * Sets the value of the 'millisOffset' field. * @param value the value to set. */ public void setMillisOffset(java.lang.Long value) { this.millisOffset = value; } /** * Gets the value of the 'millisElapsed' field. * @return The value of the 'millisElapsed' field. */ public java.lang.Long getMillisElapsed() { return millisElapsed; } /** * Sets the value of the 'millisElapsed' field. * @param value the value to set. */ public void setMillisElapsed(java.lang.Long value) { this.millisElapsed = value; } /** * Gets the value of the 'labelRef' field. * @return The value of the 'labelRef' field. */ public java.lang.Integer getLabelRef() { return labelRef; } /** * Sets the value of the 'labelRef' field. * @param value the value to set. */ public void setLabelRef(java.lang.Integer value) { this.labelRef = value; } /** * Gets the value of the 'threadNameRef' field. * @return The value of the 'threadNameRef' field. */ public java.lang.Integer getThreadNameRef() { return threadNameRef; } /** * Sets the value of the 'threadNameRef' field. * @param value the value to set. */ public void setThreadNameRef(java.lang.Integer value) { this.threadNameRef = value; } /** * Gets the value of the 'responseCodeRef' field. * @return The value of the 'responseCodeRef' field. */ public java.lang.Integer getResponseCodeRef() { return responseCodeRef; } /** * Sets the value of the 'responseCodeRef' field. * @param value the value to set. */ public void setResponseCodeRef(java.lang.Integer value) { this.responseCodeRef = value; } /** * Gets the value of the 'success' field. * @return The value of the 'success' field. */ public java.lang.Boolean getSuccess() { return success; } /** * Sets the value of the 'success' field. * @param value the value to set. */ public void setSuccess(java.lang.Boolean value) { this.success = value; } /** * Gets the value of the 'responseBytes' field. * @return The value of the 'responseBytes' field. */ public java.lang.Long getResponseBytes() { return responseBytes; } /** * Sets the value of the 'responseBytes' field. * @param value the value to set. */ public void setResponseBytes(java.lang.Long value) { this.responseBytes = value; } /** * Gets the value of the 'totalThreads' field. * @return The value of the 'totalThreads' field. */ public java.lang.Integer getTotalThreads() { return totalThreads; } /** * Sets the value of the 'totalThreads' field. * @param value the value to set. */ public void setTotalThreads(java.lang.Integer value) { this.totalThreads = value; } /** * Creates a new HttpSample RecordBuilder. * @return A new HttpSample RecordBuilder */ public static com.redsaz.lognition.convert.model.HttpSample.Builder newBuilder() { return new com.redsaz.lognition.convert.model.HttpSample.Builder(); } /** * Creates a new HttpSample RecordBuilder by copying an existing Builder. * @param other The existing builder to copy. * @return A new HttpSample RecordBuilder */ public static com.redsaz.lognition.convert.model.HttpSample.Builder newBuilder(com.redsaz.lognition.convert.model.HttpSample.Builder other) { return new com.redsaz.lognition.convert.model.HttpSample.Builder(other); } /** * Creates a new HttpSample RecordBuilder by copying an existing HttpSample instance. * @param other The existing instance to copy. * @return A new HttpSample RecordBuilder */ public static com.redsaz.lognition.convert.model.HttpSample.Builder newBuilder(com.redsaz.lognition.convert.model.HttpSample other) { return new com.redsaz.lognition.convert.model.HttpSample.Builder(other); } /** * RecordBuilder for HttpSample instances. */ public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<HttpSample> implements org.apache.avro.data.RecordBuilder<HttpSample> { private long millisOffset; private long millisElapsed; private int labelRef; private int threadNameRef; private int responseCodeRef; private boolean success; private long responseBytes; private int totalThreads; /** Creates a new Builder */ private Builder() { super(SCHEMA$); } /** * Creates a Builder by copying an existing Builder. * @param other The existing Builder to copy. */ private Builder(com.redsaz.lognition.convert.model.HttpSample.Builder other) { super(other); if (isValidValue(fields()[0], other.millisOffset)) { this.millisOffset = data().deepCopy(fields()[0].schema(), other.millisOffset); fieldSetFlags()[0] = true; } if (isValidValue(fields()[1], other.millisElapsed)) { this.millisElapsed = data().deepCopy(fields()[1].schema(), other.millisElapsed); fieldSetFlags()[1] = true; } if (isValidValue(fields()[2], other.labelRef)) { this.labelRef = data().deepCopy(fields()[2].schema(), other.labelRef); fieldSetFlags()[2] = true; } if (isValidValue(fields()[3], other.threadNameRef)) { this.threadNameRef = data().deepCopy(fields()[3].schema(), other.threadNameRef); fieldSetFlags()[3] = true; } if (isValidValue(fields()[4], other.responseCodeRef)) { this.responseCodeRef = data().deepCopy(fields()[4].schema(), other.responseCodeRef); fieldSetFlags()[4] = true; } if (isValidValue(fields()[5], other.success)) { this.success = data().deepCopy(fields()[5].schema(), other.success); fieldSetFlags()[5] = true; } if (isValidValue(fields()[6], other.responseBytes)) { this.responseBytes = data().deepCopy(fields()[6].schema(), other.responseBytes); fieldSetFlags()[6] = true; } if (isValidValue(fields()[7], other.totalThreads)) { this.totalThreads = data().deepCopy(fields()[7].schema(), other.totalThreads); fieldSetFlags()[7] = true; } } /** * Creates a Builder by copying an existing HttpSample instance * @param other The existing instance to copy. */ private Builder(com.redsaz.lognition.convert.model.HttpSample other) { super(SCHEMA$); if (isValidValue(fields()[0], other.millisOffset)) { this.millisOffset = data().deepCopy(fields()[0].schema(), other.millisOffset); fieldSetFlags()[0] = true; } if (isValidValue(fields()[1], other.millisElapsed)) { this.millisElapsed = data().deepCopy(fields()[1].schema(), other.millisElapsed); fieldSetFlags()[1] = true; } if (isValidValue(fields()[2], other.labelRef)) { this.labelRef = data().deepCopy(fields()[2].schema(), other.labelRef); fieldSetFlags()[2] = true; } if (isValidValue(fields()[3], other.threadNameRef)) { this.threadNameRef = data().deepCopy(fields()[3].schema(), other.threadNameRef); fieldSetFlags()[3] = true; } if (isValidValue(fields()[4], other.responseCodeRef)) { this.responseCodeRef = data().deepCopy(fields()[4].schema(), other.responseCodeRef); fieldSetFlags()[4] = true; } if (isValidValue(fields()[5], other.success)) { this.success = data().deepCopy(fields()[5].schema(), other.success); fieldSetFlags()[5] = true; } if (isValidValue(fields()[6], other.responseBytes)) { this.responseBytes = data().deepCopy(fields()[6].schema(), other.responseBytes); fieldSetFlags()[6] = true; } if (isValidValue(fields()[7], other.totalThreads)) { this.totalThreads = data().deepCopy(fields()[7].schema(), other.totalThreads); fieldSetFlags()[7] = true; } } /** * Gets the value of the 'millisOffset' field. * @return The value. */ public java.lang.Long getMillisOffset() { return millisOffset; } /** * Sets the value of the 'millisOffset' field. * @param value The value of 'millisOffset'. * @return This builder. */ public com.redsaz.lognition.convert.model.HttpSample.Builder setMillisOffset(long value) { validate(fields()[0], value); this.millisOffset = value; fieldSetFlags()[0] = true; return this; } /** * Checks whether the 'millisOffset' field has been set. * @return True if the 'millisOffset' field has been set, false otherwise. */ public boolean hasMillisOffset() { return fieldSetFlags()[0]; } /** * Clears the value of the 'millisOffset' field. * @return This builder. */ public com.redsaz.lognition.convert.model.HttpSample.Builder clearMillisOffset() { fieldSetFlags()[0] = false; return this; } /** * Gets the value of the 'millisElapsed' field. * @return The value. */ public java.lang.Long getMillisElapsed() { return millisElapsed; } /** * Sets the value of the 'millisElapsed' field. * @param value The value of 'millisElapsed'. * @return This builder. */ public com.redsaz.lognition.convert.model.HttpSample.Builder setMillisElapsed(long value) { validate(fields()[1], value); this.millisElapsed = value; fieldSetFlags()[1] = true; return this; } /** * Checks whether the 'millisElapsed' field has been set. * @return True if the 'millisElapsed' field has been set, false otherwise. */ public boolean hasMillisElapsed() { return fieldSetFlags()[1]; } /** * Clears the value of the 'millisElapsed' field. * @return This builder. */ public com.redsaz.lognition.convert.model.HttpSample.Builder clearMillisElapsed() { fieldSetFlags()[1] = false; return this; } /** * Gets the value of the 'labelRef' field. * @return The value. */ public java.lang.Integer getLabelRef() { return labelRef; } /** * Sets the value of the 'labelRef' field. * @param value The value of 'labelRef'. * @return This builder. */ public com.redsaz.lognition.convert.model.HttpSample.Builder setLabelRef(int value) { validate(fields()[2], value); this.labelRef = value; fieldSetFlags()[2] = true; return this; } /** * Checks whether the 'labelRef' field has been set. * @return True if the 'labelRef' field has been set, false otherwise. */ public boolean hasLabelRef() { return fieldSetFlags()[2]; } /** * Clears the value of the 'labelRef' field. * @return This builder. */ public com.redsaz.lognition.convert.model.HttpSample.Builder clearLabelRef() { fieldSetFlags()[2] = false; return this; } /** * Gets the value of the 'threadNameRef' field. * @return The value. */ public java.lang.Integer getThreadNameRef() { return threadNameRef; } /** * Sets the value of the 'threadNameRef' field. * @param value The value of 'threadNameRef'. * @return This builder. */ public com.redsaz.lognition.convert.model.HttpSample.Builder setThreadNameRef(int value) { validate(fields()[3], value); this.threadNameRef = value; fieldSetFlags()[3] = true; return this; } /** * Checks whether the 'threadNameRef' field has been set. * @return True if the 'threadNameRef' field has been set, false otherwise. */ public boolean hasThreadNameRef() { return fieldSetFlags()[3]; } /** * Clears the value of the 'threadNameRef' field. * @return This builder. */ public com.redsaz.lognition.convert.model.HttpSample.Builder clearThreadNameRef() { fieldSetFlags()[3] = false; return this; } /** * Gets the value of the 'responseCodeRef' field. * @return The value. */ public java.lang.Integer getResponseCodeRef() { return responseCodeRef; } /** * Sets the value of the 'responseCodeRef' field. * @param value The value of 'responseCodeRef'. * @return This builder. */ public com.redsaz.lognition.convert.model.HttpSample.Builder setResponseCodeRef(int value) { validate(fields()[4], value); this.responseCodeRef = value; fieldSetFlags()[4] = true; return this; } /** * Checks whether the 'responseCodeRef' field has been set. * @return True if the 'responseCodeRef' field has been set, false otherwise. */ public boolean hasResponseCodeRef() { return fieldSetFlags()[4]; } /** * Clears the value of the 'responseCodeRef' field. * @return This builder. */ public com.redsaz.lognition.convert.model.HttpSample.Builder clearResponseCodeRef() { fieldSetFlags()[4] = false; return this; } /** * Gets the value of the 'success' field. * @return The value. */ public java.lang.Boolean getSuccess() { return success; } /** * Sets the value of the 'success' field. * @param value The value of 'success'. * @return This builder. */ public com.redsaz.lognition.convert.model.HttpSample.Builder setSuccess(boolean value) { validate(fields()[5], value); this.success = value; fieldSetFlags()[5] = true; return this; } /** * Checks whether the 'success' field has been set. * @return True if the 'success' field has been set, false otherwise. */ public boolean hasSuccess() { return fieldSetFlags()[5]; } /** * Clears the value of the 'success' field. * @return This builder. */ public com.redsaz.lognition.convert.model.HttpSample.Builder clearSuccess() { fieldSetFlags()[5] = false; return this; } /** * Gets the value of the 'responseBytes' field. * @return The value. */ public java.lang.Long getResponseBytes() { return responseBytes; } /** * Sets the value of the 'responseBytes' field. * @param value The value of 'responseBytes'. * @return This builder. */ public com.redsaz.lognition.convert.model.HttpSample.Builder setResponseBytes(long value) { validate(fields()[6], value); this.responseBytes = value; fieldSetFlags()[6] = true; return this; } /** * Checks whether the 'responseBytes' field has been set. * @return True if the 'responseBytes' field has been set, false otherwise. */ public boolean hasResponseBytes() { return fieldSetFlags()[6]; } /** * Clears the value of the 'responseBytes' field. * @return This builder. */ public com.redsaz.lognition.convert.model.HttpSample.Builder clearResponseBytes() { fieldSetFlags()[6] = false; return this; } /** * Gets the value of the 'totalThreads' field. * @return The value. */ public java.lang.Integer getTotalThreads() { return totalThreads; } /** * Sets the value of the 'totalThreads' field. * @param value The value of 'totalThreads'. * @return This builder. */ public com.redsaz.lognition.convert.model.HttpSample.Builder setTotalThreads(int value) { validate(fields()[7], value); this.totalThreads = value; fieldSetFlags()[7] = true; return this; } /** * Checks whether the 'totalThreads' field has been set. * @return True if the 'totalThreads' field has been set, false otherwise. */ public boolean hasTotalThreads() { return fieldSetFlags()[7]; } /** * Clears the value of the 'totalThreads' field. * @return This builder. */ public com.redsaz.lognition.convert.model.HttpSample.Builder clearTotalThreads() { fieldSetFlags()[7] = false; return this; } @Override public HttpSample build() { try { HttpSample record = new HttpSample(); record.millisOffset = fieldSetFlags()[0] ? this.millisOffset : (java.lang.Long) defaultValue(fields()[0]); record.millisElapsed = fieldSetFlags()[1] ? this.millisElapsed : (java.lang.Long) defaultValue(fields()[1]); record.labelRef = fieldSetFlags()[2] ? this.labelRef : (java.lang.Integer) defaultValue(fields()[2]); record.threadNameRef = fieldSetFlags()[3] ? this.threadNameRef : (java.lang.Integer) defaultValue(fields()[3]); record.responseCodeRef = fieldSetFlags()[4] ? this.responseCodeRef : (java.lang.Integer) defaultValue(fields()[4]); record.success = fieldSetFlags()[5] ? this.success : (java.lang.Boolean) defaultValue(fields()[5]); record.responseBytes = fieldSetFlags()[6] ? this.responseBytes : (java.lang.Long) defaultValue(fields()[6]); record.totalThreads = fieldSetFlags()[7] ? this.totalThreads : (java.lang.Integer) defaultValue(fields()[7]); return record; } catch (Exception e) { throw new org.apache.avro.AvroRuntimeException(e); } } } private static final org.apache.avro.io.DatumWriter WRITER$ = new org.apache.avro.specific.SpecificDatumWriter(SCHEMA$); @Override public void writeExternal(java.io.ObjectOutput out) throws java.io.IOException { WRITER$.write(this, SpecificData.getEncoder(out)); } private static final org.apache.avro.io.DatumReader READER$ = new org.apache.avro.specific.SpecificDatumReader(SCHEMA$); @Override public void readExternal(java.io.ObjectInput in) throws java.io.IOException { READER$.read(this, SpecificData.getDecoder(in)); } }
3e1db9592342a93ec38951e0f16650de568a1298
2,261
java
Java
src/main/java/org/spongepowered/api/text/chat/ChatTypes.java
simon816/SpongeAPI
bd88c9166c9625e2c7500c1c02a9187523d7d266
[ "MIT" ]
2
2021-10-01T14:09:39.000Z
2021-11-17T10:35:29.000Z
src/main/java/org/spongepowered/api/text/chat/ChatTypes.java
simon816/SpongeAPI
bd88c9166c9625e2c7500c1c02a9187523d7d266
[ "MIT" ]
1
2019-08-21T10:17:46.000Z
2019-08-21T10:17:46.000Z
src/main/java/org/spongepowered/api/text/chat/ChatTypes.java
simon816/SpongeAPI
bd88c9166c9625e2c7500c1c02a9187523d7d266
[ "MIT" ]
null
null
null
37.683333
106
0.729323
12,592
/* * This file is part of SpongeAPI, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.api.text.chat; import org.spongepowered.api.util.generator.dummy.DummyObjectProvider; /** * ChatTypes is a list of the default chat types that are available in Vanilla * Minecraft. */ public final class ChatTypes { private ChatTypes() { } // SORTFIELDS:ON /** * The position right above the inventory, experience, health, item name, * etc. bars. */ public static final ChatType ACTION_BAR = DummyObjectProvider.createFor(ChatType.class, "ACTION_BAR"); /** * The standard chat position in prompt at the bottom-left. */ public static final ChatType CHAT = DummyObjectProvider.createFor(ChatType.class, "CHAT"); /** * The same position as the {@link #CHAT} position, except messages sent to * this position are still seen when chat is turned off on the Minecraft * client. */ public static final ChatType SYSTEM = DummyObjectProvider.createFor(ChatType.class, "SYSTEM"); // SORTFIELDS:OFF }
3e1db96205941fbb8eacabc1a710e8040311a8c2
491
java
Java
src/main/java/com/yangliuqing/information_security_lab4/services/PasswordHashValueGenerator.java
0102-yang/information_security_lab4
fd1bbaf580e83971326034fd93e8d0a97b80ff31
[ "Apache-2.0" ]
null
null
null
src/main/java/com/yangliuqing/information_security_lab4/services/PasswordHashValueGenerator.java
0102-yang/information_security_lab4
fd1bbaf580e83971326034fd93e8d0a97b80ff31
[ "Apache-2.0" ]
null
null
null
src/main/java/com/yangliuqing/information_security_lab4/services/PasswordHashValueGenerator.java
0102-yang/information_security_lab4
fd1bbaf580e83971326034fd93e8d0a97b80ff31
[ "Apache-2.0" ]
null
null
null
30.6875
90
0.749491
12,593
package com.yangliuqing.information_security_lab4.services; import org.springframework.stereotype.Component; import java.util.Base64; /** @author yang */ @Component public class PasswordHashValueGenerator { public static String generate(String username, String originalPassword, String salt) { int hashCode = (originalPassword + salt).hashCode(); String hashValue = hashCode + username; return Base64.getEncoder().encodeToString(hashValue.getBytes()); } }
3e1db9865a6b433f905e108e713fa04345541a74
400
java
Java
gmall-wms/src/main/java/com/atguigu/gmall/wms/mapper/WareOrderBillDetailMapper.java
gsk5476/gmall
7b3652268a169b855aab31dcf533a6512e41c1c6
[ "Apache-2.0" ]
null
null
null
gmall-wms/src/main/java/com/atguigu/gmall/wms/mapper/WareOrderBillDetailMapper.java
gsk5476/gmall
7b3652268a169b855aab31dcf533a6512e41c1c6
[ "Apache-2.0" ]
null
null
null
gmall-wms/src/main/java/com/atguigu/gmall/wms/mapper/WareOrderBillDetailMapper.java
gsk5476/gmall
7b3652268a169b855aab31dcf533a6512e41c1c6
[ "Apache-2.0" ]
null
null
null
22.111111
90
0.778894
12,594
package com.atguigu.gmall.wms.mapper; import com.atguigu.gmall.wms.entity.WareOrderBillDetailEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * 库存工作单 * * @author gsk * @email envkt@example.com * @date 2020-12-14 21:10:39 */ @Mapper public interface WareOrderBillDetailMapper extends BaseMapper<WareOrderBillDetailEntity> { }
3e1db99bac8f06f40c98d6a6e05c0cb9dfdf322f
2,032
java
Java
src/main/java/database/JOOQDatabaseInteractor.java
joschout/LazyBum
1eafa888af6d96c6f9a0bf90dc307e81f09d3f69
[ "Apache-2.0" ]
6
2019-09-06T04:04:27.000Z
2021-03-19T02:29:15.000Z
src/main/java/database/JOOQDatabaseInteractor.java
joschout/LazyBum
1eafa888af6d96c6f9a0bf90dc307e81f09d3f69
[ "Apache-2.0" ]
null
null
null
src/main/java/database/JOOQDatabaseInteractor.java
joschout/LazyBum
1eafa888af6d96c6f9a0bf90dc307e81f09d3f69
[ "Apache-2.0" ]
null
null
null
27.093333
122
0.689469
12,595
package database; import config.ProgramConfiguration; import config.ProgramConfigurationOption; import org.jooq.*; import org.jooq.conf.Settings; import org.jooq.impl.DSL; import java.sql.Connection; import java.util.List; public class JOOQDatabaseInteractor { private ProgramConfiguration programConfiguration; private DSLContext dslContext; private Schema schema; public JOOQDatabaseInteractor(Connection databaseConnection, ProgramConfiguration programConfiguration) { dslContext = DSL.using( databaseConnection, DialectManager.parse(programConfiguration.getConfigurationOption(ProgramConfigurationOption.SQL_DIALECT)), new Settings() .withRenderFormatted(true) .withAttachRecords(false) ); //TODO: https://stackoverflow.com/questions/29919830/jooq-add-schema-name-to-all-tables refreshSchema(programConfiguration); this.programConfiguration = programConfiguration; } public Schema refreshSchema(ProgramConfiguration programConfiguration){ Meta meta = dslContext.meta(); Catalog catalog = meta.getCatalog( programConfiguration.getConfigurationOption(ProgramConfigurationOption.CATALOG) ); schema = catalog.getSchema( programConfiguration.getConfigurationOption(ProgramConfigurationOption.SCHEMA) ); return schema; } public Schema refreshSchema(){ return refreshSchema(programConfiguration); } public List<Table<?>> getTables(){ return schema.getTables(); } public Table getTableByName(String name){ return schema.getTable(name); } public DSLContext getDslContext() { return dslContext; } public Schema getSchema() { return schema; } public Table getTableRepresentationWithSchemaQualifiedName(String tableName){ return DSL.table(DSL.name(schema.getName(), tableName)); } }
3e1db9ac02028b937e7436949c5d5b3b97c6bb1b
6,295
java
Java
testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/containers/KeycloakContainerTestExtension.java
roskenet/keycloak
01a0e11c8f56d265e3ae824221e766b2ac7e215e
[ "Apache-2.0" ]
12,252
2015-01-01T02:39:03.000Z
2022-03-31T19:57:55.000Z
testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/containers/KeycloakContainerTestExtension.java
roskenet/keycloak
01a0e11c8f56d265e3ae824221e766b2ac7e215e
[ "Apache-2.0" ]
4,567
2015-01-06T09:27:52.000Z
2022-03-31T21:38:13.000Z
testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/containers/KeycloakContainerTestExtension.java
roskenet/keycloak
01a0e11c8f56d265e3ae824221e766b2ac7e215e
[ "Apache-2.0" ]
5,376
2015-01-04T13:39:48.000Z
2022-03-31T19:57:56.000Z
52.89916
104
0.786338
12,596
/* * Copyright 2018 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.keycloak.testsuite.arquillian.containers; import org.jboss.arquillian.container.test.impl.ClientTestInstanceEnricher; import org.jboss.arquillian.container.test.impl.client.LocalCommandService; import org.jboss.arquillian.container.test.impl.client.container.ClientContainerControllerCreator; import org.jboss.arquillian.container.test.impl.client.container.ContainerRestarter; import org.jboss.arquillian.container.test.impl.client.container.command.ContainerCommandObserver; import org.jboss.arquillian.container.test.impl.client.deployment.ClientDeployerCreator; import org.jboss.arquillian.container.test.impl.client.deployment.DeploymentGenerator; import org.jboss.arquillian.container.test.impl.client.deployment.command.DeploymentCommandObserver; import org.jboss.arquillian.container.test.impl.client.deployment.tool.ArchiveDeploymentToolingExporter; import org.jboss.arquillian.container.test.impl.client.protocol.ProtocolRegistryCreator; import org.jboss.arquillian.container.test.impl.client.protocol.local.LocalProtocol; import org.jboss.arquillian.container.test.impl.deployment.ArquillianDeploymentAppender; import org.jboss.arquillian.container.test.impl.enricher.resource.ContainerControllerProvider; import org.jboss.arquillian.container.test.impl.enricher.resource.DeployerProvider; import org.jboss.arquillian.container.test.impl.enricher.resource.InitialContextProvider; import org.jboss.arquillian.container.test.impl.enricher.resource.RemoteResourceCommandObserver; import org.jboss.arquillian.container.test.impl.enricher.resource.URIResourceProvider; import org.jboss.arquillian.container.test.impl.enricher.resource.URLResourceProvider; import org.jboss.arquillian.container.test.impl.execution.ClientBeforeAfterLifecycleEventExecuter; import org.jboss.arquillian.container.test.impl.execution.ClientTestExecuter; import org.jboss.arquillian.container.test.impl.execution.RemoteTestExecuter; import org.jboss.arquillian.container.test.spi.client.deployment.AuxiliaryArchiveAppender; import org.jboss.arquillian.container.test.spi.client.protocol.Protocol; import org.jboss.arquillian.container.test.spi.command.CommandService; import org.jboss.arquillian.core.spi.LoadableExtension; import org.jboss.arquillian.test.impl.TestContextHandler; import org.jboss.arquillian.test.impl.context.ClassContextImpl; import org.jboss.arquillian.test.impl.context.SuiteContextImpl; import org.jboss.arquillian.test.impl.context.TestContextImpl; import org.jboss.arquillian.test.impl.enricher.resource.ArquillianResourceTestEnricher; import org.jboss.arquillian.test.spi.TestEnricher; import org.jboss.arquillian.test.spi.enricher.resource.ResourceProvider; import org.keycloak.testsuite.arquillian.ModelTestExecutor; /** * KeycloakContainerTestExtension * * This Extension Overrides the original ContainerTestExtension. * * Needed to change the behavior of ContainerEventController * to stopManualContainers @AfterSuite instead of @AfterClass * * @see base/src/main/resources/META-INF/services/org.jboss.arquillian.core.spi.LoadableExtension * @see https://issues.jboss.org/browse/ARQ-2186 * * @author vramik * @version $Revision: $ */ public class KeycloakContainerTestExtension implements LoadableExtension { @Override public void register(ExtensionBuilder builder) { registerOriginal(builder); // Overriden ContainerEventController builder.observer(KeycloakContainerEventsController.class); // overriden ContainerDeployController builder.observer(KeycloakContainerDeployController.class); } private void registerOriginal(ExtensionBuilder builder) { // Start -> Copied from TestExtension builder.context(SuiteContextImpl.class) .context(ClassContextImpl.class) .context(TestContextImpl.class); builder.observer(TestContextHandler.class) .observer(ClientTestInstanceEnricher.class); // End -> Copied from TestExtension builder.service(AuxiliaryArchiveAppender.class, ArquillianDeploymentAppender.class) .service(TestEnricher.class, ArquillianResourceTestEnricher.class) .service(Protocol.class, LocalProtocol.class) .service(CommandService.class, LocalCommandService.class) .service(ResourceProvider.class, URLResourceProvider.class) .service(ResourceProvider.class, URIResourceProvider.class) .service(ResourceProvider.class, DeployerProvider.class) .service(ResourceProvider.class, InitialContextProvider.class) .service(ResourceProvider.class, ContainerControllerProvider.class); // ContainerEventController is overriden // builder.observer(ContainerEventController.class) builder.observer(ContainerRestarter.class) .observer(DeploymentGenerator.class) .observer(ArchiveDeploymentToolingExporter.class) .observer(ProtocolRegistryCreator.class) .observer(ClientContainerControllerCreator.class) .observer(ClientDeployerCreator.class) .observer(ClientBeforeAfterLifecycleEventExecuter.class) .observer(ClientTestExecuter.class) // .observer(LocalTestExecuter.class) .observer(ModelTestExecutor.class) .observer(RemoteTestExecuter.class) .observer(DeploymentCommandObserver.class) .observer(ContainerCommandObserver.class) .observer(RemoteResourceCommandObserver.class) .observer(KeycloakContainerFeaturesController.class); } }
3e1db9bc3d11a3ea03be1080ab432be3f7e9d703
6,060
java
Java
src/main/java/uk/gov/pay/api/validation/PaymentSearchValidator.java
jonathanglassman/pay-publicapi
4cc9d5d15d5b0970bb9399613962441662f1d4ad
[ "MIT" ]
null
null
null
src/main/java/uk/gov/pay/api/validation/PaymentSearchValidator.java
jonathanglassman/pay-publicapi
4cc9d5d15d5b0970bb9399613962441662f1d4ad
[ "MIT" ]
null
null
null
src/main/java/uk/gov/pay/api/validation/PaymentSearchValidator.java
jonathanglassman/pay-publicapi
4cc9d5d15d5b0970bb9399613962441662f1d4ad
[ "MIT" ]
null
null
null
48.870968
158
0.675413
12,597
package uk.gov.pay.api.validation; import uk.gov.pay.api.auth.Account; import uk.gov.pay.api.exception.PaymentValidationException; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import static org.apache.commons.lang3.StringUtils.join; import static org.eclipse.jetty.util.StringUtil.isBlank; import static uk.gov.pay.api.model.PaymentError.Code.SEARCH_PAYMENTS_VALIDATION_ERROR; import static uk.gov.pay.api.model.PaymentError.aPaymentError; import static uk.gov.pay.api.model.TokenPaymentType.DIRECT_DEBIT; import static uk.gov.pay.api.validation.MaxLengthValidator.isValid; import static uk.gov.pay.api.validation.PaymentRequestValidator.AGREEMENT_ID_MAX_LENGTH; import static uk.gov.pay.api.validation.PaymentRequestValidator.CARD_BRAND_MAX_LENGTH; import static uk.gov.pay.api.validation.PaymentRequestValidator.EMAIL_MAX_LENGTH; import static uk.gov.pay.api.validation.PaymentRequestValidator.REFERENCE_MAX_LENGTH; import static uk.gov.pay.api.validation.SearchValidator.validateDisplaySizeIfNotNull; import static uk.gov.pay.api.validation.SearchValidator.validateFromDate; import static uk.gov.pay.api.validation.SearchValidator.validatePageIfNotNull; import static uk.gov.pay.api.validation.SearchValidator.validateToDate; public class PaymentSearchValidator { private static final int FIRST_DIGITS_CARD_NUMBER_LENGTH = 6; private static final int LAST_DIGITS_CARD_NUMBER_LENGTH = 4; // we should really find a way to not have this anywhere but in the connector... private static final Set<String> VALID_CARD_PAYMENT_STATES = new HashSet<>(Arrays.asList("created", "started", "submitted", "success", "failed", "cancelled", "error")); private static final Set<String> VALID_DIRECT_DEBIT_STATES = new HashSet<>(Arrays.asList("started", "pending", "success", "failed", "cancelled")); public static void validateSearchParameters(Account account, String state, String reference, String email, String cardBrand, String fromDate, String toDate, String pageNumber, String displaySize, String agreementId, String firstDigitsCardNumber, String lastDigitsCardNumber) { List<String> validationErrors = new LinkedList<>(); try { validateState(account, state, validationErrors); validateReference(reference, validationErrors); validateEmail(email, validationErrors); validateCardBrand(cardBrand, validationErrors); validateFromDate(fromDate, validationErrors); validateToDate(toDate, validationErrors); validatePageIfNotNull(pageNumber, validationErrors); validateDisplaySizeIfNotNull(displaySize, validationErrors); validateAgreement(agreementId, validationErrors); validateFirstDigitsCardNumber(firstDigitsCardNumber, validationErrors); validateLastDigitsCardNumber(lastDigitsCardNumber, validationErrors); } catch (Exception e) { throw new PaymentValidationException(aPaymentError(SEARCH_PAYMENTS_VALIDATION_ERROR, join(validationErrors, ", "), e.getMessage())); } if (!validationErrors.isEmpty()) { throw new PaymentValidationException(aPaymentError(SEARCH_PAYMENTS_VALIDATION_ERROR, join(validationErrors, ", "))); } } private static void validateAgreement(String agreement, List<String> validationErrors) { if (!isValid(agreement, AGREEMENT_ID_MAX_LENGTH)){ validationErrors.add("agreement_id"); } } private static void validateFirstDigitsCardNumber(String firstDigitsCardNumber, List<String> validationErrors) { if (!ExactLengthValidator.isValid(firstDigitsCardNumber, FIRST_DIGITS_CARD_NUMBER_LENGTH) || !NumericValidator.isValidOrNull(firstDigitsCardNumber)) { validationErrors.add("first_digits_card_number"); } } private static void validateLastDigitsCardNumber(String lastDigitsCardNumber, List<String> validationErrors) { if (!ExactLengthValidator.isValid(lastDigitsCardNumber, LAST_DIGITS_CARD_NUMBER_LENGTH) || !NumericValidator.isValidOrNull(lastDigitsCardNumber)) { validationErrors.add("last_digits_card_number"); } } private static void validateReference(String reference, List<String> validationErrors) { if (!isValid(reference, REFERENCE_MAX_LENGTH)) { validationErrors.add("reference"); } } private static void validateEmail(String email, List<String> validationErrors) { if (!isValid(email, EMAIL_MAX_LENGTH)) { validationErrors.add("email"); } } private static void validateCardBrand(String cardBrand, List<String> validationErrors) { if (!isValid(cardBrand, CARD_BRAND_MAX_LENGTH)) { validationErrors.add("card_brand"); } } private static void validateState(Account account, String state, List<String> validationErrors) { if (!validateState(account, state)) { validationErrors.add("state"); } } private static boolean validateState(Account account, String state) { return isBlank(state) || (isDirectDebitAccount(account) ? VALID_DIRECT_DEBIT_STATES.contains(state) : VALID_CARD_PAYMENT_STATES.contains(state)); } private static boolean isDirectDebitAccount(Account account) { return account.getPaymentType().equals(DIRECT_DEBIT); } }
3e1dbb54c955e8a5e00c6c6c55862028dd5047c6
878
java
Java
src/battlecraft/entity/structure/BarrackRockWorker.java
valcol/BattleCraft
a64ba988515ab816f9e386e0cbfb9bae94626f81
[ "MIT" ]
null
null
null
src/battlecraft/entity/structure/BarrackRockWorker.java
valcol/BattleCraft
a64ba988515ab816f9e386e0cbfb9bae94626f81
[ "MIT" ]
null
null
null
src/battlecraft/entity/structure/BarrackRockWorker.java
valcol/BattleCraft
a64ba988515ab816f9e386e0cbfb9bae94626f81
[ "MIT" ]
null
null
null
35.12
152
0.777904
12,598
package battlecraft.entity.structure; import java.awt.Canvas; import java.awt.Point; import java.awt.Rectangle; import battlecraft.LevelManager; import battlecraft.entity.unit.Worker; import battlecraft.enums.Ressources; import battlecraft.enums.Teams; public class BarrackRockWorker extends Barrack { public BarrackRockWorker(Canvas defaultCanvas, Point position, String spritePathMiddleAge, String imagePathSciFi, Rectangle BOUNDING_BOX, Teams team) { super(defaultCanvas, position, spritePathMiddleAge, imagePathSciFi, BOUNDING_BOX, team, new BarrackCosts(Ressources.ORE, 1000, Ressources.WOOD, 200)); } @Override public void createUnit() { Point p = new Point((int) (this.position.x+(Math.random() * (10))+30), (int) (this.position.y+(Math.random() * (10))+30)); LevelManager.getInstance().addWorker((Worker) unit.createRockWorker(defaultCanvas, p)); } }
3e1dbe61767c26554ff5fa7fedf3524fbf476490
194
java
Java
src/MaasHesaplayici/Main.java
kadirsunman/kodluyoruzpratik
e511975877de365738b26db40eb7bd561820cb73
[ "MIT" ]
null
null
null
src/MaasHesaplayici/Main.java
kadirsunman/kodluyoruzpratik
e511975877de365738b26db40eb7bd561820cb73
[ "MIT" ]
null
null
null
src/MaasHesaplayici/Main.java
kadirsunman/kodluyoruzpratik
e511975877de365738b26db40eb7bd561820cb73
[ "MIT" ]
null
null
null
21.555556
65
0.64433
12,599
package MaasHesaplayici; public class Main { public static void main(String[] args) { Employee employee = new Employee("Kadir", 7000, 40,2019); employee.toString(); } }
3e1dc0ea60bba895f9a0ad99f3b9d4b45419b4e9
1,046
java
Java
myzstu/myzstu-boot/src/main/java/club/zstuca/myzstu/boot/scheduled/HealthDeclaration.java
shentuzhigang/MyZSTU
691ef70279d8d249f21e42141270aa2ffeb741f9
[ "MIT" ]
2
2021-05-28T14:43:16.000Z
2021-07-25T10:36:42.000Z
myzstu/myzstu-boot/src/main/java/club/zstuca/myzstu/boot/scheduled/HealthDeclaration.java
shentuzhigang/MyZSTU
691ef70279d8d249f21e42141270aa2ffeb741f9
[ "MIT" ]
null
null
null
myzstu/myzstu-boot/src/main/java/club/zstuca/myzstu/boot/scheduled/HealthDeclaration.java
shentuzhigang/MyZSTU
691ef70279d8d249f21e42141270aa2ffeb741f9
[ "MIT" ]
null
null
null
32.6875
111
0.735182
12,600
package club.zstuca.myzstu.boot.scheduled; import club.zstuca.myzstu.spyder.ezstu.AutoHealthDeclarationServiceImpl; import lombok.SneakyThrows; import love.forte.simbot.api.sender.MsgSender; import love.forte.simbot.bot.BotManager; import org.springframework.scheduling.annotation.Scheduled; /** * @author ShenTuZhiGang * @version 1.0.0 * @date 2020-09-24 15:10 */ public class HealthDeclaration { private BotManager botManager; public HealthDeclaration(BotManager botManager){ this.botManager = botManager; } @SneakyThrows @Scheduled(cron = "0 0 6 * * ? *") public void execute() { MsgSender msgSender = botManager.getDefaultBot().getSender(); String username = "2018329621200"; String password = "081639"; AutoHealthDeclarationServiceImpl autoHealthDeclarationService = new AutoHealthDeclarationServiceImpl(); System.out.println(autoHealthDeclarationService.autoService(username, password )); msgSender.SENDER.sendPrivateMsg("1600337300", "申报成功"); } }
3e1dc11920002e85c18bfed07c4768d72de70fec
3,529
java
Java
spring-security-core/src/main/java/com/xh/security/core/authentiation/oauth2/support/request/AuthFacebookRequest.java
ht16519/spring-security-parent
8fc39b169fa9d77292ec1ce2fda19ced965152f8
[ "MIT" ]
null
null
null
spring-security-core/src/main/java/com/xh/security/core/authentiation/oauth2/support/request/AuthFacebookRequest.java
ht16519/spring-security-parent
8fc39b169fa9d77292ec1ce2fda19ced965152f8
[ "MIT" ]
null
null
null
spring-security-core/src/main/java/com/xh/security/core/authentiation/oauth2/support/request/AuthFacebookRequest.java
ht16519/spring-security-parent
8fc39b169fa9d77292ec1ce2fda19ced965152f8
[ "MIT" ]
null
null
null
37.542553
102
0.682063
12,601
package com.xh.security.core.authentiation.oauth2.support.request; import com.alibaba.fastjson.JSONObject; import com.xh.security.core.authentiation.oauth2.support.cache.AuthStateCache; import com.xh.security.core.authentiation.oauth2.support.config.AuthConfig; import com.xh.security.core.authentiation.oauth2.support.config.AuthDefaultSource; import com.xh.security.core.authentiation.oauth2.support.enums.AuthUserGender; import com.xh.security.core.authentiation.oauth2.support.exception.AuthException; import com.xh.security.core.authentiation.oauth2.support.model.AuthCallback; import com.xh.security.core.authentiation.oauth2.support.model.AuthToken; import com.xh.security.core.authentiation.oauth2.support.model.AuthUser; import com.xh.security.core.authentiation.oauth2.support.utils.UrlBuilder; /** * Facebook登录 */ public class AuthFacebookRequest extends AuthDefaultRequest { public AuthFacebookRequest(AuthConfig config) { super(config, AuthDefaultSource.FACEBOOK); } public AuthFacebookRequest(AuthConfig config, AuthStateCache authStateCache) { super(config, AuthDefaultSource.FACEBOOK, authStateCache); } @Override protected AuthToken getAccessToken(AuthCallback authCallback) { String response = doPostAuthorizationCode(authCallback.getCode()); JSONObject accessTokenObject = JSONObject.parseObject(response); this.checkResponse(accessTokenObject); return AuthToken.builder() .accessToken(accessTokenObject.getString("access_token")) .expireIn(accessTokenObject.getIntValue("expires_in")) .tokenType(accessTokenObject.getString("token_type")) .build(); } @Override protected AuthUser getUserInfo(AuthToken authToken) { String userInfo = doGetUserInfo(authToken); JSONObject object = JSONObject.parseObject(userInfo); this.checkResponse(object); return AuthUser.builder() .uuid(object.getString("id")) .username(object.getString("name")) .nickname(object.getString("name")) .avatar(getUserPicture(object)) .location(object.getString("locale")) .email(object.getString("email")) .gender(AuthUserGender.getRealGender(object.getString("gender"))) .token(authToken) .source(source.toString()) .build(); } private String getUserPicture(JSONObject object) { String picture = null; if (object.containsKey("picture")) { JSONObject pictureObj = object.getJSONObject("picture"); pictureObj = pictureObj.getJSONObject("data"); if (null != pictureObj) { picture = pictureObj.getString("url"); } } return picture; } /** * 返回获取userInfo的url * * @param authToken 用户token * @return 返回获取userInfo的url */ @Override protected String userInfoUrl(AuthToken authToken) { return UrlBuilder.fromBaseUrl(source.userInfo()) .queryParam("access_token", authToken.getAccessToken()) .queryParam("fields", "id,name,birthday,gender,hometown,email,devices,picture.width(400)") .build(); } /** * 检查响应内容是否正确 * * @param object 请求响应内容 */ private void checkResponse(JSONObject object) { if (object.containsKey("error")) { throw new AuthException(object.getJSONObject("error").getString("message")); } } }
3e1dc180d53133901ddf83c60825ecd25a636cf0
94
java
Java
server/test-data/ext/src/Test.java
filosov/extender
d227539d6f2f54cdb39332770315fa814826d29d
[ "MIT" ]
22
2020-05-19T08:36:42.000Z
2021-12-02T20:15:22.000Z
server/test-data/ext/src/Test.java
filosov/extender
d227539d6f2f54cdb39332770315fa814826d29d
[ "MIT" ]
24
2020-05-27T17:42:02.000Z
2022-02-21T12:00:47.000Z
server/test-data/ext/src/Test.java
filosov/extender
d227539d6f2f54cdb39332770315fa814826d29d
[ "MIT" ]
8
2020-05-19T14:35:22.000Z
2022-01-24T00:38:35.000Z
13.428571
29
0.574468
12,602
package com.defold; class Test { static String doStuff() { return "test"; } }
3e1dc187fc23ace090954550976059581cf22897
1,069
java
Java
WEB/HMPatrimonioWS/src/br/senai/hm/jpa/InconsistenciaJPA.java
CaioFranco/HMPatrimonio
164446fb598db036b874668d8964ead688f1a712
[ "Apache-2.0" ]
null
null
null
WEB/HMPatrimonioWS/src/br/senai/hm/jpa/InconsistenciaJPA.java
CaioFranco/HMPatrimonio
164446fb598db036b874668d8964ead688f1a712
[ "Apache-2.0" ]
null
null
null
WEB/HMPatrimonioWS/src/br/senai/hm/jpa/InconsistenciaJPA.java
CaioFranco/HMPatrimonio
164446fb598db036b874668d8964ead688f1a712
[ "Apache-2.0" ]
null
null
null
22.744681
60
0.768007
12,603
package br.senai.hm.jpa; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import org.springframework.stereotype.Repository; import br.senai.hm.dao.InconsistenciaDAO; import br.senai.hm.modelo.Inconsistencia; @Repository public class InconsistenciaJPA implements InconsistenciaDAO{ @PersistenceContext private EntityManager manager; @Override public void inserir(Inconsistencia i) { //manager.getTransaction().begin(); manager.persist(i);; //manager.getTransaction().commit(); } @Override public void alterar(Inconsistencia i) { // manager.getTransaction().begin(); manager.merge(i); // manager.getTransaction().commit(); } @Override public List<Inconsistencia> buscarTodos() { TypedQuery<Inconsistencia> query = manager.createQuery( "SELECT i FROM Inconsistencia i", Inconsistencia.class); return query.getResultList(); } @Override public Inconsistencia buscarId(Long id) { return manager.find(Inconsistencia.class, id); } }
3e1dc1cc4ca5440008079a654d6bbf0396a29836
1,996
java
Java
spring-boot-upload-file/src/main/java/com/qingtian/entity/FileInfo.java
mcrwayfun/spring-boot-learning
f5d09312b690193f15a992e0418bd01850e27ff5
[ "Apache-2.0" ]
2
2018-07-04T15:18:41.000Z
2020-08-27T06:49:50.000Z
spring-boot-upload-file/src/main/java/com/qingtian/entity/FileInfo.java
mcrwayfun/spring-boot-learning
f5d09312b690193f15a992e0418bd01850e27ff5
[ "Apache-2.0" ]
null
null
null
spring-boot-upload-file/src/main/java/com/qingtian/entity/FileInfo.java
mcrwayfun/spring-boot-learning
f5d09312b690193f15a992e0418bd01850e27ff5
[ "Apache-2.0" ]
3
2019-06-26T07:08:39.000Z
2021-07-02T02:14:45.000Z
16.915254
70
0.588677
12,604
package com.qingtian.entity; import java.io.Serializable; import java.util.Date; /** * @author mcrwayfun * @version 1.0 * @description * @date Created in 2018/7/31 */ public class FileInfo implements Serializable { /** * 主键,自增 */ private Long id; /** * 文件名(存储名) */ private String fileName; /** * 文件存储路径 */ private String filePath; /** * 文件类型 */ private String fileType; /** * 文件名(原名) */ private String fileOriginalFileName; /** * 文件大小 */ private Long fileSize; private Date createTime; private String createUser; /** * 无参构造函数,防止反序列化异常 */ public FileInfo() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } public String getFileType() { return fileType; } public void setFileType(String fileType) { this.fileType = fileType; } public String getFileOriginalFileName() { return fileOriginalFileName; } public void setFileOriginalFileName(String fileOriginalFileName) { this.fileOriginalFileName = fileOriginalFileName; } public Long getFileSize() { return fileSize; } public void setFileSize(Long fileSize) { this.fileSize = fileSize; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getCreateUser() { return createUser; } public void setCreateUser(String createUser) { this.createUser = createUser; } }
3e1dc404226dd7c10b7e4432c18d258bf15751c5
1,393
java
Java
src/br/edu/utfpr/cm/pi/modal/Fornecedor.java
macieljp/SysHotelPostgreSQL
d0a40c14fedda1b7bd8331c9d88f9624a7b3cf9c
[ "MIT" ]
null
null
null
src/br/edu/utfpr/cm/pi/modal/Fornecedor.java
macieljp/SysHotelPostgreSQL
d0a40c14fedda1b7bd8331c9d88f9624a7b3cf9c
[ "MIT" ]
null
null
null
src/br/edu/utfpr/cm/pi/modal/Fornecedor.java
macieljp/SysHotelPostgreSQL
d0a40c14fedda1b7bd8331c9d88f9624a7b3cf9c
[ "MIT" ]
null
null
null
16.987805
52
0.569993
12,605
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package br.edu.utfpr.cm.pi.modal; import java.io.Serializable; import java.util.List; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToMany; /** * * @author JoaoPaulo */ @Entity public class Fornecedor implements Serializable { @Id private Integer id; private String nome; private String cnpj; @OneToMany private List<Produto> produto; /** * @return the id */ public Integer getId() { return id; } /** * @param id the id to set */ public void setId(Integer id) { this.id = id; } /** * @return the nome */ public String getNome() { return nome; } /** * @param nome the nome to set */ public void setNome(String nome) { this.nome = nome; } /** * @return the cnpj */ public String getCnpj() { return cnpj; } /** * @param cnpj the cnpj to set */ public void setCnpj(String cnpj) { this.cnpj = cnpj; } public List<Produto> getProduto() { return produto; } public void setProduto(List<Produto> produto) { this.produto = produto; } @Override public String toString() { return nome; } }
3e1dc5ab3fb8eab18e6410982e55c3f5caa99427
10,260
java
Java
colormipsearch-tools/src/main/java/org/janelia/colormipsearch/cmd/ReplaceMIPsMetadataAttributesCmd.java
JaneliaSciComp/colormipsearch
79c03650b805d5ba281704f4036ee56096d6dcea
[ "BSD-3-Clause" ]
null
null
null
colormipsearch-tools/src/main/java/org/janelia/colormipsearch/cmd/ReplaceMIPsMetadataAttributesCmd.java
JaneliaSciComp/colormipsearch
79c03650b805d5ba281704f4036ee56096d6dcea
[ "BSD-3-Clause" ]
1
2022-01-12T17:32:19.000Z
2022-01-12T17:32:19.000Z
colormipsearch-tools/src/main/java/org/janelia/colormipsearch/cmd/ReplaceMIPsMetadataAttributesCmd.java
JaneliaSciComp/colormipsearch
79c03650b805d5ba281704f4036ee56096d6dcea
[ "BSD-3-Clause" ]
null
null
null
39.922179
145
0.587719
12,606
package org.janelia.colormipsearch.cmd; import java.io.File; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.beust.jcommander.ParametersDelegate; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.janelia.colormipsearch.api.cdmips.MIPMetadata; import org.janelia.colormipsearch.api.cdmips.MIPsUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ReplaceMIPsMetadataAttributesCmd extends AbstractCmd { private static final Logger LOG = LoggerFactory.getLogger(ReplaceMIPsMetadataAttributesCmd.class); @Parameters(commandDescription = "Replace metadata attributes") static class ReplaceMIPsMetadataAttributesArgs extends AbstractCmdArgs { @Parameter(names = {"--new-mips-attributes", "-attrs"}, required = true, description = "File containing the MIPS with the new attributes") String targetMIPsFilename; @Parameter(names = {"--input-dirs"}, variableArity = true, description = "Directory with JSON files whose image URLs have to be changed") List<String> inputDirs; @Parameter(names = {"--input-files"}, variableArity = true, description = "JSON file whose image URLs have to be changed") List<String> inputFiles; @Parameter(names = {"--id-field"}, required = true, description = "ID field name") String idFieldName; @Parameter(names = {"--fields-toUpdate"}, description = "Fields to be updated", variableArity = true) Set<String> fieldsToUpdate = new HashSet<>(); @ParametersDelegate final CommonArgs commonArgs; ReplaceMIPsMetadataAttributesArgs(CommonArgs commonArgs) { this.commonArgs = commonArgs; } @Override List<String> validate() { List<String> errors = new ArrayList<>(); boolean inputFound = inputDirs != null || CollectionUtils.isNotEmpty(inputFiles); if (!inputFound) { errors.add("No input file or directory containing results has been specified"); } return errors; } Path getOutputDir() { if (StringUtils.isNotBlank(commonArgs.outputDir)) { return Paths.get(commonArgs.outputDir); } else { return null; } } } private final ReplaceMIPsMetadataAttributesArgs args; ReplaceMIPsMetadataAttributesCmd(String commandName, CommonArgs commonArgs) { super(commandName); args = new ReplaceMIPsMetadataAttributesArgs(commonArgs); } @Override ReplaceMIPsMetadataAttributesArgs getArgs() { return args; } @Override void execute() { CmdUtils.createOutputDirs(args.getOutputDir()); replaceMIPsURLs(args); } private void replaceMIPsURLs(ReplaceMIPsMetadataAttributesArgs args) { ObjectMapper mapper = new ObjectMapper() .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // we need to index by the value of parameter id-field; to match the previous implementation, // we need to make explicit that if --id-field = id, it really means relatedImageRefId: final String idFieldName; if (args.idFieldName == "id") { idFieldName = "relatedImageRefId"; } else { idFieldName = args.idFieldName; } Map<String, MIPMetadata> indexedTargetMIPs = MIPsUtils.readMIPsFromJSON(args.targetMIPsFilename, 0, -1, Collections.emptySet(), mapper) .stream() .collect(Collectors.groupingBy( mipInfo -> StringUtils.defaultIfBlank(getFieldValueMIP(mipInfo, idFieldName), mipInfo.getId()), Collectors.collectingAndThen( Collectors.toList(), r -> r.get(0) ))); List<String> inputFileNames; if (CollectionUtils.isNotEmpty(args.inputFiles)) { inputFileNames = args.inputFiles; } else if (CollectionUtils.isNotEmpty(args.inputDirs)) { inputFileNames = args.inputDirs.stream() .flatMap(rd -> { try { return Files.find(Paths.get(rd), 1, (p, fa) -> fa.isRegularFile()); } catch (IOException e) { throw new UncheckedIOException(e); } }) .map(p -> p.toString()) .collect(Collectors.toList()); } else { inputFileNames = Collections.emptyList(); } replaceMIPsMetadataAttributes( inputFileNames, args.idFieldName, args.fieldsToUpdate, indexedTargetMIPs, args.getOutputDir()); } private void replaceMIPsMetadataAttributes(List<String> inputFileNames, String idFieldName, Set<String> atributeNames, Map<String, MIPMetadata> indexedTargetMIPs, Path outputDir) { ObjectMapper mapper = new ObjectMapper() .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); inputFileNames.stream().parallel() .forEach(fn -> { File f = new File(fn); JsonNode jsonContent = readJSONFile(f, mapper); streamJSONNodes(jsonContent).forEach(jsonNode -> { String id = getFieldValue(jsonNode, idFieldName); if (id == null) { return; // No <id> field found } MIPMetadata targetMIP = indexedTargetMIPs.get(id); if (targetMIP == null) { LOG.warn("No MIP with new attributes found for {}", id); } else { ObjectNode newAttributesNode = mapper.valueToTree(targetMIP); atributeNames.forEach(a -> replaceMIPsAttributes(id, newAttributesNode, a, jsonNode)); } }); writeJSONFile(jsonContent, CmdUtils.getOutputFile(outputDir, f), mapper); }); } private JsonNode readJSONFile(File f, ObjectMapper mapper) { try { LOG.info("Reading {}", f); return mapper.readTree(f); } catch (IOException e) { LOG.error("Error reading json file {}", f, e); throw new UncheckedIOException(e); } } private void writeJSONFile(JsonNode content, File f, ObjectMapper mapper) { try { if (f == null) { mapper.writerWithDefaultPrettyPrinter().writeValue(System.out, content); } else { LOG.info("Writing {}", f); mapper.writerWithDefaultPrettyPrinter().writeValue(f, content); } } catch (IOException e) { LOG.error("Error writing json file {}", f, e); throw new UncheckedIOException(e); } } private Stream<ObjectNode> streamJSONNodes(JsonNode jsonContent) { if (jsonContent.isArray()) { return StreamSupport.stream(jsonContent.spliterator(), false) .map(jsonNode -> (ObjectNode) jsonNode); } else { return jsonContent.findValues("results").stream() .map(jsonNode -> (ArrayNode) jsonNode) .flatMap(resultsNode -> StreamSupport.stream(resultsNode.spliterator(), false)) .map(jsonNode -> (ObjectNode) jsonNode); } } private void replaceMIPsAttributes(String id, ObjectNode srcAttributes, String attributeName, ObjectNode toUpdate) { String attributeValue = getFieldValue(srcAttributes, attributeName); if (StringUtils.isNotBlank(attributeValue)) { LOG.info("Setting {} for {} to {}", attributeName, id, attributeValue); toUpdate.put(attributeName, attributeValue); } } private String getFieldValue(ObjectNode node, String fieldName) { String value; JsonNode fieldNode = node.get(fieldName); if (fieldNode != null) { return fieldNode.textValue(); } else { return null; } } /** * like getFieldValue, but for MIPs instead of json nodes; only supports * a few attributes, the ones plausibly likely to be needed for the purpose of identifying * MIPs for indexing */ public String getFieldValueMIP(MIPMetadata mipInfo, String attrName) { if (StringUtils.isBlank(attrName)) { return ""; } else { switch(attrName) { case "id": return mipInfo.getId(); case "relatedImageRefId": return mipInfo.getRelatedImageRefId(); case "publishedName": return mipInfo.getPublishedName(); case "slideCode": return mipInfo.getSlideCode(); case "imageName": return mipInfo.getImageName(); default: return ""; } } } }
3e1dc5c6321c8d6dc226bbf9e639c0ff6a64890d
1,063
java
Java
mail/src/com/fancige/servlet/Preference.java
fancige/exercise
63c025710581782e982ab53c54c2f26bb414c448
[ "MIT" ]
null
null
null
mail/src/com/fancige/servlet/Preference.java
fancige/exercise
63c025710581782e982ab53c54c2f26bb414c448
[ "MIT" ]
null
null
null
mail/src/com/fancige/servlet/Preference.java
fancige/exercise
63c025710581782e982ab53c54c2f26bb414c448
[ "MIT" ]
null
null
null
25.926829
72
0.758231
12,607
package com.fancige.servlet; import java.io.IOException; import java.util.Properties; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.fancige.manager.FileManager; @WebServlet("/preference") public class Preference extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); String locale = req.getParameter("locale"); Properties props = FileManager.loadProperties(FileManager.CONF + "global.txt"); String list = props.getProperty("localeList"); String[] ls = list.split(","); for (String l : ls) { if (l.equals(locale)) { session.setAttribute("locale", locale); break; } } resp.sendRedirect(req.getHeader("Referer")); } }
3e1dc73e87f4971adc25efcba7109c2a9cd3b330
1,853
java
Java
core/src/test/java/org/apache/any23/extractor/ExtractionAPITest.java
JulioCCBUcuenca/any23
3475ebd6708e7857cbb021d3c51961148cb8ce87
[ "Apache-2.0" ]
null
null
null
core/src/test/java/org/apache/any23/extractor/ExtractionAPITest.java
JulioCCBUcuenca/any23
3475ebd6708e7857cbb021d3c51961148cb8ce87
[ "Apache-2.0" ]
1
2018-08-08T09:36:08.000Z
2018-08-08T09:36:08.000Z
core/src/test/java/org/apache/any23/extractor/ExtractionAPITest.java
JulioCCBUcuenca/any23
3475ebd6708e7857cbb021d3c51961148cb8ce87
[ "Apache-2.0" ]
null
null
null
39.425532
98
0.746897
12,608
/* * 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.any23.extractor; import org.junit.Assert; import org.apache.any23.extractor.example.ExampleExtractor; import org.apache.any23.rdf.RDFUtils; import org.apache.any23.writer.CountingTripleHandler; import org.junit.Test; import org.eclipse.rdf4j.model.IRI; /** * Tests the <i>extraction</i> scenario. */ public class ExtractionAPITest { private static final String exampleDoc = "http://example.com/"; private static final IRI uri = RDFUtils.iri(exampleDoc); @Test public void testDirectInstantiation() throws Exception { CountingTripleHandler out = new CountingTripleHandler(); ExampleExtractor extractor = new ExampleExtractor(); ExtractionContext extractionContext = new ExtractionContext("extractor-name", uri); ExtractionResultImpl writer = new ExtractionResultImpl(extractionContext, extractor, out); extractor.run(ExtractionParameters.newDefault(), extractionContext, uri, writer); writer.close(); Assert.assertEquals(1, out.getCount()); } }
3e1dc772addce16ad9095fec992170c994706f55
1,796
java
Java
javafxWithDi/src/main/java/de/tmosebach/snippets/javafxwithdi/MainApp.java
TMosebach/snippets
fe29442464bb93b7a1183c98723b553ba59fdfff
[ "MIT" ]
null
null
null
javafxWithDi/src/main/java/de/tmosebach/snippets/javafxwithdi/MainApp.java
TMosebach/snippets
fe29442464bb93b7a1183c98723b553ba59fdfff
[ "MIT" ]
null
null
null
javafxWithDi/src/main/java/de/tmosebach/snippets/javafxwithdi/MainApp.java
TMosebach/snippets
fe29442464bb93b7a1183c98723b553ba59fdfff
[ "MIT" ]
2
2019-02-12T21:13:55.000Z
2019-02-20T21:15:35.000Z
30.440678
78
0.726615
12,609
package de.tmosebach.snippets.javafxwithdi; import javafx.application.Application; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; @SpringBootApplication public class MainApp extends Application { private static final Logger log = LoggerFactory.getLogger(MainApp.class); private static String[] args; private ConfigurableApplicationContext applicationContext; @Autowired private SpringFXMLLoader fxmlLoader; public static void main(String[] args) throws Exception { MainApp.args = args; launch(args); } @Override public void init() throws Exception { applicationContext = SpringApplication.run(getClass(), args); applicationContext.getAutowireCapableBeanFactory().autowireBean(this); } public void start(Stage stage) throws Exception { log.info("Starting Hello JavaFX and Maven demonstration application"); String fxmlFile = "/fxml/hello.fxml"; log.debug("Loading FXML for main view from: {}", fxmlFile); Parent rootNode = (Parent)fxmlLoader.load(getClass().getResource(fxmlFile)); log.debug("Showing JFX scene"); Scene scene = new Scene(rootNode, 400, 200); scene.getStylesheets().add("/styles/styles.css"); stage.setTitle("Hello JavaFX and Maven"); stage.setScene(scene); stage.show(); } @Override public void stop() throws Exception { applicationContext.stop(); } }
3e1dc871c34186774eca03df78abc9b82722ad2b
3,864
java
Java
src/net/sf/jargsemsat/jargsemsat/datastructures/Labelling.java
jeris90/fusionAF
154be24a50be5a30984c77bc4bf2a8fb158a2897
[ "MIT" ]
4
2021-03-25T07:31:47.000Z
2021-09-06T14:42:37.000Z
src/net/sf/jargsemsat/jargsemsat/datastructures/Labelling.java
jeris90/fusionAF
154be24a50be5a30984c77bc4bf2a8fb158a2897
[ "MIT" ]
null
null
null
src/net/sf/jargsemsat/jargsemsat/datastructures/Labelling.java
jeris90/fusionAF
154be24a50be5a30984c77bc4bf2a8fb158a2897
[ "MIT" ]
2
2020-04-27T20:19:32.000Z
2020-05-11T21:31:40.000Z
27.65
80
0.691811
12,610
/** * This file is part of jArgSemSAT * * Copyright (c) 2015 Federico Cerutti <upchh@example.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package net.sf.jargsemsat.jargsemsat.datastructures; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class Labelling { public static final String lab_in = "in"; public static final String lab_out = "out"; public static final String lab_undec = "undec"; private Map<String, String> labelling = null; private Set<String> in = null; private Set<String> out = null; private Set<String> undec = null; public Labelling() { this.labelling = new HashMap<String, String>(); this.in = new HashSet<String>(); this.out = new HashSet<String>(); this.undec = new HashSet<String>(); } public boolean copyFrom(Labelling another) { this.labelling.clear(); this.in.clear(); this.out.clear(); this.undec.clear(); for (Iterator<String> inarg = another.inargs().iterator(); inarg .hasNext();) this.add_label(inarg.next(), Labelling.lab_in); for (Iterator<String> outarg = another.outargs().iterator(); outarg .hasNext();) this.add_label(outarg.next(), Labelling.lab_out); for (Iterator<String> undecarg = another.undecargs() .iterator(); undecarg.hasNext();) this.add_label(undecarg.next(), Labelling.lab_undec); return true; } public void add_label(String arg, String l) { this.labelling.put(arg, l); if (l.compareTo(lab_in) == 0) this.in.add(arg); else if (l.compareTo(lab_out) == 0) this.out.add(arg); else if (l.compareTo(lab_undec) == 0) this.undec.add(arg); } public Set<String> inargs() { return this.in; } public Set<String> outargs() { return this.out; } public Set<String> undecargs() { return this.undec; } public Labelling clone() { Labelling ret = new Labelling(); Iterator<Entry<String, String>> it = this.labelling.entrySet() .iterator(); while (it.hasNext()) { Map.Entry<String, String> pair = (Map.Entry<String, String>) it .next(); ret.add_label(pair.getKey(), pair.getValue()); } return ret; } public boolean empty() { return this.labelling.isEmpty() && this.in.isEmpty() && this.out.isEmpty() && this.undec.isEmpty(); } public HashSet<String> getExtension() { return (HashSet<String>) (this.in); } @Override public String toString() { String ret = "["; Iterator<String> it = this.in.iterator(); while (it.hasNext()) { ret += it.next(); if (it.hasNext()) ret += ","; } ret += "]"; return ret; } public boolean equals(Labelling l) { if (this.inargs().equals(l.inargs()) && this.outargs().equals(l.outargs()) && this.undecargs().equals(l.undecargs())) return true; return false; } }
3e1dc92c1c4ff1508369f1726470430f590436fa
20,434
java
Java
java/com/google/gerrit/server/mail/send/ChangeEmail.java
luismbo/gerrit
7d35ff3fbeddc22fd2e0b42ff3f971598bba0c25
[ "Apache-2.0" ]
479
2015-07-21T01:05:49.000Z
2022-02-10T07:02:21.000Z
java/com/google/gerrit/server/mail/send/ChangeEmail.java
tazmanian60/gerrit
7d35ff3fbeddc22fd2e0b42ff3f971598bba0c25
[ "Apache-2.0" ]
1
2016-02-25T16:50:20.000Z
2016-02-25T16:50:20.000Z
java/com/google/gerrit/server/mail/send/ChangeEmail.java
tazmanian60/gerrit
7d35ff3fbeddc22fd2e0b42ff3f971598bba0c25
[ "Apache-2.0" ]
171
2015-04-04T07:07:04.000Z
2022-03-18T20:43:22.000Z
33.719472
100
0.661496
12,611
// Copyright (C) 2016 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.mail.send; import com.google.common.base.Splitter; import com.google.common.collect.ListMultimap; import com.google.gerrit.common.errors.EmailException; import com.google.gerrit.extensions.api.changes.NotifyHandling; import com.google.gerrit.extensions.api.changes.RecipientType; import com.google.gerrit.extensions.restapi.AuthException; import com.google.gerrit.reviewdb.client.Account; import com.google.gerrit.reviewdb.client.AccountGroup; import com.google.gerrit.reviewdb.client.Change; import com.google.gerrit.reviewdb.client.Patch; import com.google.gerrit.reviewdb.client.PatchSet; import com.google.gerrit.reviewdb.client.PatchSetInfo; import com.google.gerrit.reviewdb.client.Project; import com.google.gerrit.server.IdentifiedUser; import com.google.gerrit.server.StarredChangesUtil; import com.google.gerrit.server.account.AccountState; import com.google.gerrit.server.account.WatchConfig.NotifyType; import com.google.gerrit.server.mail.send.ProjectWatch.Watchers; import com.google.gerrit.server.notedb.ReviewerStateInternal; import com.google.gerrit.server.patch.PatchList; import com.google.gerrit.server.patch.PatchListEntry; import com.google.gerrit.server.patch.PatchListNotAvailableException; import com.google.gerrit.server.patch.PatchListObjectTooLargeException; import com.google.gerrit.server.patch.PatchSetInfoNotAvailableException; import com.google.gerrit.server.permissions.ChangePermission; import com.google.gerrit.server.permissions.GlobalPermission; import com.google.gerrit.server.permissions.PermissionBackendException; import com.google.gerrit.server.project.ProjectState; import com.google.gerrit.server.query.change.ChangeData; import com.google.gwtorm.server.OrmException; import com.google.template.soy.data.SoyListData; import com.google.template.soy.data.SoyMapData; import java.io.IOException; import java.sql.Timestamp; import java.text.MessageFormat; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.eclipse.jgit.diff.DiffFormatter; import org.eclipse.jgit.internal.JGitText; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.util.RawParseUtils; import org.eclipse.jgit.util.TemporaryBuffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** Sends an email to one or more interested parties. */ public abstract class ChangeEmail extends NotificationEmail { private static final Logger log = LoggerFactory.getLogger(ChangeEmail.class); protected static ChangeData newChangeData( EmailArguments ea, Project.NameKey project, Change.Id id) { return ea.changeDataFactory.create(ea.db.get(), project, id); } protected final Change change; protected final ChangeData changeData; protected ListMultimap<Account.Id, String> stars; protected PatchSet patchSet; protected PatchSetInfo patchSetInfo; protected String changeMessage; protected Timestamp timestamp; protected ProjectState projectState; protected Set<Account.Id> authors; protected boolean emailOnlyAuthors; protected ChangeEmail(EmailArguments ea, String mc, ChangeData cd) throws OrmException { super(ea, mc, cd.change().getDest()); changeData = cd; change = cd.change(); emailOnlyAuthors = false; } @Override public void setFrom(Account.Id id) { super.setFrom(id); /** Is the from user in an email squelching group? */ try { IdentifiedUser user = args.identifiedUserFactory.create(id); args.permissionBackend.user(user).check(GlobalPermission.EMAIL_REVIEWERS); } catch (AuthException | PermissionBackendException e) { emailOnlyAuthors = true; } } public void setPatchSet(PatchSet ps) { patchSet = ps; } public void setPatchSet(PatchSet ps, PatchSetInfo psi) { patchSet = ps; patchSetInfo = psi; } public void setChangeMessage(String cm, Timestamp t) { changeMessage = cm; timestamp = t; } /** Format the message body by calling {@link #appendText(String)}. */ @Override protected void format() throws EmailException { formatChange(); appendText(textTemplate("ChangeFooter")); if (useHtml()) { appendHtml(soyHtmlTemplate("ChangeFooterHtml")); } formatFooter(); } /** Format the message body by calling {@link #appendText(String)}. */ protected abstract void formatChange() throws EmailException; /** * Format the message footer by calling {@link #appendText(String)}. * * @throws EmailException if an error occurred. */ protected void formatFooter() throws EmailException {} /** Setup the message headers and envelope (TO, CC, BCC). */ @Override protected void init() throws EmailException { if (args.projectCache != null) { projectState = args.projectCache.get(change.getProject()); } else { projectState = null; } if (patchSet == null) { try { patchSet = changeData.currentPatchSet(); } catch (OrmException err) { patchSet = null; } } if (patchSet != null) { setHeader("X-Gerrit-PatchSet", patchSet.getPatchSetId() + ""); if (patchSetInfo == null) { try { patchSetInfo = args.patchSetInfoFactory.get(args.db.get(), changeData.notes(), patchSet.getId()); } catch (PatchSetInfoNotAvailableException | OrmException err) { patchSetInfo = null; } } } authors = getAuthors(); try { stars = changeData.stars(); } catch (OrmException e) { throw new EmailException("Failed to load stars for change " + change.getChangeId(), e); } super.init(); if (timestamp != null) { setHeader("Date", new Date(timestamp.getTime())); } setChangeSubjectHeader(); setHeader("X-Gerrit-Change-Id", "" + change.getKey().get()); setHeader("X-Gerrit-Change-Number", "" + change.getChangeId()); setChangeUrlHeader(); setCommitIdHeader(); if (notify.ordinal() >= NotifyHandling.OWNER_REVIEWERS.ordinal()) { try { addByEmail( RecipientType.CC, changeData.reviewersByEmail().byState(ReviewerStateInternal.CC)); addByEmail( RecipientType.CC, changeData.reviewersByEmail().byState(ReviewerStateInternal.REVIEWER)); } catch (OrmException e) { throw new EmailException("Failed to add unregistered CCs " + change.getChangeId(), e); } } } private void setChangeUrlHeader() { final String u = getChangeUrl(); if (u != null) { setHeader("X-Gerrit-ChangeURL", "<" + u + ">"); } } private void setCommitIdHeader() { if (patchSet != null && patchSet.getRevision() != null && patchSet.getRevision().get() != null && patchSet.getRevision().get().length() > 0) { setHeader("X-Gerrit-Commit", patchSet.getRevision().get()); } } private void setChangeSubjectHeader() { setHeader("Subject", textTemplate("ChangeSubject")); } /** Get a link to the change; null if the server doesn't know its own address. */ public String getChangeUrl() { if (getGerritUrl() != null) { final StringBuilder r = new StringBuilder(); r.append(getGerritUrl()); r.append(change.getChangeId()); return r.toString(); } return null; } public String getChangeMessageThreadId() { return "<gerrit." + change.getCreatedOn().getTime() + "." + change.getKey().get() + "@" + this.getGerritHost() + ">"; } /** Format the sender's "cover letter", {@link #getCoverLetter()}. */ protected void formatCoverLetter() { final String cover = getCoverLetter(); if (!"".equals(cover)) { appendText(cover); appendText("\n\n"); } } /** Get the text of the "cover letter". */ public String getCoverLetter() { if (changeMessage != null) { return changeMessage.trim(); } return ""; } /** Format the change message and the affected file list. */ protected void formatChangeDetail() { appendText(getChangeDetail()); } /** Create the change message and the affected file list. */ public String getChangeDetail() { try { StringBuilder detail = new StringBuilder(); if (patchSetInfo != null) { detail.append(patchSetInfo.getMessage().trim()).append("\n"); } else { detail.append(change.getSubject().trim()).append("\n"); } if (patchSet != null) { detail.append("---\n"); PatchList patchList = getPatchList(); for (PatchListEntry p : patchList.getPatches()) { if (Patch.isMagic(p.getNewName())) { continue; } detail .append(p.getChangeType().getCode()) .append(" ") .append(p.getNewName()) .append("\n"); } detail.append( MessageFormat.format( "" // + "{0,choice,0#0 files|1#1 file|1<{0} files} changed, " // + "{1,choice,0#0 insertions|1#1 insertion|1<{1} insertions}(+), " // + "{2,choice,0#0 deletions|1#1 deletion|1<{2} deletions}(-)" // + "\n", patchList.getPatches().size() - 1, // patchList.getInsertions(), // patchList.getDeletions())); detail.append("\n"); } return detail.toString(); } catch (Exception err) { log.warn("Cannot format change detail", err); return ""; } } /** Get the patch list corresponding to this patch set. */ protected PatchList getPatchList() throws PatchListNotAvailableException { if (patchSet != null) { return args.patchListCache.get(change, patchSet); } throw new PatchListNotAvailableException("no patchSet specified"); } /** Get the project entity the change is in; null if its been deleted. */ protected ProjectState getProjectState() { return projectState; } /** Get the groups which own the project. */ protected Set<AccountGroup.UUID> getProjectOwners() { final ProjectState r; r = args.projectCache.get(change.getProject()); return r != null ? r.getOwners() : Collections.<AccountGroup.UUID>emptySet(); } /** TO or CC all vested parties (change owner, patch set uploader, author). */ protected void rcptToAuthors(RecipientType rt) { for (Account.Id id : authors) { add(rt, id); } } /** BCC any user who has starred this change. */ protected void bccStarredBy() { if (!NotifyHandling.ALL.equals(notify)) { return; } for (Map.Entry<Account.Id, Collection<String>> e : stars.asMap().entrySet()) { if (e.getValue().contains(StarredChangesUtil.DEFAULT_LABEL)) { super.add(RecipientType.BCC, e.getKey()); } } } protected void removeUsersThatIgnoredTheChange() { for (Map.Entry<Account.Id, Collection<String>> e : stars.asMap().entrySet()) { if (e.getValue().contains(StarredChangesUtil.IGNORE_LABEL)) { AccountState accountState = args.accountCache.get(e.getKey()); if (accountState != null) { removeUser(accountState.getAccount()); } } } } @Override protected final Watchers getWatchers(NotifyType type, boolean includeWatchersFromNotifyConfig) throws OrmException { if (!NotifyHandling.ALL.equals(notify)) { return new Watchers(); } ProjectWatch watch = new ProjectWatch(args, branch.getParentKey(), projectState, changeData); return watch.getWatchers(type, includeWatchersFromNotifyConfig); } /** Any user who has published comments on this change. */ protected void ccAllApprovals() { if (!NotifyHandling.ALL.equals(notify) && !NotifyHandling.OWNER_REVIEWERS.equals(notify)) { return; } try { for (Account.Id id : changeData.reviewers().all()) { add(RecipientType.CC, id); } } catch (OrmException err) { log.warn("Cannot CC users that reviewed updated change", err); } } /** Users who have non-zero approval codes on the change. */ protected void ccExistingReviewers() { if (!NotifyHandling.ALL.equals(notify) && !NotifyHandling.OWNER_REVIEWERS.equals(notify)) { return; } try { for (Account.Id id : changeData.reviewers().byState(ReviewerStateInternal.REVIEWER)) { add(RecipientType.CC, id); } } catch (OrmException err) { log.warn("Cannot CC users that commented on updated change", err); } } @Override protected void add(RecipientType rt, Account.Id to) { if (!emailOnlyAuthors || authors.contains(to)) { super.add(rt, to); } } @Override protected boolean isVisibleTo(Account.Id to) throws OrmException, PermissionBackendException { return args.permissionBackend .user(args.identifiedUserFactory.create(to)) .change(changeData) .database(args.db.get()) .test(ChangePermission.READ); } /** Find all users who are authors of any part of this change. */ protected Set<Account.Id> getAuthors() { Set<Account.Id> authors = new HashSet<>(); switch (notify) { case NONE: break; case ALL: default: if (patchSet != null) { authors.add(patchSet.getUploader()); } if (patchSetInfo != null) { if (patchSetInfo.getAuthor().getAccount() != null) { authors.add(patchSetInfo.getAuthor().getAccount()); } if (patchSetInfo.getCommitter().getAccount() != null) { authors.add(patchSetInfo.getCommitter().getAccount()); } } // $FALL-THROUGH$ case OWNER_REVIEWERS: case OWNER: authors.add(change.getOwner()); break; } return authors; } @Override protected void setupSoyContext() { super.setupSoyContext(); soyContext.put("changeId", change.getKey().get()); soyContext.put("coverLetter", getCoverLetter()); soyContext.put("fromName", getNameFor(fromId)); soyContext.put("fromEmail", getNameEmailFor(fromId)); soyContext.put("diffLines", getDiffTemplateData()); soyContextEmailData.put("unifiedDiff", getUnifiedDiff()); soyContextEmailData.put("changeDetail", getChangeDetail()); soyContextEmailData.put("changeUrl", getChangeUrl()); soyContextEmailData.put("includeDiff", getIncludeDiff()); Map<String, String> changeData = new HashMap<>(); String subject = change.getSubject(); String originalSubject = change.getOriginalSubject(); changeData.put("subject", subject); changeData.put("originalSubject", originalSubject); changeData.put("shortSubject", shortenSubject(subject)); changeData.put("shortOriginalSubject", shortenSubject(originalSubject)); changeData.put("ownerName", getNameFor(change.getOwner())); changeData.put("ownerEmail", getNameEmailFor(change.getOwner())); changeData.put("changeNumber", Integer.toString(change.getChangeId())); soyContext.put("change", changeData); Map<String, Object> patchSetData = new HashMap<>(); patchSetData.put("patchSetId", patchSet.getPatchSetId()); patchSetData.put("refName", patchSet.getRefName()); soyContext.put("patchSet", patchSetData); Map<String, Object> patchSetInfoData = new HashMap<>(); patchSetInfoData.put("authorName", patchSetInfo.getAuthor().getName()); patchSetInfoData.put("authorEmail", patchSetInfo.getAuthor().getEmail()); soyContext.put("patchSetInfo", patchSetInfoData); footers.add("Gerrit-MessageType: " + messageClass); footers.add("Gerrit-Change-Id: " + change.getKey().get()); footers.add("Gerrit-Change-Number: " + Integer.toString(change.getChangeId())); footers.add("Gerrit-PatchSet: " + patchSet.getPatchSetId()); footers.add("Gerrit-Owner: " + getNameEmailFor(change.getOwner())); if (change.getAssignee() != null) { footers.add("Gerrit-Assignee: " + getNameEmailFor(change.getAssignee())); } for (String reviewer : getEmailsByState(ReviewerStateInternal.REVIEWER)) { footers.add("Gerrit-Reviewer: " + reviewer); } for (String reviewer : getEmailsByState(ReviewerStateInternal.CC)) { footers.add("Gerrit-CC: " + reviewer); } } /** * A shortened subject is the subject limited to 72 characters, with an ellipsis if it exceeds * that limit. */ private static String shortenSubject(String subject) { if (subject.length() < 73) { return subject; } return subject.substring(0, 69) + "..."; } private Set<String> getEmailsByState(ReviewerStateInternal state) { Set<String> reviewers = new TreeSet<>(); try { for (Account.Id who : changeData.reviewers().byState(state)) { reviewers.add(getNameEmailFor(who)); } } catch (OrmException e) { log.warn("Cannot get change reviewers", e); } return reviewers; } public boolean getIncludeDiff() { return args.settings.includeDiff; } private static final int HEAP_EST_SIZE = 32 * 1024; /** Show patch set as unified difference. */ public String getUnifiedDiff() { PatchList patchList; try { patchList = getPatchList(); if (patchList.getOldId() == null) { // Octopus merges are not well supported for diff output by Gerrit. // Currently these always have a null oldId in the PatchList. return "[Octopus merge; cannot be formatted as a diff.]\n"; } } catch (PatchListObjectTooLargeException e) { log.warn("Cannot format patch " + e.getMessage()); return ""; } catch (PatchListNotAvailableException e) { log.error("Cannot format patch", e); return ""; } int maxSize = args.settings.maximumDiffSize; TemporaryBuffer.Heap buf = new TemporaryBuffer.Heap(Math.min(HEAP_EST_SIZE, maxSize), maxSize); try (DiffFormatter fmt = new DiffFormatter(buf)) { try (Repository git = args.server.openRepository(change.getProject())) { try { fmt.setRepository(git); fmt.setDetectRenames(true); fmt.format(patchList.getOldId(), patchList.getNewId()); return RawParseUtils.decode(buf.toByteArray()); } catch (IOException e) { if (JGitText.get().inMemoryBufferLimitExceeded.equals(e.getMessage())) { return ""; } log.error("Cannot format patch", e); return ""; } } catch (IOException e) { log.error("Cannot open repository to format patch", e); return ""; } } } /** * Generate a Soy list of maps representing each line of the unified diff. The line maps will have * a 'type' key which maps to one of 'common', 'add' or 'remove' and a 'text' key which maps to * the line's content. */ private SoyListData getDiffTemplateData() { SoyListData result = new SoyListData(); Splitter lineSplitter = Splitter.on(System.getProperty("line.separator")); for (String diffLine : lineSplitter.split(getUnifiedDiff())) { SoyMapData lineData = new SoyMapData(); lineData.put("text", diffLine); // Skip empty lines and lines that look like diff headers. if (diffLine.isEmpty() || diffLine.startsWith("---") || diffLine.startsWith("+++")) { lineData.put("type", "common"); } else { switch (diffLine.charAt(0)) { case '+': lineData.put("type", "add"); break; case '-': lineData.put("type", "remove"); break; default: lineData.put("type", "common"); break; } } result.add(lineData); } return result; } }
3e1dc9a4a74356ea8af9e76f30b3a0f97a01db8e
10,637
java
Java
ext/java/nokogiri/internals/c14n/NameSpaceSymbTable.java
MrfizieeD/nokogiri
0e75392d49ca3758dcdfc6610c9c22ccdc23001c
[ "MIT", "Zlib", "Apache-2.0" ]
3,513
2015-01-01T11:30:36.000Z
2022-03-30T18:42:37.000Z
ext/java/nokogiri/internals/c14n/NameSpaceSymbTable.java
MrfizieeD/nokogiri
0e75392d49ca3758dcdfc6610c9c22ccdc23001c
[ "MIT", "Zlib", "Apache-2.0" ]
1,318
2015-01-02T14:29:39.000Z
2022-03-31T17:49:57.000Z
ext/java/nokogiri/internals/c14n/NameSpaceSymbTable.java
MrfizieeD/nokogiri
0e75392d49ca3758dcdfc6610c9c22ccdc23001c
[ "MIT", "Zlib", "Apache-2.0" ]
673
2015-01-01T12:08:10.000Z
2022-03-30T17:49:08.000Z
23.481236
85
0.618972
12,612
/** * 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 nokogiri.internals.c14n; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.w3c.dom.Attr; import org.w3c.dom.Node; /** * A stack based Symbol Table. *<br>For speed reasons all the symbols are introduced in the same map, * and at the same time in a list so it can be removed when the frame is pop back. * @author Raul Benito */ public class NameSpaceSymbTable { private static final String XMLNS = "xmlns"; private static final SymbMap initialMap = new SymbMap(); static { NameSpaceSymbEntry ne = new NameSpaceSymbEntry("", null, true, XMLNS); ne.lastrendered = ""; initialMap.put(XMLNS, ne); } /**The map betwen prefix-> entry table. */ private SymbMap symb; /**The stacks for removing the definitions when doing pop.*/ private List<SymbMap> level; private boolean cloned = true; /** * Default constractor **/ public NameSpaceSymbTable() { level = new ArrayList<SymbMap>(); //Insert the default binding for xmlns. symb = (SymbMap) initialMap.clone(); } /** * Get all the unrendered nodes in the name space. * For Inclusive rendering * @param result the list where to fill the unrendered xmlns definitions. **/ public void getUnrenderedNodes(Collection<Attr> result) { Iterator<NameSpaceSymbEntry> it = symb.entrySet().iterator(); while (it.hasNext()) { NameSpaceSymbEntry n = it.next(); //put them rendered? if ((!n.rendered) && (n.n != null)) { n = (NameSpaceSymbEntry) n.clone(); needsClone(); symb.put(n.prefix, n); n.lastrendered = n.uri; n.rendered = true; result.add(n.n); } } } /** * Push a frame for visible namespace. * For Inclusive rendering. **/ public void outputNodePush() { push(); } /** * Pop a frame for visible namespace. **/ public void outputNodePop() { pop(); } /** * Push a frame for a node. * Inclusive or Exclusive. **/ public void push() { //Put the number of namespace definitions in the stack. level.add(null); cloned = false; } /** * Pop a frame. * Inclusive or Exclusive. **/ public void pop() { int size = level.size() - 1; Object ob = level.remove(size); if (ob != null) { symb = (SymbMap)ob; if (size == 0) { cloned = false; } else { cloned = (level.get(size - 1) != symb); } } else { cloned = false; } } final void needsClone() { if (!cloned) { level.set(level.size() - 1, symb); symb = (SymbMap) symb.clone(); cloned = true; } } /** * Gets the attribute node that defines the binding for the prefix. * @param prefix the prefix to obtain the attribute. * @return null if there is no need to render the prefix. Otherwise the node of * definition. **/ public Attr getMapping(String prefix) { NameSpaceSymbEntry entry = symb.get(prefix); if (entry == null) { //There is no definition for the prefix(a bug?). return null; } if (entry.rendered) { //No need to render an entry already rendered. return null; } // Mark this entry as render. entry = (NameSpaceSymbEntry) entry.clone(); needsClone(); symb.put(prefix, entry); entry.rendered = true; entry.lastrendered = entry.uri; // Return the node for outputing. return entry.n; } /** * Gets a definition without mark it as render. * For render in exclusive c14n the namespaces in the include prefixes. * @param prefix The prefix whose definition is neaded. * @return the attr to render, null if there is no need to render **/ public Attr getMappingWithoutRendered(String prefix) { NameSpaceSymbEntry entry = symb.get(prefix); if (entry == null) { return null; } if (entry.rendered) { return null; } return entry.n; } /** * Adds the mapping for a prefix. * @param prefix the prefix of definition * @param uri the Uri of the definition * @param n the attribute that have the definition * @return true if there is already defined. **/ public boolean addMapping(String prefix, String uri, Attr n) { NameSpaceSymbEntry ob = symb.get(prefix); if ((ob != null) && uri.equals(ob.uri)) { //If we have it previously defined. Don't keep working. return false; } //Creates and entry in the table for this new definition. NameSpaceSymbEntry ne = new NameSpaceSymbEntry(uri, n, false, prefix); needsClone(); symb.put(prefix, ne); if (ob != null) { //We have a previous definition store it for the pop. //Check if a previous definition(not the inmidiatly one) has been rendered. ne.lastrendered = ob.lastrendered; if ((ob.lastrendered != null) && (ob.lastrendered.equals(uri))) { //Yes it is. Mark as rendered. ne.rendered = true; } } return true; } /** * Adds a definition and mark it as render. * For inclusive c14n. * @param prefix the prefix of definition * @param uri the Uri of the definition * @param n the attribute that have the definition * @return the attr to render, null if there is no need to render **/ public Node addMappingAndRender(String prefix, String uri, Attr n) { NameSpaceSymbEntry ob = symb.get(prefix); if ((ob != null) && uri.equals(ob.uri)) { if (!ob.rendered) { ob = (NameSpaceSymbEntry) ob.clone(); needsClone(); symb.put(prefix, ob); ob.lastrendered = uri; ob.rendered = true; return ob.n; } return null; } NameSpaceSymbEntry ne = new NameSpaceSymbEntry(uri, n, true, prefix); ne.lastrendered = uri; needsClone(); symb.put(prefix, ne); if ((ob != null) && (ob.lastrendered != null) && (ob.lastrendered.equals(uri))) { ne.rendered = true; return null; } return ne.n; } public int getLevel() { return level.size(); } public void removeMapping(String prefix) { NameSpaceSymbEntry ob = symb.get(prefix); if (ob != null) { needsClone(); symb.put(prefix, null); } } public void removeMappingIfNotRender(String prefix) { NameSpaceSymbEntry ob = symb.get(prefix); if (ob != null && !ob.rendered) { needsClone(); symb.put(prefix, null); } } public boolean removeMappingIfRender(String prefix) { NameSpaceSymbEntry ob = symb.get(prefix); if (ob != null && ob.rendered) { needsClone(); symb.put(prefix, null); } return false; } } /** * The internal structure of NameSpaceSymbTable. **/ class NameSpaceSymbEntry implements Cloneable { String prefix; /**The URI that the prefix defines */ String uri; /**The last output in the URI for this prefix (This for speed reason).*/ String lastrendered = null; /**This prefix-URI has been already render or not.*/ boolean rendered = false; /**The attribute to include.*/ Attr n; NameSpaceSymbEntry(String name, Attr n, boolean rendered, String prefix) { this.uri = name; this.rendered = rendered; this.n = n; this.prefix = prefix; } /** @inheritDoc */ public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { return null; } } } class SymbMap implements Cloneable { int free = 23; NameSpaceSymbEntry[] entries; String[] keys; SymbMap() { entries = new NameSpaceSymbEntry[free]; keys = new String[free]; } void put(String key, NameSpaceSymbEntry value) { int index = index(key); Object oldKey = keys[index]; keys[index] = key; entries[index] = value; if ((oldKey == null || !oldKey.equals(key)) && (--free == 0)) { free = entries.length; int newCapacity = free << 2; rehash(newCapacity); } } List<NameSpaceSymbEntry> entrySet() { List<NameSpaceSymbEntry> a = new ArrayList<NameSpaceSymbEntry>(); for (int i = 0; i < entries.length; i++) { if ((entries[i] != null) && !("".equals(entries[i].uri))) { a.add(entries[i]); } } return a; } protected int index(Object obj) { Object[] set = keys; int length = set.length; //abs of index int index = (obj.hashCode() & 0x7fffffff) % length; Object cur = set[index]; if (cur == null || (cur.equals(obj))) { return index; } length--; do { index = index == length ? 0 : ++index; cur = set[index]; } while (cur != null && (!cur.equals(obj))); return index; } /** * rehashes the map to the new capacity. * * @param newCapacity an <code>int</code> value */ protected void rehash(int newCapacity) { int oldCapacity = keys.length; String oldKeys[] = keys; NameSpaceSymbEntry oldVals[] = entries; keys = new String[newCapacity]; entries = new NameSpaceSymbEntry[newCapacity]; for (int i = oldCapacity; i-- > 0;) { if (oldKeys[i] != null) { String o = oldKeys[i]; int index = index(o); keys[index] = o; entries[index] = oldVals[i]; } } } NameSpaceSymbEntry get(String key) { return entries[index(key)]; } protected Object clone() { try { SymbMap copy = (SymbMap) super.clone(); copy.entries = new NameSpaceSymbEntry[entries.length]; System.arraycopy(entries, 0, copy.entries, 0, entries.length); copy.keys = new String[keys.length]; System.arraycopy(keys, 0, copy.keys, 0, keys.length); return copy; } catch (CloneNotSupportedException e) { e.printStackTrace(); } return null; } }
3e1dca0882ae801da1e01eb713b98dd5c6e0b0f3
4,993
java
Java
src/com/akjava/gwt/three/client/java/ThreeLog.java
akjava/gwt-three.js-test
8f7956e40c5a41d2eeb3e73853c4671c6545505e
[ "Apache-2.0" ]
null
null
null
src/com/akjava/gwt/three/client/java/ThreeLog.java
akjava/gwt-three.js-test
8f7956e40c5a41d2eeb3e73853c4671c6545505e
[ "Apache-2.0" ]
6
2015-02-27T05:18:03.000Z
2015-03-26T07:48:31.000Z
src/com/akjava/gwt/three/client/java/ThreeLog.java
akjava/gwt-three.js-test
8f7956e40c5a41d2eeb3e73853c4671c6545505e
[ "Apache-2.0" ]
1
2019-01-11T21:48:56.000Z
2019-01-11T21:48:56.000Z
25.345178
80
0.634088
12,613
package com.akjava.gwt.three.client.java; import com.akjava.gwt.lib.client.LogUtils; import com.akjava.gwt.three.client.gwt.boneanimation.AnimationBone; import com.akjava.gwt.three.client.gwt.core.BoundingBox; import com.akjava.gwt.three.client.java.utils.GWTThreeUtils; import com.akjava.gwt.three.client.js.THREE; import com.akjava.gwt.three.client.js.math.Euler; import com.akjava.gwt.three.client.js.math.Matrix4; import com.akjava.gwt.three.client.js.math.Quaternion; import com.akjava.gwt.three.client.js.math.Sphere; import com.akjava.gwt.three.client.js.math.Vector2; import com.akjava.gwt.three.client.js.math.Vector3; import com.akjava.gwt.three.client.js.math.Vector4; import com.akjava.gwt.three.client.js.objects.SkinnedMesh; import com.google.gwt.core.client.JsArrayNumber; public class ThreeLog extends LogUtils{ public static String getAngle(Matrix4 mx){ if(mx==null){ return "Null"; } Vector3 vec=THREE.Vector3(); vec.getRotationFromMatrix(mx); return getAngle(vec); } public static String getAngle(Vector3 vec){ if(vec==null){ return "Null"; } String ret="x:"+Math.toDegrees(vec.getX()); ret+=",y:"+Math.toDegrees(vec.getY()); ret+=",z:"+Math.toDegrees(vec.getZ()); return ret; } public static String getAsDegree(Vector3 vec){ return get(GWTThreeUtils.radiantToDegree(vec)); } public static String get(Vector3 vec){ if(vec==null){ return "Null"; } String ret="x:"+vec.getX(); ret+=",y:"+vec.getY(); ret+=",z:"+vec.getZ(); return ret; } public static String get(Sphere vec){ if(vec==null){ return "Null"; } String ret="x:"+vec.getCenter().getX(); ret+=",y:"+vec.getCenter().getY(); ret+=",z:"+vec.getCenter().getZ(); ret+=",radius:"+vec.getRadius(); return ret; } public static String get(BoundingBox vec){ if(vec==null){ return "Null"; } String ret="min{x:"+vec.getMin().getX(); ret+=",y:"+vec.getMin().getY(); ret+=",z:"+vec.getMin().getZ(); ret+="} "; ret+="max{x:"+vec.getMax().getX(); ret+=",y:"+vec.getMax().getY(); ret+=",z:"+vec.getMax().getZ(); ret+="} "; return ret; } public static String get(Euler vec){ if(vec==null){ return "Null"; } String ret="x:"+Math.toDegrees(vec.getX()); ret+=",y:"+Math.toDegrees(vec.getY()); ret+=",z:"+Math.toDegrees(vec.getZ()); ret+=","+vec.getOrder(); return ret; } public static String get(Vector2 vec){ if(vec==null){ return "Null"; } String ret="x:"+vec.getX(); ret+=",y:"+vec.getY(); return ret; } public static String get(Vector4 vec){ if(vec==null){ return "Null"; } String ret="x:"+vec.getX(); ret+=",y:"+vec.getY(); ret+=",z:"+vec.getZ(); ret+=",w:"+vec.getW(); return ret; } public static String get(AnimationBone bone){ if(bone==null){ return "Null"; } String ret=get(THREE.Vector3().fromArray(bone.getPos())); return ret; } public static String get(Quaternion vec){ if(vec==null){ return "Null"; } String ret="x:"+vec.getX(); ret+=",y:"+vec.getY(); ret+=",z:"+vec.getZ(); ret+=",w:"+vec.getW(); return ret; } public static String get(JsArrayNumber numbers){ if(numbers==null){ return "Null"; } String ret=""; for(int i=0;i<numbers.length();i++){ ret+=numbers.get(i)+","; } return ret; } public static void log(Vector2 vec){ LogUtils.log(get(vec)); } public static void log(String header,double vec){ LogUtils.log(header+" "+vec); } public static void log(String header,Vector2 vec){ LogUtils.log(header+" "+get(vec)); } public static void log(Vector3 vec){ LogUtils.log(get(vec)); } public static void log(String header,Vector3 vec){ LogUtils.log(header+" "+get(vec)); } public static void log(Vector4 vec){ LogUtils.log(get(vec)); } public static void log(String header,AnimationBone vec){ LogUtils.log(header+" "+get(vec)); } public static void log(AnimationBone vec){ LogUtils.log(get(vec)); } public static void log(String header,Euler vec){ LogUtils.log(header+" "+get(vec)); } public static void log(Euler vec){ LogUtils.log(get(vec)); } public static void log(String header,Vector4 vec){ LogUtils.log(header+" "+get(vec)); } public static void logBoneNames(SkinnedMesh characterMesh) { if(characterMesh.getGeometry().getBones()==null){ LogUtils.log("no bone"); return; } for(int i=0;i<characterMesh.getGeometry().getBones().length();i++){ LogUtils.log(i+","+characterMesh.getGeometry().getBones().get(i).getName()); } } public static void log(String header, Quaternion quaternion) { LogUtils.log(header+" "+get(quaternion)); } public static void log(String header, BoundingBox box) { log(header+" "+get(box)); } public static void log(String header, Sphere sphere) { log(header+" "+get(sphere)); } }
3e1dca2cb95b62dca2aff0ecf3191786adbd82cf
4,016
java
Java
aws-java-sdk-transcribe/src/main/java/com/amazonaws/services/transcribe/model/GetCallAnalyticsCategoryRequest.java
vinayakpokharkar/aws-sdk-java
fd409dee8ae23fb8953e0bb4dbde65536a7e0514
[ "Apache-2.0" ]
1
2022-01-04T04:11:16.000Z
2022-01-04T04:11:16.000Z
aws-java-sdk-transcribe/src/main/java/com/amazonaws/services/transcribe/model/GetCallAnalyticsCategoryRequest.java
vinayakpokharkar/aws-sdk-java
fd409dee8ae23fb8953e0bb4dbde65536a7e0514
[ "Apache-2.0" ]
null
null
null
aws-java-sdk-transcribe/src/main/java/com/amazonaws/services/transcribe/model/GetCallAnalyticsCategoryRequest.java
vinayakpokharkar/aws-sdk-java
fd409dee8ae23fb8953e0bb4dbde65536a7e0514
[ "Apache-2.0" ]
null
null
null
32.128
127
0.652888
12,614
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.transcribe.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/transcribe-2017-10-26/GetCallAnalyticsCategory" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetCallAnalyticsCategoryRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The name of the category you want information about. This value is case sensitive. * </p> */ private String categoryName; /** * <p> * The name of the category you want information about. This value is case sensitive. * </p> * * @param categoryName * The name of the category you want information about. This value is case sensitive. */ public void setCategoryName(String categoryName) { this.categoryName = categoryName; } /** * <p> * The name of the category you want information about. This value is case sensitive. * </p> * * @return The name of the category you want information about. This value is case sensitive. */ public String getCategoryName() { return this.categoryName; } /** * <p> * The name of the category you want information about. This value is case sensitive. * </p> * * @param categoryName * The name of the category you want information about. This value is case sensitive. * @return Returns a reference to this object so that method calls can be chained together. */ public GetCallAnalyticsCategoryRequest withCategoryName(String categoryName) { setCategoryName(categoryName); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getCategoryName() != null) sb.append("CategoryName: ").append(getCategoryName()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof GetCallAnalyticsCategoryRequest == false) return false; GetCallAnalyticsCategoryRequest other = (GetCallAnalyticsCategoryRequest) obj; if (other.getCategoryName() == null ^ this.getCategoryName() == null) return false; if (other.getCategoryName() != null && other.getCategoryName().equals(this.getCategoryName()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getCategoryName() == null) ? 0 : getCategoryName().hashCode()); return hashCode; } @Override public GetCallAnalyticsCategoryRequest clone() { return (GetCallAnalyticsCategoryRequest) super.clone(); } }
3e1dcb312a4f1ddbd47acc884ec771d32471ca67
59
java
Java
supera_backend/src/main/java/br/com/supera/entities/Cartcao.java
anisberto/Supera-Estudo
a253eb8de0d059374607dacb02b5b1258c9cf46c
[ "MIT" ]
null
null
null
supera_backend/src/main/java/br/com/supera/entities/Cartcao.java
anisberto/Supera-Estudo
a253eb8de0d059374607dacb02b5b1258c9cf46c
[ "MIT" ]
null
null
null
supera_backend/src/main/java/br/com/supera/entities/Cartcao.java
anisberto/Supera-Estudo
a253eb8de0d059374607dacb02b5b1258c9cf46c
[ "MIT" ]
null
null
null
9.833333
31
0.745763
12,615
package br.com.supera.entities; public class Cartcao { }
3e1dcbc759c5222692f862ab366e40b2ebf08617
399
java
Java
src/main/java/de/ropemc/api/event/instrumentation/InjectionEvent.java
RopeMC/RopeMC
b464fb9a67e410355a6a498f2d6a2d3b0d022b3d
[ "MIT" ]
8
2017-10-01T17:32:54.000Z
2022-02-12T17:14:19.000Z
src/main/java/de/ropemc/api/event/instrumentation/InjectionEvent.java
RopeMC/RopeMC
b464fb9a67e410355a6a498f2d6a2d3b0d022b3d
[ "MIT" ]
null
null
null
src/main/java/de/ropemc/api/event/instrumentation/InjectionEvent.java
RopeMC/RopeMC
b464fb9a67e410355a6a498f2d6a2d3b0d022b3d
[ "MIT" ]
1
2020-03-09T13:57:29.000Z
2020-03-09T13:57:29.000Z
21
57
0.681704
12,616
package de.ropemc.api.event.instrumentation; import de.ropemc.api.event.Event; import java.util.ArrayList; import java.util.List; public class InjectionEvent extends Event { private List<Class<?>> injectors = new ArrayList<>(); public void add(Class<?> injector) { this.injectors.add(injector); } public List<Class<?>> getInjectors() { return injectors; } }
3e1dcbd6cf36282e2f0cfc79895e46919b1f366a
727
java
Java
src/main/java/com/lujianbo/app/kte/Application.java
lujianbo/moonlight-KTE
2b0da65cc0f9b57b58106d011852993b2af9946a
[ "MIT" ]
null
null
null
src/main/java/com/lujianbo/app/kte/Application.java
lujianbo/moonlight-KTE
2b0da65cc0f9b57b58106d011852993b2af9946a
[ "MIT" ]
null
null
null
src/main/java/com/lujianbo/app/kte/Application.java
lujianbo/moonlight-KTE
2b0da65cc0f9b57b58106d011852993b2af9946a
[ "MIT" ]
null
null
null
34.619048
121
0.687758
12,617
package com.lujianbo.app.kte; import com.lujianbo.app.kte.common.BatchProcessor; import com.lujianbo.app.kte.impl.Config; import com.lujianbo.app.kte.impl.KTETaskFactory; import org.apache.kafka.clients.consumer.ConsumerRecord; public class Application { public static void main(String[] args) { try { KTETaskFactory kteTaskFactory = new KTETaskFactory(Config.readConfig()); BatchProcessor<ConsumerRecord<byte[], byte[]>, byte[]> batchProcessor = new BatchProcessor<>(kteTaskFactory); batchProcessor.start(); Runtime.getRuntime().addShutdownHook(new Thread(batchProcessor::stop)); } catch (Exception e) { e.printStackTrace(); } } }
3e1dcc12a66d876913493e8a59985118dc2be6d2
28,836
java
Java
src/com/zhan_dui/animetaste/PlayActivity.java
lailiaomm/AnimeTaste
4d89550c5424d6776f22c397e7b60f8e3007c3d8
[ "MIT" ]
null
null
null
src/com/zhan_dui/animetaste/PlayActivity.java
lailiaomm/AnimeTaste
4d89550c5424d6776f22c397e7b60f8e3007c3d8
[ "MIT" ]
null
null
null
src/com/zhan_dui/animetaste/PlayActivity.java
lailiaomm/AnimeTaste
4d89550c5424d6776f22c397e7b60f8e3007c3d8
[ "MIT" ]
null
null
null
30.774813
83
0.724788
12,618
package com.zhan_dui.animetaste; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Timer; import java.util.TimerTask; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.ocpsoft.prettytime.PrettyTime; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.Typeface; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.ShareActionProvider; import android.support.v7.widget.ShareActionProvider.OnShareTargetSelectedListener; import android.text.InputFilter; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.OrientationEventListener; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import android.widget.Toast; import cn.sharesdk.sina.weibo.SinaWeibo; import cn.sharesdk.tencent.qzone.QZone; import com.avos.avoscloud.ParseException; import com.avos.avoscloud.ParseObject; import com.avos.avoscloud.ParseQuery; import com.avos.avoscloud.SaveCallback; import com.baidu.cyberplayer.core.BVideoView; import com.baidu.cyberplayer.core.BVideoView.OnCompletionListener; import com.baidu.cyberplayer.core.BVideoView.OnErrorListener; import com.baidu.cyberplayer.core.BVideoView.OnPreparedListener; import com.basv.gifmoviewview.widget.GifMovieView; import com.loopj.android.http.JsonHttpResponseHandler; import com.squareup.picasso.Picasso; import com.squareup.picasso.Picasso.LoadedFrom; import com.squareup.picasso.Target; import com.umeng.analytics.MobclickAgent; import com.zhan_dui.auth.SocialPlatform; import com.zhan_dui.auth.User; import com.zhan_dui.data.VideoDB; import com.zhan_dui.modal.Comment; import com.zhan_dui.modal.DataHandler; import com.zhan_dui.modal.VideoDataFormat; import com.zhan_dui.utils.OrientationHelper; import com.zhan_dui.utils.Screen; public class PlayActivity extends ActionBarActivity implements OnClickListener, Target, OnPreparedListener, OnCompletionListener, OnErrorListener, OnTouchListener { private TextView mTitleTextView; private TextView mContentTextView; private TextView mAutherTextView; private ShareActionProvider mShareActionProvider; private ImageView mDetailImageView; private ImageButton mPrePlayButton; private GifMovieView mLoadingGif; private int mCurrentScape; private Context mContext; private SharedPreferences mSharedPreferences; private VideoDB mVideoDB; private View mVideoAction; private VideoDataFormat mVideoInfo; private OrientationEventListener mOrientationEventListener; private MenuItem mFavMenuItem; private Bitmap mDetailPicture; private LinearLayout mComments, mRecomendList; private LayoutInflater mLayoutInflater; private RelativeLayout mHeaderWrpper; private View mLoadMoreComment; private View mRecommandView; private Button mLoadMoreButton; private Button mZoomButton; private boolean mCommentFinished; private User mUser; private final String mDir = "AnimeTaste"; private final String mShareName = "animetaste-share.jpg"; private int mCommentCount; private int mSkip = 0; private int mStep = 5; private int mLastPos = 0; private final int UI_EVENT_UPDATE_CURRPOSITION = 1; private PrettyTime mPrettyTime; private BVideoView mVV = null; private RelativeLayout mViewHolder = null; private RelativeLayout mController = null; private SeekBar mProgress = null; private TextView mDuration = null; private TextView mCurrPostion = null; private Button mPlaybtn = null; private EditText mCommentEditText; private String AK = "TrqQtzMhuoKhyLmNsfvwfWDo"; private String SK = "UuhbIKiNfr8SA3NM"; private Typeface mRobotoBold, mRobotoThin; @Override public void onCreate(Bundle savedInstance) { super.onCreate(savedInstance); mPrettyTime = new PrettyTime(); mContext = this; mVideoDB = new VideoDB(mContext, VideoDB.NAME, null, VideoDB.VERSION); if (getIntent().getExtras().containsKey("VideoInfo")) { mVideoInfo = (VideoDataFormat) (getIntent().getExtras() .getSerializable("VideoInfo")); } if (savedInstance != null && savedInstance.containsKey("VideoInfo")) { mVideoInfo = (VideoDataFormat) savedInstance.get("VideoInfo"); mLastPos = savedInstance.getInt("LastPosition"); } mUser = new User(mContext); setContentView(R.layout.activity_play); mLayoutInflater = (LayoutInflater) mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); getSupportActionBar().setDisplayShowTitleEnabled(false); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mSharedPreferences = PreferenceManager .getDefaultSharedPreferences(mContext); mCurrentScape = OrientationHelper.PORTRAIT; mTitleTextView = (TextView) findViewById(R.id.title); mContentTextView = (TextView) findViewById(R.id.content); mDetailImageView = (ImageView) findViewById(R.id.detailPic); mVideoAction = (View) findViewById(R.id.VideoAction); mAutherTextView = (TextView) findViewById(R.id.author); mPrePlayButton = (ImageButton) findViewById(R.id.pre_play_button); mLoadingGif = (GifMovieView) findViewById(R.id.loading_gif); mComments = (LinearLayout) findViewById(R.id.comments); mRecommandView = findViewById(R.id.recommand_view); mPlaybtn = (Button) findViewById(R.id.play_btn); mProgress = (SeekBar) findViewById(R.id.media_progress); mDuration = (TextView) findViewById(R.id.time_total); mCurrPostion = (TextView) findViewById(R.id.time_current); mController = (RelativeLayout) findViewById(R.id.controlbar); mViewHolder = (RelativeLayout) findViewById(R.id.view_holder); mVV = (BVideoView) findViewById(R.id.video_view); mCommentEditText = (EditText) findViewById(R.id.comment_edit_text); mHeaderWrpper = (RelativeLayout) findViewById(R.id.header_wrapper); mZoomButton = (Button) findViewById(R.id.zoom_btn); mRecomendList = (LinearLayout) findViewById(R.id.recommend_list); mRobotoBold = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Bold.ttf"); mRobotoThin = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Thin.ttf"); initPlayer(); initContent(); mVideoInfo.setFav(mVideoDB.isFav(mVideoInfo.Id)); DataHandler.instance().getRandom(5, mRandomeHandler); new CommentsTask().execute(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("LastPosition", mLastPos); outState.putSerializable("VideoInfo", mVideoInfo); } private JsonHttpResponseHandler mRandomeHandler = new JsonHttpResponseHandler() { public void onSuccess(int statusCode, org.json.JSONObject response) { if (statusCode == 200) { try { JSONArray randomList = response.getJSONArray("list"); for (int i = 0; i < randomList.length(); i++) { LinearLayout recommend_item = (LinearLayout) mLayoutInflater .inflate(R.layout.recommend_item, null); ImageView recommendThumb = (ImageView) recommend_item .findViewById(R.id.thumb); TextView recommendTitle = (TextView) recommend_item .findViewById(R.id.recommand_title); TextView recommendContent = (TextView) recommend_item .findViewById(R.id.recommand_content); JSONObject video = randomList.getJSONObject(i); VideoDataFormat videoDataFormat = VideoDataFormat .build(video); Picasso.with(mContext).load(videoDataFormat.HomePic) .placeholder(R.drawable.placeholder_thumb) .error(R.drawable.placeholder_fail) .into(recommendThumb); recommendTitle.setText(videoDataFormat.Name); recommendContent.setText(videoDataFormat.Brief); mRecommandView.setTag(videoDataFormat); mRecommandView.setOnClickListener(PlayActivity.this); View line = mRecommandView .findViewById(R.id.divide_line); if (i == randomList.length() - 1 && line != null) { recommend_item.removeView(line); } mRecomendList.addView(recommend_item); } } catch (JSONException e) { e.printStackTrace(); } } }; public void onFailure(Throwable e, org.json.JSONArray errorResponse) { }; }; private Intent getDefaultIntent() { Intent intent = new Intent(Intent.ACTION_SEND); String shareTitle = getString(R.string.share_video_title); shareTitle = String.format(shareTitle, mVideoInfo.Name); String shareContent = getString(R.string.share_video_body); intent.setType("image/*"); shareContent = String.format(shareContent, mVideoInfo.Name, mVideoInfo.Youku); intent.putExtra(Intent.EXTRA_SUBJECT, shareTitle); intent.putExtra(Intent.EXTRA_TEXT, shareContent); File file = getShareFile(); if (file != null) { intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); } intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); return intent; } private File getShareFile() { String path = Environment.getExternalStorageDirectory().getPath() + File.separator + mDir + File.separator + mShareName; File file = new File(path); if (file.exists()) { return file; } else { return null; } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.play, menu); MenuItem item = menu.findItem(R.id.menu_item_share); mShareActionProvider = (ShareActionProvider) MenuItemCompat .getActionProvider(item); mShareActionProvider .setOnShareTargetSelectedListener(new OnShareTargetSelectedListener() { @Override public boolean onShareTargetSelected( ShareActionProvider arg0, Intent arg1) { MobclickAgent.onEvent(mContext, "share"); pausePlay(); return true; } }); mFavMenuItem = menu.findItem(R.id.action_fav); mShareActionProvider.setShareIntent(getDefaultIntent()); new CheckIsFavorite().execute(); return true; } public void comment() { MobclickAgent.onEvent(mContext, "comment"); if (mUser.isLogin() == false) { new AlertDialog.Builder(this) .setTitle(R.string.choose_login) .setItems( new String[] { getString(R.string.weibo), getString(R.string.qq) }, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: new SocialPlatform(mContext).auth( SinaWeibo.NAME, mAuthHandler); break; case 1: new SocialPlatform(mContext).auth( QZone.NAME, mAuthHandler); break; default: break; } } }).setNegativeButton(R.string.cancel_login, null) .show(); } else { final EditText editText = new EditText(mContext); editText.setHeight(mContext.getResources().getDimensionPixelSize( R.dimen.comment_edit_height)); editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter( 250) }); editText.setGravity(Gravity.LEFT | Gravity.TOP); AlertDialog.Builder commentDialog = new AlertDialog.Builder( mContext).setTitle(R.string.publish_comment) .setView(editText) .setNegativeButton(R.string.cancel_publish, null) .setPositiveButton(R.string.publish, null); final AlertDialog dialog = commentDialog.create(); dialog.show(); dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { final String content = editText.getText() .toString(); if (content.length() == 0) { Toast.makeText(mContext, R.string.comment_nothing, Toast.LENGTH_SHORT).show(); } else if (content.length() < 5) { Toast.makeText(mContext, R.string.comment_too_short, Toast.LENGTH_SHORT).show(); } else { new CommentThread(content).start(); dialog.dismiss(); } } }); } } private class CommentThread extends Thread { private String mContent; private CommentThread(String commentContent) { mContent = commentContent; } @Override public void run() { super.run(); ParseObject parseComment = new ParseObject("Comments"); ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Users"); try { ParseObject user = query.get(mSharedPreferences.getString( "objectid", "0")); parseComment.put("vid", mVideoInfo.Id); parseComment.put("uid", user); parseComment.put("content", mContent); parseComment.saveInBackground(new SaveCallback() { @Override public void done(ParseException err) { if (err == null) { PlayActivity.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(mContext, R.string.comment_success, Toast.LENGTH_SHORT).show(); View commentItem = mLayoutInflater.inflate( R.layout.comment_item, null); ImageView avatar = (ImageView) commentItem .findViewById(R.id.avatar); TextView name = (TextView) commentItem .findViewById(R.id.name); TextView contentTextView = (TextView) commentItem .findViewById(R.id.content); contentTextView.setText(mContent); name.setText(mUser.getUsername()); Picasso.with(mContext) .load(mUser.getAvatar()) .into(avatar); mComments.addView(commentItem, 1); } }); } else { PlayActivity.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(mContext, R.string.comment_failed, Toast.LENGTH_SHORT).show(); } }); } } }); } catch (ParseException e) { e.printStackTrace(); } } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.pre_play_button: mPrePlayButton.setVisibility(View.INVISIBLE); mVideoAction.setVisibility(View.INVISIBLE); mPlaybtn.performClick(); startPlay(mLastPos); updateControlBar(false); if (mSharedPreferences.getBoolean("use_hd", true)) { mVV.setVideoPath(mVideoInfo.HDVideoUrl); } else { mVV.setVideoPath(mVideoInfo.CommonVideoUrl); } break; case R.id.play_btn: if (mVV.isPlaying()) { mPlaybtn.setBackgroundResource(R.drawable.play_btn_style); mVV.pause(); } else { mPlaybtn.setBackgroundResource(R.drawable.pause_btn_style); mVV.resume(); } mController.setVisibility(View.INVISIBLE); break; case R.id.comment_edit_text: comment(); break; case R.id.recommand_view: stopPlay(); VideoDataFormat videoDataFormat = (VideoDataFormat) v.getTag(); Intent intent = new Intent(mContext, PlayActivity.class); intent.putExtra("VideoInfo", videoDataFormat); mContext.startActivity(intent); MobclickAgent.onEvent(mContext, "recommend"); finish(); break; case R.id.zoom_btn: if (mCurrentScape == OrientationHelper.LANDSCAPE) { setMinSize(); } else { setMaxSize(); } break; default: break; } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; case R.id.action_fav: if (mVideoInfo.isFavorite()) { if (mVideoDB.removeFav(mVideoInfo) > 0) { Toast.makeText(mContext, R.string.fav_del_success, Toast.LENGTH_SHORT).show(); item.setIcon(R.drawable.ab_fav_normal); mVideoInfo.setFav(false); } else { Toast.makeText(mContext, R.string.fav_del_fail, Toast.LENGTH_SHORT).show(); } } else { if (mVideoDB.insertFav(mVideoInfo) > 0) { Toast.makeText(mContext, R.string.fav_success, Toast.LENGTH_SHORT).show(); item.setIcon(R.drawable.ab_fav_active); mVideoInfo.setFav(true); } else { Toast.makeText(mContext, R.string.fav_fail, Toast.LENGTH_SHORT).show(); } } return true; default: break; } return super.onOptionsItemSelected(item); } @Override public void onBitmapFailed() { if (mShareActionProvider != null) { mShareActionProvider.setShareIntent(getDefaultIntent()); } } @Override public void onBitmapLoaded(Bitmap bitmap, LoadedFrom arg1) { mDetailImageView.setImageBitmap(bitmap); mDetailPicture = bitmap; mLoadingGif.setVisibility(View.INVISIBLE); mPrePlayButton.setVisibility(View.VISIBLE); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); mDetailPicture.compress(CompressFormat.JPEG, 100, bytes); File dir = new File(Environment.getExternalStorageDirectory() + File.separator + mDir); if (dir.exists() == false || dir.isDirectory() == false) dir.mkdir(); File file = new File(Environment.getExternalStorageDirectory() + File.separator + mDir + File.separator + mShareName); try { file.createNewFile(); FileOutputStream fo = new FileOutputStream(file); fo.write(bytes.toByteArray()); fo.close(); if (mShareActionProvider != null) { mShareActionProvider.setShareIntent(getDefaultIntent()); } } catch (IOException e) { e.printStackTrace(); } } private class CommentsTask extends AsyncTask<Void, LinearLayout, Void> { @Override protected void onPreExecute() { super.onPreExecute(); if (mLoadMoreComment != null) { mLoadMoreComment.findViewById(R.id.load_progressbar) .setVisibility(View.VISIBLE); mLoadMoreComment.findViewById(R.id.load_more_comment_btn) .setVisibility(View.GONE); } } @Override protected Void doInBackground(Void... params) { ParseQuery<ParseObject> query = new ParseQuery<ParseObject>( "Comments"); query.whereEqualTo("vid", mVideoInfo.Id); query.setLimit(mStep); query.setSkip(mSkip); query.include("uid"); query.orderByDescending("updatedAt"); try { List<ParseObject> commentList = query.find(); if (commentList.size() < mStep) { mCommentFinished = true; } ArrayList<LinearLayout> commentsLayout = new ArrayList<LinearLayout>(); for (ParseObject comment : commentList) { ParseObject user = comment.getParseObject("uid"); Comment commentInformation = new Comment( user.getString("username"), user.getString("avatar"), user.getString("platform"), comment.getUpdatedAt(), comment.getString("content")); LinearLayout commentItem = (LinearLayout) mLayoutInflater .inflate(R.layout.comment_item, null); TextView content = (TextView) commentItem .findViewById(R.id.content); content.setText(commentInformation.Content); ImageView avatar = (ImageView) commentItem .findViewById(R.id.avatar); Picasso.with(mContext).load(commentInformation.Avatar) .into(avatar); TextView username = (TextView) commentItem .findViewById(R.id.name); username.setText(commentInformation.Username); TextView date = (TextView) commentItem .findViewById(R.id.time); date.setText(mPrettyTime.format(commentInformation.Date)); commentsLayout.add(commentItem); } mSkip += mStep; mCommentCount += commentList.size(); publishProgress(commentsLayout .toArray(new LinearLayout[commentList.size()])); } catch (ParseException e) { e.printStackTrace(); } return null; } @Override protected void onProgressUpdate(LinearLayout... values) { super.onProgressUpdate(values); if (mLoadMoreComment != null) { mComments.removeView(mLoadMoreComment); } for (LinearLayout commentView : values) { mComments.addView(commentView); } } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); if (mCommentFinished == false) { mLoadMoreComment = mLayoutInflater.inflate( R.layout.comment_load_more, null); mLoadMoreButton = (Button) mLoadMoreComment .findViewById(R.id.load_more_comment_btn); mComments.addView(mLoadMoreComment); mLoadMoreButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new CommentsTask().execute(); MobclickAgent.onEvent(mContext, "more_comment"); } }); } else { if (mCommentCount > 5) { mLoadMoreButton.setText(R.string.no_more_comments); mLoadMoreButton.setEnabled(false); } } } } private class CheckIsFavorite extends AsyncTask<Void, Void, Boolean> { @Override protected Boolean doInBackground(Void... params) { return mVideoDB.isFav(mVideoInfo.Id); } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); mVideoInfo.setFav(result); if (result) { mFavMenuItem.setIcon(R.drawable.ab_fav_active); } } } @SuppressLint("HandlerLeak") private Handler mAuthHandler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case SocialPlatform.AUTH_SUCCESS: Toast.makeText(mContext, R.string.login_success, Toast.LENGTH_SHORT).show(); break; case SocialPlatform.AUTH_FAILED: Toast.makeText(mContext, R.string.login_failed, Toast.LENGTH_SHORT).show(); break; default: break; } }; }; @SuppressLint("HandlerLeak") Handler mUIHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case UI_EVENT_UPDATE_CURRPOSITION: int currPosition = mVV.getCurrentPosition(); int duration = mVV.getDuration(); updateTextViewWithTimeFormat(mCurrPostion, currPosition); updateTextViewWithTimeFormat(mDuration, duration); mProgress.setMax(duration); mProgress.setProgress(currPosition); mUIHandler.sendEmptyMessageDelayed( UI_EVENT_UPDATE_CURRPOSITION, 200); break; default: break; } } }; private void updateTextViewWithTimeFormat(TextView view, int second) { int hh = second / 3600; int mm = second % 3600 / 60; int ss = second % 60; String strTemp = null; if (0 != hh) { strTemp = String.format(Locale.CHINA, "%02d:%02d:%02d", hh, mm, ss); } else { strTemp = String.format(Locale.CHINA, "%02d:%02d", mm, ss); } view.setText(strTemp); } public void updateControlBar(boolean show) { if (show) { if (mController.getVisibility() == View.INVISIBLE) { mController.setVisibility(View.VISIBLE); new Timer().schedule(new TimerTask() { @Override public void run() { PlayActivity.this.runOnUiThread(new Runnable() { @Override public void run() { updateControlBar(false); } }); } }, 4000); } } else { mController.setVisibility(View.INVISIBLE); } } private void initPlayer() { BVideoView.setAKSK(AK, SK); mZoomButton.setOnClickListener(this); mVV.setVideoScalingMode(BVideoView.VIDEO_SCALING_MODE_SCALE_TO_FIT); mPlaybtn.setOnClickListener(this); mVV.setOnPreparedListener(this); mVV.setOnCompletionListener(this); mVV.setOnErrorListener(this); registerCallbackForControls(); } private void initContent() { mTitleTextView.setTypeface(mRobotoBold); mAutherTextView.setTypeface(mRobotoThin); mTitleTextView.setText(mVideoInfo.Name); mContentTextView.setText(mVideoInfo.Brief); mAutherTextView.setText(mVideoInfo.Author + " · " + mVideoInfo.Year); mPrePlayButton.setOnClickListener(this); mViewHolder.setOnTouchListener(this); mCommentEditText.setOnClickListener(this); if (getShareFile() != null) { getShareFile().delete(); } Picasso.with(mContext).load(mVideoInfo.DetailPic) .placeholder(R.drawable.big_bg).into(this); } private void startPlay(int from) { setMaxSize(); mVV.seekTo(from); mVV.start(); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } private void stopPlay() { if (mVV.isPlaying() == false) return; mLastPos = mVV.getCurrentPosition(); mVV.stopPlayback(); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } private void pausePlay() { if (mVV.isPlaying() == false) return; mLastPos = mVV.getCurrentPosition(); mVV.pause(); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } @SuppressLint("InlinedApi") private void setMaxSize() { if (Build.VERSION.SDK_INT >= 9) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE); } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); getSupportActionBar().hide(); RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams( Screen.getScreenWidth(getWindowManager()), Screen.getScreenHeight(getWindowManager())); mHeaderWrpper.setLayoutParams(param); mVV.setLayoutParams(param); mZoomButton.setBackgroundResource(R.drawable.screensize_zoomin_button); mCurrentScape = OrientationHelper.LANDSCAPE; } private void setMinSize() { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); getSupportActionBar().show(); RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams( Screen.getScreenWidth(getWindowManager()), getResources() .getDimensionPixelSize(R.dimen.player_height)); mHeaderWrpper.setLayoutParams(param); mVV.setLayoutParams(param); mZoomButton.setBackgroundResource(R.drawable.screensize_zoomout_button); mCurrentScape = OrientationHelper.PORTRAIT; } private void registerCallbackForControls() { OnSeekBarChangeListener seekBarChangeListener = new OnSeekBarChangeListener() { public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { updateTextViewWithTimeFormat(mCurrPostion, progress); } public void onStartTrackingTouch(SeekBar seekBar) { mUIHandler.removeMessages(UI_EVENT_UPDATE_CURRPOSITION); } public void onStopTrackingTouch(SeekBar seekBar) { int iseekPos = seekBar.getProgress(); mVV.seekTo(iseekPos); mUIHandler.sendEmptyMessage(UI_EVENT_UPDATE_CURRPOSITION); } }; mProgress.setOnSeekBarChangeListener(seekBarChangeListener); } @Override public boolean onError(int arg0, int arg1) { Toast.makeText(mContext, R.string.play_error, Toast.LENGTH_SHORT) .show(); return true; } @SuppressLint("HandlerLeak") private Handler mCompleteHandler = new Handler() { public void handleMessage(android.os.Message msg) { mPrePlayButton.setVisibility(View.VISIBLE); mVideoAction.setVisibility(View.VISIBLE); }; }; @Override public void onCompletion() { mCompleteHandler.sendEmptyMessage(0); mLastPos = 0; int playcount = mSharedPreferences.getInt("playcount", 0); mSharedPreferences.edit().putInt("playcount", playcount + 1).commit(); if (mCurrentScape == OrientationHelper.LANDSCAPE) { PlayActivity.this.runOnUiThread(new Runnable() { @Override public void run() { setMinSize(); } }); } } @Override protected void onResume() { super.onResume(); if (mLastPos != 0) { startPlay(mLastPos); } MobclickAgent.onResume(mContext); } @Override protected void onPause() { super.onPause(); pausePlay(); MobclickAgent.onPause(mContext); } @Override protected void onDestroy() { super.onDestroy(); stopPlay(); if (mOrientationEventListener != null) mOrientationEventListener.disable(); } @Override public void onPrepared() { mUIHandler.sendEmptyMessage(UI_EVENT_UPDATE_CURRPOSITION); } @Override public boolean onTouch(View v, MotionEvent event) { updateControlBar(true); return false; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (mCurrentScape == OrientationHelper.LANDSCAPE) { setMinSize(); return true; } } return super.onKeyDown(keyCode, event); } };
3e1dcd03f5f32e3397debc361ead70a8c49d280f
7,759
java
Java
ZhihuDailyPurify/src/main/java/io/github/izzyleung/zhihudailypurify/ui/activity/MainActivity.java
nsdown/ZhihuDailyPurify
0c99b542af1275f770e51d4f70e932b84096e4f5
[ "Apache-2.0" ]
9
2020-03-09T12:32:59.000Z
2021-01-06T23:38:57.000Z
ZhihuDailyPurify/src/main/java/io/github/izzyleung/zhihudailypurify/ui/activity/MainActivity.java
nsdown/ZhihuDailyPurify
0c99b542af1275f770e51d4f70e932b84096e4f5
[ "Apache-2.0" ]
null
null
null
ZhihuDailyPurify/src/main/java/io/github/izzyleung/zhihudailypurify/ui/activity/MainActivity.java
nsdown/ZhihuDailyPurify
0c99b542af1275f770e51d4f70e932b84096e4f5
[ "Apache-2.0" ]
1
2021-12-11T12:11:11.000Z
2021-12-11T12:11:11.000Z
36.257009
96
0.610001
12,619
package io.github.izzyleung.zhihudailypurify.ui.activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import android.view.ViewGroup; import android.widget.LinearLayout; import com.astuetz.PagerSlidingTabStrip; import com.espian.showcaseview.ShowcaseView; import com.espian.showcaseview.ShowcaseViews; import io.github.izzyleung.zhihudailypurify.R; import io.github.izzyleung.zhihudailypurify.support.util.DateUtils; import io.github.izzyleung.zhihudailypurify.ui.fragment.NewsListFragment; import java.lang.ref.WeakReference; import java.text.SimpleDateFormat; import java.util.Calendar; public class MainActivity extends ActionBarActivity { private LinearLayout mainFrame; private MainPagerAdapter adapter; private boolean isGetFirstPage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SharedPreferences pref = PreferenceManager. getDefaultSharedPreferences(this); isGetFirstPage = pref.getBoolean("get_first_page?", true); if (isGetFirstPage) { SharedPreferences.Editor editor = pref.edit(); editor.putBoolean("get_first_page?", false); editor.commit(); mainFrame = (LinearLayout) findViewById(R.id.main_frame); } PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.main_pager_tabs); ViewPager viewPager = (ViewPager) findViewById(R.id.main_pager); viewPager.setOffscreenPageLimit(7); adapter = new MainPagerAdapter(getSupportFragmentManager()); viewPager.setAdapter(adapter); tabs.setViewPager(viewPager); tabs.setIndicatorColor(getResources().getColor(R.color.holo_blue)); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); SharedPreferences pref = PreferenceManager. getDefaultSharedPreferences(MainActivity.this); boolean isShowShowcase = pref.getBoolean("show_showcase?", true); if (isShowShowcase) { showCase(pref); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: Intent intent = new Intent(); intent.setClass(MainActivity.this, PrefsActivity.class); startActivity(intent); return true; case R.id.action_pick_date: intent = new Intent(); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_YEAR, -7); intent.putExtra("date", DateUtils.simpleDateFormat.format(calendar.getTime())); intent.setClass(MainActivity.this, PickDateActivity.class); startActivity(intent); return true; case R.id.action_go_to_search: intent = new Intent(); intent.setClass(MainActivity.this, SearchActivity.class); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } private void showCase(SharedPreferences pref) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mainFrame.setAlpha(0.1f); } ShowcaseView.ConfigOptions options = new ShowcaseView.ConfigOptions(); options.hideOnClickOutside = false; ShowcaseViews showcaseViews = new ShowcaseViews(this, new ShowcaseViews. OnShowcaseAcknowledged() { @Override public void onShowCaseAcknowledged(ShowcaseView showcaseView) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mainFrame.setAlpha(1.0f); } NewsListFragment firstPage = adapter.getFirstPage(); if (firstPage != null) { adapter.getFirstPage().refresh(); } } }); showcaseViews.addView(new ShowcaseViews.ItemViewProperties( R.id.action_go_to_search, R.string.showcase_search_title, R.string.showcase_search_message, ShowcaseView.ITEM_ACTION_ITEM, 0.5f, options )); showcaseViews.addView(new ShowcaseViews.ItemViewProperties( R.id.action_pick_date, R.string.showcase_calendar_title, R.string.showcase_calendar_message, ShowcaseView.ITEM_ACTION_ITEM, 0.5f, options )); showcaseViews.show(); SharedPreferences.Editor editor = pref.edit(); editor.putBoolean("show_showcase?", false); editor.commit(); } final class MainPagerAdapter extends FragmentStatePagerAdapter { private WeakReference<NewsListFragment> firstPage; public MainPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int i) { Bundle bundle = new Bundle(); Fragment newFragment = new NewsListFragment(); newFragment.setArguments(bundle); Calendar dateToGetUrl = Calendar.getInstance(); dateToGetUrl.add(Calendar.DAY_OF_YEAR, 1 - i); String date = DateUtils.simpleDateFormat.format(dateToGetUrl.getTime()); bundle.putBoolean("first_page?", i == 0); bundle.putBoolean("single?", false); bundle.putString("date", date); return newFragment; } @Override public Object instantiateItem(ViewGroup container, int position) { Object object = super.instantiateItem(container, position); if (position == 0 && isGetFirstPage) { firstPage = new WeakReference<NewsListFragment>((NewsListFragment) object); } return object; } @Override public void destroyItem(ViewGroup container, int position, Object object) { if (position == 0 && isGetFirstPage && firstPage != null) { firstPage.clear(); } super.destroyItem(container, position, object); } public NewsListFragment getFirstPage() { return firstPage == null ? null : firstPage.get(); } @Override public int getCount() { return 7; } @Override public CharSequence getPageTitle(int position) { Calendar displayDate = Calendar.getInstance(); displayDate.add(Calendar.DAY_OF_YEAR, -position); String date = new SimpleDateFormat(getString(R.string.display_format)). format(displayDate.getTime()); if (position == 0) { return getString(R.string.zhihu_daily_today) + " " + date; } else { return date; } } } }
3e1dcdf7d119f3733d6dedb92ca7f5b34790ca78
12,743
java
Java
src/main/java/org/synyx/urlaubsverwaltung/overtime/web/OvertimeViewController.java
fredondiek/urlaubsverwaltung
7941034ffc0c1c0e238f291f1a8ab20e8e080dd0
[ "Apache-2.0" ]
220
2015-01-19T17:20:22.000Z
2022-03-10T14:37:03.000Z
src/main/java/org/synyx/urlaubsverwaltung/overtime/web/OvertimeViewController.java
fredondiek/urlaubsverwaltung
7941034ffc0c1c0e238f291f1a8ab20e8e080dd0
[ "Apache-2.0" ]
2,170
2015-01-07T09:02:09.000Z
2022-03-31T13:50:17.000Z
src/main/java/org/synyx/urlaubsverwaltung/overtime/web/OvertimeViewController.java
fredondiek/urlaubsverwaltung
7941034ffc0c1c0e238f291f1a8ab20e8e080dd0
[ "Apache-2.0" ]
117
2015-01-16T09:35:56.000Z
2022-03-25T10:13:24.000Z
46.00361
129
0.726124
12,620
package org.synyx.urlaubsverwaltung.overtime.web; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.AccessDeniedException; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.DataBinder; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.synyx.urlaubsverwaltung.department.DepartmentService; import org.synyx.urlaubsverwaltung.overtime.Overtime; import org.synyx.urlaubsverwaltung.overtime.OvertimeCommentAction; import org.synyx.urlaubsverwaltung.overtime.OvertimeService; import org.synyx.urlaubsverwaltung.overtime.OvertimeSettings; import org.synyx.urlaubsverwaltung.person.Person; import org.synyx.urlaubsverwaltung.person.PersonService; import org.synyx.urlaubsverwaltung.person.UnknownPersonException; import org.synyx.urlaubsverwaltung.person.web.PersonPropertyEditor; import org.synyx.urlaubsverwaltung.settings.SettingsService; import org.synyx.urlaubsverwaltung.web.DecimalNumberPropertyEditor; import org.synyx.urlaubsverwaltung.web.LocalDatePropertyEditor; import javax.validation.Valid; import java.math.BigDecimal; import java.time.Clock; import java.time.LocalDate; import java.time.Year; import java.util.List; import java.util.Locale; import java.util.Optional; import static org.synyx.urlaubsverwaltung.person.Role.OFFICE; /** * Manage overtime of persons. */ @Controller @RequestMapping("/web") public class OvertimeViewController { private static final String PERSON_ATTRIBUTE = "person"; private static final String PERSONS_ATTRIBUTE = "persons"; private static final String SIGNED_IN_USER = "signedInUser"; private static final String OVERTIME = "overtime"; private static final String IS_OFFICE_ATTRIBUTE = "isOffice"; private static final String OVERTIME_OVERTIME_FORM = "overtime/overtime_form"; private final OvertimeService overtimeService; private final PersonService personService; private final OvertimeFormValidator validator; private final DepartmentService departmentService; private final Clock clock; private final SettingsService settingsService; @Autowired public OvertimeViewController(OvertimeService overtimeService, PersonService personService, OvertimeFormValidator validator, DepartmentService departmentService, SettingsService settingsService, Clock clock) { this.overtimeService = overtimeService; this.personService = personService; this.validator = validator; this.departmentService = departmentService; this.settingsService = settingsService; this.clock = clock; } @InitBinder public void initBinder(DataBinder binder, Locale locale) { binder.registerCustomEditor(LocalDate.class, new LocalDatePropertyEditor()); binder.registerCustomEditor(BigDecimal.class, new DecimalNumberPropertyEditor(locale)); binder.registerCustomEditor(Person.class, new PersonPropertyEditor(personService)); } @GetMapping("/overtime") public String showPersonalOvertime() { final Person signedInUser = personService.getSignedInUser(); return "redirect:/web/overtime?person=" + signedInUser.getId(); } @GetMapping(value = "/overtime", params = PERSON_ATTRIBUTE) public String showOvertime( @RequestParam(value = PERSON_ATTRIBUTE) Integer personId, @RequestParam(value = "year", required = false) Integer requestedYear, Model model) throws UnknownPersonException { final int year = requestedYear == null ? Year.now(clock).getValue() : requestedYear; final Person person = personService.getPersonByID(personId).orElseThrow(() -> new UnknownPersonException(personId)); final Person signedInUser = personService.getSignedInUser(); if (!departmentService.isSignedInUserAllowedToAccessPersonData(signedInUser, person)) { throw new AccessDeniedException(String.format( "User '%s' has not the correct permissions to see overtime records of user '%s'", signedInUser.getId(), person.getId())); } model.addAttribute("year", year); model.addAttribute(PERSON_ATTRIBUTE, person); model.addAttribute(SIGNED_IN_USER, signedInUser); final OvertimeListDto overtimeListDto = OvertimeListMapper.mapToDto( overtimeService.getOvertimeRecordsForPersonAndYear(person, year), overtimeService.getTotalOvertimeForPersonAndYear(person, year), overtimeService.getLeftOvertimeForPerson(person)); model.addAttribute("records", overtimeListDto.getRecords()); model.addAttribute("overtimeTotal", overtimeListDto.getOvertimeTotal()); model.addAttribute("overtimeLeft", overtimeListDto.getOvertimeLeft()); model.addAttribute("userIsAllowedToWriteOvertime", overtimeService.isUserIsAllowedToWriteOvertime(signedInUser, person)); return "overtime/overtime_list"; } @GetMapping("/overtime/{id}") public String showOvertimeDetails(@PathVariable("id") Integer id, Model model) throws UnknownOvertimeException { final Overtime overtime = overtimeService.getOvertimeById(id).orElseThrow(() -> new UnknownOvertimeException(id)); final Person person = overtime.getPerson(); final Person signedInUser = personService.getSignedInUser(); if (!departmentService.isSignedInUserAllowedToAccessPersonData(signedInUser, person)) { throw new AccessDeniedException(String.format( "User '%s' has not the correct permissions to see overtime records of user '%s'", signedInUser.getId(), person.getId())); } model.addAttribute(SIGNED_IN_USER, signedInUser); final OvertimeDetailsDto overtimeDetailsDto = OvertimeDetailsMapper.mapToDto( overtime, overtimeService.getCommentsForOvertime(overtime), overtimeService.getTotalOvertimeForPersonAndYear(person, overtime.getEndDate().getYear()), overtimeService.getLeftOvertimeForPerson(person)); model.addAttribute("record", overtimeDetailsDto.getRecord()); model.addAttribute("comments", overtimeDetailsDto.getComments()); model.addAttribute("overtimeTotal", overtimeDetailsDto.getOvertimeTotal()); model.addAttribute("overtimeLeft", overtimeDetailsDto.getOvertimeLeft()); model.addAttribute("userIsAllowedToWriteOvertime", overtimeService.isUserIsAllowedToWriteOvertime(signedInUser, person)); return "overtime/overtime_details"; } @GetMapping("/overtime/new") public String recordOvertime( @RequestParam(value = PERSON_ATTRIBUTE, required = false) Integer personId, Model model) throws UnknownPersonException { final Person signedInUser = personService.getSignedInUser(); final Person person; if (personId != null) { person = personService.getPersonByID(personId).orElseThrow(() -> new UnknownPersonException(personId)); } else { person = signedInUser; } if (!overtimeService.isUserIsAllowedToWriteOvertime(signedInUser, person)) { throw new AccessDeniedException(String.format( "User '%s' has not the correct permissions to record overtime for user '%s'", signedInUser.getId(), person.getId())); } final OvertimeForm overtimeForm = new OvertimeForm(person); prepareModelForCreation(model, signedInUser, person, overtimeForm); return OVERTIME_OVERTIME_FORM; } @PostMapping("/overtime") public String recordOvertime(@Valid @ModelAttribute(OVERTIME) OvertimeForm overtimeForm, Errors errors, Model model, RedirectAttributes redirectAttributes) { final Person signedInUser = personService.getSignedInUser(); final Person person = overtimeForm.getPerson(); if (!overtimeService.isUserIsAllowedToWriteOvertime(signedInUser, person)) { throw new AccessDeniedException(String.format( "User '%s' has not the correct permissions to record overtime for user '%s'", signedInUser.getId(), person.getId())); } validator.validate(overtimeForm, errors); if (errors.hasErrors()) { prepareModelForCreation(model, signedInUser, person, overtimeForm); return OVERTIME_OVERTIME_FORM; } final Overtime overtime = overtimeForm.generateOvertime(); final Optional<String> overtimeFormComment = Optional.ofNullable(overtimeForm.getComment()); final Overtime recordedOvertime = overtimeService.record(overtime, overtimeFormComment, signedInUser); redirectAttributes.addFlashAttribute("overtimeRecord", OvertimeCommentAction.CREATED.name()); return "redirect:/web/overtime/" + recordedOvertime.getId(); } @GetMapping("/overtime/{id}/edit") public String editOvertime(@PathVariable("id") Integer id, Model model) throws UnknownOvertimeException { final Overtime overtime = overtimeService.getOvertimeById(id).orElseThrow(() -> new UnknownOvertimeException(id)); final Person signedInUser = personService.getSignedInUser(); final Person person = overtime.getPerson(); if (!overtimeService.isUserIsAllowedToWriteOvertime(signedInUser, person)) { throw new AccessDeniedException(String.format( "User '%s' has not the correct permissions to edit overtime record of user '%s'", signedInUser.getId(), person.getId())); } prepareModelForEdit(model, signedInUser, person, new OvertimeForm(overtime)); return OVERTIME_OVERTIME_FORM; } @PostMapping("/overtime/{id}") public String updateOvertime(@PathVariable("id") Integer id, @ModelAttribute(OVERTIME) OvertimeForm overtimeForm, Errors errors, Model model, RedirectAttributes redirectAttributes) throws UnknownOvertimeException { final Overtime overtime = overtimeService.getOvertimeById(id).orElseThrow(() -> new UnknownOvertimeException(id)); final Person signedInUser = personService.getSignedInUser(); final Person person = overtime.getPerson(); if (!overtimeService.isUserIsAllowedToWriteOvertime(signedInUser, person)) { throw new AccessDeniedException(String.format( "User '%s' has not the correct permissions to edit overtime record of user '%s'", signedInUser.getId(), person.getId())); } validator.validate(overtimeForm, errors); if (errors.hasErrors()) { prepareModelForEdit(model, signedInUser, person, overtimeForm); return OVERTIME_OVERTIME_FORM; } overtimeForm.updateOvertime(overtime); overtimeService.record(overtime, Optional.ofNullable(overtimeForm.getComment()), signedInUser); redirectAttributes.addFlashAttribute("overtimeRecord", OvertimeCommentAction.EDITED.name()); return "redirect:/web/overtime/" + id; } private void prepareModelForCreation(Model model, Person signedInUser, Person person, OvertimeForm overtimeForm) { if (signedInUser.hasRole(OFFICE)) { final List<Person> persons = personService.getActivePersons(); model.addAttribute(PERSONS_ATTRIBUTE, persons); } prepareModelForEdit(model, signedInUser, person, overtimeForm); } private void prepareModelForEdit(Model model, Person signedInUser, Person person, OvertimeForm overtimeForm) { model.addAttribute(OVERTIME, overtimeForm); model.addAttribute(PERSON_ATTRIBUTE, person); model.addAttribute(SIGNED_IN_USER, signedInUser); model.addAttribute(IS_OFFICE_ATTRIBUTE, signedInUser.hasRole(OFFICE)); final OvertimeSettings overtimeSettings = settingsService.getSettings().getOvertimeSettings(); model.addAttribute("overtimeReductionPossible", overtimeSettings.isOvertimeReductionWithoutApplicationActive()); } }
3e1dce0409d406c44adedd00f443c6dfeafc073e
315
java
Java
src/main/java/io/renren/modules/WeiYu/mapper/trainingToDetailMapper.java
PaoMoXML/WeiYu
7b1f7f1741320cff1da9ad5525ef3a5bc92f4b30
[ "Apache-2.0" ]
1
2020-08-07T14:40:50.000Z
2020-08-07T14:40:50.000Z
src/main/java/io/renren/modules/WeiYu/mapper/trainingToDetailMapper.java
PaoMoXML/WeiYu
7b1f7f1741320cff1da9ad5525ef3a5bc92f4b30
[ "Apache-2.0" ]
1
2021-09-20T20:51:14.000Z
2021-09-20T20:51:14.000Z
src/main/java/io/renren/modules/WeiYu/mapper/trainingToDetailMapper.java
PaoMoXML/WeiYu
7b1f7f1741320cff1da9ad5525ef3a5bc92f4b30
[ "Apache-2.0" ]
null
null
null
22.5
56
0.8
12,621
package io.renren.modules.WeiYu.mapper; import io.renren.modules.WeiYu.model.trainingToDetail; import java.util.List; public interface trainingToDetailMapper { int insert(trainingToDetail record); int insertSelective(trainingToDetail record); List<trainingToDetail>selectByid(String trainingid); }
3e1dcedf13a6af05145ec70a2d0a0be66f2bb67a
1,080
java
Java
build/tmp/expandedArchives/forge-1.16.5-36.0.46_mapped_snapshot_20201028-1.16.3-sources.jar_d86e7e7643b801f3a450d94fefd63481/net/minecraft/client/settings/AmbientOcclusionStatus.java
JoppeGames1/TvStudio-1_16
181f67939b6c67e410e7881b20e10508b74e306b
[ "Apache-2.0" ]
2
2020-11-28T06:31:55.000Z
2020-11-29T22:15:39.000Z
build/tmp/expandedArchives/forge-1.16.5-36.0.46_mapped_snapshot_20201028-1.16.3-sources.jar_d86e7e7643b801f3a450d94fefd63481/net/minecraft/client/settings/AmbientOcclusionStatus.java
JoppeGames1/TvStudio-1_16
181f67939b6c67e410e7881b20e10508b74e306b
[ "Apache-2.0" ]
1
2020-12-05T14:47:34.000Z
2020-12-05T14:47:34.000Z
build/tmp/expandedArchives/forge-1.16.5-36.0.46_mapped_snapshot_20201028-1.16.3-sources.jar_d86e7e7643b801f3a450d94fefd63481/net/minecraft/client/settings/AmbientOcclusionStatus.java
JoppeGames1/TvStudio-1_16
181f67939b6c67e410e7881b20e10508b74e306b
[ "Apache-2.0" ]
3
2020-11-28T20:19:58.000Z
2020-11-29T22:16:03.000Z
28.421053
171
0.730556
12,622
package net.minecraft.client.settings; import java.util.Arrays; import java.util.Comparator; import net.minecraft.util.math.MathHelper; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; @OnlyIn(Dist.CLIENT) public enum AmbientOcclusionStatus { OFF(0, "options.ao.off"), MIN(1, "options.ao.min"), MAX(2, "options.ao.max"); private static final AmbientOcclusionStatus[] VALUES = Arrays.stream(values()).sorted(Comparator.comparingInt(AmbientOcclusionStatus::getId)).toArray((p_216571_0_) -> { return new AmbientOcclusionStatus[p_216571_0_]; }); private final int id; private final String resourceKey; private AmbientOcclusionStatus(int idIn, String resourceKeyIn) { this.id = idIn; this.resourceKey = resourceKeyIn; } public int getId() { return this.id; } public String getResourceKey() { return this.resourceKey; } public static AmbientOcclusionStatus getValue(int valueIn) { return VALUES[MathHelper.normalizeAngle(valueIn, VALUES.length)]; } }
3e1dcfbd124a7f29111969ad5639ec1903323228
2,282
java
Java
saksbehandling/webapp/src/test/java/no/nav/foreldrepenger/web/app/konfig/SoapApiAbacTest.java
navikt/spsak
ede4770de33bd896d62225a9617b713878d1efa5
[ "MIT" ]
1
2019-11-15T10:37:38.000Z
2019-11-15T10:37:38.000Z
saksbehandling/webapp/src/test/java/no/nav/foreldrepenger/web/app/konfig/SoapApiAbacTest.java
navikt/spsak
ede4770de33bd896d62225a9617b713878d1efa5
[ "MIT" ]
null
null
null
saksbehandling/webapp/src/test/java/no/nav/foreldrepenger/web/app/konfig/SoapApiAbacTest.java
navikt/spsak
ede4770de33bd896d62225a9617b713878d1efa5
[ "MIT" ]
1
2019-11-15T10:37:41.000Z
2019-11-15T10:37:41.000Z
37.409836
176
0.68624
12,623
package no.nav.foreldrepenger.web.app.konfig; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.Collection; import org.junit.BeforeClass; import org.junit.Test; import no.nav.vedtak.sikkerhet.abac.BeskyttetRessurs; import no.nav.vedtak.sikkerhet.abac.TilpassetAbacAttributt; public class SoapApiAbacTest { private static Collection<Method> soapMethods; @BeforeClass public static void init() { soapMethods = SoapApiTester.finnAlleSoapMetoder(); } /** * IKKE ignorer denne testen, sikrer at SOAP-endepunkter får tilgangskontroll * <p> * Kontakt Team Humle hvis du trenger hjelp til å endre koden din slik at den går igjennom her * */ @Test public void test_at_alle_soapmetoder_er_annotert_med_BeskyttetRessurs() throws Exception { for (Method soapMethod : SoapApiTester.finnAlleSoapMetoder()) { if (soapMethod.getAnnotation(BeskyttetRessurs.class) == null) { throw new AssertionError("Mangler @" + BeskyttetRessurs.class.getSimpleName() + "-annotering på " + soapMethod); } } } /** * IKKE ignorer denne testen, helper til med at input til tilgangskontroll blir riktig * <p> * Kontakt Team Humle hvis du trenger hjelp til å endre koden din slik at den går igjennom her */ @Test public void test_at_alle_input_parametre_til_soapmetoder_er_annotert_med_TilpassetAbacAttributt() { String feilmelding = "Parameter type %s på metode %s.%s må ha annotering " + TilpassetAbacAttributt.class.getSimpleName() + ".\n"; StringBuilder feilmeldinger = new StringBuilder(); for (Method soapMethod : soapMethods) { for (Parameter parameter : soapMethod.getParameters()) { if (parameter.getAnnotation(TilpassetAbacAttributt.class) == null) { feilmeldinger.append(String.format(feilmelding, parameter.getType().getSimpleName(), soapMethod.getDeclaringClass().getSimpleName(), soapMethod.getName())); } } } if (feilmeldinger.length() > 0) { throw new AssertionError("Følgende inputparametre til SOAP-tjenester passerte ikke validering\n" + feilmeldinger); } } }
3e1dd00df86fc8b08994fca55a88ecd3c68cf74f
827
java
Java
app/src/main/java/com/example/sayandeep/fooddelivery/MainActivity.java
SayandeepLahiri/FoodDelivery
b4972cd70723dbbc1126cd43ee7762ffe66b3199
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/sayandeep/fooddelivery/MainActivity.java
SayandeepLahiri/FoodDelivery
b4972cd70723dbbc1126cd43ee7762ffe66b3199
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/sayandeep/fooddelivery/MainActivity.java
SayandeepLahiri/FoodDelivery
b4972cd70723dbbc1126cd43ee7762ffe66b3199
[ "Apache-2.0" ]
1
2021-09-01T20:00:04.000Z
2021-09-01T20:00:04.000Z
26.677419
82
0.738815
12,624
package com.example.sayandeep.fooddelivery; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; public class MainActivity extends AppCompatActivity { private FirebaseAuth firebaseAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); firebaseAuth=FirebaseAuth.getInstance(); } @Override protected void onStart() { super.onStart(); FirebaseUser currentUser=firebaseAuth.getCurrentUser(); Intent singUpIntent=new Intent(MainActivity.this,LoginActivity.class); startActivity(singUpIntent); } }
3e1dd0593ad0ab331df34935ac018558452b2788
4,051
java
Java
drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraResubmitTable.java
mary-grace/onos
c0e351f8b84537bb7562e148d4cb2b9f06e8a727
[ "Apache-2.0" ]
1,091
2015-01-06T11:10:40.000Z
2022-03-30T09:09:05.000Z
drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraResubmitTable.java
mary-grace/onos
c0e351f8b84537bb7562e148d4cb2b9f06e8a727
[ "Apache-2.0" ]
39
2015-02-13T19:58:32.000Z
2022-03-02T02:38:07.000Z
drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraResubmitTable.java
mary-grace/onos
c0e351f8b84537bb7562e148d4cb2b9f06e8a727
[ "Apache-2.0" ]
914
2015-01-05T19:42:35.000Z
2022-03-30T09:25:18.000Z
27.937931
91
0.651197
12,625
/* * Copyright 2016-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.driver.extensions; import com.google.common.base.MoreObjects; import com.google.common.collect.Maps; import org.onlab.util.KryoNamespace; import org.onosproject.net.PortNumber; import org.onosproject.net.flow.AbstractExtension; import org.onosproject.net.flow.instructions.ExtensionTreatment; import org.onosproject.net.flow.instructions.ExtensionTreatmentType; import org.onosproject.store.serializers.PortNumberSerializer; import java.util.HashMap; import java.util.Map; import java.util.Objects; import static com.google.common.base.Preconditions.checkNotNull; /** * Nicira resubmit-table extension instruction. */ public class NiciraResubmitTable extends AbstractExtension implements ExtensionTreatment { private static final PortNumber DEFAULT_IN_PORT = PortNumber.portNumber(65528); private PortNumber inPort; private short table; private final KryoNamespace appKryo = new KryoNamespace.Builder() .register(new PortNumberSerializer(), PortNumber.class) .register(Map.class).register(HashMap.class) .register(byte[].class) .build("NiciraResubmitTable"); /** * Creates a new resubmit-table instruction. */ NiciraResubmitTable() { inPort = DEFAULT_IN_PORT; table = -1; } /** * Creates a new resubmit-table instruction with a particular inPort and table. * * @param inPort the in port number * @param table table */ public NiciraResubmitTable(PortNumber inPort, short table) { checkNotNull(inPort); this.inPort = inPort; this.table = table; } /** * Creates a new resubmit-table instruction with a particular table. * * @param table table */ public NiciraResubmitTable(short table) { this.inPort = DEFAULT_IN_PORT; this.table = table; } /** * Gets the inPort. * * @return inPort */ public PortNumber inPort() { return inPort; } /** * Gets the table. * * @return table */ public short table() { return table; } @Override public ExtensionTreatmentType type() { return ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_RESUBMIT_TABLE.type(); } @Override public void deserialize(byte[] data) { Map<String, Object> values = appKryo.deserialize(data); inPort = (PortNumber) values.get("inPort"); table = (short) values.get("table"); } @Override public byte[] serialize() { Map<String, Object> values = Maps.newHashMap(); values.put("inPort", inPort); values.put("table", table); return appKryo.serialize(values); } @Override public int hashCode() { return Objects.hash(inPort, table); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof NiciraResubmitTable) { NiciraResubmitTable that = (NiciraResubmitTable) obj; return Objects.equals(inPort, that.inPort) && (table == that.table); } return false; } @Override public String toString() { return MoreObjects.toStringHelper(getClass()) .add("inPort", inPort) .add("table", table) .toString(); } }
3e1dd0fc28cea28ad31a1af28a4a2c081ed74713
2,669
java
Java
src/main/java/seedu/address/logic/Logic.java
AY2122S1-CS2103T-F13-3/tp
197d5335fef311502cb600cb5d91069ae2a78647
[ "MIT" ]
null
null
null
src/main/java/seedu/address/logic/Logic.java
AY2122S1-CS2103T-F13-3/tp
197d5335fef311502cb600cb5d91069ae2a78647
[ "MIT" ]
322
2021-09-09T07:19:41.000Z
2021-11-12T13:18:09.000Z
src/main/java/seedu/address/logic/Logic.java
Chesterwongz/tp
197d5335fef311502cb600cb5d91069ae2a78647
[ "MIT" ]
7
2021-09-09T06:43:02.000Z
2022-03-29T06:40:10.000Z
31.77381
99
0.724616
12,626
package seedu.address.logic; import java.nio.file.Path; import com.calendarfx.model.Calendar; import com.calendarfx.model.Entry; import javafx.collections.ObservableList; import javafx.collections.ObservableMap; import seedu.address.commons.core.GuiSettings; import seedu.address.logic.commands.CommandResult; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.logic.parser.exceptions.ParseException; import seedu.address.model.LastUpdatedDate; import seedu.address.model.ReadOnlyAddressBook; import seedu.address.model.lesson.Lesson; import seedu.address.model.person.Person; import seedu.address.model.tag.Tag; /** * API of the Logic component */ public interface Logic { /** * Executes the command and returns the result. * @param commandText The command as entered by the user. * @return the result of the command execution. * @throws CommandException If an error occurs during command execution. * @throws ParseException If an error occurs during parsing. */ CommandResult execute(String commandText) throws CommandException, ParseException; /** * Returns the AddressBook. * * @see seedu.address.model.Model#getAddressBook() */ ReadOnlyAddressBook getAddressBook(); /** Returns an unmodifiable view of the filtered list of persons */ ObservableList<Person> getFilteredPersonList(); /** Returns an unmodifiable view of the observable list of tags */ ObservableList<Tag> getObservableTagList(); /** Returns an unmodifiable view of the tag counter. */ ObservableMap<Tag, Integer> getTagCounter(); /** Returns an unmodifiable view of the observable list of lessons belonging to the student. */ ObservableList<Lesson> getLessonList(Person student); /** Returns an unmodifiable view of an empty observable list of lessons. */ ObservableList<Lesson> getEmptyLessonList(); /** Returns the CalendarFX calendar */ Calendar getCalendar(); /** Returns an unmodifiable view of the list of upcoming lessons within two days. */ ObservableList<Entry<Lesson>> getUpcomingLessons(); /** Updates the list of upcoming lists within two days. */ void updateUpcomingLessons(); /** * Returns the user prefs' address book file path. */ Path getAddressBookFilePath(); /** * Returns the user prefs' GUI settings. */ GuiSettings getGuiSettings(); /** * Set the user prefs' GUI settings. */ void setGuiSettings(GuiSettings guiSettings); /** * Returns the last time when the system was updated. */ LastUpdatedDate getLastUpdatedDate(); }
3e1dd10bb3ab27dc15d393e53c4d9054b0dca92e
5,935
java
Java
src/main/java/org/jfrog/hudson/pipeline/steps/ArtifactoryMavenBuild.java
jbaruch/jenkins-artifactory-plugin
d321f04a9b3aba14ef26f15f8ea32dfc451a2289
[ "Apache-2.0" ]
null
null
null
src/main/java/org/jfrog/hudson/pipeline/steps/ArtifactoryMavenBuild.java
jbaruch/jenkins-artifactory-plugin
d321f04a9b3aba14ef26f15f8ea32dfc451a2289
[ "Apache-2.0" ]
null
null
null
src/main/java/org/jfrog/hudson/pipeline/steps/ArtifactoryMavenBuild.java
jbaruch/jenkins-artifactory-plugin
d321f04a9b3aba14ef26f15f8ea32dfc451a2289
[ "Apache-2.0" ]
null
null
null
34.306358
130
0.647178
12,627
package org.jfrog.hudson.pipeline.steps; import com.google.inject.Inject; import hudson.EnvVars; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.Result; import hudson.model.Run; import hudson.model.TaskListener; import org.apache.commons.lang.StringUtils; import org.jenkinsci.plugins.workflow.steps.AbstractStepDescriptorImpl; import org.jenkinsci.plugins.workflow.steps.AbstractStepImpl; import org.jenkinsci.plugins.workflow.steps.AbstractSynchronousNonBlockingStepExecution; import org.jenkinsci.plugins.workflow.steps.StepContextParameter; import org.jfrog.build.api.BuildInfoFields; import org.jfrog.hudson.maven3.Maven3Builder; import org.jfrog.hudson.pipeline.Utils; import org.jfrog.hudson.pipeline.executors.MavenGradleEnvExtractor; import org.jfrog.hudson.pipeline.types.MavenBuild; import org.jfrog.hudson.pipeline.types.buildInfo.BuildInfo; import org.jfrog.hudson.pipeline.types.deployers.Deployer; import org.jfrog.hudson.pipeline.types.deployers.MavenDeployer; import org.kohsuke.stapler.DataBoundConstructor; /** * Created by Tamirh on 04/08/2016. */ public class ArtifactoryMavenBuild extends AbstractStepImpl { private MavenBuild mavenBuild; private String goal; private String pom; private String tool; private String opts; private BuildInfo buildInfo; @DataBoundConstructor public ArtifactoryMavenBuild(MavenBuild mavenBuild, String tool, String pom, String goals, String opts, BuildInfo buildInfo) { this.mavenBuild = mavenBuild; this.goal = goals == null ? "" : goals; this.pom = pom == null ? "" : pom; this.tool = tool == null ? "" : tool; this.opts = opts == null ? "" : opts; this.buildInfo = buildInfo; } public MavenBuild getMavenBuild() { return mavenBuild; } public String getTool() { return tool; } public String getOpts() { return opts; } public String getGoal() { return goal; } public String getPom() { return pom; } public BuildInfo getBuildInfo() { return buildInfo; } public void setMavenBuild(MavenBuild mavenBuild) { this.mavenBuild = mavenBuild; } public static class Execution extends AbstractSynchronousNonBlockingStepExecution<BuildInfo> { private static final long serialVersionUID = 1L; @StepContextParameter private transient Run build; @StepContextParameter private transient TaskListener listener; @StepContextParameter private transient Launcher launcher; @Inject(optional = true) private transient ArtifactoryMavenBuild step; @StepContextParameter private transient FilePath ws; @StepContextParameter private transient EnvVars env; @Override protected BuildInfo run() throws Exception { BuildInfo buildInfo = Utils.prepareBuildinfo(build, step.getBuildInfo()); Deployer deployer = getDeployer(); deployer.createPublisherBuildInfoDetails(buildInfo); MavenGradleEnvExtractor envExtractor = new MavenGradleEnvExtractor(build, buildInfo, deployer, step.getMavenBuild().getResolver(), listener, launcher); envExtractor.buildEnvVars(ws, env); String stepOpts = step.getOpts(); String mavenOpts = stepOpts + ( env.get("MAVEN_OPTS") != null ? ( stepOpts.length() > 0 ? " " : "" ) + env.get("MAVEN_OPTS") : "" ); mavenOpts = mavenOpts.replaceAll("[\t\r\n]+", " "); Maven3Builder maven3Builder = new Maven3Builder(step.getTool(), step.getPom(), step.getGoal(), mavenOpts); convertJdkPath(); boolean result = maven3Builder.perform(build, launcher, listener, env, ws); if (!result) { build.setResult(Result.FAILURE); throw new RuntimeException("Maven build failed"); } String generatedBuildPath = env.get(BuildInfoFields.GENERATED_BUILD_INFO); buildInfo.append(Utils.getGeneratedBuildInfo(build, listener, launcher, generatedBuildPath)); buildInfo.appendDeployableArtifacts(env.get(BuildInfoFields.DEPLOYABLE_ARTIFACTS), ws, listener); buildInfo.setAgentName(Utils.getAgentName(ws)); return buildInfo; } /** * The Maven3Builder class is looking for the PATH+JDK environment varibale due to legacy code. * In The pipeline flow we need to convert the JAVA_HOME to PATH+JDK in order to reuse the code. */ private void convertJdkPath() { String seperator = launcher.isUnix() ? "/" : "\\"; String java_home = env.get("JAVA_HOME"); if (StringUtils.isNotEmpty(java_home)) { if (!StringUtils.endsWith(java_home, seperator)) { java_home += seperator; } env.put("PATH+JDK", java_home + "bin"); } } private Deployer getDeployer() { Deployer deployer = step.getMavenBuild().getDeployer(); if (deployer == null || deployer.isEmpty()) { deployer = MavenDeployer.EMPTY_DEPLOYER; } return deployer; } } @Extension public static final class DescriptorImpl extends AbstractStepDescriptorImpl { public DescriptorImpl() { super(ArtifactoryMavenBuild.Execution.class); } @Override public String getFunctionName() { return "ArtifactoryMavenBuild"; } @Override public String getDisplayName() { return "run Artifactory maven"; } @Override public boolean isAdvanced() { return true; } } }
3e1dd2ee731d1b6994724be4fe1d280c11c40b77
1,259
java
Java
Readings/QuickSort.java
toureek/blogger
59c3f65ff345b7437bd6252a1df09abb239aa190
[ "MIT" ]
null
null
null
Readings/QuickSort.java
toureek/blogger
59c3f65ff345b7437bd6252a1df09abb239aa190
[ "MIT" ]
null
null
null
Readings/QuickSort.java
toureek/blogger
59c3f65ff345b7437bd6252a1df09abb239aa190
[ "MIT" ]
null
null
null
24.211538
63
0.559174
12,628
package com.springboot.guide.springboot.guide; public class QuickSort { private int partition(int array[], int low, int high) { int i = low; int povit = array[high]; for (int j = low; j < high; j++) { if (array[j] < povit) { int temp = array[i]; array[i] = array[j]; array[j] = temp; i++; } } int tempValue = array[i]; array[i] = array[high]; array[high] = tempValue; System.out.println(i + ""); return i; } public void recursionSort(int array[], int low, int high) { if (low >= high) return; int keyPoint = partition(array, low, high); recursionSort(array, low, keyPoint-1); recursionSort(array, keyPoint+1, high); } public static void printArray(int arr[]) { int n = arr.length; for (int i=0; i<n; ++i) System.out.print(arr[i]+" "); System.out.println(); } public static void main(String args[]) { int arr[] = {1011, 9877, 118, 94, 11, 5, 0, 98}; System.out.println("array before sorted"); printArray(arr); int n = arr.length; QuickSort qs = new QuickSort(); qs.recursionSort(arr, 0, n-1); System.out.println("array sorted"); printArray(arr); } }
3e1dd330c46357fc66c4b78d84097e0a55f78471
1,051
java
Java
src/main/java/com/imaginea/assignment/turvoapi/crosscutting/TurvoAPIException.java
dineshatpramati/abcturvoassignment
4e3ae50507d9a9146ea5b8d739a83625e9873772
[ "MIT" ]
null
null
null
src/main/java/com/imaginea/assignment/turvoapi/crosscutting/TurvoAPIException.java
dineshatpramati/abcturvoassignment
4e3ae50507d9a9146ea5b8d739a83625e9873772
[ "MIT" ]
null
null
null
src/main/java/com/imaginea/assignment/turvoapi/crosscutting/TurvoAPIException.java
dineshatpramati/abcturvoassignment
4e3ae50507d9a9146ea5b8d739a83625e9873772
[ "MIT" ]
null
null
null
35.033333
111
0.682207
12,629
package com.imaginea.assignment.turvoapi.crosscutting; public class TurvoAPIException extends RuntimeException { public enum ErrorCode { CUSTOMER_NOT_FOUND(1001, "Customer does not exist"), DUPLICATE_CUSTOMER(1002, "Customer already exists"), BRANCH_NOT_FOUND(1003, "Branch doesn't exist"), SERVICE_NOT_FOUND(2001, "Service not supported"), INVALID_TOKEN(3001, "Token is invalid"), INVALID_TOKEN_STATE(3002, "Token not active"), UNAUTHORIZED_SERVICE_REQUEST(3003, "Service Request is unauthorized ,please provide valid auth token"), APPLICATION_ERROR(5001,"Application error , please try later "), INVALID_COUNTER_NUMBER(3004,"Counter number not valid,please enter valid counter number"); private int code; private String message; ErrorCode(int code, String message) { this.code = code; this.message = message; } } public TurvoAPIException(ErrorCode errorCode) { super(errorCode.message); } }
3e1dd391429aa2c77aabdd8f6dfbf4198883b6c9
252
java
Java
src/ua/kpi/java1/lab1/writer/DataWriter.java
Vasniktel/java-labs
cf4aab74fbbae05fc21c715b7b9d0d914633f1d3
[ "MIT" ]
null
null
null
src/ua/kpi/java1/lab1/writer/DataWriter.java
Vasniktel/java-labs
cf4aab74fbbae05fc21c715b7b9d0d914633f1d3
[ "MIT" ]
null
null
null
src/ua/kpi/java1/lab1/writer/DataWriter.java
Vasniktel/java-labs
cf4aab74fbbae05fc21c715b7b9d0d914633f1d3
[ "MIT" ]
null
null
null
22.909091
70
0.797619
12,630
package ua.kpi.java1.lab1.writer; import ua.kpi.java1.lab1.formatter.Formatter; import ua.kpi.java1.lab1.model.Model; import java.io.IOException; public interface DataWriter { void writeData(Formatter formatter, Model model) throws IOException; }
3e1dd3d6aaeaf2ac1d9c80c3ee2d215fbca85eca
219
java
Java
src/main/resources/archetype-resources/src/main/java/ApplicationConfig.java
capgemini-psdu/boot-microservice-archetype
096ffba2d0ce231285980e62b792dc9fa3e0f426
[ "MIT" ]
1
2018-05-10T08:05:58.000Z
2018-05-10T08:05:58.000Z
src/main/resources/archetype-resources/src/main/java/ApplicationConfig.java
capgemini-psdu/boot-microservice-archetype
096ffba2d0ce231285980e62b792dc9fa3e0f426
[ "MIT" ]
1
2017-03-31T09:13:50.000Z
2017-03-31T09:13:50.000Z
src/main/resources/archetype-resources/src/main/java/ApplicationConfig.java
capgemini-psdu/boot-microservice-archetype
096ffba2d0ce231285980e62b792dc9fa3e0f426
[ "MIT" ]
1
2017-03-29T11:56:46.000Z
2017-03-29T11:56:46.000Z
19.909091
60
0.712329
12,631
#set( $symbol_pound = '#' ) #set( $symbol_dollar = '$' ) #set( $symbol_escape = '\' ) package ${package}; import org.springframework.context.annotation.Configuration; @Configuration public class ApplicationConfig { }
3e1dd555f8ce76606af0021fe8509de3b6ef67fe
2,268
java
Java
analysis/reverse-engineering/decompile-fitts-20191031-2200/sources/kr/co/popone/fitts/viewmodel/push/OrderPartCancelModule_ProvideOrderViewModelFactory.java
skkuse-adv/2019Fall_team2
3ea84c6be39855f54634a7f9b1093e80893886eb
[ "Apache-2.0" ]
4
2019-10-07T05:17:21.000Z
2020-11-02T08:29:13.000Z
analysis/reverse-engineering/decompile-fitts-20191031-2200/sources/kr/co/popone/fitts/viewmodel/push/OrderPartCancelModule_ProvideOrderViewModelFactory.java
skkuse-adv/2019Fall_team2
3ea84c6be39855f54634a7f9b1093e80893886eb
[ "Apache-2.0" ]
38
2019-10-07T02:40:35.000Z
2019-12-12T09:15:24.000Z
analysis/reverse-engineering/decompile-fitts-20191031-2200/sources/kr/co/popone/fitts/viewmodel/push/OrderPartCancelModule_ProvideOrderViewModelFactory.java
skkuse-adv/2019Fall_team2
3ea84c6be39855f54634a7f9b1093e80893886eb
[ "Apache-2.0" ]
5
2019-10-07T02:41:15.000Z
2020-10-30T01:36:08.000Z
64.8
235
0.828483
12,632
package kr.co.popone.fitts.viewmodel.push; import dagger.internal.Factory; import dagger.internal.Preconditions; import javax.inject.Provider; import kr.co.popone.fitts.feature.push.order.OrderPartCancelFragment; public final class OrderPartCancelModule_ProvideOrderViewModelFactory implements Factory<OrderPushRendingViewModel> { private final Provider<OrderPartCancelFragment> fragmentProvider; private final OrderPartCancelModule module; private final Provider<OrderPushRendingViewModelFactory> viewModelFactoryProvider; public OrderPartCancelModule_ProvideOrderViewModelFactory(OrderPartCancelModule orderPartCancelModule, Provider<OrderPartCancelFragment> provider, Provider<OrderPushRendingViewModelFactory> provider2) { this.module = orderPartCancelModule; this.fragmentProvider = provider; this.viewModelFactoryProvider = provider2; } public OrderPushRendingViewModel get() { return provideInstance(this.module, this.fragmentProvider, this.viewModelFactoryProvider); } public static OrderPushRendingViewModel provideInstance(OrderPartCancelModule orderPartCancelModule, Provider<OrderPartCancelFragment> provider, Provider<OrderPushRendingViewModelFactory> provider2) { return proxyProvideOrderViewModel(orderPartCancelModule, (OrderPartCancelFragment) provider.get(), (OrderPushRendingViewModelFactory) provider2.get()); } public static OrderPartCancelModule_ProvideOrderViewModelFactory create(OrderPartCancelModule orderPartCancelModule, Provider<OrderPartCancelFragment> provider, Provider<OrderPushRendingViewModelFactory> provider2) { return new OrderPartCancelModule_ProvideOrderViewModelFactory(orderPartCancelModule, provider, provider2); } public static OrderPushRendingViewModel proxyProvideOrderViewModel(OrderPartCancelModule orderPartCancelModule, OrderPartCancelFragment orderPartCancelFragment, OrderPushRendingViewModelFactory orderPushRendingViewModelFactory) { return (OrderPushRendingViewModel) Preconditions.checkNotNull(orderPartCancelModule.provideOrderViewModel(orderPartCancelFragment, orderPushRendingViewModelFactory), "Cannot return null from a non-@Nullable @Provides method"); } }
3e1dd592aed75fdaf89771718a4388be36915411
96
java
Java
integration/src/main/java/com/pisces/integration/config/IntegrationMessage.java
backo880607/pisces
40ddd15a5a02d7dfc03b4892473d2eb332c2d1c6
[ "Apache-2.0" ]
null
null
null
integration/src/main/java/com/pisces/integration/config/IntegrationMessage.java
backo880607/pisces
40ddd15a5a02d7dfc03b4892473d2eb332c2d1c6
[ "Apache-2.0" ]
null
null
null
integration/src/main/java/com/pisces/integration/config/IntegrationMessage.java
backo880607/pisces
40ddd15a5a02d7dfc03b4892473d2eb332c2d1c6
[ "Apache-2.0" ]
null
null
null
16
39
0.770833
12,633
package com.pisces.integration.config; public enum IntegrationMessage { ConnectFailed, }
3e1dd5cb31e6ecdd415f948f8ea2b90fe521764c
2,042
java
Java
src/main/java/io/github/gjkf/seriousEngine/render/ShadowMap.java
gjkf/SeriousEngine
1e5ca95b0fa28091d591d374b3a4b3223164efe8
[ "MIT" ]
10
2016-12-11T13:33:47.000Z
2019-05-16T11:50:44.000Z
src/main/java/io/github/gjkf/seriousEngine/render/ShadowMap.java
gjkf/SeriousEngine
1e5ca95b0fa28091d591d374b3a4b3223164efe8
[ "MIT" ]
1
2016-08-22T16:46:43.000Z
2016-11-27T18:39:27.000Z
src/main/java/io/github/gjkf/seriousEngine/render/ShadowMap.java
gjkf/SeriousEngine
1e5ca95b0fa28091d591d374b3a4b3223164efe8
[ "MIT" ]
1
2019-02-16T18:33:09.000Z
2019-02-16T18:33:09.000Z
22.688889
104
0.619001
12,634
/* * Created by Davide Cossu (gjkf), 11/26/2016 */ package io.github.gjkf.seriousEngine.render; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL30.*; /** * Class representing a Shadow Map. */ public class ShadowMap{ /** * The map width. */ public static final int SHADOW_MAP_WIDTH = 1024; /** * The map height. */ public static final int SHADOW_MAP_HEIGHT = 1024; /** * The FrameBufferObject (FBO) */ private final int depthMapFBO; /** * The texture that is created. */ private final Texture depthMap; /** * Constructs a new ShadowMap. * * @throws Exception If anything went wrong. */ public ShadowMap() throws Exception{ // Create a FBO to render the depth map depthMapFBO = glGenFramebuffers(); // Create the depth map texture depthMap = new Texture(SHADOW_MAP_WIDTH, SHADOW_MAP_HEIGHT, GL_DEPTH_COMPONENT); // Attach the the depth map texture to the FBO glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthMap.getId(), 0); // Set only depth glDrawBuffer(GL_NONE); glReadBuffer(GL_NONE); if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE){ throw new Exception("Could not create FrameBuffer"); } // Unbind glBindFramebuffer(GL_FRAMEBUFFER, 0); } /** * Getter for property 'depthMapTexture'. * * @return Value for property 'depthMapTexture'. */ public Texture getDepthMapTexture(){ return depthMap; } /** * Getter for property 'depthMapFBO'. * * @return Value for property 'depthMapFBO'. */ public int getDepthMapFBO(){ return depthMapFBO; } /** * Cleans up resources. */ public void cleanup(){ glDeleteFramebuffers(depthMapFBO); depthMap.cleanup(); } }
3e1dd5d4120b73b54827b4b63ef50572fec42522
7,427
java
Java
rocketmq-demo/src/main/java/io/github/sruby/rocketmq/CreateOrderService.java
sruby/java-study
35834940b40036618d27fa6d54b21f27d8dd88c2
[ "Apache-2.0" ]
null
null
null
rocketmq-demo/src/main/java/io/github/sruby/rocketmq/CreateOrderService.java
sruby/java-study
35834940b40036618d27fa6d54b21f27d8dd88c2
[ "Apache-2.0" ]
1
2022-03-14T13:31:19.000Z
2022-03-14T13:31:19.000Z
rocketmq-demo/src/main/java/io/github/sruby/rocketmq/CreateOrderService.java
sruby/java-study
35834940b40036618d27fa6d54b21f27d8dd88c2
[ "Apache-2.0" ]
null
null
null
40.584699
132
0.637135
12,635
package io.github.sruby.rocketmq; import com.sun.jersey.spi.inject.Inject; import lombok.extern.slf4j.Slf4j; import org.apache.rocketmq.client.Validators; import org.apache.rocketmq.client.exception.MQClientException; import org.apache.rocketmq.client.producer.*; import org.apache.rocketmq.common.message.Message; import org.apache.rocketmq.common.message.MessageAccessor; import org.apache.rocketmq.common.message.MessageConst; import org.apache.rocketmq.common.message.MessageExt; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import javax.ws.rs.PUT; import java.util.concurrent.ExecutorService; @Slf4j public class CreateOrderService { @Inject private OrderDao orderDao; // 注入订单表的DAO @Inject private ExecutorService executorService; //注入一个ExecutorService private TransactionMQProducer producer; private DefaultMQProducer defaultMQProducer; // 初始化transactionListener 和 producer // @Init public void init() throws MQClientException { TransactionListener transactionListener = createTransactionListener(); producer = new TransactionMQProducer("myGroup"); producer.setExecutorService(executorService); producer.setTransactionListener(transactionListener); producer.start(); } // 创建订单服务的请求入口 @PUT @RequestMapping("") public boolean createOrder(@RequestBody CreateOrderRequest request) throws MQClientException { // 根据创建订单请求创建一条消息 Message msg = createMessage(request); // 发送事务消息 SendResult sendResult = producer.sendMessageInTransaction(msg, request); // 返回:事务是否成功 return sendResult.getSendStatus() == SendStatus.SEND_OK; } private Message createMessage(CreateOrderRequest request) { return null; } public TransactionSendResult sendMessageInTransaction(final Message msg, final LocalTransactionExecuter localTransactionExecuter, final Object arg) throws MQClientException { TransactionListener transactionListener = getCheckListener(); if (null == localTransactionExecuter && null == transactionListener) { throw new MQClientException("tranExecutor is null", null); } Validators.checkMessage(msg, this.defaultMQProducer); SendResult sendResult = null; // 这里给消息添加了属性,标明这是一个事务消息,也就是半消息 MessageAccessor.putProperty(msg, MessageConst.PROPERTY_TRANSACTION_PREPARED, "true"); MessageAccessor.putProperty(msg, MessageConst.PROPERTY_PRODUCER_GROUP, this.defaultMQProducer.getProducerGroup()); // 调用发送普通消息的方法,发送这条半消息 try { sendResult = this.send(msg); } catch (Exception e) { throw new MQClientException("send message Exception", e); } LocalTransactionState localTransactionState = LocalTransactionState.UNKNOW; Throwable localException = null; switch (sendResult.getSendStatus()) { case SEND_OK: { try { if (sendResult.getTransactionId() != null) { msg.putUserProperty("__transactionId__", sendResult.getTransactionId()); } String transactionId = msg.getProperty(MessageConst.PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX); if (null != transactionId && !"".equals(transactionId)) { msg.setTransactionId(transactionId); } // 执行本地事务 if (null != localTransactionExecuter) { localTransactionState = localTransactionExecuter.executeLocalTransactionBranch(msg, arg); } else if (transactionListener != null) { log.debug("Used new transaction API"); localTransactionState = transactionListener.executeLocalTransaction(msg, arg); } if (null == localTransactionState) { localTransactionState = LocalTransactionState.UNKNOW; } if (localTransactionState != LocalTransactionState.COMMIT_MESSAGE) { log.info("executeLocalTransactionBranch return {}", localTransactionState); log.info(msg.toString()); } } catch (Throwable e) { log.info("executeLocalTransactionBranch exception", e); log.info(msg.toString()); localException = e; } } break; case FLUSH_DISK_TIMEOUT: case FLUSH_SLAVE_TIMEOUT: case SLAVE_NOT_AVAILABLE: localTransactionState = LocalTransactionState.ROLLBACK_MESSAGE; break; default: break; } // 根据事务消息和本地事务的执行结果localTransactionState,决定提交或回滚事务消息 // 这里给Broker发送提交或回滚事务的RPC请求。 try { this.endTransaction(sendResult, localTransactionState, localException); } catch (Exception e) { log.warn("local transaction execute " + localTransactionState + ", but end broker transaction failed", e); } TransactionSendResult transactionSendResult = new TransactionSendResult(); transactionSendResult.setSendStatus(sendResult.getSendStatus()); transactionSendResult.setMessageQueue(sendResult.getMessageQueue()); transactionSendResult.setMsgId(sendResult.getMsgId()); transactionSendResult.setQueueOffset(sendResult.getQueueOffset()); transactionSendResult.setTransactionId(sendResult.getTransactionId()); transactionSendResult.setLocalTransactionState(localTransactionState); return transactionSendResult; } private SendResult send(Message msg) { return null; } private void endTransaction(SendResult sendResult, LocalTransactionState localTransactionState, Throwable localException) { } private TransactionListener getCheckListener() { return null; } private TransactionListener createTransactionListener() { return new TransactionListener() { @Override public LocalTransactionState executeLocalTransaction(Message msg, Object arg) { CreateOrderRequest request = (CreateOrderRequest) arg; try { // 执行本地事务创建订单 orderDao.createOrderInDB(request); // 如果没抛异常说明执行成功,提交事务消息 return LocalTransactionState.COMMIT_MESSAGE; } catch (Throwable t) { // 失败则直接回滚事务消息 return LocalTransactionState.ROLLBACK_MESSAGE; } } // 反查本地事务 @Override public LocalTransactionState checkLocalTransaction(MessageExt msg) { // 从消息中获得订单ID String orderId = msg.getUserProperty("orderId"); // 去数据库中查询订单号是否存在,如果存在则提交事务; // 如果不存在,可能是本地事务失败了,也可能是本地事务还在执行,所以返回UNKNOW //(PS:这里RocketMQ有个拼写错误:UNKNOW) return orderDao.isOrderIdExistsInDB(orderId) ? LocalTransactionState.COMMIT_MESSAGE : LocalTransactionState.UNKNOW; } }; } }
3e1dd71142c11963f8c5bef2ecb28ace3761047c
1,701
java
Java
model/mongo/src/main/java/org/keycloak/connections/mongo/impl/EntityInfo.java
didiez/keycloak
1373708dea360730f6db43c6057a266b5f095594
[ "Apache-2.0" ]
1
2020-08-17T20:44:14.000Z
2020-08-17T20:44:14.000Z
model/mongo/src/main/java/org/keycloak/connections/mongo/impl/EntityInfo.java
didiez/keycloak
1373708dea360730f6db43c6057a266b5f095594
[ "Apache-2.0" ]
1
2021-02-23T14:13:32.000Z
2021-02-23T15:30:40.000Z
model/mongo/src/main/java/org/keycloak/connections/mongo/impl/EntityInfo.java
didiez/keycloak
1373708dea360730f6db43c6057a266b5f095594
[ "Apache-2.0" ]
3
2016-03-24T18:44:57.000Z
2020-11-12T10:25:31.000Z
29.362069
112
0.71697
12,636
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.keycloak.connections.mongo.impl; import org.keycloak.models.utils.reflection.Property; import java.util.Collection; import java.util.Map; /** * @author <a href="mailto:lyhxr@example.com">Marek Posolda</a> */ public class EntityInfo { private final Class<?> entityClass; private final String dbCollectionName; private final Map<String, Property<Object>> properties; public EntityInfo(Class<?> entityClass, String dbCollectionName, Map<String, Property<Object>> properties) { this.entityClass = entityClass; this.dbCollectionName = dbCollectionName; this.properties = properties; } public Class<?> getEntityClass() { return entityClass; } public String getDbCollectionName() { return dbCollectionName; } public Collection<Property<Object>> getProperties() { return properties.values(); } public Property<Object> getPropertyByName(String propertyName) { return properties.get(propertyName); } }
3e1dd7dc090956c702e4314d366d183a0d2fb122
2,511
java
Java
sample-java/app/src/main/java/com/seerslab/argear/sample/ui/adapter/StickerListAdapter.java
Ahmed012345/argear-android-sample
ece37add36a28e0972c23e744c4826bfd4586d8d
[ "FSFAP" ]
5
2020-10-10T23:56:00.000Z
2021-12-15T05:19:27.000Z
sample-java/app/src/main/java/com/seerslab/argear/sample/ui/adapter/StickerListAdapter.java
Ahmed012345/argear-android-sample
ece37add36a28e0972c23e744c4826bfd4586d8d
[ "FSFAP" ]
6
2020-05-19T02:08:03.000Z
2021-06-22T10:52:25.000Z
sample-java/app/src/main/java/com/seerslab/argear/sample/ui/adapter/StickerListAdapter.java
Ahmed012345/argear-android-sample
ece37add36a28e0972c23e744c4826bfd4586d8d
[ "FSFAP" ]
4
2020-08-07T10:11:28.000Z
2021-08-20T12:08:16.000Z
23.036697
98
0.744723
12,637
package com.seerslab.argear.sample.ui.adapter; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.seerslab.argear.sample.R; import com.seerslab.argear.sample.model.ItemModel; import java.util.ArrayList; import java.util.List; public class StickerListAdapter extends RecyclerView.Adapter<StickerListAdapter.ViewHolder> { private static final String TAG = StickerListAdapter.class.getSimpleName(); private List<ItemModel> mItems = new ArrayList<>(); public interface Listener { void onStickerSelected(int position, ItemModel item); } private Listener mListener; private Context mContext; public StickerListAdapter(Context context, Listener listener) { mContext = context; mListener = listener; } public void setData(List<ItemModel> items) { mItems.clear(); if(items != null) { mItems.addAll(items); } notifyDataSetChanged(); } @Override public int getItemCount() { return mItems.size(); } @Override public void onBindViewHolder(final ViewHolder holder, final int position) { holder.bind(position); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_sticker, parent, false); return new StickerViewHolder(v); } @Override public int getItemViewType(int position) { return 0; } abstract class ViewHolder extends RecyclerView.ViewHolder { abstract void bind(int position); ViewHolder(View v) { super(v); } } public class StickerViewHolder extends ViewHolder implements View.OnClickListener { ImageView mImageViewItemThumbnail = null; ItemModel mItem; int position; StickerViewHolder(View v) { super(v); mImageViewItemThumbnail = v.findViewById(R.id.item_thumbnail_imageview); } @Override void bind(int position) { mItem = mItems.get(position); this.position = position; Log.d(TAG, "item_sticker " + position + " " + mItem.thumbnailUrl + " " + mItem); mImageViewItemThumbnail.setOnClickListener(this); //스티커의 섬네일을 보여줍니다 Glide.with(mContext) .load(mItem.thumbnailUrl) .fitCenter() .into(mImageViewItemThumbnail); } @Override public void onClick(View v) { if(mListener != null){ mListener.onStickerSelected(position, mItem); } } } }
3e1dd7e9d8ed3273b9abb0af969d603592594c64
1,138
java
Java
mapper/src/main/java/top/itning/yunshuvideo/mapper/CommentsMapper.java
itning/YunShuShortVideoAppletsServer
0ced62f126e5d4a61fbc1532500ce7d7d62dd82b
[ "Apache-2.0" ]
7
2019-05-06T21:38:05.000Z
2021-12-28T16:16:58.000Z
mapper/src/main/java/top/itning/yunshuvideo/mapper/CommentsMapper.java
itning/YunShuShortVideoAppletsServer
0ced62f126e5d4a61fbc1532500ce7d7d62dd82b
[ "Apache-2.0" ]
2
2020-07-03T13:35:30.000Z
2020-07-03T13:35:30.000Z
mapper/src/main/java/top/itning/yunshuvideo/mapper/CommentsMapper.java
itning/YunShuShortVideoAppletsServer
0ced62f126e5d4a61fbc1532500ce7d7d62dd82b
[ "Apache-2.0" ]
6
2019-05-06T09:16:17.000Z
2020-11-16T07:49:56.000Z
30.756757
110
0.78471
12,638
package top.itning.yunshuvideo.mapper; import org.apache.ibatis.annotations.Param; import top.itning.yunshuvideo.common.entity.Comments; import top.itning.yunshuvideo.common.entity.CommentsExample; import java.util.List; public interface CommentsMapper { long countByExample(CommentsExample example); int deleteByExample(CommentsExample example); int deleteByPrimaryKey(String id); int insert(Comments record); int insertSelective(Comments record); List<Comments> selectByExampleWithBLOBs(CommentsExample example); List<Comments> selectByExample(CommentsExample example); Comments selectByPrimaryKey(String id); int updateByExampleSelective(@Param("record") Comments record, @Param("example") CommentsExample example); int updateByExampleWithBLOBs(@Param("record") Comments record, @Param("example") CommentsExample example); int updateByExample(@Param("record") Comments record, @Param("example") CommentsExample example); int updateByPrimaryKeySelective(Comments record); int updateByPrimaryKeyWithBLOBs(Comments record); int updateByPrimaryKey(Comments record); }
3e1dd816d6d26ea95a2b0f748476f3217b526109
269
java
Java
Leetcode/Solution_1111_MaxNestedParanthesis.java
dgr8akki/DS-Algo-Made-Easy-With-Aakash
ccb6f6323af47858a6647b72fbde79fe81538eb9
[ "Apache-2.0" ]
8
2019-05-21T15:56:57.000Z
2022-02-01T11:40:09.000Z
Leetcode/Solution_1111_MaxNestedParanthesis.java
dgr8akki/DS-Algo-Made-Easy-With-Aakash
ccb6f6323af47858a6647b72fbde79fe81538eb9
[ "Apache-2.0" ]
3
2019-05-30T18:46:36.000Z
2020-01-06T10:38:21.000Z
Leetcode/Solution_1111_MaxNestedParanthesis.java
dgr8akki/DS-Algo-Made-Easy-With-Aakash
ccb6f6323af47858a6647b72fbde79fe81538eb9
[ "Apache-2.0" ]
null
null
null
24.454545
58
0.565056
12,639
package Leetcode; class Solution_1111_MaxNestedParanthesis { public int[] maxDepthAfterSplit(String seq) { int n = seq.length(), res[] = new int[n]; for (int i = 0; i < n; ++i) res[i] = seq.charAt(i) == '(' ? i & 1 : (1 - i & 1); return res; } }
3e1dd8bdd5d390dbb39fd8d1cb0ef1510103ab6d
743
java
Java
src/main/java/cn/wuxia/wechat/WeChatException.java
wuxiatech/wuxia-weixin-api
83ad2df45fb94394714d738e0720fdc445550685
[ "Apache-2.0" ]
null
null
null
src/main/java/cn/wuxia/wechat/WeChatException.java
wuxiatech/wuxia-weixin-api
83ad2df45fb94394714d738e0720fdc445550685
[ "Apache-2.0" ]
null
null
null
src/main/java/cn/wuxia/wechat/WeChatException.java
wuxiatech/wuxia-weixin-api
83ad2df45fb94394714d738e0720fdc445550685
[ "Apache-2.0" ]
null
null
null
21.852941
70
0.60969
12,640
/* * Created on :29 Aug, 2014 * Author :songlin * Change History * Version Date Author Reason * <Ver.No> <date> <who modify> <reason> * Copyright 2014-2020 songlin.li All right reserved. */ package cn.wuxia.wechat; public class WeChatException extends Exception { /** * Comment for <code>serialVersionUID</code> */ private static final long serialVersionUID = 2714496706512845530L; public WeChatException() { super(); } public WeChatException(Exception e) { super("", e); } public WeChatException(String message, Exception e) { super(message, e); } public WeChatException(String message) { super(message); } }
3e1dd97a99d4bbcfc66408f2bd6a05490fab007a
23,740
java
Java
src/com/prtech/svarog/SvCluster.java
PerunTech/svarog
84e4d91a6868e043170c7f9efdfc1e4d5176fcdd
[ "Apache-2.0" ]
1
2019-09-19T11:56:01.000Z
2019-09-19T11:56:01.000Z
src/com/prtech/svarog/SvCluster.java
PerunTech/svarog
84e4d91a6868e043170c7f9efdfc1e4d5176fcdd
[ "Apache-2.0" ]
1
2020-09-28T13:16:29.000Z
2020-09-28T13:16:29.000Z
src/com/prtech/svarog/SvCluster.java
PerunTech/svarog
84e4d91a6868e043170c7f9efdfc1e4d5176fcdd
[ "Apache-2.0" ]
null
null
null
32.972222
119
0.714069
12,641
package com.prtech.svarog; import java.lang.management.ManagementFactory; import java.net.UnknownHostException; import java.sql.Connection; import java.sql.PreparedStatement; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReentrantLock; import org.apache.logging.log4j.Logger; import org.joda.time.DateTime; import com.google.common.cache.LoadingCache; import com.google.gson.JsonObject; import com.prtech.svarog_common.DbDataArray; import com.prtech.svarog_common.DbDataObject; /** * Class for managing the svarog cluster infrastructure. Provides basic * synchronization methods between multiple svarog nodes. * * @author ristepejov * */ public class SvCluster extends SvCore { static final byte MSG_UNKNOWN = -2; static final byte MSG_FAIL = -1; static final byte MSG_SUCCESS = 0; static final byte MSG_HEARTBEAT = 1; static final byte MSG_AUTH_TOKEN_PUT = 3; static final byte MSG_AUTH_TOKEN_GET = 4; static final byte MSG_AUTH_TOKEN_SET = 6; static final byte MSG_JOIN = 10; static final byte MSG_PART = 11; static final byte MSG_LOCK = 20; static final byte MSG_LOCK_RELEASE = 21; static final byte NOTE_LOCK_ACQUIRED = 22; static final byte NOTE_LOCK_RELEASED = 23; static final byte NOTE_DIRTY_OBJECT = 30; static final byte NOTE_LOGOFF = 31; static final byte NOTE_DIRTY_TILE = 32; static final byte NOTE_ACK = 33; static final String JOIN_TIME = "join_time"; static final String PART_TIME = "part_time"; static final String LAST_MAINTENANCE = "last_maintenance"; static final String NEXT_MAINTENANCE = "next_maintenance"; static final String NODE_INFO = "node_info"; /** * Class to wrap the standard locks in order to support the distributed * locking of the svarog cluster. The key of the lock as well as the node * which holds the lock are the needed information * * @author ristepejov * */ static class DistributedLock { public String key; public Long nodeId; public ReentrantLock lock; public int lockHash; DistributedLock(String key, Long nodeId, ReentrantLock lock, int lockHash) { this.nodeId = nodeId; this.lock = lock; this.key = key; this.lockHash = lockHash; } } /** * Timeout interval on the socket receive */ static final int SOCKET_RECV_TIMEOUT = SvConf.getHeartBeatInterval() / 2; /** * Flag to know if the current node is coordinator or worker. */ private static boolean isCoordinator = false; /** * Flag if the cluster is running */ private static final AtomicBoolean isRunning = new AtomicBoolean(false); /** * Flag if the client is running */ private static AtomicBoolean isActive = new AtomicBoolean(false); /** * Log4j instance used for logging */ static final Logger log4j = SvConf.getLogger(SvCluster.class); /** * Reference to the coordinator node */ private static DbDataObject coordinatorNode = null; /** * Reference to the current node descriptor. If the current node is * coordinator, the references should be equal. */ // static DbDataObject currentNode = null; static final String IP_ADDR_DELIMITER = ";"; /** * Member fields holding reference to the heart beat thread */ static private Thread heartBeatThread = null; static private Thread notifierThread = null; /** * Reference to the coordinator node */ static boolean autoStartClient = true; /** * Default Constructor. This constructor can be used only within the svarog * package since it will run with system privileges. * * @throws SvException */ SvCluster() throws SvException { super(svCONST.systemUser, null); } /** * Method to generate a DBO describing the current node * * @return A DbDataObject descriptor of the current node */ static DbDataObject getCurrentNodeInfo() { DbDataObject cNode = new DbDataObject(svCONST.OBJECT_TYPE_CLUSTER); cNode.setVal(JOIN_TIME, new DateTime()); cNode.setVal(PART_TIME, SvConf.MAX_DATE); cNode.setVal(LAST_MAINTENANCE, new DateTime()); cNode.setVal(NEXT_MAINTENANCE, new DateTime().plusSeconds(SvConf.getClusterMaintenanceInterval())); String localIp = "0.0.0.0:" + SvConf.getHeartBeatPort(); try { localIp = SvUtil.getIpAdresses(true, IP_ADDR_DELIMITER); } catch (UnknownHostException e) { log4j.error("Can't get node IP Address!", e); } cNode.setVal("local_ip", localIp); JsonObject json = new JsonObject(); json.addProperty("pid", ManagementFactory.getRuntimeMXBean().getName()); json.addProperty("version", SvConf.appVersion); json.addProperty("build", SvConf.appBuild); json.addProperty("ip", localIp); cNode.setVal(NODE_INFO, json.toString()); return cNode; } /** * Method to perform coordinator promotion of the current node * * @param svc * A reference to an SvCore (the read/write of the nodes has to * be in the same transaction) * @return True if the current node was promoted to coordinator * @throws SvException * any underlying exception (except object not updateable, which * would mean someone else got promoted in meantime) */ static boolean becomeCoordinator(SvCore svc) throws SvException { SvWriter svw = null; boolean success = true; try { svw = new SvWriter(svc); if (coordinatorNode == null) { coordinatorNode = new DbDataObject(svCONST.OBJECT_TYPE_CLUSTER); coordinatorNode.setObjectId(svCONST.CLUSTER_COORDINATOR_ID); } coordinatorNode.setValuesMap(getCurrentNodeInfo().getValuesMap()); svw.isInternal = true; svw.saveObject(coordinatorNode, true); } catch (SvException e) { // if the object is not update-able, another node became // coordinator and we should register a worker node if (!e.getLabelCode().equals("system.error.obj_not_updateable")) throw (e); else success = false; } finally { if (svw != null) svw.release(); } // If we failed to promote lets try to refresh the coordinator node info if (!success) { DbCache.removeObject(coordinatorNode.getObjectId(), coordinatorNode.getObjectType()); coordinatorNode = null; log4j.warn("Coordinator record is invalid. Next maintenance in the past: " + coordinatorNode.getVal(NEXT_MAINTENANCE)); } else log4j.info("The node promoted to coordinator: " + coordinatorNode.getVal(NODE_INFO)); return success; } /** * Method to perform resigning of coordinator * * @param svc * A reference to an SvCore (the read/write of the nodes has to * be in the same transaction) * @return True if the current has resigned from the coordinator role * @throws SvException * any underlying exception (except object not updateable, which * would mean someone else got promoted in meantime) */ static boolean resignCoordinator() throws SvException { SvWriter svw = null; SvReader svr = null; boolean success = false; try { if (isCoordinator) { svr = new SvReader(); svr.isInternal = true; svw = new SvWriter(svr); DbCache.removeObject(svCONST.CLUSTER_COORDINATOR_ID, svCONST.OBJECT_TYPE_CLUSTER); coordinatorNode = svr.getObjectById(svCONST.CLUSTER_COORDINATOR_ID, svCONST.OBJECT_TYPE_CLUSTER, null); coordinatorNode.setVal(LAST_MAINTENANCE, DateTime.now()); coordinatorNode.setVal(NEXT_MAINTENANCE, DateTime.now()); coordinatorNode.setVal(PART_TIME, DateTime.now()); svw.isInternal = true; svw.saveObject(coordinatorNode, true); success = true; } else success = false; } catch (SvException e) { // if the object is not update-able, another node became // coordinator and we should register a worker node if (!e.getLabelCode().equals("system.error.obj_not_updateable")) throw (e); else success = false; } finally { if (svw != null) svw.release(); if (svr != null) svr.release(); } return success; } /** * Method to ensure the cluster clients have started and connected to the * hear beat address/port of the coordinator * * @param hbAddress * String list of available heartbeat end points * @return True if the client threads have started and connected with * success */ private static boolean startClients(String hbAddress) { boolean initHb = false; boolean initNotif = false; boolean threadStarted = false; initHb = SvClusterClient.initClient(hbAddress); initNotif = initHb ? SvClusterNotifierClient.initClient(hbAddress) : false; if (initHb && initNotif) { heartBeatThread = new Thread(new SvClusterClient()); heartBeatThread.setName("SvClusterClientThread"); heartBeatThread.start(); notifierThread = new Thread(new SvClusterNotifierClient()); notifierThread.setName("SvClusterNotifierClientThread"); notifierThread.start(); threadStarted = true; } else { log4j.info("Svarog Cluster Clients initialisation failed. Initiating Cluster shutdown."); shutdown(); } return initHb && initNotif && threadStarted; } /** * Method to start the server threads of the cluster * * @return True if the server threads have been started successfully. * @throws SvException */ private static boolean startServers() throws SvException { boolean initHb = false; boolean initNotif = false; initHb = SvClusterServer.initServer(); initNotif = SvClusterNotifierProxy.initServer(); if (initHb && initNotif) { // promote the local locks from the old node id heartBeatThread = new Thread(new SvClusterServer()); heartBeatThread.setName("SvClusterServerThread"); heartBeatThread.start(); notifierThread = new Thread(new SvClusterNotifierProxy()); notifierThread.setName("SvClusterNotifierProxyThread"); notifierThread.start(); // finally we are the coordinator isCoordinator = true; } else { log4j.info("Svarog Cluster Servers initialisation failed. Initiating Cluster shutdown."); shutdown(); } return initHb && initNotif && isCoordinator; } /** * Method to initialise the Svarog Cluster. This method shall try to locate * a valid coordinator node, or become one if there isn't any. If it becomes * a coordinator then it will start the heart beat listener and the notifier * proxy servers. If the current node doesn't manage to become a coordinator * then it will start a Heart Beat client and notifier client and try to * connect to the coordinator * * @return True if the cluster was properly initialised. */ static boolean initCluster() { if (!isRunning.compareAndSet(false, true)) { log4j.error("Cluster is already initialised and active. Shutdown first"); return false; } else log4j.info("SvCluster is starting"); SvReader svr = null; isCoordinator = false; try { svr = new SvReader(); svr.isInternal = true; // do try to get a valid coordinator // force purge of the cache to get the coordinator DbCache.removeObject(svCONST.CLUSTER_COORDINATOR_ID, svCONST.OBJECT_TYPE_CLUSTER); coordinatorNode = svr.getObjectById(svCONST.CLUSTER_COORDINATOR_ID, svCONST.OBJECT_TYPE_CLUSTER, null); // currentNode = getCurrentNodeInfo(); DateTime nextMaintenance = coordinatorNode != null ? (DateTime) coordinatorNode.getVal(NEXT_MAINTENANCE) : null; // the next maintenance is in the past means there's no active // coordinator, we will try to become a coordinator if (nextMaintenance == null || nextMaintenance.isBeforeNow()) isCoordinator = becomeCoordinator(svr); else log4j.info("Valid coordinator record found: " + coordinatorNode.getVal(NODE_INFO)); // if the local IP including the hb port is the same ... means that // the coordinator record is related to this node, but maybe a core // dump caused the server to fail. So lets try to become coordinator String hbAddress = (String) coordinatorNode.getVal("local_ip"); if (isCoordinator || (!isCoordinator && SvUtil.getIpAdresses(true, IP_ADDR_DELIMITER).equals(hbAddress))) isActive.set(startServers()); // if the servers failed to start, then try to start as a client if (!isActive.get() && autoStartClient) isActive.set(startClients(hbAddress)); } catch (Exception e) { log4j.error("Svarog cluster could not be initialised. Cluster not running!", e); shutdown(); } finally { if (svr != null) svr.release(); } return isActive.get(); } /** * Method to check if the cluster services are running correctly */ public static void checkCluster() { // TODO add sanity check of the threads } /** * Method to update a distributed lock. This is invoked when the Notifier * client is processing lock acknowledgments and needs to update the list of * distributed locks by the SvLock on the coordinator node. * * @param lockHash * The hash of the lock * @param lockKey * The key of the lock * * @return True if the lock was updated */ static boolean updateDistributedLock(String lockKey, Integer lockHash, ConcurrentHashMap<String, SvCluster.DistributedLock> distLocks) { DistributedLock dlock = distLocks.get(lockKey); if (dlock != null) dlock.lockHash = lockHash; return dlock != null; } /** * Method to shutdown the Svarog cluster. The cluster shutdown will in turn: * 1. Check the current node is a cluster coordinator. 2. If we are a * cluster coordinator then we shall shutdown the SvClusterServer and * SvClusterNotifierProxy 3. If we are not a coordinator then we shall * shutdown the SvClusterClient and SvClusterNotifierClient */ static void shutdown() { shutdown(true); } /** * Method to shutdown the clients if running */ static void stopClients() { if (autoStartClient) { if (SvClusterClient.isRunning.get()) SvClusterClient.shutdown(); if (SvClusterNotifierClient.isRunning.get()) SvClusterNotifierClient.shutdown(); } } /** * Method to stop the servers if running */ static void stopServers() { if (SvClusterServer.isRunning.get()) SvClusterServer.shutdown(); if (SvClusterNotifierProxy.isRunning.get()) SvClusterNotifierProxy.shutdown(); } /** * Join the heart beat and notifier threads so we are sure that the clients * or servers have stopped */ static void joinDaemonThreads() { // just check if the join isn't invoked from the heartbeat or notifier. Thread joinHb = (!Thread.currentThread().equals(heartBeatThread) ? heartBeatThread : null); Thread joinNf = (!Thread.currentThread().equals(notifierThread) ? notifierThread : null); while ((joinHb != null && joinHb.isAlive()) || (joinNf != null && joinNf.isAlive())) { try { if (joinHb != null && joinHb.isAlive()) joinHb.join(1); if (joinNf != null && joinNf.isAlive()) joinNf.join(1); synchronized (SvMaintenance.maintenanceThread) { SvMaintenance.maintenanceThread.wait(100); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); log4j.info("Waiting on the maintenance thread got interrupted. Retry to join daemon threads", e); } } } /** * Method to shutdown the Svarog cluster. The cluster shutdown will in turn: * 1. Check the current node is a cluster coordinator. 2. If we are a * cluster coordinator then we shall shutdown the SvClusterServer and * SvClusterNotifierProxy 3. If we are not a coordinator then we shall * shutdown the SvClusterClient and SvClusterNotifierClient */ static void shutdown(boolean doMaintenance) { if (!isRunning.compareAndSet(true, false)) { log4j.debug("Svarog Cluster not running. Can't shutdown"); return; } else log4j.info("SvCluster is stopping"); if (doMaintenance) SvMaintenance.performMaintenance(); // shut down all daemon threads if (isCoordinator) stopServers(); else stopClients(); // join the threads joinDaemonThreads(); // reset the global variables heartBeatThread = null; notifierThread = null; coordinatorNode = null; isCoordinator = false; // notify interested parties that we shut down synchronized (SvCluster.isRunning) { isRunning.notifyAll(); } } /** * Method to release a distributed lock. This is invoked when the * clusterServer processes releaseLock message. This method is also invoked * by the SvLock on the coordinator node. * * @param lockHash * The hash of the lock * @param nodeId * The node id which acquires the lock * @param nodeLocks * The map of nodes which contains locks held by node * @param distributedLocks * The map of distributed nodes in the cluster to be used for * releasing the lock * @return Null if the lock was NOT released, otherwise the lock key. */ static String releaseDistributedLock(Integer lockHash, long nodeId, ConcurrentHashMap<Long, CopyOnWriteArrayList<SvCluster.DistributedLock>> nodeLocks, ConcurrentHashMap<String, SvCluster.DistributedLock> distributedLocks, LoadingCache<String, ReentrantLock> sysLocks) { boolean lockReleased = false; CopyOnWriteArrayList<SvCluster.DistributedLock> nodeLock = nodeLocks.get(nodeId); SvCluster.DistributedLock currentLock = null; if (nodeLock != null) { for (SvCluster.DistributedLock dLock : nodeLock) if (lockHash.equals(dLock.lockHash)) { currentLock = dLock; break; } } if (currentLock != null) { lockReleased = SvLock.releaseLock(currentLock.key, currentLock.lock, false, sysLocks); if (currentLock.lock.getHoldCount() == 0) { synchronized (distributedLocks) { distributedLocks.remove(currentLock.key, currentLock); } nodeLock.remove(currentLock); } } else log4j.error("Lock with hash " + lockHash.toString() + ", does not exist in the list of distributed locks"); return lockReleased ? currentLock.key : null; } /** * Method to acquire a distributed lock from the svarog cluster (this is * server agnostic). It is called also by SvLock in order to synchronize * properly the distributed locks * * @param lockKey * The lock key which should be locked. * @param nodeId * The id of the node which shall acquire the lock * @param extendedInfo * The id of the node which already holds the lock (available * only if the lock fails) * @param nodeLocks * The map of nodes which contains locks held by node * @param distributedLocks * The map of distributed nodes in the cluster to be used for * releasing the lock * @return Instance of re-entrant lock if the lock was acquired. Otherwise * null. If null the extendedInfo is populated with the node holding * the lock */ static ReentrantLock acquireDistributedLock(String lockKey, Long nodeId, Long[] extendedInfo, ConcurrentHashMap<Long, CopyOnWriteArrayList<SvCluster.DistributedLock>> nodeLocks, ConcurrentHashMap<String, SvCluster.DistributedLock> distributedLocks, LoadingCache<String, ReentrantLock> sysLocks) { ReentrantLock lock = null; SvCluster.DistributedLock dlock = null; synchronized (distributedLocks) { dlock = distributedLocks.get(lockKey); if (dlock != null && dlock.nodeId.equals(nodeId)) { // same node is locking the re-entrant lock again lock = SvLock.getLock(lockKey, false, 0L, sysLocks); } else { if (dlock == null) // brand new lock { lock = SvLock.getLock(lockKey, false, 0L, sysLocks); if (lock != null) { dlock = new SvCluster.DistributedLock(lockKey, nodeId, lock, lock.hashCode()); distributedLocks.put(lockKey, dlock); } } else extendedInfo[0] = dlock.nodeId; } } updateNodeLocks(lock, dlock, nodeLocks, nodeId); return lock; } /** * Update the map with locks per node if the lock was acquired * * @param lock * @param dlock * @param nodeLocks * @param nodeId */ static void updateNodeLocks(ReentrantLock lock, SvCluster.DistributedLock dlock, ConcurrentHashMap<Long, CopyOnWriteArrayList<SvCluster.DistributedLock>> nodeLocks, long nodeId) { if (lock != null) { CopyOnWriteArrayList<SvCluster.DistributedLock> currentNode = new CopyOnWriteArrayList<SvCluster.DistributedLock>(); CopyOnWriteArrayList<SvCluster.DistributedLock> oldNode = nodeLocks.putIfAbsent(nodeId, currentNode); if (oldNode != null) currentNode = oldNode; currentNode.addIfAbsent(dlock); } } /** * Method to clean up the distributed locks acquired by a node * * @param nodeId * The node for which the distributed locks shall be cleaned */ static void clusterCleanUp(Long nodeId, ConcurrentHashMap<Long, CopyOnWriteArrayList<SvCluster.DistributedLock>> nodeLocks, ConcurrentHashMap<String, SvCluster.DistributedLock> distributedLocks) { { CopyOnWriteArrayList<SvCluster.DistributedLock> nodeLock = nodeLocks.get(nodeId); if (nodeLock != null) { for (SvCluster.DistributedLock dstLock : nodeLock) { SvLock.releaseLock(dstLock.key, dstLock.lock); synchronized (distributedLocks) { distributedLocks.remove(dstLock.key, dstLock); } } nodeLocks.remove(nodeId); } } } /** * Method to migrate locks from one node to another. This is useful if the * node has lost a heart beat, then re-joined with a new node ID. In this * case we'll just migrate the locks from the old node id to the new one * * @param nodeId * The node under which the locks shall be moved * @param oldNodeId * The node from which the locks will be moved * @param nodeLocks * The map fo locks which shall be used (Server or Client side) */ static void migrateLocks(Long nodeId, Long oldNodeId, ConcurrentHashMap<Long, CopyOnWriteArrayList<SvCluster.DistributedLock>> nodeLocks) { { CopyOnWriteArrayList<SvCluster.DistributedLock> nodeLock = nodeLocks.remove(oldNodeId); if (nodeLock != null) { for (SvCluster.DistributedLock dstLock : nodeLock) { dstLock.nodeId = nodeId; } nodeLocks.put(nodeId, nodeLock); } } } /** * Method to migrate locks from one node to another. This is useful if the * node has lost a heart beat, then re-joined with a new node ID. In this * case we'll just migrate the locks from the old node id to the new one * * @param nodeId * The node under which the locks shall be moved * @param oldNodeId * The node from which the locks will be moved * @param nodeLocks * The map fo locks which shall be used (Server or Client side) */ static void copyLocalLocks(Long nodeId, Long oldNodeId, ConcurrentHashMap<Long, CopyOnWriteArrayList<SvCluster.DistributedLock>> localNodeLocks) { { CopyOnWriteArrayList<SvCluster.DistributedLock> nodeLock = localNodeLocks.remove(oldNodeId); if (nodeLock != null) { for (SvCluster.DistributedLock dstLock : nodeLock) { SvLock.getDistributedLockImpl(dstLock.key, SvCluster.isCoordinator, nodeId); } } } } public static boolean isCoordinator() { return isCoordinator; } public static void setCoordinator(boolean isCoordinator) { SvCluster.isCoordinator = isCoordinator; } public static AtomicBoolean isRunning() { return isRunning; } public static AtomicBoolean getIsActive() { if (isCoordinator) return isActive; else return SvClusterClient.isActive; } public static void setIsActive(AtomicBoolean isActive) { SvCluster.isActive = isActive; } public static DbDataObject getCoordinatorNode() { return coordinatorNode; } public static void setCoordinatorNode(DbDataObject coordinatorNode) { SvCluster.coordinatorNode = coordinatorNode; } }
3e1dd9da2c817e2a1887c0e0cf115f1b2022a6de
865
java
Java
jax-rs-2.0-service/src/main/java/com/knightRider/config/model/Person.java
prashant-Exzeo/ClientServerAggregator
949a0edbc8e282a5aca853a9d568f533776339a8
[ "Apache-2.0" ]
null
null
null
jax-rs-2.0-service/src/main/java/com/knightRider/config/model/Person.java
prashant-Exzeo/ClientServerAggregator
949a0edbc8e282a5aca853a9d568f533776339a8
[ "Apache-2.0" ]
null
null
null
jax-rs-2.0-service/src/main/java/com/knightRider/config/model/Person.java
prashant-Exzeo/ClientServerAggregator
949a0edbc8e282a5aca853a9d568f533776339a8
[ "Apache-2.0" ]
null
null
null
19.222222
66
0.619653
12,642
package com.knightRider.config.model; public class Person { private String email; private String firstName; private String lastName; public Person() { } public Person(final String email) { this.email = email; } public Person(final String firstName, final String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(final String email) { this.email = email; } public String getFirstName() { return firstName; } public void setFirstName(final String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(final String lastName) { this.lastName = lastName; } }
3e1dda00f40280605f9777b8a6798e75bc18ad98
685
java
Java
security-keycloak-authorization-quickstart/src/main/java/org/acme/security/keycloak/authorization/UserResource.java
monicatJava/quarkus-quickstarts
5cef5e856d8bd53afc1d611a64a48444f462e3b7
[ "Apache-2.0" ]
null
null
null
security-keycloak-authorization-quickstart/src/main/java/org/acme/security/keycloak/authorization/UserResource.java
monicatJava/quarkus-quickstarts
5cef5e856d8bd53afc1d611a64a48444f462e3b7
[ "Apache-2.0" ]
null
null
null
security-keycloak-authorization-quickstart/src/main/java/org/acme/security/keycloak/authorization/UserResource.java
monicatJava/quarkus-quickstarts
5cef5e856d8bd53afc1d611a64a48444f462e3b7
[ "Apache-2.0" ]
null
null
null
20.147059
69
0.659854
12,643
package org.acme.security.keycloak.authorization; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import io.quarkus.security.identity.SecurityIdentity; @Path("/api/users") public class UserResource { @Inject SecurityIdentity keycloakSecurityContext; @GET @Path("/me") public User me() { return new User(keycloakSecurityContext); } public static class User { private final String userName; User(SecurityIdentity securityContext) { this.userName = securityContext.getPrincipal().getName(); } public String getUserName() { return userName; } } }
3e1dda6fe5668df556f5c4238307f7ba0aa4a6d0
42,823
java
Java
gemfirexd/tools/src/ddlutils/java/org/apache/ddlutils/io/DatabaseIO.java
xyxiaoyou/snappy-store
013ff282f888878cc99600e260ec1cde60112304
[ "Apache-2.0" ]
38
2016-01-04T01:31:40.000Z
2020-04-07T06:35:36.000Z
gemfirexd/tools/src/ddlutils/java/org/apache/ddlutils/io/DatabaseIO.java
xyxiaoyou/snappy-store
013ff282f888878cc99600e260ec1cde60112304
[ "Apache-2.0" ]
261
2016-01-07T09:14:26.000Z
2019-12-05T10:15:56.000Z
gemfirexd/tools/src/ddlutils/java/org/apache/ddlutils/io/DatabaseIO.java
xyxiaoyou/snappy-store
013ff282f888878cc99600e260ec1cde60112304
[ "Apache-2.0" ]
22
2016-03-09T05:47:09.000Z
2020-04-02T17:55:30.000Z
35.925336
146
0.618499
12,644
package org.apache.ddlutils.io; /* * 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. */ /* * Changes for GemFireXD distributed data platform (some marked by "GemStone changes") * * Portions Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying * LICENSE file. */ import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.StringReader; import java.io.Writer; import javax.xml.namespace.QName; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.transform.stream.StreamSource; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ddlutils.model.CascadeActionEnum; import org.apache.ddlutils.model.Column; import org.apache.ddlutils.model.Database; import org.apache.ddlutils.model.ForeignKey; import org.apache.ddlutils.model.Index; import org.apache.ddlutils.model.IndexColumn; import org.apache.ddlutils.model.NonUniqueIndex; import org.apache.ddlutils.model.Reference; import org.apache.ddlutils.model.Table; import org.apache.ddlutils.model.UniqueIndex; import org.xml.sax.InputSource; /** * This class provides functions to read and write database models from/to XML. * * @version $Revision: 987978 $ */ public class DatabaseIO { /** The name of the XML attribute use to denote that teh content of a data XML element uses Base64 encoding. */ public static final String BASE64_ATTR_NAME = "base64"; /** The namespace used by DdlUtils. */ public static final String DDLUTILS_NAMESPACE = "http://db.apache.org/ddlutils/schema/1.1"; /** Qualified name of the column element. */ public static final QName QNAME_ELEMENT_COLUMN = new QName(DDLUTILS_NAMESPACE, "column"); /** Qualified name of the database element. */ public static final QName QNAME_ELEMENT_DATABASE = new QName(DDLUTILS_NAMESPACE, "database"); /** Qualified name of the foreign-key element. */ public static final QName QNAME_ELEMENT_FOREIGN_KEY = new QName(DDLUTILS_NAMESPACE, "foreign-key"); /** Qualified name of the index element. */ public static final QName QNAME_ELEMENT_INDEX = new QName(DDLUTILS_NAMESPACE, "index"); /** Qualified name of the index-column element. */ public static final QName QNAME_ELEMENT_INDEX_COLUMN = new QName(DDLUTILS_NAMESPACE, "index-column"); /** Qualified name of the reference element. */ public static final QName QNAME_ELEMENT_REFERENCE = new QName(DDLUTILS_NAMESPACE, "reference"); /** Qualified name of the table element. */ public static final QName QNAME_ELEMENT_TABLE = new QName(DDLUTILS_NAMESPACE, "table"); /** Qualified name of the unique element. */ public static final QName QNAME_ELEMENT_UNIQUE = new QName(DDLUTILS_NAMESPACE, "unique"); /** Qualified name of the unique-column element. */ public static final QName QNAME_ELEMENT_UNIQUE_COLUMN = new QName(DDLUTILS_NAMESPACE, "unique-column"); /** Qualified name of the autoIncrement attribute. */ public static final QName QNAME_ATTRIBUTE_AUTO_INCREMENT = new QName(DDLUTILS_NAMESPACE, "autoIncrement"); /** Qualified name of the default attribute. */ public static final QName QNAME_ATTRIBUTE_DEFAULT = new QName(DDLUTILS_NAMESPACE, "default"); /** Qualified name of the defaultIdMethod attribute. */ public static final QName QNAME_ATTRIBUTE_DEFAULT_ID_METHOD = new QName(DDLUTILS_NAMESPACE, "defaultIdMethod"); /** Qualified name of the description attribute. */ public static final QName QNAME_ATTRIBUTE_DESCRIPTION = new QName(DDLUTILS_NAMESPACE, "description"); /** Qualified name of the foreign attribute. */ public static final QName QNAME_ATTRIBUTE_FOREIGN = new QName(DDLUTILS_NAMESPACE, "foreign"); /** Qualified name of the foreignTable attribute. */ public static final QName QNAME_ATTRIBUTE_FOREIGN_TABLE = new QName(DDLUTILS_NAMESPACE, "foreignTable"); /** Qualified name of the javaName attribute. */ public static final QName QNAME_ATTRIBUTE_JAVA_NAME = new QName(DDLUTILS_NAMESPACE, "javaName"); /** Qualified name of the local attribute. */ public static final QName QNAME_ATTRIBUTE_LOCAL = new QName(DDLUTILS_NAMESPACE, "local"); /** Qualified name of the name attribute. */ public static final QName QNAME_ATTRIBUTE_NAME = new QName(DDLUTILS_NAMESPACE, "name"); /** Qualified name of the onDelete attribute. */ public static final QName QNAME_ATTRIBUTE_ON_DELETE = new QName(DDLUTILS_NAMESPACE, "onDelete"); /** Qualified name of the onUpdate attribute. */ public static final QName QNAME_ATTRIBUTE_ON_UPDATE = new QName(DDLUTILS_NAMESPACE, "onUpdate"); /** Qualified name of the primaryKey attribute. */ public static final QName QNAME_ATTRIBUTE_PRIMARY_KEY = new QName(DDLUTILS_NAMESPACE, "primaryKey"); /** Qualified name of the required attribute. */ public static final QName QNAME_ATTRIBUTE_REQUIRED = new QName(DDLUTILS_NAMESPACE, "required"); /** Qualified name of the size attribute. */ public static final QName QNAME_ATTRIBUTE_SIZE = new QName(DDLUTILS_NAMESPACE, "size"); /** Qualified name of the type attribute. */ public static final QName QNAME_ATTRIBUTE_TYPE = new QName(DDLUTILS_NAMESPACE, "type"); /** Qualified name of the version attribute. */ public static final QName QNAME_ATTRIBUTE_VERSION = new QName(DDLUTILS_NAMESPACE, "version"); /** The log. */ private final Log _log = LogFactory.getLog(DatabaseIO.class); /** Whether to validate the XML. */ private boolean _validateXml = true; /** Whether to use the internal dtd that comes with DdlUtils. */ private boolean _useInternalDtd = true; /** * Returns whether XML is validated upon reading it. * * @return <code>true</code> if read XML is validated */ public boolean isValidateXml() { return _validateXml; } /** * Specifies whether XML shall be validated upon reading it. * * @param validateXml <code>true</code> if read XML shall be validated */ public void setValidateXml(boolean validateXml) { _validateXml = validateXml; } /** * Returns whether the internal dtd that comes with DdlUtils is used. * * @return <code>true</code> if parsing uses the internal dtd * @deprecated Switched to XML schema, and the internal XML schema should always be used */ public boolean isUseInternalDtd() { return _useInternalDtd; } /** * Specifies whether the internal dtd is to be used. * * @param useInternalDtd Whether to use the internal dtd * @deprecated Switched to XML schema, and the internal XML schema should always be used */ public void setUseInternalDtd(boolean useInternalDtd) { _useInternalDtd = useInternalDtd; } /** * Reads the database model contained in the specified file. * * @param filename The model file name * @return The database model */ public Database read(String filename) throws DdlUtilsXMLException { return read(new File(filename)); } /** * Reads the database model contained in the specified file. * * @param file The model file * @return The database model */ public Database read(File file) throws DdlUtilsXMLException { FileReader reader = null; if (_validateXml) { try { reader = new FileReader(file); new ModelValidator().validate(new StreamSource(reader)); } catch (IOException ex) { throw new DdlUtilsXMLException(ex); } finally { if (reader != null) { try { reader.close(); } catch (IOException ex) { _log.warn("Could not close reader for file " + file.getAbsolutePath()); } reader = null; } } } try { reader = new FileReader(file); return read(getXMLInputFactory().createXMLStreamReader(reader)); } catch (XMLStreamException ex) { throw new DdlUtilsXMLException(ex); } catch (IOException ex) { throw new DdlUtilsXMLException(ex); } finally { if (reader != null) { try { reader.close(); } catch (IOException ex) { _log.warn("Could not close reader for file " + file.getAbsolutePath()); } } } } /** * Reads the database model given by the reader. Note that this method does not close the * given reader. * * @param reader The reader that returns the model XML * @return The database model */ public Database read(Reader reader) throws DdlUtilsXMLException { try { if (_validateXml) { StringBuilder tmpXml = new StringBuilder(); char[] buf = new char[4096]; int len; while ((len = reader.read(buf)) >= 0) { tmpXml.append(buf, 0, len); } new ModelValidator().validate(new StreamSource(new StringReader(tmpXml.toString()))); return read(getXMLInputFactory().createXMLStreamReader(new StringReader(tmpXml.toString()))); } else { return read(getXMLInputFactory().createXMLStreamReader(reader)); } } catch (XMLStreamException ex) { throw new DdlUtilsXMLException(ex); } catch (IOException ex) { throw new DdlUtilsXMLException(ex); } } /** * Reads the database model from the given input source. * * @param source The input source * @return The database model */ public Database read(InputSource source) throws DdlUtilsXMLException { return read(source.getCharacterStream()); } /** * Creates a new, initialized XML input factory object. * * @return The factory object */ private XMLInputFactory getXMLInputFactory() { XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty("javax.xml.stream.isCoalescing", Boolean.TRUE); factory.setProperty("javax.xml.stream.isNamespaceAware", Boolean.TRUE); return factory; } /** * Reads the database model from the given XML stream reader. * * @param xmlReader The reader * @return The database model */ private Database read(XMLStreamReader xmlReader) throws DdlUtilsXMLException { Database model = null; try { while (xmlReader.getEventType() != XMLStreamReader.START_ELEMENT) { if (xmlReader.next() == XMLStreamReader.END_DOCUMENT) { return null; } } if (isSameAs(xmlReader.getName(), QNAME_ELEMENT_DATABASE)) { model = readDatabaseElement(xmlReader); } } catch (IOException ex) { throw new DdlUtilsXMLException(ex); } catch (XMLStreamException ex) { throw new DdlUtilsXMLException(ex); } if (model != null) { model.initialize(); } return model; } /** * Reads a database element from the XML stream reader. * * @param xmlReader The reader * @return The database object */ private Database readDatabaseElement(XMLStreamReader xmlReader) throws XMLStreamException, IOException { Database model = new Database(); for (int idx = 0; idx < xmlReader.getAttributeCount(); idx++) { QName attrQName = xmlReader.getAttributeName(idx); if (isSameAs(attrQName, QNAME_ATTRIBUTE_NAME)) { model.setName(xmlReader.getAttributeValue(idx)); } else if (isSameAs(attrQName, QNAME_ATTRIBUTE_DEFAULT_ID_METHOD)) { model.setIdMethod(xmlReader.getAttributeValue(idx)); } else if (isSameAs(attrQName, QNAME_ATTRIBUTE_VERSION)) { model.setVersion(xmlReader.getAttributeValue(idx)); } } readTableElements(xmlReader, model); consumeRestOfElement(xmlReader); return model; } /** * Reads table elements from the XML stream reader and adds them to the given * database model. * * @param xmlReader The reader * @param model The database model to add the table objects to */ private void readTableElements(XMLStreamReader xmlReader, Database model) throws XMLStreamException, IOException { int eventType = XMLStreamReader.START_ELEMENT; while (eventType != XMLStreamReader.END_ELEMENT) { eventType = xmlReader.next(); if (eventType == XMLStreamReader.START_ELEMENT) { if (isSameAs(xmlReader.getName(), QNAME_ELEMENT_TABLE)) { model.addTable(readTableElement(xmlReader)); } else { readOverElement(xmlReader); } } } } /** * Reads a table element from the XML stream reader. * * @param xmlReader The reader * @return The table object */ private Table readTableElement(XMLStreamReader xmlReader) throws XMLStreamException, IOException { Table table = new Table(); for (int idx = 0; idx < xmlReader.getAttributeCount(); idx++) { QName attrQName = xmlReader.getAttributeName(idx); if (isSameAs(attrQName, QNAME_ATTRIBUTE_NAME)) { // GemStone changes BEGIN // check for fully qualified name String tableName = xmlReader.getAttributeValue(idx); int dotPos = tableName.indexOf('.'); if (dotPos > 0) { table.setSchema(tableName.substring(0, dotPos)); table.setName(tableName.substring(dotPos + 1)); } else { table.setName(tableName); } /* (original code) table.setName(xmlReader.getAttributeValue(idx)); */ // GemStone changes END } else if (isSameAs(attrQName, QNAME_ATTRIBUTE_DESCRIPTION)) { table.setDescription(xmlReader.getAttributeValue(idx)); } } readTableSubElements(xmlReader, table); consumeRestOfElement(xmlReader); return table; } /** * Reads table sub elements (column, foreign key, index) from the XML stream reader and adds * them to the given table. * * @param xmlReader The reader * @param table The table */ private void readTableSubElements(XMLStreamReader xmlReader, Table table) throws XMLStreamException, IOException { int eventType = XMLStreamReader.START_ELEMENT; while (eventType != XMLStreamReader.END_ELEMENT) { eventType = xmlReader.next(); if (eventType == XMLStreamReader.START_ELEMENT) { QName elemQName = xmlReader.getName(); if (isSameAs(elemQName, QNAME_ELEMENT_COLUMN)) { table.addColumn(readColumnElement(xmlReader)); } else if (isSameAs(elemQName, QNAME_ELEMENT_FOREIGN_KEY)) { table.addForeignKey(readForeignKeyElement(xmlReader)); } else if (isSameAs(elemQName, QNAME_ELEMENT_INDEX)) { table.addIndex(readIndexElement(xmlReader)); } else if (isSameAs(elemQName, QNAME_ELEMENT_UNIQUE)) { table.addIndex(readUniqueElement(xmlReader)); } else { readOverElement(xmlReader); } } } } /** * Reads a column element from the XML stream reader. * * @param xmlReader The reader * @return The column object */ private Column readColumnElement(XMLStreamReader xmlReader) throws XMLStreamException, IOException { Column column = new Column(); for (int idx = 0; idx < xmlReader.getAttributeCount(); idx++) { QName attrQName = xmlReader.getAttributeName(idx); if (isSameAs(attrQName, QNAME_ATTRIBUTE_NAME)) { column.setName(xmlReader.getAttributeValue(idx)); } else if (isSameAs(attrQName, QNAME_ATTRIBUTE_PRIMARY_KEY)) { column.setPrimaryKey(getAttributeValueAsBoolean(xmlReader, idx)); } else if (isSameAs(attrQName, QNAME_ATTRIBUTE_REQUIRED)) { column.setRequired(getAttributeValueAsBoolean(xmlReader, idx)); } else if (isSameAs(attrQName, QNAME_ATTRIBUTE_TYPE)) { column.setType(xmlReader.getAttributeValue(idx)); } else if (isSameAs(attrQName, QNAME_ATTRIBUTE_SIZE)) { column.setSize(getAttributeValueBeingNullAware(xmlReader, idx)); } else if (isSameAs(attrQName, QNAME_ATTRIBUTE_DEFAULT)) { column.setDefaultValue(xmlReader.getAttributeValue(idx)); } else if (isSameAs(attrQName, QNAME_ATTRIBUTE_AUTO_INCREMENT)) { column.setAutoIncrement(getAttributeValueAsBoolean(xmlReader, idx)); } else if (isSameAs(attrQName, QNAME_ATTRIBUTE_DESCRIPTION)) { column.setDescription(xmlReader.getAttributeValue(idx)); } else if (isSameAs(attrQName, QNAME_ATTRIBUTE_JAVA_NAME)) { column.setJavaName(xmlReader.getAttributeValue(idx)); } } consumeRestOfElement(xmlReader); return column; } /** * Reads a foreign key element from the XML stream reader. * * @param xmlReader The reader * @return The foreign key object */ private ForeignKey readForeignKeyElement(XMLStreamReader xmlReader) throws XMLStreamException, IOException { ForeignKey foreignKey = new ForeignKey(); for (int idx = 0; idx < xmlReader.getAttributeCount(); idx++) { QName attrQName = xmlReader.getAttributeName(idx); if (isSameAs(attrQName, QNAME_ATTRIBUTE_FOREIGN_TABLE)) { foreignKey.setForeignTableName(xmlReader.getAttributeValue(idx)); } else if (isSameAs(attrQName, QNAME_ATTRIBUTE_NAME)) { foreignKey.setName(xmlReader.getAttributeValue(idx)); } else if (isSameAs(attrQName, QNAME_ATTRIBUTE_ON_UPDATE)) { foreignKey.setOnUpdate(getAttributeValueAsCascadeEnum(xmlReader, idx)); } else if (isSameAs(attrQName, QNAME_ATTRIBUTE_ON_DELETE)) { foreignKey.setOnDelete(getAttributeValueAsCascadeEnum(xmlReader, idx)); } } readReferenceElements(xmlReader, foreignKey); consumeRestOfElement(xmlReader); return foreignKey; } /** * Reads reference elements from the XML stream reader and adds them to the given * foreign key. * * @param xmlReader The reader * @param foreignKey The foreign key */ private void readReferenceElements(XMLStreamReader xmlReader, ForeignKey foreignKey) throws XMLStreamException, IOException { int eventType = XMLStreamReader.START_ELEMENT; while (eventType != XMLStreamReader.END_ELEMENT) { eventType = xmlReader.next(); if (eventType == XMLStreamReader.START_ELEMENT) { QName elemQName = xmlReader.getName(); if (isSameAs(elemQName, QNAME_ELEMENT_REFERENCE)) { foreignKey.addReference(readReferenceElement(xmlReader)); } else { readOverElement(xmlReader); } } } } /** * Reads a reference element from the XML stream reader. * * @param xmlReader The reader * @return The reference object */ private Reference readReferenceElement(XMLStreamReader xmlReader) throws XMLStreamException, IOException { Reference reference = new Reference(); for (int idx = 0; idx < xmlReader.getAttributeCount(); idx++) { QName attrQName = xmlReader.getAttributeName(idx); if (isSameAs(attrQName, QNAME_ATTRIBUTE_LOCAL)) { reference.setLocalColumnName(xmlReader.getAttributeValue(idx)); } else if (isSameAs(attrQName, QNAME_ATTRIBUTE_FOREIGN)) { reference.setForeignColumnName(xmlReader.getAttributeValue(idx)); } } consumeRestOfElement(xmlReader); return reference; } /** * Reads an index element from the XML stream reader. * * @param xmlReader The reader * @return The index object */ private Index readIndexElement(XMLStreamReader xmlReader) throws XMLStreamException, IOException { Index index = new NonUniqueIndex(); for (int idx = 0; idx < xmlReader.getAttributeCount(); idx++) { QName attrQName = xmlReader.getAttributeName(idx); if (isSameAs(attrQName, QNAME_ATTRIBUTE_NAME)) { index.setName(xmlReader.getAttributeValue(idx)); } } readIndexColumnElements(xmlReader, index); consumeRestOfElement(xmlReader); return index; } /** * Reads an unique index element from the XML stream reader. * * @param xmlReader The reader * @return The unique index object */ private Index readUniqueElement(XMLStreamReader xmlReader) throws XMLStreamException, IOException { Index index = new UniqueIndex(); for (int idx = 0; idx < xmlReader.getAttributeCount(); idx++) { QName attrQName = xmlReader.getAttributeName(idx); if (isSameAs(attrQName, QNAME_ATTRIBUTE_NAME)) { index.setName(xmlReader.getAttributeValue(idx)); } } readUniqueColumnElements(xmlReader, index); consumeRestOfElement(xmlReader); return index; } /** * Reads index column elements from the XML stream reader and adds them to the given * index object. * * @param xmlReader The reader * @param index The index object */ private void readIndexColumnElements(XMLStreamReader xmlReader, Index index) throws XMLStreamException, IOException { int eventType = XMLStreamReader.START_ELEMENT; while (eventType != XMLStreamReader.END_ELEMENT) { eventType = xmlReader.next(); if (eventType == XMLStreamReader.START_ELEMENT) { QName elemQName = xmlReader.getName(); if (isSameAs(elemQName, QNAME_ELEMENT_INDEX_COLUMN)) { index.addColumn(readIndexColumnElement(xmlReader)); } else { readOverElement(xmlReader); } } } } /** * Reads unique index column elements from the XML stream reader and adds them to the given * index object. * * @param xmlReader The reader * @param index The index object */ private void readUniqueColumnElements(XMLStreamReader xmlReader, Index index) throws XMLStreamException, IOException { int eventType = XMLStreamReader.START_ELEMENT; while (eventType != XMLStreamReader.END_ELEMENT) { eventType = xmlReader.next(); if (eventType == XMLStreamReader.START_ELEMENT) { QName elemQName = xmlReader.getName(); if (isSameAs(elemQName, QNAME_ELEMENT_UNIQUE_COLUMN)) { index.addColumn(readIndexColumnElement(xmlReader)); } else { readOverElement(xmlReader); } } } } /** * Reads an index column element from the XML stream reader. * * @param xmlReader The reader * @return The index column object */ private IndexColumn readIndexColumnElement(XMLStreamReader xmlReader) throws XMLStreamException, IOException { IndexColumn indexColumn = new IndexColumn(); for (int idx = 0; idx < xmlReader.getAttributeCount(); idx++) { QName attrQName = xmlReader.getAttributeName(idx); if (isSameAs(attrQName, QNAME_ATTRIBUTE_NAME)) { indexColumn.setName(xmlReader.getAttributeValue(idx)); } else if (isSameAs(attrQName, QNAME_ATTRIBUTE_SIZE)) { indexColumn.setSize(getAttributeValueBeingNullAware(xmlReader, idx)); } } consumeRestOfElement(xmlReader); return indexColumn; } /** * Compares the given qnames. This specifically ignores the namespace * uri of the other qname if the namespace of the current element is * empty. * * @param curElemQName The qname of the current element * @param qName The qname to compare to * @return <code>true</code> if they are the same */ private boolean isSameAs(QName curElemQName, QName qName) { if (StringUtils.isEmpty(curElemQName.getNamespaceURI())) { return qName.getLocalPart().equals(curElemQName.getLocalPart()); } else { return qName.equals(curElemQName); } } /** * Returns the value of the indicated attribute of the current element as a string. * This method can handle "null" in which case it returns a null object. * * @param xmlReader The xml reader * @param attributeIdx The index of the attribute * @return The attribute's value */ private String getAttributeValueBeingNullAware(XMLStreamReader xmlReader, int attributeIdx) throws DdlUtilsXMLException { String value = xmlReader.getAttributeValue(attributeIdx); return "null".equalsIgnoreCase(value) ? null : value; } /** * Returns the value of the indicated attribute of the current element as a boolean. * If the value is not a valid boolean, then an exception is thrown. * * @param xmlReader The xml reader * @param attributeIdx The index of the attribute * @return The attribute's value as a boolean */ private boolean getAttributeValueAsBoolean(XMLStreamReader xmlReader, int attributeIdx) throws DdlUtilsXMLException { String value = xmlReader.getAttributeValue(attributeIdx); if ("true".equalsIgnoreCase(value)) { return true; } else if ("false".equalsIgnoreCase(value)) { return false; } else { throw new DdlUtilsXMLException("Illegal boolean value '" + value +"' for attribute " + xmlReader.getAttributeLocalName(attributeIdx)); } } /** * Returns the value of the indicated attribute of the current element as a boolean. * If the value is not a valid boolean, then an exception is thrown. * * @param xmlReader The xml reader * @param attributeIdx The index of the attribute * @return The attribute's value as a boolean */ private CascadeActionEnum getAttributeValueAsCascadeEnum(XMLStreamReader xmlReader, int attributeIdx) throws DdlUtilsXMLException { String value = xmlReader.getAttributeValue(attributeIdx); CascadeActionEnum enumValue = value == null ? null : CascadeActionEnum.getEnum(value.toLowerCase()); if (enumValue == null) { throw new DdlUtilsXMLException("Illegal boolean value '" + value +"' for attribute " + xmlReader.getAttributeLocalName(attributeIdx)); } else { return enumValue; } } /** * Consumes the rest of the current element. This assumes that the current XML stream * event type is not START_ELEMENT. * * @param reader The xml reader */ private void consumeRestOfElement(XMLStreamReader reader) throws XMLStreamException { int eventType = reader.getEventType(); while ((eventType != XMLStreamReader.END_ELEMENT) && (eventType != XMLStreamReader.END_DOCUMENT)) { eventType = reader.next(); } } /** * Reads over the current element. This assumes that the current XML stream event type is * START_ELEMENT. * * @param reader The xml reader */ private void readOverElement(XMLStreamReader reader) throws XMLStreamException { int depth = 1; while (depth > 0) { int eventType = reader.next(); if (eventType == XMLStreamReader.START_ELEMENT) { depth++; } else if (eventType == XMLStreamReader.END_ELEMENT) { depth--; } } } /** * Writes the database model to the specified file. * * @param model The database model * @param filename The model file name */ public void write(Database model, String filename) throws DdlUtilsXMLException { try { BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(filename)); write(model, writer); writer.flush(); } finally { if (writer != null) { writer.close(); } } } catch (Exception ex) { throw new DdlUtilsXMLException(ex); } } /** * Writes the database model to the given output stream. Note that this method * does not flush or close the stream. * * @param model The database model * @param output The output stream */ public void write(Database model, OutputStream output) throws DdlUtilsXMLException { PrettyPrintingXmlWriter xmlWriter = new PrettyPrintingXmlWriter(output, "UTF-8"); xmlWriter.setDefaultNamespace(DDLUTILS_NAMESPACE); xmlWriter.writeDocumentStart(); writeDatabaseElement(model, xmlWriter); xmlWriter.writeDocumentEnd(); } /** * Writes the database model to the given output writer. Note that this method * does not flush or close the writer. * * @param model The database model * @param output The output writer */ public void write(Database model, Writer output) throws DdlUtilsXMLException { PrettyPrintingXmlWriter xmlWriter = new PrettyPrintingXmlWriter(output, "UTF-8"); xmlWriter.setDefaultNamespace(DDLUTILS_NAMESPACE); xmlWriter.writeDocumentStart(); writeDatabaseElement(model, xmlWriter); xmlWriter.writeDocumentEnd(); } /** * Writes the database model to the given XML writer. * * @param model The database model * @param xmlWriter The XML writer */ private void writeDatabaseElement(Database model, PrettyPrintingXmlWriter xmlWriter) throws DdlUtilsXMLException { writeElementStart(xmlWriter, QNAME_ELEMENT_DATABASE); xmlWriter.writeNamespace(null, DDLUTILS_NAMESPACE); writeAttribute(xmlWriter, QNAME_ATTRIBUTE_NAME, model.getName()); writeAttribute(xmlWriter, QNAME_ATTRIBUTE_DEFAULT_ID_METHOD, model.getIdMethod()); writeAttribute(xmlWriter, QNAME_ATTRIBUTE_VERSION, model.getVersion()); if (model.getTableCount() > 0) { xmlWriter.printlnIfPrettyPrinting(); for (int idx = 0; idx < model.getTableCount(); idx++) { writeTableElement(model.getTable(idx), xmlWriter); } } writeElementEnd(xmlWriter); } /** * Writes the table object to the given XML writer. * * @param table The table object * @param xmlWriter The XML writer */ private void writeTableElement(Table table, PrettyPrintingXmlWriter xmlWriter) throws DdlUtilsXMLException { xmlWriter.indentIfPrettyPrinting(1); writeElementStart(xmlWriter, QNAME_ELEMENT_TABLE); // GemStone changes BEGIN // write fully qualified table name final String tableName = table.getQualifiedName(); writeAttribute(xmlWriter, QNAME_ATTRIBUTE_NAME, tableName); /* (original code) writeAttribute(xmlWriter, QNAME_ATTRIBUTE_NAME, table.getName()); */ // GemStone changes END writeAttribute(xmlWriter, QNAME_ATTRIBUTE_DESCRIPTION, table.getDescription()); if ((table.getColumnCount() > 0) || (table.getForeignKeyCount() > 0) || (table.getIndexCount() > 0)) { xmlWriter.printlnIfPrettyPrinting(); for (int idx = 0; idx < table.getColumnCount(); idx++) { writeColumnElement(table.getColumn(idx), xmlWriter); } for (int idx = 0; idx < table.getForeignKeyCount(); idx++) { writeForeignKeyElement(table.getForeignKey(idx), xmlWriter); } for (int idx = 0; idx < table.getIndexCount(); idx++) { writeIndexElement(table.getIndex(idx), xmlWriter); } xmlWriter.indentIfPrettyPrinting(1); } writeElementEnd(xmlWriter); } /** * Writes the column object to the given XML writer. * * @param column The column object * @param xmlWriter The XML writer */ private void writeColumnElement(Column column, PrettyPrintingXmlWriter xmlWriter) throws DdlUtilsXMLException { xmlWriter.indentIfPrettyPrinting(2); writeElementStart(xmlWriter, QNAME_ELEMENT_COLUMN); writeAttribute(xmlWriter, QNAME_ATTRIBUTE_NAME, column.getName()); writeAttribute(xmlWriter, QNAME_ATTRIBUTE_PRIMARY_KEY, String.valueOf(column.isPrimaryKey())); writeAttribute(xmlWriter, QNAME_ATTRIBUTE_REQUIRED, String.valueOf(column.isRequired())); writeAttribute(xmlWriter, QNAME_ATTRIBUTE_TYPE, column.getType()); writeAttribute(xmlWriter, QNAME_ATTRIBUTE_SIZE, column.getSize()); writeAttribute(xmlWriter, QNAME_ATTRIBUTE_DEFAULT, column.getDefaultValue()); writeAttribute(xmlWriter, QNAME_ATTRIBUTE_AUTO_INCREMENT, String.valueOf(column.isAutoIncrement())); writeAttribute(xmlWriter, QNAME_ATTRIBUTE_DESCRIPTION, column.getDescription()); writeAttribute(xmlWriter, QNAME_ATTRIBUTE_JAVA_NAME, column.getJavaName()); writeElementEnd(xmlWriter); } /** * Writes the foreign key object to the given XML writer. * * @param foreignKey The foreign key object * @param xmlWriter The XML writer */ private void writeForeignKeyElement(ForeignKey foreignKey, PrettyPrintingXmlWriter xmlWriter) throws DdlUtilsXMLException { xmlWriter.indentIfPrettyPrinting(2); writeElementStart(xmlWriter, QNAME_ELEMENT_FOREIGN_KEY); writeAttribute(xmlWriter, QNAME_ATTRIBUTE_FOREIGN_TABLE, foreignKey.getForeignTableName()); writeAttribute(xmlWriter, QNAME_ATTRIBUTE_NAME, foreignKey.getName()); if (foreignKey.getOnUpdate() != CascadeActionEnum.NONE) { writeAttribute(xmlWriter, QNAME_ATTRIBUTE_ON_UPDATE, foreignKey.getOnUpdate().getName()); } if (foreignKey.getOnDelete() != CascadeActionEnum.NONE) { writeAttribute(xmlWriter, QNAME_ATTRIBUTE_ON_DELETE, foreignKey.getOnDelete().getName()); } if (foreignKey.getReferenceCount() > 0) { xmlWriter.printlnIfPrettyPrinting(); for (int idx = 0; idx < foreignKey.getReferenceCount(); idx++) { writeReferenceElement(foreignKey.getReference(idx), xmlWriter); } xmlWriter.indentIfPrettyPrinting(2); } writeElementEnd(xmlWriter); } /** * Writes the reference object to the given XML writer. * * @param reference The reference object * @param xmlWriter The XML writer */ private void writeReferenceElement(Reference reference, PrettyPrintingXmlWriter xmlWriter) throws DdlUtilsXMLException { xmlWriter.indentIfPrettyPrinting(3); writeElementStart(xmlWriter, QNAME_ELEMENT_REFERENCE); writeAttribute(xmlWriter, QNAME_ATTRIBUTE_LOCAL, reference.getLocalColumnName()); writeAttribute(xmlWriter, QNAME_ATTRIBUTE_FOREIGN, reference.getForeignColumnName()); writeElementEnd(xmlWriter); } /** * Writes the index object to the given XML writer. * * @param index The index object * @param xmlWriter The XML writer */ private void writeIndexElement(Index index, PrettyPrintingXmlWriter xmlWriter) throws DdlUtilsXMLException { xmlWriter.indentIfPrettyPrinting(2); writeElementStart(xmlWriter, index.isUnique() ? QNAME_ELEMENT_UNIQUE : QNAME_ELEMENT_INDEX); writeAttribute(xmlWriter, QNAME_ATTRIBUTE_NAME, index.getName()); if (index.getColumnCount() > 0) { xmlWriter.printlnIfPrettyPrinting(); for (int idx = 0; idx < index.getColumnCount(); idx++) { writeIndexColumnElement(index.getColumn(idx), index.isUnique(), xmlWriter); } xmlWriter.indentIfPrettyPrinting(2); } writeElementEnd(xmlWriter); } /** * Writes the index column object to the given XML writer. * * @param indexColumn The index column object * @param isUnique Whether the index that the index column belongs to, is unique * @param xmlWriter The XML writer */ private void writeIndexColumnElement(IndexColumn indexColumn, boolean isUnique, PrettyPrintingXmlWriter xmlWriter) throws DdlUtilsXMLException { xmlWriter.indentIfPrettyPrinting(3); writeElementStart(xmlWriter, isUnique ? QNAME_ELEMENT_UNIQUE_COLUMN : QNAME_ELEMENT_INDEX_COLUMN); writeAttribute(xmlWriter, QNAME_ATTRIBUTE_NAME, indexColumn.getName()); writeAttribute(xmlWriter, QNAME_ATTRIBUTE_SIZE, indexColumn.getSize()); writeElementEnd(xmlWriter); } /** * Writes the start of the specified XML element to the given XML writer. * * @param xmlWriter The xml writer * @param qName The qname of the XML element */ private void writeElementStart(PrettyPrintingXmlWriter xmlWriter, QName qName) throws DdlUtilsXMLException { xmlWriter.writeElementStart(qName.getNamespaceURI(), qName.getLocalPart()); } /** * Writes an attribute to the given XML writer. * * @param xmlWriter The xml writer * @param qName The qname of the attribute * @param value The value; if empty, then nothing is written */ private void writeAttribute(PrettyPrintingXmlWriter xmlWriter, QName qName, String value) throws DdlUtilsXMLException { if (value != null) { xmlWriter.writeAttribute(null, qName.getLocalPart(), value); } } /** * Writes the end of the current XML element to the given XML writer. * * @param xmlWriter The xml writer */ private void writeElementEnd(PrettyPrintingXmlWriter xmlWriter) throws DdlUtilsXMLException { xmlWriter.writeElementEnd(); xmlWriter.printlnIfPrettyPrinting(); } }
3e1ddaf25c408cb37b715b5a755c7ad9e09ba52c
3,792
java
Java
src/main/java/org/ldk/structs/Result_NodeAnnouncementInfoDecodeErrorZ.java
lightningdevkit/ldk-garbagecollected
52476c310c3ec9e37a37929c19bad0b8e5dc0f35
[ "Apache-2.0", "MIT" ]
27
2021-02-05T16:34:19.000Z
2022-03-30T18:41:56.000Z
src/main/java/org/ldk/structs/Result_NodeAnnouncementInfoDecodeErrorZ.java
TheBlueMatt/ldk-garbagecollected
99a3d528524ef1de3ad0dd3d0f81e5c2df0de226
[ "Apache-2.0", "MIT" ]
57
2021-02-05T16:38:28.000Z
2022-03-29T22:27:00.000Z
src/main/java/org/ldk/structs/Result_NodeAnnouncementInfoDecodeErrorZ.java
TheBlueMatt/ldk-garbagecollected
99a3d528524ef1de3ad0dd3d0f81e5c2df0de226
[ "Apache-2.0", "MIT" ]
8
2021-02-12T02:22:14.000Z
2021-12-11T09:40:21.000Z
39.915789
125
0.783492
12,645
package org.ldk.structs; import org.ldk.impl.bindings; import org.ldk.enums.*; import org.ldk.util.*; import java.util.Arrays; import java.lang.ref.Reference; import javax.annotation.Nullable; public class Result_NodeAnnouncementInfoDecodeErrorZ extends CommonBase { private Result_NodeAnnouncementInfoDecodeErrorZ(Object _dummy, long ptr) { super(ptr); } protected void finalize() throws Throwable { if (ptr != 0) { bindings.CResult_NodeAnnouncementInfoDecodeErrorZ_free(ptr); } super.finalize(); } static Result_NodeAnnouncementInfoDecodeErrorZ constr_from_ptr(long ptr) { if (bindings.CResult_NodeAnnouncementInfoDecodeErrorZ_is_ok(ptr)) { return new Result_NodeAnnouncementInfoDecodeErrorZ_OK(null, ptr); } else { return new Result_NodeAnnouncementInfoDecodeErrorZ_Err(null, ptr); } } public static final class Result_NodeAnnouncementInfoDecodeErrorZ_OK extends Result_NodeAnnouncementInfoDecodeErrorZ { public final NodeAnnouncementInfo res; private Result_NodeAnnouncementInfoDecodeErrorZ_OK(Object _dummy, long ptr) { super(_dummy, ptr); long res = bindings.LDKCResult_NodeAnnouncementInfoDecodeErrorZ_get_ok(ptr); NodeAnnouncementInfo res_hu_conv = null; if (res < 0 || res > 4096) { res_hu_conv = new NodeAnnouncementInfo(null, res); } res_hu_conv.ptrs_to.add(this); this.res = res_hu_conv; } } public static final class Result_NodeAnnouncementInfoDecodeErrorZ_Err extends Result_NodeAnnouncementInfoDecodeErrorZ { public final DecodeError err; private Result_NodeAnnouncementInfoDecodeErrorZ_Err(Object _dummy, long ptr) { super(_dummy, ptr); long err = bindings.LDKCResult_NodeAnnouncementInfoDecodeErrorZ_get_err(ptr); DecodeError err_hu_conv = null; if (err < 0 || err > 4096) { err_hu_conv = new DecodeError(null, err); } err_hu_conv.ptrs_to.add(this); this.err = err_hu_conv; } } /** * Creates a new CResult_NodeAnnouncementInfoDecodeErrorZ in the success state. */ public static Result_NodeAnnouncementInfoDecodeErrorZ ok(NodeAnnouncementInfo o) { long ret = bindings.CResult_NodeAnnouncementInfoDecodeErrorZ_ok(o == null ? 0 : o.ptr & ~1); Reference.reachabilityFence(o); if (ret >= 0 && ret <= 4096) { return null; } Result_NodeAnnouncementInfoDecodeErrorZ ret_hu_conv = Result_NodeAnnouncementInfoDecodeErrorZ.constr_from_ptr(ret); return ret_hu_conv; } /** * Creates a new CResult_NodeAnnouncementInfoDecodeErrorZ in the error state. */ public static Result_NodeAnnouncementInfoDecodeErrorZ err(DecodeError e) { long ret = bindings.CResult_NodeAnnouncementInfoDecodeErrorZ_err(e == null ? 0 : e.ptr & ~1); Reference.reachabilityFence(e); if (ret >= 0 && ret <= 4096) { return null; } Result_NodeAnnouncementInfoDecodeErrorZ ret_hu_conv = Result_NodeAnnouncementInfoDecodeErrorZ.constr_from_ptr(ret); return ret_hu_conv; } /** * Checks if the given object is currently in the success state */ public boolean is_ok() { boolean ret = bindings.CResult_NodeAnnouncementInfoDecodeErrorZ_is_ok(this.ptr); Reference.reachabilityFence(this); return ret; } long clone_ptr() { long ret = bindings.CResult_NodeAnnouncementInfoDecodeErrorZ_clone_ptr(this.ptr); Reference.reachabilityFence(this); return ret; } /** * Creates a new CResult_NodeAnnouncementInfoDecodeErrorZ which has the same data as `orig` * but with all dynamically-allocated buffers duplicated in new buffers. */ public Result_NodeAnnouncementInfoDecodeErrorZ clone() { long ret = bindings.CResult_NodeAnnouncementInfoDecodeErrorZ_clone(this.ptr); Reference.reachabilityFence(this); if (ret >= 0 && ret <= 4096) { return null; } Result_NodeAnnouncementInfoDecodeErrorZ ret_hu_conv = Result_NodeAnnouncementInfoDecodeErrorZ.constr_from_ptr(ret); return ret_hu_conv; } }
3e1ddced60ef9b35ea6daf1be82563d24b22551d
5,214
java
Java
src/main/java/com/u8/server/web/pay/sdk/KuGouPayCallbackAction.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/web/pay/sdk/KuGouPayCallbackAction.java
game-platform-awaresome/sdkserver
109c5070b68d0aa8de97fb217e1e14feecc17d66
[ "Apache-2.0" ]
null
null
null
src/main/java/com/u8/server/web/pay/sdk/KuGouPayCallbackAction.java
game-platform-awaresome/sdkserver
109c5070b68d0aa8de97fb217e1e14feecc17d66
[ "Apache-2.0" ]
1
2019-03-20T08:27:22.000Z
2019-03-20T08:27:22.000Z
25.811881
118
0.583237
12,646
package com.u8.server.web.pay.sdk; import com.u8.server.common.UActionSupport; import com.u8.server.constants.PayState; import com.u8.server.data.UChannel; import com.u8.server.data.UOrder; import com.u8.server.log.Log; import com.u8.server.service.UOrderManager; import com.u8.server.utils.EncryptUtils; import com.u8.server.web.pay.SendAgent; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import java.io.IOException; import java.util.Date; /** * 酷狗SDK支付回调处理 * Created by ant on 2016/1/18. */ @Controller @Namespace("/pay/kugou") public class KuGouPayCallbackAction extends UActionSupport{ private String orderid; //平台订单号(联运平台唯一订单号) private String outorderid; //游戏厂商订单号(游戏厂商需保证订单唯一性) (回调时url编码) private Integer amount; //充值金额(人民币),以此值兑换游戏币。单位(元) private String username; //平台帐号(回调时url编码) private Integer status; //是否扣费成功.1:成功,0:不成功 private String time; //发起请求时间,Unix时间戳 private String ext1; //扩展字段1,原样传回(回调时url编码) private String ext2; //扩展字段2,原样传回(回调时url编码) private String sign; //md5后的结果小写md5(orderid+outorderid+amount+username+status+time+ext1+ext2+key) @Autowired private UOrderManager orderManager; @Action("payCallback") public void payCallback(){ try{ long orderID = Long.parseLong(outorderid); UOrder order = orderManager.getOrder(orderID); if(order == null){ Log.d("The order is null"); this.renderState(false); return; } UChannel channel = order.getChannel(); if(channel == null){ Log.d("the channel is null."); this.renderState(false); return; } if(order.getState() > PayState.STATE_PAYING) { Log.d("The state of the order is complete. The state is " + order.getState()); this.renderState(true); return; } if(!isSignOK(channel)){ Log.d("The sign verify failed.sign:%s;appKey:%s;orderID:%s", sign, channel.getCpPayKey(), outorderid); this.renderState(false); return; } if(this.status == 1){ int moneyInt = amount * 100; //以分为单位 order.setRealMoney(moneyInt); order.setSdkOrderTime(time); order.setCompleteTime(new Date()); order.setChannelOrderID(orderid); order.setState(PayState.STATE_SUC); orderManager.saveOrder(order); SendAgent.sendCallbackToServer(this.orderManager, order); }else{ order.setChannelOrderID(orderid); order.setState(PayState.STATE_FAILED); orderManager.saveOrder(order); } renderState(true); }catch(Exception e){ try { renderState(false); } catch (IOException e1) { e1.printStackTrace(); } e.printStackTrace(); } } private boolean isSignOK(UChannel channel){ StringBuilder sb = new StringBuilder(); sb.append(orderid).append(outorderid) .append(amount).append(username) .append(status).append(time) .append(ext1).append(ext2) .append(channel.getCpAppSecret()); String md5 = EncryptUtils.md5(sb.toString()).toLowerCase(); return md5.equals(this.sign); } private void renderState(boolean suc) throws IOException { String res = "SUCCESS"; if(!suc){ res = "FAIL"; } renderText(res); } public String getOrderid() { return orderid; } public void setOrderid(String orderid) { this.orderid = orderid; } public String getOutorderid() { return outorderid; } public void setOutorderid(String outorderid) { this.outorderid = outorderid; } public Integer getAmount() { return amount; } public void setAmount(Integer amount) { this.amount = amount; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public String getExt1() { return ext1; } public void setExt1(String ext1) { this.ext1 = ext1; } public String getExt2() { return ext2; } public void setExt2(String ext2) { this.ext2 = ext2; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } }
3e1ddd3ebcc7cc6b07dfddf1e4e30db7ec38ebf6
927
java
Java
org.metaborg.spoofax.core/src/main/java/org/metaborg/spoofax/core/action/TransformAction.java
mpsijm/spoofax
d1e0d02e7343ceffb81ca340380bcb4ec9415955
[ "Apache-2.0" ]
null
null
null
org.metaborg.spoofax.core/src/main/java/org/metaborg/spoofax/core/action/TransformAction.java
mpsijm/spoofax
d1e0d02e7343ceffb81ca340380bcb4ec9415955
[ "Apache-2.0" ]
null
null
null
org.metaborg.spoofax.core/src/main/java/org/metaborg/spoofax/core/action/TransformAction.java
mpsijm/spoofax
d1e0d02e7343ceffb81ca340380bcb4ec9415955
[ "Apache-2.0" ]
null
null
null
24.394737
107
0.68932
12,647
package org.metaborg.spoofax.core.action; import org.metaborg.core.action.ITransformAction; import org.metaborg.core.action.ITransformGoal; import org.metaborg.core.action.TransformActionFlags; public class TransformAction implements ITransformAction { public final String name; public final ITransformGoal goal; public final TransformActionFlags flags; public final String strategy; public TransformAction(String name, ITransformGoal goal, TransformActionFlags flags, String strategy) { this.name = name; this.goal = goal; this.flags = flags; this.strategy = strategy; } @Override public String name() { return name; } @Override public ITransformGoal goal() { return goal; } @Override public TransformActionFlags flags() { return flags; } @Override public String toString() { return name; } }
3e1dddc038d6b00603c8a3fa083271d48f37838f
506
java
Java
managed/src/main/java/com/yugabyte/yw/models/helpers/KnownAlertTypes.java
TiannV/yugabyte-db
d9bbcb186fdcdf8d06e2ceaafda642084c2058d1
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
managed/src/main/java/com/yugabyte/yw/models/helpers/KnownAlertTypes.java
TiannV/yugabyte-db
d9bbcb186fdcdf8d06e2ceaafda642084c2058d1
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
managed/src/main/java/com/yugabyte/yw/models/helpers/KnownAlertTypes.java
TiannV/yugabyte-db
d9bbcb186fdcdf8d06e2ceaafda642084c2058d1
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
28.111111
100
0.73913
12,648
/* * Copyright 2021 YugaByte, Inc. and Contributors * * Licensed under the Polyform Free Trial License 1.0.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://github.com/YugaByte/yugabyte-db/blob/master/licenses/POLYFORM-FREE-TRIAL-LICENSE-1.0.0.txt */ package com.yugabyte.yw.models.helpers; // TODO - probably need to be removed and replaced with severity public enum KnownAlertTypes { Warning, Error }
3e1ddf213c2616d4cfa875fd014afeeef3c95028
8,633
java
Java
src/main/java/ru/mail/polis/alexanderkiselyov/CompactOperations.java
PaaavelZ/2022-nosql-lsm
f9fba1097339c736e0cbfc9632c82d3dbd8761de
[ "Apache-2.0" ]
2
2022-02-24T18:35:40.000Z
2022-03-03T10:58:27.000Z
src/main/java/ru/mail/polis/alexanderkiselyov/CompactOperations.java
PaaavelZ/2022-nosql-lsm
f9fba1097339c736e0cbfc9632c82d3dbd8761de
[ "Apache-2.0" ]
61
2022-02-24T23:50:10.000Z
2022-03-31T21:43:53.000Z
src/main/java/ru/mail/polis/alexanderkiselyov/CompactOperations.java
PaaavelZ/2022-nosql-lsm
f9fba1097339c736e0cbfc9632c82d3dbd8761de
[ "Apache-2.0" ]
27
2022-02-24T18:35:52.000Z
2022-03-11T11:31:20.000Z
43.822335
118
0.634194
12,649
package ru.mail.polis.alexanderkiselyov; import ru.mail.polis.BaseEntry; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.nio.file.StandardCopyOption.ATOMIC_MOVE; public class CompactOperations { private Path compactedFile; private Path compactedIndex; private static final String FILE_START_COMPACT = "startCompact.sc"; private static final String FILE_START_COMPACT_INDEX = "startCompactIndex.sdx"; private static final String FILE_CONTINUE_COMPACT = "continueCompact.cc"; private static final String FILE_CONTINUE_COMPACT_INDEX = "continueCompactIndex.cdx"; private final String fileName; private final String fileExtension; private final String fileIndexName; private final String fileIndexExtension; public CompactOperations(String fileName, String fileExtension, String fileIndexName, String fileIndexExtension) { this.fileName = fileName; this.fileExtension = fileExtension; this.fileIndexName = fileIndexName; this.fileIndexExtension = fileIndexExtension; } Map<Path, Path> checkFiles(Path basePath) throws IOException { Map<Path, Path> allData = new LinkedHashMap<>(); try (Stream<Path> filesStream = Files.list(basePath)) { List<Path> files = filesStream.toList(); checkCompactConflicts(basePath, files); List<Path> ssTables = files .stream().toList().stream() .filter(f -> String.valueOf(f.getFileName()).startsWith(fileName)) .sorted(new PathsComparator(fileName, fileExtension)) .toList(); List<Path> ssIndexes = files .stream().toList().stream() .filter(f -> String.valueOf(f.getFileName()).startsWith(fileIndexName)) .sorted(new PathsComparator(fileIndexName, fileIndexExtension)) .toList(); if (ssTables.size() != ssIndexes.size()) { throw new NoSuchFileException("Not all files found!"); } for (int i = 0; i < ssTables.size(); i++) { Path data = ssTables.get(i); Path index = ssIndexes.get(i); checkDataAndIndexCompliance(data, index); allData.put(data, index); } } return allData; } private void checkCompactConflicts(Path basePath, List<Path> files) throws IOException { for (Path file : files) { if (checkStartCompactConflicts(basePath, file, files)) { break; } if (checkContinueCompactionConflicts(basePath, file, files)) { break; } } } private boolean checkStartCompactConflicts(Path basePath, Path file, List<Path> files) throws IOException { if (file == basePath.resolve(FILE_START_COMPACT)) { Files.delete(basePath.resolve(FILE_START_COMPACT)); if (files.contains(basePath.resolve(FILE_START_COMPACT_INDEX))) { Files.delete(basePath.resolve(FILE_START_COMPACT_INDEX)); } return true; } return false; } private boolean checkContinueCompactionConflicts(Path basePath, Path file, List<Path> files) throws IOException { if (file == basePath.resolve(FILE_CONTINUE_COMPACT)) { if (files.contains(basePath.resolve(FILE_CONTINUE_COMPACT_INDEX))) { List<Path> ssTables = files .stream().toList().stream() .filter(f -> f.getFileName().toString().startsWith(fileName)) .sorted(new PathsComparator(fileName, fileExtension)) .collect(Collectors.toList()); List<Path> ssIndexes = files .stream().toList().stream() .filter(f -> f.getFileName().toString().startsWith(fileIndexName)) .sorted(new PathsComparator(fileIndexName, fileIndexExtension)) .collect(Collectors.toList()); deleteFiles(ssTables); deleteFiles(ssIndexes); Files.move(basePath.resolve(FILE_CONTINUE_COMPACT), basePath.resolve(fileName + "0" + fileExtension), ATOMIC_MOVE); Files.move(basePath.resolve(FILE_CONTINUE_COMPACT_INDEX), basePath.resolve(fileIndexName + "0" + fileIndexExtension), ATOMIC_MOVE); } else { Files.delete(basePath.resolve(FILE_CONTINUE_COMPACT)); } return true; } return false; } private void deleteFiles(List<Path> filePaths) throws IOException { for (Path filePath : filePaths) { Files.delete(filePath); } } private void checkDataAndIndexCompliance(Path data, Path index) throws IOException { String dataStr = data.toString(); String indexStr = index.toString(); if (Integer.parseInt(dataStr.substring(dataStr.indexOf(fileName) + fileName.length(), dataStr.indexOf(fileExtension))) != Integer.parseInt(indexStr.substring(indexStr.indexOf(fileIndexName) + fileIndexName.length(), indexStr.indexOf(fileIndexExtension)))) { throw new NoSuchFileException("Not all files match!"); } } void saveDataAndIndexesCompact(Iterator<BaseEntry<byte[]>> iterator, Path basePath) throws IOException { long elementsCount = 0; long offset = 0; compactedFile = basePath.resolve(FILE_START_COMPACT); compactedIndex = basePath.resolve(FILE_START_COMPACT_INDEX); Files.createFile(compactedFile); Files.createFile(compactedIndex); try (FileReaderWriter writerFile = new FileReaderWriter(compactedFile, compactedIndex)) { writeIndexInitialPosition(writerFile.getIndexChannel()); while (iterator.hasNext()) { BaseEntry<byte[]> current = iterator.next(); Map.Entry<byte[], BaseEntry<byte[]>> currentBaseEntry = Map.entry(current.key(), new BaseEntry<>(current.key(), current.value())); FileOperations.writePair(writerFile.getFileChannel(), currentBaseEntry); offset = FileOperations.writeEntryPosition(writerFile.getIndexChannel(), currentBaseEntry, offset); elementsCount++; } writeIndexSize(elementsCount, writerFile.getIndexChannel()); } Files.move(compactedFile, basePath.resolve(FILE_CONTINUE_COMPACT), ATOMIC_MOVE); Files.move(compactedIndex, basePath.resolve(FILE_CONTINUE_COMPACT_INDEX), ATOMIC_MOVE); compactedFile = basePath.resolve(FILE_CONTINUE_COMPACT); compactedIndex = basePath.resolve(FILE_CONTINUE_COMPACT_INDEX); } private static void writeIndexInitialPosition(FileChannel channel) throws IOException { ByteBuffer longBuffer = ByteBuffer.allocate(Long.BYTES); channel.position(Long.BYTES); longBuffer.putLong(0); longBuffer.flip(); channel.write(longBuffer); } private static void writeIndexSize(long elementsCount, FileChannel channel) throws IOException { ByteBuffer longBuffer = ByteBuffer.allocate(Long.BYTES); channel.position(0); longBuffer.putLong(elementsCount); longBuffer.flip(); channel.write(longBuffer); } void renameCompactedFile(Path basePath) throws IOException { Files.move(compactedFile, basePath.resolve(fileName + "0" + fileExtension), ATOMIC_MOVE); Files.move(compactedIndex, basePath.resolve(fileIndexName + "0" + fileIndexExtension), ATOMIC_MOVE); } void clearFileIterators(List<FileIterator> fileIterators) throws IOException { for (FileIterator fi : fileIterators) { if (fi != null) { fi.close(); } } fileIterators.clear(); } void deleteAllFiles(List<Path> ssTables, List<Path> ssIndexes) throws IOException { for (Path ssTable : ssTables) { Files.delete(ssTable); } for (Path ssIndex : ssIndexes) { Files.delete(ssIndex); } } }
3e1ddfe5c55b9407a955900e2b198aca9510b063
152
java
Java
java/java-tests/testData/codeInsight/completion/smartType/SameSignatureWithGenerics.java
dunno99/intellij-community
aa656a5d874b947271b896b2105e4370827b9149
[ "Apache-2.0" ]
2
2018-12-29T09:53:39.000Z
2018-12-29T09:53:42.000Z
java/java-tests/testData/codeInsight/completion/smartType/SameSignatureWithGenerics.java
dunno99/intellij-community
aa656a5d874b947271b896b2105e4370827b9149
[ "Apache-2.0" ]
173
2018-07-05T13:59:39.000Z
2018-08-09T01:12:03.000Z
java/java-tests/testData/codeInsight/completion/smartType/SameSignatureWithGenerics.java
dunno99/intellij-community
aa656a5d874b947271b896b2105e4370827b9149
[ "Apache-2.0" ]
2
2020-03-15T08:57:37.000Z
2020-04-07T04:48:14.000Z
19
43
0.592105
12,650
class A<T> { public A(T i, String z, String zz) {} } class B extends A<String> { public B(String i, String zz, String z) { super(<caret>); } }
3e1de01eca3943db7f4286b61877c08b1e515fe9
2,218
java
Java
src/com/facebook/buck/core/rules/analysis/impl/RuleAnalysisContextImpl.java
njlr/buck
3d83814d615f54269bb5f83fa383b4c823f69eb2
[ "Apache-2.0" ]
1
2019-04-14T20:16:47.000Z
2019-04-14T20:16:47.000Z
src/com/facebook/buck/core/rules/analysis/impl/RuleAnalysisContextImpl.java
njlr/buck
3d83814d615f54269bb5f83fa383b4c823f69eb2
[ "Apache-2.0" ]
null
null
null
src/com/facebook/buck/core/rules/analysis/impl/RuleAnalysisContextImpl.java
njlr/buck
3d83814d615f54269bb5f83fa383b4c823f69eb2
[ "Apache-2.0" ]
null
null
null
36.360656
100
0.770514
12,651
/* * Copyright 2018-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.core.rules.analysis.impl; import com.facebook.buck.core.rules.actions.ActionAnalysisData; import com.facebook.buck.core.rules.actions.ActionAnalysisData.Key; import com.facebook.buck.core.rules.analysis.RuleAnalysisContext; import com.facebook.buck.core.rules.analysis.RuleAnalysisKey; import com.facebook.buck.core.rules.providers.ProviderInfoCollection; import com.google.common.base.Verify; import com.google.common.collect.ImmutableMap; import java.util.HashMap; import java.util.Map; /** * Implementation of {@link com.facebook.buck.core.rules.analysis.RuleAnalysisContext}. This context * is created per rule analysis. */ class RuleAnalysisContextImpl implements RuleAnalysisContext { private final ImmutableMap<RuleAnalysisKey, ProviderInfoCollection> depProviders; private final Map<Key, ActionAnalysisData> actionRegistry = new HashMap<>(); RuleAnalysisContextImpl(ImmutableMap<RuleAnalysisKey, ProviderInfoCollection> depProviders) { this.depProviders = depProviders; } @Override public ImmutableMap<RuleAnalysisKey, ProviderInfoCollection> deps() { return depProviders; } @Override public void registerAction(ActionAnalysisData actionAnalysisData) { ActionAnalysisData prev = actionRegistry.putIfAbsent(actionAnalysisData.getKey(), actionAnalysisData); Verify.verify( prev == null, "Action of key %s was already registered with %s", actionAnalysisData.getKey(), prev); } public Map<ActionAnalysisData.Key, ActionAnalysisData> getRegisteredActionData() { return actionRegistry; } }