blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 410 | content_id stringlengths 40 40 | detected_licenses listlengths 0 51 | license_type stringclasses 2
values | repo_name stringlengths 5 132 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 80 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 132
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 9.45M | extension stringclasses 28
values | content stringlengths 3 9.45M | authors listlengths 1 1 | author_id stringlengths 0 352 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
adee0dfc1febee494a32386a86d0068747648b56 | 6d5297916213639382a2f049437190b872f4224a | /malapi/src/main/java/org/ccsds/moims/mo/mal/structures/factory/FineTimeListFactory.java | 4e2e441b2bc7eb9febeec2b07d4548a98ee7e3c6 | [
"MIT"
] | permissive | CNES/ccsdsmo-maljava | 9051d8b89f344ebde1bbe5aa087830f7d114619a | d3def5815edd5df24c18a0d7132c35181820e42c | refs/heads/master | 2023-07-01T21:10:39.359622 | 2021-08-02T14:00:46 | 2021-08-02T14:00:46 | 109,702,581 | 0 | 1 | MIT | 2021-08-02T13:52:24 | 2017-11-06T14:01:13 | Java | UTF-8 | Java | false | false | 1,606 | java | /*******************************************************************************
* MIT License
*
* Copyright (c) 2017 CNES
*
* 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.ccsds.moims.mo.mal.structures.factory;
public final class FineTimeListFactory implements org.ccsds.moims.mo.mal.MALElementFactory {
public org.ccsds.moims.mo.mal.structures.Element createElement() {
return new org.ccsds.moims.mo.mal.structures.FineTimeList();
}
}
| [
"andre.freyssinet@scalagent.com"
] | andre.freyssinet@scalagent.com |
5f295e5de7eb72f93207bc1492170cbdd105db8e | c4183785154ea47c325bea881b162c04b2026072 | /JTAF-ExtWebDriver/src/test/java/org/finra/jtaf/ewd/widget/element/ElementTest.java | afe89d7dcf992aee5dfcbe457bd74d7708870940 | [
"Apache-2.0"
] | permissive | EWD-Avengers/JTAF-ExtWebDriver | 4222e07070e334c5a06eb123f6acde0cdd333133 | 1d75569bab51e3018d903c3cadbcfb83fea2a712 | refs/heads/master | 2021-01-16T23:27:34.387070 | 2014-07-19T20:43:43 | 2014-07-19T20:43:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 19,413 | java | /*
* (C) Copyright 2013 Java Test Automation Framework Contributors.
*
* 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.finra.jtaf.ewd.widget.element;
import org.finra.jtaf.ewd.ExtWebDriver;
import org.finra.jtaf.ewd.HighlightProvider;
import org.finra.jtaf.ewd.session.SessionManager;
import org.finra.jtaf.ewd.widget.IElement;
import org.finra.jtaf.ewd.widget.IInteractiveElement;
import org.finra.jtaf.ewd.widget.WidgetException;
import org.finra.jtaf.ewd.widget.element.html.Button;
import org.finra.jtaf.ewd.widget.element.html.Input;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class ElementTest {
public static String url = "http://localhost:29090/simpleapp/elementstestapp.html";
public ExtWebDriver wd;
public static String button = "//button[@id='myButton']";
public static String invisibleButton = "//button[@id='myInvisibleButton']";
private String getButton(String id){
return "//button[@id='" + id + "']";
}
private String getSpan(String id){
return "//span[@id='" + id + "']";
}
private String getDiv(String id){
return "//div[@id='" + id + "']";
}
@Before
public void setup() throws Exception {
wd = SessionManager.getInstance().getNewSession();
}
@After
public void teardown() {
wd.close();
SessionManager.getInstance().removeSession(wd);
}
@Test
public void testGetLocator() throws WidgetException{
wd.open(url);
String test = "//DIV[@id='this_is_my_locator']";
IElement e = new Element(test);
Assert.assertEquals("Test get locator should return the value passed in", test, e.getLocator());
}
@Test
public void testIsElementPresentTrue() throws WidgetException{
wd.open(url);
IElement e = new Element(button);
Assert.assertTrue("Test isElementPresent on an element that does exist returns true", e.isElementPresent());
}
@Test
public void testIsElementPresentFalse() throws WidgetException{
wd.open(url);
String test = "//button[@id='myButtonDoesntExist']";
IElement e = new Element(test);
Assert.assertFalse("Test isElementPresent on an element that doesn't exist returns false", e.isElementPresent());
}
// @Test(expected=WidgetException.class)
// public void testIsElementPresentException() throws WidgetException{
// wd.open(url);
// String test = "//button[@id='myButtonDo";
// IElement e = new Element(test);
// e.isElementPresent();
// }
@Test
public void testIsElementPresentTimeoutTrue() throws WidgetException{
wd.open(url);
IElement e = new Element(button);
Assert.assertTrue("Test isElementPresent on an element that does exist returns true", e.isElementPresent(500));
}
@Test
public void testIsElementPresentTimeoutFalse() throws WidgetException{
wd.open(url);
String test = "//button[@id='myButtonDoesntExist']";
IElement e = new Element(test);
Assert.assertFalse("Test isElementPresent on an element that doesn't exist returns false", e.isElementPresent(500));
}
// @Test(expected=WidgetException.class)
// public void testIsElementPresentTimeoutException() throws WidgetException{
// wd.open(url);
// String test = "//button[@id='myButtonDo";
// IElement e = new Element(test);
// e.isElementPresent(500);
// }
@Test
public void testIsElementNotPresentFalse() throws WidgetException{
wd.open(url);
IElement e = new Element(button);
Assert.assertFalse("Test isElementPresent on an element that does not exist returns false", e.isElementNotPresent());
}
@Test
public void testIsElementNotPresentTrue() throws WidgetException{
wd.open(url);
String test = "//button[@id='myButtonDoesntExist']";
IElement e = new Element(test);
Assert.assertTrue("Test isElementPresent on an element that doesn't exist returns true", e.isElementNotPresent());
}
// @Test(expected=WidgetException.class)
// public void testIsElementNotPresentException() throws WidgetException{
// wd.open(url);
// String test = "//button[@id='myButtonDo";
// IElement e = new Element(test);
// e.isElementNotPresent();
// }
@Test
public void testIsElementNotPresentTimeoutFalse() throws WidgetException{
wd.open(url);
IElement e = new Element(button);
Assert.assertFalse("Test isElementPresent on an element that does not exist returns false", e.isElementNotPresent(500));
}
@Test
public void testIsElementNotPresentTimeoutTrue() throws WidgetException{
wd.open(url);
String test = "//button[@id='myButtonDoesntExist']";
IElement e = new Element(test);
Assert.assertTrue("Test isElementPresent on an element that doesn't exist returns true", e.isElementNotPresent(500));
}
// @Test(expected=WidgetException.class)
// public void testIsElementNotPresentTimeoutException() throws WidgetException{
// wd.open(url);
// String test = "//button[@id='myButtonDo";
// IElement e = new Element(test);
// e.isElementNotPresent(500);
// }
@Test
public void testIsElementVisibleFalse() throws WidgetException{
wd.open(url);
IElement hidden = new Element(invisibleButton);
Assert.assertFalse("Testing isElementVisible on a non-hidden button should be return true", hidden.isElementVisible());
}
@Test
public void testIsElementVisibleTrue() throws WidgetException{
wd.open(url);
IElement hidden = new Element(button);
Assert.assertTrue("Testing isElementVisible on a hidden button should be return false", hidden.isElementVisible());
}
@Test(expected=WidgetException.class)
public void testIsElementVisibleException() throws WidgetException{
wd.open(url);
IElement hidden = new Element(null);
hidden.isElementVisible();
}
@Test
public void testIsElementVisibleTimeoutFalse() throws WidgetException{
wd.open(url);
IElement hidden = new Element(invisibleButton);
Assert.assertFalse("Testing isElementVisible on a non-hidden button should be return true", hidden.isElementVisible(500));
}
@Test
public void testIsElementVisibleTimeoutTrue() throws WidgetException{
wd.open(url);
IElement hidden = new Element(button);
Assert.assertTrue("Testing isElementVisible on a hidden button should be return false", hidden.isElementVisible(500));
}
// @Test(expected=WidgetException.class)
// public void testIsElementVisibleTimeoutException() throws WidgetException{
// wd.open(url);
// IElement hidden = new Element(null);
// hidden.isElementVisible(500);
// }
@Test
public void testWaitForElementPresent() throws WidgetException{
wd.open(url);
IInteractiveElement clickButton = new Button(getButton("testWaitButton"));
IElement waitForElement = new Element(getSpan("waitForSpan"));
clickButton.click();
waitForElement.waitForElementPresent();
}
@Test(expected=WidgetException.class)
public void testWaitForElementPresentTimeout() throws WidgetException{
wd.open(url);
IInteractiveElement clickButton = new Button(getButton("testWaitButton"));
IElement waitForElement = new Element(getSpan("failMe"));
clickButton.click();
waitForElement.waitForElementPresent();
}
@Test
public void testWaitForElementNotPresent() throws WidgetException{
wd.open(url);
IInteractiveElement clickButton = new Button(getButton("testWaitElementNotPresentButton"));
IElement waitForElement = new Element(getSpan("someText"));
clickButton.click();
waitForElement.waitForElementNotPresent();
}
@Test(expected=WidgetException.class)
public void testWaitForElementNotPresentTimeout() throws WidgetException{
wd.open(url);
IElement waitForElement = new Element(getSpan("someText"));
waitForElement.waitForElementNotPresent();
}
@Test
public void testWaitForVisible() throws WidgetException{
wd.open(url);
IInteractiveElement clickButton = new Button(getButton("visibilityTest"));
IElement element = new Element(getButton("myInvisibleButton"));
clickButton.click();
element.waitForVisible();
}
@Test(expected=WidgetException.class)
public void testWaitForVisibleException() throws WidgetException{
wd.open(url);
IElement element = new Element(getButton("myInvisibleButton"));
element.waitForVisible();
}
@Test
public void testWaitForNotVisible() throws WidgetException{
wd.open(url);
IInteractiveElement clickButton = new Button(getButton("nonVisibilityTest"));
IElement element = new Element(getButton("visibilityTest"));
clickButton.click();
element.waitForNotVisible();
}
@Test(expected=WidgetException.class)
public void testWaitForNotVisibleException() throws WidgetException{
wd.open(url);
IElement element = new Element(getButton("visibilityTest"));
element.waitForNotVisible();
}
@Test
public void testGetText() throws WidgetException{
wd.open(url);
IElement element = new Element(getSpan("someText"));
String exp = "Here is some text";
Assert.assertEquals(exp, element.getText());
}
@Test(expected=WidgetException.class)
public void testGetTextException() throws WidgetException{
wd.open(url);
IElement element = new Element(getSpan("INVALIDsomeText"));
element.getText();
}
@Test
public void testIsAttributePresentTrue() throws WidgetException{
wd.open(url);
IElement element = new Element(getDiv("content"));
Assert.assertTrue("Test isAttributePresent returns true", element.isAttributePresent("randomAttrib"));
}
// * TODO: Instead of returning false, HTMLUnit throws the WidgetException, try running this test in firefox
@Test
public void testIsAttributePresentFalse() throws WidgetException{
wd.open(url);
IElement element = new Element(getDiv("content"));
Assert.assertFalse("Test isAttributePresent returns false", element.isAttributePresent("someAttribute"));
}
@Test(expected=WidgetException.class)
public void testIsAttributePresentException() throws WidgetException{
wd.open(url);
IElement element = new Element(getDiv("myContent"));
element.isAttributePresent("randomAttrib");
}
@Test
public void testGetAttribute() throws WidgetException{
wd.open(url);
IElement element = new Element(getDiv("content"));
String expected = "Hello";
Assert.assertEquals("Test getAttribute returns expected string", expected, element.getAttribute("randomAttrib"));
}
// @Test(expected=WidgetException.class)
// public void testGetAttributeException() throws WidgetException{
// wd.open(url);
//
// IElement element = new Element(getDiv("NotMyContent"));
// element.getAttribute("randomAttrib");
// }
@Test
public void testWaitForAttributeEqualTo() throws WidgetException{
wd.open(url);
IInteractiveElement clickButton = new Button(getButton("attributeChanger"));
IElement element = new Element(getDiv("content"));
clickButton.click();
element.waitForAttributeEqualTo("randomAttrib", "Goodbye");
}
@Test(expected=WidgetException.class)
public void testWaitForAttributeEqualToException() throws WidgetException{
wd.open(url);
IElement element = new Element(getDiv("content"));
element.waitForAttributeEqualTo("randomAttrib", "Goodbye");
}
@Test
public void testWaitForAttributeNotEqualTo() throws WidgetException{
wd.open(url);
IInteractiveElement clickButton = new Button(getButton("attributeChanger"));
IElement element = new Element(getDiv("content"));
clickButton.click();
element.waitForAttributeNotEqualTo("randomAttrib", "Hello");
}
@Test(expected=WidgetException.class)
public void testWaitForAttributeNotEqualToException() throws WidgetException{
wd.open(url);
IElement element = new Element(getDiv("content"));
element.waitForAttributeNotEqualTo("randomAttrib", "Hello");
}
@Test
public void testWaitForText() throws WidgetException{
wd.open(url);
IInteractiveElement clickButton = new Button(getButton("testWaitButton"));
IElement element = new Element(getDiv("content"));
clickButton.click();
element.waitForText();
}
@Test(expected=WidgetException.class)
public void testWaitForTextException() throws WidgetException{
wd.open(url);
IElement element = new Element(getDiv("content"));
element.waitForText();
}
@Test
public void testGetLocationX() throws WidgetException{
wd.open(url);
IElement element = new Element(getButton("testWaitButton"));
int val = -1;
val = element.getLocationX();
Assert.assertNotEquals("Test that getLocationX returned an int value", -1, val);
}
@Test (expected=WidgetException.class)
public void testGetLocationXException() throws WidgetException{
wd.open(url);
IElement element = new Element(getButton("zzztestWaitButton"));
int val = -1;
val = element.getLocationX();
Assert.assertNotEquals(-1, val);
}
@Test
public void testGetLocationY() throws WidgetException{
wd.open(url);
IElement element = new Element(getButton("testWaitButton"));
int val = -1;
val = element.getLocationY();
Assert.assertNotEquals("Test that getLocationY returned an int value", -1, val);
}
@Test (expected=WidgetException.class)
public void testGetLocationYException() throws WidgetException{
wd.open(url);
IElement element = new Element(getButton("zzztestWaitButton"));
int val = -1;
val = element.getLocationY();
Assert.assertNotEquals(-1, val);
}
@Test
public void testHasTextTrue() throws WidgetException{
wd.open(url);
IElement element = new Element(getDiv("removeContent"));
Assert.assertTrue("Test that hasText returns true", element.hasText("some"));
}
@Test
public void testHasTextFalse() throws WidgetException{
wd.open(url);
IElement element = new Element(getDiv("removeContent"));
Assert.assertFalse("Test that hasText returns false", element.hasText("This Be"));
}
@Test(expected=WidgetException.class)
public void testHasTextException() throws WidgetException{
wd.open(url);
IElement element = new Element(getDiv("zzzzcontent"));
element.hasText("Here");
}
@Test
public void testGetCssValue() throws WidgetException{
wd.open(url);
IElement element = new Element(getButton("myInvisibleButton"));
Assert.assertEquals("Test that getCssValue returns the correct attribute", "hidden", element.getCssValue("visibility"));
}
@Test(expected=WidgetException.class)
public void testGetCssValueException() throws WidgetException{
wd.open(url);
IElement element = new Element(getButton("zzzmyInvisibleButton"));
Assert.assertEquals("Test that getCssValue returns the correct attribute", "hidden", element.getCssValue("visibility"));
}
//*Not part of IElement, but part of Element
@Test
public void testSetGUIDriver() throws Exception{
ExtWebDriver otherwd = null;
try {
otherwd = SessionManager.getInstance().getNewSession(false);
wd.open(url);
otherwd.open(url);
Element content = new Element(getDiv("content"));
IInteractiveElement button = new Button(getButton("testWaitButton"));
button.click();
content.waitForText();
String session1Str = content.getText();
content.setGUIDriver(otherwd);
content.waitForElementPresent();
String session2Str = content.getText();
Assert.assertNotEquals("Test that Element successfully switched sessions", session1Str, session2Str);
} finally {
if(otherwd != null) {
otherwd.close();
SessionManager.getInstance().removeSession(otherwd);
}
}
}
@Test
public void testGetInnerHtml() throws WidgetException {
wd.open(url);
IElement e = new Element("someText");
String html = e.getInnerHTML();
Assert.assertEquals("Here is some text", html);
}
@Test
public void testGetChildNodesValuesText() throws WidgetException{
wd.open(url);
IElement e = new Element("inner1");
String[] actual = e.getChildNodesValuesText();
String[] expected = new String[]{"hello world", "welcome"};
Assert.assertArrayEquals(expected, actual);
}
@Test
public void testCSSSelector() throws WidgetException{
wd.open(url);
IElement e = new Element("#myButton");
Assert.assertEquals("Click me", e.getText());
}
@Test
public void testCSSSelector2() throws WidgetException{
wd.open(url);
IElement e = new Element("#removeContent>span");
Assert.assertEquals("Here is some text", e.getText());
}
@Test
public void testHighlight() throws WidgetException{
wd.open(url);
HighlightProvider highDriver = (HighlightProvider) wd;
if(highDriver.isHighlight()){
Element e1 = new Element(getButton("testOverTime"));
e1.findElement();
Assert.assertEquals(highDriver.getHighlightColor("find"),getRgb(e1.getCssValue("background-color")) );
Element e2 = new Element(getButton("myButton"));
e2.isAttributePresent("xyz");
Assert.assertEquals(getRgb(e2.getCssValue("background-color")), highDriver.getHighlightColor("get"));
}
}
@Test
public void testFocusOn() throws WidgetException {
wd.open(url);
Input in = new Input("//input[@id=\"focusOnMe\"]");
Assert.assertEquals(in.getValue(), "");
in.focusOn();
Assert.assertEquals(in.getValue(), "you focused!");
}
public String getRgb(String rgba){
if(rgba.startsWith("rgba") & rgba.split(",").length>3){
String[] splits = rgba.substring(rgba.indexOf("a")+1).split(",");
return "rgb"+splits[0]+","+splits[1]+","+splits[2]+")";
}
else
return rgba;
}
}
| [
"bryantrobbins@gmail.com"
] | bryantrobbins@gmail.com |
43a0faff4c5cf4d46fd4aede56b42c13f73e1843 | 2c3d38702b7f9e9c808b97a10b45a1ec0e5afcbe | /eiana-web-common/test/org/iana/rzm/web/common/technical_check/NotEnoughNameServersMessageBuilderTest.java | d3c4856896c798e407bc314673c95838a7b2e104 | [] | no_license | immon/eiana | b600b6521d87e2af5d84f12457382d9696b730ae | d3edc3476a15d49d02b64df8c93eab2a5112bb79 | refs/heads/master | 2016-09-11T02:03:26.800463 | 2009-09-02T15:13:35 | 2009-09-02T15:13:35 | 35,203,663 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,094 | java | package org.iana.rzm.web.common.technical_check;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.StringReader;
public class NotEnoughNameServersMessageBuilderTest {
@Test
public void testBuildMessage()throws Exception{
String xml =
"<exception name=\"NotEnoughNameServersException\">\n" +
" <received>\n" +
" <value name=\"ns\">2</value>\n" +
" </received>\n" +
" <expected>\n" +
" <value name=\"ns\">3</value>\n" +
" </expected>\n" +
"</exception>";
Document document = new SAXBuilder().build(new StringReader(xml));
Element element = document.getRootElement();
NotEnoughNameServersMessageBuilder builder = new NotEnoughNameServersMessageBuilder();
Assert.assertEquals(builder.build(element, "root"), "IANA Required a minimum of 3 name servers hosts you only have 2");
}
}
| [
"sraveh@54c49d9a-8729-0410-8bbb-d8f729217203"
] | sraveh@54c49d9a-8729-0410-8bbb-d8f729217203 |
614da69c3ce92d0ae97e7886104a7fcd12f1565c | 924a8e06bc46da3f0f5b44449cdce4cd78033b30 | /Client/app/src/main/java/com/example/zhiliao/OperateData.java | 7f8550decd534c424075ac09698c0f43febf1c82 | [] | no_license | kelis-cpu/zhiliao_success | 9f00b33d54d462ff7d0c53c22d586f8525330c88 | ccf330d21153fe3f0e3b376f257641e26a420448 | refs/heads/main | 2023-04-15T07:57:59.961984 | 2021-04-25T16:07:27 | 2021-04-25T16:07:27 | 361,466,437 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,178 | java | package com.example.zhiliao;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.IDN;
import java.net.ProtocolException;
import java.net.URI;
import java.net.URL;
public class OperateData {
public String stringTojson(String stringArray[])//string转json格式字符串
{
JSONObject js=null;
if (stringArray==null)
{
return "";
}
js=new JSONObject();
try{
js.put("username",stringArray[0]);
js.put("password",stringArray[1]);
}
catch (JSONException e)
{
e.printStackTrace();
}
String jsonString=String.valueOf(js);
return jsonString;
}
public String stringTojson2(int ID,boolean islike,String usrname)//设置点赞
{
JSONObject js=null;
js=new JSONObject();
try{
js.put("articleID", ID);
js.put("islike",islike);
js.put("usrname",usrname);
} catch (JSONException e) {
e.printStackTrace();
}
return js.toString();
}
public int jsonToint(String jsonString)//获取jsonString中的具体数值,用于判断登录状态
{
int type=1;
try{
JSONObject js=new JSONObject(jsonString);
type=js.getInt("type");
Log.i("type",""+type);
}catch (JSONException e)
{
e.printStackTrace();
}
return type;
}
/**
功能:发送jsonString到服务器进行解析
msg.what:
0:服务器连接失败
1:注册/登录成功 跳转页面
2:用户已存在/登陆失败
3:地址为空
4:连接超时
**/
public void sendData(final String jsonString, final android.os.Handler mh, final URL url)
{
if (url==null)
{
mh.sendEmptyMessage(3);
}
else
{
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection httpURLConnection=null;
BufferedReader bufferedReader=null;
try{
httpURLConnection = (HttpURLConnection) url.openConnection();
// 设置连接超时时间
httpURLConnection.setConnectTimeout(5 * 1000);
//设置从主机读取数据超时
httpURLConnection.setReadTimeout(5 * 1000);
// Post请求必须设置允许输出 默认false
httpURLConnection.setDoOutput(true);
//设置请求允许输入 默认是true
httpURLConnection.setDoInput(true);
// Post请求不能使用缓存
httpURLConnection.setUseCaches(false);
// 设置为Post请求
httpURLConnection.setRequestMethod("POST");
//设置本次连接是否自动处理重定向
httpURLConnection.setInstanceFollowRedirects(true);
// 配置请求Content-Type
httpURLConnection.setRequestProperty("Content-Type", "application/json");
//开始连接
httpURLConnection.connect();
//发送数据
Log.i("JSONString",jsonString);
DataOutputStream os=new DataOutputStream(httpURLConnection.getOutputStream());
os.writeBytes(jsonString);
os.flush();
os.close();
Log.i("状态码",""+httpURLConnection.getResponseCode());
if (httpURLConnection.getResponseCode()==httpURLConnection.HTTP_OK)//判断服务器是否连接成功
{
bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
StringBuilder res = new StringBuilder();
String temp;
while ((temp=bufferedReader.readLine())!=null)
{
res.append(temp);
Log.i("Main",res.toString());
}
int type=jsonToint(res.toString());//判断状态
switch (type)
{
case 0:
mh.sendEmptyMessage(1);
break;
case 1:
mh.sendEmptyMessage(2);
break;
case 2:
mh.sendEmptyMessage(5);
default:
}
}
else
{
mh.sendEmptyMessage(0);
}
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
mh.sendEmptyMessage(4);
}finally {
if (bufferedReader!=null){
try{bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (httpURLConnection!=null)
{
httpURLConnection.disconnect();
}
}
}
}).start();
}
}
}
| [
"2652355330@qq.com"
] | 2652355330@qq.com |
527805dcbacf33a69aa0c8cd61bb93c3276558d0 | 580b2cd51051d42c543a0eafcc7f31e8b9da0780 | /src/jfugue/demo/java/org/jfugue/pattern/InstrumentListener.java | f601e60dd95711a36702a77ca6c3046535b3fc22 | [] | no_license | cozzarin787/Music_Theory | 0739dc2fbbbb0ec77dc5c83dcbb28c189891e8b8 | 3824f3b8a69d4a533ebb803ad564610bbcce6b7d | refs/heads/master | 2021-01-12T18:28:10.801950 | 2016-10-19T20:51:55 | 2016-10-19T20:51:55 | 71,385,003 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,151 | java | /*
* JFugue, an Application Programming Interface (API) for Music Programming
* http://www.jfugue.org
*
* Copyright (C) 2003-2014 David Koelle
*
* 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 jfugue.demo.java.org.jfugue.pattern;
import java.util.ArrayList;
import java.util.List;
import org.jfugue.parser.ParserListenerAdapter;
public class InstrumentListener extends ParserListenerAdapter {
private List<Byte> instruments = new ArrayList<Byte>();
@Override
public void onInstrumentParsed(byte instrument) {
instruments.add(instrument);
}
public List<Byte> getInstruments() {
return this.instruments;
}
}
| [
"cozzarin787@gmail.com"
] | cozzarin787@gmail.com |
1c6d9cc5d37f46c3079fb89cabd7d1812922a466 | 265246868844ff6c2c14aebe37f379072c6ca7ce | /src/main/java/com/ctsdev/sqsdemo/service/SqsReceiverImpl.java | 56aa70b5e5dd806f1d1d992bf2bdf9068ac3de3c | [] | no_license | nanda-dev/aws-sqs-demo | f52f901df9c85c4f9aa18e5b2620403d06c19610 | f1e8a4d684e91e119dca97b6374a1358223e1e74 | refs/heads/master | 2021-09-10T00:27:06.799648 | 2018-03-20T11:14:33 | 2018-03-20T11:14:33 | 125,999,012 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,230 | java | package com.ctsdev.sqsdemo.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.aws.messaging.core.QueueMessagingTemplate;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.stereotype.Component;
@Component
public class SqsReceiverImpl implements SqsReceiver {
Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private QueueMessagingTemplate sqsTemplate;
@Value("${queue.activation.name}")
private String activationQueue;
@Override
public Object receiveMessage() {
logger.info("Receiving Message from Queue: {}", activationQueue);
String message = sqsTemplate.receiveAndConvert(activationQueue, String.class);
logger.info("Message received:{}", message);
return message;
}
@MessageMapping("${queue.activation.name}")
public void pollForMessage(Object message, @Header("SenderId") String senderId) {
logger.info("Received {} sent by {}, from Queue: {}", (String) message, senderId, activationQueue);
}
}
| [
"172201@cognizant.com"
] | 172201@cognizant.com |
798eaea6ed21e2b8844d42d6875300efd935a438 | 2706c5ec72d9c7bc8ea4efe6ae3aa72abc2f8bf9 | /02 - 自定义登录/src/test/java/com/spring4all/config/CustomFromLoginFilterWebTest.java | 25dc8c74ea8108214dd37023c52322dd50f62b2a | [] | no_license | fish-spring/spring-security-demos | 275b55541eb49e77889b0574381e35292c956cbd | 0362812771661c936652c276bec23551a5b9bc12 | refs/heads/master | 2020-05-22T14:29:48.620236 | 2019-05-14T10:28:58 | 2019-05-14T10:28:58 | 186,386,211 | 0 | 0 | null | 2019-05-13T09:16:16 | 2019-05-13T09:16:15 | null | UTF-8 | Java | false | false | 831 | java | package com.spring4all.config;
import com.spring4all.ApplicationTest;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import static org.junit.Assert.*;
public class CustomFromLoginFilterWebTest extends ApplicationTest {
@Test
public void attemptAuthentication() throws Exception {
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders
.post("/login")
.param("username", "Jon")
.param("password", "123456");
mockMvc.perform(builder)
.andDo(MockMvcResultHandlers.print());
}
} | [
"bitfishxyz@gmail.com"
] | bitfishxyz@gmail.com |
74bce09609c526686b4b35d5e9d17acac9a9e06d | b2a310022a956b16b6d52a71f6dc7130abb8a146 | /net.sf.ubq.script/src-gen/net/sf/ubq/script/ubqt/impl/UbqSlotImpl.java | 8b9b1ccf4af9e230920c1c87cfca9a399a55faed | [] | no_license | lucascraft/ubq | 4a6827a426acba84626ebd0d490d183516b8722e | 6cea9daf447bc6693e38af2ed882931103e1240f | refs/heads/master | 2021-01-24T16:11:02.480362 | 2016-03-18T20:20:30 | 2016-03-18T20:20:30 | 37,204,048 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,730 | java | /**
* <copyright>
* </copyright>
*
*/
package net.sf.ubq.script.ubqt.impl;
import java.util.Collection;
import net.sf.ubq.script.ubqt.SLOTS;
import net.sf.ubq.script.ubqt.SLOT_KIND;
import net.sf.ubq.script.ubqt.SLOT_STATUS;
import net.sf.ubq.script.ubqt.UbqBounds;
import net.sf.ubq.script.ubqt.UbqEmmitedActions;
import net.sf.ubq.script.ubqt.UbqHandledReactions;
import net.sf.ubq.script.ubqt.UbqSlot;
import net.sf.ubq.script.ubqt.UbqtPackage;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Ubq Slot</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link net.sf.ubq.script.ubqt.impl.UbqSlotImpl#getName <em>Name</em>}</li>
* <li>{@link net.sf.ubq.script.ubqt.impl.UbqSlotImpl#getBounds <em>Bounds</em>}</li>
* <li>{@link net.sf.ubq.script.ubqt.impl.UbqSlotImpl#getPosition <em>Position</em>}</li>
* <li>{@link net.sf.ubq.script.ubqt.impl.UbqSlotImpl#getKind <em>Kind</em>}</li>
* <li>{@link net.sf.ubq.script.ubqt.impl.UbqSlotImpl#getStatus <em>Status</em>}</li>
* <li>{@link net.sf.ubq.script.ubqt.impl.UbqSlotImpl#getEmitted <em>Emitted</em>}</li>
* <li>{@link net.sf.ubq.script.ubqt.impl.UbqSlotImpl#getReacted <em>Reacted</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class UbqSlotImpl extends MinimalEObjectImpl.Container implements UbqSlot
{
/**
* The default value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected static final String NAME_EDEFAULT = null;
/**
* The cached value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected String name = NAME_EDEFAULT;
/**
* The cached value of the '{@link #getBounds() <em>Bounds</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getBounds()
* @generated
* @ordered
*/
protected UbqBounds bounds;
/**
* The default value of the '{@link #getPosition() <em>Position</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getPosition()
* @generated
* @ordered
*/
protected static final SLOTS POSITION_EDEFAULT = SLOTS.P0;
/**
* The cached value of the '{@link #getPosition() <em>Position</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getPosition()
* @generated
* @ordered
*/
protected SLOTS position = POSITION_EDEFAULT;
/**
* The default value of the '{@link #getKind() <em>Kind</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getKind()
* @generated
* @ordered
*/
protected static final SLOT_KIND KIND_EDEFAULT = SLOT_KIND.PUSH;
/**
* The cached value of the '{@link #getKind() <em>Kind</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getKind()
* @generated
* @ordered
*/
protected SLOT_KIND kind = KIND_EDEFAULT;
/**
* The default value of the '{@link #getStatus() <em>Status</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getStatus()
* @generated
* @ordered
*/
protected static final SLOT_STATUS STATUS_EDEFAULT = SLOT_STATUS.SELECTED;
/**
* The cached value of the '{@link #getStatus() <em>Status</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getStatus()
* @generated
* @ordered
*/
protected SLOT_STATUS status = STATUS_EDEFAULT;
/**
* The cached value of the '{@link #getEmitted() <em>Emitted</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getEmitted()
* @generated
* @ordered
*/
protected EList<UbqEmmitedActions> emitted;
/**
* The cached value of the '{@link #getReacted() <em>Reacted</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getReacted()
* @generated
* @ordered
*/
protected EList<UbqHandledReactions> reacted;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected UbqSlotImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass()
{
return UbqtPackage.Literals.UBQ_SLOT;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName()
{
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setName(String newName)
{
String oldName = name;
name = newName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, UbqtPackage.UBQ_SLOT__NAME, oldName, name));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public UbqBounds getBounds()
{
return bounds;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetBounds(UbqBounds newBounds, NotificationChain msgs)
{
UbqBounds oldBounds = bounds;
bounds = newBounds;
if (eNotificationRequired())
{
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, UbqtPackage.UBQ_SLOT__BOUNDS, oldBounds, newBounds);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setBounds(UbqBounds newBounds)
{
if (newBounds != bounds)
{
NotificationChain msgs = null;
if (bounds != null)
msgs = ((InternalEObject)bounds).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - UbqtPackage.UBQ_SLOT__BOUNDS, null, msgs);
if (newBounds != null)
msgs = ((InternalEObject)newBounds).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - UbqtPackage.UBQ_SLOT__BOUNDS, null, msgs);
msgs = basicSetBounds(newBounds, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, UbqtPackage.UBQ_SLOT__BOUNDS, newBounds, newBounds));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SLOTS getPosition()
{
return position;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setPosition(SLOTS newPosition)
{
SLOTS oldPosition = position;
position = newPosition == null ? POSITION_EDEFAULT : newPosition;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, UbqtPackage.UBQ_SLOT__POSITION, oldPosition, position));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SLOT_KIND getKind()
{
return kind;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setKind(SLOT_KIND newKind)
{
SLOT_KIND oldKind = kind;
kind = newKind == null ? KIND_EDEFAULT : newKind;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, UbqtPackage.UBQ_SLOT__KIND, oldKind, kind));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SLOT_STATUS getStatus()
{
return status;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setStatus(SLOT_STATUS newStatus)
{
SLOT_STATUS oldStatus = status;
status = newStatus == null ? STATUS_EDEFAULT : newStatus;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, UbqtPackage.UBQ_SLOT__STATUS, oldStatus, status));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<UbqEmmitedActions> getEmitted()
{
if (emitted == null)
{
emitted = new EObjectContainmentEList<UbqEmmitedActions>(UbqEmmitedActions.class, this, UbqtPackage.UBQ_SLOT__EMITTED);
}
return emitted;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<UbqHandledReactions> getReacted()
{
if (reacted == null)
{
reacted = new EObjectContainmentEList<UbqHandledReactions>(UbqHandledReactions.class, this, UbqtPackage.UBQ_SLOT__REACTED);
}
return reacted;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
{
switch (featureID)
{
case UbqtPackage.UBQ_SLOT__BOUNDS:
return basicSetBounds(null, msgs);
case UbqtPackage.UBQ_SLOT__EMITTED:
return ((InternalEList<?>)getEmitted()).basicRemove(otherEnd, msgs);
case UbqtPackage.UBQ_SLOT__REACTED:
return ((InternalEList<?>)getReacted()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType)
{
switch (featureID)
{
case UbqtPackage.UBQ_SLOT__NAME:
return getName();
case UbqtPackage.UBQ_SLOT__BOUNDS:
return getBounds();
case UbqtPackage.UBQ_SLOT__POSITION:
return getPosition();
case UbqtPackage.UBQ_SLOT__KIND:
return getKind();
case UbqtPackage.UBQ_SLOT__STATUS:
return getStatus();
case UbqtPackage.UBQ_SLOT__EMITTED:
return getEmitted();
case UbqtPackage.UBQ_SLOT__REACTED:
return getReacted();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue)
{
switch (featureID)
{
case UbqtPackage.UBQ_SLOT__NAME:
setName((String)newValue);
return;
case UbqtPackage.UBQ_SLOT__BOUNDS:
setBounds((UbqBounds)newValue);
return;
case UbqtPackage.UBQ_SLOT__POSITION:
setPosition((SLOTS)newValue);
return;
case UbqtPackage.UBQ_SLOT__KIND:
setKind((SLOT_KIND)newValue);
return;
case UbqtPackage.UBQ_SLOT__STATUS:
setStatus((SLOT_STATUS)newValue);
return;
case UbqtPackage.UBQ_SLOT__EMITTED:
getEmitted().clear();
getEmitted().addAll((Collection<? extends UbqEmmitedActions>)newValue);
return;
case UbqtPackage.UBQ_SLOT__REACTED:
getReacted().clear();
getReacted().addAll((Collection<? extends UbqHandledReactions>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID)
{
switch (featureID)
{
case UbqtPackage.UBQ_SLOT__NAME:
setName(NAME_EDEFAULT);
return;
case UbqtPackage.UBQ_SLOT__BOUNDS:
setBounds((UbqBounds)null);
return;
case UbqtPackage.UBQ_SLOT__POSITION:
setPosition(POSITION_EDEFAULT);
return;
case UbqtPackage.UBQ_SLOT__KIND:
setKind(KIND_EDEFAULT);
return;
case UbqtPackage.UBQ_SLOT__STATUS:
setStatus(STATUS_EDEFAULT);
return;
case UbqtPackage.UBQ_SLOT__EMITTED:
getEmitted().clear();
return;
case UbqtPackage.UBQ_SLOT__REACTED:
getReacted().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID)
{
switch (featureID)
{
case UbqtPackage.UBQ_SLOT__NAME:
return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
case UbqtPackage.UBQ_SLOT__BOUNDS:
return bounds != null;
case UbqtPackage.UBQ_SLOT__POSITION:
return position != POSITION_EDEFAULT;
case UbqtPackage.UBQ_SLOT__KIND:
return kind != KIND_EDEFAULT;
case UbqtPackage.UBQ_SLOT__STATUS:
return status != STATUS_EDEFAULT;
case UbqtPackage.UBQ_SLOT__EMITTED:
return emitted != null && !emitted.isEmpty();
case UbqtPackage.UBQ_SLOT__REACTED:
return reacted != null && !reacted.isEmpty();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString()
{
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (name: ");
result.append(name);
result.append(", position: ");
result.append(position);
result.append(", kind: ");
result.append(kind);
result.append(", status: ");
result.append(status);
result.append(')');
return result.toString();
}
} //UbqSlotImpl
| [
"lucas.bigeardel@gmail.com"
] | lucas.bigeardel@gmail.com |
82d3137fc27ebbf96d81160dc8f32362fd78e4a5 | b99d56b287df37598f56015f18a86e8472203205 | /app/src/main/java/com/example/infostudentfpoo/Login.java | 08461863d373a0df46f0ddeef62ecd1b6631cfdc | [] | no_license | DaniENP/InfoStudentfPOO | 2fed80e824c57994aae0183bfac0a2766166f102 | 1f61a3d6c97cb4b98b90c99b37a887ecfb596063 | refs/heads/master | 2022-10-08T02:40:44.510367 | 2020-06-12T05:29:57 | 2020-06-12T05:29:57 | 261,348,332 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,464 | java | package com.example.infostudentfpoo;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class Login extends AppCompatActivity {
EditText mEmail,mPassword;
Button mLoginBtn;
TextView mCreateBtn,forgotTextLink;
ProgressBar progressBar;
FirebaseAuth fAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
mEmail = findViewById(R.id.Email);
mPassword = findViewById(R.id.password);
progressBar = findViewById(R.id.progressBar);
fAuth = FirebaseAuth.getInstance();
mLoginBtn = findViewById(R.id.loginBtn);
mCreateBtn = findViewById(R.id.createText);
forgotTextLink = findViewById(R.id.forgotPassword);
mLoginBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
if(TextUtils.isEmpty(email)){
mEmail.setError("Se necesita un email.");
return;
}
if(TextUtils.isEmpty(password)){
mPassword.setError("Ingrese Contraseña.");
return;
}
if(password.length() < 6){
mPassword.setError("La contrasseña dede tener al menos 6 caracteres");
return;
}
progressBar.setVisibility(View.VISIBLE);
// authenticate the user
fAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(Login.this, "Inicio exitoso", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),Main_Chat.class));
}else {
Toast.makeText(Login.this, "Error ! " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
});
}
});
mCreateBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),Register.class));
}
});
forgotTextLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final EditText resetMail = new EditText(v.getContext());
final AlertDialog.Builder passwordResetDialog = new AlertDialog.Builder(v.getContext());
passwordResetDialog.setTitle("¿Restablecer contraseña?");
passwordResetDialog.setMessage("Ingresa email para recibir link de recuperacion.");
passwordResetDialog.setView(resetMail);
passwordResetDialog.setPositiveButton("Si", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// extract the email and send reset link
String mail = resetMail.getText().toString();
fAuth.sendPasswordResetEmail(mail).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Toast.makeText(Login.this, "Link de recuperacion enviado.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(Login.this, "Error ! El correo no se ha enviado" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
});
passwordResetDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// close the dialog
}
});
passwordResetDialog.create().show();
}
});
}
}
| [
"SebasAngarita@users.noreply.github.com"
] | SebasAngarita@users.noreply.github.com |
1aa3d699aecd02b3b3dd412cb07ff320dc33ba11 | 0764ac07b7bb3a6e6e36311b138d7362b383bbb4 | /algo-lecture/src/main/java/기초코딩테스트_트레이닝/삽입정렬3.java | 6c1361f277e412f5f291db2e67ac89e38955b4eb | [] | no_license | pparksuuu/algorithm | 183104fdc8a6b3ed106b068235baaab7a1e0e960 | e9467e225b598ce069618bfb5a93bdc3614a5472 | refs/heads/master | 2020-03-24T21:07:43.862206 | 2019-01-23T15:00:32 | 2019-01-23T15:00:32 | 143,014,741 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 520 | java | package 기초코딩테스트_트레이닝;
public class 삽입정렬3 { // 카드를 삽입한다!
public static void main(String[] args) {
int[] input = {5, 6, 2, 8, 7, 23, 4, 1, 44};
insertionSort(input, input.length);
for (int a : input) {
System.out.print(a + " ");
}
}
private static void insertionSort(int[] a, int n) {
int temp = 0;
int j = 0;
for (int i = 1; i < n; i++) {
temp = a[i];
for (j = i; j > 0 && a[j - 1] > temp; j--) {
a[j] = a[j - 1];
}
a[j] = temp;
}
}
}
| [
"supr2000@gmail.com"
] | supr2000@gmail.com |
77394d831404a5f2c283e0c144a9d0ce440b6ffd | a11d5011782a8a400d4cff87192b06f3ec3101c1 | /youjung/src/프_야근지수/Main.java | 8f4eefb6218c3b1935dc8dd26b2e8431fe4f65d1 | [] | no_license | ujungggg/algorithm- | b380e5d182c6866a69ab07afb9a3dfea3a0d074c | e2e9340af06a54bc9bce66ef032324e4e647db88 | refs/heads/main | 2023-04-22T12:37:17.167001 | 2021-05-06T09:28:14 | 2021-05-06T09:28:14 | 364,835,313 | 0 | 0 | null | null | null | null | UHC | Java | false | false | 1,928 | java | package 프_야근지수;
import java.util.*;
class Solution {
public static void main(String[] args) {
int[] works = {4,3,3};
int n = 4;
solution(n,works);
}
public static long solution(int n, int[] nworks) {
Integer[] works = Arrays.stream(nworks).boxed().toArray(Integer[]::new);
Arrays.sort(works,Collections.reverseOrder());
/*
int total = works.length;
while( n / total > 0 ){
int minus = n / total ;
for(int i=0;i<total ;i++){
if( works[i] - minus>=0){
works[i] -= minus;
n -= minus;
}else{
works[i] = 0;
}
}
}
long answer = 0;
for(int i=0;i<total;i++){
if(n>0){
if(works[i]-1>=0){
works[i] --;
n--;
}
}
answer += Math.pow(works[i],2);
}
*/
int total = works.length;
int minus = n/total;
for(int i=0;i<total;i++){
System.out.println(works[i]);
}
for(int i=0;i< total;i++){
if(n<= 0) break;
if(works[i]-minus>=0){
System.out.println(works[i]);
works[i] -= minus;
System.out.println(works[i]);
n -= minus;
}
}
for(int i=0;i<total;i++){
System.out.print(works[i]+" ");
}
long answer =0;
if(n>0){
for(int i=0;i< total;i++){
if(n<= 0) break;
if(works[i]-1>=0){
works[i] -= 1;
n -= 1;
}
answer += Math.pow(works[i], 2);
}
}
System.out.println(answer);
return answer;
}
} | [
"choijessy@naver.com"
] | choijessy@naver.com |
bcc07dba2b4f9e1e88c849286b56616295d0b695 | 8bb57607197432fd54cfed45fd5396501d8d5a3a | /src/FilterPattern/Person.java | 27dacfd15b06de3cb10aa88bab5ed0f436dfff27 | [] | no_license | lucasgaspar22/DesignPatterns-Java | 5a124f9cc781f54d1fd23008fcc6aef53d4742fa | f59c0492188c159a764e09fff895e7772cd97da5 | refs/heads/master | 2020-05-31T16:20:56.643891 | 2019-06-06T13:53:51 | 2019-06-06T13:53:51 | 190,378,853 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 440 | java | package FilterPattern;
public class Person {
private String name;
private String gender;
private String maritalStatus;
public Person(String name, String gender, String maritalStatus){
this.name = name;
this.gender = gender;
this.maritalStatus = maritalStatus;
}
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public String getMaritalStatus() {
return maritalStatus;
}
}
| [
"lucasprgaspar@gmail.com"
] | lucasprgaspar@gmail.com |
15a116f99abc65db234c72c398c8d7958bd8c254 | 3bd8a394efffc3bd9626c4c022259a095c6642ef | /dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Versions.java | 703ea96aa2df80bebb09616351cc578ed11cb3c6 | [
"Apache-2.0",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | LostKe/dubbo-copy | 2a74b58a9514f99e438072f0c9bfa314272e10d2 | 792ed99805ed7a86c17222f008210f0be63fd99e | refs/heads/master | 2022-12-19T20:29:28.022709 | 2021-07-09T09:31:17 | 2021-07-09T09:31:17 | 158,633,639 | 0 | 1 | Apache-2.0 | 2022-12-16T03:05:09 | 2018-11-22T02:47:23 | Java | UTF-8 | Java | false | false | 4,008 | java | /*
* Copyright 1999-2101 Alibaba Group.
*
* 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.alibaba.dubbo.governance.web.sysinfo.module.screen;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.governance.service.ConsumerService;
import com.alibaba.dubbo.governance.service.ProviderService;
import com.alibaba.dubbo.governance.web.common.module.screen.Restful;
import com.alibaba.dubbo.registry.common.domain.Consumer;
import com.alibaba.dubbo.registry.common.domain.Provider;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author tony.chenl
*/
public class Versions extends Restful {
@Autowired
private ProviderService providerService;
@Autowired
private ConsumerService consumerService;
public void index(Map<String, Object> context) {
List<Provider> providers = providerService.findAll();
List<Consumer> consumers = consumerService.findAll();
Set<String> parametersSet = new HashSet<String>();
for (Provider provider : providers) {
parametersSet.add(provider.getParameters());
}
for (Consumer consumer : consumers) {
parametersSet.add(consumer.getParameters());
}
Map<String, Set<String>> versions = new HashMap<String, Set<String>>();
Iterator<String> temp = parametersSet.iterator();
while (temp.hasNext()) {
Map<String, String> parameter = StringUtils.parseQueryString(temp.next());
if (parameter != null) {
String dubbo = parameter.get("dubbo");
if (dubbo == null) dubbo = "0.0.0";
String application = parameter.get("application");
if (versions.get(dubbo) == null) {
Set<String> apps = new HashSet<String>();
versions.put(dubbo, apps);
}
versions.get(dubbo).add(application);
}
}
context.put("versions", versions);
}
public void show(Long[] ids, Map<String, Object> context) {
String version = (String) context.get("version");
if (version != null && version.length() > 0) {
List<Provider> providers = providerService.findAll();
List<Consumer> consumers = consumerService.findAll();
Set<String> parametersSet = new HashSet<String>();
Set<String> applications = new HashSet<String>();
for (Provider provider : providers) {
parametersSet.add(provider.getParameters());
}
for (Consumer consumer : consumers) {
parametersSet.add(consumer.getParameters());
}
Iterator<String> temp = parametersSet.iterator();
while (temp.hasNext()) {
Map<String, String> parameter = StringUtils.parseQueryString(temp.next());
if (parameter != null) {
String dubbo = parameter.get("dubbo");
if (dubbo == null) dubbo = "0.0.0";
String application = parameter.get("application");
if (version.equals(dubbo)) {
applications.add(application);
}
}
}
context.put("applications", applications);
}
}
}
| [
"zhangshuqing@smyfinancial.com"
] | zhangshuqing@smyfinancial.com |
3d19b8006e223b167bae543be0fdadda9a1696de | 6015bd13f963841579326995d5008c2b89c4be71 | /app/src/main/java/org/almiso/taskreminder/utils/AndroidUtilities.java | 7e55458d59474cb59086218f70522e19dffa5cfd | [
"Apache-2.0"
] | permissive | almiso/TaskReminder | b41263126e05b755016dd4da2f887fdbbc5a719b | 1f789c0399282c06cb98a2d64be85fd84cede2a4 | refs/heads/master | 2021-01-17T06:50:42.928656 | 2018-10-07T20:44:00 | 2018-10-07T20:44:00 | 55,700,639 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,739 | java | package org.almiso.taskreminder.utils;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.inputmethod.InputMethodManager;
import org.almiso.taskreminder.core.TaskReminderApplication;
import java.util.Hashtable;
/**
* Created by Alexandr Sosorev on 04.04.2016.
*/
public class AndroidUtilities {
protected static final String TAG = "AndroidUtilities";
public static float density = 1;
private static final Hashtable<String, Typeface> typefaceCache = new Hashtable<>();
static {
density = TaskReminderApplication.applicationContext.getResources().getDisplayMetrics().density;
}
public static void RunOnUIThread(Runnable runnable) {
RunOnUIThread(runnable, 0);
}
public static void RunOnUIThread(Runnable runnable, long delay) {
if (delay == 0) {
TaskReminderApplication.applicationHandler.post(runnable);
} else {
TaskReminderApplication.applicationHandler.postDelayed(runnable, delay);
}
}
public static Resources getResources() {
return TaskReminderApplication.application.getResources();
}
public static void showView(View view) {
showView(view, true);
}
public static void showView(View view, boolean isAnimating) {
if (view == null) {
return;
}
if (view.getVisibility() == View.VISIBLE) {
return;
}
if (isAnimating) {
AlphaAnimation alpha = new AlphaAnimation(0.0F, 1.0f);
alpha.setDuration(250);
alpha.setFillAfter(false);
view.startAnimation(alpha);
}
view.setVisibility(View.VISIBLE);
}
public static void hideView(View view) {
hideView(view, true);
}
public static void hideView(View view, boolean isAnimating) {
if (view == null) {
return;
}
if (view.getVisibility() != View.VISIBLE) {
return;
}
if (isAnimating) {
AlphaAnimation alpha = new AlphaAnimation(1.0F, 0.0f);
alpha.setDuration(250);
alpha.setFillAfter(false);
view.startAnimation(alpha);
}
view.setVisibility(View.INVISIBLE);
}
public static void goneView(View view) {
goneView(view, true);
}
public static void goneView(View view, boolean isAnimating) {
if (view == null) {
return;
}
if (view.getVisibility() != View.VISIBLE) {
return;
}
if (isAnimating) {
AlphaAnimation alpha = new AlphaAnimation(1.0F, 0.0f);
alpha.setDuration(250);
alpha.setFillAfter(false);
view.startAnimation(alpha);
}
view.setVisibility(View.GONE);
}
public static void prepareView(View view, boolean isVisible) {
if (view == null) {
return;
}
if (isVisible) {
showView(view);
} else {
goneView(view);
}
}
public static int getPx(float dp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, AndroidUtilities.getResources().getDisplayMetrics());
}
public static int getSp(float sp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, AndroidUtilities.getResources().getDisplayMetrics());
}
public static int dp(float value) {
return (int) Math.ceil(density * value);
}
public static Typeface getTypeface(String assetPath) {
synchronized (typefaceCache) {
if (!typefaceCache.containsKey(assetPath)) {
try {
Typeface t = Typeface.createFromAsset(TaskReminderApplication.applicationContext.getAssets(), assetPath);
typefaceCache.put(assetPath, t);
} catch (Exception e) {
Logger.e(TAG, "Could not get typeface '" + assetPath + "' because " + e.getMessage(), e);
return null;
}
}
return typefaceCache.get(assetPath);
}
}
public static void showKeyboard(View view) {
if (view == null) {
return;
}
InputMethodManager inputManager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
((InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(view, 0);
}
}
| [
"alexandr.sosorev@gmail.com"
] | alexandr.sosorev@gmail.com |
62e4d7a0d86a98cb6b6e091d353fed9003a143c5 | e6ab1c86a343f6c02ee9775506f0abc69f658667 | /m2103/Monopoly-PGM/src/Jeu/Cartes/CarteDeplacement.java | db520c9c8e9d3279e0fb8473b7a0638e583a5e72 | [] | no_license | levitt38/Monopoly-Ihm | 1ae6f3e5c1d8f3eb8d8152ef0866251fe8499f9c | 3db290de9b99312f72732645b58c51e1606d7e2d | refs/heads/master | 2021-01-18T20:08:47.292018 | 2016-06-15T11:01:57 | 2016-06-15T11:01:57 | 60,510,554 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 599 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Jeu.Cartes;
import Data.TypeCarte;
/**
*
* @author Louis
*/
public abstract class CarteDeplacement extends Carte{
private int deplacement;
public CarteDeplacement(String text, TypeCarte type, int location) {
super(text, type);
this.deplacement = location;
}
public int getDeplacement() {
return deplacement;
}
}
| [
"karim.nouri@etu.upmf-grenoble.fr"
] | karim.nouri@etu.upmf-grenoble.fr |
1f6fb0abeffa08413f51c76a9adb50b0c6554414 | 3755c0aa95aab7e412c2d35268e3db4ad66c47e0 | /Lec32_WebCrawl/src/com/lec/java/crawl02/Crawl02Main.java | bc779709a1d9df1832d1dc7e233d8dbab46c4133 | [] | no_license | 108231ju/JavaWork | aeb9e2d4662a96b325454caa31050872920d59e0 | 13048d5d049ce541bf52e6d7fb48235de4f2de76 | refs/heads/master | 2022-07-15T10:40:32.018168 | 2020-05-21T00:09:27 | 2020-05-21T00:09:27 | 259,173,423 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 882 | java | package com.lec.java.crawl02;
import java.io.IOException;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Crawl02Main {
public static void main(String[] args) throws IOException {
System.out.println("네이트 인기 검색어");
//TODO
// www.nate.com
String url;
Response response;
Document doc;
Element element;
url = "https://www.nate.com";
response = Jsoup.connect(url).execute();
doc =response.parse();
Elements search_elements = doc.select("div.search_keyword dd a");
System.out.println(search_elements.size() + "개");
for (Element e : search_elements) {
System.out.println(e.text().trim());
System.out.println(e.attr("href").trim());
}
System.out.println("\n 프로그램 종료");
}
}
| [
"108231ju@naver.com"
] | 108231ju@naver.com |
21ced33200a1a683bc5d5f2a3cf2ef80fc71500b | 9b861cd8a979b56bc912a46d5b0d5892466059ba | /0308_数据存储_下/030804_ContentProvider/3、ContactsProject(增加上下文菜单)/ContactsProject/src/org/lxh/demo/ContactsDemo.java | fb95901f82491e345f56cbfd7b3f4325f9ae9ed4 | [] | no_license | lxxself/MLDN_Android_Code | 9b3c8c08c3d2499ecb37bc354cebef33dd806988 | 5f84582acd5d50ade000de73cddbe21d85aed819 | refs/heads/master | 2020-05-01T00:00:12.355569 | 2015-06-12T05:38:53 | 2015-06-12T05:38:53 | 37,302,322 | 2 | 3 | null | null | null | null | GB18030 | Java | false | false | 3,911 | java | package org.lxh.demo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class ContactsDemo extends Activity {
private Cursor result = null; // 既然要查询,查询返回的就是结果
private ListView contactsList = null; // 定义ListView组件
private List<Map<String, Object>> allContacts = null;
private SimpleAdapter simple = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.main);
this.contactsList = (ListView) super.findViewById(R.id.contactsList); // 取得组件
this.result = super.getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null, null, null); // 查询
super.startManagingCursor(this.result); // 将结果集交给容器管理
this.allContacts = new ArrayList<Map<String, Object>>(); // 实例化List集合
for (this.result.moveToFirst(); !this.result.isAfterLast(); this.result
.moveToNext()) { // 取出结果集中的每一个内容
Map<String, Object> contact = new HashMap<String, Object>();
contact.put("_id", this.result.getInt(this.result
.getColumnIndex(ContactsContract.Contacts._ID)));
contact.put("name", this.result.getString(this.result
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
this.allContacts.add(contact);
}
this.simple = new SimpleAdapter(this, this.allContacts,
R.layout.contacts, new String[] { "_id", "name" }, new int[] {
R.id._id, R.id.name });
this.contactsList.setAdapter(this.simple);
super.registerForContextMenu(this.contactsList); // 注册菜单
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
.getMenuInfo();
int position = info.position; // 取得操作位置
String contactsId = this.allContacts.get(position).get("_id").toString() ;
switch(item.getItemId()){ // 进行菜单的操作
case Menu.FIRST + 1: // 查看
String phoneSelection = ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ "=?";
String[] phoneSelectionArgs = new String[] { contactsId};
Cursor c = super.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
phoneSelection, phoneSelectionArgs, null);
StringBuffer buf = new StringBuffer() ;
buf.append("电话号码是:") ;
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
buf.append(
c.getString(c
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)))
.append("、");
}
Toast.makeText(this, buf, Toast.LENGTH_SHORT)
.show();
break ;
case Menu.FIRST + 2: // 删除
super.getContentResolver().delete(
Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI,
contactsId), null, null);
this.allContacts.remove(position) ; // 删除集合数据项
this.simple.notifyDataSetChanged() ; // 通知改变
Toast.makeText(this, "数据已删除!", Toast.LENGTH_SHORT).show();
break ;
}
return super.onContextItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) { // 创建菜单
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("联系人操作");
menu.add(Menu.NONE, Menu.FIRST + 1, 1, "查看详情");
menu.add(Menu.NONE, Menu.FIRST + 2, 1, "删除信息");
}
} | [
"lxxself@foxmail"
] | lxxself@foxmail |
2e437a3dfa57c522eef62b39c3e3376f5f3fcff5 | 1d1ee8bb1c54b8fcc19add3bd2a1699fbed59b89 | /src/phone/MaxConinuousLengthString.java | 053972a5d9d7b535af71ac508a6230b30ede1788 | [] | no_license | xn1990114/GOOG-My-Code | 49047322db4f39021b843d06db9894e8e8b82a77 | 8fc5126c709a636d6218df3bdfe193538c62a9ff | refs/heads/master | 2021-07-13T01:16:12.717102 | 2020-05-10T00:39:43 | 2020-05-10T00:39:43 | 100,756,319 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,134 | java | package phone;
import java.util.*;
/*
* 给一个list of words,当且仅当word2可以由word1通过插入一个字母达到的时候,可以将word2放在word1之后,比如.
*a-ab-acb-tabc-tabqc- tabpqc.
*每个这样的结构必须从长度为1的单词开始,求返回list中word可以组成的长度最长的结构的最后一个单词,如果上面的例子就是tabpqc。
*/
public class MaxConinuousLengthString {
public Set<String> findLastStringWithSequenceChange(String[] strs){
Map<Integer,Set<String>> map=new HashMap<Integer,Set<String>>();
Map<String,Set<String>> keyMap=new HashMap<String,Set<String>>();
for(String s:strs){
int len=s.length();
if(!map.containsKey(len)){
map.put(len, new HashSet<String>());
}
String key=serilize(s);
map.get(len).add(key);
if(!keyMap.containsKey(key)){
keyMap.put(key, new HashSet<String>());
}
keyMap.get(key).add(s);
}
Set<String> last=map.get(1);
if(last==null){
return new HashSet<String>();
}
int round=2;
while(map.containsKey(round)){
Set<String> target=map.get(round);
Set<String> curr=new HashSet<String>();
for(String s:target){
String[] temp=s.split(",");
int[] tempInt=new int[temp.length];
for(int i=0;i<temp.length;i++){
tempInt[i]=Integer.parseInt(temp[i]);
}
for(int i=0;i<tempInt.length;i++){
if(tempInt[i]>0){
tempInt[i]--;
String tobeFound=reCombine(tempInt);
if(last.contains(tobeFound)){
curr.add(s);
break;
}
tempInt[i]++;
}
}
}
if(curr.isEmpty()){
break;
}
last=curr;
round++;
}
Set<String> res=new HashSet<String>();
for(String key:last){
res.addAll(keyMap.get(key));
}
return res;
}
public Set<String> findLastStringNoSequenceChange(String[] strs){
Map<Integer,Set<String>> map=new HashMap<Integer,Set<String>>();
for(String s:strs){
int len=s.length();
if(!map.containsKey(len)){
map.put(len, new HashSet<String>());
}
map.get(len).add(s);
}
Set<String> last=map.get(1);
if(last==null){
return new HashSet<String>();
}
int round=2;
while(map.containsKey(round)){
Set<String> target=map.get(round);
Set<String> curr=new HashSet<String>();
for(String s:target){
for(int i=0;i<s.length();i++){
String newStr=s.substring(0, i)+s.substring(i+1);
if(last.contains(newStr)){
curr.add(s);
break;
}
}
}
if(curr.isEmpty()){
break;
}
last=curr;
round++;
}
return last;
}
public String serilize(String s){
int[] count=new int[256];
for(int i=0;i<s.length();i++){
count[s.charAt(i)]++;
}
StringBuilder sb=new StringBuilder();
for(int i=0;i<256;i++){
sb.append(count[i]);
if(i<255){
sb.append(',');
}
}
return sb.toString();
}
public String reCombine(int[] nums){
StringBuilder sb=new StringBuilder();
for(int i=0;i<256;i++){
sb.append(nums[i]);
if(i<255){
sb.append(',');
}
}
return sb.toString();
}
public void display(Set<String> set){
for(String s:set){
System.out.print(s+".");
}
System.out.println();
}
}
| [
"xn19901142hotmail.com"
] | xn19901142hotmail.com |
07513848cb2951025d4bd3aed688f5df76525ba1 | 5765c87fd41493dff2fde2a68f9dccc04c1ad2bd | /Variant Programs/1-4/35/filmmaker/FilmmakerFinis.java | 075f8952ce2fe232f22c3f3873b84fc00ab449a0 | [
"MIT"
] | permissive | hjc851/Dataset2-HowToDetectAdvancedSourceCodePlagiarism | 42e4c2061c3f8da0dfce760e168bb9715063645f | a42ced1d5a92963207e3565860cac0946312e1b3 | refs/heads/master | 2020-08-09T08:10:08.888384 | 2019-11-25T01:14:23 | 2019-11-25T01:14:23 | 214,041,532 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 953 | java | package filmmaker;
import producingAim.FissionableCavil;
import disk.*;
public class FilmmakerFinis extends filmmaker.Director {
public disk.FlyerTiedLitany<FissionableCavil> mop;
public static String secondLeap = "pFaFooRgQyhKblxP";
protected synchronized void awardedNewMatter() throws ShelvingWhiteExcluded {
String postSouvenirs = "yaLQKn";
try {
this.actualArtifact = this.latestSafekeeping.upcomingSomething();
} catch (disk.ShelvingWhiteExcluded cma) {
throw cma;
}
}
public FilmmakerFinis(double meanspirited, double rove, Storing preceding) {
demodulating(meanspirited, rove, null, preceding);
this.republic = ProduceGovernmental.fasting;
this.mop = new disk.FlyerTiedLitany<FissionableCavil>();
}
protected synchronized void runActualArtifactEapStore() {
double maximal = 0.8620148655338057;
this.mop.deleteClosing(this.actualArtifact);
this.actualArtifact = null;
}
}
| [
"hayden.cheers@me.com"
] | hayden.cheers@me.com |
35e1ed62cb8a6e3b1051574523de2831288549f2 | 9c6d2de9e85c679c9b9bae0c91f84fae0d410053 | /2015-02/Individual Projects/Grupo 1/Proyecto Instancia 2/Generador/generado/androidApplication/app/src/main/java/co/edu/uniandes/proyectoautomatizacion/widget/CatalogoDetallesFragment.java | 93c0dcd60d8870085c63a39bf6b06e9d879cad44 | [] | no_license | phillipus85/ETLMetricsDataset | 902b526900b8c91889570b15538fa92df0db980f | 7756381f9d580911b1dff9048f3cff002b110b19 | refs/heads/master | 2021-06-21T12:02:38.368652 | 2017-07-12T05:13:21 | 2017-07-12T05:13:21 | 79,398,957 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,986 | java | package co.edu.uniandes.proyectoautomatizacion.widget;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
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.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;
import co.edu.uniandes.proyectoautomatizacion.ApplicationClass;
import co.edu.uniandes.proyectoautomatizacion.R;
import co.edu.uniandes.proyectoautomatizacion.database.CategoriaDb;
import co.edu.uniandes.proyectoautomatizacion.database.DatabaseHelper;
import co.edu.uniandes.proyectoautomatizacion.database.ImagenSliderItemDb;
import co.edu.uniandes.proyectoautomatizacion.database.ProductoDb;
/**
* Created by juandavid on 4/10/15.
*/
public class CatalogoDetallesFragment extends Fragment{
public static final String TAG = CatalogoDetallesFragment.class.getSimpleName();
public static final String CATEGORIAS = "categorias";
public static final String IMAGENES_SLIDE_HOME = "slidingImages";
private ApplicationClass appClass;
private DatabaseHelper dh;
private CategoriaDb catalogo;
private CatalogoDetallesClickListener listener;
private List<ImagenSliderItemDb> imgsdb;
public final static String USUARIO_PREFERENCES = "UsuarioPref";
private SharedPreferences usuarioPref;
private SharedPreferences.Editor usuarioEdit;
public CatalogoDetallesFragment() {
// Required empty public constructor
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.i(TAG, "Attached CatalogoDetallesFragment");
appClass = (ApplicationClass) getActivity().getApplication();
dh = appClass.getDbh();
catalogo = dh.findCategoriaByNombre(((CategoriaDb) getArguments().getSerializable(CATEGORIAS)).getNombre()).get(0);
listener = (CatalogoDetallesClickListener) activity;
System.out.println(catalogo.getNombre() + dh.findProductosByCategoria(catalogo.getId()).size());
//imgsSlider = (ImagenesSlider) getArguments().getSerializable(IMAGENES_SLIDE_HOME);
}
@Override
public void onStop(){
super.onStop();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v;
DisplayMetrics displaymetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int scrHeight = displaymetrics.heightPixels;
int scrWidth = displaymetrics.widthPixels;
Log.i(TAG, "CatalogoDetallesFragment Started!");
//slidingImagesList = Arrays.asList(pictures);
v = inflater.inflate(R.layout.fragment_catalogo_detalles, container, false);
final ViewPager pager = (ViewPager) v.findViewById(R.id.catalogoDetallesViewPager);
Display mDisplay = getActivity().getWindowManager().getDefaultDisplay();
int width = mDisplay.getWidth();
int height = mDisplay.getHeight();
ViewGroup.LayoutParams params = pager.getLayoutParams();
// Changes the height and width to the specified *pixels*
params.height = (int)((width * 1.42) + (height*0.25));
params.width = width;
pager.setLayoutParams(params);
pager.setAdapter(new MyPagerAdapter(getChildFragmentManager()));
return v;
}
private class MyPagerAdapter extends FragmentStatePagerAdapter implements ProductoSliderFragment.OnSliderProductosClickListener {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int pos) {
//return CuponDetalladoFragment.newInstance(mPaseDeta.get(pos));
return ProductoSliderFragment.newInstance(dh.findProductosByCategoria(catalogo.getId()).get(pos), this);
}
@Override
public int getCount() {
return dh.findProductosByCategoria(catalogo.getId()).size();
}
@Override
public void onProductoClickListener(ProductoDb img) {
System.out.println("click producto imagen slider ");
listener.onImagenSlideCatalogoDetallesClick(img);
}
@Override
public void onComprarProductoClickListener(ProductoDb p) {
listener.onComprarProductoClick(p);
}
}
public interface CatalogoDetallesClickListener {
/**
* Called when the view is clicked.
*
*/
public void onImagenSlideCatalogoDetallesClick(ProductoDb img);
public void onComprarProductoClick(ProductoDb p);
}
} | [
"n.bonet2476@uniandes.edu.co"
] | n.bonet2476@uniandes.edu.co |
480bfaf4939794c017c04e2378c1464162544cd7 | e4f6e63b96b5b64e0432e668d19a4c3c24e51101 | /src/com/toplevel/TabsFragmentActivity.java | 4cf8977cb975a35d8940c40bfcd960a88fefdbaf | [] | no_license | tonsV2/TabsFragmentActivity | bdaeb6da265090a4531d16ce4f0236032c399704 | a5cf6b3d92c5cf33cd68005a2068959230891363 | refs/heads/master | 2020-04-06T06:27:53.375947 | 2013-10-22T11:04:53 | 2013-10-22T11:04:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,863 | java | package com.toplevel;
import java.util.ArrayList;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TabHost;
import android.widget.TabWidget;
/* ref: http://developer.android.com/resources/samples/Support4Demos/src/com/example/android/supportv4/app/FragmentTabsPager.html
* TODO: implement horizontal view...
* TODO: hide header, add action bar, change header icon, etc. lots of customizations
*/
public class TabsFragmentActivity extends FragmentActivity
{
private final String TAG = this.getClass().getName();
TabHost mTabHost;
ViewPager mViewPager;
TabsAdapter ta;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
setContentView(R.layout.fragment_tabs_pager);
mTabHost = (TabHost)findViewById(android.R.id.tabhost);
mTabHost.setup();
mViewPager = (ViewPager)findViewById(R.id.pager);
ta = new TabsAdapter(this, mTabHost, mViewPager);
Log.d(TAG, "end onCreate");
}
protected void restoreFromSavedInstanceState(Bundle savedInstanceState)
{
if(savedInstanceState != null)
{
mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
}
}
public void addTab(String id, String label, Class<?> c)
{
ta.addTab(mTabHost.newTabSpec(id).setIndicator(label), c, null);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("tab", mTabHost.getCurrentTabTag());
}
/**
* This is a helper class that implements the management of tabs and all
* details of connecting a ViewPager with associated TabHost. It relies on a
* trick. Normally a tab host has a simple API for supplying a View or
* Intent that each tab will show. This is not sufficient for switching
* between pages. So instead we make the content part of the tab host
* 0dp high (it is not shown) and the TabsAdapter supplies its own dummy
* view to show as the tab content. It listens to changes in tabs, and takes
* care of switch to the correct paged in the ViewPager whenever the selected
* tab changes.
*/
public static class TabsAdapter extends FragmentPagerAdapter
implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
private final Context mContext;
private final TabHost mTabHost;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
static final class TabInfo {
@SuppressWarnings("unused")
private final String tag;
private final Class<?> clss;
private final Bundle args;
TabInfo(String _tag, Class<?> _class, Bundle _args) {
tag = _tag;
clss = _class;
args = _args;
}
}
static class DummyTabFactory implements TabHost.TabContentFactory {
private final Context mContext;
public DummyTabFactory(Context context) {
mContext = context;
}
@Override
public View createTabContent(String tag) {
View v = new View(mContext);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
public TabsAdapter(FragmentActivity activity, TabHost tabHost, ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mTabHost = tabHost;
mViewPager = pager;
mTabHost.setOnTabChangedListener(this);
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) {
tabSpec.setContent(new DummyTabFactory(mContext));
String tag = tabSpec.getTag();
TabInfo info = new TabInfo(tag, clss, args);
mTabs.add(info);
mTabHost.addTab(tabSpec);
notifyDataSetChanged();
}
@Override
public int getCount() {
return mTabs.size();
}
@Override
public Fragment getItem(int position) {
TabInfo info = mTabs.get(position);
return Fragment.instantiate(mContext, info.clss.getName(), info.args);
}
@Override
public void onTabChanged(String tabId) {
int position = mTabHost.getCurrentTab();
mViewPager.setCurrentItem(position);
}
@Override
public void onPageSelected(int position) {
// Unfortunately when TabHost changes the current tab, it kindly
// also takes care of putting focus on it when not in touch mode.
// The jerk.
// This hack tries to prevent this from pulling focus out of our
// ViewPager.
TabWidget widget = mTabHost.getTabWidget();
int oldFocusability = widget.getDescendantFocusability();
widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
mTabHost.setCurrentTab(position);
widget.setDescendantFocusability(oldFocusability);
}
@Override
public void onPageScrollStateChanged(int state) {
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
}
}
| [
"sebastianthegreatful@gmail.com"
] | sebastianthegreatful@gmail.com |
88fb76ddad02a015cbd7d9963cf6c8f76d8601e8 | 7c870f98d607ebce8c983b2acf97bf0a38342715 | /com/google/android/gms/tagmanager/zzch.java | ee9999de48d440e683e6a966bb2d897f185fb1ab | [] | no_license | ioanlongjing/shsh-app | c75b21cc1366badfc3a2ccd483b874b6e43c06a3 | c8672c113e816806bddde52c4ed5b10334d19f1a | refs/heads/master | 2020-03-12T19:48:55.752462 | 2018-04-24T03:20:16 | 2018-04-24T03:20:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 499 | java | package com.google.android.gms.tagmanager;
import com.google.android.gms.internal.zzag;
import com.google.android.gms.internal.zzaj.zza;
import java.util.Map;
class zzch extends zzam {
private static final String ID = zzag.PLATFORM.toString();
private static final zza zzbEZ = zzdm.zzR("Android");
public zzch() {
super(ID, new String[0]);
}
public boolean zzOw() {
return true;
}
public zza zzY(Map<String, zza> map) {
return zzbEZ;
}
}
| [
"song374561@chivincent.net"
] | song374561@chivincent.net |
562775398124adc8c4ceccffaef93501ded9f829 | 4074c95ab41621a3b4b2543ab4d0adfe9ae7dd9d | /test-src/coop/nisc/samples/guava/HomeworkTest.java | c27d7dcaec318f6476ef099b3151aaf90c8bb346 | [] | no_license | emugaas/guava-example | fff065374297442cdeb110017439b04b5ae6ec70 | 6055296b5fb4c89a691ee42045a9d5dcf92e299a | refs/heads/master | 2021-01-22T07:35:33.502886 | 2015-02-18T02:04:15 | 2015-02-18T02:04:15 | 30,892,691 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 640 | java | package coop.nisc.samples.guava;
import com.google.common.collect.Iterables;
import coop.nisc.samples.guava.data.Data;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
public class HomeworkTest {
@Test
public void testGetFullNamesForCustomersWithExactlyOneAccount() throws Exception {
Homework hw = new Homework();
Iterable<String> names = hw.getFullNamesForCustomersWithExactlyOneAccount(Data.getAllCustomers());
assertArrayEquals(
new Object[]{"Haggard, Johana", "Sidle, Cheryll", "Smith, Bob"},
Iterables.toArray(names, Object.class));
}
} | [
"eric.mugaas2@gmail.com"
] | eric.mugaas2@gmail.com |
4d6734f236f4e79ace1eaf604f923bdae66cd9b5 | 7b8fd459b6db85b328063ead75027d0f6e8d353b | /minecraft/net/minecraft/src/TileEntityEnderChestRenderer.java | 1605944d866f8a99c7bba14f39127f0e86f71761 | [] | no_license | Game-Killers/mcclient | 0b659ed664da30bf4c1daa99a170e8f71fe3709f | 975439b9beab880ac978f87d7f847228b44fb3eb | refs/heads/master | 2021-01-18T08:52:13.541841 | 2014-12-20T19:01:46 | 2014-12-20T19:02:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,183 | java | package net.minecraft.src;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
public class TileEntityEnderChestRenderer extends TileEntitySpecialRenderer
{
private static final ResourceLocation field_110637_a = new ResourceLocation("textures/entity/chest/ender.png");
/** The Ender Chest Chest's model. */
private ModelChest theEnderChestModel = new ModelChest();
/**
* Helps to render Ender Chest.
*/
public void renderEnderChest(TileEntityEnderChest par1TileEntityEnderChest, double par2, double par4, double par6, float par8)
{
int var9 = 0;
if (par1TileEntityEnderChest.hasWorldObj())
{
var9 = par1TileEntityEnderChest.getBlockMetadata();
}
this.bindTexture(field_110637_a);
GL11.glPushMatrix();
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glTranslatef((float)par2, (float)par4 + 1.0F, (float)par6 + 1.0F);
GL11.glScalef(1.0F, -1.0F, -1.0F);
GL11.glTranslatef(0.5F, 0.5F, 0.5F);
short var10 = 0;
if (var9 == 2)
{
var10 = 180;
}
if (var9 == 3)
{
var10 = 0;
}
if (var9 == 4)
{
var10 = 90;
}
if (var9 == 5)
{
var10 = -90;
}
GL11.glRotatef((float)var10, 0.0F, 1.0F, 0.0F);
GL11.glTranslatef(-0.5F, -0.5F, -0.5F);
float var11 = par1TileEntityEnderChest.prevLidAngle + (par1TileEntityEnderChest.lidAngle - par1TileEntityEnderChest.prevLidAngle) * par8;
var11 = 1.0F - var11;
var11 = 1.0F - var11 * var11 * var11;
this.theEnderChestModel.chestLid.rotateAngleX = -(var11 * (float)Math.PI / 2.0F);
this.theEnderChestModel.renderAll();
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
GL11.glPopMatrix();
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
}
public void renderTileEntityAt(TileEntity par1TileEntity, double par2, double par4, double par6, float par8)
{
this.renderEnderChest((TileEntityEnderChest)par1TileEntity, par2, par4, par6, par8);
}
}
| [
"d3fault.player@gmail.com"
] | d3fault.player@gmail.com |
f8d723928674d7ea26334bc4c32277415f9a3c46 | 81ab317697ef36d0d3df74f08a4aa8cfdf533a30 | /java/lista1/src/lista1/atividade6.java | a5132acb8612a9c295a2bafdf2363abc78f1af5e | [] | no_license | Kelven14/turma14java | 7cf226cd8f44fa7fde8b411c86b3f0d5e4be0be4 | eb63a51fb89e1ffead063b09b4b1795ee33375c1 | refs/heads/main | 2023-02-02T06:33:31.969105 | 2020-12-18T22:40:19 | 2020-12-18T22:40:19 | 315,411,655 | 1 | 0 | null | null | null | null | WINDOWS-1252 | Java | false | false | 552 | java | package lista1;
import java.util.Scanner;
public class atividade6 {
public static void main(String[] args) {
Scanner leia = new Scanner(System.in);
int A, B,C;
double D,R,S;
System.out.println("Informe o valor de A: ");
A = leia.nextInt();
System.out.println("Informe o valor de B: ");
B = leia.nextInt();
System.out.println("Informe o valor de C: ");
C = leia.nextInt();
R = Math.pow((A+B), 2);
S = Math.pow((B+C), 2);
D = (R + S)/2;
System.out.printf(" D é igual a %.2f",D,".");
leia.close();
}
}
| [
"kelven.cleiton14@gmail.com"
] | kelven.cleiton14@gmail.com |
108d315cfb241e3d7005ca80a25cb1cb4432516b | e4d7fa36e07cdbcb5fcb601c33dd01fbb548c244 | /android/app/src/main/java/versioned/host/exp/exponent/modules/api/components/svg/RNSVGGroupShadowNode.java | 5fe76c33e4b3f849566a8ffc7aebfc4870681720 | [
"CC-BY-4.0",
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | permissive | decebal/exponent | b99ef0c11c23cb363178a1a22372c28c9a3ba446 | fefd95ee052c458b75a3c1a2e5c818ba99070752 | refs/heads/master | 2023-04-08T11:35:38.995397 | 2016-09-08T21:47:25 | 2016-09-08T21:47:45 | 67,743,155 | 0 | 0 | NOASSERTION | 2023-04-04T00:36:21 | 2016-09-08T21:57:11 | JavaScript | UTF-8 | Java | false | false | 4,185 | java | /**
* Copyright (c) 2015-present, Horcrux.
* All rights reserved.
*
* This source code is licensed under the MIT-style license found in the
* LICENSE file in the root directory of this source tree.
*/
package versioned.host.exp.exponent.modules.api.components.svg;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.view.View;
import android.view.ViewGroup;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.uimanager.ReactShadowNode;
import javax.annotation.Nullable;
/**
* Shadow node for virtual RNSVGGroup view
*/
public class RNSVGGroupShadowNode extends RNSVGPathShadowNode {
public void draw(Canvas canvas, Paint paint, float opacity) {
RNSVGSvgViewShadowNode svg = getSvgShadowNode();
if (opacity > MIN_OPACITY_FOR_DRAW) {
int count = saveAndSetupCanvas(canvas);
clip(canvas, paint);
for (int i = 0; i < getChildCount(); i++) {
if (!(getChildAt(i) instanceof RNSVGVirtualNode)) {
continue;
}
RNSVGVirtualNode child = (RNSVGVirtualNode) getChildAt(i);
child.setupDimensions(canvas);
child.mergeProperties(this, mPropList, true);
child.draw(canvas, paint, opacity * mOpacity);
if (child.isResponsible()) {
svg.enableTouchEvents();
}
}
restoreCanvas(canvas, count);
}
}
@Override
protected Path getPath(Canvas canvas, Paint paint) {
Path path = new Path();
for (int i = 0; i < getChildCount(); i++) {
if (!(getChildAt(i) instanceof RNSVGVirtualNode)) {
continue;
}
RNSVGVirtualNode child = (RNSVGVirtualNode) getChildAt(i);
child.setupDimensions(canvas);
path.addPath(child.getPath(canvas, paint));
}
return path;
}
@Override
public int hitTest(Point point, View view, @Nullable Matrix matrix) {
int viewTag = -1;
Matrix combinedMatrix = new Matrix();
if (matrix != null) {
combinedMatrix.postConcat(matrix);
}
combinedMatrix.postConcat(mMatrix);
for (int i = getChildCount() - 1; i >= 0; i--) {
ReactShadowNode child = getChildAt(i);
if (!(child instanceof RNSVGVirtualNode)) {
continue;
}
RNSVGVirtualNode node = (RNSVGVirtualNode) child;
View childView = ((ViewGroup) view).getChildAt(i);
viewTag = node.hitTest(point, childView, combinedMatrix);
if (viewTag != -1) {
return (node.isResponsible() || viewTag != childView.getId()) ? viewTag : view.getId();
}
}
return viewTag;
}
@Override
public int hitTest(Point point, View view) {
return this.hitTest(point, view, null);
}
protected void saveDefinition() {
if (mName != null) {
getSvgShadowNode().defineTemplate(this, mName);
}
for (int i = getChildCount() - 1; i >= 0; i--) {
if (!(getChildAt(i) instanceof RNSVGVirtualNode)) {
continue;
}
((RNSVGVirtualNode) getChildAt(i)).saveDefinition();
}
}
@Override
public void mergeProperties(RNSVGVirtualNode target, ReadableArray mergeList) {
if (mergeList.size() != 0) {
for (int i = getChildCount() - 1; i >= 0; i--) {
if (!(getChildAt(i) instanceof RNSVGVirtualNode)) {
continue;
}
((RNSVGVirtualNode) getChildAt(i)).mergeProperties(target, mergeList);
}
}
}
@Override
public void resetProperties() {
for (int i = getChildCount() - 1; i >= 0; i--) {
if (!(getChildAt(i) instanceof RNSVGVirtualNode)) {
continue;
}
((RNSVGVirtualNode) getChildAt(i)).resetProperties();
}
}
}
| [
"aurora@exp.host"
] | aurora@exp.host |
40f49f9f5061384ade110a99fbafca9d1d858ae6 | 0b2072785f6ac3a295c9d6f1b9d68854b464bacf | /app/src/main/java/com/andrius/fileutilexample/MainActivity.java | d4424e2a46d520ea1f83b119e9d9dce234e908a0 | [] | no_license | anurbanv/FileUtil-Android | 476cbd81cb852f2e1b08ef292c9d41d8667f8ffb | 33778fab5a8f84d39ed2356b9575854743a8cc21 | refs/heads/master | 2020-05-28T06:18:41.261467 | 2019-05-27T20:53:22 | 2019-05-27T20:53:22 | 188,906,284 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 340 | java | package com.andrius.fileutilexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
| [
"UrbanAndrius@users.noreply.github.com"
] | UrbanAndrius@users.noreply.github.com |
41616bf84bf0fe00a8661ae4c596db1a9f1db429 | e406ae28049ade22d2c95797d267ac71a719139e | /app/src/androidTest/java/integracionip/impresoras/ExampleInstrumentedTest.java | 6116e7ca62acfcbd3d9afef79d3f5a17a2cc0c37 | [] | no_license | yosoyafa/CRM-GO-Live | 72d8e62556bb6164742e925914700fef359a2fad | 313877f04aca216a9491a2b1848dd7c71a2d4378 | refs/heads/master | 2020-04-27T18:36:35.655493 | 2019-07-02T06:14:00 | 2019-07-02T06:14:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 732 | java | package integracionip.impresoras;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("integracionip.impresoras", appContext.getPackageName());
}
}
| [
"carlosafanador97@MacBook-Pro-de-Afa.local"
] | carlosafanador97@MacBook-Pro-de-Afa.local |
d72dab0fff5870f06b55277ffacfbd15322639cf | 4ebf08f79e11903a14acb8d8a53e9b6f0f0e8994 | /Pilot/src/com/emitrom/pilot/maps/client/maptypes/MapTypeStyler.java | 2a33af1ebbb5abc4a3068ebcd2b17ec550b37ac7 | [] | no_license | sanyaade-mobiledev/Pilot | a48247328f58bde119646b93e9d7dff713a3f7ad | a385352f241b46f9d273a50a85c8e92e625ee5ba | refs/heads/master | 2021-01-20T21:25:55.533922 | 2013-05-05T00:01:15 | 2013-05-05T00:01:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,476 | java | /**
Copyright (c) 2012 Emitrom LLC. All rights reserved.
For licensing questions, please contact us at licensing@emitrom.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.emitrom.pilot.maps.client.maptypes;
import com.emitrom.pilot.util.client.core.JsObject;
import com.emitrom.pilot.util.client.core.JsoHelper;
/**
* A styler affects how a map's elements will be styled. Each MapTypeStyler
* should contain one and only one key. If more than one key is specified in a
* single MapTypeStyler, all but one will be ignored. For example: var rule =
* {hue: '#ff0000'}.
*
*/
public class MapTypeStyler extends JsObject {
public MapTypeStyler() {
jsObj = JsoHelper.createObject();
}
/**
* Gamma. Modifies the gamma by raising the lightness to the given power.
* Valid values: Floating point numbers, [0.01, 10], with 1.0 representing
* no change.
*
* @param value
*/
public native void setGamma(double value)/*-{
var jso = this.@com.emitrom.pilot.util.client.core.JsObject::getJsObj()();
jso.gamma = value;
}-*/;
public native double getGamma()/*-{
var jso = this.@com.emitrom.pilot.util.client.core.JsObject::getJsObj()();
return jso.gamma;
}-*/;
/**
* Sets the hue of the feature to match the hue of the color supplied. Note
* that the saturation and lightness of the feature is conserved, which
* means that the feature will not match the color supplied exactly. Valid
* values: An RGB hex string, i.e. '#ff0000'.
*
* @param value
*/
public native void setHue(String value)/*-{
var jso = this.@com.emitrom.pilot.util.client.core.JsObject::getJsObj()();
jso.hue = value;
}-*/;
public native String getHue()/*-{
var jso = this.@com.emitrom.pilot.util.client.core.JsObject::getJsObj()();
return jso.hue;
}-*/;
/**
* Inverts lightness. A value of true will invert the lightness of the
* feature while preserving the hue and saturation.
*
* @param value
*/
public native void setInvertLightness(boolean value)/*-{
var jso = this.@com.emitrom.pilot.util.client.core.JsObject::getJsObj()();
jso.invert_lightness = value;
}-*/;
public native boolean invertLightness()/*-{
var jso = this.@com.emitrom.pilot.util.client.core.JsObject::getJsObj()();
return jso.invert_lightness;
}-*/;
/**
* Lightness. Shifts lightness of colors by a percentage of the original
* value if decreasing and a percentage of the remaining value if
* increasing. Valid values: [-100, 100].
*
* @param value
*/
public native void setLightness(double value)/*-{
var jso = this.@com.emitrom.pilot.util.client.core.JsObject::getJsObj()();
jso.lightness = value;
}-*/;
public native double getLightness()/*-{
var jso = this.@com.emitrom.pilot.util.client.core.JsObject::getJsObj()();
return jso.lightness;
}-*/;
/**
* Saturation. Shifts the saturation of colors by a percentage of the
* original value if decreasing and a percentage of the remaining value if
* increasing. Valid values: [-100, 100].
*
* @param value
*/
public native void setSaturation(double value)/*-{
var jso = this.@com.emitrom.pilot.util.client.core.JsObject::getJsObj()();
jso.saturation = value;
}-*/;
public native double getSaturation()/*-{
var jso = this.@com.emitrom.pilot.util.client.core.JsObject::getJsObj()();
return jso.saturation;
}-*/;
/**
* Visibility: Valid values: 'on', 'off' or 'simplified'.
*
* @param value
*/
public native void setVisibility(String value)/*-{
var jso = this.@com.emitrom.pilot.util.client.core.JsObject::getJsObj()();
jso.visibility = value;
}-*/;
public native String getVisibility()/*-{
var jso = this.@com.emitrom.pilot.util.client.core.JsObject::getJsObj()();
return jso.visibility;
}-*/;
}
| [
"jazzmatadazz@gmail.com"
] | jazzmatadazz@gmail.com |
0eeb690f9c68e2c86cf7bf602a8d47607bf6d310 | a3211b4da9beae2267f7e68d8a9cbe8600521af4 | /src/main/java/com/verispjdbcprg/verispjdbc/VerispjdbcApplication.java | ba1e2d683f5e45d533c8125027e988469e9aef3c | [] | no_license | abhijeetvc/verispjdbc | f8d9e10f01a050cd3b22c54bcd41789da1485b79 | fdaa8cb527c2d5083154b88456b9b539104cc2f1 | refs/heads/master | 2023-02-07T15:06:41.154815 | 2020-12-17T06:57:34 | 2020-12-17T06:57:34 | 321,895,620 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 329 | java | package com.verispjdbcprg.verispjdbc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class VerispjdbcApplication {
public static void main(String[] args) {
SpringApplication.run(VerispjdbcApplication.class, args);
}
}
| [
"abhijeetvc7@gmail.com"
] | abhijeetvc7@gmail.com |
0948d5ea22297ab424ea5b4540a4d1c28521713f | 14188d585cf51cbae72823bb41fcd910c76e8f8a | /src/main/java/com/sn/abs/exception/LoginException.java | fbea213309bdfd69b4e1d198b54c8eb14b55a411 | [] | no_license | yalexz/abs-webapp | 6d63d11678c21174723b1694589bab86fd479898 | 73daf0e5a9328760817b500a44add60d775287c1 | refs/heads/master | 2021-01-17T15:26:38.993690 | 2016-09-28T09:48:22 | 2016-09-28T09:48:22 | 69,449,126 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 511 | java | package com.sn.abs.exception;
/**
* 登录异常
* @author yangzhi
*/
public class LoginException extends RuntimeException {
private String message;
private static final long serialVersionUID = 1L;
public LoginException() {
super();
}
public LoginException(String message, Exception e) {
super(message, e);
this.message = message;
}
public LoginException(String message) {
super(message);
this.message = message;
}
@Override
public String getMessage() {
return this.message;
}
}
| [
"zhi.yang@qunar.com"
] | zhi.yang@qunar.com |
3a2c8afa1eb92aa3c5c21c502bf4e952831d46e1 | a68fcf7bad70e91af4b398df8bee04b9b0bda82e | /S15_S17_phylogenetic_inference/scripts/resources/statistical_binning/graphColoring/code/Constants.java | e8d94e179129d75a938e2d3468ce291585487435 | [] | no_license | hj1994412/teleost_genomes_immune | 44aac06190125b4dea9533823b33e28fc34d6b67 | 50f1552ebb5f19703b388ba7d5517a3ba800c872 | refs/heads/master | 2021-03-06T18:24:10.316076 | 2016-08-27T10:58:39 | 2016-08-27T10:58:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,797 | java |
/**
* Constants.
*
* @author Shalin Shah
* Email: shah.shalin@gmail.com
*/
public class Constants {
public static int NUMBER_NODES; // populated by GraphReader.readGraph()
/*
* The file from which the graph has to be read.
* The format is specified by the following URL:
* http://www.nlsde.buaa.edu.cn/~kexu/benchmarks/graph-benchmarks.htm
*/
public static final String FILE = "/dev/stdin";
/* The number of iterations */
public static final int ANNEALING_ITERATIONS = 2000;
/* Uncolored Vertex Value */
public static final int UNCOLORED = -1;
/* Time to spend on one k */
public static final long TIME = 1000;
/* If optimal coloring is known this field can be populated. This will
* significantly reduce the duration for which the algorithm runs.
*
* If you populate this field, make sure that you increase the TIME constant to
* a higher value so that it would try its best to find the KNOWN_K coloring
*/
public static final int KNOWN_K = 0;
/* Constants for random restart for MaxClique */
public static final int TOLERANCE = 250;
/* Maximum iterations to spend on finding a unique random restart */
public static final int MAX_UNIQUE_ITERATIONS = 100;
// iterated greedy
public static final int ITERATIONS = 1000;
public static final double DECREASING = 0.1;
public static final double REVERSE = 0.05;
public static final double INCREASING = 0.8;
public static final double RANDOM = 0.05;
// local search
public static final int LOCAL_SEARCH_ITERATIONS = 10000;
public static final long LOCAL_SEARCH_MAX_TIME = 20000; // milliseconds
}
| [
"lex.nederbragt@ibv.uio.no"
] | lex.nederbragt@ibv.uio.no |
fd20990a7460e2ad2b0f6b57f2d4de046e403e87 | 999cf6f680b8cd34145183edfa5a00b4bafe94d5 | /runtime-api/src/main/java/com/reedelk/runtime/api/annotation/Description.java | 0eb55f78ad69c34399061fcca93fdc361599766e | [
"Apache-2.0"
] | permissive | awesomeDataTool/reedelk-runtime | 987e0d61db32059b6811cbc8822d58b72f53bdd5 | 88177e4f0c046b46ae872cfdb37c9f0cc5fc2d29 | refs/heads/master | 2023-02-04T08:03:28.919692 | 2020-10-06T09:39:06 | 2020-10-06T09:39:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 344 | java | package com.reedelk.runtime.api.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.TYPE})
public @interface Description {
String value();
}
| [
"lorenzo@lorenzo.info.com"
] | lorenzo@lorenzo.info.com |
0212a757753dac75e821dd465d6c93e40c527e09 | a5276a6ea997e1d92df43a83c72031c3fd1d4ac9 | /SjTest/src/java_181108/Car1.java | 98e4984f84e2c14a1f0795cc6765ff811274da76 | [] | no_license | hoooof0304/sangJin | 4a92f5b53f9ac7258df004547b2bead9d54c0064 | cc4b883bbcc9a982fc26814889a443cc3aa9a5b6 | refs/heads/master | 2020-04-05T06:51:26.908737 | 2018-11-15T07:30:52 | 2018-11-15T07:30:52 | 156,653,901 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 257 | java | package java_181108;
public class Car1 {
//생성자 연습.
//생성자의 이름은 클래스와 동일
//기본 생성자
Car1(){
}
//color와 cc를 매개변수로 갖는 생성자
Car1(String color, int cc){
}
}
| [
"zerock@Yongcom0078-PC"
] | zerock@Yongcom0078-PC |
f2d15e7a00bfa825039f951269a490ef8f4bc057 | cc83d947649ec7bb9a502a3bc7293b6b875e5278 | /CodeSmellAnalyzer/src/it/unisa/codeSmellAnalyzer/testSmellDetector/MysteryGuest.java | 1fcf667c272adc3ace6bb68544d536f6a052fd47 | [] | no_license | Gcatolino/CodeSmellAnalyzer | 13daa9e0289c5e94e1a4462dfab8e6d92085d3d4 | 385fc9c7e2fa510bd1320b04e78a3995674ec5da | refs/heads/master | 2023-04-11T06:35:35.051810 | 2021-04-21T20:02:27 | 2021-04-21T20:02:27 | 72,425,861 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 844 | java | package it.unisa.codeSmellAnalyzer.testSmellDetector;
import it.unisa.codeSmellAnalyzer.beans.ClassBean;
import it.unisa.codeSmellAnalyzer.beans.MethodBean;
public class MysteryGuest {
public boolean isMysteryGuest(ClassBean pClassBean) {
boolean mysteryGuest = false;
for (MethodBean mb : pClassBean.getMethods()) {
String body = mb.getTextContent();
if (!mysteryGuest){
if (body.contains(" File ") || body.contains(" File(") || body.contains("db")){
mysteryGuest = true;
}
}
}
return mysteryGuest;
}
public boolean isMysteryGuest(MethodBean pMethodBean) {
boolean mysteryGuest = false;
String body = pMethodBean.getTextContent();
if (!mysteryGuest){
if (body.contains(" File ") || body.contains(" File(") || body.contains("db")){
mysteryGuest = true;
}
}
return mysteryGuest;
}
} | [
"fabio.palomba.89@gmail.com"
] | fabio.palomba.89@gmail.com |
214e45cdb9dff6e59092274fa7f7df99837d1306 | 48f172fd7a678a4bc5eed63fc9467673b363a6dd | /src/test/java/POM/OnTheGo_AndroidProject/Logintodetails.java | 687a8eb850d775ec265f8367b346863ec16614ed | [] | no_license | Vineshsoft/OntheGo | d8aa62eec9740809d6a0cde78d2078ca0bab4a98 | cc0f6352bfc53f05da18f45a3bd1a4cd9bf04130 | refs/heads/master | 2020-04-10T00:00:18.043382 | 2018-12-19T09:10:49 | 2018-12-19T09:10:49 | 160,673,221 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,377 | java | package POM.OnTheGo_AndroidProject;
import java.util.Base64;
import org.apache.log4j.PropertyConfigurator;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.PageFactory;
import Generic.OnTheGo_AndroidProject.Base_page;
import Generic.OnTheGo_AndroidProject.Base_test;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.pagefactory.AndroidFindBy;
import io.appium.java_client.pagefactory.AppiumFieldDecorator;
public class Logintodetails extends Base_page {
public Logintodetails(AppiumDriver<MobileElement> driver) {
super();
Base_test.driver1 = driver;
PageFactory.initElements(new AppiumFieldDecorator(driver), this);
PropertyConfigurator.configure("Log4j.properties");
}
@AndroidFindBy(xpath= "//android.widget.EditText[@text='Email']")
private WebElement email;
@AndroidFindBy(xpath= "//android.widget.EditText[@index='3']")
private WebElement email1;
@AndroidFindBy(xpath= "//android.widget.EditText[@text='Password']")
private WebElement password;
@AndroidFindBy(xpath= "//android.widget.EditText[@index='6']")
private WebElement password1;
@AndroidFindBy(xpath= "//android.view.ViewGroup[@index='10']")
private WebElement loginbtn;
@AndroidFindBy(xpath= "//android.widget.TextView[@text='Please check your username and password']")
private WebElement inputError;
@AndroidFindBy(xpath= "//android.view.ViewGroup[@index='3']")
private WebElement clickok;
public void emailtxtbox(String emailaddress) throws InterruptedException
{
email.clear();
email1.sendKeys(emailaddress);
Base_test.Log.info("Email id provided as "+ emailaddress);
Base_test.Log.debug(emailaddress);
}
public void passwordtxtbox(String pass)
{
password.clear();
password1.sendKeys(pass);
byte[] encryptedPassword = Base64.getEncoder().encode(pass.getBytes());
Base_test.Log.info("Encrypted Password provided as "+ new String(encryptedPassword));
Base_test.Log.debug(encryptedPassword);
}
public void loginbutton()
{
loginbtn.click();
Base_test.Log.info("Tapped on login button");
}
public boolean validateLoginpage()
{
boolean elements = false;
if(this.email.isDisplayed())
{
if(this.password.isDisplayed())
{
if(this.loginbtn.isDisplayed())
{
elements = true;
}
}
}
else
{
elements = false;
}
return elements;
}
public boolean testLoginWithoutCredentials() {
boolean loginStatus = false;
this.loginbtn.click();
if (this.inputError.getText().equalsIgnoreCase("Please check your username and password"))
{
loginStatus = true;
}
clickok.click();
return loginStatus;
}
}
//@FindBy(xpath="//android.widget.Button[@text='LOGIN']")
/*public Logintodetails(AndroidDriver<MobileElement> driver)
{
PageFactory.initElements(driver,this);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
waitForPresence(driver, 20 ,email);
textbox(password, driver);
button(loginbtn, driver);
}*/ | [
"vinesh.c@BRILAP800.BRILLIO.COM"
] | vinesh.c@BRILAP800.BRILLIO.COM |
f92477df76919a93373a526544f9bdc7d7dd5372 | 0a1ebb057ceba59f4786812e1d96f075809b59f5 | /src/test/java/com/doctor/esper/reference/Chapter5EPLReferenceClausesTest.java | bbf1df8d0c2e9b69133dd5b827e96f115d628289 | [
"Apache-2.0"
] | permissive | XiaoqingWang/esper-2015 | 0406c23b372fe41885f15989e608080f643497c0 | bf6db6229cb5493174345d8b681a46ea36f12442 | refs/heads/master | 2021-01-17T20:06:15.366512 | 2015-08-06T16:16:08 | 2015-08-06T16:16:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 196 | java | package com.doctor.esper.reference;
/**
* Chapter 5. EPL Reference: Clauses
*
* @author doctor
*
* @time 2015年6月2日 下午4:52:39
*/
public class Chapter5EPLReferenceClausesTest {
}
| [
"sdcuike@users.noreply.github.com"
] | sdcuike@users.noreply.github.com |
0579d368e6c02c8df6d43be0506d32b93f566585 | 1a4bd510bf4f5760552614b1284494c969eb5934 | /src/main/java/cz/spring/boot/start/start/StartApplication.java | b78493023063ab2e75bbe6969fd52c9f77afec6b | [] | no_license | AlexGitStudy/TestProjectSpringBootH2 | e59e381e21e5e59e36dbe41d44838b4a69753cad | 086c24fba107011e83fb1636a9de2dacadd2bf5d | refs/heads/master | 2021-05-07T19:52:25.191208 | 2017-10-30T21:28:42 | 2017-10-30T21:28:42 | 108,910,506 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 316 | java | package cz.spring.boot.start.start;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class StartApplication {
public static void main(String[] args) {
SpringApplication.run(StartApplication.class, args);
}
}
| [
"mironov@datalite.cz"
] | mironov@datalite.cz |
6ad2c80a7648cad8e3b6dbe18a45494d22941458 | 5e781132c0244d11b5da044172b27fd986fdc062 | /src/IncreaseSalary.java | c2a9bb7260174eb8efe9e57e440faae6e3a14a9e | [] | no_license | yinglung174/employee_record_system | 2f1dceb48424dd915e77ba39f122cd1a2244ddc5 | 45d171a6ae3a0e704fe7536c82a3683f24467d0e | refs/heads/master | 2022-09-18T21:58:34.418768 | 2020-05-29T04:23:39 | 2020-05-29T04:23:39 | 267,762,021 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,898 | java | /* Name: Ng Ying Lung
No.: 150130141
Class: IT114103/1C
Program: IncreaseSalary
*/
public class IncreaseSalary {
public static void main(String args[]){
//define three employees attributes
Employee emp[] = new Employee[3];
String output = "";
emp[0] = new Manager("M000003","CHIU Shun Kin",33,"Male","95515368",
"HR Manager","Room B,27/F,234 Chu Wing Street,Hung Hom,Kowloon",
115000,5750,11500,11500);
emp[1] = new GeneralStaff("G000001","AU Chi Shing",22,"Male","NA","Engineer",
"Flat A,15/F,332 Mei Yi Street,Kowloon Tong,Kowloon",50000,2500,5000);
emp[2] = new Manager("M000001","CHUNG Man Han",55,"Male","98340485","General Manager",
"Room D,16/F,37 Mei Yi Street,Kowloon Tong,Kowloon",150000,7500,15000,15000);
//increase the salary for all employees
for(int d = 0; d < emp.length; d++){
emp[d].increaseSalary(1.1);
}
System.out.println("The sample records of the employees are shown below:");
//output the employees data after increase of salary
for(int i = 0; i < emp.length; i++) {
if (emp[i].getStaffID().startsWith("M")) {
System.out.println(" sample record "+ (i+1)+ ":"+ emp[i].getStaffID()+","+emp[i].getName()+","+emp[i].getAge()+","+emp[i].getGender()+","+emp[i].getMobileNo()+
","+ emp[i].getPost()+","+emp[i].getAddress()+","+emp[i].getSalary()+","+emp[i].getMpf() +","+ ((Manager)emp[i]).getHouseAllow() +","+ ((Manager)emp[i]).getTravelAllow()+"\n");
}
else {
System.out.println(" sample record "+ (i+1)+ ":"+ emp[i].getStaffID()+","+emp[i].getName()+","+emp[i].getAge()+","+emp[i].getGender()+","+emp[i].getMobileNo()+
","+ emp[i].getPost()+","+emp[i].getAddress()+","+emp[i].getSalary()+","+emp[i].getMpf() +","+((GeneralStaff)emp[i]).getBonus()+"\n");
}
}
}
} | [
"michaelng195@gmail.com"
] | michaelng195@gmail.com |
afb24926787d7dbce4482db377af373db1603b62 | ade7d59f41b10f591abfacac296fc3af4a5cf444 | /Online Development Part Verification System/CODE/src/com/track/project/action/SubmitReportByTlToAdmin.java | 4b7387df8e64f085c911eeeb05d99f43fc696821 | [
"MIT"
] | permissive | raghuinmar/automation | 9738b5496dd1e6434d8b24a0b503de6c197d0581 | e5adc1c688535dc16a7c327ae7b61dc5a99e0134 | refs/heads/master | 2020-04-22T23:14:17.291446 | 2019-08-10T20:01:11 | 2019-08-10T20:01:11 | 170,734,079 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,196 | java | package com.track.project.action;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.track.project.dao.ReportDao;
public class SubmitReportByTlToAdmin extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String target="";
boolean flag;
int tid;
try{
tid=Integer.parseInt(request.getParameter("tid"));
System.out.println("tlid in action is......."+tid);
flag= new ReportDao().submitReportToAdminByTl(tid);
if(flag==true)
target="ViewReportonPartiDate.jsp?status=ReportSubmitedSucessfully";
else
target="ViewReportonPartiDate.jsp";
RequestDispatcher rd=request.getRequestDispatcher(target);
rd.forward(request, response);
}
catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
}
}
| [
"raghusharmas8@gmail.com"
] | raghusharmas8@gmail.com |
5b98e53b6df8598a891066f57c54b2548b7b9be6 | 005712c065dcb71be2f5dc19fb9b4269822931c5 | /src/main/java/com/donghyeon/designpattern/bridge/BridgePatternTest.java | b026248b5415ba42762d7d20d35a8de05bc91749 | [] | no_license | DaeAkin/java-design-pattern | 4f3547a522efe1365ca7a6a790667b26962d4901 | e0878e14e7a1432e911fcc7ded397947c14992c0 | refs/heads/master | 2020-12-27T15:09:09.863941 | 2020-07-04T01:40:43 | 2020-07-04T01:40:43 | 237,947,437 | 8 | 0 | null | null | null | null | UTF-8 | Java | false | false | 288 | java | package com.donghyeon.designpattern.bridge;
public class BridgePatternTest {
public static void main(String[] args) {
Shape tri = new Triangle(new RedColor());
tri.applyColor();
Shape pent = new Pentagon(new GreenColor());
pent.applyColor();
}
}
| [
"mindonghyeon890@gmail.com"
] | mindonghyeon890@gmail.com |
3e585d638a73a97bceac812ea0e3316581bc5e0f | 4ffb73a2d90908bd950c0e2b4c7026395007b32a | /src/com/chess/engine/board/BoardUtils.java | f4f90b3f1fc46a3c21cfeb2ad210eface04f514e | [] | no_license | TrashPanda94/BattleChess | 2b00c9433a84a09c12ca34d1629bea4578af6a18 | 919df516021faa4d0291489747cb6acfb329d050 | refs/heads/master | 2020-07-26T16:02:44.847301 | 2019-11-12T03:44:06 | 2019-11-12T03:44:06 | 208,697,977 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 518 | java | package com.chess.engine.board;
public class BoardUtils {
public static final boolean[] FIRST_COLUMN = null;
public static final boolean[] SECOND_COLUMN = null;
public static final boolean[] SEVENTH_COLUMN = null;
public static final boolean[] EIGHTH_COLUMN = null;
private BoardUtils() {
throw new RuntimeException("BoardUtils shouldn't be instantiated!");
}
public static boolean isValidTileCoordinate(int coordinate) {
return coordinate>=0 && coordinate <64;
}
}
| [
"31078941+TrashPanda94@users.noreply.github.com"
] | 31078941+TrashPanda94@users.noreply.github.com |
44293664249d2f9ba3b532e17c6c4a592469e3ce | af62c80faba96302a2b89fb0bbf9c882a88e542d | /src/main/java/de/pandadoxo/dox_varo/api/gui/Buttons/SwitchButton.java | a577445ee84c939c493edfad27944635a6a27b49 | [] | no_license | Pandadoxo/Dox_Varo | 56a936ff52ae46dcc19f6a027fae3d141fa88f91 | 530c930bd383c1721b4343ae0a098b3c886b4d55 | refs/heads/master | 2023-03-21T05:28:09.534382 | 2021-03-16T11:16:10 | 2021-03-16T11:16:10 | 348,318,927 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,579 | java | package de.pandadoxo.dox_varo.api.gui.Buttons;
import de.pandadoxo.dox_varo.Main;
import de.pandadoxo.dox_varo.api.gui.Listener.ButtonPressedListener;
import de.pandadoxo.dox_varo.api.gui.Menu.GuiItem;
import de.pandadoxo.dox_varo.api.gui.Menu.GuiMenu;
import org.bukkit.Bukkit;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
public class SwitchButton extends Button {
private Listener listener;
private GuiMenu menu;
private int slot;
private GuiItem iconOn;
private GuiItem iconOff;
private boolean active;
private ButtonPressedListener buttonPressedListener;
public SwitchButton(GuiItem iconOn, GuiItem iconOff, GuiMenu menu, int slot,
ButtonPressedListener buttonPressedListener) {
super(menu, slot);
this.iconOn = iconOn;
this.iconOff = iconOff;
this.menu = menu;
this.slot = slot;
this.buttonPressedListener = buttonPressedListener;
if (active)
menu.getInventory().setItem(slot, iconOn.getItem());
else
menu.getInventory().setItem(slot, iconOff.getItem());
Listener listener = new Listener() {
@EventHandler
public void onInventoryClick(InventoryClickEvent e) {
if (getMenu() == null)
return;
if (!e.getInventory().equals(getMenu().getInventory())) {
destroy();
return;
}
if (e.getSlot() != getSlot())
return;
if (!(e.getWhoClicked() instanceof Player))
return;
e.setCancelled(true);
setActive(!active);
((Player) e.getWhoClicked()).playSound(e.getWhoClicked().getLocation(), Sound.CHEST_CLOSE, 1, 2);
getButtonPressedListener().onPressed(e.getClick(), menu, getIconOn(), getIconOff(), getSlot(), active);
return;
}
};
Bukkit.getPluginManager().registerEvents(listener, Main.getInstance());
}
public GuiMenu getMenu() {
return menu;
}
public void setMenu(GuiMenu menu) {
this.menu = menu;
}
public int getSlot() {
return slot;
}
public void setSlot(int slot) {
this.slot = slot;
}
public GuiItem getIconOn() {
return iconOn;
}
public void setIconOn(GuiItem iconOn) {
this.iconOn = iconOn;
}
public GuiItem getIconOff() {
return iconOff;
}
public void setIconOff(GuiItem iconOff) {
this.iconOff = iconOff;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
if (active) menu.getInventory().setItem(slot, iconOn.getItem());
else menu.getInventory().setItem(slot, iconOff.getItem());
this.active = active;
}
public ButtonPressedListener getButtonPressedListener() {
return buttonPressedListener;
}
public void setButtonPressedListener(ButtonPressedListener buttonPressedListener) {
this.buttonPressedListener = buttonPressedListener;
}
public void destroy() {
HandlerList.unregisterAll(listener);
iconOn = null;
iconOff = null;
menu = null;
slot = -1;
buttonPressedListener = null;
listener = null;
}
}
| [
"unconfigured@null.spigotmc.org"
] | unconfigured@null.spigotmc.org |
17d779d4d1f10b5a08e0ff2f023ea7266bd593b2 | 3a7cf8e94d640a2e1c861696b6426aeb72b61ad0 | /app/src/main/java/spriu/com/spriuv1/LoginActivity.java | 2aea8c32f7b056da0219ef0dd81c7a7ef81ade6c | [] | no_license | como-quesito/spriuv1 | 37b7c120eab68d4e3ee29eb8ddcdbdb774406ba4 | 7dc273ac72ebaefa71cb924f4ffbee1a8f3e8180 | refs/heads/master | 2021-01-10T13:09:01.432913 | 2016-04-07T18:29:03 | 2016-04-07T18:29:03 | 55,718,057 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,241 | java | package spriu.com.spriuv1;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import static android.Manifest.permission.READ_CONTACTS;
/**
* A login screen that offers login via email/password.
*/
public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor> {
/**
* Id to identity READ_CONTACTS permission request.
*/
private static final int REQUEST_READ_CONTACTS = 0;
/**
* A dummy authentication store containing known user names and passwords.
* TODO: remove after connecting to a real authentication system.
*/
private static final String[] DUMMY_CREDENTIALS = new String[]{
"foo@example.com:hello", "bar@example.com:world"
};
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
// UI references.
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Set up the login form.
mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
populateAutoComplete();
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
}
private void populateAutoComplete() {
if (!mayRequestContacts()) {
return;
}
getLoaderManager().initLoader(0, null, this);
}
private boolean mayRequestContacts() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
return true;
}
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
.setAction(android.R.string.ok, new View.OnClickListener() {
@Override
@TargetApi(Build.VERSION_CODES.M)
public void onClick(View v) {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
});
} else {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
return false;
}
/**
* Callback received when a permissions request has been completed.
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == REQUEST_READ_CONTACTS) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
populateAutoComplete();
}
}
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
private void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mEmailView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String email = mEmailView.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
} else if (!isEmailValid(email)) {
mEmailView.setError(getString(R.string.error_invalid_email));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgress(true);
mAuthTask = new UserLoginTask(email, password);
mAuthTask.execute((Void) null);
}
}
private boolean isEmailValid(String email) {
//TODO: Replace this with your own logic
return email.contains("@");
}
private boolean isPasswordValid(String password) {
//TODO: Replace this with your own logic
return password.length() > 4;
}
/**
* Shows the progress UI and hides the login form.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE +
" = ?", new String[]{ContactsContract.CommonDataKinds.Email
.CONTENT_ITEM_TYPE},
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
List<String> emails = new ArrayList<>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
emails.add(cursor.getString(ProfileQuery.ADDRESS));
cursor.moveToNext();
}
addEmailsToAutoComplete(emails);
}
@Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
//Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
ArrayAdapter<String> adapter =
new ArrayAdapter<>(LoginActivity.this,
android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
mEmailView.setAdapter(adapter);
}
private interface ProfileQuery {
String[] PROJECTION = {
ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
};
int ADDRESS = 0;
int IS_PRIMARY = 1;
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private final String mEmail;
private final String mPassword;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
@Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
try {
// Simulate network access.
Thread.sleep(2000);
} catch (InterruptedException e) {
return false;
}
for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mEmail)) {
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword);
}
}
// TODO: register the new account here.
return true;
}
@Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
finish();
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
@Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
}
| [
"rapidclimate@outlook.com"
] | rapidclimate@outlook.com |
dfe0fa1897dc3b0c11111a3afd14c0395a0ccd39 | 66a5ba8adb5a592f7bc3303f4b3ffc84b09fde5a | /domain/src/main/java/com/example/interactor/program/GetProgramFromId.java | 51e5aad1630a149fa0959a6c58efac7cde56538d | [] | no_license | Tboy70/GuitarTraining | 212272de3c544bc0ec7bd35567a8c65db04d3610 | 4bae76793e3c43c27efafe947526ff566be3508e | refs/heads/master | 2021-01-19T14:11:07.240913 | 2018-04-29T20:41:55 | 2018-04-29T20:41:55 | 84,665,606 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,058 | java | package com.example.interactor.program;
import com.example.executor.PostExecutionThread;
import com.example.executor.ThreadExecutor;
import com.example.interactor.UseCase;
import com.example.repository.ProgramRepository;
import javax.inject.Inject;
import rx.Observable;
public class GetProgramFromId extends UseCase<GetProgramFromId.Params> {
private ProgramRepository programRepository;
@Inject
public GetProgramFromId(ThreadExecutor io, PostExecutionThread scheduler, ProgramRepository programRepository) {
super(io, scheduler);
this.programRepository = programRepository;
}
@Override
public Observable buildUseCaseObservable(Params params) {
return programRepository.getProgramFromId(params.idProgram);
}
public static final class Params {
private final String idProgram;
private Params(String idProgram) {
this.idProgram = idProgram;
}
public static Params toGet(String idProgram) {
return new Params(idProgram);
}
}
}
| [
"thomas.boy@orange.fr"
] | thomas.boy@orange.fr |
f443138eac5cf2cbfc5c0667a56bb1216c3ce1a0 | c59ff0752e1aa1bd176c824f10d6fb1a06677ac9 | /src/test/java/com/custom/orm/test/JdbcTest.java | 3e07674ebb7073680449b0c039f4c8576d8348d3 | [] | no_license | wanghlGitHub/custom-orm | 70277e6ca5f2c0a90aec32ab217ca1ac06cbcef6 | de1c0146eea574355656bc50aa049a44ea3dc080 | refs/heads/master | 2022-12-23T21:04:15.020215 | 2020-02-18T10:59:16 | 2020-02-18T10:59:16 | 241,338,815 | 0 | 0 | null | 2022-12-16T04:25:52 | 2020-02-18T10:59:11 | Java | UTF-8 | Java | false | false | 6,667 | java | package com.custom.orm.test;
import com.custom.orm.demo.entity.Member;
import javax.persistence.Column;
import javax.persistence.Table;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;
/**
* Created by Tom on 2019/4/20.
*/
public class JdbcTest {
public static void main(String[] args) {
Member condition = new Member();
condition.setName("Tom");
condition.setAge(19);
List<?> result = select(condition);
System.out.println(Arrays.toString(result.toArray()));
}
private static List<?> select(Object condition) {
List<Object> result = new ArrayList<>();
Class<?> entityClass = condition.getClass();
Connection con = null;
PreparedStatement pstm = null;
ResultSet rs = null;
try {
//1、加载驱动类
Class.forName("com.mysql.jdbc.Driver");
//2、建立连接
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/gp-vip-spring-db-demo?characterEncoding=UTF-8&rewriteBatchedStatements=true", "root", "123456");
//根据类名找属性名
Map<String, String> columnMapper = new HashMap<String, String>();
//根据属性名找字段名
Map<String, String> fieldMapper = new HashMap<String, String>();
Field[] fields = entityClass.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
String fieldName = field.getName();
if (field.isAnnotationPresent(Column.class)) {
Column column = field.getAnnotation(Column.class);
String columnName = column.name();
columnMapper.put(columnName, fieldName);
fieldMapper.put(fieldName, columnName);
} else {
//默认就是字段名属性名一致
columnMapper.put(fieldName, fieldName);
fieldMapper.put(fieldName, fieldName);
}
}
//3、创建语句集
Table table = entityClass.getAnnotation(Table.class);
String sql = "select * from " + table.name();
StringBuffer where = new StringBuffer(" where 1=1 ");
for (Field field : fields) {
Object value = field.get(condition);
if (null != value) {
if (String.class == field.getType()) {
where.append(" and " + fieldMapper.get(field.getName()) + " = '" + value + "'");
} else {
where.append(" and " + fieldMapper.get(field.getName()) + " = " + value + "");
}
//其他的,在这里就不一一列举,下半截我们手写ORM框架会完善
}
}
System.out.println(sql + where.toString());
pstm = con.prepareStatement(sql + where.toString());
//4、执行语句集
rs = pstm.executeQuery();
//元数据?
//保存了处理真正数值以外的所有的附加信息
int columnCounts = rs.getMetaData().getColumnCount();
while (rs.next()) {
Object instance = entityClass.newInstance();
for (int i = 1; i <= columnCounts; i++) {
//实体类 属性名,对应数据库表的字段名
//可以通过反射机制拿到实体类的说有的字段
//从rs中取得当前这个游标下的类名
String columnName = rs.getMetaData().getColumnName(i);
//有可能是私有的
Field field = entityClass.getDeclaredField(columnMapper.get(columnName));
field.setAccessible(true);
field.set(instance, rs.getObject(columnName));
}
result.add(instance);
}
//5、获取结果集
} catch (Exception e) {
e.printStackTrace();
}
//6、关闭结果集、关闭语句集、关闭连接
finally {
try {
rs.close();
pstm.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
// private static List<Member> select(String sql) {
// List<Member> result = new ArrayList<>();
// Connection con = null;
// PreparedStatement pstm = null;
// ResultSet rs = null;
// try {
// //1、加载驱动类
// Class.forName("com.mysql.jdbc.Driver");
// //2、建立连接
// con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/gp-vip-spring-db-demo","root","123456");
// //3、创建语句集
// pstm = con.prepareStatement(sql);
// //4、执行语句集
// rs = pstm.executeQuery();
// while (rs.next()){
// Member instance = new Member();
// instance.setId(rs.getLong("id"));
// instance.setName(rs.getString("name"));
// instance.setAge(rs.getInt("age"));
// instance.setAddr(rs.getString("addr"));
// result.add(instance);
// }
// //5、获取结果集
// }catch (Exception e){
// e.printStackTrace();
// }
// //6、关闭结果集、关闭语句集、关闭连接
// finally {
// try {
// rs.close();
// pstm.close();
// con.close();
// }catch (Exception e){
// e.printStackTrace();
// }
// }
// return result;
// }
// private static List<Member> select(String sql) {
// List<Member> result = new ArrayList<>();
// Connection con = null;
// PreparedStatement pstm = null;
// ResultSet rs = null;
// try {
// //1、加载驱动类
// Class.forName("com.mysql.jdbc.Driver");
// //2、建立连接
// con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/gp-vip-spring-db-demo","root","123456");
// //3、创建语句集
// pstm = con.prepareStatement(sql);
// //4、执行语句集
// rs = pstm.executeQuery();
// while (rs.next()){
// Member instance = mapperRow(rs,rs.getRow());
// result.add(instance);
// }
// //5、获取结果集
// }catch (Exception e){
// e.printStackTrace();
// }
// //6、关闭结果集、关闭语句集、关闭连接
// finally {
// try {
// rs.close();
// pstm.close();
// con.close();
// }catch (Exception e){
// e.printStackTrace();
// }
// }
// return result;
// }
//
// private static Member mapperRow(ResultSet rs, int i) throws Exception {
// Member instance = new Member();
// instance.setId(rs.getLong("id"));
// instance.setName(rs.getString("name"));
// instance.setAge(rs.getInt("age"));
// instance.setAddr(rs.getString("addr"));
// return instance;
// }
}
| [
"wangheliang@bj-sjzy.com"
] | wangheliang@bj-sjzy.com |
22df3bffe2c3b6f812989d1f7676cd294518ac65 | 6274d6be5ce66966f14d75fc9560ebab0fccabd2 | /QuanLyQuayThuoc/src/giaodien/NhanVien/GiaoDienNhanVien.java | f545bbfda890ae857cf06e9ae2e7638e26d718c1 | [] | no_license | dckool/HeThongQuanLyQuayThuoc-By-Java | 59368daca018a8204a62cc3d9915f9cdef2792c7 | c1cb4663bffda0ce9e252c08b1c7450c7d989d92 | refs/heads/master | 2020-03-28T00:00:51.903998 | 2018-09-04T15:34:08 | 2018-09-04T15:34:08 | 147,368,302 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 45,685 | java | package giaodien.NhanVien;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import control.ControlGiaoDien;
import control.DanhSachDuLieu;
import entity.CTHoaDonBan;
import entity.HoaDonBanHang;
import entity.KhachHang;
import entity.ThongTinThuoc;
import giaodien.GiaoDienDangNhap;
import giaodien.GiaoDienThongTinNhanVien;
import giaodien.QuanLy.GiaoDienQuanLy;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.security.AllPermission;
import java.security.acl.Group;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.awt.event.ActionEvent;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JToolBar;
import javax.swing.JComboBox;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import java.awt.ScrollPane;
import java.awt.Panel;
import javax.swing.ScrollPaneConstants;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import java.awt.Label;
import javax.swing.JLayeredPane;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.SystemColor;
import javax.swing.UIManager;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JToggleButton;
import java.awt.TextArea;
import javax.swing.JTextArea;
import javax.swing.DropMode;
import com.toedter.calendar.JDateChooser;
import com.toedter.calendar.JMonthChooser;
import com.toedter.calendar.JYearChooser;
import javax.swing.JRadioButton;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import javax.swing.KeyStroke;
import java.awt.event.KeyEvent;
import java.awt.event.InputEvent;
public class GiaoDienNhanVien extends JFrame {
private JPanel contentPane, panelTTKH,panelTrangChu;
private JScrollPane scrollPaneDanhSachThuoc,scrollPaneDanhSachDon,scrollPaneCTHD,scrollPaneDoanhThu;
private DefaultTableModel tablemodelThuoc,tablemodelDoanhThu,tablemodelCTHD,tablemodelDanhSachDon;
JTable tableDanhSachThuoc,tableDanhSachDon,tableCTHD,tableDoanhThu ;
ControlGiaoDien control = new ControlGiaoDien();
DanhSachDuLieu ds = new DanhSachDuLieu();
GiaoDienDangNhap dn;
public String IDNhanVien=dn.txtTK.getText();
private JTextField txtMaHD;
private JTextField txtNgayLap;
private JTextField txtNguoiLap_timkiem;
private JTextField txtTongTien_timkiem;
private JTextField txtTongDoanhThu;
private JPanel panelCTHD,panelDSHD,panelDSThuoc,panelDoanhThu;
private JRadioButtonMenuItem chude1,chude2,chude3,chude4,chude5,chude6,chude7,chude8,chude9,chude10;
public JButton btnLapHoaDon;
GiaoDienThongTinNhanVien thongtinnv = new GiaoDienThongTinNhanVien();
GiaoDienLapHoaDon laphoadon ;
private JTextField txtCMND_CTHD;
private JTextField txtTen_CTHD;
private JTextField txtSDT_CTHD;
private JTextField txtNgaySinh_CTHD;
private TextArea textAreaMoTa;
private JLabel lblCMND,lblSDT,lblNgaySinh,lblTen;
private JLabel lblNewLabel_8;
private JRadioButton rdbtnHienHet_DSHD,rdbtnTheoThang_DSHD,rdbtnChinhXac_DSHD,rdbtnTheoNam_DSHD;
private JRadioButton rdbtnHienhet_Doanhthu,rdbtnTheoThang_Doanhthu,rdbtnChinhXac_Doanhthu,rdbtnTheonam_Doanhthu;
private ButtonGroup GroupTimdon,GroupTimdoanhthu;
private DateFormat dateformat =new SimpleDateFormat("yyyy-MM-dd");
private JDateChooser dateChooser_DSHD,dateChooser_DoanhThu;
private JLabel label;
private JPanel panelTim_DSDon;
private JMonthChooser monthChooser_DSHD,monthChooser_DoanhThu;
private JYearChooser yearChooser_DSHD,yearChooser_DoanhThu;
private JLabel lblNewLabel_10;
private JPanel panel_DoanhThu;
private JLabel lblNewLabel_12;
private JMenu menu_1;
private JMenuItem menuItem;
private JMenuItem mntmLpn;
private JMenuItem mntmDanhSchn;
private JMenuItem mntmDsn;
private JMenuItem mntmDoanhThu;
private JButton btnTrangDangNhap,btnDanhSachThuoc,btnDsHD,btnDoanhThu;
public GiaoDienNhanVien() {
setResizable(false);
setIconImage(Toolkit.getDefaultToolkit().getImage(GiaoDienNhanVien.class.getResource("/ser/pill.png")));
setTitle("Nhân Viên");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(300, 100, 800, 600);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JMenuBar menuBar = new JMenuBar();
menuBar.setBounds(0, 0, 794, 21);
contentPane.add(menuBar);
JMenu mnNewMenu = new JMenu("Hệ thống");
menuBar.add(mnNewMenu);
JMenuItem mntmngXut = new JMenuItem("Đăng xuất");
mntmngXut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, InputEvent.CTRL_MASK));
mntmngXut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
dispose();
new GiaoDienDangNhap().setVisible(true);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
JMenu menu = new JMenu("Đổi giao diện");
mnNewMenu.add(menu);
chude1 = new JRadioButtonMenuItem("McWin",true);
chude1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
doiGiaoDien("com.jtattoo.plaf.mcwin.McWinLookAndFeel");
}
});
menu.add(chude1);
chude2 = new JRadioButtonMenuItem("Luna");
chude2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doiGiaoDien("com.jtattoo.plaf.luna.LunaLookAndFeel");
}
});
menu.add(chude2);
chude3 = new JRadioButtonMenuItem("Areo");
chude3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doiGiaoDien("com.jtattoo.plaf.aero.AeroLookAndFeel");
}
});
menu.add(chude3);
chude4 = new JRadioButtonMenuItem("Texture");
chude4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doiGiaoDien("com.jtattoo.plaf.texture.TextureLookAndFeel");
}
});
menu.add(chude4);
chude5 = new JRadioButtonMenuItem("aluminium");
chude5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doiGiaoDien("com.jtattoo.plaf.aluminium.AluminiumLookAndFeel");
}
});
menu.add(chude5);
chude6 = new JRadioButtonMenuItem("NimBus");
chude6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doiGiaoDien("com.jtattoo.plaf.acryl.AcrylLookAndFeel");
}
});
menu.add(chude6);
chude7 = new JRadioButtonMenuItem("Bernstein");
chude7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doiGiaoDien("com.jtattoo.plaf.bernstein.BernsteinLookAndFeel");
}
});
menu.add(chude7);
chude8 = new JRadioButtonMenuItem("Fast");
chude8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doiGiaoDien("com.jtattoo.plaf.fast.FastLookAndFeel");
}
});
menu.add(chude8);
chude9 = new JRadioButtonMenuItem("Graphite");
chude9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doiGiaoDien("com.jtattoo.plaf.graphite.GraphiteLookAndFeel");
}
});
menu.add(chude9);
chude10 = new JRadioButtonMenuItem("Mint");
chude10.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doiGiaoDien("com.jtattoo.plaf.mint.MintLookAndFeel");
}
});
menu.add(chude10);
mnNewMenu.add(mntmngXut);
JMenuItem mntmNewMenuItem = new JMenuItem("Thoát");
mntmNewMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, InputEvent.ALT_MASK));
mnNewMenu.add(mntmNewMenuItem);
mntmNewMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.exit(0);
}
});
menu_1 = new JMenu("Chức năng");
menuBar.add(menu_1);
menuItem = new JMenuItem("Trang chủ");
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
btnTrangDangNhap.doClick();
}
});
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, InputEvent.CTRL_MASK));
menu_1.add(menuItem);
mntmLpn = new JMenuItem("Lập đơn");
mntmLpn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
btnLapHoaDon.doClick();
}
});
mntmLpn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, InputEvent.CTRL_MASK));
menu_1.add(mntmLpn);
mntmDanhSchn = new JMenuItem("DS Thuốc");
mntmDanhSchn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
btnDanhSachThuoc.doClick();
}
});
mntmDanhSchn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_3, InputEvent.CTRL_MASK));
menu_1.add(mntmDanhSchn);
mntmDsn = new JMenuItem("DS đơn");
mntmDsn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
btnDsHD.doClick();
}
});
mntmDsn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_4, InputEvent.CTRL_MASK));
menu_1.add(mntmDsn);
mntmDoanhThu = new JMenuItem("Doanh thu");
mntmDoanhThu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
btnDoanhThu.doClick();
}
});
mntmDoanhThu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_5, InputEvent.CTRL_MASK));
menu_1.add(mntmDoanhThu);
JMenu menuTroGiup = new JMenu("Trợ giúp");
menuBar.add(menuTroGiup);
ButtonGroup groupChuDe = new ButtonGroup();
groupChuDe.add(chude1);
groupChuDe.add(chude2);
groupChuDe.add(chude3);
groupChuDe.add(chude4);
groupChuDe.add(chude5);
groupChuDe.add(chude6);
groupChuDe.add(chude7);
groupChuDe.add(chude8);
groupChuDe.add(chude9);
groupChuDe.add(chude10);
//----------------------------toolbar---------------------------------------
ButtonGroup groupToolBar =new ButtonGroup();
JPanel ThanhToolBar = new JPanel();
ThanhToolBar.setOpaque(false);
ThanhToolBar.setBounds(0, 24, 522, 80);
contentPane.add(ThanhToolBar);
ThanhToolBar.setLayout(new FlowLayout(FlowLayout.LEFT, 0,0));
JToolBar toolBar = new JToolBar();
toolBar.setMinimumSize(new Dimension(0, 0));
ThanhToolBar.add(toolBar);
toolBar.setVerifyInputWhenFocusTarget(false);
btnTrangDangNhap = new JButton("Trang chủ");
btnTrangDangNhap.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
panelCTHD.setVisible(false);
panelDoanhThu.setVisible(false);
panelDSHD.setVisible(false);
panelDSThuoc.setVisible(false);
panelTrangChu.setVisible(true);
}
});
btnTrangDangNhap.setFont(new Font("Tahoma", Font.BOLD, 11));
btnTrangDangNhap.setHorizontalTextPosition(SwingConstants.CENTER);
btnTrangDangNhap.setVerticalAlignment(SwingConstants.TOP);
btnTrangDangNhap.setVerticalTextPosition(SwingConstants.BOTTOM);
btnTrangDangNhap.setIcon(new ImageIcon(GiaoDienQuanLy.class.getResource("/ser/home.png")));
btnTrangDangNhap.setPreferredSize(new Dimension(100, 75));
btnTrangDangNhap.setMaximumSize(new Dimension(100, 100));
toolBar.add(btnTrangDangNhap);
groupToolBar.add(btnTrangDangNhap);
btnLapHoaDon =new JButton("Lập hóa đơn");
btnLapHoaDon.setFont(new Font("Tahoma", Font.BOLD, 11));
btnLapHoaDon.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new GiaoDienLapHoaDon().setVisible(true);
}
});
toolBar.add(btnLapHoaDon);
btnLapHoaDon.setIcon(new ImageIcon(GiaoDienNhanVien.class.getResource("/ser/bill.png")));
btnLapHoaDon.setVerticalTextPosition(SwingConstants.BOTTOM);
btnLapHoaDon.setVerticalAlignment(SwingConstants.TOP);
btnLapHoaDon.setPreferredSize(new Dimension(100, 75));
btnLapHoaDon.setMaximumSize(new Dimension(100, 100));
btnLapHoaDon.setHorizontalTextPosition(SwingConstants.CENTER);
btnDanhSachThuoc = new JButton("DS thuốc");
btnDanhSachThuoc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
panelCTHD.setVisible(false);
panelTrangChu.setVisible(false);
panelDoanhThu.setVisible(false);
panelDSHD.setVisible(false);
panelDSThuoc.setVisible(true);
for(int i = tablemodelThuoc.getRowCount()-1;i>=0;i--)
tablemodelThuoc.removeRow(i);
try {
ds.docThuoc();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
for (ThongTinThuoc thuoc : ds.listThuoc)
{
Object[] row = {thuoc.getMaThuoc(),thuoc.getTenThuoc(),thuoc.getLoai(),thuoc.getNcc(),thuoc.getSoLuong(),thuoc.getGiaBan()};
tablemodelThuoc.addRow(row);
}
}
});
groupToolBar.add(btnDanhSachThuoc);
btnDanhSachThuoc.setIcon(new ImageIcon(GiaoDienNhanVien.class.getResource("/ser/death_list.png")));
btnDanhSachThuoc.setVerticalTextPosition(SwingConstants.BOTTOM);
btnDanhSachThuoc.setVerticalAlignment(SwingConstants.TOP);
btnDanhSachThuoc.setPreferredSize(new Dimension(100, 75));
btnDanhSachThuoc.setMaximumSize(new Dimension(100, 100));
btnDanhSachThuoc.setHorizontalTextPosition(SwingConstants.CENTER);
btnDanhSachThuoc.setFont(new Font("Tahoma", Font.BOLD, 11));
toolBar.add(btnDanhSachThuoc);
btnDsHD = new JButton("DS hóa đơn");
btnDsHD.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
tablemodelCTHD.getDataVector().removeAllElements();
tablemodelCTHD.fireTableDataChanged();
panelCTHD.setVisible(false);
panelDSThuoc.setVisible(false);
panelDoanhThu.setVisible(false);
panelTrangChu.setVisible(false);
xoaDuLieuTrongTable();
panelDSHD.setVisible(true);
try {
ds.docBangHDB();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (HoaDonBanHang hd : ds.listHDB)
{
if (hd.getMaNVLap().equalsIgnoreCase(IDNhanVien))
{
Object[] row = {hd.getMaHD(),hd.getMaNVLap(),hd.getNgayLap(),hd.getMaKH(),hd.getTongTien()};
tablemodelDanhSachDon.addRow(row);
}
}
}
});
groupToolBar.add(btnDsHD);
btnDsHD.setIcon(new ImageIcon(GiaoDienNhanVien.class.getResource("/ser/list.png")));
btnDsHD.setVerticalTextPosition(SwingConstants.BOTTOM);
btnDsHD.setVerticalAlignment(SwingConstants.TOP);
btnDsHD.setPreferredSize(new Dimension(100, 75));
btnDsHD.setMaximumSize(new Dimension(100, 100));
btnDsHD.setHorizontalTextPosition(SwingConstants.CENTER);
btnDsHD.setFont(new Font("Tahoma", Font.BOLD, 11));
toolBar.add(btnDsHD);
btnDoanhThu = new JButton("Doanh thu");
btnDoanhThu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
panelCTHD.setVisible(false);
panelDSThuoc.setVisible(false);
panelDSHD.setVisible(false);
panelTrangChu.setVisible(false);
panelDoanhThu.setVisible(true);
xoaDuLieuTrongTable();
try {
ds.docBangHDB();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
for (HoaDonBanHang hd : ds.listHDB) {
if (hd.getMaNVLap().equalsIgnoreCase(IDNhanVien)) {
Object[] row = {hd.getMaHD(),hd.getNgayLap(),hd.getMaNVLap(),hd.getTongTien()};
tablemodelDoanhThu.addRow(row);
}
}
txtTongDoanhThu.setText(control.tongDoanhThu(tablemodelDoanhThu,3)+"");
}
});
groupToolBar.add(btnDoanhThu);
btnDoanhThu.setIcon(new ImageIcon(GiaoDienNhanVien.class.getResource("/ser/report.png")));
btnDoanhThu.setVerticalTextPosition(SwingConstants.BOTTOM);
btnDoanhThu.setVerticalAlignment(SwingConstants.TOP);
btnDoanhThu.setPreferredSize(new Dimension(100, 75));
btnDoanhThu.setMaximumSize(new Dimension(100, 100));
btnDoanhThu.setHorizontalTextPosition(SwingConstants.CENTER);
btnDoanhThu.setFont(new Font("Tahoma", Font.BOLD, 11));
toolBar.add(btnDoanhThu);
//-----------------------------------------header table---------------------
String[] headerDanhSachDon="Mã hóa đơn;Người lập;Ngày lập;Khách hàng;Tổng tiền".split(";");
tablemodelDanhSachDon = new DefaultTableModel(headerDanhSachDon,0){
@Override//Override lại phương thức isCellEditable
public boolean isCellEditable(int row, int column) {
return false;//Trả về false không cho edit.
}
};
String[] headerCTHD="Tên thuốc;Số lượng;Giá bán".split(";");
tablemodelCTHD = new DefaultTableModel(headerCTHD,0){
@Override//Override lại phương thức isCellEditable
public boolean isCellEditable(int row, int column) {
return false;//Trả về false không cho edit.
}
};
String[] headerDoanhThu="Mã đơn;Ngày lập;Người Lập;Tổng tiền".split(";");
tablemodelDoanhThu = new DefaultTableModel(headerDoanhThu,0){
@Override//Override lại phương thức isCellEditable
public boolean isCellEditable(int row, int column) {
return false;//Trả về false không cho edit.
}
};
String[] header="Mã thuốc;Tên thuốc;Loại thuốc;Nhà cung cấp;Số lượng còn;Giá bán".split(";");
tablemodelThuoc = new DefaultTableModel(header,0){
@Override//Override lại phương thức isCellEditable
public boolean isCellEditable(int row, int column) {
return false;//Trả về false không cho edit.
}
};
JPanel panelthongTin = new JPanel();
panelthongTin.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Th\u00F4ng tin nh\u00E2n vi\u00EAn:", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(233, 150, 122)));
panelthongTin.setBounds(571, 24, 223, 80);
contentPane.add(panelthongTin);
panelthongTin.setLayout(null);
label = new JLabel(dn.txtTK.getText()+"");
label.setForeground(Color.BLUE);
label.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
@Override
public void mouseExited(MouseEvent e) {
label.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
@Override
public void mouseClicked(MouseEvent e) {
thongtinnv.setVisible(true);
}
});
label.setFont(new Font("Tahoma", Font.BOLD, 11));
label.setBounds(59, 20, 78, 15);
panelthongTin.add(label);
JLabel lblNewLabel_1 = new JLabel("ID :");
lblNewLabel_1.setFont(new Font("Tahoma", Font.BOLD, 11));
lblNewLabel_1.setBounds(10, 20, 46, 14);
panelthongTin.add(lblNewLabel_1);
JLabel lblNewLabel_9 = new JLabel("Tên :");
lblNewLabel_9.setFont(new Font("Tahoma", Font.BOLD, 11));
lblNewLabel_9.setBounds(10, 40, 46, 14);
panelthongTin.add(lblNewLabel_9);
JLabel lblTenNV = new JLabel("New label");
lblTenNV.setFont(new Font("Tahoma", Font.PLAIN, 11));
lblTenNV.setBounds(59, 40, 154, 14);
panelthongTin.add(lblTenNV);
JLabel lblNewLabel_11 = new JLabel("Số ĐT:");
lblNewLabel_11.setFont(new Font("Tahoma", Font.BOLD, 11));
lblNewLabel_11.setBounds(10, 60, 46, 14);
panelthongTin.add(lblNewLabel_11);
JLabel lbSoDT = new JLabel("New label");
lbSoDT.setFont(new Font("Tahoma", Font.PLAIN, 11));
lbSoDT.setBounds(59, 60, 154, 14);
panelthongTin.add(lbSoDT);
JLabel lblDangXuat = new JLabel("Đăng xuất");
lblDangXuat.setFont(new Font("Tahoma", Font.BOLD, 11));
lblDangXuat.setForeground(Color.BLUE);
lblDangXuat.setBounds(147, 20, 76, 14);
lblDangXuat.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
lblDangXuat.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
@Override
public void mouseExited(MouseEvent e) {
lblDangXuat.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
@Override
public void mouseClicked(MouseEvent e) {
try {
new GiaoDienDangNhap().setVisible(true);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
dispose();
}
});
panelthongTin.add(lblDangXuat);
JLabel lblbanquyen = new JLabel("Made by cCc ");
lblbanquyen.setBounds(696, 546, 88, 14);
contentPane.add(lblbanquyen);
lblbanquyen.setForeground(Color.LIGHT_GRAY);
lblbanquyen.setFont(new Font("Trebuchet MS", Font.BOLD, 13));
//----------------------------đa layer---------------------------------
JLayeredPane layeredPane = new JLayeredPane();
layeredPane.setBounds(0, 115, 794, 456);
contentPane.add(layeredPane);
panelTrangChu = new JPanel();
layeredPane.setLayer(panelTrangChu, 1);
panelTrangChu.setForeground(new Color(173, 255, 47));
panelTrangChu.setBounds(0, 11, 794, 445);
layeredPane.add(panelTrangChu);
panelTrangChu.setLayout(null);
JPanel panel = new JPanel();
panel.setEnabled(false);
panel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "", TitledBorder.CENTER, TitledBorder.BELOW_TOP, null, new Color(0, 0, 0)));
panel.setBounds(395, 11, 352, 190);
panelTrangChu.add(panel);
panel.setLayout(null);
JTextArea txtrthngTinH = new JTextArea();
txtrthngTinH.setOpaque(false);
txtrthngTinH.setVerifyInputWhenFocusTarget(false);
txtrthngTinH.setFocusable(false);
txtrthngTinH.setFocusTraversalKeysEnabled(false);
txtrthngTinH.setFocusTraversalPolicyProvider(true);
txtrthngTinH.setBounds(10, 11, 339, 164);
panel.add(txtrthngTinH);
txtrthngTinH.setLineWrap(true);
txtrthngTinH.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrthngTinH.setEditable(false);
txtrthngTinH.setForeground(new Color(106, 90, 205));
txtrthngTinH.setText("\t------THÔNG TIN-------\r\n Hệ thống quản lý quầy thuốc của bệnh viện\r\n Thiết kế bởi:\r\n\t+ Trần Đình Chiến\t15091761\r\n\t+ Trần Hùng Cường\t15056921\r\n\t+ Nguyễn Văn Mạnh Cường\t15051431\r\n GV: Võ Thị Thanh Vân\r\n Lớp: DHKTPM11A\r\n Môn: Phát triển ứng dụng\r\n Khoa Công nghệ thông tin - Đại học Công Nghiệp TPHCM");
txtrthngTinH.setBackground(new Color(0, 0, 0,0));
JLabel baner = new JLabel("");
baner.setIcon(new ImageIcon(GiaoDienNhanVien.class.getResource("/ser/baner2222.png")));
baner.setBounds(0, 223, 794, 222);
panelTrangChu.add(baner);
lblNewLabel_8 = new JLabel("");
lblNewLabel_8.setIcon(new ImageIcon(GiaoDienNhanVien.class.getResource("/ser/paramedic_spinning_st_a_ha.gif")));
lblNewLabel_8.setBounds(10, 0, 365, 233);
panelTrangChu.add(lblNewLabel_8);
panelCTHD = new JPanel();
panelCTHD.setBounds(10, 11, 774, 408);
layeredPane.add(panelCTHD);
panelCTHD.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Chi ti\u1EBFt h\u00F3a \u0111\u01A1n: ", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 255)));
panelCTHD.setForeground(new Color(0, 255, 255));
layeredPane.setLayer(panelCTHD, 0);
panelCTHD.setLayout(null);
JLabel lblMa = new JLabel("Mã:");
lblMa.setBounds(31, 34, 36, 14);
lblMa.setFont(new Font("Tahoma", Font.BOLD, 11));
panelCTHD.add(lblMa);
txtMaHD = new JTextField();
txtMaHD.setBounds(59, 31, 67, 20);
txtMaHD.setEditable(false);
txtMaHD.setEnabled(false);
panelCTHD.add(txtMaHD);
txtMaHD.setColumns(10);
JLabel lblNgay = new JLabel("Ngày:");
lblNgay.setBounds(136, 34, 52, 14);
lblNgay.setFont(new Font("Tahoma", Font.BOLD, 11));
panelCTHD.add(lblNgay);
txtNgayLap = new JTextField();
txtNgayLap.setBounds(178, 31, 108, 20);
txtNgayLap.setEnabled(false);
txtNgayLap.setEditable(false);
panelCTHD.add(txtNgayLap);
txtNgayLap.setColumns(10);
JLabel lblNewLabel_3 = new JLabel("Người lập:");
lblNewLabel_3.setBounds(307, 34, 67, 14);
lblNewLabel_3.setFont(new Font("Tahoma", Font.BOLD, 11));
panelCTHD.add(lblNewLabel_3);
txtNguoiLap_timkiem = new JTextField();
txtNguoiLap_timkiem.setBounds(373, 31, 86, 20);
txtNguoiLap_timkiem.setText(IDNhanVien);
txtNguoiLap_timkiem.setEditable(false);
txtNguoiLap_timkiem.setEnabled(false);
panelCTHD.add(txtNguoiLap_timkiem);
txtNguoiLap_timkiem.setColumns(10);
txtTongTien_timkiem = new JTextField();
txtTongTien_timkiem.setBounds(346, 59, 113, 20);
txtTongTien_timkiem.setEditable(false);
txtTongTien_timkiem.setEnabled(false);
panelCTHD.add(txtTongTien_timkiem);
txtTongTien_timkiem.setColumns(10);
JLabel lblNewLabel = new JLabel("Tổng tiền hóa đơn: ");
lblNewLabel.setBounds(216, 62, 121, 14);
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 11));
panelCTHD.add(lblNewLabel);
JLabel lblNewLabel_2 = new JLabel("Danh sách thuốc bán:");
lblNewLabel_2.setBounds(25, 65, 136, 14);
lblNewLabel_2.setFont(new Font("Tahoma", Font.BOLD, 11));
panelCTHD.add(lblNewLabel_2);
panelCTHD.add(scrollPaneCTHD = new JScrollPane(tableCTHD = new JTable(tablemodelCTHD)));
tableCTHD.setForeground(new Color(210, 105, 30));
JButton btnBack2 = new JButton("Quay lại");
btnBack2.setFont(new Font("Tahoma", Font.BOLD, 11));
btnBack2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//------2 dòng này để xóa hết bảng cũ và hiện cái mới lên, ko có cái này thông tin chồng lên nhau
tablemodelCTHD.getDataVector().removeAllElements();
tablemodelCTHD.fireTableDataChanged();
//-----------------
panelDSThuoc.setVisible(false);
panelDoanhThu.setVisible(false);
panelCTHD.setVisible(false);
panelDSHD.setVisible(true);
}
});
btnBack2.setHorizontalTextPosition(SwingConstants.CENTER);
btnBack2.setVerticalTextPosition(SwingConstants.BOTTOM);
btnBack2.setVerticalAlignment(SwingConstants.TOP);
btnBack2.setIcon(new ImageIcon(GiaoDienNhanVien.class.getResource("/ser/back4848.png")));
btnBack2.setBounds(469, 11, 77, 75);
panelCTHD.add(btnBack2);
JLabel lblNewLabel_5 = new JLabel("");
lblNewLabel_5.setIcon(new ImageIcon(GiaoDienNhanVien.class.getResource("/ser/banner3.png")));
lblNewLabel_5.setBounds(9, 293, 757, 110);
panelCTHD.add(lblNewLabel_5);
panelTTKH = new JPanel();
panelTTKH.setEnabled(false);
panelTTKH.setBorder(new TitledBorder(null, "Th\u00F4ng tin kh\u00E1ch h\u00E0ng:", TitledBorder.LEADING, TitledBorder.TOP, null, Color.BLUE));
panelTTKH.setBounds(552, 11, 214, 271);
panelCTHD.add(panelTTKH);
panelTTKH.setLayout(null);
lblCMND = new JLabel("CMND:");
lblCMND.setEnabled(false);
lblCMND.setFont(new Font("Tahoma", Font.BOLD, 11));
lblCMND.setBounds(10, 28, 46, 14);
panelTTKH.add(lblCMND);
txtCMND_CTHD = new JTextField();
txtCMND_CTHD.setEditable(false);
txtCMND_CTHD.setEnabled(false);
txtCMND_CTHD.setBounds(74, 25, 130, 20);
panelTTKH.add(txtCMND_CTHD);
txtCMND_CTHD.setColumns(10);
lblTen = new JLabel("Tên: ");
lblTen.setEnabled(false);
lblTen.setFont(new Font("Tahoma", Font.BOLD, 11));
lblTen.setBounds(10, 59, 46, 14);
panelTTKH.add(lblTen);
txtTen_CTHD = new JTextField();
txtTen_CTHD.setEnabled(false);
txtTen_CTHD.setEditable(false);
txtTen_CTHD.setBounds(74, 56, 130, 20);
panelTTKH.add(txtTen_CTHD);
txtTen_CTHD.setColumns(10);
lblSDT = new JLabel("SDT:");
lblSDT.setEnabled(false);
lblSDT.setFont(new Font("Tahoma", Font.BOLD, 11));
lblSDT.setBounds(10, 90, 46, 14);
panelTTKH.add(lblSDT);
txtSDT_CTHD = new JTextField();
txtSDT_CTHD.setEditable(false);
txtSDT_CTHD.setEnabled(false);
txtSDT_CTHD.setBounds(74, 87, 130, 20);
panelTTKH.add(txtSDT_CTHD);
txtSDT_CTHD.setColumns(10);
lblNgaySinh = new JLabel("Ngày sinh:");
lblNgaySinh.setEnabled(false);
lblNgaySinh.setFont(new Font("Tahoma", Font.BOLD, 11));
lblNgaySinh.setBounds(10, 121, 57, 14);
panelTTKH.add(lblNgaySinh);
txtNgaySinh_CTHD = new JTextField();
txtNgaySinh_CTHD.setEditable(false);
txtNgaySinh_CTHD.setEnabled(false);
txtNgaySinh_CTHD.setBounds(74, 118, 130, 20);
panelTTKH.add(txtNgaySinh_CTHD);
txtNgaySinh_CTHD.setColumns(10);
textAreaMoTa = new TextArea();
textAreaMoTa.setEditable(false);
textAreaMoTa.setEnabled(false);
textAreaMoTa.setBounds(10, 144, 194, 117);
panelTTKH.add(textAreaMoTa);
scrollPaneCTHD.setBounds(25, 90, 524, 192);
panelDSThuoc = new JPanel();
panelDSThuoc.setBorder(new TitledBorder(null, "Danh s\u00E1ch thu\u1ED1c:", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 255)));
panelDSThuoc.setBounds(10, 11, 774, 408);
layeredPane.add(panelDSThuoc);
panelDSThuoc.add(scrollPaneDanhSachThuoc = new JScrollPane(tableDanhSachThuoc= new JTable(tablemodelThuoc)));
tableDanhSachThuoc.setForeground(new Color(148, 0, 211));
scrollPaneDanhSachThuoc.setPreferredSize(new Dimension(750, 380));
panelDSHD = new JPanel();
panelDSHD.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Danh s\u00E1ch h\u00F3a \u0111\u01A1n: ", TitledBorder.CENTER, TitledBorder.TOP, null, new Color(0, 0, 255)));
layeredPane.setLayer(panelDSHD, 0);
panelDSHD.setBounds(10, 11, 774, 408);
layeredPane.add(panelDSHD);
panelDSHD.setLayout(null);
JLabel lblNgayLap_timkiem = new JLabel("Tìm theo thời gian lập:");
lblNgayLap_timkiem.setBounds(22, 18, 141, 14);
panelDSHD.add(lblNgayLap_timkiem);
lblNgayLap_timkiem.setFont(new Font("Tahoma", Font.BOLD, 11));
JButton btnXemChiTiet = new JButton("Xem chi tiết");
btnXemChiTiet.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
xemChiTietHD();
}
});
btnXemChiTiet.setBounds(156, 372, 125, 25);
panelDSHD.add(btnXemChiTiet);
btnXemChiTiet.setIcon(new ImageIcon(GiaoDienNhanVien.class.getResource("/ser/more_01.png")));
btnXemChiTiet.setFont(new Font("Tahoma", Font.BOLD, 12));
JButton btnTim_DSHoaDon = new JButton("Tìm");
btnTim_DSHoaDon.setVerticalTextPosition(SwingConstants.BOTTOM);
btnTim_DSHoaDon.setHorizontalTextPosition(SwingConstants.CENTER);
btnTim_DSHoaDon.setBounds(386, 18, 68, 57);
panelDSHD.add(btnTim_DSHoaDon);
btnTim_DSHoaDon.setFont(new Font("Tahoma", Font.BOLD, 11));
btnTim_DSHoaDon.setIcon(new ImageIcon(GiaoDienNhanVien.class.getResource("/ser/search.png")));
btnTim_DSHoaDon.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
timKiemDSHD();
}
});
panelDSHD.add(scrollPaneDanhSachDon = new JScrollPane(tableDanhSachDon = new JTable(tablemodelDanhSachDon)));
tableDanhSachDon.setForeground(new Color(165, 42, 42));
tableDanhSachDon.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent arg0) {
// TODO Auto-generated method stub
int row = tableDanhSachDon.getSelectedRow();
}
});
JLabel lblCcHan = new JLabel("Các hóa đơn đã lập:");
lblCcHan.setFont(new Font("Tahoma", Font.BOLD, 11));
lblCcHan.setBounds(41, 79, 176, 14);
panelDSHD.add(lblCcHan);
JLabel lblNewLabel_7 = new JLabel("");
lblNewLabel_7.setToolTipText("Uống thuốc đi bạn ơi");
lblNewLabel_7.setIcon(new ImageIcon(GiaoDienNhanVien.class.getResource("/ser/doctor_doing_pill_end_a_ha.gif")));
lblNewLabel_7.setBounds(471, 31, 280, 350);
panelDSHD.add(lblNewLabel_7);
GroupTimdon = new ButtonGroup();
rdbtnHienHet_DSHD = new JRadioButton("Hiện hết đơn");
rdbtnHienHet_DSHD.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
LoadJCalender_DSDon(true, false, false, false);
}
});
rdbtnHienHet_DSHD.setSelected(true);
rdbtnHienHet_DSHD.setBounds(191, 25, 101, 23);
panelDSHD.add(rdbtnHienHet_DSHD);
GroupTimdon.add(rdbtnHienHet_DSHD);
rdbtnTheoThang_DSHD = new JRadioButton("Theo tháng");
rdbtnTheoThang_DSHD.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
LoadJCalender_DSDon(false, false,true, false);
}
});
rdbtnTheoThang_DSHD.setBounds(191, 49, 101, 23);
panelDSHD.add(rdbtnTheoThang_DSHD);
GroupTimdon.add(rdbtnTheoThang_DSHD);
rdbtnChinhXac_DSHD = new JRadioButton("Chính xác");
rdbtnChinhXac_DSHD.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
LoadJCalender_DSDon(false,true,false, false);
}
});
rdbtnChinhXac_DSHD.setBounds(294, 25, 90, 23);
panelDSHD.add(rdbtnChinhXac_DSHD);
GroupTimdon.add( rdbtnChinhXac_DSHD);
rdbtnTheoNam_DSHD = new JRadioButton("Theo năm");
rdbtnTheoNam_DSHD.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
LoadJCalender_DSDon(false,false,false, true);
}
});
rdbtnTheoNam_DSHD.setBounds(294, 49, 90, 23);
panelDSHD.add(rdbtnTheoNam_DSHD);
GroupTimdon.add(rdbtnTheoNam_DSHD);
panelTim_DSDon = new JPanel();
panelTim_DSDon.setBounds(10, 38, 153, 30);
panelDSHD.add(panelTim_DSDon);
panelTim_DSDon.setLayout(null);
lblNewLabel_10 = new JLabel("Tìm hết các móc thời gian");
lblNewLabel_10.setBounds(0, 0, 153, 30);
panelTim_DSDon.add(lblNewLabel_10);
scrollPaneDanhSachDon.setBounds(22, 99, 439, 262);
panelDoanhThu = new JPanel();
panelDoanhThu.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Th\u1ED1ng k\u00EA doanh thu:", TitledBorder.CENTER, TitledBorder.TOP, null, new Color(0, 0, 255)));
layeredPane.setLayer(panelDoanhThu, 0);
panelDoanhThu.setBounds(10, 11, 774, 408);
layeredPane.add(panelDoanhThu);
panelDoanhThu.setLayout(null);
JLabel lblChon = new JLabel("Chọn mốc thời gian:");
lblChon.setBounds(10, 11, 110, 14);
panelDoanhThu.add(lblChon);
lblChon.setFont(new Font("Tahoma", Font.BOLD, 11));
JLabel lblNewLabel_4 = new JLabel("Tổng doanh thu:");
lblNewLabel_4.setBounds(463, 368, 104, 15);
panelDoanhThu.add(lblNewLabel_4);
lblNewLabel_4.setFont(new Font("Tahoma", Font.BOLD, 12));
txtTongDoanhThu = new JTextField();
txtTongDoanhThu.setBounds(572, 365, 195, 20);
panelDoanhThu.add(txtTongDoanhThu);
txtTongDoanhThu.setEnabled(false);
txtTongDoanhThu.setEditable(false);
txtTongDoanhThu.setColumns(10);
JButton btntimDoanhThu = new JButton("Xem");
btntimDoanhThu.setHorizontalTextPosition(SwingConstants.CENTER);
btntimDoanhThu.setVerticalTextPosition(SwingConstants.BOTTOM);
btntimDoanhThu.setBounds(378, 21, 75, 59);
panelDoanhThu.add(btntimDoanhThu);
btntimDoanhThu.setIcon(new ImageIcon(GiaoDienNhanVien.class.getResource("/ser/search.png")));
btntimDoanhThu.setFont(new Font("Tahoma", Font.BOLD, 11));
btntimDoanhThu.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
timKiem_DoanhThu();
}
});
panelDoanhThu.add(scrollPaneDoanhThu = new JScrollPane(tableDoanhThu = new JTable(tablemodelDoanhThu)));
tableDoanhThu.setForeground(new Color(210, 105, 30));
JLabel lblNewLabel_6 = new JLabel("");
lblNewLabel_6.setIcon(new ImageIcon(GiaoDienNhanVien.class.getResource("/ser/doanhthu.png")));
lblNewLabel_6.setBounds(463, 39, 301, 315);
panelDoanhThu.add(lblNewLabel_6);
scrollPaneDoanhThu.setBounds(10, 97, 443, 288);
txtTongDoanhThu.setText(control.tongDoanhThu(tablemodelDoanhThu,3)+"");
GroupTimdoanhthu=new ButtonGroup();
rdbtnHienhet_Doanhthu = new JRadioButton("Hiện hết đơn");
rdbtnHienhet_Doanhthu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
LoadJCalender_Doanhthu(true, false, false, false);
}
});
rdbtnHienhet_Doanhthu.setSelected(true);
rdbtnHienhet_Doanhthu.setBounds(172, 21, 101, 23);
panelDoanhThu.add(rdbtnHienhet_Doanhthu);
GroupTimdoanhthu.add(rdbtnHienhet_Doanhthu);
rdbtnTheoThang_Doanhthu = new JRadioButton("Theo tháng");
rdbtnTheoThang_Doanhthu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
LoadJCalender_Doanhthu(false, false,true, false);
}
});
rdbtnTheoThang_Doanhthu.setBounds(172, 45, 101, 23);
panelDoanhThu.add(rdbtnTheoThang_Doanhthu);
GroupTimdoanhthu.add(rdbtnTheoThang_Doanhthu);
rdbtnChinhXac_Doanhthu = new JRadioButton("Chính xác");
rdbtnChinhXac_Doanhthu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
LoadJCalender_Doanhthu(false, true,false, false);
}
});
rdbtnChinhXac_Doanhthu.setBounds(275, 21, 90, 23);
panelDoanhThu.add(rdbtnChinhXac_Doanhthu);
GroupTimdoanhthu.add(rdbtnChinhXac_Doanhthu);
rdbtnTheonam_Doanhthu = new JRadioButton("Theo năm");
rdbtnTheonam_Doanhthu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
LoadJCalender_Doanhthu(false,false,false, true);
}
});
rdbtnTheonam_Doanhthu.setBounds(275, 45, 90, 23);
panelDoanhThu.add(rdbtnTheonam_Doanhthu);
GroupTimdoanhthu.add(rdbtnTheonam_Doanhthu);
panel_DoanhThu = new JPanel();
panel_DoanhThu.setBounds(10, 36, 152, 34);
panelDoanhThu.add(panel_DoanhThu);
panel_DoanhThu.setLayout(null);
lblNewLabel_12 = new JLabel("Tìm hết các móc thời gian");
lblNewLabel_12.setBounds(0, 0, 152, 34);
panel_DoanhThu.add(lblNewLabel_12);
try {
ds.docNV();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
lblTenNV.setText(ds.timNVTheoMa(IDNhanVien).getHoTenNV());
lbSoDT.setText(ds.timNVTheoMa(IDNhanVien).getSdt());
}
////////////////////////////////////////////
//////////////////////
void duaDuLieuTuListVaoTable()
{
try {
ds.docThuoc();
ds.docBangHDB();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (ThongTinThuoc thuoc : ds.listThuoc)
{
Object[] row = {thuoc.getMaThuoc(),thuoc.getTenThuoc(),thuoc.getLoai(),thuoc.getNcc(),thuoc.getSoLuong(),thuoc.getGiaBan()};
tablemodelThuoc.addRow(row);
}
for (HoaDonBanHang hd : ds.listHDB)
{
if (hd.getMaNVLap().equalsIgnoreCase(IDNhanVien))
{
Object[] row = {hd.getMaHD(),hd.getMaNVLap(),hd.getNgayLap(),hd.getMaKH(),hd.getTongTien()};
tablemodelDanhSachDon.addRow(row);
}
}
for (HoaDonBanHang hd : ds.listHDB)
{
if (hd.getMaNVLap().equalsIgnoreCase(IDNhanVien)) {
Object[] row = {hd.getMaHD(),hd.getNgayLap(),hd.getMaNVLap(),hd.getTongTien()};
tablemodelDoanhThu.addRow(row);
}
}
}
void xoaDuLieuTrongTable()
{
for(int i = tablemodelThuoc.getRowCount()-1;i>=0;i--)
tablemodelThuoc.removeRow(i);
for(int i = tablemodelDanhSachDon.getRowCount()-1;i>=0;i--)
tablemodelDanhSachDon.removeRow(i);
for(int i = tablemodelDoanhThu.getRowCount()-1;i>=0;i--)
tablemodelDoanhThu.removeRow(i);
}
public void doiGiaoDien(String chude)
{
try
{
UIManager.setLookAndFeel(chude);
SwingUtilities.updateComponentTreeUI(GiaoDienNhanVien.this);
control.LuuChuDe(chude);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void xemChiTietHD() {
int row = tableDanhSachDon.getSelectedRow();
if (row!=-1) {
panelDSThuoc.setVisible(false);
panelDoanhThu.setVisible(false);
panelDSHD.setVisible(false);
panelCTHD.setVisible(true);
String maHD =(String) tableDanhSachDon.getValueAt(row, 0);
String ngay =(String) tableDanhSachDon.getValueAt(row, 2);
String tongTien = tableDanhSachDon.getValueAt(row, 4)+"";
String CMND = tableDanhSachDon.getValueAt(row, 3)+"";
try {
ds.docBangCTHoaDonBan();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
for (CTHoaDonBan cthd : ds.listThuocBan)
{
if (cthd.getMaHD().equalsIgnoreCase(maHD)) {
Object[] roww = {cthd.getTenThuoc(),cthd.getSoLuong(),cthd.getDonGia()};
tablemodelCTHD.addRow(roww);
}
}
txtMaHD.setText(maHD);
txtNgayLap.setText(ngay);
txtTongTien_timkiem.setText(tongTien);
if (!CMND.equals("")) {
panelTTKH.setEnabled(true);
txtCMND_CTHD.setEnabled(true);
txtTen_CTHD.setEnabled(true);
txtSDT_CTHD.setEnabled(true);
txtNgaySinh_CTHD.setEnabled(true);
textAreaMoTa.setEnabled(true);
lblCMND.setEnabled(true);
lblSDT.setEnabled(true);
lblTen.setEnabled(true);
lblNgaySinh.setEnabled(true);
try {
ds.docBangKhachHang();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
KhachHang kh = new KhachHang();
kh = ds.timKHTheoCMND(CMND);
txtCMND_CTHD.setText(CMND);
txtTen_CTHD.setText(kh.getHoTenKH());
txtNgaySinh_CTHD.setText(kh.getNgaySinh());
txtSDT_CTHD.setText(kh.getSdt());
textAreaMoTa.setText(kh.getMoTaKH());
}
else
{
panelTTKH.setEnabled(false);
txtCMND_CTHD.setEnabled(false);
txtTen_CTHD.setEnabled(false);
txtSDT_CTHD.setEnabled(false);
txtNgaySinh_CTHD.setEnabled(false);
textAreaMoTa.setEnabled(false);
lblCMND.setEnabled(false);
lblSDT.setEnabled(false);
lblTen.setEnabled(false);
lblNgaySinh.setEnabled(false);
txtCMND_CTHD.setText("");
txtTen_CTHD.setText("");
txtNgaySinh_CTHD.setText("");
txtSDT_CTHD.setText("");
textAreaMoTa.setText("");
}
}
else {
JOptionPane.showMessageDialog(panelDSHD, "Vui lòng chọn hóa đơn cần xem !!!");
}
}
public void timKiem_DoanhThu()
{
for(int i = tablemodelDoanhThu.getRowCount()-1;i>=0;i--)
{
tablemodelDoanhThu.removeRow(i);
}
try {
ds.docNV();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<HoaDonBanHang> dshdban=null;
if(rdbtnHienhet_Doanhthu.isSelected())
{
dshdban=ds.listHDB;
}
else if(rdbtnChinhXac_Doanhthu.isSelected())
{
Date ngay = dateChooser_DoanhThu.getDate();
dshdban=control.TimHDNBanTheoNgay(dateformat.format(ngay));
}
else if(rdbtnTheoThang_Doanhthu.isSelected())
{
dshdban=control.TimHDNBanTheoThang(monthChooser_DoanhThu.getMonth()+1);
}
else if(rdbtnTheonam_Doanhthu.isSelected())
{
dshdban=control.TimHDNBanTheoNam(yearChooser_DoanhThu.getYear());
}
for(HoaDonBanHang hd : dshdban)
{
if(hd.getMaNVLap().equals(IDNhanVien))
{
Object[] row = {hd.getMaHD(),hd.getNgayLap(),hd.getMaNVLap(),hd.getTongTien()};
tablemodelDoanhThu.addRow(row);
}
}
}
public void timKiemDSHD()
{
for(int i = tablemodelDanhSachDon.getRowCount()-1;i>=0;i--)
{
tablemodelDanhSachDon.removeRow(i);
}
try {
ds.docNV();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<HoaDonBanHang> dshdban=null;
if(rdbtnHienHet_DSHD.isSelected())
{
dshdban=ds.listHDB;
}
else if(rdbtnChinhXac_DSHD.isSelected())
{
Date ngay = dateChooser_DSHD.getDate();
dshdban=control.TimHDNBanTheoNgay(dateformat.format(ngay));
}
else if(rdbtnTheoThang_DSHD.isSelected())
{
dshdban=control.TimHDNBanTheoThang(monthChooser_DSHD.getMonth()+1);
}
else if(rdbtnTheoNam_DSHD.isSelected())
{
dshdban=control.TimHDNBanTheoNam(yearChooser_DSHD.getYear());
}
for(HoaDonBanHang hd : dshdban)
{
if(hd.getMaNVLap().equals(IDNhanVien))
{
Object[] row = {hd.getMaHD(),hd.getMaNVLap(),hd.getNgayLap(),hd.getMaKH(),hd.getTongTien()};
tablemodelDanhSachDon.addRow(row);
}
}
}
public void LoadJCalender_DSDon(boolean a, boolean b,boolean c,boolean d)
{
panelTim_DSDon.removeAll();
panelTim_DSDon.repaint();
panelTim_DSDon.revalidate();
if(a==true)
{
panelTim_DSDon.add(new JLabel("Tìm hết các móc thời gian")).setSize(panelTim_DSDon.getSize());;
}
else if(b==true)
{
dateChooser_DSHD = new JDateChooser();
dateChooser_DSHD.setDateFormatString("dd / MM /yyyy");
dateChooser_DSHD.setLocale(new Locale("vi", "VN"));
dateChooser_DSHD.setSize(panelTim_DSDon.getSize());
panelTim_DSDon.add(dateChooser_DSHD);
}
else if(c==true)
{
monthChooser_DSHD = new JMonthChooser();
monthChooser_DSHD .setMonth(0);
monthChooser_DSHD .setLocale(new Locale("vi", "VN"));
monthChooser_DSHD .setSize(panelTim_DSDon.getSize());
panelTim_DSDon.add(monthChooser_DSHD );
}
else if(d==true)
{
yearChooser_DSHD = new JYearChooser();
yearChooser_DSHD.setSize(panelTim_DSDon.getSize());
panelTim_DSDon.add(yearChooser_DSHD);
}
}
public void LoadJCalender_Doanhthu(boolean a, boolean b,boolean c,boolean d)
{
panel_DoanhThu.removeAll();
panel_DoanhThu.repaint();
panel_DoanhThu.revalidate();
if(a==true)
{
panel_DoanhThu.add(new JLabel("Tìm hết các móc thời gian")).setSize(panel_DoanhThu.getSize());;
}
else if(b==true)
{
dateChooser_DoanhThu = new JDateChooser();
dateChooser_DoanhThu.setDateFormatString("dd / MM /yyyy");
dateChooser_DoanhThu.setLocale(new Locale("vi", "VN"));
dateChooser_DoanhThu.setSize(panel_DoanhThu.getSize());
panel_DoanhThu.add(dateChooser_DoanhThu);
}
else if(c==true)
{
monthChooser_DoanhThu = new JMonthChooser();
monthChooser_DoanhThu.setMonth(0);
monthChooser_DoanhThu.setLocale(new Locale("vi", "VN"));
monthChooser_DoanhThu.setSize(panel_DoanhThu.getSize());
panel_DoanhThu.add(monthChooser_DoanhThu);
}
else if(d==true)
{
yearChooser_DoanhThu = new JYearChooser();
yearChooser_DoanhThu.setSize(panel_DoanhThu.getSize());
panel_DoanhThu.add(yearChooser_DoanhThu);
}
}
}
| [
"dinhchien.se@gmail.com"
] | dinhchien.se@gmail.com |
893fb75c16e05706a013db94448aa5f3f908f3b2 | 44298254e00bbac5a459bfe680161f5053d5530c | /app/src/main/java/com/fanting/aidongtan/adapter/SportWikiAdapter.java | cbffc15f8f42bf4e6ff41c317cd5109878470619 | [] | no_license | FightTech/aidong | 64e95be5363b2be3d1038a94e905f4a0e830ad9b | 0e2948df266203f4cfcf8e23b6c19dee74e07867 | refs/heads/master | 2021-09-04T22:06:44.505118 | 2018-01-22T14:58:13 | 2018-01-22T14:58:13 | 112,009,587 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,075 | java | package com.fanting.aidongtan.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.fanting.aidongtan.R;
/**
* Created by Administrator on 2018/1/7.
*/
public class SportWikiAdapter extends RecyclerView.Adapter {
private Context context;
public SportWikiAdapter(Context context) {
this.context = context;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(context).inflate(R.layout.item_sport_wiki,parent,false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
}
@Override
public int getItemCount() {
return 5;
}
class MyViewHolder extends RecyclerView.ViewHolder{
public MyViewHolder(View itemView) {
super(itemView);
}
}
}
| [
"760993807@qq.com"
] | 760993807@qq.com |
5ea0b982afe85d474203a2a3edbc413b93533c5f | 61b38d9d7b116d20fc8b42a3210bf17b23417a3f | /src/de/pnientiedt/main/Renderer.java | d35a396475f0388eaf4b844c8482eee1c27ada84 | [] | no_license | pnientiedt/space-invaders | 5a2fe709855f0763a9088f3dcff970ec01922b42 | 751491bab0ed951aede38050d2ff4c424769bdea | refs/heads/master | 2021-04-12T01:25:16.017423 | 2014-03-24T09:07:43 | 2014-03-24T09:07:43 | 249,073,987 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,047 | java | package de.pnientiedt.main;
import java.util.ArrayList;
import javax.microedition.khronos.opengles.GL10;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLU;
import android.util.Log;
import de.pnientiedt.generic.Font;
import de.pnientiedt.generic.GameActivity;
import de.pnientiedt.generic.Mesh;
import de.pnientiedt.generic.MeshLoader;
import de.pnientiedt.generic.Texture;
import de.pnientiedt.generic.Font.FontStyle;
import de.pnientiedt.generic.Font.Text;
import de.pnientiedt.generic.Mesh.PrimitiveType;
import de.pnientiedt.generic.Texture.TextureFilter;
import de.pnientiedt.generic.Texture.TextureWrap;
import de.pnientiedt.simulation.Block;
import de.pnientiedt.simulation.Explosion;
import de.pnientiedt.simulation.Invader;
import de.pnientiedt.simulation.Ship;
import de.pnientiedt.simulation.Shot;
import de.pnientiedt.simulation.Simulation;
public class Renderer {
private Mesh shipMesh;
private Texture shipTextur;
private Mesh invaderMesh;
private Texture invaderTextur;
private Mesh blockMesh;
private Mesh shotMesh;
private Mesh backgroundMesh;
private Texture backgroundTextur;
private Mesh explosionMesh;
private Texture explosionTextur;
private Font font;
private Text text;
private float invaderAngle = 0;
private int lastScore = 0;
private int lastLives = 0;
private int lastWave = 0;
public Renderer(GL10 gl, GameActivity activity) {
try {
shipMesh = MeshLoader.loadObj(gl, activity.getAssets().open("ship.obj"));
invaderMesh = MeshLoader.loadObj(gl, activity.getAssets().open("invader.obj"));
blockMesh = MeshLoader.loadObj(gl, activity.getAssets().open("block.obj"));
shotMesh = MeshLoader.loadObj(gl, activity.getAssets().open("shot.obj"));
backgroundMesh = new Mesh(gl, 4, false, true, false);
backgroundMesh.texCoord(0, 0);
backgroundMesh.vertex(-1, 1, 0);
backgroundMesh.texCoord(1, 0);
backgroundMesh.vertex(1, 1, 0);
backgroundMesh.texCoord(1, 1);
backgroundMesh.vertex(1, -1, 0);
backgroundMesh.texCoord(0, 1);
backgroundMesh.vertex(-1, -1, 0);
explosionMesh = new Mesh(gl, 4 * 16, false, true, false);
for (int row = 0; row < 4; row++) {
for (int column = 0; column < 4; column++) {
explosionMesh.texCoord(0.25f + column * 0.25f, 0 + row * 0.25f);
explosionMesh.vertex(1, 1, 0);
explosionMesh.texCoord(0 + column * 0.25f, 0 + row * 0.25f);
explosionMesh.vertex(-1, 1, 0);
explosionMesh.texCoord(0f + column * 0.25f, 0.25f + row * 0.25f);
explosionMesh.vertex(-1, -1, 0);
explosionMesh.texCoord(0.25f + column * 0.25f, 0.25f + row * 0.25f);
explosionMesh.vertex(1, -1, 0);
}
}
} catch (Exception ex) {
Log.d("Space Invaders", "couldn't load meshes");
throw new RuntimeException(ex);
}
try {
Bitmap bitmap = BitmapFactory.decodeStream(activity.getAssets().open("ship.png"));
shipTextur = new Texture(gl, bitmap, TextureFilter.MipMap, TextureFilter.Nearest, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge);
bitmap.recycle();
bitmap = BitmapFactory.decodeStream(activity.getAssets().open("invader.png"));
invaderTextur = new Texture(gl, bitmap, TextureFilter.MipMap, TextureFilter.Nearest, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge);
bitmap.recycle();
bitmap = BitmapFactory.decodeStream(activity.getAssets().open("planet.jpg"));
backgroundTextur = new Texture(gl, bitmap, TextureFilter.Nearest, TextureFilter.Nearest, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge);
bitmap.recycle();
bitmap = BitmapFactory.decodeStream(activity.getAssets().open("explode.png"));
explosionTextur = new Texture(gl, bitmap, TextureFilter.MipMap, TextureFilter.Nearest, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge);
bitmap.recycle();
} catch (Exception ex) {
Log.d("Space Invaders", "couldn't load Texturs");
throw new RuntimeException(ex);
}
font = new Font(gl, activity.getAssets(), "font.ttf", 16, FontStyle.Plain);
text = font.newText(gl);
float[] lightColor = { 1, 1, 1, 1 };
float[] ambientLightColor = { 0.0f, 0.0f, 0.0f, 1 };
gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_AMBIENT, ambientLightColor, 0);
gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_DIFFUSE, lightColor, 0);
gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_SPECULAR, lightColor, 0);
}
public void render(GL10 gl, GameActivity activity, Simulation simulation) {
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
gl.glViewport(0, 0, activity.getViewportWidth(), activity.getViewportHeight());
gl.glEnable(GL10.GL_TEXTURE_2D);
renderBackground(gl);
gl.glEnable(GL10.GL_DEPTH_TEST);
gl.glEnable(GL10.GL_CULL_FACE);
setProjectionAndCamera(gl, simulation.getShip(), activity);
setLighting(gl);
renderShip(gl, simulation.getShip(), activity);
renderInvaders(gl, simulation.getInvaders());
gl.glDisable(GL10.GL_TEXTURE_2D);
renderBlocks(gl, simulation.getBlocks());
gl.glDisable(GL10.GL_LIGHTING);
renderShots(gl, simulation.getShots());
gl.glEnable(GL10.GL_TEXTURE_2D);
renderExplosions(gl, simulation.getExplosions());
gl.glDisable(GL10.GL_CULL_FACE);
gl.glDisable(GL10.GL_DEPTH_TEST);
set2DProjection(gl, activity);
gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glTranslatef(0, activity.getViewportHeight(), 0);
if (simulation.getShip().getLives() != lastLives || simulation.getScore() != lastScore || simulation.getWave() != lastWave) {
text.setText("lives: " + simulation.getShip().getLives() + " wave: " + simulation.getWave() + " score: " + simulation.getScore());
lastLives = simulation.getShip().getLives();
lastScore = simulation.getScore();
lastWave = simulation.getWave();
}
text.render();
gl.glDisable(GL10.GL_BLEND);
gl.glDisable(GL10.GL_TEXTURE_2D);
invaderAngle += activity.getDeltaTime() * 90;
if (invaderAngle > 360)
invaderAngle -= 360;
}
private void renderBackground(GL10 gl) {
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
backgroundTextur.bind();
backgroundMesh.render(PrimitiveType.TriangleFan);
}
private void setProjectionAndCamera(GL10 gl, Ship ship, GameActivity activity) {
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
float aspectRatio = (float) activity.getViewportWidth() / activity.getViewportHeight();
GLU.gluPerspective(gl, 67, aspectRatio, 1, 1000);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
GLU.gluLookAt(gl, ship.getPosition().x, 6, 2, ship.getPosition().x, 0, -4, 0, 1, 0);
}
private void set2DProjection(GL10 gl, GameActivity activity) {
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
GLU.gluOrtho2D(gl, 0, activity.getViewportWidth(), 0, activity.getViewportHeight());
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
}
float[] direction = { 1, 0.5f, 0, 0 };
private void setLighting(GL10 gl) {
gl.glEnable(GL10.GL_LIGHTING);
gl.glEnable(GL10.GL_LIGHT0);
gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, direction, 0);
gl.glEnable(GL10.GL_COLOR_MATERIAL);
}
private void renderShip(GL10 gl, Ship ship, GameActivity activity) {
if (ship.isExploding())
return;
shipTextur.bind();
gl.glPushMatrix();
gl.glTranslatef(ship.getPosition().x, ship.getPosition().y, ship.getPosition().z);
gl.glRotatef(45 * (-activity.getAccelerationOnYAxis() / 5), 0, 0, 1);
gl.glRotatef(180, 0, 1, 0);
shipMesh.render(PrimitiveType.Triangles);
gl.glPopMatrix();
}
private void renderInvaders(GL10 gl, ArrayList<Invader> invaders) {
invaderTextur.bind();
for (int i = 0; i < invaders.size(); i++) {
Invader invader = invaders.get(i);
gl.glPushMatrix();
gl.glTranslatef(invader.getPosition().x, invader.getPosition().y, invader.getPosition().z);
gl.glRotatef(invaderAngle, 0, 1, 0);
invaderMesh.render(PrimitiveType.Triangles);
gl.glPopMatrix();
}
}
private void renderBlocks(GL10 gl, ArrayList<Block> blocks) {
gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glColor4f(0.2f, 0.2f, 1, 0.7f);
for (int i = 0; i < blocks.size(); i++) {
Block block = blocks.get(i);
gl.glPushMatrix();
gl.glTranslatef(block.getPosition().x, block.getPosition().y, block.getPosition().z);
blockMesh.render(PrimitiveType.Triangles);
gl.glPopMatrix();
}
gl.glColor4f(1, 1, 1, 1);
gl.glDisable(GL10.GL_BLEND);
}
private void renderShots(GL10 gl, ArrayList<Shot> shots) {
gl.glColor4f(1, 1, 0, 1);
for (int i = 0; i < shots.size(); i++) {
Shot shot = shots.get(i);
gl.glPushMatrix();
gl.glTranslatef(shot.getPosition().x, shot.getPosition().y, shot.getPosition().z);
shotMesh.render(PrimitiveType.Triangles);
gl.glPopMatrix();
}
gl.glColor4f(1, 1, 1, 1);
}
private void renderExplosions(GL10 gl, ArrayList<Explosion> explosions) {
gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
explosionTextur.bind();
for (int i = 0; i < explosions.size(); i++) {
Explosion explosion = explosions.get(i);
gl.glPushMatrix();
gl.glTranslatef(explosion.getPosition().x, explosion.getPosition().y, explosion.getPosition().z);
explosionMesh.render(PrimitiveType.TriangleFan, (int) ((explosion.getAliveTime() / Explosion.EXPLOSION_LIVE_TIME) * 15) * 4, 4);
gl.glPopMatrix();
}
gl.glDisable(GL10.GL_BLEND);
}
public void dispose() {
shipTextur.dispose();
invaderTextur.dispose();
backgroundTextur.dispose();
explosionTextur.dispose();
font.dispose();
text.dispose();
explosionMesh.dispose();
shipMesh.dispose();
invaderMesh.dispose();
shotMesh.dispose();
blockMesh.dispose();
backgroundMesh.dispose();
}
}
| [
"phillipnientiedt@gmail.com"
] | phillipnientiedt@gmail.com |
a874b7c8e7d37b31526bf108b98b266a8daa0cab | 20c5d4e75e22904255e94b1614aaaf3c396c6f66 | /Biblioteca/Biblioteca/src/java/Model/Conexao/ConnectionPool.java | 8798e015073f21957cc2cec6ab9ec7cffa841d4d | [] | no_license | thiagotste/Testes | 292c0848d54b38670d867bbdd1c9b8bbf47d954f | 810904b612e7680aee5bb048b03ab2135d576873 | refs/heads/master | 2020-03-18T00:34:28.859187 | 2018-10-15T23:55:00 | 2018-10-15T23:55:00 | 134,101,800 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,109 | java | package Model.Conexao;
import java.sql.*;
import javax.sql.DataSource;
import javax.naming.InitialContext;
public class ConnectionPool {
private static ConnectionPool pool = null;
private static DataSource dataSource = null;
private ConnectionPool(){
try {
InitialContext ic = new InitialContext();
dataSource = (DataSource)
ic.lookup("java:/comp/env/jdbc/db_biblioteca");
} catch (Exception e) {
e.printStackTrace();
}
}
public static ConnectionPool getInstance(){
if(pool == null){
pool = new ConnectionPool();
}
return pool;
}
public Connection getConnection(){
try {
return dataSource.getConnection();
} catch (SQLException sqle) {
sqle.printStackTrace();
return null;
}
}
public void freeConnection(Connection c){
try {
c.close();
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
}
| [
"thiago-f_4@outlook.com"
] | thiago-f_4@outlook.com |
39f7addcb1f760aabd677106ecea6481b934e6fb | a082b37d683b9f02dd8fa1da632dbaf65c116fce | /src/main/java/com/sudeepnm/redis/sortedsets/service/RedisBean.java | d976d6dc881481125032b88eaf9ede0c22695773 | [] | no_license | vickydahiya/redis-sortedsets | f0500ab7e47daa05a4c5e5ff6b20062240c34673 | db52d124c4d61de2f9b8d8da119d8ce02878cd86 | refs/heads/master | 2022-05-05T01:34:29.217055 | 2017-10-23T00:57:22 | 2017-10-23T00:57:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,467 | java | /**
*
*/
package com.sudeepnm.redis.sortedsets.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
/**
* Value bean to read the Redis connection properties from Environment Variable
* @author Sudeep
*
*/
@Configuration
public class RedisBean {
/*
* Java buildpack translates Cloud Foundry VCAP_* environment variables
* into usable property sources in the Spring Environment
* [https://spring.io/blog/2015/04/27/binding-to-data-services-with-spring-boot-in-cloud-foundry]
*
* In this example, my-redis is the name of the Marketplace service I created
*/
@Value("${vcap.services.my-redis.connection.host}")
private String host;
@Value("${vcap.services.my-redis.connection.password}")
private String password;
@Value("${vcap.services.my-redis.connection.port}")
private String port;
/**
* @return the host
*/
public String getHost() {
return host;
}
/**
* @param host the host to set
*/
public void setHost(String host) {
this.host = host;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return the port
*/
public String getPort() {
return port;
}
/**
* @param port the port to set
*/
public void setPort(String port) {
this.port = port;
}
}
| [
"smoothed9@gmail.com"
] | smoothed9@gmail.com |
0e59d3ba1ba58d4c945ac61435d899d83b71d830 | cadd9336f71200c67f0be0559945b73e499393d4 | /src/main/java/org/wildfly/security/auth/realm/token/validator/OAuth2IntrospectValidator.java | 1682956d770d39d2ee20daf62135a1d169a2e31c | [
"Apache-2.0"
] | permissive | panossot/wildfly-elytron | 9838bef8957c9e882b02fb96eaec9a2e1e882f3d | b76ba98e95b9862998530d294956eaa4072c3b0f | refs/heads/master | 2021-01-13T15:11:55.597964 | 2016-12-08T17:50:26 | 2016-12-08T17:50:26 | 76,252,803 | 0 | 0 | null | 2016-12-12T12:04:37 | 2016-12-12T12:04:36 | null | UTF-8 | Java | false | false | 11,908 | java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2016 Red Hat, Inc., and individual 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.wildfly.security.auth.realm.token.validator;
import org.wildfly.common.Assert;
import org.wildfly.security.auth.realm.token.TokenValidator;
import org.wildfly.security.auth.server.RealmUnavailableException;
import org.wildfly.security.authz.Attributes;
import org.wildfly.security.evidence.BearerTokenEvidence;
import org.wildfly.security.util.ByteStringBuilder;
import org.wildfly.security.util.CodePointIterator;
import javax.json.Json;
import javax.json.JsonObject;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import static org.wildfly.security._private.ElytronMessages.log;
import static org.wildfly.security.util.JsonUtil.toAttributes;
/**
* A RFC-7662 (OAuth2 Token Introspection) compliant {@link TokenValidator}.
*
* @author <a href="mailto:psilva@redhat.com">Pedro Igor</a>
*/
public class OAuth2IntrospectValidator implements TokenValidator {
/**
* Returns a {@link Builder} instance that can be used to configure and create a {@link OAuth2IntrospectValidator}.
*
* @return the {@link Builder}
*/
public static Builder builder() {
return new Builder();
}
private final URL tokenIntrospectionUrl;
private final String clientId;
private final String clientSecret;
private final SSLContext sslContext;
private final HostnameVerifier hostnameVerifier;
OAuth2IntrospectValidator(Builder configuration) {
this.tokenIntrospectionUrl = Assert.checkNotNullParam("tokenIntrospectionUrl", configuration.tokenIntrospectionUrl);
this.clientId = Assert.checkNotNullParam("clientId", configuration.clientId);
this.clientSecret = Assert.checkNotNullParam("clientSecret", configuration.clientSecret);
if (tokenIntrospectionUrl.getProtocol().equalsIgnoreCase("https")) {
if (configuration.sslContext == null) {
throw log.tokenRealmOAuth2SSLContextNotSpecified(tokenIntrospectionUrl);
}
if (configuration.hostnameVerifier == null) {
throw log.tokenRealmOAuth2HostnameVerifierNotSpecified(tokenIntrospectionUrl);
}
}
this.sslContext = configuration.sslContext;
this.hostnameVerifier = configuration.hostnameVerifier;
}
@Override
public Attributes validate(BearerTokenEvidence evidence) throws RealmUnavailableException {
Assert.checkNotNullParam("evidence", evidence);
try {
JsonObject claims = introspectAccessToken(this.tokenIntrospectionUrl,
this.clientId, this.clientSecret, evidence.getToken(), this.sslContext, this.hostnameVerifier);
if (isValidToken(claims)) {
return toAttributes(claims);
}
} catch (Exception e) {
throw log.tokenRealmOAuth2TokenIntrospectionFailed(e);
}
return null;
}
private boolean isValidToken(JsonObject claims) {
return claims != null && claims.getBoolean("active", false);
}
/**
* Introspects an OAuth2 Access Token using a RFC-7662 compatible endpoint.
*
* @param tokenIntrospectionUrl an {@link URL} pointing to a RFC-7662 compatible endpoint
* @param clientId the identifier of a client within the OAUth2 Authorization Server
* @param clientSecret the secret of the client
* @param token the access token to introspect
* @param sslContext the ssl context
* @param hostnameVerifier the hostname verifier
* @return a @{JsonObject} representing the response from the introspection endpoint or null if
*/
private JsonObject introspectAccessToken(URL tokenIntrospectionUrl, String clientId, String clientSecret, String token, SSLContext sslContext, HostnameVerifier hostnameVerifier) throws RealmUnavailableException {
Assert.checkNotNullParam("clientId", clientId);
Assert.checkNotNullParam("clientSecret", clientSecret);
Assert.checkNotNullParam("token", token);
HttpURLConnection connection = null;
try {
connection = openConnection(tokenIntrospectionUrl, sslContext, hostnameVerifier);
HashMap<String, String> parameters = new HashMap<>();
parameters.put("token", token);
parameters.put("token_type_hint", "access_token");
byte[] params = buildParameters(parameters);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", String.valueOf(params.length));
connection.setRequestProperty("Authorization", "Basic " + CodePointIterator.ofString(clientId + ":" + clientSecret).asUtf8().base64Encode().drainToString());
try (OutputStream outputStream = connection.getOutputStream()) {
outputStream.write(params);
}
try (InputStream inputStream = new BufferedInputStream(connection.getInputStream())) {
return Json.createReader(inputStream).readObject();
}
} catch (IOException ioe) {
if (connection != null && connection.getErrorStream() != null) {
InputStream errorStream = connection.getErrorStream();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream))) {
StringBuffer response = reader.lines().reduce(new StringBuffer(), StringBuffer::append, (buffer1, buffer2) -> buffer1);
log.errorf(ioe, "Unexpected response from token introspection endpoint [%s]. Response: [%s]", tokenIntrospectionUrl, response);
} catch (IOException e) {
throw log.tokenRealmOAuth2TokenIntrospectionFailed(ioe);
}
} else {
throw log.tokenRealmOAuth2TokenIntrospectionFailed(ioe);
}
} catch (Exception e) {
throw log.tokenRealmOAuth2TokenIntrospectionFailed(e);
}
return null;
}
private HttpURLConnection openConnection(URL url, SSLContext sslContext, HostnameVerifier hostnameVerifier) throws IOException {
Assert.checkNotNullParam("url", url);
boolean isHttps = url.getProtocol().equalsIgnoreCase("https");
if (isHttps) {
if (sslContext == null) {
throw log.tokenRealmOAuth2SSLContextNotSpecified(url);
}
if (hostnameVerifier == null) {
throw log.tokenRealmOAuth2HostnameVerifierNotSpecified(url);
}
}
try {
log.debugf("Opening connection to token introspection endpoint [%s]", url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if (isHttps) {
HttpsURLConnection https = (HttpsURLConnection) connection;
https.setSSLSocketFactory(sslContext.getSocketFactory());
https.setHostnameVerifier(hostnameVerifier);
}
return connection;
} catch (IOException cause) {
throw cause;
}
}
private byte[] buildParameters(Map<String, String> parameters) throws UnsupportedEncodingException {
ByteStringBuilder params = new ByteStringBuilder();
parameters.entrySet().stream().forEach(entry -> {
if (params.length() > 0) {
params.append('&');
}
params.append(entry.getKey()).append('=').append(entry.getValue());
});
return params.toArray();
}
public static class Builder {
private String clientId;
private String clientSecret;
private URL tokenIntrospectionUrl;
private SSLContext sslContext;
private HostnameVerifier hostnameVerifier;
private Builder() {
}
/**
* An {@link URL} pointing to a RFC-7662 OAuth2 Token Introspection compatible endpoint.
*
* @param url the token introspection endpoint
* @return this instance
*/
public Builder tokenIntrospectionUrl(URL url) {
this.tokenIntrospectionUrl = url;
return this;
}
/**
* <p>The identifier of a client registered within the OAuth2 Authorization Server that will be used to authenticate this server
* in order to validate bearer tokens arriving to this server.
*
* <p>Please note that the client will be usually a confidential client with both an identifier and secret configured in order to
* authenticate against the token introspection endpoint. In this case, the endpoint must support HTTP BASIC authentication using
* the client credentials (both id and secret).
*
* @param clientId the identifier of a client within the OAUth2 Authorization Server
* @return this instance
*/
public Builder clientId(String clientId) {
this.clientId = clientId;
return this;
}
/**
* The secret of the client identified by the given {@link #clientId}.
*
* @param clientSecret the secret of the client
* @return this instance
*/
public Builder clientSecret(String clientSecret) {
this.clientSecret = clientSecret;
return this;
}
/**
* <p>A predefined {@link SSLContext} that will be used to connect to the token introspection endpoint when using SSL/TLS. This configuration is mandatory
* if the given token introspection url is using SSL/TLS.
*
* @param sslContext the SSL context
* @return this instance
*/
public Builder useSslContext(SSLContext sslContext) {
this.sslContext = sslContext;
return this;
}
/**
* A {@link HostnameVerifier} that will be used to validate the hostname when using SSL/TLS. This configuration is mandatory
* if the given token introspection url is using SSL/TLS.
*
* @param hostnameVerifier the hostname verifier
* @return this instance
*/
public Builder useSslHostnameVerifier(HostnameVerifier hostnameVerifier) {
this.hostnameVerifier = hostnameVerifier;
return this;
}
/**
* Returns a {@link OAuth2IntrospectValidator} instance based on all the configuration provided with this builder.
*
* @return a new {@link OAuth2IntrospectValidator} instance with all the given configuration
*/
public OAuth2IntrospectValidator build() {
return new OAuth2IntrospectValidator(this);
}
}
}
| [
"pedroigor@gmail.com"
] | pedroigor@gmail.com |
d33ca466c58a16498afa177c2e1abaafcc8707b7 | 6a7966384ce4d278b922f66c08f8d266f9255d7e | /app/src/main/java/com/dimfcompany/signpdfapp/ui/act_profile_dialog/ActProfileDialog.java | 62761ab78b66949dadc70a2596190021d5674e69 | [] | no_license | bios90/SignPdfApp | 87a07b9e99087407160b6dc4bc71c3991deee483 | ef671cbe9d6a2e5983924648cd9c75be0c2a5e2d | refs/heads/master | 2020-05-17T05:07:55.264774 | 2019-09-21T08:45:56 | 2019-09-21T08:45:56 | 183,523,353 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,251 | java | package com.dimfcompany.signpdfapp.ui.act_profile_dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.Nullable;
import com.dimfcompany.signpdfapp.base.Constants;
import com.dimfcompany.signpdfapp.base.activity.BaseActivity;
import com.dimfcompany.signpdfapp.local_db.raw.LocalDatabase;
import com.dimfcompany.signpdfapp.local_db.sharedprefs.SharedPrefsHelper;
import com.dimfcompany.signpdfapp.models.Model_Document;
import com.dimfcompany.signpdfapp.models.Model_User;
import com.dimfcompany.signpdfapp.networking.Downloader;
import com.dimfcompany.signpdfapp.networking.helpers.HelperUser;
import com.dimfcompany.signpdfapp.sync.SyncManager;
import com.dimfcompany.signpdfapp.sync.Synchronizer;
import com.dimfcompany.signpdfapp.utils.FileManager;
import com.dimfcompany.signpdfapp.utils.GlobalHelper;
import com.dimfcompany.signpdfapp.utils.MessagesManager;
import java.util.List;
import javax.inject.Inject;
public class ActProfileDialog extends BaseActivity implements ActProfileDialogMvp.ViewListener, HelperUser.CallbackGetDocsCount, HelperUser.CallbackUserRoleName, SyncManager.CallbackSyncFromServer
{
private static final String TAG = "ActProfileDialog";
@Inject
MessagesManager messagesManager;
@Inject
SharedPrefsHelper sharedPrefsHelper;
@Inject
HelperUser helperUser;
@Inject
GlobalHelper globalHelper;
@Inject
Downloader downloader;
@Inject
LocalDatabase localDatabase;
@Inject
FileManager fileManager;
@Inject
Synchronizer synchronizer;
Model_User user;
ActProfileDialogMvp.MvpView mvpView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getPresenterComponent().inject(this);
mvpView = viewMvcFactory.getActProfileDialogMvpView(null);
mvpView.registerListener(this);
setContentView(mvpView.getRootView());
}
@Override
protected void onStart()
{
super.onStart();
user = sharedPrefsHelper.getUserFromSharedPrefs();
if (user == null)
{
return;
}
String name = user.getLast_name() + " " + user.getFirst_name();
mvpView.setUserName(name);
mvpView.setUserEmail(user.getEmail());
loadInfo();
}
private void loadInfo()
{
if (user == null || !globalHelper.isNetworkAvailable())
{
return;
}
helperUser.getDocsCount(user.getId(), this);
helperUser.getUserRoleName(user.getId(), this);
}
@Override
public void clickedSync()
{
if (!GlobalHelper.isNetworkAvailable())
{
messagesManager.showNoInternetAlerter();
return;
}
if (user == null)
{
return;
}
messagesManager.showProgressDialog();
synchronizer.syncronizeNotSynced(new SyncManager.CallbackSyncronizeNoSynced()
{
@Override
public void onSuccessSync()
{
synchronizer.makeSyncFromServer(ActProfileDialog.this);
}
@Override
public void onErrorSync()
{
Log.e(TAG, "onErrorSync: Error on pre sync");
messagesManager.dismissProgressDialog();
messagesManager.showRedAlerter("Не удалось загрузить документы");
}
});
}
@Override
public void clickedExit()
{
messagesManager.showSimpleDialog("Выход", "Выйти из аккаунта?", "Выйти", "Отмена", new MessagesManager.DialogButtonsListener()
{
@Override
public void onOkClicked(DialogInterface dialog)
{
dialog.dismiss();
sharedPrefsHelper.clearUserLocalData();
navigationManager.toActFirst(null);
finish();
}
@Override
public void onCancelClicked(DialogInterface dialog)
{
dialog.dismiss();
}
});
}
@Override
public void onSuccessGetDocsCount(Integer count)
{
mvpView.setDogovorCount(count);
}
@Override
public void onSuccessGetUserRole(String roleName)
{
mvpView.setRoleName(roleName);
}
@Override
protected void onDestroy()
{
mvpView.unregisterListener(this);
super.onDestroy();
}
@Override
public void onSuccessSyncFromServer()
{
messagesManager.dismissProgressDialog();
messagesManager.showGreenAlerter("База успешно синхронизирована");
sendBroadcast(new Intent(Constants.BROADCAST_UPDATE_FINISHED_UI));
}
@Override
public void onErrorSyncFromServer()
{
messagesManager.dismissProgressDialog();
messagesManager.showRedAlerter("Не удалось загрузить документы");
}
@Override
public void clickedEditUser()
{
navigationManager.toActUserAuthDialog(null, user.getId());
}
}
| [
"bios90@mail.ru"
] | bios90@mail.ru |
30b7bab5d21912cf2e9cde2ddf554b10a2695786 | 04a10fecc1a1a7538b550639ff21c362c4a35df8 | /src/StudentCourse/Course.java | 9b06f221b0655bbc0754b8d057ecc1340ea0b718 | [] | no_license | ahmedalashii/PR3Assignment4 | 6e6ffdcc84893f0d244295be123fb3497f6cbb70 | 9669983ba8a1a613a340a88d8ddfafa5cf9bf83f | refs/heads/master | 2023-05-13T20:22:38.628125 | 2021-06-02T20:03:59 | 2021-06-02T20:03:59 | 373,287,188 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 642 | java | package StudentCourse;
public class Course {
private String id;
private String name;
private String room;
public Course(String id, String name, String room) {
this.id = id;
this.name = name;
this.room = room;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRoom() {
return room;
}
public void setRoom(String room) {
this.room = room;
}
}
| [
"AHmED AlAsHi@DESKTOP-U5190AG"
] | AHmED AlAsHi@DESKTOP-U5190AG |
a486d27c5029be314d71e64be58250f72bcb2295 | e546bd09628701a4e1b509f075d5d46770faf277 | /Functional/src/examples/AnonymousClassThreadExample.java | 6269a6b90f09cd7c83da9c77147da8325ff52c20 | [] | no_license | Olsm/PG4100-Exercises | dd449fe8722d377a41cac8d4bff61428a9fc3f5c | f4fe8b492aaae63d4aef417664395ed1de3ce6d5 | refs/heads/master | 2021-01-10T16:00:57.488399 | 2016-03-24T19:16:51 | 2016-03-24T19:16:51 | 49,580,238 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 344 | java | package examples;
public class AnonymousClassThreadExample {
public static void main(String... args) {
new AnonymousClassThreadExample().runExample();
}
private void runExample() {
Runnable run = new Runnable() {
public void run() {
System.out.println("hello world");
}
};
new Thread(run).start();
}
}
| [
"per.lauvaas@gmail.com"
] | per.lauvaas@gmail.com |
0b129f266984b7c68b1a8e4f33f9fb1bf9bf3bd9 | c6f0dfc6349305e1ae96918ddebada253a03c20f | /src/二叉树/DFS与递归/HasPathSum.java | f03d35674d555b0fdb5796e49c608e3ed2a10797 | [] | no_license | KaguyaShinomiya/LeetCodeGuidebook | 8cbdc2021ca31590d7db7d816322960cd3cca4e4 | 40408607a9bc24bc965597d84be6b6ef9701651d | refs/heads/master | 2023-02-20T21:01:58.168014 | 2021-01-19T16:37:57 | 2021-01-19T16:37:57 | 310,035,017 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 932 | java | package 二叉树.DFS与递归;
import utils.TreeNode;
/**
* The Class: HasPathSum
* 112. 路径总和
* https://leetcode-cn.com/problems/path-sum/
*
* 给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。
* 说明: 叶子节点是指没有子节点的节点。
*
* @author: Kaguya Y
* @since: 2020-12-02 01:01
*/
public class HasPathSum {
/**
* 解法1: 递归
* 拆解为子问题hasPathSum(root.left, sum - root.val)和hasPathSum(root.right, sum - root.val)即可
*/
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
if (root.left == null && root.right == null) {
return sum == root.val;
}
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
}
}
| [
"1154611508@qq.com"
] | 1154611508@qq.com |
b3d13d8b66d306e26f22ba5d407ec4a978726c2e | 0ce4ab3d794ea7b2f0caf89c747d0ffd0e692c88 | /src/test/lombok/de/larssh/jes/parser/JesFtpFileEntryParserTest.java | e3224ebcaeadb16d7999a5d1ab403decb374ca7a | [
"MIT"
] | permissive | lars-sh/jes-client | 98b7db5c3509f4ec96005201f965657a77ebb79e | 0d6001708b2fe91b74d439b54328c1fef55c513b | refs/heads/master | 2023-06-22T06:34:53.323174 | 2023-06-08T15:44:08 | 2023-06-08T15:44:08 | 161,603,874 | 1 | 3 | MIT | 2023-06-08T15:44:09 | 2018-12-13T07:58:00 | Java | UTF-8 | Java | false | false | 11,555 | java | package de.larssh.jes.parser;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.io.UncheckedIOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.Set;
import java.util.function.Supplier;
import org.junit.jupiter.api.Test;
import de.larssh.jes.Job;
import de.larssh.jes.JobFlag;
import de.larssh.jes.JobStatus;
import de.larssh.utils.SneakyException;
import de.larssh.utils.collection.Maps;
import lombok.NoArgsConstructor;
/**
* {@link JesFtpFileEntryParser}
*/
@NoArgsConstructor
public final class JesFtpFileEntryParserTest {
private static final JesFtpFileEntryParser INSTANCE = new JesFtpFileEntryParser();
private static final Path PATH_FTP_INPUT;
private static final Path PATH_FTP_INPUT_THROWS;
// @formatter:off
private static final Map<String, List<Job>> PARSE_FTP_ENTRY_EXPECTED_JOBS = Maps.builder(new LinkedHashMap<String, List<Job>>())
.put("abend.txt", asList(
new Job("JOB00009", "JABC456", JobStatus.OUTPUT, "USER9", Optional.of("I"), OptionalInt.empty(), Optional.of("622")),
new Job("JOB00010", "JABC789", JobStatus.OUTPUT, "USER10", Optional.of("J"), OptionalInt.empty(), Optional.of("EC6")),
new Job("TSU08743", "USER2", JobStatus.OUTPUT, "USER2", Optional.of("TSU"), OptionalInt.empty(), Optional.of("622"))))
.put("dup.txt", singletonList(
new Job("JOB00003", "JABC678", JobStatus.INPUT, "USER3", Optional.of("C"), OptionalInt.empty(), Optional.empty(), JobFlag.DUP)))
.put("held.txt", singletonList(
new Job("JOB00002", "JABC345", JobStatus.INPUT, "USER2", Optional.of("B"), OptionalInt.empty(), Optional.empty(), JobFlag.HELD)))
.put("jcl-error.txt", singletonList(
new Job("JOB00008", "JABC123", JobStatus.OUTPUT, "USER8", Optional.of("H"), OptionalInt.empty(), Optional.empty(), JobFlag.JCL_ERROR)))
.put("not-accessible.txt", asList(
new Job("STC85256", "ABCDEF3", JobStatus.OUTPUT, "USER3", Optional.of("STC"), OptionalInt.of(0), Optional.empty(), JobFlag.HELD),
new Job("STC21743", "ABCDEF4", JobStatus.OUTPUT, "USER4", Optional.of("STC"), OptionalInt.empty(), Optional.empty(), JobFlag.HELD)))
.put("rc.txt", asList(
new Job("JOB00005", "JABC234", JobStatus.OUTPUT, "USER5", Optional.of("E"), OptionalInt.of(0), Optional.empty()),
new Job("JOB00006", "JABC567", JobStatus.OUTPUT, "USER9", Optional.of("F"), OptionalInt.of(1), Optional.empty()),
new Job("JOB00007", "JABC890", JobStatus.OUTPUT, "USER7", Optional.of("G"), OptionalInt.empty(), Optional.empty()),
new Job("STC18403", "ABCDEF2", JobStatus.OUTPUT, "USER2", Optional.of("STC"), OptionalInt.of(2), Optional.empty()),
new Job("TSU15944", "USER3", JobStatus.OUTPUT, "USER3", Optional.of("TSU"), OptionalInt.of(3), Optional.empty())))
.put("simple.txt", singletonList(
new Job("JOB00001", "JABC012", JobStatus.INPUT, "USER1", Optional.of("A"), OptionalInt.empty(), Optional.empty())))
.put("job-output-byte-count.txt", singletonList(
new Job("JOB00054", "USER1", JobStatus.OUTPUT, "USER1", Optional.of("A"), OptionalInt.of(0), Optional.empty())))
.put("job-output-empty.txt", singletonList(
new Job("JOB00054", "USER1", JobStatus.OUTPUT, "USER1", Optional.of("A"), OptionalInt.of(0), Optional.empty())))
.put("job-output-rec-count.txt", singletonList(
new Job("JOB00061", "USER3A", JobStatus.OUTPUT, "USER3", Optional.of("D"), OptionalInt.of(0), Optional.empty())))
.unmodifiable();
// @formatter:on
private static final Set<String> PARSE_FTP_ENTRY_THROWS_EXPECTED_JOBS
= Collections.unmodifiableSet(new LinkedHashSet<>(asList("sub-title.txt", "job-output.txt")));
private static final Map<String, Integer> PRE_PARSE_EXPECTED_SIZES
= Maps.builder(new LinkedHashMap<String, Integer>())
.put("abend.txt", 3)
.put("dup.txt", 1)
.put("held.txt", 1)
.put("jcl-error.txt", 1)
.put("not-accessible.txt", 2)
.put("rc.txt", 5)
.put("simple.txt", 1)
.unmodifiable();
static {
try {
PATH_FTP_INPUT = Paths.get(JesFtpFileEntryParserTest.class.getResource("ftp-input").toURI());
} catch (final URISyntaxException e) {
throw new SneakyException(e);
}
PATH_FTP_INPUT_THROWS = PATH_FTP_INPUT.resolve("throws");
// Outputs
final Job jobOutputByteCount = PARSE_FTP_ENTRY_EXPECTED_JOBS.get("job-output-byte-count.txt").get(0);
jobOutputByteCount.createOutput(1, "JESMSGLG", 1200, Optional.of("JESE"), Optional.empty(), Optional.of("H"));
jobOutputByteCount.createOutput(2, "JESJCL", 526, Optional.of("JESE"), Optional.empty(), Optional.of("H"));
jobOutputByteCount.createOutput(3, "JESYSMSG", 1255, Optional.of("JESE"), Optional.empty(), Optional.of("H"));
jobOutputByteCount.createOutput(4, "SYSUT2", 741, Optional.of("STEP57"), Optional.empty(), Optional.of("H"));
jobOutputByteCount.createOutput(5, "SYSPRINT", 209, Optional.of("STEP57"), Optional.empty(), Optional.of("A"));
final Job jobOutputRecCount = PARSE_FTP_ENTRY_EXPECTED_JOBS.get("job-output-rec-count.txt").get(0);
jobOutputRecCount.createOutput(1, "JESMSGLG", 18, Optional.of("JESE"), Optional.empty(), Optional.of("H"));
jobOutputRecCount.createOutput(2, "JESJCL", 11, Optional.of("JESE"), Optional.empty(), Optional.of("H"));
jobOutputRecCount.createOutput(3, "JESYSMSG", 22, Optional.empty(), Optional.empty(), Optional.of("A"));
}
/**
* Assert that two lists of {@link Job} are equal. If necessary, the failure
* message will be retrieved lazily from {@code messageSupplier}.
*
* <p>
* This method considers two {@code Job} objects as equal if all of their fields
* are equal. That behavior varies from {@link Job#equals(Object)}!
*
* <p>
* <b>Implementation Notice:</b> {@link Job#toString()} serializes all fields
* and therefore does a good job for comparing equality for tests. This code
* should not be used for production systems.
*
* @param expected the expected list
* @param actual the actual list
* @param messageSupplier the supplier to retrieve a failure message lazily
*/
private static void assertEqualsJobList(final List<Job> expected,
final List<Job> actual,
final Supplier<String> messageSupplier) {
assertThat(expected.toString()).isEqualTo(actual.toString(), messageSupplier);
}
/**
* {@link JesFtpFileEntryParser#parseFTPEntry(String)}
*/
@Test
public void testParseFTPEntry() {
assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> INSTANCE.parseFTPEntry(null));
assertThatExceptionOfType(JesFtpFileEntryParserException.class).isThrownBy(() -> INSTANCE.parseFTPEntry(""));
assertThatExceptionOfType(JesFtpFileEntryParserException.class).isThrownBy(() -> INSTANCE.parseFTPEntry(" "));
for (final Entry<String, List<Job>> entry : PARSE_FTP_ENTRY_EXPECTED_JOBS.entrySet()) {
final Path path = PATH_FTP_INPUT.resolve(entry.getKey());
try (BufferedReader reader = Files.newBufferedReader(path)) {
assertEqualsJobList(entry.getValue(),
INSTANCE.preParse(reader.lines().collect(toList()))
.stream()
.map(INSTANCE::parseFTPEntry)
.map(JesFtpFile::getJob)
.collect(toList()),
() -> path.toString());
} catch (final IOException e) {
throw new UncheckedIOException(e);
}
}
// throws
for (final String fileName : PARSE_FTP_ENTRY_THROWS_EXPECTED_JOBS) {
final Path path = PATH_FTP_INPUT_THROWS.resolve(fileName);
try (BufferedReader reader = Files.newBufferedReader(path)) {
assertThatExceptionOfType(JesFtpFileEntryParserException.class).isThrownBy(
() -> INSTANCE.preParse(reader.lines().collect(toList())).forEach(INSTANCE::parseFTPEntry));
} catch (final IOException e) {
throw new UncheckedIOException(e);
}
}
}
/**
* {@link JesFtpFileEntryParser#preParse(java.util.List)}
*/
@Test
public void testPreParse() {
assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> INSTANCE.preParse(null));
assertThatExceptionOfType(JesFtpFileEntryParserException.class)
.isThrownBy(() -> INSTANCE.preParse(emptyList()));
assertThatExceptionOfType(JesFtpFileEntryParserException.class)
.isThrownBy(() -> INSTANCE.preParse(Arrays.asList(" ")));
for (final Entry<String, Integer> entry : PRE_PARSE_EXPECTED_SIZES.entrySet()) {
final Path path = PATH_FTP_INPUT.resolve(entry.getKey());
try (BufferedReader reader = Files.newBufferedReader(path)) {
assertThat(entry.getValue()).describedAs(path.toString())
.isEqualTo(INSTANCE.preParse(reader.lines().collect(toList())).size());
} catch (final IOException e) {
throw new UncheckedIOException(e);
}
}
}
/**
* {@link JesFtpFileEntryParser#readNextEntry(BufferedReader)}
*/
@Test
public void testReadNextEntry() {
try {
assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> INSTANCE.readNextEntry(null));
assertThat(INSTANCE.readNextEntry(new BufferedReader(new StringReader("")))).isNull();
try (BufferedReader reader = new BufferedReader(new StringReader("\n"))) {
assertThat("").isEqualTo(INSTANCE.readNextEntry(reader));
assertThat(INSTANCE.readNextEntry(reader)).isNull();
}
try (BufferedReader reader = new BufferedReader(new StringReader("\r\n"))) {
assertThat("").isEqualTo(INSTANCE.readNextEntry(reader));
assertThat(INSTANCE.readNextEntry(reader)).isNull();
}
try (BufferedReader reader = new BufferedReader(new StringReader("\r"))) {
assertThat("").isEqualTo(INSTANCE.readNextEntry(reader));
assertThat(INSTANCE.readNextEntry(reader)).isNull();
}
try (BufferedReader reader = new BufferedReader(new StringReader("a"))) {
assertThat("a").isEqualTo(INSTANCE.readNextEntry(reader));
assertThat(INSTANCE.readNextEntry(reader)).isNull();
}
try (BufferedReader reader = new BufferedReader(new StringReader("a\n"))) {
assertThat("a").isEqualTo(INSTANCE.readNextEntry(reader));
assertThat(INSTANCE.readNextEntry(reader)).isNull();
}
try (BufferedReader reader = new BufferedReader(new StringReader("a\nb"))) {
assertThat("a").isEqualTo(INSTANCE.readNextEntry(reader));
assertThat("b").isEqualTo(INSTANCE.readNextEntry(reader));
assertThat(INSTANCE.readNextEntry(reader)).isNull();
}
try (BufferedReader reader = new BufferedReader(new StringReader("a\n\nb"))) {
assertThat("a").isEqualTo(INSTANCE.readNextEntry(reader));
assertThat("").isEqualTo(INSTANCE.readNextEntry(reader));
assertThat("b").isEqualTo(INSTANCE.readNextEntry(reader));
assertThat(INSTANCE.readNextEntry(reader)).isNull();
}
try (BufferedReader reader = new BufferedReader(new StringReader("a\r\nb"))) {
assertThat("a").isEqualTo(INSTANCE.readNextEntry(reader));
assertThat("b").isEqualTo(INSTANCE.readNextEntry(reader));
assertThat(INSTANCE.readNextEntry(reader)).isNull();
}
} catch (final IOException e) {
throw new UncheckedIOException(e);
}
}
}
| [
"mail@lars-sh.de"
] | mail@lars-sh.de |
a4a1858f4c1aca85a9231bb0ab5d48420aebf401 | b4086052ebc0736a0224a203bf7ffe491a874148 | /org/liuyaping/demo/datastruct/Node.java | 250a068a0da8e270306a34a97d7bff5fa11edf5a | [] | no_license | applesline/demo | 84a855caa126f9ac5cda225d527b5efd7897882c | e6f6a9d18531440b6b11aa814356cb7c29819aa8 | refs/heads/master | 2022-05-28T06:04:26.158309 | 2020-05-01T10:31:29 | 2020-05-01T10:31:29 | 114,860,959 | 1 | 0 | null | null | null | null | GB18030 | Java | false | false | 638 | java | /**
*
*/
package org.liuyaping.demo.datastruct;
/**
* 循环列表节点
*
* @author liuyaping
*
* 创建时间:2018年1月5日
*/
public class Node {
private Node preNode;
private Node nextNode;
private Object data;
public Node(Object data) {
this.data = data;
}
public Node getPreNode() {
return preNode;
}
public void setPreNode(Node preNode) {
this.preNode = preNode;
}
public Node getNextNode() {
return nextNode;
}
public void setNextNode(Node nextNode) {
this.nextNode = nextNode;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
} | [
"applesline@163.com"
] | applesline@163.com |
b0522b89f3a69f0e68f060ccba3646e1f48dd171 | cac785532488f99b12b47f2cadc1b3302b181765 | /src/main/java/com/github/lbroudoux/elasticsearch/river/s3/rest/S3ManageAction.java | 7f7f0d5e171e3fc187c35a3096e965650a98a2bc | [
"Apache-2.0"
] | permissive | harrisj/es-amazon-s3-river | d101c2f29423c2cdd1bd99026d8584ad78fe78e2 | a7c42ece22a63b75bd19fad405e0b91da8d11a34 | refs/heads/master | 2020-12-25T08:38:19.494111 | 2015-04-27T16:12:40 | 2015-04-27T16:12:40 | 31,087,975 | 1 | 3 | null | 2015-02-20T22:21:12 | 2015-02-20T22:21:12 | null | UTF-8 | Java | false | false | 3,870 | java | /*
* Licensed to Laurent Broudoux (the "Author") under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Author licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.github.lbroudoux.elasticsearch.river.s3.rest;
import java.io.IOException;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentBuilderString;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.RestRequest.Method;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
/**
* REST actions definition for starting and stopping an Amazon S3 river.
* @author laurent
*/
public class S3ManageAction extends BaseRestHandler{
/** The constant for 'start river' command. */
public static final String START_COMMAND = "_start";
/** The constant for 'stop river' command. */
public static final String STOP_COMMAND = "_stop";
@Inject
public S3ManageAction(Settings settings, Client client, RestController controller){
super(settings, client);
// Define S3 REST endpoints.
controller.registerHandler(Method.GET, "/_s3/{rivername}/{command}", this);
}
@Override
public void handleRequest(RestRequest request, RestChannel channel, Client client) throws Exception{
if (logger.isDebugEnabled()){
logger.debug("REST S3ManageAction called");
}
String rivername = request.param("rivername");
String command = request.param("command");
String status = null;
if (START_COMMAND.equals(command)){
status = "STARTED";
} else if (STOP_COMMAND.equals(command)){
status = "STOPPED";
}
try{
if (status != null){
XContentBuilder xb = jsonBuilder()
.startObject()
.startObject("amazon-s3")
.field("feedname", rivername)
.field("status", status)
.endObject()
.endObject();
client.prepareIndex("_river", rivername, "_s3status").setSource(xb).execute().actionGet();
}
XContentBuilder builder = jsonBuilder();
builder
.startObject()
.field(new XContentBuilderString("ok"), true)
.endObject();
channel.sendResponse(new BytesRestResponse(RestStatus.OK, builder));
} catch (IOException e) {
onFailure(request, channel, e);
}
}
/** */
private void onFailure(RestRequest request, RestChannel channel, Exception e) throws Exception{
try{
channel.sendResponse(new BytesRestResponse(channel, e));
} catch (IOException ioe){
logger.error("Sending failure response fails !", e);
channel.sendResponse(new BytesRestResponse(RestStatus.INTERNAL_SERVER_ERROR));
}
}
}
| [
"laurent.broudoux@gmail.com"
] | laurent.broudoux@gmail.com |
06958d4cad0cc13430b2c2cf457952fa777eac2e | 48477c25f9a23e15fd3eb1abc0b3e6a28e511fdf | /src/com/mfu/servlet/addnewArticle.java | d66e061e193143bddffbef3623c86b607cd7074c | [] | no_license | AEDOProject/AEDOProject | c9e6677250082f5cedc677d84fa1e860cd5e034d | 379e88109b4d1be3c9547ce71462d4e4d8be5fb1 | refs/heads/master | 2021-01-17T17:47:58.392668 | 2016-07-31T11:28:50 | 2016-07-31T11:28:50 | 63,310,048 | 3 | 0 | null | 2016-07-23T05:16:00 | 2016-07-14T06:49:57 | Java | UTF-8 | Java | false | false | 4,236 | java | package com.mfu.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Date;
import com.mfu.dao.*;
import com.mfu.entity.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.apache.commons.io.IOUtils;
@WebServlet("/Back_End/addArticle")
@MultipartConfig(maxFileSize = 25177215)
// upload file's size up to 16MB
public class addnewArticle extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String afterpart = null;
if (request.getPart("photo") != null) {
Part filePart = request.getPart("photo"); // Retrieves <input
// type="file"
// name="file">
String fileName = getFileName(filePart);
// String fileType = filePart.getContentType();
InputStream fileContent = filePart.getInputStream();
// Create folder if no existing folder
File folderPart = new File(request.getServletContext().getRealPath("")+File.separator+"Back_End\\uploadarticle");
if (!folderPart.exists()) {
folderPart.mkdir();
}
try {
// Directory
afterpart = request.getServletContext().getRealPath("")+File.separator+"Back_End\\uploadarticle\\" + fileName;
// Copy file to the part that we set before.
FileOutputStream output = new FileOutputStream(afterpart);
IOUtils.copy(fileContent, output);
afterpart = "uploadarticle/" + fileName;
} catch (Exception e) {
afterpart = null;
}
}
String title = request.getParameter("title");
String titleen = new String(title.getBytes("ISO-8859-1"), "UTF-8");
String content = request.getParameter("editor");
String contenten = new String(content.getBytes("ISO-8859-1"), "UTF-8");
long articletypeid = Long.parseLong(request.getParameter("typeid"));
long worktypeid = Long.parseLong(request.getParameter("worktype"));
Article article = new Article();
article.setTitle(titleen);
article.setContent(contenten);
Date date = new Date();
article.setDate(date);
article.setPublish(true);
article.setDraft(false);
article.setLastupdate(date);
article.setPhoto(afterpart);
article.setArticletype(new ArticleTypeDAO().findArticleTypeById(articletypeid));
article.setWorktype(new WorkTypeDAO().findWorkTypeById(worktypeid));
ArticleDAO dao = new ArticleDAO();
dao.create(article);
// Return page
doGet(request, response,articletypeid);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response,long typeid) throws ServletException, IOException {
//getServletContext().getRequestDispatcher("/Back_End/allnewsandevent.jsp").forward(
// request, response);
ArticleTypeDAO dao = new ArticleTypeDAO();
System.out.println(dao.findArticleTypeById(typeid).getTypename());
String url = "" ;
request.setCharacterEncoding("UTF-8");
if(typeid == 2){
url = "/Back_End/AllNews?type="+dao.findArticleTypeById(typeid).getTypename();
System.out.println("url "+url);
RequestDispatcher rd = getServletContext().getRequestDispatcher(url);
rd.forward(request, response);
}else{
url = "/Back_End/AllEvents?type="+dao.findArticleTypeById(typeid).getTypename();
System.out.println("url "+url);
RequestDispatcher rd = getServletContext().getRequestDispatcher(url);
rd.forward(request, response);
}
}
private static String getFileName(Part part) {
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
String fileName = cd.substring(cd.indexOf('=') + 1).trim()
.replace("\"", "");
return fileName.substring(fileName.lastIndexOf('/') + 1)
.substring(fileName.lastIndexOf('\\') + 1); // MSIE fix.
}
}
return null;
}
} | [
"China@PHOEBUS"
] | China@PHOEBUS |
b1b1c5461424d6d78071f903fa4073859f5196e2 | 3d11ef54f8e2508fbef50abaf875f7ce0632f351 | /code/SortService.java | 8cfd56478268e78e4d72c5ff2ecede77972f1cdb | [] | no_license | JoeBlack220/sentimentAnalysis | 98d5c26eec26cb06effdcd73170ef05bc203cf21 | f7d446fc9840ac3ba4773c8e2e78c19540b24df5 | refs/heads/master | 2020-04-26T11:47:46.038472 | 2019-03-07T06:21:52 | 2019-03-07T06:21:52 | 173,528,837 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | true | 36,538 | java | /**
* Autogenerated by Thrift Compiler (0.9.3)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;
import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.server.AbstractNonblockingServer.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import javax.annotation.Generated;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.3)", date = "2019-03-03")
public class SortService {
public interface Iface {
public List<String> sort(List<MapResult> scores) throws org.apache.thrift.TException;
}
public interface AsyncIface {
public void sort(List<MapResult> scores, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;
}
public static class Client extends org.apache.thrift.TServiceClient implements Iface {
public static class Factory implements org.apache.thrift.TServiceClientFactory<Client> {
public Factory() {}
public Client getClient(org.apache.thrift.protocol.TProtocol prot) {
return new Client(prot);
}
public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
return new Client(iprot, oprot);
}
}
public Client(org.apache.thrift.protocol.TProtocol prot)
{
super(prot, prot);
}
public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
super(iprot, oprot);
}
public List<String> sort(List<MapResult> scores) throws org.apache.thrift.TException
{
send_sort(scores);
return recv_sort();
}
public void send_sort(List<MapResult> scores) throws org.apache.thrift.TException
{
sort_args args = new sort_args();
args.setScores(scores);
sendBase("sort", args);
}
public List<String> recv_sort() throws org.apache.thrift.TException
{
sort_result result = new sort_result();
receiveBase(result, "sort");
if (result.isSetSuccess()) {
return result.success;
}
throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "sort failed: unknown result");
}
}
public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface {
public static class Factory implements org.apache.thrift.async.TAsyncClientFactory<AsyncClient> {
private org.apache.thrift.async.TAsyncClientManager clientManager;
private org.apache.thrift.protocol.TProtocolFactory protocolFactory;
public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) {
this.clientManager = clientManager;
this.protocolFactory = protocolFactory;
}
public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) {
return new AsyncClient(protocolFactory, clientManager, transport);
}
}
public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) {
super(protocolFactory, clientManager, transport);
}
public void sort(List<MapResult> scores, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {
checkReady();
sort_call method_call = new sort_call(scores, resultHandler, this, ___protocolFactory, ___transport);
this.___currentMethod = method_call;
___manager.call(method_call);
}
public static class sort_call extends org.apache.thrift.async.TAsyncMethodCall {
private List<MapResult> scores;
public sort_call(List<MapResult> scores, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {
super(client, protocolFactory, transport, resultHandler, false);
this.scores = scores;
}
public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("sort", org.apache.thrift.protocol.TMessageType.CALL, 0));
sort_args args = new sort_args();
args.setScores(scores);
args.write(prot);
prot.writeMessageEnd();
}
public List<String> getResult() throws org.apache.thrift.TException {
if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
throw new IllegalStateException("Method call not finished!");
}
org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());
org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
return (new Client(prot)).recv_sort();
}
}
}
public static class Processor<I extends Iface> extends org.apache.thrift.TBaseProcessor<I> implements org.apache.thrift.TProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class.getName());
public Processor(I iface) {
super(iface, getProcessMap(new HashMap<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>>()));
}
protected Processor(I iface, Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
super(iface, getProcessMap(processMap));
}
private static <I extends Iface> Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> getProcessMap(Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
processMap.put("sort", new sort());
return processMap;
}
public static class sort<I extends Iface> extends org.apache.thrift.ProcessFunction<I, sort_args> {
public sort() {
super("sort");
}
public sort_args getEmptyArgsInstance() {
return new sort_args();
}
protected boolean isOneway() {
return false;
}
public sort_result getResult(I iface, sort_args args) throws org.apache.thrift.TException {
sort_result result = new sort_result();
result.success = iface.sort(args.scores);
return result;
}
}
}
public static class AsyncProcessor<I extends AsyncIface> extends org.apache.thrift.TBaseAsyncProcessor<I> {
private static final Logger LOGGER = LoggerFactory.getLogger(AsyncProcessor.class.getName());
public AsyncProcessor(I iface) {
super(iface, getProcessMap(new HashMap<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>>()));
}
protected AsyncProcessor(I iface, Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {
super(iface, getProcessMap(processMap));
}
private static <I extends AsyncIface> Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase,?>> getProcessMap(Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {
processMap.put("sort", new sort());
return processMap;
}
public static class sort<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, sort_args, List<String>> {
public sort() {
super("sort");
}
public sort_args getEmptyArgsInstance() {
return new sort_args();
}
public AsyncMethodCallback<List<String>> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {
final org.apache.thrift.AsyncProcessFunction fcall = this;
return new AsyncMethodCallback<List<String>>() {
public void onComplete(List<String> o) {
sort_result result = new sort_result();
result.success = o;
try {
fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);
return;
} catch (Exception e) {
LOGGER.error("Exception writing to internal frame buffer", e);
}
fb.close();
}
public void onError(Exception e) {
byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
org.apache.thrift.TBase msg;
sort_result result = new sort_result();
{
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
}
try {
fcall.sendResponse(fb,msg,msgType,seqid);
return;
} catch (Exception ex) {
LOGGER.error("Exception writing to internal frame buffer", ex);
}
fb.close();
}
};
}
protected boolean isOneway() {
return false;
}
public void start(I iface, sort_args args, org.apache.thrift.async.AsyncMethodCallback<List<String>> resultHandler) throws TException {
iface.sort(args.scores,resultHandler);
}
}
}
public static class sort_args implements org.apache.thrift.TBase<sort_args, sort_args._Fields>, java.io.Serializable, Cloneable, Comparable<sort_args> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("sort_args");
private static final org.apache.thrift.protocol.TField SCORES_FIELD_DESC = new org.apache.thrift.protocol.TField("scores", org.apache.thrift.protocol.TType.LIST, (short)1);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new sort_argsStandardSchemeFactory());
schemes.put(TupleScheme.class, new sort_argsTupleSchemeFactory());
}
public List<MapResult> scores; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
SCORES((short)1, "scores");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // SCORES
return SCORES;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.SCORES, new org.apache.thrift.meta_data.FieldMetaData("scores", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST,
new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, MapResult.class))));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(sort_args.class, metaDataMap);
}
public sort_args() {
}
public sort_args(
List<MapResult> scores)
{
this();
this.scores = scores;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public sort_args(sort_args other) {
if (other.isSetScores()) {
List<MapResult> __this__scores = new ArrayList<MapResult>(other.scores.size());
for (MapResult other_element : other.scores) {
__this__scores.add(new MapResult(other_element));
}
this.scores = __this__scores;
}
}
public sort_args deepCopy() {
return new sort_args(this);
}
@Override
public void clear() {
this.scores = null;
}
public int getScoresSize() {
return (this.scores == null) ? 0 : this.scores.size();
}
public java.util.Iterator<MapResult> getScoresIterator() {
return (this.scores == null) ? null : this.scores.iterator();
}
public void addToScores(MapResult elem) {
if (this.scores == null) {
this.scores = new ArrayList<MapResult>();
}
this.scores.add(elem);
}
public List<MapResult> getScores() {
return this.scores;
}
public sort_args setScores(List<MapResult> scores) {
this.scores = scores;
return this;
}
public void unsetScores() {
this.scores = null;
}
/** Returns true if field scores is set (has been assigned a value) and false otherwise */
public boolean isSetScores() {
return this.scores != null;
}
public void setScoresIsSet(boolean value) {
if (!value) {
this.scores = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case SCORES:
if (value == null) {
unsetScores();
} else {
setScores((List<MapResult>)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case SCORES:
return getScores();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case SCORES:
return isSetScores();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof sort_args)
return this.equals((sort_args)that);
return false;
}
public boolean equals(sort_args that) {
if (that == null)
return false;
boolean this_present_scores = true && this.isSetScores();
boolean that_present_scores = true && that.isSetScores();
if (this_present_scores || that_present_scores) {
if (!(this_present_scores && that_present_scores))
return false;
if (!this.scores.equals(that.scores))
return false;
}
return true;
}
@Override
public int hashCode() {
List<Object> list = new ArrayList<Object>();
boolean present_scores = true && (isSetScores());
list.add(present_scores);
if (present_scores)
list.add(scores);
return list.hashCode();
}
@Override
public int compareTo(sort_args other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetScores()).compareTo(other.isSetScores());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetScores()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.scores, other.scores);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("sort_args(");
boolean first = true;
sb.append("scores:");
if (this.scores == null) {
sb.append("null");
} else {
sb.append(this.scores);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class sort_argsStandardSchemeFactory implements SchemeFactory {
public sort_argsStandardScheme getScheme() {
return new sort_argsStandardScheme();
}
}
private static class sort_argsStandardScheme extends StandardScheme<sort_args> {
public void read(org.apache.thrift.protocol.TProtocol iprot, sort_args struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // SCORES
if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {
{
org.apache.thrift.protocol.TList _list8 = iprot.readListBegin();
struct.scores = new ArrayList<MapResult>(_list8.size);
MapResult _elem9;
for (int _i10 = 0; _i10 < _list8.size; ++_i10)
{
_elem9 = new MapResult();
_elem9.read(iprot);
struct.scores.add(_elem9);
}
iprot.readListEnd();
}
struct.setScoresIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, sort_args struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.scores != null) {
oprot.writeFieldBegin(SCORES_FIELD_DESC);
{
oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.scores.size()));
for (MapResult _iter11 : struct.scores)
{
_iter11.write(oprot);
}
oprot.writeListEnd();
}
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class sort_argsTupleSchemeFactory implements SchemeFactory {
public sort_argsTupleScheme getScheme() {
return new sort_argsTupleScheme();
}
}
private static class sort_argsTupleScheme extends TupleScheme<sort_args> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, sort_args struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetScores()) {
optionals.set(0);
}
oprot.writeBitSet(optionals, 1);
if (struct.isSetScores()) {
{
oprot.writeI32(struct.scores.size());
for (MapResult _iter12 : struct.scores)
{
_iter12.write(oprot);
}
}
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, sort_args struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(1);
if (incoming.get(0)) {
{
org.apache.thrift.protocol.TList _list13 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32());
struct.scores = new ArrayList<MapResult>(_list13.size);
MapResult _elem14;
for (int _i15 = 0; _i15 < _list13.size; ++_i15)
{
_elem14 = new MapResult();
_elem14.read(iprot);
struct.scores.add(_elem14);
}
}
struct.setScoresIsSet(true);
}
}
}
}
public static class sort_result implements org.apache.thrift.TBase<sort_result, sort_result._Fields>, java.io.Serializable, Cloneable, Comparable<sort_result> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("sort_result");
private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.LIST, (short)0);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new sort_resultStandardSchemeFactory());
schemes.put(TupleScheme.class, new sort_resultTupleSchemeFactory());
}
public List<String> success; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
SUCCESS((short)0, "success");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 0: // SUCCESS
return SUCCESS;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(sort_result.class, metaDataMap);
}
public sort_result() {
}
public sort_result(
List<String> success)
{
this();
this.success = success;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public sort_result(sort_result other) {
if (other.isSetSuccess()) {
List<String> __this__success = new ArrayList<String>(other.success);
this.success = __this__success;
}
}
public sort_result deepCopy() {
return new sort_result(this);
}
@Override
public void clear() {
this.success = null;
}
public int getSuccessSize() {
return (this.success == null) ? 0 : this.success.size();
}
public java.util.Iterator<String> getSuccessIterator() {
return (this.success == null) ? null : this.success.iterator();
}
public void addToSuccess(String elem) {
if (this.success == null) {
this.success = new ArrayList<String>();
}
this.success.add(elem);
}
public List<String> getSuccess() {
return this.success;
}
public sort_result setSuccess(List<String> success) {
this.success = success;
return this;
}
public void unsetSuccess() {
this.success = null;
}
/** Returns true if field success is set (has been assigned a value) and false otherwise */
public boolean isSetSuccess() {
return this.success != null;
}
public void setSuccessIsSet(boolean value) {
if (!value) {
this.success = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case SUCCESS:
if (value == null) {
unsetSuccess();
} else {
setSuccess((List<String>)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case SUCCESS:
return getSuccess();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case SUCCESS:
return isSetSuccess();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof sort_result)
return this.equals((sort_result)that);
return false;
}
public boolean equals(sort_result that) {
if (that == null)
return false;
boolean this_present_success = true && this.isSetSuccess();
boolean that_present_success = true && that.isSetSuccess();
if (this_present_success || that_present_success) {
if (!(this_present_success && that_present_success))
return false;
if (!this.success.equals(that.success))
return false;
}
return true;
}
@Override
public int hashCode() {
List<Object> list = new ArrayList<Object>();
boolean present_success = true && (isSetSuccess());
list.add(present_success);
if (present_success)
list.add(success);
return list.hashCode();
}
@Override
public int compareTo(sort_result other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetSuccess()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("sort_result(");
boolean first = true;
sb.append("success:");
if (this.success == null) {
sb.append("null");
} else {
sb.append(this.success);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class sort_resultStandardSchemeFactory implements SchemeFactory {
public sort_resultStandardScheme getScheme() {
return new sort_resultStandardScheme();
}
}
private static class sort_resultStandardScheme extends StandardScheme<sort_result> {
public void read(org.apache.thrift.protocol.TProtocol iprot, sort_result struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 0: // SUCCESS
if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {
{
org.apache.thrift.protocol.TList _list16 = iprot.readListBegin();
struct.success = new ArrayList<String>(_list16.size);
String _elem17;
for (int _i18 = 0; _i18 < _list16.size; ++_i18)
{
_elem17 = iprot.readString();
struct.success.add(_elem17);
}
iprot.readListEnd();
}
struct.setSuccessIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, sort_result struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.success != null) {
oprot.writeFieldBegin(SUCCESS_FIELD_DESC);
{
oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, struct.success.size()));
for (String _iter19 : struct.success)
{
oprot.writeString(_iter19);
}
oprot.writeListEnd();
}
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class sort_resultTupleSchemeFactory implements SchemeFactory {
public sort_resultTupleScheme getScheme() {
return new sort_resultTupleScheme();
}
}
private static class sort_resultTupleScheme extends TupleScheme<sort_result> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, sort_result struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetSuccess()) {
optionals.set(0);
}
oprot.writeBitSet(optionals, 1);
if (struct.isSetSuccess()) {
{
oprot.writeI32(struct.success.size());
for (String _iter20 : struct.success)
{
oprot.writeString(_iter20);
}
}
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, sort_result struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(1);
if (incoming.get(0)) {
{
org.apache.thrift.protocol.TList _list21 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, iprot.readI32());
struct.success = new ArrayList<String>(_list21.size);
String _elem22;
for (int _i23 = 0; _i23 < _list21.size; ++_i23)
{
_elem22 = iprot.readString();
struct.success.add(_elem22);
}
}
struct.setSuccessIsSet(true);
}
}
}
}
}
| [
"yan00104@umn.edu"
] | yan00104@umn.edu |
0cb624043f6c565daad9e8b771719158c34b6bea | a796250a14048f08aa6b576b673266650cd6aa1b | /src/principal/CommandLineParser.java | 3789c9de5fcd92485764cbee4dce4d69ae7b9bb6 | [] | no_license | howiepowie/m1projctl2012g6 | 3236212bd33661296576f048aecde78ce057228d | e1a51a0aaf8875fa85ffcd56c24d04d99ef01ff3 | refs/heads/master | 2016-08-06T19:21:49.096503 | 2013-01-25T16:06:23 | 2013-01-25T16:06:23 | 32,143,422 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 131,487 | java | // $ANTLR 3.4 /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g 2013-01-24 11:30:43
package principal;
import org.antlr.runtime.*;
import java.util.Stack;
import java.util.List;
import java.util.ArrayList;
import org.antlr.runtime.tree.*;
@SuppressWarnings({"all", "warnings", "unchecked"})
public class CommandLineParser extends Parser {
public static final String[] tokenNames = new String[] {
"<invalid>", "<EOR>", "<DOWN>", "<UP>", "AF", "AG", "AND", "ATOM", "AU", "AX", "CHAR", "DEAD", "EF", "EG", "ENABLE", "EQUIV", "ESC_SEQ", "EU", "EX", "EXPONENT", "FALSE", "HEX_DIGIT", "IMPLY", "INITIAL", "LETTER", "NEG", "NUMBER", "OCTAL_ESC", "OR", "STRING", "STRING_FILE_DOT", "STRING_FILE_NET", "TRUE", "UNICODE_ESC", "WS", "'!'", "'('", "')'", "'-'", "'.'", "'../'", "'./'", "'/'", "';'", "'A'", "'AF'", "'AG'", "'AX'", "'E'", "'EF'", "'EG'", "'EX'", "'Justifie'", "'Justifietodot'", "'U'", "'_'", "'ctl'", "'ctltodot'", "'dead'", "'dot'", "'enable'", "'false'", "'graphe'", "'initial'", "'load'", "'look'", "'net'", "'shell'", "'stop'", "'succ'", "'todot'", "'true'"
};
public static final int EOF=-1;
public static final int T__35=35;
public static final int T__36=36;
public static final int T__37=37;
public static final int T__38=38;
public static final int T__39=39;
public static final int T__40=40;
public static final int T__41=41;
public static final int T__42=42;
public static final int T__43=43;
public static final int T__44=44;
public static final int T__45=45;
public static final int T__46=46;
public static final int T__47=47;
public static final int T__48=48;
public static final int T__49=49;
public static final int T__50=50;
public static final int T__51=51;
public static final int T__52=52;
public static final int T__53=53;
public static final int T__54=54;
public static final int T__55=55;
public static final int T__56=56;
public static final int T__57=57;
public static final int T__58=58;
public static final int T__59=59;
public static final int T__60=60;
public static final int T__61=61;
public static final int T__62=62;
public static final int T__63=63;
public static final int T__64=64;
public static final int T__65=65;
public static final int T__66=66;
public static final int T__67=67;
public static final int T__68=68;
public static final int T__69=69;
public static final int T__70=70;
public static final int T__71=71;
public static final int AF=4;
public static final int AG=5;
public static final int AND=6;
public static final int ATOM=7;
public static final int AU=8;
public static final int AX=9;
public static final int CHAR=10;
public static final int DEAD=11;
public static final int EF=12;
public static final int EG=13;
public static final int ENABLE=14;
public static final int EQUIV=15;
public static final int ESC_SEQ=16;
public static final int EU=17;
public static final int EX=18;
public static final int EXPONENT=19;
public static final int FALSE=20;
public static final int HEX_DIGIT=21;
public static final int IMPLY=22;
public static final int INITIAL=23;
public static final int LETTER=24;
public static final int NEG=25;
public static final int NUMBER=26;
public static final int OCTAL_ESC=27;
public static final int OR=28;
public static final int STRING=29;
public static final int STRING_FILE_DOT=30;
public static final int STRING_FILE_NET=31;
public static final int TRUE=32;
public static final int UNICODE_ESC=33;
public static final int WS=34;
// delegates
public Parser[] getDelegates() {
return new Parser[] {};
}
// delegators
public CommandLineParser(TokenStream input) {
this(input, new RecognizerSharedState());
}
public CommandLineParser(TokenStream input, RecognizerSharedState state) {
super(input, state);
}
protected TreeAdaptor adaptor = new CommonTreeAdaptor();
public void setTreeAdaptor(TreeAdaptor adaptor) {
this.adaptor = adaptor;
}
public TreeAdaptor getTreeAdaptor() {
return adaptor;
}
public String[] getTokenNames() { return CommandLineParser.tokenNames; }
public String getGrammarFileName() { return "/Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g"; }
private ICallback callback;
private boolean programDeclDone;
private boolean usesDeclAllowed;
public CommandLineParser(final ICallback callback) {
super(null);
this.callback = callback;
programDeclDone = false;
usesDeclAllowed = true;
}
private void onShell() {
callback.shell();
}
private void onLoad(final String filename) {
callback.load(filename);
}
private void onGraphe() {
callback.graphe();
}
private void onLook(final int etat) {
callback.look(etat);
}
private void onSucc(final int etat) {
callback.succ(etat);
}
private void onToDot(final String filename) {
callback.toDot(filename);
}
private void onCtl(final Tree formule) {
callback.ctl(formule);
}
private void onCtl(final Tree formule, final int etat) {
callback.ctl(formule, etat);
}
private void onCtlToDot(final Tree formule, final String filename) {
callback.ctlToDot(formule, filename);
}
private void onJustifie(final Tree formule, final int etat) {
callback.justifie(formule, etat);
}
private void onJustifieToDot(final Tree formule, final int etat, final String filename) {
callback.justifieToDot(formule, etat, filename);
}
private void onStop() {
callback.stop();
}
public void process(String source) throws Exception {
ANTLRStringStream in = new ANTLRStringStream(source);
CommandLineLexer lexer = new CommandLineLexer(in);
CommonTokenStream tokens = new CommonTokenStream(lexer);
super.setTokenStream(tokens);
this.start();
}
private Tree formule(final Object f) {
return (Tree) f;
}
private int etat(final String e) {
return Integer.parseInt(e);
}
public void displayRecognitionError(String[] tokenNames, RecognitionException e) {
String hdr = getErrorHeader(e);
String msg = getErrorMessage(e, tokenNames);
System.out.println(hdr + " " + msg);
}
public static class start_return extends ParserRuleReturnScope {
Object tree;
public Object getTree() { return tree; }
};
// $ANTLR start "start"
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:116:1: start : instruction ( ';' instruction )* ;
public final CommandLineParser.start_return start() throws RecognitionException {
CommandLineParser.start_return retval = new CommandLineParser.start_return();
retval.start = input.LT(1);
Object root_0 = null;
Token char_literal2=null;
CommandLineParser.instruction_return instruction1 =null;
CommandLineParser.instruction_return instruction3 =null;
Object char_literal2_tree=null;
try {
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:117:2: ( instruction ( ';' instruction )* )
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:117:4: instruction ( ';' instruction )*
{
root_0 = (Object)adaptor.nil();
pushFollow(FOLLOW_instruction_in_start111);
instruction1=instruction();
state._fsp--;
adaptor.addChild(root_0, instruction1.getTree());
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:117:16: ( ';' instruction )*
loop1:
do {
int alt1=2;
int LA1_0 = input.LA(1);
if ( (LA1_0==43) ) {
alt1=1;
}
switch (alt1) {
case 1 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:117:17: ';' instruction
{
char_literal2=(Token)match(input,43,FOLLOW_43_in_start114);
char_literal2_tree =
(Object)adaptor.create(char_literal2)
;
adaptor.addChild(root_0, char_literal2_tree);
pushFollow(FOLLOW_instruction_in_start116);
instruction3=instruction();
state._fsp--;
adaptor.addChild(root_0, instruction3.getTree());
}
break;
default :
break loop1;
}
} while (true);
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "start"
public static class instruction_return extends ParserRuleReturnScope {
Object tree;
public Object getTree() { return tree; }
};
// $ANTLR start "instruction"
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:120:1: instruction : ( shell | load | graphe | look | succ | todot | ctl | ctltodot | justifie | justifietodot | stop );
public final CommandLineParser.instruction_return instruction() throws RecognitionException {
CommandLineParser.instruction_return retval = new CommandLineParser.instruction_return();
retval.start = input.LT(1);
Object root_0 = null;
CommandLineParser.shell_return shell4 =null;
CommandLineParser.load_return load5 =null;
CommandLineParser.graphe_return graphe6 =null;
CommandLineParser.look_return look7 =null;
CommandLineParser.succ_return succ8 =null;
CommandLineParser.todot_return todot9 =null;
CommandLineParser.ctl_return ctl10 =null;
CommandLineParser.ctltodot_return ctltodot11 =null;
CommandLineParser.justifie_return justifie12 =null;
CommandLineParser.justifietodot_return justifietodot13 =null;
CommandLineParser.stop_return stop14 =null;
try {
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:121:2: ( shell | load | graphe | look | succ | todot | ctl | ctltodot | justifie | justifietodot | stop )
int alt2=11;
switch ( input.LA(1) ) {
case 67:
{
alt2=1;
}
break;
case 64:
{
alt2=2;
}
break;
case 62:
{
alt2=3;
}
break;
case 65:
{
alt2=4;
}
break;
case 69:
{
alt2=5;
}
break;
case 70:
{
alt2=6;
}
break;
case 56:
{
alt2=7;
}
break;
case 57:
{
alt2=8;
}
break;
case 52:
{
alt2=9;
}
break;
case 53:
{
alt2=10;
}
break;
case 68:
{
alt2=11;
}
break;
default:
NoViableAltException nvae =
new NoViableAltException("", 2, 0, input);
throw nvae;
}
switch (alt2) {
case 1 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:121:4: shell
{
root_0 = (Object)adaptor.nil();
pushFollow(FOLLOW_shell_in_instruction129);
shell4=shell();
state._fsp--;
adaptor.addChild(root_0, shell4.getTree());
}
break;
case 2 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:122:4: load
{
root_0 = (Object)adaptor.nil();
pushFollow(FOLLOW_load_in_instruction134);
load5=load();
state._fsp--;
adaptor.addChild(root_0, load5.getTree());
}
break;
case 3 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:123:4: graphe
{
root_0 = (Object)adaptor.nil();
pushFollow(FOLLOW_graphe_in_instruction139);
graphe6=graphe();
state._fsp--;
adaptor.addChild(root_0, graphe6.getTree());
}
break;
case 4 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:124:4: look
{
root_0 = (Object)adaptor.nil();
pushFollow(FOLLOW_look_in_instruction144);
look7=look();
state._fsp--;
adaptor.addChild(root_0, look7.getTree());
}
break;
case 5 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:125:4: succ
{
root_0 = (Object)adaptor.nil();
pushFollow(FOLLOW_succ_in_instruction149);
succ8=succ();
state._fsp--;
adaptor.addChild(root_0, succ8.getTree());
}
break;
case 6 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:126:4: todot
{
root_0 = (Object)adaptor.nil();
pushFollow(FOLLOW_todot_in_instruction154);
todot9=todot();
state._fsp--;
adaptor.addChild(root_0, todot9.getTree());
}
break;
case 7 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:127:4: ctl
{
root_0 = (Object)adaptor.nil();
pushFollow(FOLLOW_ctl_in_instruction159);
ctl10=ctl();
state._fsp--;
adaptor.addChild(root_0, ctl10.getTree());
}
break;
case 8 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:128:4: ctltodot
{
root_0 = (Object)adaptor.nil();
pushFollow(FOLLOW_ctltodot_in_instruction164);
ctltodot11=ctltodot();
state._fsp--;
adaptor.addChild(root_0, ctltodot11.getTree());
}
break;
case 9 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:129:4: justifie
{
root_0 = (Object)adaptor.nil();
pushFollow(FOLLOW_justifie_in_instruction169);
justifie12=justifie();
state._fsp--;
adaptor.addChild(root_0, justifie12.getTree());
}
break;
case 10 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:130:4: justifietodot
{
root_0 = (Object)adaptor.nil();
pushFollow(FOLLOW_justifietodot_in_instruction174);
justifietodot13=justifietodot();
state._fsp--;
adaptor.addChild(root_0, justifietodot13.getTree());
}
break;
case 11 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:131:4: stop
{
root_0 = (Object)adaptor.nil();
pushFollow(FOLLOW_stop_in_instruction179);
stop14=stop();
state._fsp--;
adaptor.addChild(root_0, stop14.getTree());
}
break;
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "instruction"
public static class shell_return extends ParserRuleReturnScope {
Object tree;
public Object getTree() { return tree; }
};
// $ANTLR start "shell"
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:134:1: shell : 'shell' ;
public final CommandLineParser.shell_return shell() throws RecognitionException {
CommandLineParser.shell_return retval = new CommandLineParser.shell_return();
retval.start = input.LT(1);
Object root_0 = null;
Token string_literal15=null;
Object string_literal15_tree=null;
try {
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:135:2: ( 'shell' )
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:135:4: 'shell'
{
root_0 = (Object)adaptor.nil();
string_literal15=(Token)match(input,67,FOLLOW_67_in_shell191);
string_literal15_tree =
(Object)adaptor.create(string_literal15)
;
adaptor.addChild(root_0, string_literal15_tree);
onShell();
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "shell"
public static class load_return extends ParserRuleReturnScope {
Object tree;
public Object getTree() { return tree; }
};
// $ANTLR start "load"
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:138:1: load : 'load' p1= file_net ;
public final CommandLineParser.load_return load() throws RecognitionException {
CommandLineParser.load_return retval = new CommandLineParser.load_return();
retval.start = input.LT(1);
Object root_0 = null;
Token string_literal16=null;
CommandLineParser.file_net_return p1 =null;
Object string_literal16_tree=null;
try {
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:139:2: ( 'load' p1= file_net )
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:139:4: 'load' p1= file_net
{
root_0 = (Object)adaptor.nil();
string_literal16=(Token)match(input,64,FOLLOW_64_in_load204);
string_literal16_tree =
(Object)adaptor.create(string_literal16)
;
adaptor.addChild(root_0, string_literal16_tree);
pushFollow(FOLLOW_file_net_in_load208);
p1=file_net();
state._fsp--;
adaptor.addChild(root_0, p1.getTree());
onLoad((p1!=null?input.toString(p1.start,p1.stop):null));
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "load"
public static class graphe_return extends ParserRuleReturnScope {
Object tree;
public Object getTree() { return tree; }
};
// $ANTLR start "graphe"
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:142:1: graphe : 'graphe' ;
public final CommandLineParser.graphe_return graphe() throws RecognitionException {
CommandLineParser.graphe_return retval = new CommandLineParser.graphe_return();
retval.start = input.LT(1);
Object root_0 = null;
Token string_literal17=null;
Object string_literal17_tree=null;
try {
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:143:2: ( 'graphe' )
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:143:4: 'graphe'
{
root_0 = (Object)adaptor.nil();
string_literal17=(Token)match(input,62,FOLLOW_62_in_graphe222);
string_literal17_tree =
(Object)adaptor.create(string_literal17)
;
adaptor.addChild(root_0, string_literal17_tree);
onGraphe();
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "graphe"
public static class look_return extends ParserRuleReturnScope {
Object tree;
public Object getTree() { return tree; }
};
// $ANTLR start "look"
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:146:1: look : 'look' p1= etat ;
public final CommandLineParser.look_return look() throws RecognitionException {
CommandLineParser.look_return retval = new CommandLineParser.look_return();
retval.start = input.LT(1);
Object root_0 = null;
Token string_literal18=null;
CommandLineParser.etat_return p1 =null;
Object string_literal18_tree=null;
try {
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:147:2: ( 'look' p1= etat )
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:147:4: 'look' p1= etat
{
root_0 = (Object)adaptor.nil();
string_literal18=(Token)match(input,65,FOLLOW_65_in_look236);
string_literal18_tree =
(Object)adaptor.create(string_literal18)
;
adaptor.addChild(root_0, string_literal18_tree);
pushFollow(FOLLOW_etat_in_look240);
p1=etat();
state._fsp--;
adaptor.addChild(root_0, p1.getTree());
onLook(etat((p1!=null?input.toString(p1.start,p1.stop):null)));
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "look"
public static class succ_return extends ParserRuleReturnScope {
Object tree;
public Object getTree() { return tree; }
};
// $ANTLR start "succ"
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:150:1: succ : 'succ' p1= etat ;
public final CommandLineParser.succ_return succ() throws RecognitionException {
CommandLineParser.succ_return retval = new CommandLineParser.succ_return();
retval.start = input.LT(1);
Object root_0 = null;
Token string_literal19=null;
CommandLineParser.etat_return p1 =null;
Object string_literal19_tree=null;
try {
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:151:2: ( 'succ' p1= etat )
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:151:4: 'succ' p1= etat
{
root_0 = (Object)adaptor.nil();
string_literal19=(Token)match(input,69,FOLLOW_69_in_succ254);
string_literal19_tree =
(Object)adaptor.create(string_literal19)
;
adaptor.addChild(root_0, string_literal19_tree);
pushFollow(FOLLOW_etat_in_succ258);
p1=etat();
state._fsp--;
adaptor.addChild(root_0, p1.getTree());
onSucc(etat((p1!=null?input.toString(p1.start,p1.stop):null)));
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "succ"
public static class todot_return extends ParserRuleReturnScope {
Object tree;
public Object getTree() { return tree; }
};
// $ANTLR start "todot"
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:154:1: todot : 'todot' p1= file_dot ;
public final CommandLineParser.todot_return todot() throws RecognitionException {
CommandLineParser.todot_return retval = new CommandLineParser.todot_return();
retval.start = input.LT(1);
Object root_0 = null;
Token string_literal20=null;
CommandLineParser.file_dot_return p1 =null;
Object string_literal20_tree=null;
try {
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:155:2: ( 'todot' p1= file_dot )
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:155:4: 'todot' p1= file_dot
{
root_0 = (Object)adaptor.nil();
string_literal20=(Token)match(input,70,FOLLOW_70_in_todot272);
string_literal20_tree =
(Object)adaptor.create(string_literal20)
;
adaptor.addChild(root_0, string_literal20_tree);
pushFollow(FOLLOW_file_dot_in_todot276);
p1=file_dot();
state._fsp--;
adaptor.addChild(root_0, p1.getTree());
onToDot((p1!=null?input.toString(p1.start,p1.stop):null));
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "todot"
public static class ctl_return extends ParserRuleReturnScope {
Object tree;
public Object getTree() { return tree; }
};
// $ANTLR start "ctl"
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:158:1: ctl : 'ctl' p1= formule (p2= etat |) ;
public final CommandLineParser.ctl_return ctl() throws RecognitionException {
CommandLineParser.ctl_return retval = new CommandLineParser.ctl_return();
retval.start = input.LT(1);
Object root_0 = null;
Token string_literal21=null;
CommandLineParser.formule_return p1 =null;
CommandLineParser.etat_return p2 =null;
Object string_literal21_tree=null;
try {
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:159:2: ( 'ctl' p1= formule (p2= etat |) )
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:159:4: 'ctl' p1= formule (p2= etat |)
{
root_0 = (Object)adaptor.nil();
string_literal21=(Token)match(input,56,FOLLOW_56_in_ctl290);
string_literal21_tree =
(Object)adaptor.create(string_literal21)
;
adaptor.addChild(root_0, string_literal21_tree);
pushFollow(FOLLOW_formule_in_ctl294);
p1=formule();
state._fsp--;
adaptor.addChild(root_0, p1.getTree());
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:159:21: (p2= etat |)
int alt3=2;
int LA3_0 = input.LA(1);
if ( (LA3_0==NUMBER) ) {
alt3=1;
}
else if ( (LA3_0==EOF||LA3_0==43) ) {
alt3=2;
}
else {
NoViableAltException nvae =
new NoViableAltException("", 3, 0, input);
throw nvae;
}
switch (alt3) {
case 1 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:160:3: p2= etat
{
pushFollow(FOLLOW_etat_in_ctl302);
p2=etat();
state._fsp--;
adaptor.addChild(root_0, p2.getTree());
onCtl(formule((p1!=null?((Object)p1.tree):null)), etat((p2!=null?input.toString(p2.start,p2.stop):null)));
}
break;
case 2 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:161:5:
{
onCtl(formule((p1!=null?((Object)p1.tree):null)));
}
break;
}
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "ctl"
public static class ctltodot_return extends ParserRuleReturnScope {
Object tree;
public Object getTree() { return tree; }
};
// $ANTLR start "ctltodot"
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:165:1: ctltodot : 'ctltodot' p1= formule p2= file_dot ;
public final CommandLineParser.ctltodot_return ctltodot() throws RecognitionException {
CommandLineParser.ctltodot_return retval = new CommandLineParser.ctltodot_return();
retval.start = input.LT(1);
Object root_0 = null;
Token string_literal22=null;
CommandLineParser.formule_return p1 =null;
CommandLineParser.file_dot_return p2 =null;
Object string_literal22_tree=null;
try {
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:166:2: ( 'ctltodot' p1= formule p2= file_dot )
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:166:4: 'ctltodot' p1= formule p2= file_dot
{
root_0 = (Object)adaptor.nil();
string_literal22=(Token)match(input,57,FOLLOW_57_in_ctltodot325);
string_literal22_tree =
(Object)adaptor.create(string_literal22)
;
adaptor.addChild(root_0, string_literal22_tree);
pushFollow(FOLLOW_formule_in_ctltodot329);
p1=formule();
state._fsp--;
adaptor.addChild(root_0, p1.getTree());
pushFollow(FOLLOW_file_dot_in_ctltodot333);
p2=file_dot();
state._fsp--;
adaptor.addChild(root_0, p2.getTree());
onCtlToDot(formule((p1!=null?((Object)p1.tree):null)), (p2!=null?input.toString(p2.start,p2.stop):null));
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "ctltodot"
public static class justifie_return extends ParserRuleReturnScope {
Object tree;
public Object getTree() { return tree; }
};
// $ANTLR start "justifie"
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:169:1: justifie : 'Justifie' p1= formule p2= etat ;
public final CommandLineParser.justifie_return justifie() throws RecognitionException {
CommandLineParser.justifie_return retval = new CommandLineParser.justifie_return();
retval.start = input.LT(1);
Object root_0 = null;
Token string_literal23=null;
CommandLineParser.formule_return p1 =null;
CommandLineParser.etat_return p2 =null;
Object string_literal23_tree=null;
try {
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:170:2: ( 'Justifie' p1= formule p2= etat )
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:170:4: 'Justifie' p1= formule p2= etat
{
root_0 = (Object)adaptor.nil();
string_literal23=(Token)match(input,52,FOLLOW_52_in_justifie347);
string_literal23_tree =
(Object)adaptor.create(string_literal23)
;
adaptor.addChild(root_0, string_literal23_tree);
pushFollow(FOLLOW_formule_in_justifie351);
p1=formule();
state._fsp--;
adaptor.addChild(root_0, p1.getTree());
pushFollow(FOLLOW_etat_in_justifie355);
p2=etat();
state._fsp--;
adaptor.addChild(root_0, p2.getTree());
onJustifie(formule((p1!=null?((Object)p1.tree):null)), etat((p2!=null?input.toString(p2.start,p2.stop):null)));
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "justifie"
public static class justifietodot_return extends ParserRuleReturnScope {
Object tree;
public Object getTree() { return tree; }
};
// $ANTLR start "justifietodot"
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:173:1: justifietodot : 'Justifietodot' p1= formule p2= etat p3= file_dot ;
public final CommandLineParser.justifietodot_return justifietodot() throws RecognitionException {
CommandLineParser.justifietodot_return retval = new CommandLineParser.justifietodot_return();
retval.start = input.LT(1);
Object root_0 = null;
Token string_literal24=null;
CommandLineParser.formule_return p1 =null;
CommandLineParser.etat_return p2 =null;
CommandLineParser.file_dot_return p3 =null;
Object string_literal24_tree=null;
try {
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:174:2: ( 'Justifietodot' p1= formule p2= etat p3= file_dot )
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:174:4: 'Justifietodot' p1= formule p2= etat p3= file_dot
{
root_0 = (Object)adaptor.nil();
string_literal24=(Token)match(input,53,FOLLOW_53_in_justifietodot369);
string_literal24_tree =
(Object)adaptor.create(string_literal24)
;
adaptor.addChild(root_0, string_literal24_tree);
pushFollow(FOLLOW_formule_in_justifietodot373);
p1=formule();
state._fsp--;
adaptor.addChild(root_0, p1.getTree());
pushFollow(FOLLOW_etat_in_justifietodot377);
p2=etat();
state._fsp--;
adaptor.addChild(root_0, p2.getTree());
pushFollow(FOLLOW_file_dot_in_justifietodot381);
p3=file_dot();
state._fsp--;
adaptor.addChild(root_0, p3.getTree());
onJustifieToDot(formule((p1!=null?((Object)p1.tree):null)), etat((p2!=null?input.toString(p2.start,p2.stop):null)), (p3!=null?input.toString(p3.start,p3.stop):null));
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "justifietodot"
public static class stop_return extends ParserRuleReturnScope {
Object tree;
public Object getTree() { return tree; }
};
// $ANTLR start "stop"
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:177:1: stop : 'stop' ;
public final CommandLineParser.stop_return stop() throws RecognitionException {
CommandLineParser.stop_return retval = new CommandLineParser.stop_return();
retval.start = input.LT(1);
Object root_0 = null;
Token string_literal25=null;
Object string_literal25_tree=null;
try {
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:178:2: ( 'stop' )
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:178:4: 'stop'
{
root_0 = (Object)adaptor.nil();
string_literal25=(Token)match(input,68,FOLLOW_68_in_stop395);
string_literal25_tree =
(Object)adaptor.create(string_literal25)
;
adaptor.addChild(root_0, string_literal25_tree);
onStop();
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "stop"
public static class file_net_return extends ParserRuleReturnScope {
Object tree;
public Object getTree() { return tree; }
};
// $ANTLR start "file_net"
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:181:1: file_net : (p= STRING_FILE_NET | filename 'net' );
public final CommandLineParser.file_net_return file_net() throws RecognitionException {
CommandLineParser.file_net_return retval = new CommandLineParser.file_net_return();
retval.start = input.LT(1);
Object root_0 = null;
Token p=null;
Token string_literal27=null;
CommandLineParser.filename_return filename26 =null;
Object p_tree=null;
Object string_literal27_tree=null;
try {
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:182:2: (p= STRING_FILE_NET | filename 'net' )
int alt4=2;
int LA4_0 = input.LA(1);
if ( (LA4_0==STRING_FILE_NET) ) {
alt4=1;
}
else if ( (LA4_0==LETTER||LA4_0==38||(LA4_0 >= 40 && LA4_0 <= 41)||LA4_0==55) ) {
alt4=2;
}
else {
NoViableAltException nvae =
new NoViableAltException("", 4, 0, input);
throw nvae;
}
switch (alt4) {
case 1 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:182:4: p= STRING_FILE_NET
{
root_0 = (Object)adaptor.nil();
p=(Token)match(input,STRING_FILE_NET,FOLLOW_STRING_FILE_NET_in_file_net411);
p_tree =
(Object)adaptor.create(p)
;
adaptor.addChild(root_0, p_tree);
p.setText((p!=null?p.getText():null).substring(1, (p!=null?p.getText():null).length() - 1));
}
break;
case 2 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:183:4: filename 'net'
{
root_0 = (Object)adaptor.nil();
pushFollow(FOLLOW_filename_in_file_net418);
filename26=filename();
state._fsp--;
adaptor.addChild(root_0, filename26.getTree());
string_literal27=(Token)match(input,66,FOLLOW_66_in_file_net420);
string_literal27_tree =
(Object)adaptor.create(string_literal27)
;
adaptor.addChild(root_0, string_literal27_tree);
}
break;
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "file_net"
public static class file_dot_return extends ParserRuleReturnScope {
Object tree;
public Object getTree() { return tree; }
};
// $ANTLR start "file_dot"
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:186:1: file_dot : (p= STRING_FILE_DOT | filename 'dot' );
public final CommandLineParser.file_dot_return file_dot() throws RecognitionException {
CommandLineParser.file_dot_return retval = new CommandLineParser.file_dot_return();
retval.start = input.LT(1);
Object root_0 = null;
Token p=null;
Token string_literal29=null;
CommandLineParser.filename_return filename28 =null;
Object p_tree=null;
Object string_literal29_tree=null;
try {
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:187:2: (p= STRING_FILE_DOT | filename 'dot' )
int alt5=2;
int LA5_0 = input.LA(1);
if ( (LA5_0==STRING_FILE_DOT) ) {
alt5=1;
}
else if ( (LA5_0==LETTER||LA5_0==38||(LA5_0 >= 40 && LA5_0 <= 41)||LA5_0==55) ) {
alt5=2;
}
else {
NoViableAltException nvae =
new NoViableAltException("", 5, 0, input);
throw nvae;
}
switch (alt5) {
case 1 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:187:4: p= STRING_FILE_DOT
{
root_0 = (Object)adaptor.nil();
p=(Token)match(input,STRING_FILE_DOT,FOLLOW_STRING_FILE_DOT_in_file_dot434);
p_tree =
(Object)adaptor.create(p)
;
adaptor.addChild(root_0, p_tree);
p.setText( (p!=null?p.getText():null).substring(1, (p!=null?p.getText():null).length() - 1));
}
break;
case 2 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:188:4: filename 'dot'
{
root_0 = (Object)adaptor.nil();
pushFollow(FOLLOW_filename_in_file_dot441);
filename28=filename();
state._fsp--;
adaptor.addChild(root_0, filename28.getTree());
string_literal29=(Token)match(input,59,FOLLOW_59_in_file_dot443);
string_literal29_tree =
(Object)adaptor.create(string_literal29)
;
adaptor.addChild(root_0, string_literal29_tree);
}
break;
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "file_dot"
public static class filename_return extends ParserRuleReturnScope {
Object tree;
public Object getTree() { return tree; }
};
// $ANTLR start "filename"
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:191:1: filename : ( path_modifier )? ( LETTER | '_' | '-' )+ ( '.' | '/' filename ) ;
public final CommandLineParser.filename_return filename() throws RecognitionException {
CommandLineParser.filename_return retval = new CommandLineParser.filename_return();
retval.start = input.LT(1);
Object root_0 = null;
Token set31=null;
Token char_literal32=null;
Token char_literal33=null;
CommandLineParser.path_modifier_return path_modifier30 =null;
CommandLineParser.filename_return filename34 =null;
Object set31_tree=null;
Object char_literal32_tree=null;
Object char_literal33_tree=null;
try {
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:192:2: ( ( path_modifier )? ( LETTER | '_' | '-' )+ ( '.' | '/' filename ) )
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:192:4: ( path_modifier )? ( LETTER | '_' | '-' )+ ( '.' | '/' filename )
{
root_0 = (Object)adaptor.nil();
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:192:4: ( path_modifier )?
int alt6=2;
int LA6_0 = input.LA(1);
if ( ((LA6_0 >= 40 && LA6_0 <= 41)) ) {
alt6=1;
}
switch (alt6) {
case 1 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:192:4: path_modifier
{
pushFollow(FOLLOW_path_modifier_in_filename456);
path_modifier30=path_modifier();
state._fsp--;
adaptor.addChild(root_0, path_modifier30.getTree());
}
break;
}
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:192:19: ( LETTER | '_' | '-' )+
int cnt7=0;
loop7:
do {
int alt7=2;
int LA7_0 = input.LA(1);
if ( (LA7_0==LETTER||LA7_0==38||LA7_0==55) ) {
alt7=1;
}
switch (alt7) {
case 1 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:
{
set31=(Token)input.LT(1);
if ( input.LA(1)==LETTER||input.LA(1)==38||input.LA(1)==55 ) {
input.consume();
adaptor.addChild(root_0,
(Object)adaptor.create(set31)
);
state.errorRecovery=false;
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
throw mse;
}
}
break;
default :
if ( cnt7 >= 1 ) break loop7;
EarlyExitException eee =
new EarlyExitException(7, input);
throw eee;
}
cnt7++;
} while (true);
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:192:41: ( '.' | '/' filename )
int alt8=2;
int LA8_0 = input.LA(1);
if ( (LA8_0==39) ) {
alt8=1;
}
else if ( (LA8_0==42) ) {
alt8=2;
}
else {
NoViableAltException nvae =
new NoViableAltException("", 8, 0, input);
throw nvae;
}
switch (alt8) {
case 1 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:193:3: '.'
{
char_literal32=(Token)match(input,39,FOLLOW_39_in_filename476);
char_literal32_tree =
(Object)adaptor.create(char_literal32)
;
adaptor.addChild(root_0, char_literal32_tree);
}
break;
case 2 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:194:5: '/' filename
{
char_literal33=(Token)match(input,42,FOLLOW_42_in_filename482);
char_literal33_tree =
(Object)adaptor.create(char_literal33)
;
adaptor.addChild(root_0, char_literal33_tree);
pushFollow(FOLLOW_filename_in_filename484);
filename34=filename();
state._fsp--;
adaptor.addChild(root_0, filename34.getTree());
}
break;
}
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "filename"
public static class path_modifier_return extends ParserRuleReturnScope {
Object tree;
public Object getTree() { return tree; }
};
// $ANTLR start "path_modifier"
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:198:1: path_modifier : ( './' | '../' );
public final CommandLineParser.path_modifier_return path_modifier() throws RecognitionException {
CommandLineParser.path_modifier_return retval = new CommandLineParser.path_modifier_return();
retval.start = input.LT(1);
Object root_0 = null;
Token set35=null;
Object set35_tree=null;
try {
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:199:2: ( './' | '../' )
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:
{
root_0 = (Object)adaptor.nil();
set35=(Token)input.LT(1);
if ( (input.LA(1) >= 40 && input.LA(1) <= 41) ) {
input.consume();
adaptor.addChild(root_0,
(Object)adaptor.create(set35)
);
state.errorRecovery=false;
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
throw mse;
}
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "path_modifier"
public static class formule_return extends ParserRuleReturnScope {
Object tree;
public Object getTree() { return tree; }
};
// $ANTLR start "formule"
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:204:1: formule : term3 ( OR ^ term3 )* ;
public final CommandLineParser.formule_return formule() throws RecognitionException {
CommandLineParser.formule_return retval = new CommandLineParser.formule_return();
retval.start = input.LT(1);
Object root_0 = null;
Token OR37=null;
CommandLineParser.term3_return term336 =null;
CommandLineParser.term3_return term338 =null;
Object OR37_tree=null;
try {
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:205:2: ( term3 ( OR ^ term3 )* )
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:205:4: term3 ( OR ^ term3 )*
{
root_0 = (Object)adaptor.nil();
pushFollow(FOLLOW_term3_in_formule517);
term336=term3();
state._fsp--;
adaptor.addChild(root_0, term336.getTree());
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:205:10: ( OR ^ term3 )*
loop9:
do {
int alt9=2;
int LA9_0 = input.LA(1);
if ( (LA9_0==OR) ) {
alt9=1;
}
switch (alt9) {
case 1 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:205:11: OR ^ term3
{
OR37=(Token)match(input,OR,FOLLOW_OR_in_formule520);
OR37_tree =
(Object)adaptor.create(OR37)
;
root_0 = (Object)adaptor.becomeRoot(OR37_tree, root_0);
pushFollow(FOLLOW_term3_in_formule523);
term338=term3();
state._fsp--;
adaptor.addChild(root_0, term338.getTree());
}
break;
default :
break loop9;
}
} while (true);
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "formule"
public static class term3_return extends ParserRuleReturnScope {
Object tree;
public Object getTree() { return tree; }
};
// $ANTLR start "term3"
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:208:1: term3 : term2 ( EQUIV ^ term2 )* ;
public final CommandLineParser.term3_return term3() throws RecognitionException {
CommandLineParser.term3_return retval = new CommandLineParser.term3_return();
retval.start = input.LT(1);
Object root_0 = null;
Token EQUIV40=null;
CommandLineParser.term2_return term239 =null;
CommandLineParser.term2_return term241 =null;
Object EQUIV40_tree=null;
try {
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:209:2: ( term2 ( EQUIV ^ term2 )* )
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:209:4: term2 ( EQUIV ^ term2 )*
{
root_0 = (Object)adaptor.nil();
pushFollow(FOLLOW_term2_in_term3536);
term239=term2();
state._fsp--;
adaptor.addChild(root_0, term239.getTree());
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:209:10: ( EQUIV ^ term2 )*
loop10:
do {
int alt10=2;
int LA10_0 = input.LA(1);
if ( (LA10_0==EQUIV) ) {
alt10=1;
}
switch (alt10) {
case 1 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:209:11: EQUIV ^ term2
{
EQUIV40=(Token)match(input,EQUIV,FOLLOW_EQUIV_in_term3539);
EQUIV40_tree =
(Object)adaptor.create(EQUIV40)
;
root_0 = (Object)adaptor.becomeRoot(EQUIV40_tree, root_0);
pushFollow(FOLLOW_term2_in_term3542);
term241=term2();
state._fsp--;
adaptor.addChild(root_0, term241.getTree());
}
break;
default :
break loop10;
}
} while (true);
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "term3"
public static class term2_return extends ParserRuleReturnScope {
Object tree;
public Object getTree() { return tree; }
};
// $ANTLR start "term2"
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:212:1: term2 : term1 ( IMPLY ^ term1 )? ;
public final CommandLineParser.term2_return term2() throws RecognitionException {
CommandLineParser.term2_return retval = new CommandLineParser.term2_return();
retval.start = input.LT(1);
Object root_0 = null;
Token IMPLY43=null;
CommandLineParser.term1_return term142 =null;
CommandLineParser.term1_return term144 =null;
Object IMPLY43_tree=null;
try {
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:213:2: ( term1 ( IMPLY ^ term1 )? )
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:213:4: term1 ( IMPLY ^ term1 )?
{
root_0 = (Object)adaptor.nil();
pushFollow(FOLLOW_term1_in_term2555);
term142=term1();
state._fsp--;
adaptor.addChild(root_0, term142.getTree());
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:213:10: ( IMPLY ^ term1 )?
int alt11=2;
int LA11_0 = input.LA(1);
if ( (LA11_0==IMPLY) ) {
alt11=1;
}
switch (alt11) {
case 1 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:213:11: IMPLY ^ term1
{
IMPLY43=(Token)match(input,IMPLY,FOLLOW_IMPLY_in_term2558);
IMPLY43_tree =
(Object)adaptor.create(IMPLY43)
;
root_0 = (Object)adaptor.becomeRoot(IMPLY43_tree, root_0);
pushFollow(FOLLOW_term1_in_term2561);
term144=term1();
state._fsp--;
adaptor.addChild(root_0, term144.getTree());
}
break;
}
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "term2"
public static class term1_return extends ParserRuleReturnScope {
Object tree;
public Object getTree() { return tree; }
};
// $ANTLR start "term1"
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:216:1: term1 : term0 ( AND ^ term0 )* ;
public final CommandLineParser.term1_return term1() throws RecognitionException {
CommandLineParser.term1_return retval = new CommandLineParser.term1_return();
retval.start = input.LT(1);
Object root_0 = null;
Token AND46=null;
CommandLineParser.term0_return term045 =null;
CommandLineParser.term0_return term047 =null;
Object AND46_tree=null;
try {
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:217:2: ( term0 ( AND ^ term0 )* )
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:217:4: term0 ( AND ^ term0 )*
{
root_0 = (Object)adaptor.nil();
pushFollow(FOLLOW_term0_in_term1575);
term045=term0();
state._fsp--;
adaptor.addChild(root_0, term045.getTree());
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:217:10: ( AND ^ term0 )*
loop12:
do {
int alt12=2;
int LA12_0 = input.LA(1);
if ( (LA12_0==AND) ) {
alt12=1;
}
switch (alt12) {
case 1 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:217:11: AND ^ term0
{
AND46=(Token)match(input,AND,FOLLOW_AND_in_term1578);
AND46_tree =
(Object)adaptor.create(AND46)
;
root_0 = (Object)adaptor.becomeRoot(AND46_tree, root_0);
pushFollow(FOLLOW_term0_in_term1581);
term047=term0();
state._fsp--;
adaptor.addChild(root_0, term047.getTree());
}
break;
default :
break loop12;
}
} while (true);
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "term1"
public static class term0_return extends ParserRuleReturnScope {
Object tree;
public Object getTree() { return tree; }
};
// $ANTLR start "term0"
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:220:1: term0 : ( atom | term01 | term02 );
public final CommandLineParser.term0_return term0() throws RecognitionException {
CommandLineParser.term0_return retval = new CommandLineParser.term0_return();
retval.start = input.LT(1);
Object root_0 = null;
CommandLineParser.atom_return atom48 =null;
CommandLineParser.term01_return term0149 =null;
CommandLineParser.term02_return term0250 =null;
try {
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:221:2: ( atom | term01 | term02 )
int alt13=3;
switch ( input.LA(1) ) {
case ATOM:
case 36:
case 58:
case 60:
case 61:
case 63:
case 71:
{
alt13=1;
}
break;
case 35:
{
alt13=2;
}
break;
case 44:
case 45:
case 46:
case 47:
case 48:
case 49:
case 50:
case 51:
{
alt13=3;
}
break;
default:
NoViableAltException nvae =
new NoViableAltException("", 13, 0, input);
throw nvae;
}
switch (alt13) {
case 1 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:221:4: atom
{
root_0 = (Object)adaptor.nil();
pushFollow(FOLLOW_atom_in_term0596);
atom48=atom();
state._fsp--;
adaptor.addChild(root_0, atom48.getTree());
}
break;
case 2 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:222:4: term01
{
root_0 = (Object)adaptor.nil();
pushFollow(FOLLOW_term01_in_term0601);
term0149=term01();
state._fsp--;
adaptor.addChild(root_0, term0149.getTree());
}
break;
case 3 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:223:4: term02
{
root_0 = (Object)adaptor.nil();
pushFollow(FOLLOW_term02_in_term0606);
term0250=term02();
state._fsp--;
adaptor.addChild(root_0, term0250.getTree());
}
break;
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "term0"
public static class term01_return extends ParserRuleReturnScope {
Object tree;
public Object getTree() { return tree; }
};
// $ANTLR start "term01"
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:226:1: term01 : ( '!' ( atom -> ^( NEG atom ) | term02 -> ^( NEG term02 ) ) | '!' term01 -> ^( NEG term01 ) );
public final CommandLineParser.term01_return term01() throws RecognitionException {
CommandLineParser.term01_return retval = new CommandLineParser.term01_return();
retval.start = input.LT(1);
Object root_0 = null;
Token char_literal51=null;
Token char_literal54=null;
CommandLineParser.atom_return atom52 =null;
CommandLineParser.term02_return term0253 =null;
CommandLineParser.term01_return term0155 =null;
Object char_literal51_tree=null;
Object char_literal54_tree=null;
RewriteRuleTokenStream stream_35=new RewriteRuleTokenStream(adaptor,"token 35");
RewriteRuleSubtreeStream stream_term01=new RewriteRuleSubtreeStream(adaptor,"rule term01");
RewriteRuleSubtreeStream stream_atom=new RewriteRuleSubtreeStream(adaptor,"rule atom");
RewriteRuleSubtreeStream stream_term02=new RewriteRuleSubtreeStream(adaptor,"rule term02");
try {
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:227:2: ( '!' ( atom -> ^( NEG atom ) | term02 -> ^( NEG term02 ) ) | '!' term01 -> ^( NEG term01 ) )
int alt15=2;
int LA15_0 = input.LA(1);
if ( (LA15_0==35) ) {
int LA15_1 = input.LA(2);
if ( (LA15_1==ATOM||LA15_1==36||(LA15_1 >= 44 && LA15_1 <= 51)||LA15_1==58||(LA15_1 >= 60 && LA15_1 <= 61)||LA15_1==63||LA15_1==71) ) {
alt15=1;
}
else if ( (LA15_1==35) ) {
alt15=2;
}
else {
NoViableAltException nvae =
new NoViableAltException("", 15, 1, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("", 15, 0, input);
throw nvae;
}
switch (alt15) {
case 1 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:227:4: '!' ( atom -> ^( NEG atom ) | term02 -> ^( NEG term02 ) )
{
char_literal51=(Token)match(input,35,FOLLOW_35_in_term01618);
stream_35.add(char_literal51);
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:227:8: ( atom -> ^( NEG atom ) | term02 -> ^( NEG term02 ) )
int alt14=2;
int LA14_0 = input.LA(1);
if ( (LA14_0==ATOM||LA14_0==36||LA14_0==58||(LA14_0 >= 60 && LA14_0 <= 61)||LA14_0==63||LA14_0==71) ) {
alt14=1;
}
else if ( ((LA14_0 >= 44 && LA14_0 <= 51)) ) {
alt14=2;
}
else {
NoViableAltException nvae =
new NoViableAltException("", 14, 0, input);
throw nvae;
}
switch (alt14) {
case 1 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:228:3: atom
{
pushFollow(FOLLOW_atom_in_term01624);
atom52=atom();
state._fsp--;
stream_atom.add(atom52.getTree());
// AST REWRITE
// elements: atom
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (Object)adaptor.nil();
// 228:8: -> ^( NEG atom )
{
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:228:11: ^( NEG atom )
{
Object root_1 = (Object)adaptor.nil();
root_1 = (Object)adaptor.becomeRoot(
(Object)adaptor.create(NEG, "NEG")
, root_1);
adaptor.addChild(root_1, stream_atom.nextTree());
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
break;
case 2 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:229:5: term02
{
pushFollow(FOLLOW_term02_in_term01638);
term0253=term02();
state._fsp--;
stream_term02.add(term0253.getTree());
// AST REWRITE
// elements: term02
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (Object)adaptor.nil();
// 229:12: -> ^( NEG term02 )
{
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:229:15: ^( NEG term02 )
{
Object root_1 = (Object)adaptor.nil();
root_1 = (Object)adaptor.becomeRoot(
(Object)adaptor.create(NEG, "NEG")
, root_1);
adaptor.addChild(root_1, stream_term02.nextTree());
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
break;
}
}
break;
case 2 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:231:4: '!' term01
{
char_literal54=(Token)match(input,35,FOLLOW_35_in_term01654);
stream_35.add(char_literal54);
pushFollow(FOLLOW_term01_in_term01656);
term0155=term01();
state._fsp--;
stream_term01.add(term0155.getTree());
// AST REWRITE
// elements: term01
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (Object)adaptor.nil();
// 231:15: -> ^( NEG term01 )
{
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:231:18: ^( NEG term01 )
{
Object root_1 = (Object)adaptor.nil();
root_1 = (Object)adaptor.becomeRoot(
(Object)adaptor.create(NEG, "NEG")
, root_1);
adaptor.addChild(root_1, stream_term01.nextTree());
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
break;
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "term01"
public static class term02_return extends ParserRuleReturnScope {
Object tree;
public Object getTree() { return tree; }
};
// $ANTLR start "term02"
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:234:1: term02 : ( 'EF' atom -> ^( EF atom ) | 'EG' atom -> ^( EG atom ) | 'EX' atom -> ^( EX atom ) | 'AF' atom -> ^( AF atom ) | 'AG' atom -> ^( AG atom ) | 'AX' atom -> ^( AX atom ) | 'E' '(' formule 'U' formule ')' -> ^( EU formule formule ) | 'A' '(' formule 'U' formule ')' -> ^( AU formule formule ) );
public final CommandLineParser.term02_return term02() throws RecognitionException {
CommandLineParser.term02_return retval = new CommandLineParser.term02_return();
retval.start = input.LT(1);
Object root_0 = null;
Token string_literal56=null;
Token string_literal58=null;
Token string_literal60=null;
Token string_literal62=null;
Token string_literal64=null;
Token string_literal66=null;
Token char_literal68=null;
Token char_literal69=null;
Token char_literal71=null;
Token char_literal73=null;
Token char_literal74=null;
Token char_literal75=null;
Token char_literal77=null;
Token char_literal79=null;
CommandLineParser.atom_return atom57 =null;
CommandLineParser.atom_return atom59 =null;
CommandLineParser.atom_return atom61 =null;
CommandLineParser.atom_return atom63 =null;
CommandLineParser.atom_return atom65 =null;
CommandLineParser.atom_return atom67 =null;
CommandLineParser.formule_return formule70 =null;
CommandLineParser.formule_return formule72 =null;
CommandLineParser.formule_return formule76 =null;
CommandLineParser.formule_return formule78 =null;
Object string_literal56_tree=null;
Object string_literal58_tree=null;
Object string_literal60_tree=null;
Object string_literal62_tree=null;
Object string_literal64_tree=null;
Object string_literal66_tree=null;
Object char_literal68_tree=null;
Object char_literal69_tree=null;
Object char_literal71_tree=null;
Object char_literal73_tree=null;
Object char_literal74_tree=null;
Object char_literal75_tree=null;
Object char_literal77_tree=null;
Object char_literal79_tree=null;
RewriteRuleTokenStream stream_49=new RewriteRuleTokenStream(adaptor,"token 49");
RewriteRuleTokenStream stream_48=new RewriteRuleTokenStream(adaptor,"token 48");
RewriteRuleTokenStream stream_45=new RewriteRuleTokenStream(adaptor,"token 45");
RewriteRuleTokenStream stream_44=new RewriteRuleTokenStream(adaptor,"token 44");
RewriteRuleTokenStream stream_47=new RewriteRuleTokenStream(adaptor,"token 47");
RewriteRuleTokenStream stream_46=new RewriteRuleTokenStream(adaptor,"token 46");
RewriteRuleTokenStream stream_51=new RewriteRuleTokenStream(adaptor,"token 51");
RewriteRuleTokenStream stream_36=new RewriteRuleTokenStream(adaptor,"token 36");
RewriteRuleTokenStream stream_54=new RewriteRuleTokenStream(adaptor,"token 54");
RewriteRuleTokenStream stream_37=new RewriteRuleTokenStream(adaptor,"token 37");
RewriteRuleTokenStream stream_50=new RewriteRuleTokenStream(adaptor,"token 50");
RewriteRuleSubtreeStream stream_atom=new RewriteRuleSubtreeStream(adaptor,"rule atom");
RewriteRuleSubtreeStream stream_formule=new RewriteRuleSubtreeStream(adaptor,"rule formule");
try {
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:235:2: ( 'EF' atom -> ^( EF atom ) | 'EG' atom -> ^( EG atom ) | 'EX' atom -> ^( EX atom ) | 'AF' atom -> ^( AF atom ) | 'AG' atom -> ^( AG atom ) | 'AX' atom -> ^( AX atom ) | 'E' '(' formule 'U' formule ')' -> ^( EU formule formule ) | 'A' '(' formule 'U' formule ')' -> ^( AU formule formule ) )
int alt16=8;
switch ( input.LA(1) ) {
case 49:
{
alt16=1;
}
break;
case 50:
{
alt16=2;
}
break;
case 51:
{
alt16=3;
}
break;
case 45:
{
alt16=4;
}
break;
case 46:
{
alt16=5;
}
break;
case 47:
{
alt16=6;
}
break;
case 48:
{
alt16=7;
}
break;
case 44:
{
alt16=8;
}
break;
default:
NoViableAltException nvae =
new NoViableAltException("", 16, 0, input);
throw nvae;
}
switch (alt16) {
case 1 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:235:4: 'EF' atom
{
string_literal56=(Token)match(input,49,FOLLOW_49_in_term02676);
stream_49.add(string_literal56);
pushFollow(FOLLOW_atom_in_term02678);
atom57=atom();
state._fsp--;
stream_atom.add(atom57.getTree());
// AST REWRITE
// elements: atom
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (Object)adaptor.nil();
// 235:14: -> ^( EF atom )
{
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:235:17: ^( EF atom )
{
Object root_1 = (Object)adaptor.nil();
root_1 = (Object)adaptor.becomeRoot(
(Object)adaptor.create(EF, "EF")
, root_1);
adaptor.addChild(root_1, stream_atom.nextTree());
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
break;
case 2 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:236:4: 'EG' atom
{
string_literal58=(Token)match(input,50,FOLLOW_50_in_term02691);
stream_50.add(string_literal58);
pushFollow(FOLLOW_atom_in_term02693);
atom59=atom();
state._fsp--;
stream_atom.add(atom59.getTree());
// AST REWRITE
// elements: atom
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (Object)adaptor.nil();
// 236:14: -> ^( EG atom )
{
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:236:17: ^( EG atom )
{
Object root_1 = (Object)adaptor.nil();
root_1 = (Object)adaptor.becomeRoot(
(Object)adaptor.create(EG, "EG")
, root_1);
adaptor.addChild(root_1, stream_atom.nextTree());
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
break;
case 3 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:237:4: 'EX' atom
{
string_literal60=(Token)match(input,51,FOLLOW_51_in_term02706);
stream_51.add(string_literal60);
pushFollow(FOLLOW_atom_in_term02708);
atom61=atom();
state._fsp--;
stream_atom.add(atom61.getTree());
// AST REWRITE
// elements: atom
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (Object)adaptor.nil();
// 237:14: -> ^( EX atom )
{
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:237:17: ^( EX atom )
{
Object root_1 = (Object)adaptor.nil();
root_1 = (Object)adaptor.becomeRoot(
(Object)adaptor.create(EX, "EX")
, root_1);
adaptor.addChild(root_1, stream_atom.nextTree());
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
break;
case 4 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:238:4: 'AF' atom
{
string_literal62=(Token)match(input,45,FOLLOW_45_in_term02721);
stream_45.add(string_literal62);
pushFollow(FOLLOW_atom_in_term02723);
atom63=atom();
state._fsp--;
stream_atom.add(atom63.getTree());
// AST REWRITE
// elements: atom
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (Object)adaptor.nil();
// 238:14: -> ^( AF atom )
{
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:238:17: ^( AF atom )
{
Object root_1 = (Object)adaptor.nil();
root_1 = (Object)adaptor.becomeRoot(
(Object)adaptor.create(AF, "AF")
, root_1);
adaptor.addChild(root_1, stream_atom.nextTree());
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
break;
case 5 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:239:4: 'AG' atom
{
string_literal64=(Token)match(input,46,FOLLOW_46_in_term02736);
stream_46.add(string_literal64);
pushFollow(FOLLOW_atom_in_term02738);
atom65=atom();
state._fsp--;
stream_atom.add(atom65.getTree());
// AST REWRITE
// elements: atom
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (Object)adaptor.nil();
// 239:14: -> ^( AG atom )
{
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:239:17: ^( AG atom )
{
Object root_1 = (Object)adaptor.nil();
root_1 = (Object)adaptor.becomeRoot(
(Object)adaptor.create(AG, "AG")
, root_1);
adaptor.addChild(root_1, stream_atom.nextTree());
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
break;
case 6 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:240:4: 'AX' atom
{
string_literal66=(Token)match(input,47,FOLLOW_47_in_term02751);
stream_47.add(string_literal66);
pushFollow(FOLLOW_atom_in_term02753);
atom67=atom();
state._fsp--;
stream_atom.add(atom67.getTree());
// AST REWRITE
// elements: atom
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (Object)adaptor.nil();
// 240:14: -> ^( AX atom )
{
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:240:17: ^( AX atom )
{
Object root_1 = (Object)adaptor.nil();
root_1 = (Object)adaptor.becomeRoot(
(Object)adaptor.create(AX, "AX")
, root_1);
adaptor.addChild(root_1, stream_atom.nextTree());
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
break;
case 7 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:241:4: 'E' '(' formule 'U' formule ')'
{
char_literal68=(Token)match(input,48,FOLLOW_48_in_term02766);
stream_48.add(char_literal68);
char_literal69=(Token)match(input,36,FOLLOW_36_in_term02768);
stream_36.add(char_literal69);
pushFollow(FOLLOW_formule_in_term02770);
formule70=formule();
state._fsp--;
stream_formule.add(formule70.getTree());
char_literal71=(Token)match(input,54,FOLLOW_54_in_term02772);
stream_54.add(char_literal71);
pushFollow(FOLLOW_formule_in_term02774);
formule72=formule();
state._fsp--;
stream_formule.add(formule72.getTree());
char_literal73=(Token)match(input,37,FOLLOW_37_in_term02776);
stream_37.add(char_literal73);
// AST REWRITE
// elements: formule, formule
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (Object)adaptor.nil();
// 241:36: -> ^( EU formule formule )
{
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:241:39: ^( EU formule formule )
{
Object root_1 = (Object)adaptor.nil();
root_1 = (Object)adaptor.becomeRoot(
(Object)adaptor.create(EU, "EU")
, root_1);
adaptor.addChild(root_1, stream_formule.nextTree());
adaptor.addChild(root_1, stream_formule.nextTree());
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
break;
case 8 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:242:4: 'A' '(' formule 'U' formule ')'
{
char_literal74=(Token)match(input,44,FOLLOW_44_in_term02791);
stream_44.add(char_literal74);
char_literal75=(Token)match(input,36,FOLLOW_36_in_term02793);
stream_36.add(char_literal75);
pushFollow(FOLLOW_formule_in_term02795);
formule76=formule();
state._fsp--;
stream_formule.add(formule76.getTree());
char_literal77=(Token)match(input,54,FOLLOW_54_in_term02797);
stream_54.add(char_literal77);
pushFollow(FOLLOW_formule_in_term02799);
formule78=formule();
state._fsp--;
stream_formule.add(formule78.getTree());
char_literal79=(Token)match(input,37,FOLLOW_37_in_term02801);
stream_37.add(char_literal79);
// AST REWRITE
// elements: formule, formule
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (Object)adaptor.nil();
// 242:36: -> ^( AU formule formule )
{
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:242:39: ^( AU formule formule )
{
Object root_1 = (Object)adaptor.nil();
root_1 = (Object)adaptor.becomeRoot(
(Object)adaptor.create(AU, "AU")
, root_1);
adaptor.addChild(root_1, stream_formule.nextTree());
adaptor.addChild(root_1, stream_formule.nextTree());
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
break;
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "term02"
public static class atom_return extends ParserRuleReturnScope {
Object tree;
public Object getTree() { return tree; }
};
// $ANTLR start "atom"
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:245:1: atom : (p= ATOM | 'dead' -> DEAD | 'initial' -> INITIAL | 'enable' '(' ATOM ')' -> ^( ENABLE ATOM ) | 'true' -> TRUE | 'false' -> FALSE | '(' ! formule ')' !);
public final CommandLineParser.atom_return atom() throws RecognitionException {
CommandLineParser.atom_return retval = new CommandLineParser.atom_return();
retval.start = input.LT(1);
Object root_0 = null;
Token p=null;
Token string_literal80=null;
Token string_literal81=null;
Token string_literal82=null;
Token char_literal83=null;
Token ATOM84=null;
Token char_literal85=null;
Token string_literal86=null;
Token string_literal87=null;
Token char_literal88=null;
Token char_literal90=null;
CommandLineParser.formule_return formule89 =null;
Object p_tree=null;
Object string_literal80_tree=null;
Object string_literal81_tree=null;
Object string_literal82_tree=null;
Object char_literal83_tree=null;
Object ATOM84_tree=null;
Object char_literal85_tree=null;
Object string_literal86_tree=null;
Object string_literal87_tree=null;
Object char_literal88_tree=null;
Object char_literal90_tree=null;
RewriteRuleTokenStream stream_58=new RewriteRuleTokenStream(adaptor,"token 58");
RewriteRuleTokenStream stream_ATOM=new RewriteRuleTokenStream(adaptor,"token ATOM");
RewriteRuleTokenStream stream_36=new RewriteRuleTokenStream(adaptor,"token 36");
RewriteRuleTokenStream stream_71=new RewriteRuleTokenStream(adaptor,"token 71");
RewriteRuleTokenStream stream_63=new RewriteRuleTokenStream(adaptor,"token 63");
RewriteRuleTokenStream stream_60=new RewriteRuleTokenStream(adaptor,"token 60");
RewriteRuleTokenStream stream_61=new RewriteRuleTokenStream(adaptor,"token 61");
RewriteRuleTokenStream stream_37=new RewriteRuleTokenStream(adaptor,"token 37");
try {
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:246:2: (p= ATOM | 'dead' -> DEAD | 'initial' -> INITIAL | 'enable' '(' ATOM ')' -> ^( ENABLE ATOM ) | 'true' -> TRUE | 'false' -> FALSE | '(' ! formule ')' !)
int alt17=7;
switch ( input.LA(1) ) {
case ATOM:
{
alt17=1;
}
break;
case 58:
{
alt17=2;
}
break;
case 63:
{
alt17=3;
}
break;
case 60:
{
alt17=4;
}
break;
case 71:
{
alt17=5;
}
break;
case 61:
{
alt17=6;
}
break;
case 36:
{
alt17=7;
}
break;
default:
NoViableAltException nvae =
new NoViableAltException("", 17, 0, input);
throw nvae;
}
switch (alt17) {
case 1 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:246:4: p= ATOM
{
root_0 = (Object)adaptor.nil();
p=(Token)match(input,ATOM,FOLLOW_ATOM_in_atom825);
p_tree =
(Object)adaptor.create(p)
;
adaptor.addChild(root_0, p_tree);
p.setText((p!=null?p.getText():null).substring(1));
}
break;
case 2 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:247:4: 'dead'
{
string_literal80=(Token)match(input,58,FOLLOW_58_in_atom832);
stream_58.add(string_literal80);
// AST REWRITE
// elements:
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (Object)adaptor.nil();
// 247:11: -> DEAD
{
adaptor.addChild(root_0,
(Object)adaptor.create(DEAD, "DEAD")
);
}
retval.tree = root_0;
}
break;
case 3 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:248:4: 'initial'
{
string_literal81=(Token)match(input,63,FOLLOW_63_in_atom841);
stream_63.add(string_literal81);
// AST REWRITE
// elements:
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (Object)adaptor.nil();
// 248:14: -> INITIAL
{
adaptor.addChild(root_0,
(Object)adaptor.create(INITIAL, "INITIAL")
);
}
retval.tree = root_0;
}
break;
case 4 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:249:4: 'enable' '(' ATOM ')'
{
string_literal82=(Token)match(input,60,FOLLOW_60_in_atom850);
stream_60.add(string_literal82);
char_literal83=(Token)match(input,36,FOLLOW_36_in_atom852);
stream_36.add(char_literal83);
ATOM84=(Token)match(input,ATOM,FOLLOW_ATOM_in_atom854);
stream_ATOM.add(ATOM84);
char_literal85=(Token)match(input,37,FOLLOW_37_in_atom856);
stream_37.add(char_literal85);
// AST REWRITE
// elements: ATOM
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (Object)adaptor.nil();
// 249:26: -> ^( ENABLE ATOM )
{
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:249:29: ^( ENABLE ATOM )
{
Object root_1 = (Object)adaptor.nil();
root_1 = (Object)adaptor.becomeRoot(
(Object)adaptor.create(ENABLE, "ENABLE")
, root_1);
adaptor.addChild(root_1,
stream_ATOM.nextNode()
);
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
break;
case 5 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:250:4: 'true'
{
string_literal86=(Token)match(input,71,FOLLOW_71_in_atom869);
stream_71.add(string_literal86);
// AST REWRITE
// elements:
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (Object)adaptor.nil();
// 250:11: -> TRUE
{
adaptor.addChild(root_0,
(Object)adaptor.create(TRUE, "TRUE")
);
}
retval.tree = root_0;
}
break;
case 6 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:251:4: 'false'
{
string_literal87=(Token)match(input,61,FOLLOW_61_in_atom878);
stream_61.add(string_literal87);
// AST REWRITE
// elements:
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (Object)adaptor.nil();
// 251:12: -> FALSE
{
adaptor.addChild(root_0,
(Object)adaptor.create(FALSE, "FALSE")
);
}
retval.tree = root_0;
}
break;
case 7 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:252:4: '(' ! formule ')' !
{
root_0 = (Object)adaptor.nil();
char_literal88=(Token)match(input,36,FOLLOW_36_in_atom887);
pushFollow(FOLLOW_formule_in_atom890);
formule89=formule();
state._fsp--;
adaptor.addChild(root_0, formule89.getTree());
char_literal90=(Token)match(input,37,FOLLOW_37_in_atom892);
}
break;
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "atom"
public static class etat_return extends ParserRuleReturnScope {
Object tree;
public Object getTree() { return tree; }
};
// $ANTLR start "etat"
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:256:1: etat : ( NUMBER )+ ;
public final CommandLineParser.etat_return etat() throws RecognitionException {
CommandLineParser.etat_return retval = new CommandLineParser.etat_return();
retval.start = input.LT(1);
Object root_0 = null;
Token NUMBER91=null;
Object NUMBER91_tree=null;
try {
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:257:2: ( ( NUMBER )+ )
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:257:4: ( NUMBER )+
{
root_0 = (Object)adaptor.nil();
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:257:4: ( NUMBER )+
int cnt18=0;
loop18:
do {
int alt18=2;
int LA18_0 = input.LA(1);
if ( (LA18_0==NUMBER) ) {
alt18=1;
}
switch (alt18) {
case 1 :
// /Users/jeremymorosi/Documents/Programmation/Modelisation et verif/modelproj/src/principal/CommandLine.g:257:4: NUMBER
{
NUMBER91=(Token)match(input,NUMBER,FOLLOW_NUMBER_in_etat907);
NUMBER91_tree =
(Object)adaptor.create(NUMBER91)
;
adaptor.addChild(root_0, NUMBER91_tree);
}
break;
default :
if ( cnt18 >= 1 ) break loop18;
EarlyExitException eee =
new EarlyExitException(18, input);
throw eee;
}
cnt18++;
} while (true);
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "etat"
// Delegated rules
public static final BitSet FOLLOW_instruction_in_start111 = new BitSet(new long[]{0x0000080000000002L});
public static final BitSet FOLLOW_43_in_start114 = new BitSet(new long[]{0x4330000000000000L,0x000000000000007BL});
public static final BitSet FOLLOW_instruction_in_start116 = new BitSet(new long[]{0x0000080000000002L});
public static final BitSet FOLLOW_shell_in_instruction129 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_load_in_instruction134 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_graphe_in_instruction139 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_look_in_instruction144 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_succ_in_instruction149 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_todot_in_instruction154 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_ctl_in_instruction159 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_ctltodot_in_instruction164 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_justifie_in_instruction169 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_justifietodot_in_instruction174 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_stop_in_instruction179 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_67_in_shell191 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_64_in_load204 = new BitSet(new long[]{0x0080034081000000L});
public static final BitSet FOLLOW_file_net_in_load208 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_62_in_graphe222 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_65_in_look236 = new BitSet(new long[]{0x0000000004000000L});
public static final BitSet FOLLOW_etat_in_look240 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_69_in_succ254 = new BitSet(new long[]{0x0000000004000000L});
public static final BitSet FOLLOW_etat_in_succ258 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_70_in_todot272 = new BitSet(new long[]{0x0080034041000000L});
public static final BitSet FOLLOW_file_dot_in_todot276 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_56_in_ctl290 = new BitSet(new long[]{0xB40FF01800000080L,0x0000000000000080L});
public static final BitSet FOLLOW_formule_in_ctl294 = new BitSet(new long[]{0x0000000004000002L});
public static final BitSet FOLLOW_etat_in_ctl302 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_57_in_ctltodot325 = new BitSet(new long[]{0xB40FF01800000080L,0x0000000000000080L});
public static final BitSet FOLLOW_formule_in_ctltodot329 = new BitSet(new long[]{0x0080034041000000L});
public static final BitSet FOLLOW_file_dot_in_ctltodot333 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_52_in_justifie347 = new BitSet(new long[]{0xB40FF01800000080L,0x0000000000000080L});
public static final BitSet FOLLOW_formule_in_justifie351 = new BitSet(new long[]{0x0000000004000000L});
public static final BitSet FOLLOW_etat_in_justifie355 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_53_in_justifietodot369 = new BitSet(new long[]{0xB40FF01800000080L,0x0000000000000080L});
public static final BitSet FOLLOW_formule_in_justifietodot373 = new BitSet(new long[]{0x0000000004000000L});
public static final BitSet FOLLOW_etat_in_justifietodot377 = new BitSet(new long[]{0x0080034041000000L});
public static final BitSet FOLLOW_file_dot_in_justifietodot381 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_68_in_stop395 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_STRING_FILE_NET_in_file_net411 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_filename_in_file_net418 = new BitSet(new long[]{0x0000000000000000L,0x0000000000000004L});
public static final BitSet FOLLOW_66_in_file_net420 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_STRING_FILE_DOT_in_file_dot434 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_filename_in_file_dot441 = new BitSet(new long[]{0x0800000000000000L});
public static final BitSet FOLLOW_59_in_file_dot443 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_path_modifier_in_filename456 = new BitSet(new long[]{0x0080004001000000L});
public static final BitSet FOLLOW_39_in_filename476 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_42_in_filename482 = new BitSet(new long[]{0x0080034001000000L});
public static final BitSet FOLLOW_filename_in_filename484 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_term3_in_formule517 = new BitSet(new long[]{0x0000000010000002L});
public static final BitSet FOLLOW_OR_in_formule520 = new BitSet(new long[]{0xB40FF01800000080L,0x0000000000000080L});
public static final BitSet FOLLOW_term3_in_formule523 = new BitSet(new long[]{0x0000000010000002L});
public static final BitSet FOLLOW_term2_in_term3536 = new BitSet(new long[]{0x0000000000008002L});
public static final BitSet FOLLOW_EQUIV_in_term3539 = new BitSet(new long[]{0xB40FF01800000080L,0x0000000000000080L});
public static final BitSet FOLLOW_term2_in_term3542 = new BitSet(new long[]{0x0000000000008002L});
public static final BitSet FOLLOW_term1_in_term2555 = new BitSet(new long[]{0x0000000000400002L});
public static final BitSet FOLLOW_IMPLY_in_term2558 = new BitSet(new long[]{0xB40FF01800000080L,0x0000000000000080L});
public static final BitSet FOLLOW_term1_in_term2561 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_term0_in_term1575 = new BitSet(new long[]{0x0000000000000042L});
public static final BitSet FOLLOW_AND_in_term1578 = new BitSet(new long[]{0xB40FF01800000080L,0x0000000000000080L});
public static final BitSet FOLLOW_term0_in_term1581 = new BitSet(new long[]{0x0000000000000042L});
public static final BitSet FOLLOW_atom_in_term0596 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_term01_in_term0601 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_term02_in_term0606 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_35_in_term01618 = new BitSet(new long[]{0xB40FF01000000080L,0x0000000000000080L});
public static final BitSet FOLLOW_atom_in_term01624 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_term02_in_term01638 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_35_in_term01654 = new BitSet(new long[]{0x0000000800000000L});
public static final BitSet FOLLOW_term01_in_term01656 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_49_in_term02676 = new BitSet(new long[]{0xB400001000000080L,0x0000000000000080L});
public static final BitSet FOLLOW_atom_in_term02678 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_50_in_term02691 = new BitSet(new long[]{0xB400001000000080L,0x0000000000000080L});
public static final BitSet FOLLOW_atom_in_term02693 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_51_in_term02706 = new BitSet(new long[]{0xB400001000000080L,0x0000000000000080L});
public static final BitSet FOLLOW_atom_in_term02708 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_45_in_term02721 = new BitSet(new long[]{0xB400001000000080L,0x0000000000000080L});
public static final BitSet FOLLOW_atom_in_term02723 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_46_in_term02736 = new BitSet(new long[]{0xB400001000000080L,0x0000000000000080L});
public static final BitSet FOLLOW_atom_in_term02738 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_47_in_term02751 = new BitSet(new long[]{0xB400001000000080L,0x0000000000000080L});
public static final BitSet FOLLOW_atom_in_term02753 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_48_in_term02766 = new BitSet(new long[]{0x0000001000000000L});
public static final BitSet FOLLOW_36_in_term02768 = new BitSet(new long[]{0xB40FF01800000080L,0x0000000000000080L});
public static final BitSet FOLLOW_formule_in_term02770 = new BitSet(new long[]{0x0040000000000000L});
public static final BitSet FOLLOW_54_in_term02772 = new BitSet(new long[]{0xB40FF01800000080L,0x0000000000000080L});
public static final BitSet FOLLOW_formule_in_term02774 = new BitSet(new long[]{0x0000002000000000L});
public static final BitSet FOLLOW_37_in_term02776 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_44_in_term02791 = new BitSet(new long[]{0x0000001000000000L});
public static final BitSet FOLLOW_36_in_term02793 = new BitSet(new long[]{0xB40FF01800000080L,0x0000000000000080L});
public static final BitSet FOLLOW_formule_in_term02795 = new BitSet(new long[]{0x0040000000000000L});
public static final BitSet FOLLOW_54_in_term02797 = new BitSet(new long[]{0xB40FF01800000080L,0x0000000000000080L});
public static final BitSet FOLLOW_formule_in_term02799 = new BitSet(new long[]{0x0000002000000000L});
public static final BitSet FOLLOW_37_in_term02801 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_ATOM_in_atom825 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_58_in_atom832 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_63_in_atom841 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_60_in_atom850 = new BitSet(new long[]{0x0000001000000000L});
public static final BitSet FOLLOW_36_in_atom852 = new BitSet(new long[]{0x0000000000000080L});
public static final BitSet FOLLOW_ATOM_in_atom854 = new BitSet(new long[]{0x0000002000000000L});
public static final BitSet FOLLOW_37_in_atom856 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_71_in_atom869 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_61_in_atom878 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_36_in_atom887 = new BitSet(new long[]{0xB40FF01800000080L,0x0000000000000080L});
public static final BitSet FOLLOW_formule_in_atom890 = new BitSet(new long[]{0x0000002000000000L});
public static final BitSet FOLLOW_37_in_atom892 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_NUMBER_in_etat907 = new BitSet(new long[]{0x0000000004000002L});
} | [
"jeremymorosi@hotmail.fr@faacee29-6519-3c6a-2639-f3781addc0c1"
] | jeremymorosi@hotmail.fr@faacee29-6519-3c6a-2639-f3781addc0c1 |
3ad32fc65dc758e5062d787de69c1b8a931c23f0 | 6f581e209761374a5fa4d49730cff4e8fedc06cb | /src/main/java/ru/epam/javacore/lesson_18_19_20_java_8/homework/cargo/domain/FoodCargo.java | df646ab902b3c0f066cc8e77f0849349cf215bb9 | [] | no_license | DmitryYusupov/epamjavacore | b4cfe78ba608e05d855568704b13d696d357474a | 6f5009c89d372dbeb7dd5daffaed47e383ad93c0 | refs/heads/master | 2022-02-14T00:42:11.032705 | 2020-02-13T08:31:15 | 2020-02-13T08:31:15 | 225,563,013 | 0 | 10 | null | 2022-01-21T23:37:23 | 2019-12-03T07:59:48 | Java | UTF-8 | Java | false | false | 631 | java | package ru.epam.javacore.lesson_18_19_20_java_8.homework.cargo.domain;
import java.util.Date;
public class FoodCargo extends Cargo {
private Date expirationDate;
private int storeTemperature;
@Override
public CargoType getCargoType() {
return CargoType.FOOD;
}
public Date getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(Date expirationDate) {
this.expirationDate = expirationDate;
}
public int getStoreTemperature() {
return storeTemperature;
}
public void setStoreTemperature(int storeTemperature) {
this.storeTemperature = storeTemperature;
}
}
| [
"Dmitry_Yusupov@epam.com"
] | Dmitry_Yusupov@epam.com |
5dd151ec0b3d5c4d410b69242ceac8e9781b4b6e | ae69836f8866e1765f1ce9dcef414548a93609ce | /src/round/RoundDAO.java | 125ea3f9203bcc783c7e985445a4f30bb2908253 | [] | no_license | kyupkyup/doggerbox | d30f331709c86f7ab9373c58be8bbe39489931b4 | 65f8053721240e41bff5d244eaed2d72ecec541b | refs/heads/master | 2020-05-18T19:34:11.770441 | 2019-11-18T11:05:20 | 2019-11-18T11:05:20 | 184,610,613 | 0 | 0 | null | null | null | null | UHC | Java | false | false | 4,471 | java | package round;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import doggerboxuser.DoggerboxUser;
public class RoundDAO {
private Connection conn;
private PreparedStatement pstmt;
private ResultSet rs;
public RoundDAO() {
try {
String dbURL = "jdbc:mysql://localhost/doggerbox1?serverTimezone=UTC"; //서버 선언
String dbID = "doggerbox1";
String dbPassword = "a1870523!!";
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(dbURL, dbID, dbPassword); //연결시켜서 conn에 저장
}
catch(Exception e) {
e.printStackTrace();
}
}
public int getNext() {
String SQL = "SELECT roundPrimeNum FROM doggerboxRound ORDER BY roundPrimeNum DESC";
try {
PreparedStatement pstmt = conn.prepareStatement(SQL);
rs = pstmt.executeQuery();
if(rs.next()) {
return rs.getInt(1) + 1;
}
return 1; // 첫번째 게시글인 경우
}
catch(Exception e) {
e.printStackTrace();
}
return -1; //데이터베이스 오류
}
public int roundAdd(String roundDeliveryDate, String roundTitle) {
String SQL = "INSERT INTO doggerboxRound VALUES(?,?,?)";
try {
pstmt = conn.prepareStatement(SQL);
pstmt.setString(1, roundDeliveryDate);
pstmt.setInt(2, getNext());
pstmt.setString(3, roundTitle);
return pstmt.executeUpdate();
}
catch(Exception e) {
e.printStackTrace();
}
return -1; //데이터베이스 오류
}
public Round getRound(int roundPrimeNum) {
String SQL = "SELECT * FROM doggerboxRound WHERE roundPrimeNum = ? ";
try {
PreparedStatement pstmt = conn.prepareStatement(SQL);
pstmt.setInt(1, roundPrimeNum);
rs = pstmt.executeQuery();
if(rs.next()) {
Round round = new Round();
round.setRoundDeliveryDate(rs.getString(1));
round.setRoundPrimeNum(rs.getInt(2));
round.setRoundTitle(rs.getString(3));
return round;
}
}
catch(Exception e) {
e.printStackTrace();
}
return null; // 불러오기 실패
}
public ArrayList<Round> getList(){
String SQL = "SELECT * FROM round";
ArrayList<Round> list = new ArrayList<Round>();
try {
PreparedStatement pstmt = conn.prepareStatement(SQL);
rs = pstmt.executeQuery();
while(rs.next()) {
Round round = new Round();
round.setRoundDeliveryDate(rs.getString(1));
round.setRoundPrimeNum(rs.getInt(2));
round.setRoundTitle(rs.getString(3));
list.add(round);
}
}
catch(Exception e) {
e.printStackTrace();
}
return list; //데이터 반환
}
public String getRoundTitle(int roundPrimeNum){
String SQL = "SELECT roundTitle FROM doggerboxRound WHERE roundPrimeNum = ? ";
try {
PreparedStatement pstmt = conn.prepareStatement(SQL);
pstmt.setInt(1, roundPrimeNum);
rs = pstmt.executeQuery();
if(rs.next()) {
return rs.getString(1);
}
else
{
return null;
}
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
public String getRoundDeliveryDate(int roundPrimeNum){
String SQL = "SELECT roundDeliveryDate FROM doggerboxRound WHERE roundPrimeNum = ? ";
try {
PreparedStatement pstmt = conn.prepareStatement(SQL);
pstmt.setInt(1, roundPrimeNum);
rs = pstmt.executeQuery();
if(rs.next()) {
return rs.getString(1);
}
else
{
return null;
}
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
public int roundUpdate(String roundDeliveryDate, String roundTitle, int roundPrimeNum) {
String SQL = "update doggerboxRound set roundDeliveryDate =?, roundTitle=? where roundPrimeNum=?";
try {
pstmt = conn.prepareStatement(SQL);
pstmt.setString(1, roundDeliveryDate);
pstmt.setString(2, roundTitle);
pstmt.setInt(3, roundPrimeNum);
return pstmt.executeUpdate();
}
catch(Exception e) {
e.printStackTrace();
}
return -1; //데이터베이스 오류
}
public int deleteRound(int roundPrimeNum) {
String SQL = "delete from doggerboxRound WHERE roundPrimeNum = ?";
try {
PreparedStatement pstmt = conn.prepareStatement(SQL);
pstmt.setInt(1, roundPrimeNum);
return pstmt.executeUpdate();
}
catch(Exception e) {
e.printStackTrace();
}
return -1; //데이터베이스 오류
}
}
| [
"rudduqdl@naver.com"
] | rudduqdl@naver.com |
515c8dc8d6b90351be53e7e70d20d6a72dc00bc1 | e83a76fead2de256db9a67d216f52b1f74541b88 | /src/main/java/zabi/minecraft/covens/common/enchantment/ModEnchantments.java | 7b411a956a3f8f208a487524d25d792a47257b7d | [] | no_license | Ionharin/Covens | a4d3489c0283317540d78f523f4c6d1053c623fc | 2a05138a8d6e4916118b7427a0b27748f4aef538 | refs/heads/master | 2021-05-12T19:41:06.619335 | 2017-12-03T20:18:53 | 2017-12-03T20:18:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,057 | java | package zabi.minecraft.covens.common.enchantment;
import zabi.minecraft.covens.common.lib.Log;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.Enchantment.Rarity;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
public class ModEnchantments {
public static Enchantment soul_siphon, curse_resilience, spell_shielding;
public static void registerAll() {
MinecraftForge.EVENT_BUS.register(new ModEnchantments());
Log.i("Creating Enchantments");
soul_siphon = new EnchantmentTalismans(Rarity.UNCOMMON, "soul_siphon");
curse_resilience = new EnchantmentTalismans(Rarity.COMMON, "curse_resilience");
spell_shielding = new EnchantmentTalismans(Rarity.UNCOMMON, "spell_shielding");
}
@SubscribeEvent
public void registerEnchantment(RegistryEvent.Register<Enchantment> evt) {
Log.i("Registering Enchantments");
evt.getRegistry().registerAll(soul_siphon, curse_resilience, spell_shielding);
}
}
| [
"zabi94@gmail.com"
] | zabi94@gmail.com |
47b9cf84237236b54053c80b3b99ff592ddbe2a5 | 29261321441a1fff6971ea5a2ce66cfc3087df8a | /Net/ConnectServer.java | 1c7dffdb56beeb36dc6c69cf820a27259087757d | [] | no_license | amitsrivastava4all/javabatchjune430 | 364a1bb24ef7665abcbdaeb3cef0bd35536ade2f | 02aedf231a37b8b450aa67473d93c7846d4f4431 | refs/heads/master | 2020-04-06T07:10:04.411283 | 2016-09-10T09:33:47 | 2016-09-10T09:33:47 | 62,220,158 | 3 | 2 | null | null | null | null | UTF-8 | Java | false | false | 1,118 | java | import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
public class ConnectServer {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String path = "/Users/amit/Documents/downloadlocation";
System.out.println("Enter the URL to Connect....");
String urlValue = new Scanner(System.in).next();
String fileName = urlValue.substring(urlValue.lastIndexOf("/"));
System.out.println("URL VALUE is "+urlValue);
System.out.println("FileName is "+fileName);
System.out.println("Path is "+path);
System.out.println("Full Path "+path+fileName);
FileOutputStream fs = new FileOutputStream(path+fileName);
URL url =new URL(urlValue);
URLConnection connection = url.openConnection();
connection.connect();
InputStream is = connection.getInputStream();
int singleByte = is.read();
while(singleByte!=-1){
fs.write(singleByte);
System.out.print((char)singleByte);
singleByte = is.read();
}
fs.close();
is.close();
}
}
| [
"amit4alljava@gmail.com"
] | amit4alljava@gmail.com |
4bed59a506bdbfafa84a0d1a5eb3e0faa5f78b38 | 3b9ec463f4247eeac3c5dbaee1739b3a8f875abf | /SwingCamera/src/main/java/org/freedesktop/gstreamer/examples/SwingCamera.java | e05a85d9ba1f7679d43e1eebc0aa622b4fff8edf | [] | no_license | gstreamer-java/gst1-java-examples | bd6624c384ec3971d84a32c6dfd2f5ee9ea9b5e8 | 0667161ac70d3c8394990e8c010947c3a6aed7fe | refs/heads/master | 2022-09-17T06:04:29.444764 | 2022-09-02T12:08:10 | 2022-09-02T12:08:10 | 42,820,401 | 50 | 43 | null | 2022-09-05T17:22:40 | 2015-09-20T16:35:10 | Java | UTF-8 | Java | false | false | 3,453 | java | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2021 Neil C Smith - Codelerity Ltd.
*
* Copying and distribution of this file, with or without modification,
* are permitted in any medium without royalty provided the copyright
* notice and this notice are preserved. This file is offered as-is,
* without any warranty.
*
*/
package org.freedesktop.gstreamer.examples;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import org.freedesktop.gstreamer.Bin;
import org.freedesktop.gstreamer.Gst;
import org.freedesktop.gstreamer.Pipeline;
import org.freedesktop.gstreamer.Version;
import org.freedesktop.gstreamer.swing.GstVideoComponent;
/**
* Displays camera input to a Swing window. By using autovideosrc, this will
* revert to a test video source if no camera is detected.
*
* @author Neil C Smith ( https://www.codelerity.com )
*
*/
public class SwingCamera {
/**
* Always store the top-level pipeline reference to stop it being garbage
* collected.
*/
private static Pipeline pipeline;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
/**
* Set up paths to native GStreamer libraries - see adjacent file.
*/
Utils.configurePaths();
/**
* Initialize GStreamer. Always pass the lowest version you require -
* Version.BASELINE is GStreamer 1.8. Use Version.of() for higher.
* Features requiring later versions of GStreamer than passed here will
* throw an exception in the bindings even if the actual native library
* is a higher version.
*/
Gst.init(Version.BASELINE, "SwingCamera", args);
EventQueue.invokeLater(() -> {
/**
* GstVideoComponent from gst1-java-swing is a Swing component that
* wraps a GStreamer AppSink to display video in a Swing UI.
*/
GstVideoComponent vc = new GstVideoComponent();
/**
* Parse a Bin to contain the autovideosrc from a GStreamer string
* representation. The alternative approach would be to create and
* link the elements in code using ElementFactory::make.
*
* The Bin uses a capsfilter to specify a width and height, as well
* as a videoconvert element to convert the video format to that
* required by GstVideoComponent, and a videoscale in case the
* source does not support the required resolution.
*
* The bin is added to a top-level pipeline and linked to the
* AppSink from the Swing component.
*/
Bin bin = Gst.parseBinFromDescription(
"autovideosrc ! "
+ "videoscale ! videoconvert ! "
+ "capsfilter caps=video/x-raw,width=640,height=480",
true);
pipeline = new Pipeline();
pipeline.addMany(bin, vc.getElement());
Pipeline.linkMany(bin, vc.getElement());
JFrame f = new JFrame("Camera Test");
f.add(vc);
vc.setPreferredSize(new Dimension(640, 480));
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pipeline.play();
f.setVisible(true);
});
}
}
| [
"neil@codelerity.com"
] | neil@codelerity.com |
f2ac6a871fa08a37b802fb9ec0539ab448f28a12 | 2958df3f24ae8a8667394b6ebb083ba6a9a1d36a | /Universal08Cloud/src/br/UFSC/GRIMA/util/Ponto.java | 1836edabcb88ff185a079247d2a375c740a46398 | [] | no_license | igorbeninca/utevolux | 27ac6af9a6d03f21d815c057f18524717b3d1c4d | 3f602d9cf9f58d424c3ea458346a033724c9c912 | refs/heads/master | 2021-01-19T02:50:04.157218 | 2017-10-13T16:19:41 | 2017-10-13T16:19:41 | 51,842,805 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 781 | java | package br.UFSC.GRIMA.util;
import java.io.Serializable;
public class Ponto implements Serializable{
private double x;
private double y;
private double z;
public Ponto(double x, double y, double z) {
// TODO Auto-generated constructor stub
this.x = x;
this.y = y;
this.z = z;
}
public double getX()
{
return this.x;
}
public double getY()
{
return this.y;
}
public double getZ()
{
return this.z;
}
public void setX(double x) {
this.x = x;
}
public void setY(double y) {
this.y = y;
}
public void setZ(double z) {
this.z = z;
}
public String toString(){
return "X=" + x + " Y=" + y + " Z=" + z;
}
public String getDados(){
return ("[" + x + ", " + y + ", " + z + "]\n");
}
}
| [
"pilarrmeister@gmail.com"
] | pilarrmeister@gmail.com |
6d2791538b3c53fa8839e6234b7c099a7aee19cf | eece75a31b7b5acb4e2f34d3edc103bc4b4dc6d8 | /viikko1/teht14-16/NhlStatistics1/src/test/java/ohtuesimerkki/StatisticsTest.java | 51f348680e9a1ff25e38d1d7c7d23361a9fc1018 | [] | no_license | JFaarinen/ohtu-2020-tehtavat | 9dd08094efbd7ae0f444d52c8ad909d9923983e6 | 005c411b1188d0737a7c8fde8191db1b0c8b53ec | refs/heads/master | 2021-01-01T03:04:02.111097 | 2020-04-27T13:37:49 | 2020-04-27T13:37:49 | 239,152,924 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,106 | java | package ohtuesimerkki;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import java.util.List;
import java.util.ArrayList;
/**
*
* @author Juho
*/
public class StatisticsTest {
Reader readerStub = new Reader() {
public List<Player> getPlayers() {
ArrayList<Player> players = new ArrayList<>();
players.add(new Player("Semenko", "EDM", 4, 12));
players.add(new Player("Lemieux", "PIT", 45, 54));
players.add(new Player("Kurri", "EDM", 37, 53));
players.add(new Player("Yzerman", "DET", 42, 56));
players.add(new Player("Gretzky", "EDM", 35, 89));
return players;
}
};
Statistics stats;
@Before
public void setUp(){
// luodaan Statistics-olio joka käyttää "stubia"
stats = new Statistics(readerStub);
}
public StatisticsTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@After
public void tearDown() {
}
@Test
public void playerHakeeOikeanPelaajan() {
Player p = stats.search("Semenko");
assertEquals("Semenko", p.getName());
}
@Test
public void playerPalauttaaTyhjanJosPelaajaaEiLoydy() {
Player p = stats.search("Koivu");
assertEquals(null, p);
}
@Test
public void teamHakeeJoukkueenPelaajat() {
List pelaajat = stats.team("EDM");
assertEquals(3, pelaajat.size());
}
@Test
public void topScoresPalauttaaOikeatPisteet() {
List top = stats.topScorers(3);
Player grezky = (Player)top.get(0);
assertEquals(3, top.size());
assertEquals(124, grezky.getPoints());
}
}
| [
"juho.faarinen@gmail.com"
] | juho.faarinen@gmail.com |
0cf7dc8bea2dac3f5806ca1886d603163b2436a1 | 392f127a16e72dd2b24baa1718d76eff983b955d | /AndroidGenesisSample/src/main/java/com/emerchantpay/gateway/androidgenesissample/activities/TransactionDetailsActivity.java | bfa07e43f1577ac043118df2f0ca9c831e0a11c8 | [
"MIT"
] | permissive | plpt88/android_app | 5b70fad348e8cb4d37820cd158a25f446b68074f | 31e1cad3ee1e2e6f102c03e81c1bd2c7f5809ce0 | refs/heads/master | 2020-06-08T03:41:52.560001 | 2019-06-24T09:12:26 | 2019-06-24T09:12:26 | 193,150,344 | 0 | 0 | MIT | 2019-06-21T19:29:44 | 2019-06-21T19:29:43 | null | UTF-8 | Java | false | false | 8,521 | java | package com.emerchantpay.gateway.androidgenesissample.activities;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import com.emerchantpay.gateway.androidgenesissample.R;
import com.emerchantpay.gateway.androidgenesissample.handlers.AlertDialogHandler;
import com.emerchantpay.gateway.androidgenesissample.handlers.TransactionDetailsHandler;
import com.emerchantpay.gateway.genesisandroid.api.constants.Endpoints;
import com.emerchantpay.gateway.genesisandroid.api.constants.Environments;
import com.emerchantpay.gateway.genesisandroid.api.constants.ErrorMessages;
import com.emerchantpay.gateway.genesisandroid.api.constants.IntentExtras;
import com.emerchantpay.gateway.genesisandroid.api.constants.KlarnaItemTypes;
import com.emerchantpay.gateway.genesisandroid.api.constants.Locales;
import com.emerchantpay.gateway.genesisandroid.api.constants.TransactionTypes;
import com.emerchantpay.gateway.genesisandroid.api.internal.Genesis;
import com.emerchantpay.gateway.genesisandroid.api.internal.request.PaymentRequest;
import com.emerchantpay.gateway.genesisandroid.api.internal.request.TransactionTypesRequest;
import com.emerchantpay.gateway.genesisandroid.api.internal.response.Response;
import com.emerchantpay.gateway.genesisandroid.api.models.Country;
import com.emerchantpay.gateway.genesisandroid.api.models.Currency;
import com.emerchantpay.gateway.genesisandroid.api.models.DynamicDescriptorParams;
import com.emerchantpay.gateway.genesisandroid.api.models.GenesisError;
import com.emerchantpay.gateway.genesisandroid.api.models.PaymentAddress;
import com.emerchantpay.gateway.genesisandroid.api.models.RiskParams;
import com.emerchantpay.gateway.genesisandroid.api.util.Configuration;
import java.math.BigDecimal;
import java.util.HashMap;
public class TransactionDetailsActivity extends Activity {
// Alert dialog
private AlertDialogHandler dialogHandler;
// Genesis Handler error
private GenesisError error;
// Transaction details
TransactionDetailsHandler transactionDetails = new TransactionDetailsHandler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transaction_details);
// Load params to UI
transactionDetails.setUIParams(this);
try {
// Load currencies and countries
Currency currencyObject = new Currency();
Country countryObject = new Country();
ArrayAdapter<String> currenciesAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, currencyObject.getCurrencies());
currenciesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ArrayAdapter<String> countriesAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, countryObject.getCountryNames());
countriesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Adapters Hash map
HashMap<String, ArrayAdapter<String>> adapters = new HashMap<String, ArrayAdapter<String>>();
adapters.put("currency", currenciesAdapter);
adapters.put("country", countriesAdapter);
// Add spinners
transactionDetails.addSpinners(this, adapters);
} catch (IllegalAccessException e) {
Log.e("Illegal Exception", e.toString());
}
}
public void loadPaymentView(View view) throws IllegalAccessException {
// Get param values from UI
transactionDetails.getUIParams();
// Create configuration
Configuration configuration = new Configuration("SET_YOUR_USERNAME",
"SET_YOUR_PASSWORD",
Environments.STAGING, Endpoints.EMERCHANTPAY,
Locales.EN);
configuration.setDebugMode(true);
// Create Billing PaymentAddress
PaymentAddress billingAddress = new PaymentAddress(transactionDetails.getFirstname(),
transactionDetails.getLastname(), transactionDetails.getAddress1(), transactionDetails.getAddress2(),
transactionDetails.getZipCode(), transactionDetails.getCity(), transactionDetails.getState(),
new Country().getCountry(transactionDetails.getCountry()));
// Create Transaction types
TransactionTypesRequest transactionTypes = new TransactionTypesRequest();
transactionTypes.addTransaction(transactionDetails.getTransactionType());
// Risk params
RiskParams riskParams = new RiskParams("1002547", "1DA53551-5C60-498C-9C18-8456BDBA74A9",
"987-65-4320", "12-34-56-78-9A-BC", "123456",
"emil@example.com", "+49301234567", "245.253.2.12",
"10000000000", "1234", "100000000", "John",
"Doe", "US", "test", "245.25 3.2.12",
"test", "test123456", "Bin name",
"+49301234567");
// Dynamic descriptor params
DynamicDescriptorParams dynamicDescriptorParams = new DynamicDescriptorParams("eMerchantPay Ltd",
"Sofia");
// Init WPF API request
PaymentRequest paymentRequest = new PaymentRequest(this,
transactionDetails.getTransactionId(), new BigDecimal(transactionDetails.getAmount()),
new Currency().findCurrencyByName(transactionDetails.getCurrency()),
transactionDetails.getCustomerEmail(), transactionDetails.getCustomerPhone(),
billingAddress, transactionDetails.getNotificationUrl(), transactionTypes);
// Additionaly params
paymentRequest.setUsage(transactionDetails.getUsage());
paymentRequest.setLifetime(60);
paymentRequest.setRiskParams(riskParams);
Genesis genesis = new Genesis(this, configuration, paymentRequest);
if (!genesis.isConnected(this)) {
dialogHandler = new AlertDialogHandler(this, "Error",
ErrorMessages.CONNECTION_ERROR);
dialogHandler.show();
} else if (genesis.isConnected(this) && genesis.isValidData()) {
//Execute WPF API request
genesis.push();
// Get response
Response response = genesis.getResponse();
// Check if response isSuccess
if (!response.isSuccess()) {
// Get Error Handler
error = response.getError();
dialogHandler = new AlertDialogHandler(this, "Failure",
"Code: " + error.getCode() + "\nMessage: "
+ error.getMessage());
dialogHandler.show();
}
} else if (!genesis.isValidData()) {
// Get Error Handler
error = genesis.getError();
String message = error.getMessage();
String technicalMessage;
if (error.getTechnicalMessage() != null && !error.getTechnicalMessage().isEmpty()) {
technicalMessage = error.getTechnicalMessage();
} else {
technicalMessage = "";
}
dialogHandler = new AlertDialogHandler(this, "Invalid",
technicalMessage + " " + message);
dialogHandler.show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == RESULT_FIRST_USER) {
// Make sure the request was successful
if (resultCode == RESULT_CANCELED && data != null) {
dialogHandler = new AlertDialogHandler(this, "Cancel", "Cancel");
dialogHandler.show();
}
if (resultCode == RESULT_OK) {
String technicalMessage = data.getStringExtra(IntentExtras.EXTRA_RESULT);
if (technicalMessage != null) {
dialogHandler = new AlertDialogHandler(this, "Failure",
technicalMessage);
dialogHandler.show();
} else {
dialogHandler = new AlertDialogHandler(this, "Success",
"Success");
dialogHandler.show();
}
}
}
}
}
| [
"plamen.petrov@emerchantpay.com"
] | plamen.petrov@emerchantpay.com |
bc3b756480289c49ca6c54fd68123bfcbca42e5d | 539d84c6f3ee281787ed50883ef748e827c8637e | /1st/homework_10/id_55/triangle_55.java | 50f699c2045010ad02b360c1aa2d51137e172c0e | [] | no_license | StuQAlgorithm/AlgorithmHomework | 513678422ff4a984b90d137d7dabe075d23f5dcf | 88da6b274e49ce97d432e1f4d4de8efa55593836 | refs/heads/master | 2021-01-21T06:52:35.934321 | 2017-10-09T02:12:52 | 2017-10-09T02:12:52 | 101,950,372 | 6 | 12 | null | 2017-10-09T02:12:53 | 2017-08-31T02:31:32 | Python | UTF-8 | Java | false | false | 506 | java | class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
if(triangle == null || triangle.size() == 0) return 0;
int n = triangle.size();
int[] min = new int[triangle.get(n - 1).size() + 1]; //as add one layer to the bottom
for(int i = n - 1; i >= 0; i--){
for(int j = 0; j < triangle.get(i).size(); j++){
min[j] = triangle.get(i).get(j) + Math.min(min[j], min[j + 1]);
}
}
return min[0];
}
} | [
"wangye@wangyedeMBP.lan"
] | wangye@wangyedeMBP.lan |
d0fdd30db9e43a413ab4a9d2002e823038ec7d48 | 3c4747720b0f10e8caa00bf0ed472563ba88f975 | /Femina/app/src/androidTest/java/com/alejandro/android/femina/ExampleInstrumentedTest.java | 44fe3a01e5b1f0c5e76a5ae9af1b786e364fc5b7 | [] | no_license | bbchiaradia/FEMINA | f5613ea384636d452e4cae047c3eca8fbedd1e65 | e37b039ac454eb350a1d2b49bc41ec93cda7ef69 | refs/heads/master | 2023-01-14T04:10:28.610929 | 2020-11-20T01:36:38 | 2020-11-20T01:36:38 | 299,344,797 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 770 | java | package com.alejandro.android.femina;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.alejandro.android.femina", appContext.getPackageName());
}
} | [
"ale.salgado08@hotmail.com"
] | ale.salgado08@hotmail.com |
f1f096c94df22b3a6ad7aa557366c2e2358ec074 | 1fda88262a94119ce17345564937f42bf2df388c | /src/main/java/controller/AddProduto.java | 10f9c236e7a545f579e5a23d289be9c0b809f0a6 | [] | no_license | Dhonrian/cookies | 941f29cd8ffb95a26500782b16c228f590a2aafe | 050ed6391b1b8c36d629669cad3cd7918b08c44c | refs/heads/master | 2020-11-25T22:58:43.749175 | 2019-12-18T16:53:15 | 2019-12-18T16:53:15 | 228,881,034 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 919 | java |
package controller;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.ServletContext;
import javax.servlet.annotation.WebServlet;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.List;
import model.Produto;
import model.ProdutoDAO;
@WebServlet(urlPatterns="/AddProduto")
public class AddProduto extends HttpServlet {
@Override
public void doGet( HttpServletRequest req,
HttpServletResponse res){
ServletContext sc = req.getServletContext();
String path = req.getRequestURI();
try{
sc.getRequestDispatcher("/jsp/AddProduto.jsp").forward(req, res);
} catch (Exception e){
System.out.println(e);
}
}
} | [
"leonardo.tamanhao@gmail.com"
] | leonardo.tamanhao@gmail.com |
dcb2642df6ec690a6c849ce5dfb02766ed5bd857 | 4e911bf160344c43395116ebdfd361501075c356 | /controller-module/src/test/java/com/gmail/salahub/nikolay/online/market/nsalahub/webcontroller/controller/rest/UserRestControllerTest.java | 4521e0209047ea8ae2bb1eef61a3968a11f48cc1 | [] | no_license | nsalahub/online_market_nsalahub | e7af8b9f116a61981823d9083c0c566c23ec10af | 4a2b23fdc88982956787f94a3bc80368e6916f0b | refs/heads/master | 2022-04-30T22:26:17.788433 | 2019-06-10T13:45:52 | 2019-06-10T13:45:52 | 184,597,641 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,202 | java | package com.gmail.salahub.nikolay.online.market.nsalahub.webcontroller.controller.rest;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gmail.salahub.nikolay.online.market.nsalahub.service.model.user.UserDTO;
import com.gmail.salahub.nikolay.online.market.nsalahub.webcontroller.controller.testmodel.TestModel;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.ANY)
public class UserRestControllerTest {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.build();
}
private UserDTO userDTO = TestModel.getTestUserForRest();
@Test
public void shouldCreateUser() throws Exception {
mvc.perform(post("/api/users")
.contentType(MediaType.APPLICATION_PROBLEM_JSON_UTF8)
.content(asJsonString(userDTO)))
.andExpect(status().isCreated());
}
private static String asJsonString(final Object obj) {
try {
final ObjectMapper mapper = new ObjectMapper();
final String jsonContent = mapper.writeValueAsString(obj);
return jsonContent;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| [
"nikolay.salahub@gmail.com"
] | nikolay.salahub@gmail.com |
a15c94d04fa8debbb8c403260eebde555caa47b8 | c0077ec0a25ccab1731b6646ae773abaf0408ddf | /src/main/java/BinaryTree.java | b15a5f3bc99529f81ff8e00ea7deb6e0ee01684d | [] | no_license | emmanuelHa/coding-interview | 712b04694aa63d770da4c67ae35e06d8e6721e45 | a98dc365e613a1126f102fc07720bbdbd0b53d8d | refs/heads/master | 2021-07-11T04:43:03.026443 | 2019-08-27T16:56:49 | 2019-08-27T16:56:49 | 204,734,109 | 0 | 0 | null | 2020-10-13T15:37:40 | 2019-08-27T15:33:00 | Java | UTF-8 | Java | false | false | 7,845 | java | import javax.swing.tree.TreeNode;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class BinaryTree {
Node root;
/*
* Definition for a binary tree node.
**
*/
public static class Node {
int value;
Node left;
Node right;
Node(int x) {
value = x;
}
}
public void add(int value) {
root = addRecursive(root, value);
}
public boolean containsNode(int value) {
return containsNodeRecursive(root, value);
}
public void traverseInOrder(Node node) {
if (node != null) {
traverseInOrder(node.left);
System.out.print(" " + node.value);
traverseInOrder(node.right);
}
}
public void traversePreOrder(Node node) {
if (node != null) {
System.out.print(" " + node.value);
traversePreOrder(node.left);
traversePreOrder(node.right);
}
}
public void traversePostOrder(Node node) {
if (node != null) {
traversePostOrder(node.left);
traversePostOrder(node.right);
System.out.print(" " + node.value);
}
}
public void traverseLevelOrder() {
if (root == null) {
return;
}
Queue<Node> nodes = new LinkedList<>();
nodes.add(root);
while (!nodes.isEmpty()) {
Node node = nodes.remove();
System.out.print(" " + node.value);
if (node.left != null) {
nodes.add(node.left);
}
if (node.right!= null) {
nodes.add(node.right);
}
}
}
public void delete(int value) {
root = deleteRecursive(root, value);
}
private Node addRecursive(Node current, int value) {
if (current == null) {
return new Node(value);
}
if (value < current.value) {
current.left = addRecursive(current.left, value);
} else if (value > current.value) {
current.right = addRecursive(current.right, value);
} else {
// value already exists
return current;
}
return current;
}
private boolean containsNodeRecursive(Node current, int value) {
if (current == null) {
return false;
}
if (value == current.value) {
return true;
}
return value < current.value
? containsNodeRecursive(current.left, value)
: containsNodeRecursive(current.right, value);
}
private Node deleteRecursive(Node current, int value) {
if (current == null) {
return null;
}
if (value == current.value) {
// Node to delete found
// ... code to delete the node will go here
if (current.left == null && current.right == null) {
return null;
}
if (current.right == null) {
return current.left;
}
if (current.left == null) {
return current.right;
}
int smallestValue = findSmallestValue(current.right);
current.value = smallestValue;
current.right = deleteRecursive(current.right, smallestValue);
}
if (value < current.value) {
current.left = deleteRecursive(current.left, value);
return current;
}
current.right = deleteRecursive(current.right, value);
return current;
}
private int findSmallestValue(Node root) {
return root.left == null ? root.value : findSmallestValue(root.left);
}
static BinaryTree createBinaryTree() {
BinaryTree bt = new BinaryTree();
bt.add(6);
bt.add(4);
bt.add(8);
bt.add(3);
bt.add(5);
bt.add(7);
bt.add(9);
return bt;
}
public static String NodeToString(Node root) {
if (root == null) {
return "[]";
}
String output = "";
Queue<Node> nodeQueue = new LinkedList<>();
nodeQueue.add(root);
while (!nodeQueue.isEmpty()) {
Node node = nodeQueue.remove();
if (node == null) {
output += "null, ";
continue;
}
output += String.valueOf(node.value) + ", ";
nodeQueue.add(node.left);
nodeQueue.add(node.right);
}
return "[" + output.substring(0, output.length() - 2) + "]";
}
public static Node stringToNode(String input) {
input = input.trim();
input = input.substring(1, input.length() - 1);
if (input.length() == 0) {
return null;
}
String[] parts = input.split(",");
String item = parts[0];
Node root = new Node(Integer.parseInt(item));
Queue<Node> nodeQueue = new LinkedList<>();
nodeQueue.add(root);
int index = 1;
while (!nodeQueue.isEmpty()) {
Node node = nodeQueue.remove();
if (index == parts.length) {
break;
}
item = parts[index++];
item = item.trim();
if (!item.equals("null")) {
int leftNumber = Integer.parseInt(item);
node.left = new Node(leftNumber);
nodeQueue.add(node.left);
}
if (index == parts.length) {
break;
}
item = parts[index++];
item = item.trim();
if (!item.equals("null")) {
int rightNumber = Integer.parseInt(item);
node.right = new Node(rightNumber);
nodeQueue.add(node.right);
}
}
return root;
}
public static void prettyPrintTree(Node node, String prefix, boolean isLeft) {
if (node == null) {
System.out.println("Empty tree");
return;
}
if (node.right != null) {
prettyPrintTree(node.right, prefix + (isLeft ? "│ " : " "), false);
}
System.out.println(prefix + (isLeft ? "└── " : "┌── ") + node.value);
if (node.left != null) {
prettyPrintTree(node.left, prefix + (isLeft ? " " : "│ "), true);
}
}
public static void prettyPrintTree(Node node) {
prettyPrintTree(node, "", true);
}
/*ArrayList<LinkedList<TreeNode>> findLevelLinkList(TreeNode root) {
int level = 0;
ArrayList<LinkedList<TreeNode>> result = new ArrayList<>();
LinkedList<TreeNode> list = new LinkedList<>();
list.add(root);
result.add(level, list);
while (true) {
list = new LinkedList<>();
for (int i = 0; i < result.get(level).size(); i++) {
TreeNode n = result.get(level).get(i);
if (n != null) {
if(n.left != null) list.add(n.left);
if(n.right!= null) list.add(n.right);
}
}
if (list.size() > 0) {
result.add(level + 1, list);
} else {
break;
}
level++;
}
return result;
}*/
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = in.readLine()) != null) {
BinaryTree.Node root = BinaryTree.stringToNode(line);
BinaryTree.prettyPrintTree(root);
}
}
}
| [
"emmanuel.harel@zenika.com"
] | emmanuel.harel@zenika.com |
45a3f002b9cfecb312ad4f7e182f0a5c8cc736f1 | e907266594f78ecfdfdcfe903f3ed47906db3e20 | /LaundryApp/src/com/washhous/menudrawer/NavDrawerItem.java | e2a3d2dd7eaf7907a257c05ced551afd2e9c8271 | [] | no_license | LilhareAnand/EaxampleDemo | 6c5482ccaa4451f6486e00488de0393f83e36e62 | c7f82875f6708bf45369fef7f9298b7b491589ef | refs/heads/master | 2020-05-18T16:30:05.075974 | 2015-08-24T04:51:38 | 2015-08-24T04:51:38 | 41,259,973 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,239 | java | package com.washhous.menudrawer;
public class NavDrawerItem {
private String title;
private int icon;
private String count = "0";
// boolean to set visiblity of the counter
private boolean isCounterVisible = false;
public NavDrawerItem(){}
public NavDrawerItem(String title, int icon){
this.title = title;
this.icon = icon;
}
public NavDrawerItem(String title, int icon, boolean isCounterVisible, String count){
this.title = title;
this.icon = icon;
this.isCounterVisible = isCounterVisible;
this.count = count;
}
public NavDrawerItem(String title) {
// TODO Auto-generated constructor stub
this.title = title;
}
public String getTitle(){
return this.title;
}
public int getIcon(){
return this.icon;
}
public String getCount(){
return this.count;
}
public boolean getCounterVisibility(){
return this.isCounterVisible;
}
public void setTitle(String title){
this.title = title;
}
public void setIcon(int icon){
this.icon = icon;
}
public void setCount(String count){
this.count = count;
}
public void setCounterVisibility(boolean isCounterVisible){
this.isCounterVisible = isCounterVisible;
}
}
| [
"anandlilhare69@gmail.com"
] | anandlilhare69@gmail.com |
87db351081a4e1293634fce5e04573beaa95f2e6 | e78ec3b8505370a4015b15e7cb8b28512495dc01 | /src/main/java/com/swcommodities/wsmill/domain/event/st/NewlyCreatedSTEvent.java | a5c3115cdb1c42c74b5917c70364af9065dab65d | [] | no_license | gmvn90/rooterp | ed4d4241e6848186753bc9acfae0e5dfd33e0ea5 | a9a5304d4b688a939c213e1c3620e19162d3892c | refs/heads/master | 2020-03-31T18:04:25.680272 | 2018-10-27T14:15:38 | 2018-10-27T14:15:38 | 152,445,454 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 464 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.swcommodities.wsmill.domain.event.st;
import com.swcommodities.wsmill.hibernate.dto.SampleType;
import lombok.Data;
import lombok.NonNull;
/**
*
* @author macOS
*/
@Data
public class NewlyCreatedSTEvent {
@NonNull private SampleType sampleType;
}
| [
"gmvn@Dinhs-MacBook-Air.local"
] | gmvn@Dinhs-MacBook-Air.local |
ce318b46e528c9d506ee968a8f404fdabc81e845 | f3785e28cb5d65fa76fc8e2270a4bcdeb2b294f7 | /maven-common/src/main/java/com/github/goldin/org/apache/tools/ant/taskdefs/optional/net/FTP.java | 6823d17117309e5580260ed0e462ba70b19589ef | [
"Apache-2.0"
] | permissive | hoggarth/maven-plugins | d3c67ef292504ecdc9074fdcde1c7d8f3390e14a | 1261ba3cba2d0488db34cecdd4c2d1e9d5c50571 | refs/heads/master | 2020-12-25T01:29:46.909587 | 2012-09-02T21:23:46 | 2012-09-02T21:23:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 102,984 | java | /**
* Copied from {@link org.apache.tools.ant.taskdefs.optional.net.FTP}, Ant v1.8.1
* with minor changes in {@link #execute()} and {@link #listFile}
*
* See http://evgeny-goldin.com/blog/2010/08/18/ant-ftp-task-progress-indicator-timeout/
*/
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.github.goldin.org.apache.tools.ant.taskdefs.optional.net;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.taskdefs.Delete;
import org.apache.tools.ant.types.EnumeratedAttribute;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.selectors.SelectorUtils;
import org.apache.tools.ant.util.FileUtils;
import org.apache.tools.ant.util.RetryHandler;
import org.apache.tools.ant.util.Retryable;
import org.apache.tools.ant.util.VectorSet;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Basic FTP client. Performs the following actions:
* <ul>
* <li> <strong>send</strong> - send files to a remote server. This is the
* default action.</li>
* <li> <strong>get</strong> - retrieve files from a remote server.</li>
* <li> <strong>del</strong> - delete files from a remote server.</li>
* <li> <strong>list</strong> - create a file listing.</li>
* <li> <strong>chmod</strong> - change unix file permissions.</li>
* <li> <strong>rmdir</strong> - remove directories, if empty, from a
* remote server.</li>
* </ul>
* <strong>Note:</strong> Some FTP servers - notably the Solaris server - seem
* to hold data ports open after a "retr" operation, allowing them to timeout
* instead of shutting them down cleanly. This happens in active or passive
* mode, and the ports will remain open even after ending the FTP session. FTP
* "send" operations seem to close ports immediately. This behavior may cause
* problems on some systems when downloading large sets of files.
*
* @since Ant 1.3
*/
public class FTP extends Task {
protected static final int SEND_FILES = 0;
protected static final int GET_FILES = 1;
protected static final int DEL_FILES = 2;
protected static final int LIST_FILES = 3;
protected static final int MK_DIR = 4;
protected static final int CHMOD = 5;
protected static final int RM_DIR = 6;
protected static final int SITE_CMD = 7;
/** return code of ftp - not implemented in commons-net version 1.0 */
private static final int CODE_521 = 521;
/** adjust uptodate calculations where server timestamps are HH:mm and client's
* are HH:mm:ss */
private static final long GRANULARITY_MINUTE = 60000L;
/** Date formatter used in logging, note not thread safe! */
private static final SimpleDateFormat TIMESTAMP_LOGGING_SDF =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/** Default port for FTP */
public static final int DEFAULT_FTP_PORT = 21;
private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
private String remotedir;
private String server;
private String userid;
private String password;
private String account;
private File listing;
private boolean listingFullPath = false;
private boolean listingAppend = false;
private boolean binary = true;
private boolean passive = false;
private boolean verbose = false;
private boolean newerOnly = false;
private long timeDiffMillis = 0;
private long granularityMillis = 0L;
private boolean timeDiffAuto = false;
private int action = SEND_FILES;
private Vector filesets = new Vector();
private Set dirCache = new HashSet();
private int transferred = 0;
private String remoteFileSep = "/";
private int port = DEFAULT_FTP_PORT;
private boolean skipFailedTransfers = false;
private int skipped = 0;
private boolean ignoreNoncriticalErrors = false;
private boolean preserveLastModified = false;
private String chmod = null;
private String umask = null;
private FTPSystemType systemTypeKey = FTPSystemType.getDefault();
private String defaultDateFormatConfig = null;
private String recentDateFormatConfig = null;
private LanguageCode serverLanguageCodeConfig = LanguageCode.getDefault();
private String serverTimeZoneConfig = null;
private String shortMonthNamesConfig = null;
private Granularity timestampGranularity = Granularity.getDefault();
private boolean isConfigurationSet = false;
private int retriesAllowed = 0;
private String siteCommand = null;
private String initialSiteCommand = null;
private boolean enableRemoteVerification = true;
protected static final String[] ACTION_STRS = {
"sending",
"getting",
"deleting",
"listing",
"making directory",
"chmod",
"removing",
"site"
};
protected static final String[] COMPLETED_ACTION_STRS = {
"sent",
"retrieved",
"deleted",
"listed",
"created directory",
"mode changed",
"removed",
"site command executed"
};
protected static final String[] ACTION_TARGET_STRS = {
"files",
"files",
"files",
"files",
"directory",
"files",
"directories",
"site command"
};
/**
* internal class providing a File-like interface to some of the information
* available from the FTP server
*
*/
protected static class FTPFileProxy extends File {
private final FTPFile file;
private final String[] parts;
private final String name;
/**
* creates a proxy to a FTP file
* @param file
*/
public FTPFileProxy(FTPFile file) {
super(file.getName());
name = file.getName();
this.file = file;
parts = FileUtils.getPathStack(name);
}
/**
* creates a proxy to a FTP directory
* @param completePath the remote directory.
*/
public FTPFileProxy(String completePath) {
super(completePath);
file = null;
name = completePath;
parts = FileUtils.getPathStack(completePath);
}
/* (non-Javadoc)
* @see java.io.File#exists()
*/
public boolean exists() {
return true;
}
/* (non-Javadoc)
* @see java.io.File#getAbsolutePath()
*/
public String getAbsolutePath() {
return name;
}
/* (non-Javadoc)
* @see java.io.File#getName()
*/
public String getName() {
return parts.length > 0 ? parts[parts.length - 1] : name;
}
/* (non-Javadoc)
* @see java.io.File#getParent()
*/
public String getParent() {
String result = "";
for(int i = 0; i < parts.length - 1; i++){
result += File.separatorChar + parts[i];
}
return result;
}
/* (non-Javadoc)
* @see java.io.File#getPath()
*/
public String getPath() {
return name;
}
/**
* FTP files are stored as absolute paths
* @return true
*/
public boolean isAbsolute() {
return true;
}
/* (non-Javadoc)
* @see java.io.File#isDirectory()
*/
public boolean isDirectory() {
return file == null;
}
/* (non-Javadoc)
* @see java.io.File#isFile()
*/
public boolean isFile() {
return file != null;
}
/**
* FTP files cannot be hidden
*
* @return false
*/
public boolean isHidden() {
return false;
}
/* (non-Javadoc)
* @see java.io.File#lastModified()
*/
public long lastModified() {
if (file != null) {
return file.getTimestamp().getTimeInMillis();
}
return 0;
}
/* (non-Javadoc)
* @see java.io.File#length()
*/
public long length() {
if (file != null) {
return file.getSize();
}
return 0;
}
}
/**
* internal class allowing to read the contents of a remote file system
* using the FTP protocol
* used in particular for ftp get operations
* differences with DirectoryScanner
* "" (the root of the fileset) is never included in the included directories
* followSymlinks defaults to false
*/
protected class FTPDirectoryScanner extends DirectoryScanner {
// CheckStyle:VisibilityModifier OFF - bc
protected FTPClient ftp = null;
// CheckStyle:VisibilityModifier ON
private String rootPath = null;
/**
* since ant 1.6
* this flag should be set to true on UNIX and can save scanning time
*/
private boolean remoteSystemCaseSensitive = false;
private boolean remoteSensitivityChecked = false;
/**
* constructor
* @param ftp ftpclient object
*/
public FTPDirectoryScanner(FTPClient ftp) {
super();
this.ftp = ftp;
this.setFollowSymlinks(false);
}
/**
* scans the remote directory,
* storing internally the included files, directories, ...
*/
public void scan() {
if (includes == null) {
// No includes supplied, so set it to 'matches all'
includes = new String[1];
includes[0] = "**";
}
if (excludes == null) {
excludes = new String[0];
}
filesIncluded = new VectorSet();
filesNotIncluded = new Vector();
filesExcluded = new VectorSet();
dirsIncluded = new VectorSet();
dirsNotIncluded = new Vector();
dirsExcluded = new VectorSet();
try {
String cwd = ftp.printWorkingDirectory();
// always start from the current ftp working dir
forceRemoteSensitivityCheck();
checkIncludePatterns();
clearCaches();
ftp.changeWorkingDirectory(cwd);
} catch (IOException e) {
throw new BuildException("Unable to scan FTP server: ", e);
}
}
/**
* this routine is actually checking all the include patterns in
* order to avoid scanning everything under base dir
* @since ant1.6
*/
private void checkIncludePatterns() {
Hashtable newroots = new Hashtable();
// put in the newroots vector the include patterns without
// wildcard tokens
for (int icounter = 0; icounter < includes.length; icounter++) {
String newpattern =
SelectorUtils.rtrimWildcardTokens(includes[icounter]);
newroots.put(newpattern, includes[icounter]);
}
if (remotedir == null) {
try {
remotedir = ftp.printWorkingDirectory();
} catch (IOException e) {
throw new BuildException("could not read current ftp directory",
getLocation());
}
}
AntFTPFile baseFTPFile = new AntFTPRootFile(ftp, remotedir);
rootPath = baseFTPFile.getAbsolutePath();
// construct it
if (newroots.containsKey("")) {
// we are going to scan everything anyway
scandir(rootPath, "", true);
} else {
// only scan directories that can include matched files or
// directories
Enumeration enum2 = newroots.keys();
while (enum2.hasMoreElements()) {
String currentelement = (String) enum2.nextElement();
String originalpattern = (String) newroots.get(currentelement);
AntFTPFile myfile = new AntFTPFile(baseFTPFile, currentelement);
boolean isOK = true;
boolean traversesSymlinks = false;
String path = null;
if (myfile.exists()) {
forceRemoteSensitivityCheck();
if (remoteSensitivityChecked
&& remoteSystemCaseSensitive && isFollowSymlinks()) {
// cool case,
//we do not need to scan all the subdirs in the relative path
path = myfile.getFastRelativePath();
} else {
// may be on a case insensitive file system. We want
// the results to show what's really on the disk, so
// we need to double check.
try {
path = myfile.getRelativePath();
traversesSymlinks = myfile.isTraverseSymlinks();
} catch (IOException be) {
throw new BuildException(be, getLocation());
} catch (BuildException be) {
isOK = false;
}
}
} else {
isOK = false;
}
if (isOK) {
currentelement = path.replace(remoteFileSep.charAt(0), File.separatorChar);
if (!isFollowSymlinks()
&& traversesSymlinks) {
continue;
}
if (myfile.isDirectory()) {
if (isIncluded(currentelement)
&& currentelement.length() > 0) {
accountForIncludedDir(currentelement, myfile, true);
} else {
if (currentelement.length() > 0) {
if (currentelement.charAt(currentelement
.length() - 1)
!= File.separatorChar) {
currentelement =
currentelement + File.separatorChar;
}
}
scandir(myfile.getAbsolutePath(), currentelement, true);
}
} else {
if (isCaseSensitive
&& originalpattern.equals(currentelement)) {
accountForIncludedFile(currentelement);
} else if (!isCaseSensitive
&& originalpattern
.equalsIgnoreCase(currentelement)) {
accountForIncludedFile(currentelement);
}
}
}
}
}
}
/**
* scans a particular directory. populates the scannedDirs cache.
*
* @param dir directory to scan
* @param vpath relative path to the base directory of the remote fileset
* always ended with a File.separator
* @param fast seems to be always true in practice
*/
protected void scandir(String dir, String vpath, boolean fast) {
// avoid double scanning of directories, can only happen in fast mode
if (fast && hasBeenScanned(vpath)) {
return;
}
try {
if (!ftp.changeWorkingDirectory(dir)) {
return;
}
String completePath = null;
if (!vpath.equals("")) {
completePath = rootPath + remoteFileSep
+ vpath.replace(File.separatorChar, remoteFileSep.charAt(0));
} else {
completePath = rootPath;
}
FTPFile[] newfiles = listFiles(completePath, false);
if (newfiles == null) {
ftp.changeToParentDirectory();
return;
}
for (int i = 0; i < newfiles.length; i++) {
FTPFile file = newfiles[i];
if (file != null
&& !file.getName().equals(".")
&& !file.getName().equals("..")) {
String name = vpath + file.getName();
scannedDirs.put(name, new FTPFileProxy(file));
if (isFunctioningAsDirectory(ftp, dir, file)) {
boolean slowScanAllowed = true;
if (!isFollowSymlinks() && file.isSymbolicLink()) {
dirsExcluded.addElement(name);
slowScanAllowed = false;
} else if (isIncluded(name)) {
accountForIncludedDir(name,
new AntFTPFile(ftp, file, completePath) , fast);
} else {
dirsNotIncluded.addElement(name);
if (fast && couldHoldIncluded(name)) {
scandir(file.getName(),
name + File.separator, fast);
}
}
if (!fast && slowScanAllowed) {
scandir(file.getName(),
name + File.separator, fast);
}
} else {
if (!isFollowSymlinks() && file.isSymbolicLink()) {
filesExcluded.addElement(name);
} else if (isFunctioningAsFile(ftp, dir, file)) {
accountForIncludedFile(name);
}
}
}
}
ftp.changeToParentDirectory();
} catch (IOException e) {
throw new BuildException("Error while communicating with FTP "
+ "server: ", e);
}
}
/**
* process included file
* @param name path of the file relative to the directory of the fileset
*/
private void accountForIncludedFile(String name) {
if (!filesIncluded.contains(name)
&& !filesExcluded.contains(name)) {
if (isIncluded(name)) {
if (!isExcluded(name)
&& isSelected(name, (File) scannedDirs.get(name))) {
filesIncluded.addElement(name);
} else {
filesExcluded.addElement(name);
}
} else {
filesNotIncluded.addElement(name);
}
}
}
/**
*
* @param name path of the directory relative to the directory of
* the fileset
* @param file directory as file
* @param fast
*/
private void accountForIncludedDir(String name, AntFTPFile file, boolean fast) {
if (!dirsIncluded.contains(name)
&& !dirsExcluded.contains(name)) {
if (!isExcluded(name)) {
if (fast) {
if (file.isSymbolicLink()) {
try {
file.getClient().changeWorkingDirectory(file.curpwd);
} catch (IOException ioe) {
throw new BuildException("could not change directory to curpwd");
}
scandir(file.getLink(),
name + File.separator, fast);
} else {
try {
file.getClient().changeWorkingDirectory(file.curpwd);
} catch (IOException ioe) {
throw new BuildException("could not change directory to curpwd");
}
scandir(file.getName(),
name + File.separator, fast);
}
}
dirsIncluded.addElement(name);
} else {
dirsExcluded.addElement(name);
if (fast && couldHoldIncluded(name)) {
try {
file.getClient().changeWorkingDirectory(file.curpwd);
} catch (IOException ioe) {
throw new BuildException("could not change directory to curpwd");
}
scandir(file.getName(),
name + File.separator, fast);
}
}
}
}
/**
* temporary table to speed up the various scanning methods below
*
* @since Ant 1.6
*/
private Map fileListMap = new HashMap();
/**
* List of all scanned directories.
*
* @since Ant 1.6
*/
private Map scannedDirs = new HashMap();
/**
* Has the directory with the given path relative to the base
* directory already been scanned?
*
* @since Ant 1.6
*/
private boolean hasBeenScanned(String vpath) {
return scannedDirs.containsKey(vpath);
}
/**
* Clear internal caches.
*
* @since Ant 1.6
*/
private void clearCaches() {
fileListMap.clear();
scannedDirs.clear();
}
/**
* list the files present in one directory.
* @param directory full path on the remote side
* @param changedir if true change to directory directory before listing
* @return array of FTPFile
*/
public FTPFile[] listFiles(String directory, boolean changedir) {
//getProject().log("listing files in directory " + directory, Project.MSG_DEBUG);
String currentPath = directory;
if (changedir) {
try {
boolean result = ftp.changeWorkingDirectory(directory);
if (!result) {
return null;
}
currentPath = ftp.printWorkingDirectory();
} catch (IOException ioe) {
throw new BuildException(ioe, getLocation());
}
}
if (fileListMap.containsKey(currentPath)) {
getProject().log("filelist map used in listing files", Project.MSG_DEBUG);
return ((FTPFile[]) fileListMap.get(currentPath));
}
FTPFile[] result = null;
try {
result = ftp.listFiles();
} catch (IOException ioe) {
throw new BuildException(ioe, getLocation());
}
fileListMap.put(currentPath, result);
if (!remoteSensitivityChecked) {
checkRemoteSensitivity(result, directory);
}
return result;
}
private void forceRemoteSensitivityCheck() {
if (!remoteSensitivityChecked) {
try {
checkRemoteSensitivity(ftp.listFiles(), ftp.printWorkingDirectory());
} catch (IOException ioe) {
throw new BuildException(ioe, getLocation());
}
}
}
/**
* cd into one directory and
* list the files present in one directory.
* @param directory full path on the remote side
* @return array of FTPFile
*/
public FTPFile[] listFiles(String directory) {
return listFiles(directory, true);
}
private void checkRemoteSensitivity(FTPFile[] array, String directory) {
if (array == null) {
return;
}
boolean candidateFound = false;
String target = null;
for (int icounter = 0; icounter < array.length; icounter++) {
if (array[icounter] != null && array[icounter].isDirectory()) {
if (!array[icounter].getName().equals(".")
&& !array[icounter].getName().equals("..")) {
candidateFound = true;
target = fiddleName(array[icounter].getName());
getProject().log("will try to cd to "
+ target + " where a directory called " + array[icounter].getName()
+ " exists", Project.MSG_DEBUG);
for (int pcounter = 0; pcounter < array.length; pcounter++) {
if (array[pcounter] != null
&& pcounter != icounter
&& target.equals(array[pcounter].getName())) {
candidateFound = false;
}
}
if (candidateFound) {
break;
}
}
}
}
if (candidateFound) {
try {
getProject().log("testing case sensitivity, attempting to cd to "
+ target, Project.MSG_DEBUG);
remoteSystemCaseSensitive = !ftp.changeWorkingDirectory(target);
} catch (IOException ioe) {
remoteSystemCaseSensitive = true;
} finally {
try {
ftp.changeWorkingDirectory(directory);
} catch (IOException ioe) {
throw new BuildException(ioe, getLocation());
}
}
getProject().log("remote system is case sensitive : " + remoteSystemCaseSensitive,
Project.MSG_VERBOSE);
remoteSensitivityChecked = true;
}
}
private String fiddleName(String origin) {
StringBuffer result = new StringBuffer();
for (int icounter = 0; icounter < origin.length(); icounter++) {
if (Character.isLowerCase(origin.charAt(icounter))) {
result.append(Character.toUpperCase(origin.charAt(icounter)));
} else if (Character.isUpperCase(origin.charAt(icounter))) {
result.append(Character.toLowerCase(origin.charAt(icounter)));
} else {
result.append(origin.charAt(icounter));
}
}
return result.toString();
}
/**
* an AntFTPFile is a representation of a remote file
* @since Ant 1.6
*/
protected class AntFTPFile {
/**
* ftp client
*/
private FTPClient client;
/**
* parent directory of the file
*/
private String curpwd;
/**
* the file itself
*/
private FTPFile ftpFile;
/**
*
*/
private AntFTPFile parent = null;
private boolean relativePathCalculated = false;
private boolean traversesSymlinks = false;
private String relativePath = "";
/**
* constructor
* @param client ftp client variable
* @param ftpFile the file
* @param curpwd absolute remote path where the file is found
*/
public AntFTPFile(FTPClient client, FTPFile ftpFile, String curpwd) {
this.client = client;
this.ftpFile = ftpFile;
this.curpwd = curpwd;
}
/**
* other constructor
* @param parent the parent file
* @param path a relative path to the parent file
*/
public AntFTPFile(AntFTPFile parent, String path) {
this.parent = parent;
this.client = parent.client;
Vector pathElements = SelectorUtils.tokenizePath(path);
try {
boolean result = this.client.changeWorkingDirectory(parent.getAbsolutePath());
//this should not happen, except if parent has been deleted by another process
if (!result) {
return;
}
this.curpwd = parent.getAbsolutePath();
} catch (IOException ioe) {
throw new BuildException("could not change working dir to "
+ parent.curpwd);
}
for (int fcount = 0; fcount < pathElements.size() - 1; fcount++) {
String currentPathElement = (String) pathElements.elementAt(fcount);
try {
boolean result = this.client.changeWorkingDirectory(currentPathElement);
if (!result && !isCaseSensitive()
&& (remoteSystemCaseSensitive || !remoteSensitivityChecked)) {
currentPathElement = findPathElementCaseUnsensitive(this.curpwd,
currentPathElement);
if (currentPathElement == null) {
return;
}
} else if (!result) {
return;
}
this.curpwd = this.curpwd + remoteFileSep
+ currentPathElement;
} catch (IOException ioe) {
throw new BuildException("could not change working dir to "
+ (String) pathElements.elementAt(fcount)
+ " from " + this.curpwd);
}
}
String lastpathelement = (String) pathElements.elementAt(pathElements.size() - 1);
FTPFile [] theFiles = listFiles(this.curpwd);
this.ftpFile = getFile(theFiles, lastpathelement);
}
/**
* find a file in a directory in case unsensitive way
* @param parentPath where we are
* @param soughtPathElement what is being sought
* @return the first file found or null if not found
*/
private String findPathElementCaseUnsensitive(String parentPath,
String soughtPathElement) {
// we are already in the right path, so the second parameter
// is false
FTPFile[] theFiles = listFiles(parentPath, false);
if (theFiles == null) {
return null;
}
for (int icounter = 0; icounter < theFiles.length; icounter++) {
if (theFiles[icounter] != null
&& theFiles[icounter].getName().equalsIgnoreCase(soughtPathElement)) {
return theFiles[icounter].getName();
}
}
return null;
}
/**
* find out if the file exists
* @return true if the file exists
*/
public boolean exists() {
return (ftpFile != null);
}
/**
* if the file is a symbolic link, find out to what it is pointing
* @return the target of the symbolic link
*/
public String getLink() {
return ftpFile.getLink();
}
/**
* get the name of the file
* @return the name of the file
*/
public String getName() {
return ftpFile.getName();
}
/**
* find out the absolute path of the file
* @return absolute path as string
*/
public String getAbsolutePath() {
return curpwd + remoteFileSep + ftpFile.getName();
}
/**
* find out the relative path assuming that the path used to construct
* this AntFTPFile was spelled properly with regards to case.
* This is OK on a case sensitive system such as UNIX
* @return relative path
*/
public String getFastRelativePath() {
String absPath = getAbsolutePath();
if (absPath.indexOf(rootPath + remoteFileSep) == 0) {
return absPath.substring(rootPath.length() + remoteFileSep.length());
}
return null;
}
/**
* find out the relative path to the rootPath of the enclosing scanner.
* this relative path is spelled exactly like on disk,
* for instance if the AntFTPFile has been instantiated as ALPHA,
* but the file is really called alpha, this method will return alpha.
* If a symbolic link is encountered, it is followed, but the name of the link
* rather than the name of the target is returned.
* (ie does not behave like File.getCanonicalPath())
* @return relative path, separated by remoteFileSep
* @throws IOException if a change directory fails, ...
* @throws BuildException if one of the components of the relative path cannot
* be found.
*/
public String getRelativePath() throws IOException, BuildException {
if (!relativePathCalculated) {
if (parent != null) {
traversesSymlinks = parent.isTraverseSymlinks();
relativePath = getRelativePath(parent.getAbsolutePath(),
parent.getRelativePath());
} else {
relativePath = getRelativePath(rootPath, "");
relativePathCalculated = true;
}
}
return relativePath;
}
/**
* get thge relative path of this file
* @param currentPath base path
* @param currentRelativePath relative path of the base path with regards to remote dir
* @return relative path
*/
private String getRelativePath(String currentPath, String currentRelativePath) {
Vector pathElements = SelectorUtils.tokenizePath(getAbsolutePath(), remoteFileSep);
Vector pathElements2 = SelectorUtils.tokenizePath(currentPath, remoteFileSep);
String relPath = currentRelativePath;
for (int pcount = pathElements2.size(); pcount < pathElements.size(); pcount++) {
String currentElement = (String) pathElements.elementAt(pcount);
FTPFile[] theFiles = listFiles(currentPath);
FTPFile theFile = null;
if (theFiles != null) {
theFile = getFile(theFiles, currentElement);
}
if (!relPath.equals("")) {
relPath = relPath + remoteFileSep;
}
if (theFile == null) {
// hit a hidden file assume not a symlink
relPath = relPath + currentElement;
currentPath = currentPath + remoteFileSep + currentElement;
log("Hidden file " + relPath
+ " assumed to not be a symlink.",
Project.MSG_VERBOSE);
} else {
traversesSymlinks = traversesSymlinks || theFile.isSymbolicLink();
relPath = relPath + theFile.getName();
currentPath = currentPath + remoteFileSep + theFile.getName();
}
}
return relPath;
}
/**
* find a file matching a string in an array of FTPFile.
* This method will find "alpha" when requested for "ALPHA"
* if and only if the caseSensitive attribute is set to false.
* When caseSensitive is set to true, only the exact match is returned.
* @param theFiles array of files
* @param lastpathelement the file name being sought
* @return null if the file cannot be found, otherwise return the matching file.
*/
public FTPFile getFile(FTPFile[] theFiles, String lastpathelement) {
if (theFiles == null) {
return null;
}
for (int fcount = 0; fcount < theFiles.length; fcount++) {
if (theFiles[fcount] != null) {
if (theFiles[fcount].getName().equals(lastpathelement)) {
return theFiles[fcount];
} else if (!isCaseSensitive()
&& theFiles[fcount].getName().equalsIgnoreCase(
lastpathelement)) {
return theFiles[fcount];
}
}
}
return null;
}
/**
* tell if a file is a directory.
* note that it will return false for symbolic links pointing to directories.
* @return <code>true</code> for directories
*/
public boolean isDirectory() {
return ftpFile.isDirectory();
}
/**
* tell if a file is a symbolic link
* @return <code>true</code> for symbolic links
*/
public boolean isSymbolicLink() {
return ftpFile.isSymbolicLink();
}
/**
* return the attached FTP client object.
* Warning : this instance is really shared with the enclosing class.
* @return FTP client
*/
protected FTPClient getClient() {
return client;
}
/**
* sets the current path of an AntFTPFile
* @param curpwd the current path one wants to set
*/
protected void setCurpwd(String curpwd) {
this.curpwd = curpwd;
}
/**
* returns the path of the directory containing the AntFTPFile.
* of the full path of the file itself in case of AntFTPRootFile
* @return parent directory of the AntFTPFile
*/
public String getCurpwd() {
return curpwd;
}
/**
* find out if a symbolic link is encountered in the relative path of this file
* from rootPath.
* @return <code>true</code> if a symbolic link is encountered in the relative path.
* @throws IOException if one of the change directory or directory listing operations
* fails
* @throws BuildException if a path component in the relative path cannot be found.
*/
public boolean isTraverseSymlinks() throws IOException, BuildException {
if (!relativePathCalculated) {
// getRelativePath also finds about symlinks
getRelativePath();
}
return traversesSymlinks;
}
/**
* Get a string rep of this object.
* @return a string containing the pwd and the file.
*/
public String toString() {
return "AntFtpFile: " + curpwd + "%" + ftpFile;
}
}
/**
* special class to represent the remote directory itself
* @since Ant 1.6
*/
protected class AntFTPRootFile extends AntFTPFile {
private String remotedir;
/**
* constructor
* @param aclient FTP client
* @param remotedir remote directory
*/
public AntFTPRootFile(FTPClient aclient, String remotedir) {
super(aclient, null, remotedir);
this.remotedir = remotedir;
try {
this.getClient().changeWorkingDirectory(this.remotedir);
this.setCurpwd(this.getClient().printWorkingDirectory());
} catch (IOException ioe) {
throw new BuildException(ioe, getLocation());
}
}
/**
* find the absolute path
* @return absolute path
*/
public String getAbsolutePath() {
return this.getCurpwd();
}
/**
* find out the relative path to root
* @return empty string
* @throws BuildException actually never
* @throws IOException actually never
*/
public String getRelativePath() throws BuildException, IOException {
return "";
}
}
}
/**
* check FTPFiles to check whether they function as directories too
* the FTPFile API seem to make directory and symbolic links incompatible
* we want to find out if we can cd to a symbolic link
* @param dir the parent directory of the file to test
* @param file the file to test
* @return true if it is possible to cd to this directory
* @since ant 1.6
*/
private boolean isFunctioningAsDirectory(FTPClient ftp, String dir, FTPFile file) {
boolean result = false;
String currentWorkingDir = null;
if (file.isDirectory()) {
return true;
} else if (file.isFile()) {
return false;
}
try {
currentWorkingDir = ftp.printWorkingDirectory();
} catch (IOException ioe) {
getProject().log("could not find current working directory " + dir
+ " while checking a symlink",
Project.MSG_DEBUG);
}
if (currentWorkingDir != null) {
try {
result = ftp.changeWorkingDirectory(file.getLink());
} catch (IOException ioe) {
getProject().log("could not cd to " + file.getLink() + " while checking a symlink",
Project.MSG_DEBUG);
}
if (result) {
boolean comeback = false;
try {
comeback = ftp.changeWorkingDirectory(currentWorkingDir);
} catch (IOException ioe) {
getProject().log("could not cd back to " + dir + " while checking a symlink",
Project.MSG_ERR);
} finally {
if (!comeback) {
throw new BuildException("could not cd back to " + dir
+ " while checking a symlink");
}
}
}
}
return result;
}
/**
* check FTPFiles to check whether they function as directories too
* the FTPFile API seem to make directory and symbolic links incompatible
* we want to find out if we can cd to a symbolic link
* @param dir the parent directory of the file to test
* @param file the file to test
* @return true if it is possible to cd to this directory
* @since ant 1.6
*/
private boolean isFunctioningAsFile(FTPClient ftp, String dir, FTPFile file) {
if (file.isDirectory()) {
return false;
} else if (file.isFile()) {
return true;
}
return !isFunctioningAsDirectory(ftp, dir, file);
}
/**
* Sets the remote directory where files will be placed. This may be a
* relative or absolute path, and must be in the path syntax expected by
* the remote server. No correction of path syntax will be performed.
*
* @param dir the remote directory name.
*/
public void setRemotedir(String dir) {
this.remotedir = dir;
}
/**
* Sets the FTP server to send files to.
*
* @param server the remote server name.
*/
public void setServer(String server) {
this.server = server;
}
/**
* Sets the FTP port used by the remote server.
*
* @param port the port on which the remote server is listening.
*/
public void setPort(int port) {
this.port = port;
}
/**
* Sets the login user id to use on the specified server.
*
* @param userid remote system userid.
*/
public void setUserid(String userid) {
this.userid = userid;
}
/**
* Sets the login password for the given user id.
*
* @param password the password on the remote system.
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Sets the login account to use on the specified server.
*
* @param pAccount the account name on remote system
* @since Ant 1.7
*/
public void setAccount(String pAccount) {
this.account = pAccount;
}
/**
* If true, uses binary mode, otherwise text mode (default is binary).
*
* @param binary if true use binary mode in transfers.
*/
public void setBinary(boolean binary) {
this.binary = binary;
}
/**
* Specifies whether to use passive mode. Set to true if you are behind a
* firewall and cannot connect without it. Passive mode is disabled by
* default.
*
* @param passive true is passive mode should be used.
*/
public void setPassive(boolean passive) {
this.passive = passive;
}
/**
* Set to true to receive notification about each file as it is
* transferred.
*
* @param verbose true if verbose notifications are required.
*/
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
/**
* A synonym for <tt>depends</tt>. Set to true to transmit only new
* or changed files.
*
* See the related attributes timediffmillis and timediffauto.
*
* @param newer if true only transfer newer files.
*/
public void setNewer(boolean newer) {
this.newerOnly = newer;
}
/**
* number of milliseconds to add to the time on the remote machine
* to get the time on the local machine.
*
* use in conjunction with <code>newer</code>
*
* @param timeDiffMillis number of milliseconds
*
* @since ant 1.6
*/
public void setTimeDiffMillis(long timeDiffMillis) {
this.timeDiffMillis = timeDiffMillis;
}
/**
* "true" to find out automatically the time difference
* between local and remote machine.
*
* This requires right to create
* and delete a temporary file in the remote directory.
*
* @param timeDiffAuto true = find automatically the time diff
*
* @since ant 1.6
*/
public void setTimeDiffAuto(boolean timeDiffAuto) {
this.timeDiffAuto = timeDiffAuto;
}
/**
* Set to true to preserve modification times for "gotten" files.
*
* @param preserveLastModified if true preserver modification times.
*/
public void setPreserveLastModified(boolean preserveLastModified) {
this.preserveLastModified = preserveLastModified;
}
/**
* Set to true to transmit only files that are new or changed from their
* remote counterparts. The default is to transmit all files.
*
* @param depends if true only transfer newer files.
*/
public void setDepends(boolean depends) {
this.newerOnly = depends;
}
/**
* Sets the remote file separator character. This normally defaults to the
* Unix standard forward slash, but can be manually overridden using this
* call if the remote server requires some other separator. Only the first
* character of the string is used.
*
* @param separator the file separator on the remote system.
*/
public void setSeparator(String separator) {
remoteFileSep = separator;
}
/**
* Sets the file permission mode (Unix only) for files sent to the
* server.
*
* @param theMode unix style file mode for the files sent to the remote
* system.
*/
public void setChmod(String theMode) {
this.chmod = theMode;
}
/**
* Sets the default mask for file creation on a unix server.
*
* @param theUmask unix style umask for files created on the remote server.
*/
public void setUmask(String theUmask) {
this.umask = theUmask;
}
/**
* A set of files to upload or download
*
* @param set the set of files to be added to the list of files to be
* transferred.
*/
public void addFileset(FileSet set) {
filesets.addElement(set);
}
/**
* Sets the FTP action to be taken. Currently accepts "put", "get", "del",
* "mkdir", "chmod", "list", and "site".
*
* @deprecated since 1.5.x.
* setAction(String) is deprecated and is replaced with
* setAction(FTP.Action) to make Ant's Introspection mechanism do the
* work and also to encapsulate operations on the type in its own
* class.
* @ant.attribute ignore="true"
*
* @param action the FTP action to be performed.
*
* @throws BuildException if the action is not a valid action.
*/
public void setAction(String action) throws BuildException {
log("DEPRECATED - The setAction(String) method has been deprecated."
+ " Use setAction(FTP.Action) instead.");
Action a = new Action();
a.setValue(action);
this.action = a.getAction();
}
/**
* Sets the FTP action to be taken. Currently accepts "put", "get", "del",
* "mkdir", "chmod", "list", and "site".
*
* @param action the FTP action to be performed.
*
* @throws BuildException if the action is not a valid action.
*/
public void setAction(Action action) throws BuildException {
this.action = action.getAction();
}
/**
* The output file for the "list" action. This attribute is ignored for
* any other actions.
*
* @param listing file in which to store the listing.
*/
public void setListing(File listing) {
this.listing = listing;
}
public void setListingFullPath(boolean listingFullPath) {
this.listingFullPath = listingFullPath;
}
public void setListingAppend(boolean listingAppend) {
this.listingAppend = listingAppend;
}
/**
* If true, enables unsuccessful file put, delete and get
* operations to be skipped with a warning and the remainder
* of the files still transferred.
*
* @param skipFailedTransfers true if failures in transfers are ignored.
*/
public void setSkipFailedTransfers(boolean skipFailedTransfers) {
this.skipFailedTransfers = skipFailedTransfers;
}
/**
* set the flag to skip errors on directory creation.
* (and maybe later other server specific errors)
*
* @param ignoreNoncriticalErrors true if non-critical errors should not
* cause a failure.
*/
public void setIgnoreNoncriticalErrors(boolean ignoreNoncriticalErrors) {
this.ignoreNoncriticalErrors = ignoreNoncriticalErrors;
}
private void configurationHasBeenSet() {
this.isConfigurationSet = true;
}
/**
* Sets the systemTypeKey attribute.
* Method for setting <code>FTPClientConfig</code> remote system key.
*
* @param systemKey the key to be set - BUT if blank
* the default value of null (which signifies "autodetect") will be kept.
* @see org.apache.commons.net.ftp.FTPClientConfig
*/
public void setSystemTypeKey(FTPSystemType systemKey) {
if (systemKey != null && !systemKey.getValue().equals("")) {
this.systemTypeKey = systemKey;
configurationHasBeenSet();
}
}
/**
* Sets the defaultDateFormatConfig attribute.
* @param defaultDateFormat configuration to be set, unless it is
* null or empty string, in which case ignored.
* @see org.apache.commons.net.ftp.FTPClientConfig
*/
public void setDefaultDateFormatConfig(String defaultDateFormat) {
if (defaultDateFormat != null && !defaultDateFormat.equals("")) {
this.defaultDateFormatConfig = defaultDateFormat;
configurationHasBeenSet();
}
}
/**
* Sets the recentDateFormatConfig attribute.
* @param recentDateFormat configuration to be set, unless it is
* null or empty string, in which case ignored.
* @see org.apache.commons.net.ftp.FTPClientConfig
*/
public void setRecentDateFormatConfig(String recentDateFormat) {
if (recentDateFormat != null && !recentDateFormat.equals("")) {
this.recentDateFormatConfig = recentDateFormat;
configurationHasBeenSet();
}
}
/**
* Sets the serverLanguageCode attribute.
* @param serverLanguageCode configuration to be set, unless it is
* null or empty string, in which case ignored.
* @see org.apache.commons.net.ftp.FTPClientConfig
*/
public void setServerLanguageCodeConfig(LanguageCode serverLanguageCode) {
if (serverLanguageCode != null && !"".equals(serverLanguageCode.getValue())) {
this.serverLanguageCodeConfig = serverLanguageCode;
configurationHasBeenSet();
}
}
/**
* Sets the serverTimeZoneConfig attribute.
* @param serverTimeZoneId configuration to be set, unless it is
* null or empty string, in which case ignored.
* @see org.apache.commons.net.ftp.FTPClientConfig
*/
public void setServerTimeZoneConfig(String serverTimeZoneId) {
if (serverTimeZoneId != null && !serverTimeZoneId.equals("")) {
this.serverTimeZoneConfig = serverTimeZoneId;
configurationHasBeenSet();
}
}
/**
* Sets the shortMonthNamesConfig attribute
*
* @param shortMonthNames configuration to be set, unless it is
* null or empty string, in which case ignored.
* @see org.apache.commons.net.ftp.FTPClientConfig
*/
public void setShortMonthNamesConfig(String shortMonthNames) {
if (shortMonthNames != null && !shortMonthNames.equals("")) {
this.shortMonthNamesConfig = shortMonthNames;
configurationHasBeenSet();
}
}
/**
* Defines how many times to retry executing FTP command before giving up.
* Default is 0 - try once and if failure then give up.
*
* @param retriesAllowed number of retries to allow. -1 means
* keep trying forever. "forever" may also be specified as a
* synonym for -1.
*/
public void setRetriesAllowed(String retriesAllowed) {
if ("FOREVER".equalsIgnoreCase(retriesAllowed)) {
this.retriesAllowed = Retryable.RETRY_FOREVER;
} else {
try {
int retries = Integer.parseInt(retriesAllowed);
if (retries < Retryable.RETRY_FOREVER) {
throw new BuildException(
"Invalid value for retriesAllowed attribute: "
+ retriesAllowed);
}
this.retriesAllowed = retries;
} catch (NumberFormatException px) {
throw new BuildException(
"Invalid value for retriesAllowed attribute: "
+ retriesAllowed);
}
}
}
/**
* @return Returns the systemTypeKey.
*/
public String getSystemTypeKey() {
return systemTypeKey.getValue();
}
/**
* @return Returns the defaultDateFormatConfig.
*/
public String getDefaultDateFormatConfig() {
return defaultDateFormatConfig;
}
/**
* @return Returns the recentDateFormatConfig.
*/
public String getRecentDateFormatConfig() {
return recentDateFormatConfig;
}
/**
* @return Returns the serverLanguageCodeConfig.
*/
public String getServerLanguageCodeConfig() {
return serverLanguageCodeConfig.getValue();
}
/**
* @return Returns the serverTimeZoneConfig.
*/
public String getServerTimeZoneConfig() {
return serverTimeZoneConfig;
}
/**
* @return Returns the shortMonthNamesConfig.
*/
public String getShortMonthNamesConfig() {
return shortMonthNamesConfig;
}
/**
* @return Returns the timestampGranularity.
*/
Granularity getTimestampGranularity() {
return timestampGranularity;
}
/**
* Sets the timestampGranularity attribute
* @param timestampGranularity The timestampGranularity to set.
*/
public void setTimestampGranularity(Granularity timestampGranularity) {
if (null == timestampGranularity || "".equals(timestampGranularity.getValue())) {
return;
}
this.timestampGranularity = timestampGranularity;
}
/**
* Sets the siteCommand attribute. This attribute
* names the command that will be executed if the action
* is "site".
* @param siteCommand The siteCommand to set.
*/
public void setSiteCommand(String siteCommand) {
this.siteCommand = siteCommand;
}
/**
* Sets the initialSiteCommand attribute. This attribute
* names a site command that will be executed immediately
* after connection.
* @param initialCommand The initialSiteCommand to set.
*/
public void setInitialSiteCommand(String initialCommand) {
this.initialSiteCommand = initialCommand;
}
/**
* Whether to verify that data and control connections are
* connected to the same remote host.
*
* @since Ant 1.8.0
*/
public void setEnableRemoteVerification(boolean b) {
enableRemoteVerification = b;
}
/**
* Checks to see that all required parameters are set.
*
* @throws BuildException if the configuration is not valid.
*/
protected void checkAttributes() throws BuildException {
if (server == null) {
throw new BuildException("server attribute must be set!");
}
if (userid == null) {
throw new BuildException("userid attribute must be set!");
}
if (password == null) {
throw new BuildException("password attribute must be set!");
}
if ((action == LIST_FILES) && (listing == null)) {
throw new BuildException("listing attribute must be set for list "
+ "action!");
}
if (action == MK_DIR && remotedir == null) {
throw new BuildException("remotedir attribute must be set for "
+ "mkdir action!");
}
if (action == CHMOD && chmod == null) {
throw new BuildException("chmod attribute must be set for chmod "
+ "action!");
}
if (action == SITE_CMD && siteCommand == null) {
throw new BuildException("sitecommand attribute must be set for site "
+ "action!");
}
if (this.isConfigurationSet) {
try {
Class.forName("org.apache.commons.net.ftp.FTPClientConfig");
} catch (ClassNotFoundException e) {
throw new BuildException(
"commons-net.jar >= 1.4.0 is required for at least one"
+ " of the attributes specified.");
}
}
}
/**
* Executable a retryable object.
* @param h the retry hander.
* @param r the object that should be retried until it succeeds
* or the number of retrys is reached.
* @param descr a description of the command that is being run.
* @throws IOException if there is a problem.
*/
protected void executeRetryable(RetryHandler h, Retryable r, String descr)
throws IOException {
h.execute(r, descr);
}
/**
* For each file in the fileset, do the appropriate action: send, get,
* delete, or list.
*
* @param ftp the FTPClient instance used to perform FTP actions
* @param fs the fileset on which the actions are performed.
*
* @return the number of files to be transferred.
*
* @throws IOException if there is a problem reading a file
* @throws BuildException if there is a problem in the configuration.
*/
protected int transferFiles(final FTPClient ftp, FileSet fs)
throws IOException, BuildException {
DirectoryScanner ds;
if (action == SEND_FILES) {
ds = fs.getDirectoryScanner(getProject());
} else {
ds = new FTPDirectoryScanner(ftp);
fs.setupDirectoryScanner(ds, getProject());
ds.setFollowSymlinks(fs.isFollowSymlinks());
ds.scan();
}
String[] dsfiles = null;
if (action == RM_DIR) {
dsfiles = ds.getIncludedDirectories();
} else {
dsfiles = ds.getIncludedFiles();
}
String dir = null;
if ((ds.getBasedir() == null)
&& ((action == SEND_FILES) || (action == GET_FILES))) {
throw new BuildException("the dir attribute must be set for send "
+ "and get actions");
} else {
if ((action == SEND_FILES) || (action == GET_FILES)) {
dir = ds.getBasedir().getAbsolutePath();
}
}
// If we are doing a listing, we need the output stream created now.
BufferedWriter bw = null;
try {
if (action == LIST_FILES) {
File pd = listing.getParentFile();
if (!pd.exists()) {
pd.mkdirs();
}
bw = new BufferedWriter(new FileWriter(listing, listingAppend));
}
RetryHandler h = new RetryHandler(this.retriesAllowed, this);
if (action == RM_DIR) {
// to remove directories, start by the end of the list
// the trunk does not let itself be removed before the leaves
for (int i = dsfiles.length - 1; i >= 0; i--) {
final String dsfile = dsfiles[i];
executeRetryable(h, new Retryable() {
public void execute() throws IOException {
rmDir(ftp, dsfile);
}
}, dsfile);
}
} else {
final BufferedWriter fbw = bw;
final String fdir = dir;
if (this.newerOnly) {
this.granularityMillis =
this.timestampGranularity.getMilliseconds(action);
}
for (int i = 0; i < dsfiles.length; i++) {
final String dsfile = dsfiles[i];
executeRetryable(h, new Retryable() {
public void execute() throws IOException {
switch (action) {
case SEND_FILES:
sendFile(ftp, fdir, dsfile);
break;
case GET_FILES:
getFile(ftp, fdir, dsfile);
break;
case DEL_FILES:
delFile(ftp, dsfile);
break;
case LIST_FILES:
listFile(ftp, fbw, dsfile);
break;
case CHMOD:
doSiteCommand(ftp, "chmod " + chmod
+ " " + resolveFile(dsfile));
transferred++;
break;
default:
throw new BuildException("unknown ftp action " + action);
}
}
}, dsfile);
}
}
} finally {
FileUtils.close(bw);
}
return dsfiles.length;
}
/**
* Sends all files specified by the configured filesets to the remote
* server.
*
* @param ftp the FTPClient instance used to perform FTP actions
*
* @throws IOException if there is a problem reading a file
* @throws BuildException if there is a problem in the configuration.
*/
protected void transferFiles(FTPClient ftp)
throws IOException, BuildException {
transferred = 0;
skipped = 0;
if (filesets.size() == 0) {
throw new BuildException("at least one fileset must be specified.");
} else {
// get files from filesets
for (int i = 0; i < filesets.size(); i++) {
FileSet fs = (FileSet) filesets.elementAt(i);
if (fs != null) {
transferFiles(ftp, fs);
}
}
}
log(transferred + " " + ACTION_TARGET_STRS[action] + " "
+ COMPLETED_ACTION_STRS[action]);
if (skipped != 0) {
log(skipped + " " + ACTION_TARGET_STRS[action]
+ " were not successfully " + COMPLETED_ACTION_STRS[action]);
}
}
/**
* Correct a file path to correspond to the remote host requirements. This
* implementation currently assumes that the remote end can handle
* Unix-style paths with forward-slash separators. This can be overridden
* with the <code>separator</code> task parameter. No attempt is made to
* determine what syntax is appropriate for the remote host.
*
* @param file the remote file name to be resolved
*
* @return the filename as it will appear on the server.
*/
protected String resolveFile(String file) {
return file.replace(System.getProperty("file.separator").charAt(0),
remoteFileSep.charAt(0));
}
/**
* Creates all parent directories specified in a complete relative
* pathname. Attempts to create existing directories will not cause
* errors.
*
* @param ftp the FTP client instance to use to execute FTP actions on
* the remote server.
* @param filename the name of the file whose parents should be created.
* @throws IOException under non documented circumstances
* @throws BuildException if it is impossible to cd to a remote directory
*
*/
protected void createParents(FTPClient ftp, String filename)
throws IOException, BuildException {
File dir = new File(filename);
if (dirCache.contains(dir)) {
return;
}
Vector parents = new Vector();
String dirname;
while ((dirname = dir.getParent()) != null) {
File checkDir = new File(dirname);
if (dirCache.contains(checkDir)) {
break;
}
dir = checkDir;
parents.addElement(dir);
}
// find first non cached dir
int i = parents.size() - 1;
if (i >= 0) {
String cwd = ftp.printWorkingDirectory();
String parent = dir.getParent();
if (parent != null) {
if (!ftp.changeWorkingDirectory(resolveFile(parent))) {
throw new BuildException("could not change to "
+ "directory: " + ftp.getReplyString());
}
}
while (i >= 0) {
dir = (File) parents.elementAt(i--);
// check if dir exists by trying to change into it.
if (!ftp.changeWorkingDirectory(dir.getName())) {
// could not change to it - try to create it
log("creating remote directory "
+ resolveFile(dir.getPath()), Project.MSG_VERBOSE);
if (!ftp.makeDirectory(dir.getName())) {
handleMkDirFailure(ftp);
}
if (!ftp.changeWorkingDirectory(dir.getName())) {
throw new BuildException("could not change to "
+ "directory: " + ftp.getReplyString());
}
}
dirCache.add(dir);
}
ftp.changeWorkingDirectory(cwd);
}
}
/**
* auto find the time difference between local and remote
* @param ftp handle to ftp client
* @return number of millis to add to remote time to make it comparable to local time
* @since ant 1.6
*/
private long getTimeDiff(FTPClient ftp) {
long returnValue = 0;
File tempFile = findFileName(ftp);
try {
// create a local temporary file
FILE_UTILS.createNewFile(tempFile);
long localTimeStamp = tempFile.lastModified();
BufferedInputStream instream = new BufferedInputStream(new FileInputStream(tempFile));
ftp.storeFile(tempFile.getName(), instream);
instream.close();
boolean success = FTPReply.isPositiveCompletion(ftp.getReplyCode());
if (success) {
FTPFile [] ftpFiles = ftp.listFiles(tempFile.getName());
if (ftpFiles.length == 1) {
long remoteTimeStamp = ftpFiles[0].getTimestamp().getTime().getTime();
returnValue = localTimeStamp - remoteTimeStamp;
}
ftp.deleteFile(ftpFiles[0].getName());
}
// delegate the deletion of the local temp file to the delete task
// because of race conditions occuring on Windows
Delete mydelete = new Delete();
mydelete.bindToOwner(this);
mydelete.setFile(tempFile.getCanonicalFile());
mydelete.execute();
} catch (Exception e) {
throw new BuildException(e, getLocation());
}
return returnValue;
}
/**
* find a suitable name for local and remote temporary file
*/
private File findFileName(FTPClient ftp) {
FTPFile [] theFiles = null;
final int maxIterations = 1000;
for (int counter = 1; counter < maxIterations; counter++) {
File localFile = FILE_UTILS.createTempFile(
"ant" + Integer.toString(counter), ".tmp",
null, false, false);
String fileName = localFile.getName();
boolean found = false;
try {
if (theFiles == null) {
theFiles = ftp.listFiles();
}
for (int counter2 = 0; counter2 < theFiles.length; counter2++) {
if (theFiles[counter2] != null
&& theFiles[counter2].getName().equals(fileName)) {
found = true;
break;
}
}
} catch (IOException ioe) {
throw new BuildException(ioe, getLocation());
}
if (!found) {
localFile.deleteOnExit();
return localFile;
}
}
return null;
}
/**
* Checks to see if the remote file is current as compared with the local
* file. Returns true if the target file is up to date.
* @param ftp ftpclient
* @param localFile local file
* @param remoteFile remote file
* @return true if the target file is up to date
* @throws IOException in unknown circumstances
* @throws BuildException if the date of the remote files cannot be found and the action is
* GET_FILES
*/
protected boolean isUpToDate(FTPClient ftp, File localFile,
String remoteFile)
throws IOException, BuildException {
log("checking date for " + remoteFile, Project.MSG_VERBOSE);
FTPFile[] files = ftp.listFiles(remoteFile);
// For Microsoft's Ftp-Service an Array with length 0 is
// returned if configured to return listings in "MS-DOS"-Format
if (files == null || files.length == 0) {
// If we are sending files, then assume out of date.
// If we are getting files, then throw an error
if (action == SEND_FILES) {
log("Could not date test remote file: " + remoteFile
+ "assuming out of date.", Project.MSG_VERBOSE);
return false;
} else {
throw new BuildException("could not date test remote file: "
+ ftp.getReplyString());
}
}
long remoteTimestamp = files[0].getTimestamp().getTime().getTime();
long localTimestamp = localFile.lastModified();
long adjustedRemoteTimestamp =
remoteTimestamp + this.timeDiffMillis + this.granularityMillis;
StringBuffer msg;
synchronized(TIMESTAMP_LOGGING_SDF) {
msg = new StringBuffer(" [")
.append(TIMESTAMP_LOGGING_SDF.format(new Date(localTimestamp)))
.append("] local");
}
log(msg.toString(), Project.MSG_VERBOSE);
synchronized(TIMESTAMP_LOGGING_SDF) {
msg = new StringBuffer(" [")
.append(TIMESTAMP_LOGGING_SDF.format(new Date(adjustedRemoteTimestamp)))
.append("] remote");
}
if (remoteTimestamp != adjustedRemoteTimestamp) {
synchronized(TIMESTAMP_LOGGING_SDF) {
msg.append(" - (raw: ")
.append(TIMESTAMP_LOGGING_SDF.format(new Date(remoteTimestamp)))
.append(")");
}
}
log(msg.toString(), Project.MSG_VERBOSE);
if (this.action == SEND_FILES) {
return adjustedRemoteTimestamp >= localTimestamp;
} else {
return localTimestamp >= adjustedRemoteTimestamp;
}
}
/**
* Sends a site command to the ftp server
* @param ftp ftp client
* @param theCMD command to execute
* @throws IOException in unknown circumstances
* @throws BuildException in unknown circumstances
*/
protected void doSiteCommand(FTPClient ftp, String theCMD)
throws IOException, BuildException {
boolean rc;
String[] myReply = null;
log("Doing Site Command: " + theCMD, Project.MSG_VERBOSE);
rc = ftp.sendSiteCommand(theCMD);
if (!rc) {
log("Failed to issue Site Command: " + theCMD, Project.MSG_WARN);
} else {
myReply = ftp.getReplyStrings();
for (int x = 0; x < myReply.length; x++) {
if (myReply[x].indexOf("200") == -1) {
log(myReply[x], Project.MSG_WARN);
}
}
}
}
/**
* Sends a single file to the remote host. <code>filename</code> may
* contain a relative path specification. When this is the case, <code>sendFile</code>
* will attempt to create any necessary parent directories before sending
* the file. The file will then be sent using the entire relative path
* spec - no attempt is made to change directories. It is anticipated that
* this may eventually cause problems with some FTP servers, but it
* simplifies the coding.
* @param ftp ftp client
* @param dir base directory of the file to be sent (local)
* @param filename relative path of the file to be send
* locally relative to dir
* remotely relative to the remotedir attribute
* @throws IOException in unknown circumstances
* @throws BuildException in unknown circumstances
*/
protected void sendFile(FTPClient ftp, String dir, String filename)
throws IOException, BuildException {
InputStream instream = null;
try {
// XXX - why not simply new File(dir, filename)?
File file = getProject().resolveFile(new File(dir, filename).getPath());
if (newerOnly && isUpToDate(ftp, file, resolveFile(filename))) {
return;
}
if (verbose) {
log("transferring " + file.getAbsolutePath());
}
instream = new BufferedInputStream(new FileInputStream(file));
createParents(ftp, filename);
ftp.storeFile(resolveFile(filename), instream);
boolean success = FTPReply.isPositiveCompletion(ftp.getReplyCode());
if (!success) {
String s = "could not put file: " + ftp.getReplyString();
if (skipFailedTransfers) {
log(s, Project.MSG_WARN);
skipped++;
} else {
throw new BuildException(s);
}
} else {
// see if we should issue a chmod command
if (chmod != null) {
doSiteCommand(ftp, "chmod " + chmod + " " + resolveFile(filename));
}
log("File " + file.getAbsolutePath() + " copied to " + server,
Project.MSG_VERBOSE);
transferred++;
}
} finally {
FileUtils.close(instream);
}
}
/**
* Delete a file from the remote host.
* @param ftp ftp client
* @param filename file to delete
* @throws IOException in unknown circumstances
* @throws BuildException if skipFailedTransfers is set to false
* and the deletion could not be done
*/
protected void delFile(FTPClient ftp, String filename)
throws IOException, BuildException {
if (verbose) {
log("deleting " + filename);
}
if (!ftp.deleteFile(resolveFile(filename))) {
String s = "could not delete file: " + ftp.getReplyString();
if (skipFailedTransfers) {
log(s, Project.MSG_WARN);
skipped++;
} else {
throw new BuildException(s);
}
} else {
log("File " + filename + " deleted from " + server,
Project.MSG_VERBOSE);
transferred++;
}
}
/**
* Delete a directory, if empty, from the remote host.
* @param ftp ftp client
* @param dirname directory to delete
* @throws IOException in unknown circumstances
* @throws BuildException if skipFailedTransfers is set to false
* and the deletion could not be done
*/
protected void rmDir(FTPClient ftp, String dirname)
throws IOException, BuildException {
if (verbose) {
log("removing " + dirname);
}
if (!ftp.removeDirectory(resolveFile(dirname))) {
String s = "could not remove directory: " + ftp.getReplyString();
if (skipFailedTransfers) {
log(s, Project.MSG_WARN);
skipped++;
} else {
throw new BuildException(s);
}
} else {
log("Directory " + dirname + " removed from " + server,
Project.MSG_VERBOSE);
transferred++;
}
}
/**
* Retrieve a single file from the remote host. <code>filename</code> may
* contain a relative path specification. <p>
*
* The file will then be retreived using the entire relative path spec -
* no attempt is made to change directories. It is anticipated that this
* may eventually cause problems with some FTP servers, but it simplifies
* the coding.</p>
* @param ftp the ftp client
* @param dir local base directory to which the file should go back
* @param filename relative path of the file based upon the ftp remote directory
* and/or the local base directory (dir)
* @throws IOException in unknown circumstances
* @throws BuildException if skipFailedTransfers is false
* and the file cannot be retrieved.
*/
protected void getFile(FTPClient ftp, String dir, String filename)
throws IOException, BuildException {
OutputStream outstream = null;
try {
File file = getProject().resolveFile(new File(dir, filename).getPath());
if (newerOnly && isUpToDate(ftp, file, resolveFile(filename))) {
return;
}
if (verbose) {
log("transferring " + filename + " to "
+ file.getAbsolutePath());
}
File pdir = file.getParentFile();
if (!pdir.exists()) {
pdir.mkdirs();
}
outstream = new BufferedOutputStream(new FileOutputStream(file));
ftp.retrieveFile(resolveFile(filename), outstream);
if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
String s = "could not get file: " + ftp.getReplyString();
if (skipFailedTransfers) {
log(s, Project.MSG_WARN);
skipped++;
} else {
throw new BuildException(s);
}
} else {
log("File " + file.getAbsolutePath() + " copied from "
+ server, Project.MSG_VERBOSE);
transferred++;
if (preserveLastModified) {
outstream.close();
outstream = null;
FTPFile[] remote = ftp.listFiles(resolveFile(filename));
if (remote.length > 0) {
FILE_UTILS.setFileLastModified(file,
remote[0].getTimestamp()
.getTime().getTime());
}
}
}
} finally {
FileUtils.close(outstream);
}
}
/**
* Provides a listing for the single file.
*
* @param server FTP server address
* @param filePath path of the file on server
* @param fileSize size of the file
* @return listing entry for the server and file specified
*/
public static String listSingleFile ( String server, String filePath, long fileSize )
{
return String.format( "ftp://%s//%s|%s",
server,
filePath.replaceAll( "/+", "/" ). /* '//' => '/' */
replaceAll( "^/", "" ), /* Removing starting '/' */
fileSize ).replace( '\\', '/' );
}
/**
* List information about a single file from the remote host. <code>filename</code>
* may contain a relative path specification. <p>
*
* The file listing will then be retrieved using the entire relative path
* spec - no attempt is made to change directories. It is anticipated that
* this may eventually cause problems with some FTP servers, but it
* simplifies the coding.</p>
* @param ftp ftp client
* @param bw buffered writer
* @param filename the directory one wants to list
* @throws IOException in unknown circumstances
* @throws BuildException in unknown circumstances
*/
protected void listFile(FTPClient ftp, BufferedWriter bw, String filename)
throws IOException, BuildException {
if (verbose) {
log("listing " + filename);
}
FTPFile[] ftpfiles = ftp.listFiles(resolveFile(filename));
if (ftpfiles != null && ftpfiles.length > 0)
{
String path = this.listingFullPath ?
// "ftp://host.com//od/small/OfficersDirectors03_GL_f_20101120_1of1.xml.zip|23505456"
listSingleFile( this.server, this.remotedir + "/" + filename, ftpfiles[ 0 ].getSize()) :
// Default listing
ftpfiles[0].toString();
bw.write( path );
bw.newLine();
transferred++;
}
}
/**
* Create the specified directory on the remote host.
*
* @param ftp The FTP client connection
* @param dir The directory to create (format must be correct for host
* type)
* @throws IOException in unknown circumstances
* @throws BuildException if ignoreNoncriticalErrors has not been set to true
* and a directory could not be created, for instance because it was
* already existing. Precisely, the codes 521, 550 and 553 will trigger
* a BuildException
*/
protected void makeRemoteDir(FTPClient ftp, String dir)
throws IOException, BuildException {
String workingDirectory = ftp.printWorkingDirectory();
if (verbose) {
if (dir.indexOf("/") == 0 || workingDirectory == null) {
log("Creating directory: " + dir + " in /");
} else {
log("Creating directory: " + dir + " in " + workingDirectory);
}
}
if (dir.indexOf("/") == 0) {
ftp.changeWorkingDirectory("/");
}
String subdir = "";
StringTokenizer st = new StringTokenizer(dir, "/");
while (st.hasMoreTokens()) {
subdir = st.nextToken();
log("Checking " + subdir, Project.MSG_DEBUG);
if (!ftp.changeWorkingDirectory(subdir)) {
if (!ftp.makeDirectory(subdir)) {
// codes 521, 550 and 553 can be produced by FTP Servers
// to indicate that an attempt to create a directory has
// failed because the directory already exists.
int rc = ftp.getReplyCode();
if (!(ignoreNoncriticalErrors
&& (rc == FTPReply.CODE_550 || rc == FTPReply.CODE_553
|| rc == CODE_521))) {
throw new BuildException("could not create directory: "
+ ftp.getReplyString());
}
if (verbose) {
log("Directory already exists");
}
} else {
if (verbose) {
log("Directory created OK");
}
ftp.changeWorkingDirectory(subdir);
}
}
}
if (workingDirectory != null) {
ftp.changeWorkingDirectory(workingDirectory);
}
}
/**
* look at the response for a failed mkdir action, decide whether
* it matters or not. If it does, we throw an exception
* @param ftp current ftp connection
* @throws BuildException if this is an error to signal
*/
private void handleMkDirFailure(FTPClient ftp)
throws BuildException {
int rc = ftp.getReplyCode();
if (!(ignoreNoncriticalErrors
&& (rc == FTPReply.CODE_550 || rc == FTPReply.CODE_553 || rc == CODE_521))) {
throw new BuildException("could not create directory: "
+ ftp.getReplyString());
}
}
/**
* Runs the task.
*
* @throws BuildException if the task fails or is not configured
* correctly.
*/
public void execute() throws BuildException {
checkAttributes();
FTPClient ftp = null;
try
{
log("Opening FTP connection to " + server, Project.MSG_VERBOSE);
/**
* "verbose" version of <code>FTPClient</code> prints progress indicator
* See http://evgeny-goldin.com/blog/2010/08/18/ant-ftp-task-progress-indicator-timeout/
*/
ftp = ( verbose ? new com.github.goldin.org.apache.tools.ant.taskdefs.optional.net.FTPClient( getProject()) :
new org.apache.commons.net.ftp.FTPClient());
ftp.setDataTimeout( 5 * 60 * 1000 ); // 5 minutes
if (this.isConfigurationSet) {
ftp = FTPConfigurator.configure(ftp, this);
}
ftp.setRemoteVerificationEnabled(enableRemoteVerification);
ftp.connect(server, port);
if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
throw new BuildException("FTP connection failed: "
+ ftp.getReplyString());
}
log("connected", Project.MSG_VERBOSE);
log("logging in to FTP server", Project.MSG_VERBOSE);
if ((this.account != null && !ftp.login(userid, password, account))
|| (this.account == null && !ftp.login(userid, password))) {
throw new BuildException("Could not login to FTP server");
}
log("login succeeded", Project.MSG_VERBOSE);
if (binary) {
ftp.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
throw new BuildException("could not set transfer type: "
+ ftp.getReplyString());
}
} else {
ftp.setFileType(org.apache.commons.net.ftp.FTP.ASCII_FILE_TYPE);
if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
throw new BuildException("could not set transfer type: "
+ ftp.getReplyString());
}
}
if (passive) {
log("entering passive mode", Project.MSG_VERBOSE);
ftp.enterLocalPassiveMode();
if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
throw new BuildException("could not enter into passive "
+ "mode: " + ftp.getReplyString());
}
}
// If an initial command was configured then send it.
// Some FTP servers offer different modes of operation,
// E.G. switching between a UNIX file system mode and
// a legacy file system.
if (this.initialSiteCommand != null) {
RetryHandler h = new RetryHandler(this.retriesAllowed, this);
final FTPClient lftp = ftp;
executeRetryable(h, new Retryable() {
public void execute() throws IOException {
doSiteCommand(lftp, FTP.this.initialSiteCommand);
}
}, "initial site command: " + this.initialSiteCommand);
}
// For a unix ftp server you can set the default mask for all files
// created.
if (umask != null) {
RetryHandler h = new RetryHandler(this.retriesAllowed, this);
final FTPClient lftp = ftp;
executeRetryable(h, new Retryable() {
public void execute() throws IOException {
doSiteCommand(lftp, "umask " + umask);
}
}, "umask " + umask);
}
// If the action is MK_DIR, then the specified remote
// directory is the directory to create.
if (action == MK_DIR) {
RetryHandler h = new RetryHandler(this.retriesAllowed, this);
final FTPClient lftp = ftp;
executeRetryable(h, new Retryable() {
public void execute() throws IOException {
makeRemoteDir(lftp, remotedir);
}
}, remotedir);
} else if (action == SITE_CMD) {
RetryHandler h = new RetryHandler(this.retriesAllowed, this);
final FTPClient lftp = ftp;
executeRetryable(h, new Retryable() {
public void execute() throws IOException {
doSiteCommand(lftp, FTP.this.siteCommand);
}
}, "Site Command: " + this.siteCommand);
} else {
if (remotedir != null) {
log("changing the remote directory to " + remotedir,
Project.MSG_VERBOSE);
ftp.changeWorkingDirectory(remotedir);
if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
throw new BuildException("could not change remote "
+ "directory: " + ftp.getReplyString());
}
}
if (newerOnly && timeDiffAuto) {
// in this case we want to find how much time span there is between local
// and remote
timeDiffMillis = getTimeDiff(ftp);
}
log(ACTION_STRS[action] + " " + ACTION_TARGET_STRS[action]);
transferFiles(ftp);
}
} catch (IOException ex) {
throw new BuildException("error during FTP transfer: " + ex, ex);
} finally {
if (ftp != null && ftp.isConnected()) {
try {
log("disconnecting", Project.MSG_VERBOSE);
ftp.logout();
ftp.disconnect();
} catch (IOException ex) {
// ignore it
}
}
}
}
/**
* an action to perform, one of
* "send", "put", "recv", "get", "del", "delete", "list", "mkdir", "chmod",
* "rmdir"
*/
public static class Action extends EnumeratedAttribute {
private static final String[] VALID_ACTIONS = {
"send", "put", "recv", "get", "del", "delete", "list", "mkdir",
"chmod", "rmdir", "site"
};
/**
* Get the valid values
*
* @return an array of the valid FTP actions.
*/
public String[] getValues() {
return VALID_ACTIONS;
}
/**
* Get the symbolic equivalent of the action value.
*
* @return the SYMBOL representing the given action.
*/
public int getAction() {
String actionL = getValue().toLowerCase(Locale.ENGLISH);
if (actionL.equals("send") || actionL.equals("put")) {
return SEND_FILES;
} else if (actionL.equals("recv") || actionL.equals("get")) {
return GET_FILES;
} else if (actionL.equals("del") || actionL.equals("delete")) {
return DEL_FILES;
} else if (actionL.equals("list")) {
return LIST_FILES;
} else if (actionL.equals("chmod")) {
return CHMOD;
} else if (actionL.equals("mkdir")) {
return MK_DIR;
} else if (actionL.equals("rmdir")) {
return RM_DIR;
} else if (actionL.equals("site")) {
return SITE_CMD;
}
return SEND_FILES;
}
}
/**
* represents one of the valid timestamp adjustment values
* recognized by the <code>timestampGranularity</code> attribute.<p>
* A timestamp adjustment may be used in file transfers for checking
* uptodateness. MINUTE means to add one minute to the server
* timestamp. This is done because FTP servers typically list
* timestamps HH:mm and client FileSystems typically use HH:mm:ss.
*
* The default is to use MINUTE for PUT actions and NONE for GET
* actions, since GETs have the <code>preserveLastModified</code>
* option, which takes care of the problem in most use cases where
* this level of granularity is an issue.
*
*/
public static class Granularity extends EnumeratedAttribute {
private static final String[] VALID_GRANULARITIES = {
"", "MINUTE", "NONE"
};
/**
* Get the valid values.
* @return the list of valid Granularity values
*/
public String[] getValues() {
return VALID_GRANULARITIES;
}
/**
* returns the number of milliseconds associated with
* the attribute, which can vary in some cases depending
* on the value of the action parameter.
* @param action SEND_FILES or GET_FILES
* @return the number of milliseconds associated with
* the attribute, in the context of the supplied action
*/
public long getMilliseconds(int action) {
String granularityU = getValue().toUpperCase(Locale.ENGLISH);
if ("".equals(granularityU)) {
if (action == SEND_FILES) {
return GRANULARITY_MINUTE;
}
} else if ("MINUTE".equals(granularityU)) {
return GRANULARITY_MINUTE;
}
return 0L;
}
static final Granularity getDefault() {
Granularity g = new Granularity();
g.setValue("");
return g;
}
}
/**
* one of the valid system type keys recognized by the systemTypeKey
* attribute.
*/
public static class FTPSystemType extends EnumeratedAttribute {
private static final String[] VALID_SYSTEM_TYPES = {
"", "UNIX", "VMS", "WINDOWS", "OS/2", "OS/400",
"MVS"
};
/**
* Get the valid values.
* @return the list of valid system types.
*/
public String[] getValues() {
return VALID_SYSTEM_TYPES;
}
static final FTPSystemType getDefault() {
FTPSystemType ftpst = new FTPSystemType();
ftpst.setValue("");
return ftpst;
}
}
/**
* Enumerated class for languages.
*/
public static class LanguageCode extends EnumeratedAttribute {
private static final String[] VALID_LANGUAGE_CODES =
getValidLanguageCodes();
private static String[] getValidLanguageCodes() {
Collection c = FTPClientConfig.getSupportedLanguageCodes();
String[] ret = new String[c.size() + 1];
int i = 0;
ret[i++] = "";
for (Iterator it = c.iterator(); it.hasNext(); i++) {
ret[i] = (String) it.next();
}
return ret;
}
/**
* Return the value values.
* @return the list of valid language types.
*/
public String[] getValues() {
return VALID_LANGUAGE_CODES;
}
static final LanguageCode getDefault() {
LanguageCode lc = new LanguageCode();
lc.setValue("");
return lc;
}
}
}
| [
"evgenyg@gmail.com"
] | evgenyg@gmail.com |
7f5afb94c0efcaa796d35e85913e33f57712ca8d | 0e5a9811094343f68a0ffd81e992644fccf3c896 | /Game.java | 3a79bf2873b8b1ed94fda8172fe2803df29ceeaf | [] | no_license | aritra24/Mine | 084aec5513b0e6385e6274b2cd372427ba1afa29 | 83c3fb78485d4a4d247c7a68409ccd4107f3fa74 | refs/heads/master | 2021-05-15T20:15:38.590384 | 2018-10-30T11:49:46 | 2018-10-30T11:49:46 | 107,845,141 | 0 | 1 | null | 2018-10-30T11:49:47 | 2017-10-22T07:12:48 | Java | UTF-8 | Java | false | false | 8,055 | java | /*
Program Name: Mines
Author : Aritra Basu
Description : A game of Mines
Edited By : Shreyansh Murarka
*/
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import java.time.Duration;
import java.time.Instant;
import java.lang.*;
public class Game extends JFrame
{
//set variables
static Instant startTime,endTime;
boolean startedTime=false,wonCalled=false;
int rows=10,columns=10;
Random random = new Random();
JButton[][] grids = new JButton[rows][columns];
JButton start = new JButton("reset");
final int CELL_HEIGHT = 40, CELL_LENGTH = 40, CELL_PADDING = 5, PANEL_BORDER = 25;
Color backgroundColor = new Color(103,200,190);
Color cellColor = new Color(134,134,134);
Color startColor = new Color(146,142,202);
Color numColor = new Color(0,0,0);
Color postCellColor = new Color(224,224,224);
Border mainBorder = BorderFactory.createEmptyBorder(20, 20, 20, 20);
ListenForGridButton buttonClicked =new ListenForGridButton();
ListenForStartButton startButtonClicked = new ListenForStartButton();
public Game()
{
this.setSize(CELL_LENGTH * (columns + 4) + CELL_PADDING * columns , CELL_HEIGHT * (rows + 1) + CELL_PADDING * rows + PANEL_BORDER * 2);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel= new JPanel();
JPanel settingsPanel = new JPanel();
JPanel outerPanel = new JPanel();
FlowLayout outerLayout = new FlowLayout();
outerPanel.setLayout(outerLayout);
mainPanel.setBorder(mainBorder);
GridLayout mainLayout = new GridLayout(rows, columns, CELL_PADDING, CELL_PADDING);
mainPanel.setLayout(mainLayout);
mainPanel.setBackground(backgroundColor);
settingsPanel.setBackground(backgroundColor);
outerPanel.setBackground(backgroundColor);
//make buttons and set all to zero
for(int i = 0;i < rows;i++)
for(int j = 0;j < columns;j++)
{
grids[i][j] = new JButton("0");
grids[i][j].setEnabled(true);
grids[i][j].setHorizontalAlignment(SwingConstants.CENTER);
grids[i][j].setFont(new Font("Ariel",Font.PLAIN,25));
grids[i][j].setFocusPainted(false);
grids[i][j].setMargin(new Insets(0, 0, 0, 0));
grids[i][j].setPreferredSize(new Dimension(CELL_LENGTH, CELL_HEIGHT));
grids[i][j].setBackground(cellColor);
grids[i][j].setForeground(cellColor);
grids[i][j].setBorderPainted(false);
grids[i][j].addActionListener(buttonClicked);
mainPanel.add(grids[i][j]);
}
setMines();
start.addActionListener(startButtonClicked);
start.setBackground(startColor);
start.setForeground(numColor);
start.setBorderPainted(false);
start.setFocusPainted(false);
settingsPanel.add(start);
outerPanel.add(mainPanel);
outerPanel.add(settingsPanel);
outerPanel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
this.add(outerPanel);
this.setVisible(true);
}
//set the mines and increment the values around it
void setMines()
{
int x=(int)Math.sqrt(rows*columns);
// int x= 1;
int mineCount=0;
while(mineCount<x)
{
int p = random.nextInt(rows);
int q = random.nextInt(columns);
if(grids[p][q].getText()!="-1")
{
grids[p][q].setText("-1");
mineCount++;
}
}
for(int r = 0; r < rows; r++)
for( int c = 0; c < columns; c++)
if( grids[r][c].getText()=="-1")
for(int i = r-1; i < r+2; i++)
for(int j = c-1; j < c+2; j++)
if(i > -1 && i < rows && j> -1 && j < columns && (i != r || j != c))
if(!grids[i][j].getText().equals("-1"))
grids[i][j].setText(""+(1+Integer.parseInt(grids[i][j].getText())));
}
//Set the Button with a Mine Icon
void setMineIcon(JButton a)
{
ImageIcon icon = new ImageIcon("./icon.png");
Image img = icon.getImage();
Image newimg = img.getScaledInstance( CELL_LENGTH, CELL_LENGTH, java.awt.Image.SCALE_SMOOTH );
icon = new ImageIcon( newimg);
a.setHorizontalAlignment(SwingConstants.LEFT);
a.setIcon(icon);
a.setDisabledIcon(icon);
}
//restart the game when start button is clicked
void restartGame()
{
for(int i = 0;i < rows;i++)
for(int j = 0;j < columns;j++)
{
grids[i][j].setText("0");
grids[i][j].setIcon(null);
grids[i][j].setEnabled(true);
grids[i][j].setFont(new Font("Ariel",Font.PLAIN,25));
grids[i][j].setFocusPainted(false);
grids[i][j].setHorizontalAlignment(SwingConstants.CENTER);
grids[i][j].setMargin(new Insets(0, 0, 0, 0));
grids[i][j].setPreferredSize(new Dimension(CELL_LENGTH, CELL_HEIGHT));
grids[i][j].setBackground(cellColor);
grids[i][j].setForeground(cellColor);
grids[i][j].setBorderPainted(false);
}
setMines();
}
void won()
{
if(!wonCalled)
{
wonCalled=true;
for(int i = 0; i < rows; i++)
for(int j = 0; j < columns; j++)
if(grids[i][j].getText()=="-1")
{
grids[i][j].setText("");
grids[i][j].setEnabled(false);
}
Duration totalTime = Duration.between(startTime,endTime);
try
{
//Smooth out the time taken to show the Game won Panel
Thread.sleep(300);
}
catch(Exception e)
{
System.out.println(e);
}
String time=totalTime.toMinutes()+":"+((totalTime.toMillis()/1000)%60);
JOptionPane.showMessageDialog(null,"Yay, you won the game\n Time Taken = "+time,"Winning Message",JOptionPane.INFORMATION_MESSAGE,null);
}
}
public class clicker extends Thread
{
JButton tempButton;
int row, column;
clicker(JButton a, int r, int c)
{
tempButton=a;
row=r;
column=c;
start();
}
public void run()
{
if(tempButton.isEnabled())
tempButton.doClick();
}
}
class ListenForGridButton implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(!startedTime)
{
startTime=Instant.now();
startedTime=true;
}
JButton w = (JButton) e.getSource();
for(int i = 0; i < rows; i++)
for(int j = 0; j < columns; j++)
if(w==grids[i][j])
{
this.recursiveClick(w,i,j);
}
}
//function when a mine is clicked
void recursiveClick(JButton a, int r, int c)
{
if(a.getText().equals("-1"))
{
a.setBackground(Color.red);
a.setEnabled(false);
setMineIcon(a);
gameOver();
}
else if(a.getText().equals("0"))
{
a.setEnabled(false);
a.setText("");
a.setBackground(postCellColor);
for(int i = r-1; i < r+2; i++)
for(int j = c-1; j < c+2; j++)
if(i > -1 && i < rows && j > -1 && j < columns)
try
{
Thread.sleep(25);
new clicker(grids[i][j],i,j);
// this.recursiveClick(grids[i][j],i,j);
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
else
{
a.setBackground(postCellColor);
a.setEnabled(false);
}
if(ifWon())
{
endTime=Instant.now();
won();
}
}
void gameOver()
{
for(int i = 0; i < rows; i++)
for(int j = 0; j < columns; j++)
{
if(grids[i][j].getText()=="-1")
setMineIcon(grids[i][j]);
if(grids[i][j].getBackground()==cellColor)
grids[i][j].setText("");
grids[i][j].setEnabled(false);
}
JOptionPane.showMessageDialog(null,"Sorry, you've lost the game","Game Over",JOptionPane.INFORMATION_MESSAGE,null);
}
//check if the game has been won
boolean ifWon()
{
int count=0;
for( int i =0; i < rows; i++)
for( int j = 0; j < columns; j++)
if(grids[i][j].getBackground()==postCellColor) //colour of the clicked grids are
count+=1; //changed so check the colours
if(count==rows*columns-(int)Math.sqrt(rows*columns))
return true;
return false;
}
}
//Game is won
class ListenForStartButton implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
wonCalled=false;
startedTime=false;
restartGame();
}
}
//start the game
public static void main(String[] args)
{
Game game = new Game();
}
} | [
"aritrabasu1999@gmail.com"
] | aritrabasu1999@gmail.com |
89177aa15cf6a1f4e5fdfc85e304ebd325991400 | cbea23d5e087a862edcf2383678d5df7b0caab67 | /aws-java-sdk-route53recoverycontrolconfig/src/main/java/com/amazonaws/services/route53recoverycontrolconfig/model/DeleteControlPanelResult.java | ede20c2f4a7657c5e02cfdba4f29d55917f64914 | [
"Apache-2.0"
] | permissive | phambryan/aws-sdk-for-java | 66a614a8bfe4176bf57e2bd69f898eee5222bb59 | 0f75a8096efdb4831da8c6793390759d97a25019 | refs/heads/master | 2021-12-14T21:26:52.580137 | 2021-12-03T22:50:27 | 2021-12-03T22:50:27 | 4,263,342 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,402 | java | /*
* Copyright 2016-2021 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.route53recoverycontrolconfig.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/route53-recovery-control-config-2020-11-02/DeleteControlPanel"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeleteControlPanelResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* 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("{");
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DeleteControlPanelResult == false)
return false;
DeleteControlPanelResult other = (DeleteControlPanelResult) obj;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
return hashCode;
}
@Override
public DeleteControlPanelResult clone() {
try {
return (DeleteControlPanelResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| [
""
] | |
d3cf5cb5878b4c4806e1ddf07857a7850773c8a6 | f5b2c05cb7a9cba40688e2f02abf6d14e34ddd8d | /LetMeInHost/src/main/java/com/dawidcha/letmein/handlers/ExtractSessionId.java | a8ea1a232cae68cf4df2dc561487866ca631428b | [] | no_license | dawidcha/letmein | b8182de7c646f5c3d018467bea8d401376c9ad1c | 9f2637e35775b33d8c8b1b6306c0c8230339c959 | refs/heads/master | 2020-12-25T14:33:30.190172 | 2016-09-06T23:40:23 | 2016-09-06T23:40:23 | 66,707,347 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,134 | java | package com.dawidcha.letmein.handlers;
import com.dawidcha.letmein.Registry;
import com.dawidcha.letmein.data.BookingInfo;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.Handler;
import io.vertx.ext.web.RoutingContext;
import java.util.Map;
import java.util.UUID;
public class ExtractSessionId implements Handler<RoutingContext> {
@Override
public void handle(RoutingContext routingContext) {
Map<String, String> queryParams = ApiRouters.getQueryParameters(routingContext.request());
String sessionId = queryParams.get("sessionId");
if(sessionId == null) {
ApiRouters.closeWithStatus(routingContext.response(), HttpResponseStatus.UNAUTHORIZED);
return;
}
routingContext.put("sessionId", sessionId);
BookingInfo info = Registry.bookingInfoForSession(UUID.fromString(sessionId));
if(info == null) {
ApiRouters.closeWithStatus(routingContext.response(), HttpResponseStatus.FORBIDDEN);
return;
}
routingContext.put("bookingInfo", info);
routingContext.next();
}
}
| [
"dawidcha@gmail.com"
] | dawidcha@gmail.com |
e18f76619aaf3aee9f4a6953e7e6d5b18990c8a7 | 4aa90348abcb2119011728dc067afd501f275374 | /app/src/main/java/com/tencent/mm/plugin/wallet_payu/balance/a/b.java | ee06d48202275f15fc9c7447d849317b84cf9e39 | [] | no_license | jambestwick/HackWechat | 0d4ceb2d79ccddb45004ca667e9a6a984a80f0f6 | 6a34899c8bfd50d19e5a5ec36a58218598172a6b | refs/heads/master | 2022-01-27T12:48:43.446804 | 2021-12-29T10:36:30 | 2021-12-29T10:36:30 | 249,366,791 | 0 | 0 | null | 2020-03-23T07:48:32 | 2020-03-23T07:48:32 | null | UTF-8 | Java | false | false | 1,807 | java | package com.tencent.mm.plugin.wallet_payu.balance.a;
import com.tencent.mm.wallet_core.e.a.a;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
public final class b extends a {
public String fpP;
public String fuH;
public boolean isRedirect;
public String lie;
public double pNX;
public String pin;
public String tbn;
public String tbo;
public String tbp;
public String tbq;
public int tbr;
public String tbs;
public String tbt;
public boolean tbu;
public String tbv;
public b(String str, String str2, String str3, double d, String str4, String str5, String str6, String str7) {
this.pin = str;
this.tbn = str2;
this.fuH = str3;
this.pNX = d;
this.fpP = str4;
this.tbo = str5;
this.tbp = str6;
this.tbq = str7;
Map hashMap = new HashMap();
hashMap.put("pin", str);
hashMap.put("bind_serial", str5);
hashMap.put("req_key", str3);
hashMap.put("fee_type", str4);
hashMap.put("total_fee", Math.round(100.0d * d));
hashMap.put("bank_type", str6);
hashMap.put("cvv", str2);
hashMap.put("dest_bind_serial", str7);
D(hashMap);
}
public final int bKL() {
return 10;
}
public final void a(int i, String str, JSONObject jSONObject) {
this.lie = jSONObject.optString("trans_id");
this.tbr = jSONObject.optInt("response_result");
this.isRedirect = jSONObject.optBoolean("redirect");
this.tbs = jSONObject.optString("gateway_reference");
this.tbt = jSONObject.optString("gateway_code");
this.tbu = jSONObject.optBoolean("is_force_adjust");
this.tbv = jSONObject.optString("force_adjust_code");
}
}
| [
"malin.myemail@163.com"
] | malin.myemail@163.com |
7509798d6f3aeb8e68caa84bc7fc6cf075baea39 | ee2e3f3e70b8374010f887db5a083ebc772a8915 | /SMT-Assigments_Fall14_UMKC-master/Assignment5/L2/umkc.Bharat.Calculator/src/com/objectsbydesign/calc/model/Cpu.java | 5dad33cc78af9e31aefdb8d995169ff74e94ca8e | [] | no_license | meetsriharsha/SMT | 9aae3f00bede16ebdd6dc06c23ee52bd0b57f1c2 | 43029870b138152b44ce705b29c118451637f019 | refs/heads/master | 2021-01-10T07:34:46.552668 | 2016-03-02T04:21:09 | 2016-03-02T04:21:09 | 52,933,134 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 7,623 | java | /**
Object-Oriented Calculator
Copyright (C) 1999-2002, Objects by Design, Inc. All Rights Reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation. A copy of the license may be found at
http://www.objectsbydesign.com/projects/gpl.txt
*/
/**
* Implements the central processor unit (CPU).
* Coordinates the input of operands and the execution of operations.
*/
package com.objectsbydesign.calc.model;
import java.lang.reflect.Constructor;
import java.util.Observable;
import java.util.Observer;
import java.util.HashMap;
import com.objectsbydesign.calc.view.CalculatorArch;
public class Cpu extends Observable {
private OperandStack operandStack;
private OperationStack operationStack;
private Memory memory;
private Display display;
private State state;
private HashMap operationMap;
public State WaitingForInputState;
public State WaitingForNumberState;
public State WaitingForOperationState;
public State EnteringNumberState;
boolean displayUpdate;
Command cmd;
public Cpu(CalculatorArch calArch) {
// Bharat changed here code to get value
Value initialValue = calArch.OUT_Value;//new DecimalValue(0);
cmd = calArch.OUT_Command;
operandStack = new OperandStack();
operationStack = new OperationStack();
memory = new Memory(initialValue);
display = new Display(initialValue);
displayUpdate = false;
operationMap = new HashMap();
initializeStates();
// set the initial state
loadOperand(initialValue);
setState(WaitingForInputState);
}
private void initializeStates ( ) {
WaitingForInputState = new WaitingForInputState(this);
WaitingForNumberState = new WaitingForNumberState(this);
WaitingForOperationState = new WaitingForOperationState(this);
EnteringNumberState = new EnteringNumberState(this);
}
private void setState ( State state ) {
boolean viewStateChange = false;
this.state = state;
if (viewStateChange) {
String name = state.getClass().getName();
System.out.println("State: " + name);
}
}
/**
* Enter operations into the CPU
*/
public void enterOperation(String opcode) {
// create a class for the operation
Operation op = findOperation(opcode);
// depending on the current state, do operation, set new state
if (opcode.compareTo("MemoryRecall") == 0) {
// memory recall is an operation but behaves like a number
// so handle it as entering a value
setState(state.enterValue(op));
}
else
setState(state.enterOperation(op));
}
/**
* Enter numbers into the CPU. The CPU uses its current state
* to determine what to do with the number.
*/
public void enterDigit(String digit) {
// depending on the current state, handle new digit, set new state.
setState(state.enterDigit(digit));
}
private Operation findOperation(String operation) {
String model = "com.objectsbydesign.calc.model";
Operation op = null;
Constructor constructor = null;
try {
// check the operation cache first
op = (Operation) operationMap.get(operation);
if (op == null) {
// create an instance of the operation
Class klass = Class.forName(model + "." +operation);
constructor = klass.getDeclaredConstructor(null);
op = (Operation) constructor.newInstance(null);
operationMap.put(operation, op);
}
} catch (Exception ex) {
System.out.println(ex.toString());
}
return op;
}
/**
* Push the display input onto the operand stack, and broadcasts the
* input to all observers
*/
public void pushDisplayRegister() {
Value value = display.createValue();
operandStack.push(value);
doNotify(new OperandCommand(value));
}
/**
* Push the operand value onto the operand stack.
*/
public void loadOperand(Value value) {
operandStack.push(value);
}
/**
* Push the operation onto the operation stack or execute immediately, and broadcast the
* input to all observers
*/
public void pushOperation(Operation op) {
// compare precedence of new operation to the top of the stack (if not empty)
// if the new operation has equal or higher precedence,
// execute the operation from the stack
if (!operationStack.empty() &&
operationStack.peek().getPrecedence() >= op.getPrecedence())
operationStack.pop().execute(this);
// if the operation has no lookahead
if (!op.getLookahead()) {
// execute immediately
op.execute(this);
}
// if the operation has a lookahead
else {
// push operation for later execution
operationStack.push(op);
}
cmd.setOp(op);
doNotify(cmd);
// doNotify(new OperationCommand(op));
updateDisplay();
}
/**
* Execute the operation and broadcast the input to all observers
*/
public void executeOperation(Operation op) {
op.execute(this);
cmd.setOp(op);
doNotify(cmd);
// doNotify(new OperationCommand(op));
}
/**
* Replace the top operation on the operation stack.
*/
public void replaceOperation(Operation op) {
if (!operationStack.empty()) {
operationStack.pop();
pushOperation(op);
}
}
/**
* Execute the equals function.
*/
public void equals() {
while (!operationStack.empty()) {
operationStack.pop().execute(this);
}
}
/**
* Set the display register with any calculated results
*/
public void updateDisplay() {
if (displayUpdate && !operandStack.empty()) {
Value value = operandStack.peek();
display.setValue(value);
doNotify(new OperandCommand(value));
displayUpdate = false;
}
}
/**
* Executes the clear function. Empties the stacks and clears the display register.
*/
public void clear() {
operandStack.clear();
operationStack.clear();
display.clear();
}
/**
* Resets the CPU. Empties the stacks and resets the display register.
*/
public void reset() {
operandStack.clear();
operationStack.clear();
display.reset();
}
public void addDisplayObserver(Observer observer) {
display.addObserver(observer);
}
public void addMemoryObserver(Observer observer) {
memory.addObserver(observer);
}
/**
* Notify all observers of an input to the CPU
*/
private void doNotify(Object object) {
setChanged();
notifyObservers(object);
}
public void setUpdateDisplay() {
displayUpdate = true;
}
public OperandStack getOperandStack() {
return operandStack;
}
public OperationStack getOperationStack() {
return operationStack;
}
public Memory getMemoryRegister() {
return memory;
}
public Display getDisplayRegister() {
return display;
}
}
| [
"meetsriharsha@gmail.com"
] | meetsriharsha@gmail.com |
5d232041ba8351f1fa3265f4472849f26fbae2a5 | f7f1066e9ece490f9a7b061d232ee398813c6348 | /ExercicioGit1/src/Main.java | 148d3b45100b2be13a3ed565a187084afa32a486 | [] | no_license | nestoraugusto/ExercicioGit1 | 7fd10b5afc86073a0a92d07ea256cfda95b7077c | 2686a7e348d817978e845332a83572c3921ac775 | refs/heads/master | 2021-01-23T11:47:43.488409 | 2015-04-07T00:57:17 | 2015-04-07T00:57:30 | 33,513,522 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 123 | java |
public class Main {
public static void main(String[] args) {
System.out.println("Eu sei Criar isso");
}
}
| [
"nestor_boleiro@hotmail.com"
] | nestor_boleiro@hotmail.com |
26d9598af38030895baf6dd585725cac9ebaa4c7 | a5b866f5708d857347a50d6f106754c040d1acf4 | /Maps, Lambda and Stream API - Exercise/src/LegendaryFarming.java | 7558b2ae47a964f576ee230c972d7ecadd1d4bf5 | [] | no_license | StanchevaYoana/Java-Fundamentals | 3c8434cdab20a009737e0d25be2d45bc0d772e37 | 99a883c313864f52ae39026a508925f4924325d4 | refs/heads/master | 2020-06-21T20:00:54.710482 | 2019-08-05T13:50:29 | 2019-08-05T13:50:29 | 197,541,288 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,636 | java | import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class LegendaryFarming {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Map<String, Integer> keyMaterials = new HashMap<>();
Map<String, Integer> trash = new HashMap<>();
String winner = "";
boolean haveWinner = false;
keyMaterials.put("shards", 0);
keyMaterials.put("fragments", 0);
keyMaterials.put("motes", 0);
do {
String[] input = scanner.nextLine().split("\\s+");
for (int i = 0; i < input.length; i += 2) {
int quantity = Integer.valueOf(input[i]);
String material = input[i + 1].toLowerCase();
if (!keyMaterials.containsKey(material)) {
trash.putIfAbsent(material, 0);
trash.put(material, trash.get(material) + quantity);
} else {
keyMaterials.put(material, keyMaterials.get(material) + quantity);
if (keyMaterials.get(material) >= 250) {
keyMaterials.put(material, keyMaterials.get(material) - 250);
switch (material) {
case "shards":
winner = "Shadowmourne";
break;
case "fragments":
winner = "Valanyr";
break;
case "motes":
winner = "Dragonwrath";
break;
}
System.out.printf("%s obtained!%n", winner);
haveWinner = true;
break;
}
}
}
} while (!haveWinner);
keyMaterials
.entrySet().stream().sorted((a, b) -> {
int sort = Integer.compare(b.getValue(), a.getValue());
if (sort == 0) {
sort = a.getKey().compareTo(b.getKey());
}
return sort;
}).forEach(e -> {
System.out.println(String.format(
"%s: %d", e.getKey(), e.getValue()
));
});
trash
.entrySet().stream()
.sorted(Comparator.comparing(Map.Entry::getKey))
.forEach(e -> {
System.out.println(String.format("%s: %d", e.getKey(), e.getValue()));
});
}
}
| [
"yoana.radoslavova@gmail.com"
] | yoana.radoslavova@gmail.com |
b21db13942648cb064d9b720529b416488bf03ed | e69fbe41b7f347d59c5c11580af5721688407378 | /ad/src/main/java/com/example/adtest/splash/SplashViewADLoadListener.java | c2f9dc5ac225070caa5b11b6c3042da1dd0edda4 | [] | no_license | ZhouSilverBullet/mobiclearsafe-overseas | 578fa39a3a320e41c68e9c6f6703647b5f6d4fc8 | f885469217c1942eb680da712f083bede8ee4fd7 | refs/heads/master | 2022-07-03T13:06:38.407425 | 2020-05-11T02:58:22 | 2020-05-11T02:58:22 | 261,681,978 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 581 | java | package com.example.adtest.splash;
/**
* author : liangning
* date : 2019-11-28 21:54
*/
public interface SplashViewADLoadListener {
void LoadError(String channel, int errorCode, String errorMsg);//广告加载错误
void onTimeout(String channel);//广告加载超时
void onAdClicked(String channel);//广告被点击
void onAdShow(String channel);//广告显示
void onSplashAdLoad(String channel);//广告加载成功
default void onAdSkip(String channel) { //广告跳过
}
default void onAdTimeOver() { //广告倒计时结束
}
}
| [
"zhousaito@163.com"
] | zhousaito@163.com |
eb037bc1c29caf9d37a290886b11cf624521a6fb | ac27a514f3e7e24b9ed24ad272806d553aa2e6f2 | /src/test/java/com/asule/test/Test1.java | aa9f924caff00dcf6a80b82961d72671df96d3a6 | [] | no_license | ausle/mystore | 9fea15ae7e7cee6a16ff2c4aa7af8cb45bff5a2f | de3da15fd063d3428b3ce68fcdfb4d7a46d72beb | refs/heads/master | 2020-05-02T19:06:07.155643 | 2019-04-09T12:42:18 | 2019-04-09T12:42:18 | 178,149,073 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,856 | java | package com.asule.test;
import com.asule.entity.User;
import com.google.common.cache.*;
import junit.framework.TestCase;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class Test1 extends TestCase{
public void test3() throws IOException, ExecutionException, InterruptedException {
//缓存接口这里是LoadingCache,LoadingCache在缓存项不存在时可以自动加载缓存
LoadingCache<Integer,User> studentCache
//CacheBuilder的构造函数是私有的,只能通过其静态方法newBuilder()来获得CacheBuilder的实例
= CacheBuilder.newBuilder()
//设置并发级别为8,并发级别是指可以同时写缓存的线程数
.concurrencyLevel(8)
//设置写缓存后8秒钟过期
.expireAfterWrite(8, TimeUnit.SECONDS)
//设置缓存容器的初始容量为10
.initialCapacity(10)
//设置缓存最大容量为100,超过100之后就会按照LRU最近虽少使用算法来移除缓存项
.maximumSize(100)
//设置要统计缓存的命中率
.recordStats()
//设置缓存的移除通知
.removalListener(new RemovalListener<Object, Object>() {
@Override
public void onRemoval(RemovalNotification<Object, Object> notification) {
System.out.println(notification.getKey() + " was removed, cause is " + notification.getCause());
}
})
//build方法中可以指定CacheLoader,在缓存不存在时通过CacheLoader的实现自动加载缓存
.build(
new CacheLoader<Integer, User>() {
@Override
public User load(Integer key) throws Exception {
System.out.println("load student " + key);
User student = new User();
student.setId(key);
student.setUsername("name " + key);
return student;
}
}
);
for (int i=0;i<20;i++) {
//从缓存中得到数据,由于我们没有设置过缓存,所以需要通过CacheLoader加载缓存数据
User student = studentCache.get(1);
System.out.println(student);
//休眠1秒
TimeUnit.SECONDS.sleep(1);
}
System.out.println("cache stats:");
//最后打印缓存的命中率等 情况
System.out.println(studentCache.stats().toString());
}
}
| [
"distincfofwang@gmail.com"
] | distincfofwang@gmail.com |
642a05e36e553a723e0074fad2262cb95845f81a | 589332007e2329af5b183fac676dc8712d67d169 | /server/cas/src/main/java/org/apereo/cas/support/oauth/web/endpoints/OAuth20AccessTokenEndpointController.java | a24e08c0cebc24e3e2956d202e003af37ec0d7e3 | [
"Apache-2.0"
] | permissive | ThierryTouin/cas5-oidc-cluster | d2b2d8ad72ab7bd4c912847b0a5db9848b66769a | 207d69c90ab1e96de68a4f3ae84994abe0e4763d | refs/heads/master | 2022-06-05T14:37:53.107612 | 2022-05-12T13:49:23 | 2022-05-12T13:49:23 | 142,321,855 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 15,255 | java | package org.apereo.cas.support.oauth.web.endpoints;
import com.google.common.base.Supplier;
import org.apache.commons.lang3.tuple.Pair;
import org.apereo.cas.authentication.principal.PrincipalFactory;
import org.apereo.cas.authentication.principal.ServiceFactory;
import org.apereo.cas.authentication.principal.WebApplicationService;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.services.ServicesManager;
import org.apereo.cas.support.oauth.OAuth20Constants;
import org.apereo.cas.support.oauth.OAuth20GrantTypes;
import org.apereo.cas.support.oauth.OAuth20ResponseTypes;
import org.apereo.cas.support.oauth.profile.OAuth20ProfileScopeToAttributesFilter;
import org.apereo.cas.support.oauth.services.OAuthRegisteredService;
import org.apereo.cas.support.oauth.util.OAuth20Utils;
import org.apereo.cas.support.oauth.validator.OAuth20Validator;
import org.apereo.cas.support.oauth.web.response.accesstoken.AccessTokenResponseGenerator;
import org.apereo.cas.support.oauth.web.response.accesstoken.OAuth20TokenGenerator;
import org.apereo.cas.support.oauth.web.response.accesstoken.ext.AccessTokenRequestDataHolder;
import org.apereo.cas.support.oauth.web.response.accesstoken.ext.BaseAccessTokenGrantRequestExtractor;
import org.apereo.cas.ticket.ExpirationPolicy;
import org.apereo.cas.ticket.Ticket;
import org.apereo.cas.ticket.accesstoken.AccessToken;
import org.apereo.cas.ticket.accesstoken.AccessTokenFactory;
import org.apereo.cas.ticket.refreshtoken.RefreshToken;
import org.apereo.cas.ticket.registry.TicketRegistry;
import org.apereo.cas.util.Pac4jUtils;
import org.apereo.cas.web.support.CookieRetrievingCookieGenerator;
import org.pac4j.core.context.J2EContext;
import org.pac4j.core.profile.ProfileManager;
import org.pac4j.core.profile.UserProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.Optional;
/**
* This controller returns an access token according to the given
* OAuth code and client credentials (authorization code grant type)
* or according to the refresh token and client credentials
* (refresh token grant type) or according to the user identity
* (resource owner password grant type).
*
* @author Jerome Leleu
* @since 3.5.0
*/
public class OAuth20AccessTokenEndpointController extends BaseOAuth20Controller {
private static final Logger LOGGER = LoggerFactory.getLogger(OAuth20AccessTokenEndpointController.class);
private final OAuth20TokenGenerator accessTokenGenerator;
private final AccessTokenResponseGenerator accessTokenResponseGenerator;
private final ExpirationPolicy accessTokenExpirationPolicy;
private final Collection<BaseAccessTokenGrantRequestExtractor> accessTokenGrantRequestExtractors;
public OAuth20AccessTokenEndpointController(final ServicesManager servicesManager,
final TicketRegistry ticketRegistry,
final OAuth20Validator validator,
final AccessTokenFactory accessTokenFactory,
final PrincipalFactory principalFactory,
final ServiceFactory<WebApplicationService> webApplicationServiceServiceFactory,
final OAuth20TokenGenerator accessTokenGenerator,
final AccessTokenResponseGenerator accessTokenResponseGenerator,
final OAuth20ProfileScopeToAttributesFilter scopeToAttributesFilter,
final CasConfigurationProperties casProperties,
final CookieRetrievingCookieGenerator ticketGrantingTicketCookieGenerator,
final ExpirationPolicy accessTokenExpirationPolicy,
final Collection<BaseAccessTokenGrantRequestExtractor> accessTokenGrantRequestExtractors) {
super(servicesManager, ticketRegistry, validator, accessTokenFactory,
principalFactory, webApplicationServiceServiceFactory,
scopeToAttributesFilter, casProperties, ticketGrantingTicketCookieGenerator);
LOGGER.debug("****** accessTokenGenerator=" + accessTokenGenerator);
this.accessTokenGenerator = accessTokenGenerator;
this.accessTokenResponseGenerator = accessTokenResponseGenerator;
this.accessTokenExpirationPolicy = accessTokenExpirationPolicy;
this.accessTokenGrantRequestExtractors = accessTokenGrantRequestExtractors;
}
/**
* Handle request internal model and view.
*
* @param request the request
* @param response the response
* @throws Exception the exception
*/
@PostMapping(path = {OAuth20Constants.BASE_OAUTH20_URL + '/' + OAuth20Constants.ACCESS_TOKEN_URL,
OAuth20Constants.BASE_OAUTH20_URL + '/' + OAuth20Constants.TOKEN_URL})
public void handleRequest(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
LOGGER.debug("****** handleRequest");
try {
response.setContentType(MediaType.TEXT_PLAIN_VALUE);
if (!verifyAccessTokenRequest(request, response)) {
LOGGER.error("Access token request verification failed");
OAuth20Utils.writeTextError(response, OAuth20Constants.INVALID_REQUEST);
return;
}
final AccessTokenRequestDataHolder responseHolder;
try {
responseHolder = examineAndExtractAccessTokenGrantRequest(request, response);
LOGGER.debug("Creating access token for [{}]", responseHolder);
LOGGER.debug("responseHolder.getToken() [{}]", responseHolder.getToken());
LOGGER.debug("responseHolder.getToken().getGrantingTicket() [{}]", responseHolder.getToken().getGrantingTicket());
} catch (final Exception e) {
LOGGER.error("Could not identify and extract access token request", e);
OAuth20Utils.writeTextError(response, OAuth20Constants.INVALID_GRANT);
return;
}
LOGGER.debug("****** 1");
final J2EContext context = Pac4jUtils.getPac4jJ2EContext(request, response);
LOGGER.debug("****** 2");
final Pair<AccessToken, RefreshToken> accessToken = accessTokenGenerator.generate(responseHolder);
LOGGER.debug("****** 3");
LOGGER.debug("Access token generated is: [{}]. Refresh token generated is [{}]", accessToken.getKey(), accessToken.getValue());
generateAccessTokenResponse(request, response, responseHolder, context, accessToken.getKey(), accessToken.getValue());
LOGGER.debug("****** 4");
response.setStatus(HttpServletResponse.SC_OK);
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
throw new RuntimeException(e.getMessage(), e);
}
}
/**
* Handle request internal model and view.
*
* @param request the request
* @param response the response
* @throws Exception the exception
*/
@GetMapping(path = {OAuth20Constants.BASE_OAUTH20_URL + '/' + OAuth20Constants.ACCESS_TOKEN_URL,
OAuth20Constants.BASE_OAUTH20_URL + '/' + OAuth20Constants.TOKEN_URL})
public void handleGetRequest(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
LOGGER.debug("******handleGetRequest");
handleRequest(request, response);
}
private void generateAccessTokenResponse(final HttpServletRequest request, final HttpServletResponse response,
final AccessTokenRequestDataHolder responseHolder,
final J2EContext context, final AccessToken accessToken,
final RefreshToken refreshToken) {
LOGGER.debug("******Generating access token response for [{}]", accessToken);
final OAuth20ResponseTypes type = OAuth20Utils.getResponseType(context);
LOGGER.debug("Located response type as [{}]", type);
this.accessTokenResponseGenerator.generate(request, response,
responseHolder.getRegisteredService(),
responseHolder.getService(),
accessToken, refreshToken,
accessTokenExpirationPolicy.getTimeToLive(), type);
}
private AccessTokenRequestDataHolder examineAndExtractAccessTokenGrantRequest(final HttpServletRequest request,
final HttpServletResponse response) {
LOGGER.debug("******examineAndExtractAccessTokenGrantRequest");
return this.accessTokenGrantRequestExtractors.stream()
.filter(ext -> ext.supports(request))
.findFirst()
.orElseThrow((Supplier<RuntimeException>) () -> new UnsupportedOperationException("Request is not supported"))
.extract(request, response);
}
/**
* Verify the access token request.
*
* @param request the HTTP request
* @param response the HTTP response
* @return true, if successful
*/
private boolean verifyAccessTokenRequest(final HttpServletRequest request, final HttpServletResponse response) {
LOGGER.debug("******verifyAccessTokenRequest");
final String grantType = request.getParameter(OAuth20Constants.GRANT_TYPE);
if (!isGrantTypeSupported(grantType, OAuth20GrantTypes.values())) {
LOGGER.warn("Grant type is not supported: [{}]", grantType);
return false;
}
final ProfileManager manager = Pac4jUtils.getPac4jProfileManager(request, response);
final Optional<UserProfile> profile = manager.get(true);
if (profile == null || !profile.isPresent()) {
LOGGER.warn("Could not locate authenticated profile for this request");
return false;
}
final UserProfile uProfile = profile.get();
if (uProfile == null) {
LOGGER.warn("Could not locate authenticated profile for this request as null");
return false;
}
if (OAuth20Utils.isGrantType(grantType, OAuth20GrantTypes.AUTHORIZATION_CODE)) {
LOGGER.debug("******verifyAccessTokenRequest AUTHORIZATION_CODE ");
return verifyAccessForGrantAuthorizationCode(request, grantType, uProfile);
}
if (OAuth20Utils.isGrantType(grantType, OAuth20GrantTypes.REFRESH_TOKEN)) {
LOGGER.debug("******verifyAccessTokenRequest REFRESH_TOKEN");
return verifyAccessForGrantRefreshToken(request, uProfile);
}
if (OAuth20Utils.isGrantType(grantType, OAuth20GrantTypes.PASSWORD)) {
LOGGER.debug("******verifyAccessTokenRequest PASSWORD");
return verifyAccessForGrantPassword(request, grantType, uProfile);
}
if (OAuth20Utils.isGrantType(grantType, OAuth20GrantTypes.CLIENT_CREDENTIALS)) {
LOGGER.debug("******verifyAccessTokenRequest CLIENT_CREDENTIALS");
return verifyAccessForGrantClientCredentials(request, grantType, uProfile);
}
return false;
}
private boolean verifyAccessForGrantClientCredentials(final HttpServletRequest request, final String grantType, final UserProfile uProfile) {
LOGGER.debug("******verifyAccessForGrantClientCredentials");
final String clientId = uProfile.getId();
LOGGER.debug("Received grant type [{}] with client id [{}]", grantType, clientId);
final OAuthRegisteredService registeredService = OAuth20Utils.getRegisteredOAuthService(this.servicesManager, clientId);
return this.validator.checkServiceValid(registeredService);
}
private boolean verifyAccessForGrantPassword(final HttpServletRequest request, final String grantType, final UserProfile uProfile) {
LOGGER.debug("******verifyAccessForGrantPassword");
return verifyAccessForGrantClientCredentials(request, grantType, uProfile);
}
private boolean verifyAccessForGrantRefreshToken(final HttpServletRequest request, final UserProfile uProfile) {
LOGGER.debug("******verifyAccessForGrantRefreshToken");
if (!this.validator.checkParameterExist(request, OAuth20Constants.REFRESH_TOKEN)) {
return false;
}
final String token = request.getParameter(OAuth20Constants.REFRESH_TOKEN);
final Ticket refreshToken = ticketRegistry.getTicket(token);
if (refreshToken == null) {
LOGGER.warn("Provided refresh token [{}] cannot be found in the registry", token);
return false;
}
if (!RefreshToken.class.isAssignableFrom(refreshToken.getClass())) {
LOGGER.warn("Provided refresh token [{}] is found in the registry but its type is not classified as a refresh token", token);
return false;
}
if (refreshToken.isExpired()) {
LOGGER.warn("Provided refresh token [{}] has expired and is no longer valid.", token);
return false;
}
return true;
}
private boolean verifyAccessForGrantAuthorizationCode(final HttpServletRequest request, final String grantType, final UserProfile uProfile) {
LOGGER.debug("******verifyAccessForGrantAuthorizationCode");
final String clientId = uProfile.getId();
final String redirectUri = request.getParameter(OAuth20Constants.REDIRECT_URI);
final OAuthRegisteredService registeredService = OAuth20Utils.getRegisteredOAuthService(this.servicesManager, clientId);
LOGGER.debug("Received grant type [{}] with client id [{}] and redirect URI [{}]", grantType, clientId, redirectUri);
return this.validator.checkParameterExist(request, OAuth20Constants.REDIRECT_URI)
&& this.validator.checkParameterExist(request, OAuth20Constants.CODE)
&& this.validator.checkCallbackValid(registeredService, redirectUri);
}
/**
* Check the grant type against expected grant types.
*
* @param type the current grant type
* @param expectedTypes the expected grant types
* @return whether the grant type is supported
*/
private static boolean isGrantTypeSupported(final String type, final OAuth20GrantTypes... expectedTypes) {
LOGGER.debug("****** Grant type: [{}]", type);
for (final OAuth20GrantTypes expectedType : expectedTypes) {
if (OAuth20Utils.isGrantType(type, expectedType)) {
return true;
}
}
LOGGER.error("Unsupported grant type: [{}]", type);
return false;
}
}
| [
"thierry.touin@gfi.fr"
] | thierry.touin@gfi.fr |
6efcd2482f44faedbb6590c1c742eb2dabd1be5c | 706dae6cc6526064622d4f5557471427441e5c5e | /src/main/java/com/anbo/juja/patterns/nullObject_15/sample/codenjoy/Point.java | bbfaf717c3cd6fe213c39ac6c65db829b8a942c8 | [] | no_license | Anton-Bondar/Design-patterns-JUJA-examples- | 414edabfd8c4148640de7de8d01f809b01c3c17c | 9e3d628f7e45c0106514f8f459ea30fffed702d5 | refs/heads/master | 2021-10-09T04:45:42.372993 | 2018-12-21T12:09:00 | 2018-12-21T12:11:14 | 121,509,668 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 336 | java | package com.anbo.juja.patterns.nullObject_15.sample.codenjoy;
/**
* Created by oleksandr.baglai on 10.12.2015.
*/
// координата x, y
public interface Point {
// тоже синглтончик (смотри Game.NULL - там объяснение)
Point NULL = new NullPoint();
int getX();
int getY();
}
| [
"AntonBondar2013@gmail.com"
] | AntonBondar2013@gmail.com |
a1b07ad131190610dd38fd1db74a2d7e0bdf3d8d | 6ac41caa50166da82e0174cee3e5c2b1c1a9c9c6 | /src/main/java/com/tencent/easycount/driver/GraphPrinter.java | a2509acc6220411fdf794af68b0ba4d78bcf449a | [] | no_license | bobqiu/EasyCount | dcbbd7b7bb24ee8cc0ab29056f83d3aae6903eba | 5327b4eb5175f1b9ea805dda6e8f981a6ad8b6aa | refs/heads/master | 2020-05-27T05:53:21.505874 | 2017-12-21T02:49:58 | 2017-12-21T02:49:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,843 | java | package com.tencent.easycount.driver;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Stack;
import prefuse.data.Graph;
import prefuse.data.io.GraphMLReader;
import com.tencent.easycount.plan.logical.LogicalPlan;
import com.tencent.easycount.plan.logical.OpDesc;
import com.tencent.easycount.plan.physical.PhysicalPlan;
import com.tencent.easycount.util.graph.GraphDrawer;
import com.tencent.easycount.util.graph.GraphWalker;
import com.tencent.easycount.util.graph.GraphWalker.Dispatcher;
import com.tencent.easycount.util.graph.GraphWalker.Node;
import com.tencent.easycount.util.graph.GraphWalker.WalkMode;
import com.tencent.easycount.util.graph.GraphXmlBuilder;
public class GraphPrinter {
static void graphPrint(final LogicalPlan lPlan, final PhysicalPlan pPlan,
final boolean withRoot) throws Exception {
final ArrayList<Node> rootOpDescs = new ArrayList<Node>();
if (withRoot) {
final OpDesc rootOp = new OpDesc() {
private static final long serialVersionUID = -1298273294286915472L;
@Override
public String getName() {
return "ROOT";
}
};
for (final OpDesc op : lPlan.getRootOps()) {
rootOp.addChild(op);
}
rootOpDescs.add(rootOp);
} else {
for (final OpDesc op : lPlan.getRootOps()) {
rootOpDescs.add(op);
}
}
final GraphXmlBuilder builder = new GraphXmlBuilder();
final HashMap<OpDesc, Integer> opDesc2TaskId = pPlan.getOpDesc2TaskId();
final GraphWalker<String> walker = new GraphWalker<String>(
new Dispatcher<String>() {
@Override
public String dispatch(final Node nd,
final Stack<Node> stack,
final ArrayList<String> nodeOutputs,
final HashMap<Node, String> retMap) {
builder.addNode(nd.toString(), nd.getName(),
String.valueOf(opDesc2TaskId.get(nd)));
for (final Node node : nd.getChildren()) {
builder.addEdge(nd.toString(), node.toString());
}
return "";
}
@Override
public boolean needToDispatchChildren(final Node nd,
final Stack<Node> stack,
final ArrayList<String> nodeOutputs,
final HashMap<Node, String> retMap) {
return true;
}
}, WalkMode.CHILD_FIRST, "driverGraphPrint");
walker.walk(rootOpDescs);
final String xml = builder.build();
System.out.println(xml);
final ByteBuffer buffer = ByteBuffer.wrap(xml.getBytes());
final InputStream is = new InputStream() {
@Override
public int read() throws IOException {
if (!buffer.hasRemaining()) {
return -1;
}
return buffer.get();
}
};
final Graph graph = new GraphMLReader().readGraph(is);
GraphDrawer.draw(graph);
}
}
| [
"tianwp@gmail.com"
] | tianwp@gmail.com |
7daca65a166813501ff418a66c899ed07db2c4ba | 0462af66f84057513387bb09616b74441970082b | /primavera/primavera-web/src/main/java/br/com/leonardoferreira/primavera/web/request/handler/RequestHandlerMetadata.java | 6a391bd1bf16efb902f3b4e260a9f0f65ab2d95f | [] | no_license | LeonardoFerreiraa/vacation-projects | d468a98dc8fc819bd2f3dccac1adc60cb1e59a6f | 839860333a69f5efddbae3686eea38b978197b1b | refs/heads/master | 2022-12-22T15:35:47.117575 | 2022-05-13T18:52:08 | 2022-05-13T18:52:08 | 228,439,669 | 0 | 0 | null | 2022-12-14T20:43:20 | 2019-12-16T17:29:42 | Java | UTF-8 | Java | false | false | 2,283 | java | package br.com.leonardoferreira.primavera.web.request.handler;
import br.com.leonardoferreira.primavera.functional.Outcome;
import br.com.leonardoferreira.primavera.util.AnnotationUtils;
import br.com.leonardoferreira.primavera.web.request.RequestMethod;
import br.com.leonardoferreira.primavera.web.resolver.MethodArgumentResolver;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Data;
import lombok.RequiredArgsConstructor;
@Data
@Builder(access = AccessLevel.PRIVATE)
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class RequestHandlerMetadata {
private final RequestMethod requestMethod;
private final Object instance;
private final Method method;
private final RequestPath path;
public static RequestHandlerMetadata newInstance(final Object instance, final Method method) {
return AnnotationUtils.findAnnotation(method, RequestHandler.class)
.map(handler -> RequestHandlerMetadata.builder()
.instance(instance)
.method(method)
.requestMethod(handler.method())
.path(RequestPath.fromPath(handler.path()))
.build())
.orElse(null);
}
public boolean canHandle(final HttpServletRequest req) {
final String pathInfo = req.getPathInfo();
final RequestMethod method = RequestMethod.valueOf(req.getMethod());
return path.matches(pathInfo) && method.equals(this.requestMethod);
}
public Outcome<Object, Throwable> handle(final HttpServletRequest request,
final HttpServletResponse response,
final Set<MethodArgumentResolver> resolvers) {
return Outcome.of(() -> {
final Object[] args = Arrays.stream(method.getParameters())
.map(parameter -> MethodArgumentResolver.resolve(request, response, this, resolvers, parameter))
.toArray();
return method.invoke(instance, args);
});
}
}
| [
"mail@leonardoferreira.com.br"
] | mail@leonardoferreira.com.br |
d8b3e1cc3d9145a3b9ca4ec13db11b629bcfbe4e | 7c2f5bdf6199ee25afafbc8bc2eb77541976d00e | /Game/src/main/java/io/riguron/game/winner/solo/order/PlaceOrderBy.java | 2ca17afecbc54e6c967e3e3275199de5cddcd021 | [
"MIT"
] | permissive | Stijn-van-Nieulande/MinecraftNetwork | 0995d2fad0f7e1150dff0394c2568d9e8f6d1dca | 7ed43098a5ba7574e2fb19509e363c3cf124fc0b | refs/heads/master | 2022-04-03T17:48:42.635003 | 2020-01-22T05:22:49 | 2020-01-22T05:22:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 240 | java | package io.riguron.game.winner.solo.order;
import io.riguron.game.player.GamePlayer;
import java.util.function.Function;
public interface PlaceOrderBy extends Function<GamePlayer, Integer> {
Integer apply(GamePlayer gamePlayer);
}
| [
"25826296+riguron@users.noreply.github.com"
] | 25826296+riguron@users.noreply.github.com |
82e27a5479aa9ce32efd636a5f6152f49562f035 | e16bb94db667cfc82e90132ef9f1e90c42c80264 | /src/com/myPackage/ArmstrongNumber.java | 6cea53d3fd4490636af5690dc866620fdfc38d9f | [] | no_license | akshayark97/PracticeJavaProgram | 1f4b0f09c1a389c35e35303333667d4e48ef49b9 | cf42e3ca1b9a8d8bbe4eda7f78aa4729152a0ae9 | refs/heads/master | 2020-09-14T02:03:01.997668 | 2019-11-20T16:41:20 | 2019-11-20T16:41:20 | 222,977,375 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 432 | java | package com.myPackage;
import java.util.Scanner;
public class ArmstrongNumber {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int temp = n;
int c=0, a;
while(n > 0)
{
a = n % 10;
n = n/10;
c = c + (a*a*a);
}
if(temp == c)
{
System.out.println("Armstrong number");
}
else
{
System.out.println("Not an Armstrong number");
}
}
}
| [
"39210915+akshayark97@users.noreply.github.com"
] | 39210915+akshayark97@users.noreply.github.com |
d05c8fab97b36a4861d278f1a2f38d40c570c60e | fe14cd30d5ec3449a2153d70a3e96eb389a186a8 | /src/main/java/org/huahinframework/core/lib/join/MasterJoinFilter.java | 5531ecaa436870964a8edb7914ee8ba4d9a20598 | [
"Apache-2.0"
] | permissive | huahin/huahin-core | 6f2f25a192b859f932f940e76627ad7fbb34b0d3 | a87921b5a12be92a822f753c075ab2431036e6f5 | refs/heads/master | 2020-04-08T18:38:24.197693 | 2013-03-04T03:32:54 | 2013-03-04T03:32:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,416 | java | /*
* 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.huahinframework.core.lib.join;
import java.io.IOException;
import org.huahinframework.core.Filter;
import org.huahinframework.core.SimpleJob;
import org.huahinframework.core.io.Record;
import org.huahinframework.core.writer.Writer;
/**
* this filter is master fileter for big join.
*/
public class MasterJoinFilter extends Filter {
private String[] joinColumn;
private String[] masterLabels;
/**
* {@inheritDoc}
*/
@Override
public void init() {
}
/**
* {@inheritDoc}
*/
@Override
public void filter(Record record, Writer writer)
throws IOException, InterruptedException {
Record emitRecord = new Record();
for (int i = 0; i < joinColumn.length; i++) {
emitRecord.addGrouping("JOIN_KEY" + i, record.getValueString(joinColumn[i]));
}
emitRecord.addSort(1, Record.SORT_LOWER, 1);
for (String s : masterLabels) {
emitRecord.addValue(s, record.getValueString(s));
}
writer.write(emitRecord);
}
/**
* {@inheritDoc}
*/
@Override
public void filterSetup() {
int type = getIntParameter(SimpleJob.READER_TYPE);
if (type == SimpleJob.SINGLE_COLUMN_JOIN_READER) {
joinColumn = new String[1];
joinColumn[0] = getStringParameter(SimpleJob.JOIN_MASTER_COLUMN);
} else if (type == SimpleJob.SOME_COLUMN_JOIN_READER) {
joinColumn = getStringsParameter(SimpleJob.JOIN_MASTER_COLUMN);
}
masterLabels = getStringsParameter(SimpleJob.MASTER_LABELS);
}
}
| [
"beter.max@gmail.com"
] | beter.max@gmail.com |
cc5278523e33e4d537d3acf895d8f735ce2ff33c | 199d7f11bc6178a8ea240b5bf6e6e3092e50a214 | /container/openejb-core/src/test/java/org/apache/openejb/config/AutoConfigPersistenceUnitsTest.java | 77f6d2eb4d81f03dce89357e9a92c88ebff7eec6 | [
"BSD-3-Clause",
"W3C-19980720",
"CDDL-1.0",
"Apache-2.0",
"W3C",
"MIT"
] | permissive | kdchamil/ASTomEE | 31fc4478cc58351d98a298e5849d3a5a72e7ab6e | eaad273b8def8836bb2e82aab04c067662d2f67b | refs/heads/master | 2023-01-13T07:31:53.989780 | 2014-08-07T06:52:32 | 2014-08-07T06:52:32 | 19,934,900 | 0 | 0 | Apache-2.0 | 2023-01-02T22:04:23 | 2014-05-19T08:49:01 | Java | UTF-8 | Java | false | false | 54,400 | java | /**
* 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.openejb.config;
import junit.framework.TestCase;
import org.apache.openejb.Core;
import org.apache.openejb.OpenEJBException;
import org.apache.openejb.assembler.classic.AppInfo;
import org.apache.openejb.assembler.classic.Assembler;
import org.apache.openejb.assembler.classic.OpenEjbConfiguration;
import org.apache.openejb.assembler.classic.PersistenceUnitInfo;
import org.apache.openejb.assembler.classic.ProxyFactoryInfo;
import org.apache.openejb.assembler.classic.ResourceInfo;
import org.apache.openejb.assembler.classic.SecurityServiceInfo;
import org.apache.openejb.assembler.classic.TransactionServiceInfo;
import org.apache.openejb.config.sys.Resource;
import org.apache.openejb.jee.WebApp;
import org.apache.openejb.jee.jpa.unit.Persistence;
import org.apache.openejb.jee.jpa.unit.PersistenceUnit;
import org.apache.openejb.loader.SystemInstance;
import org.apache.openejb.monitoring.LocalMBeanServer;
import org.apache.openjpa.persistence.osgi.BundleUtils;
import javax.naming.NamingException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Properties;
import java.util.List;
import java.util.logging.Logger;
/**
* @version $Revision: 1415902 $ $Date: 2012-12-01 01:09:26 +0000 (Sat, 01 Dec 2012) $
*/
public class AutoConfigPersistenceUnitsTest extends TestCase {
static {
Core.warmup();
}
private ConfigurationFactory config;
private Assembler assembler;
private List<ResourceInfo> resources;
protected void setUp() throws Exception {
System.setProperty(LocalMBeanServer.OPENEJB_JMX_ACTIVE, "false");
config = new ConfigurationFactory();
assembler = new Assembler();
assembler.createProxyFactory(config.configureService(ProxyFactoryInfo.class));
assembler.createTransactionManager(config.configureService(TransactionServiceInfo.class));
assembler.createSecurityService(config.configureService(SecurityServiceInfo.class));
OpenEjbConfiguration configuration = SystemInstance.get().getComponent(OpenEjbConfiguration.class);
resources = configuration.facilities.resources;
}
@Override
public void tearDown() {
System.getProperties().remove(LocalMBeanServer.OPENEJB_JMX_ACTIVE);
}
/**
* Existing data source "Orange", jta managed
* Existing data source "OrangeUnmanaged", not jta managed
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit">
* <jta-data-source>Orange</jta-data-source>
* <non-jta-data-source>OrangeUnamanged</non-jta-data-source>
* </persistence-unit>
*
* This is the happy path.
*
* @throws Exception
*/
public void test() throws Exception {
ResourceInfo jta = addDataSource("Orange", OrangeDriver.class, "jdbc:orange:some:stuff", true);
ResourceInfo nonJta = addDataSource("OrangeUnmanaged", OrangeDriver.class, "jdbc:orange:some:stuff", false);
assertSame(jta, resources.get(0));
assertSame(nonJta, resources.get(1));
PersistenceUnitInfo unitInfo = addPersistenceUnit("orange-unit", "orange", "orangeUnmanaged");
assertNotNull(unitInfo);
assertEquals(jta.id, unitInfo.jtaDataSource);
assertEquals(nonJta.id, unitInfo.nonJtaDataSource);
}
/**
* Existing data source "Orange", jta managed
* Existing data source "OrangeUnmanaged", not jta managed
* Existing data source "Lime", jta managed
* Existing data source "LimeUnmanaged", not jta managed
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit">
* <jta-data-source>Orange</jta-data-source>
* <non-jta-data-source>OrangeUnmanaged</non-jta-data-source>
* </persistence-unit>
* <persistence-unit name="lime-unit">
* <jta-data-source>Lime</jta-data-source>
* <non-jta-data-source>LimeUnmanaged</non-jta-data-source>
* </persistence-unit>
*
* This is the happy path.
*
* @throws Exception
*/
public void testMultiple() throws Exception {
ResourceInfo orangeJta = addDataSource("Orange", OrangeDriver.class, "jdbc:orange:some:stuff", true);
ResourceInfo orangeNonJta = addDataSource("OrangeUnmanaged", OrangeDriver.class, "jdbc:orange:some:stuff", false);
ResourceInfo limeJta = addDataSource("Lime", LimeDriver.class, "jdbc:lime:some:stuff", true);
ResourceInfo limeNonJta = addDataSource("LimeUnmanaged", LimeDriver.class, "jdbc:lime:some:stuff", false);
assertSame(orangeJta, resources.get(0));
assertSame(orangeNonJta, resources.get(1));
assertSame(limeJta, resources.get(2));
assertSame(limeNonJta, resources.get(3));
PersistenceUnit unit1 = new PersistenceUnit("orange-unit");
unit1.setJtaDataSource("Orange");
unit1.setNonJtaDataSource("OrangeUnmanaged");
PersistenceUnit unit2 = new PersistenceUnit("lime-unit");
unit2.setJtaDataSource("Lime");
unit2.setNonJtaDataSource("LimeUnmanaged");
AppModule app = new AppModule(this.getClass().getClassLoader(), "test-app");
app.addPersistenceModule(new PersistenceModule("root", new Persistence(unit1, unit2)));
// Create app
AppInfo appInfo = config.configureApplication(app);
assembler.createApplication(appInfo);
// Check results
PersistenceUnitInfo orangeUnit = appInfo.persistenceUnits.get(0);
PersistenceUnitInfo limeUnit = appInfo.persistenceUnits.get(1);
assertNotNull(orangeUnit);
assertEquals(orangeJta.id, orangeUnit.jtaDataSource);
assertEquals(orangeNonJta.id, orangeUnit.nonJtaDataSource);
assertNotNull(limeUnit);
assertEquals(limeJta.id, limeUnit.jtaDataSource);
assertEquals(limeNonJta.id, limeUnit.nonJtaDataSource);
}
/**
* Existing data source "orange-unit", not controlled by us
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit" />
*
* The orange-unit app should automatically use orange-unit data source and the non-jta-datasource should be null
*
* @throws Exception
*/
public void testFromUnitNameThirdParty() throws Exception {
ResourceInfo supplied = addDataSource("orange-unit", OrangeDriver.class, "jdbc:orange:some:stuff", null);
assertSame(supplied, resources.get(0));
PersistenceUnitInfo unitInfo = addPersistenceUnit("orange-unit", null, null);
assertNotNull(unitInfo);
//Check results
assertEquals(supplied.id, unitInfo.jtaDataSource);
assertNull(unitInfo.nonJtaDataSource);
}
/**
* Existing data source "orange-unit", jta-managed
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit" />
*
* The orange-unit app should automatically use orange-unit data source and create a new non-JtaManaged datasource
*
* @throws Exception
*/
public void testFromUnitNameJta() throws Exception {
ResourceInfo supplied = addDataSource("orange-unit", OrangeDriver.class, "jdbc:orange:some:stuff", true);
assertSame(supplied, resources.get(0));
PersistenceUnitInfo unitInfo = addPersistenceUnit("orange-unit", null, null);
assertNotNull(unitInfo);
// Check results
ResourceInfo generated = resources.get(1);
assertEquals(supplied.id + "NonJta", generated.id);
assertEquals(supplied.service, generated.service);
assertEquals(supplied.className, generated.className);
assertEquals(supplied.properties.get("JdbcDriver"), generated.properties.get("JdbcDriver"));
assertEquals(supplied.properties.get("JdbcUrl"), generated.properties.get("JdbcUrl"));
assertEquals("false", generated.properties.get("JtaManaged"));
}
/**
* Existing data source "orange-unit", non-jta-managed
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit" />
*
* The orange-unit app should automatically use orange-unit data source and create a new JtaManaged datasource
*
* @throws Exception
*/
public void testFromUnitNameNonJta() throws Exception {
ResourceInfo supplied = addDataSource("orange-unit", OrangeDriver.class, "jdbc:orange:some:stuff", false);
assertSame(supplied, resources.get(0));
PersistenceUnitInfo unitInfo = addPersistenceUnit("orange-unit", null, null);
assertNotNull(unitInfo);
// Check results
ResourceInfo generated = resources.get(1);
assertEquals(supplied.id + "Jta", generated.id);
assertEquals(supplied.service, generated.service);
assertEquals(supplied.className, generated.className);
assertEquals(supplied.properties.get("JdbcDriver"), generated.properties.get("JdbcDriver"));
assertEquals(supplied.properties.get("JdbcUrl"), generated.properties.get("JdbcUrl"));
assertEquals("true", generated.properties.get("JtaManaged"));
}
/**
* Existing data source "orange-id", not controlled by us
*
* Application contains a web module with id "orange-id"
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit" />
*
* The orange-unit app should automatically use orange-id data source and the non-jta-datasource should be null
*
* @throws Exception
*/
public void testFromWebAppIdThirdParty() throws Exception {
ResourceInfo supplied = addDataSource("orange-id", OrangeDriver.class, "jdbc:orange-web:some:stuff", null);
assertSame(supplied, resources.get(0));
PersistenceUnit persistenceUnit = new PersistenceUnit("orange-unit");
ClassLoader cl = this.getClass().getClassLoader();
AppModule app = new AppModule(cl, "orange-app");
app.addPersistenceModule(new PersistenceModule("root", new Persistence(persistenceUnit)));
WebApp webApp = new WebApp();
webApp.setMetadataComplete(true);
app.getWebModules().add(new WebModule(webApp, "orange-web", cl, null, "orange-id"));
// Create app
AppInfo appInfo = config.configureApplication(app);
assembler.createApplication(appInfo);
PersistenceUnitInfo unitInfo = appInfo.persistenceUnits.get(0);
//Check results
assertEquals(supplied.id, unitInfo.jtaDataSource);
assertNull(unitInfo.nonJtaDataSource);
}
/**
* Existing data source "orange-web", jta managed
*
* Application contains a web module with id "orange-id"
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit" />
*
* The orange-unit app should automatically use orange-id data source and create a new non-JtaManaged datasource
*
* @throws Exception
*/
public void testFromWebAppIdJta() throws Exception {
ResourceInfo supplied = addDataSource("orange-id", OrangeDriver.class, "jdbc:orange-web:some:stuff", true);
assertSame(supplied, resources.get(0));
PersistenceUnit persistenceUnit = new PersistenceUnit("orange-unit");
ClassLoader cl = this.getClass().getClassLoader();
AppModule app = new AppModule(cl, "orange-app");
app.addPersistenceModule(new PersistenceModule("root", new Persistence(persistenceUnit)));
WebApp webApp = new WebApp();
webApp.setMetadataComplete(true);
app.getWebModules().add(new WebModule(webApp, "orange-web", cl, "war", "orange-id"));
// Create app
AppInfo appInfo = config.configureApplication(app);
assembler.createApplication(appInfo);
// Check results
ResourceInfo generated = resources.get(1);
assertEquals(supplied.id + "NonJta", generated.id);
assertEquals(supplied.service, generated.service);
assertEquals(supplied.className, generated.className);
assertEquals(supplied.properties.get("JdbcDriver"), generated.properties.get("JdbcDriver"));
assertEquals(supplied.properties.get("JdbcUrl"), generated.properties.get("JdbcUrl"));
assertEquals("false", generated.properties.get("JtaManaged"));
}
/**
* Existing data source "orange-id", non-jta managed
*
* Application contains a web module with id "orange-id"
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit" />
*
* The orange-unit app should automatically use orange-id data source and create a new non-JtaManaged datasource
*
* @throws Exception
*/
public void testFromWebAppIdNonJta() throws Exception {
ResourceInfo supplied = addDataSource("orange-id", OrangeDriver.class, "jdbc:orange-web:some:stuff", false);
assertSame(supplied, resources.get(0));
PersistenceUnit persistenceUnit = new PersistenceUnit("orange-unit");
ClassLoader cl = this.getClass().getClassLoader();
AppModule app = new AppModule(cl, "orange-app");
app.addPersistenceModule(new PersistenceModule("root", new Persistence(persistenceUnit)));
WebApp webApp = new WebApp();
webApp.setMetadataComplete(true);
app.getWebModules().add(new WebModule(webApp, "orange-web", cl, "war", "orange-id"));
// Create app
AppInfo appInfo = config.configureApplication(app);
assembler.createApplication(appInfo);
// Check results
ResourceInfo generated = resources.get(1);
assertEquals(supplied.id + "Jta", generated.id);
assertEquals(supplied.service, generated.service);
assertEquals(supplied.className, generated.className);
assertEquals(supplied.properties.get("JdbcDriver"), generated.properties.get("JdbcDriver"));
assertEquals(supplied.properties.get("JdbcUrl"), generated.properties.get("JdbcUrl"));
assertEquals("true", generated.properties.get("JtaManaged"));
}
/**
* Existing data source "orange-web", not controlled by us
*
* Application contains a web module with root context path as "orange-web"
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit" />
*
* The orange-unit app should automatically use orange-web data source and the non-jta-datasource should be null
*
* @throws Exception
*/
public void testFromWebAppContextThirdParty() throws Exception {
ResourceInfo supplied = addDataSource("orange-web", OrangeDriver.class, "jdbc:orange-web:some:stuff", null);
assertSame(supplied, resources.get(0));
PersistenceUnit persistenceUnit = new PersistenceUnit("orange-unit");
ClassLoader cl = this.getClass().getClassLoader();
AppModule app = new AppModule(cl, "orange-app");
app.addPersistenceModule(new PersistenceModule("root", new Persistence(persistenceUnit)));
WebApp webApp = new WebApp();
webApp.setMetadataComplete(true);
app.getWebModules().add(new WebModule(webApp, "orange-web", cl, "war", "orange-web"));
// Create app
AppInfo appInfo = config.configureApplication(app);
assembler.createApplication(appInfo);
PersistenceUnitInfo unitInfo = appInfo.persistenceUnits.get(0);
//Check results
assertEquals(supplied.id, unitInfo.jtaDataSource);
assertNull(unitInfo.nonJtaDataSource);
}
/**
* Existing data source "orange-web", jta managed
*
* Application contains a web module with root context path as "orange-web"
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit" />
*
* The orange-unit app should automatically use orange-web data source and create a new non-JtaManaged datasource
*
* @throws Exception
*/
public void testFromWebAppContextJta() throws Exception {
ResourceInfo supplied = addDataSource("orange-web", OrangeDriver.class, "jdbc:orange-web:some:stuff", true);
assertSame(supplied, resources.get(0));
PersistenceUnit persistenceUnit = new PersistenceUnit("orange-unit");
ClassLoader cl = this.getClass().getClassLoader();
AppModule app = new AppModule(cl, "orange-app");
app.addPersistenceModule(new PersistenceModule("root", new Persistence(persistenceUnit)));
WebApp webApp = new WebApp();
webApp.setMetadataComplete(true);
app.getWebModules().add(new WebModule(webApp, "orange-web", cl, "war", "orange-web"));
// Create app
AppInfo appInfo = config.configureApplication(app);
assembler.createApplication(appInfo);
// Check results
ResourceInfo generated = resources.get(1);
assertEquals(supplied.id + "NonJta", generated.id);
assertEquals(supplied.service, generated.service);
assertEquals(supplied.className, generated.className);
assertEquals(supplied.properties.get("JdbcDriver"), generated.properties.get("JdbcDriver"));
assertEquals(supplied.properties.get("JdbcUrl"), generated.properties.get("JdbcUrl"));
assertEquals("false", generated.properties.get("JtaManaged"));
}
/**
* Existing data source "orange-web", non-jta managed
*
* Application contains a web module with root context path as "orange-web"
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit" />
*
* The orange-unit app should automatically use orange-web data source and create a new non-JtaManaged datasource
*
* @throws Exception
*/
public void testFromWebAppContextNonJta() throws Exception {
ResourceInfo supplied = addDataSource("orange-web", OrangeDriver.class, "jdbc:orange-web:some:stuff", false);
assertSame(supplied, resources.get(0));
PersistenceUnit persistenceUnit = new PersistenceUnit("orange-unit");
ClassLoader cl = this.getClass().getClassLoader();
AppModule app = new AppModule(cl, "orange-app");
app.addPersistenceModule(new PersistenceModule("root", new Persistence(persistenceUnit)));
WebApp webApp = new WebApp();
webApp.setMetadataComplete(true);
app.getWebModules().add(new WebModule(webApp, "orange-web", cl, "war", "orange-web"));
// Create app
AppInfo appInfo = config.configureApplication(app);
assembler.createApplication(appInfo);
// Check results
ResourceInfo generated = resources.get(1);
assertEquals(supplied.id + "Jta", generated.id);
assertEquals(supplied.service, generated.service);
assertEquals(supplied.className, generated.className);
assertEquals(supplied.properties.get("JdbcDriver"), generated.properties.get("JdbcDriver"));
assertEquals(supplied.properties.get("JdbcUrl"), generated.properties.get("JdbcUrl"));
assertEquals("true", generated.properties.get("JtaManaged"));
}
/**
* Existing data source "orange-unit-app", not controlled by us
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit" />
*
* The app module id is orange-unit-app. The jta data source should be orange-unit-app and the non-jta-data-source should be null
*
* @throws Exception
*/
public void testFromAppIdThirdParty() throws Exception {
ResourceInfo supplied = addDataSource("orange-unit-app", OrangeDriver.class, "jdbc:orange:some:stuff", null);
assertSame(supplied, resources.get(0));
PersistenceUnitInfo unitInfo = addPersistenceUnit("orange-unit", null, null);
assertNotNull(unitInfo);
//Check results
assertEquals(supplied.id, unitInfo.jtaDataSource);
assertNull(unitInfo.nonJtaDataSource);
}
/**
* Existing data source "orange-unit-app", jta-managed
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit" />
*
* The app module id is orange-unit-app. Use orange-unit-app data source and create a new non-JtaManaged datasource
*
* @throws Exception
*/
public void testFromAppIdJta() throws Exception {
ResourceInfo supplied = addDataSource("orange-unit-app", OrangeDriver.class, "jdbc:orange:some:stuff", true);
assertSame(supplied, resources.get(0));
PersistenceUnitInfo unitInfo = addPersistenceUnit("orange-unit", null, null);
assertNotNull(unitInfo);
// Check results
ResourceInfo generated = resources.get(1);
assertEquals(supplied.id + "NonJta", generated.id);
assertEquals(supplied.service, generated.service);
assertEquals(supplied.className, generated.className);
assertEquals(supplied.properties.get("JdbcDriver"), generated.properties.get("JdbcDriver"));
assertEquals(supplied.properties.get("JdbcUrl"), generated.properties.get("JdbcUrl"));
assertEquals("false", generated.properties.get("JtaManaged"));
}
/**
* Existing data source "orange-unit-app", non-jta-managed
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit" />
*
* The app module id is orange-unit-app. Use orange-unit-app data source and create a new JtaManaged datasource
*
* @throws Exception
*/
public void testFromAppIdNonJta() throws Exception {
ResourceInfo supplied = addDataSource("orange-unit-app", OrangeDriver.class, "jdbc:orange:some:stuff", false);
assertSame(supplied, resources.get(0));
PersistenceUnitInfo unitInfo = addPersistenceUnit("orange-unit", null, null);
assertNotNull(unitInfo);
// Check results
ResourceInfo generated = resources.get(1);
assertEquals(supplied.id + "Jta", generated.id);
assertEquals(supplied.service, generated.service);
assertEquals(supplied.className, generated.className);
assertEquals(supplied.properties.get("JdbcDriver"), generated.properties.get("JdbcDriver"));
assertEquals(supplied.properties.get("JdbcUrl"), generated.properties.get("JdbcUrl"));
assertEquals("true", generated.properties.get("JtaManaged"));
}
/**
* Existing data source "Orange", not controlled by us
* Existing data source "OrangeUnmanaged", also not controlled by us
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit">
* <jta-data-source>Orange</jta-data-source>
* <non-jta-data-source>OrangeUnamanged</non-jta-data-source>
* </persistence-unit>
*
* @throws Exception
*/
public void testThirdPartyDataSources() throws Exception {
ResourceInfo jta = addDataSource("Orange", OrangeDriver.class, "jdbc:orange:some:stuff", null);
ResourceInfo nonJta = addDataSource("OrangeUnmanaged", OrangeDriver.class, "jdbc:orange:some:stuff", null);
assertSame(jta, resources.get(0));
assertSame(nonJta, resources.get(1));
PersistenceUnitInfo unitInfo = addPersistenceUnit("orange-unit", "orange", "orangeUnmanaged");
assertNotNull(unitInfo);
assertEquals(jta.id, unitInfo.jtaDataSource);
assertEquals(nonJta.id, unitInfo.nonJtaDataSource);
}
/**
* Existing data source "Orange", not controlled by us
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit">
* <jta-data-source>Orange</jta-data-source>
* </persistence-unit>
*
* Here we should just let them try and get by with
* just the one data source.
*
* @throws Exception
*/
public void testThirdPartyDataSources2() throws Exception {
ResourceInfo dataSource = addDataSource("Orange", OrangeDriver.class, "jdbc:orange:some:stuff", null);
assertSame(dataSource, resources.get(0));
PersistenceUnitInfo unitInfo = addPersistenceUnit("orange-unit", "orange", null);
assertNotNull(unitInfo);
assertEquals(dataSource.id, unitInfo.jtaDataSource);
assertNull(unitInfo.nonJtaDataSource);
}
/**
* Existing data source "Orange", not controlled by us
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit">
* <non-jta-data-source>Orange</non-jta-data-source>
* </persistence-unit>
*
* Here we should just let them try and get by with
* just the one data source.
*
* @throws Exception
*/
public void testThirdPartyDataSources3() throws Exception {
ResourceInfo dataSource = addDataSource("Orange", OrangeDriver.class, "jdbc:orange:some:stuff", null);
assertSame(dataSource, resources.get(0));
PersistenceUnitInfo unitInfo = addPersistenceUnit("orange-unit", null, "orange");
assertNotNull(unitInfo);
assertNull(unitInfo.jtaDataSource);
assertEquals(dataSource.id, unitInfo.nonJtaDataSource);
}
/**
* Existing data source "Orange", not controlled by us
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit">
* <jta-data-source>Orange</jta-data-source>
* <non-jta-data-source>Orange</non-jta-data-source>
* </persistence-unit>
*
* Here we should just let them try and get by with
* both jta and non-jta references pointed at the same
* data source.
*
* @throws Exception
*/
public void testThirdPartyDataSources4() throws Exception {
ResourceInfo dataSource = addDataSource("Orange", OrangeDriver.class, "jdbc:orange:some:stuff", null);
assertSame(dataSource, resources.get(0));
PersistenceUnitInfo unitInfo = addPersistenceUnit("orange-unit", "orange", "orange");
assertNotNull(unitInfo);
assertEquals(dataSource.id, unitInfo.jtaDataSource);
assertEquals(dataSource.id, unitInfo.nonJtaDataSource);
}
/**
* Existing data source "Orange", jta managed
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit">
* <jta-data-source>Orange</jta-data-source>
* <non-jta-data-source>Orange</non-jta-data-source>
* </persistence-unit>
*
* They used the same data source for both the
* jta-data-source and non-jta-data-source and we
* can determine the data source will not work as
* a non-jta-data-source
*
* We should generate the missing data source for them
* based on the one they supplied.
*
* @throws Exception
*/
public void testSameDataSourceForBoth1() throws Exception {
ResourceInfo supplied = addDataSource("Orange", OrangeDriver.class, "jdbc:orange:some:stuff", true);
assertSame(supplied, resources.get(0));
PersistenceUnitInfo unitInfo = addPersistenceUnit("orange-unit", "orange", "orange");
assertNotNull(unitInfo);
ResourceInfo generated = resources.get(1);
assertEquals(supplied.id, unitInfo.jtaDataSource);
assertEquals(generated.id, unitInfo.nonJtaDataSource);
assertNotNull(generated);
assertEquals(supplied.id + "NonJta", generated.id);
assertEquals(supplied.service, generated.service);
assertEquals(supplied.className, generated.className);
assertEquals(supplied.properties.get("JdbcDriver"), generated.properties.get("JdbcDriver"));
assertEquals(supplied.properties.get("JdbcUrl"), generated.properties.get("JdbcUrl"));
assertEquals("false", generated.properties.get("JtaManaged"));
}
/**
* Existing data source "Orange", not jta managed
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit">
* <jta-data-source>Orange</jta-data-source>
* <non-jta-data-source>Orange</non-jta-data-source>
* </persistence-unit>
*
* They used the same data source for both the
* jta-data-source and non-jta-data-source and we
* can determine the data source will not work as
* a jta-data-source
*
* We should generate the missing data source for them
* based on the one they supplied.
*
* @throws Exception
*/
public void testSameDataSourceForBoth2() throws Exception {
ResourceInfo supplied = addDataSource("Orange", OrangeDriver.class, "jdbc:orange:some:stuff", false);
assertSame(supplied, resources.get(0));
PersistenceUnitInfo unitInfo = addPersistenceUnit("orange-unit", "orange", "orange");
assertNotNull(unitInfo);
ResourceInfo generated = resources.get(1);
assertEquals(generated.id, unitInfo.jtaDataSource);
assertEquals(supplied.id, unitInfo.nonJtaDataSource);
assertNotNull(generated);
assertEquals(supplied.id + "Jta", generated.id);
assertEquals(supplied.service, generated.service);
assertEquals(supplied.className, generated.className);
assertEquals(supplied.properties.get("JdbcDriver"), generated.properties.get("JdbcDriver"));
assertEquals(supplied.properties.get("JdbcUrl"), generated.properties.get("JdbcUrl"));
assertEquals("true", generated.properties.get("JtaManaged"));
}
/**
* Existing data source "OrangeOne", jta managed
* Existing data source "OrangeTwo", not jta managed
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit">
* <jta-data-source>OrangeOne</jta-data-source>
* <non-jta-data-source>OrangeOne</non-jta-data-source>
* </persistence-unit>
*
* They used the same data source for both the
* jta-data-source and non-jta-data-source and we
* can determine the data source will not work as
* a non-jta-data-source
* BUT
* they have explicitly configured a data source
* that nearly matches the named datasource and
* would be identical to what we would auto-create
*
* @throws Exception
*/
public void testSameDataSourceForBoth3() throws Exception {
ResourceInfo jta = addDataSource("OrangeOne", OrangeDriver.class, "jdbc:orange:some:stuff", true);
ResourceInfo nonJta = addDataSource("OrangeTwo", OrangeDriver.class, "jdbc:orange:some:stuff", false);
assertSame(jta, resources.get(0));
assertSame(nonJta, resources.get(1));
PersistenceUnitInfo unitInfo = addPersistenceUnit("orange-unit", "orangeOne", "orangeOne");
assertNotNull(unitInfo);
assertEquals(jta.id, unitInfo.jtaDataSource);
assertEquals(nonJta.id, unitInfo.nonJtaDataSource);
}
/**
* Existing data source "OrangeOne", jta managed
* Existing data source "OrangeTwo", not jta managed
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit">
* <jta-data-source>OrangeTwo</jta-data-source>
* <non-jta-data-source>OrangeTwo</non-jta-data-source>
* </persistence-unit>
*
* They used the same data source for both the
* jta-data-source and non-jta-data-source and we
* can determine the data source will not work as
* a jta-data-source
* BUT
* they have explicitly configured a data source
* that nearly matches the named datasource and
* would be identical to what we would auto-create
*
* @throws Exception
*/
public void testSameDataSourceForBoth4() throws Exception {
ResourceInfo jta = addDataSource("OrangeOne", OrangeDriver.class, "jdbc:orange:some:stuff", true);
ResourceInfo nonJta = addDataSource("OrangeTwo", OrangeDriver.class, "jdbc:orange:some:stuff", false);
assertSame(jta, resources.get(0));
assertSame(nonJta, resources.get(1));
PersistenceUnitInfo unitInfo = addPersistenceUnit("orange-unit", "orangeTwo", "orangeTwo");
assertNotNull(unitInfo);
assertEquals(jta.id, unitInfo.jtaDataSource);
assertEquals(nonJta.id, unitInfo.nonJtaDataSource);
}
/**
* Existing data source "Orange", jta managed
* Existing data source "OrangeUnmanaged", not jta managed
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit">
* <jta-data-source>java:foo/bar/baz/Orange</jta-data-source>
* <non-jta-data-source>java:foo/bar/baz/OrangeUnamanged</non-jta-data-source>
* </persistence-unit>
*
* The datasources should be mapped correctly despite the
* vendor specific prefix.
*
* @throws Exception
*/
public void testShortName() throws Exception {
ResourceInfo jta = addDataSource("Orange", OrangeDriver.class, "jdbc:orange:some:stuff", true);
ResourceInfo nonJta = addDataSource("OrangeUnmanaged", OrangeDriver.class, "jdbc:orange:some:stuff", false);
assertSame(jta, resources.get(0));
assertSame(nonJta, resources.get(1));
PersistenceUnitInfo unitInfo = addPersistenceUnit("orange-unit", "java:foo/bar/baz/orange", "java:foo/bar/baz/orangeUnmanaged");
assertNotNull(unitInfo);
assertEquals(jta.id, unitInfo.jtaDataSource);
assertEquals(nonJta.id, unitInfo.nonJtaDataSource);
}
/**
* Existing data source "Orange", jta managed
* Existing data source "OrangeUnmanaged", not jta managed
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit">
* <jta-data-source>DoesNotExist</jta-data-source>
* <non-jta-data-source>AlsoDoesNotExist</non-jta-data-source>
* </persistence-unit>
*
* We should automatically hook them up to the configured
* datasources that do match
*
* @throws Exception
*/
public void testInvalidRefs() throws Exception {
ResourceInfo jta = addDataSource("Orange", OrangeDriver.class, "jdbc:orange:some:stuff", true);
ResourceInfo nonJta = addDataSource("OrangeUnmanaged", OrangeDriver.class, "jdbc:orange:some:stuff", false);
assertSame(jta, resources.get(0));
assertSame(nonJta, resources.get(1));
PersistenceUnitInfo unitInfo = addPersistenceUnit("orange-unit", "DoesNotExist", "AlsoDoesNotExist");
assertNotNull(unitInfo);
assertEquals(jta.id, unitInfo.jtaDataSource);
assertEquals(nonJta.id, unitInfo.nonJtaDataSource);
}
// ---
/**
* Existing data source "OrangeOne", not jta managed
* Existing data source "OrangeTwo", not jta managed
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit">
* <jta-data-source>OrangeOne</jta-data-source>
* <non-jta-data-source>OrangeTwo</non-jta-data-source>
* </persistence-unit>
*
* This configuration should be rejected
*
* @throws Exception
*/
public void testJtaRefToContrarilyConfiguredDataSource() throws Exception {
ResourceInfo nonJta1 = addDataSource("OrangeOne", OrangeDriver.class, "jdbc:orange:some:stuff", false);
ResourceInfo nonJta2 = addDataSource("OrangeTwo", OrangeDriver.class, "jdbc:orange:some:stuff", false);
assertSame(nonJta1, resources.get(0));
assertSame(nonJta2, resources.get(1));
try {
addPersistenceUnit("orange-unit", "orangeOne", "orangeTwo");
fail("Configuration should be rejected");
} catch (OpenEJBException e) {
// pass
}
}
/**
* Existing data source "OrangeOne", jta managed
* Existing data source "OrangeTwo", jta managed
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit">
* <jta-data-source>OrangeOne</jta-data-source>
* <non-jta-data-source>OrangeTwo</non-jta-data-source>
* </persistence-unit>
*
* This configuration should be rejected
*
* @throws Exception
*/
public void testNonJtaRefToContrarilyConfiguredDataSource() throws Exception {
ResourceInfo jta1 = addDataSource("OrangeOne", OrangeDriver.class, "jdbc:orange:some:stuff", true);
ResourceInfo jta2 = addDataSource("OrangeTwo", OrangeDriver.class, "jdbc:orange:some:stuff", true);
assertSame(jta1, resources.get(0));
assertSame(jta2, resources.get(1));
try {
addPersistenceUnit("orange-unit", "orangeOne", "orangeTwo");
fail("Configuration should be rejected");
} catch (OpenEJBException e) {
// pass
}
}
/**
* Existing data source "OrangeOne", not jta managed
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit">
* <jta-data-source>OrangeOne</jta-data-source>
* </persistence-unit>
*
* This configuration should be rejected
*
* @throws Exception
*/
public void testJtaRefToContrarilyConfiguredDataSource2() throws Exception {
ResourceInfo jta = addDataSource("OrangeOne", OrangeDriver.class, "jdbc:orange:some:stuff", false);
assertSame(jta, resources.get(0));
try {
addPersistenceUnit("orange-unit", "orangeOne", null);
fail("Configuration should be rejected");
} catch (OpenEJBException e) {
// pass
}
}
/**
* Existing data source "OrangeOne", jta managed
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit">
* <non-jta-data-source>OrangeOne</non-jta-data-source>
* </persistence-unit>
*
* This configuration should be rejected
*
* @throws Exception
*/
public void testNonJtaRefToContrarilyConfiguredDataSource2() throws Exception {
ResourceInfo jta = addDataSource("OrangeOne", OrangeDriver.class, "jdbc:orange:some:stuff", true);
assertSame(jta, resources.get(0));
try {
addPersistenceUnit("orange-unit", null, "orangeOne");
fail("Configuration should be rejected");
} catch (OpenEJBException e) {
// pass
}
}
// ---
/**
* Existing data source "Orange" not jta managed
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit">
* <non-jta-data-source>Orange</non-jta-data-source>
* </persistence-unit>
*
* We should generate a <jta-data-source> based on
* the <non-jta-data-source>
*
* @throws Exception
*/
public void testMissingJtaDataSource() throws Exception {
ResourceInfo supplied = addDataSource("Orange", OrangeDriver.class, "jdbc:orange:some:stuff", false);
assertSame(supplied, resources.get(0));
PersistenceUnitInfo unitInfo = addPersistenceUnit("orange-unit", null, "orange");
assertNotNull(unitInfo);
ResourceInfo generated = resources.get(1);
assertEquals(supplied.id, unitInfo.nonJtaDataSource);
assertEquals(generated.id, unitInfo.jtaDataSource);
assertNotNull(generated);
assertEquals(supplied.id + "Jta", generated.id);
assertEquals(supplied.service, generated.service);
assertEquals(supplied.className, generated.className);
assertEquals(supplied.properties.get("JdbcDriver"), generated.properties.get("JdbcDriver"));
assertEquals(supplied.properties.get("JdbcUrl"), generated.properties.get("JdbcUrl"));
assertEquals("true", generated.properties.get("JtaManaged"));
}
/**
* Existing data source "Orange" jta managed
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit">
* <jta-data-source>Orange</jta-data-source>
* </persistence-unit>
*
* We should generate a <non-jta-data-source> based on
* the <jta-data-source>
*
* @throws Exception
*/
public void testMissingNonJtaDataSource() throws Exception {
ResourceInfo supplied = addDataSource("Orange", OrangeDriver.class, "jdbc:orange:some:stuff", true);
assertSame(supplied, resources.get(0));
PersistenceUnitInfo unitInfo = addPersistenceUnit("orange-unit", "orange", null);
assertNotNull(unitInfo);
ResourceInfo generated = resources.get(1);
assertEquals(supplied.id, unitInfo.jtaDataSource);
assertEquals(generated.id, unitInfo.nonJtaDataSource);
assertEquals(supplied.id + "NonJta", generated.id);
assertEquals(supplied.service, generated.service);
assertEquals(supplied.className, generated.className);
assertEquals(supplied.properties.get("JdbcDriver"), generated.properties.get("JdbcDriver"));
assertEquals(supplied.properties.get("JdbcUrl"), generated.properties.get("JdbcUrl"));
assertEquals("false", generated.properties.get("JtaManaged"));
}
// ---
/**
* Existing data source "Orange", not jta managed
* Existing data source "Lime", jta managed
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit">
* <non-jta-data-source>Orange</non-jta-data-source>
* </persistence-unit>
*
* We should generate a <jta-data-source> based on
* the <non-jta-data-source>. We should not select
* the Lime datasource which is for a different database.
*
* @throws Exception
*/
public void testInvalidOptionsJta() throws Exception {
ResourceInfo supplied = addDataSource("Orange", OrangeDriver.class, "jdbc:orange:some:stuff", false);
ResourceInfo badMatch = addDataSource("Lime", LimeDriver.class, "jdbc:lime:some:stuff", true);
assertSame(supplied, resources.get(0));
assertSame(badMatch, resources.get(1));
PersistenceUnitInfo unitInfo = addPersistenceUnit("orange-unit", null, "orange");
assertNotNull(unitInfo);
ResourceInfo generated = resources.get(2);
assertEquals(generated.id, unitInfo.jtaDataSource);
assertEquals(supplied.id, unitInfo.nonJtaDataSource);
assertEquals(supplied.id + "Jta", generated.id);
assertEquals(supplied.service, generated.service);
assertEquals(supplied.className, generated.className);
assertEquals(supplied.properties.get("JdbcDriver"), generated.properties.get("JdbcDriver"));
assertEquals(supplied.properties.get("JdbcUrl"), generated.properties.get("JdbcUrl"));
assertEquals("true", generated.properties.get("JtaManaged"));
}
/**
* Existing data source "Orange", jta managed
* Existing data source "Lime", non jta managed
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit">
* <jta-data-source>Orange</jta-data-source>
* </persistence-unit>
*
* We should generate a <non-jta-data-source> based on
* the <jta-data-source>. We should not select the
* Lime datasource which is for a different database.
*
* @throws Exception
*/
public void testInvalidOptionsNonJta() throws Exception {
ResourceInfo supplied = addDataSource("Orange", OrangeDriver.class, "jdbc:orange:some:stuff", true);
ResourceInfo badMatch = addDataSource("Lime", LimeDriver.class, "jdbc:lime:some:stuff", false);
assertSame(supplied, resources.get(0));
assertSame(badMatch, resources.get(1));
PersistenceUnitInfo unitInfo = addPersistenceUnit("orange-unit", "orange", null);
assertNotNull(unitInfo);
ResourceInfo generated = resources.get(2);
assertEquals(supplied.id, unitInfo.jtaDataSource);
assertEquals(generated.id, unitInfo.nonJtaDataSource);
assertEquals(supplied.id + "NonJta", generated.id);
assertEquals(supplied.service, generated.service);
assertEquals(supplied.className, generated.className);
assertEquals(supplied.properties.get("JdbcDriver"), generated.properties.get("JdbcDriver"));
assertEquals(supplied.properties.get("JdbcUrl"), generated.properties.get("JdbcUrl"));
assertEquals("false", generated.properties.get("JtaManaged"));
}
// ---
/**
* Existing data source "Orange", not jta managed
* Existing data source "Lime", jta managed
* Existing data source "JtaOrange", jta managed
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit">
* <non-jta-data-source>Orange</non-jta-data-source>
* </persistence-unit>
*
* We should select the <jta-data-source> based on
* the closest match to the <non-jta-data-source>
*
* @throws Exception
*/
public void testPossiblyAmbiguousJtaOptions() throws Exception {
ResourceInfo supplied = addDataSource("Orange", OrangeDriver.class, "jdbc:orange:some:stuff", false);
ResourceInfo badMatch = addDataSource("Lime", LimeDriver.class, "jdbc:lime:some:stuff", true);
ResourceInfo goodMatch = addDataSource("JtaOrange", OrangeDriver.class, "jdbc:orange:some:stuff", true);
assertSame(supplied, resources.get(0));
assertSame(badMatch, resources.get(1));
assertSame(goodMatch, resources.get(2));
PersistenceUnitInfo unitInfo = addPersistenceUnit("orange-unit", null, "orange");
assertNotNull(unitInfo);
assertEquals(goodMatch.id, unitInfo.jtaDataSource);
assertEquals(supplied.id, unitInfo.nonJtaDataSource);
}
/**
* Existing data source "Orange", jta managed
* Existing data source "Lime", not jta managed
* Existing data source "OrangeUnamanged", not jta managed
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit">
* <jta-data-source>Orange</jta-data-source>
* </persistence-unit>
*
* We should select the <non-jta-data-source> based on
* the closest match to the <jta-data-source>
*
* @throws Exception
*/
public void testPossiblyAmbiguousNonJtaOptions() throws Exception {
ResourceInfo supplied = addDataSource("Orange", OrangeDriver.class, "jdbc:orange:some:stuff", true);
ResourceInfo badMatch = addDataSource("Lime", LimeDriver.class, "jdbc:lime:some:stuff", false);
ResourceInfo goodMatch = addDataSource("OrangeUnmanaged", OrangeDriver.class, "jdbc:orange:some:stuff", false);
assertSame(supplied, resources.get(0));
assertSame(badMatch, resources.get(1));
assertSame(goodMatch, resources.get(2));
PersistenceUnitInfo unitInfo = addPersistenceUnit("orange-unit", "orange", null);
assertNotNull(unitInfo);
assertEquals(supplied.id, unitInfo.jtaDataSource);
assertEquals(goodMatch.id, unitInfo.nonJtaDataSource);
}
// ---
/**
* Existing data source "Orange", not jta managed
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit">
* </persistence-unit>
*
* The <non-jta-data-source> should be auto linked
* to the Orange data source
*
* We should generate a <jta-data-source> based on
* the <non-jta-data-source>
*
* @throws Exception
*/
public void testEmptyUnitOneAvailableNonJtaDataSource() throws Exception {
ResourceInfo supplied = addDataSource("Orange", OrangeDriver.class, "jdbc:orange:some:stuff", false);
assertSame(supplied, resources.get(0));
PersistenceUnitInfo unitInfo = addPersistenceUnit("orange-unit", null, null);
assertNotNull(unitInfo);
ResourceInfo generated = resources.get(1);
assertEquals(generated.id, unitInfo.jtaDataSource);
assertEquals(supplied.id, unitInfo.nonJtaDataSource);
assertEquals(supplied.id + "Jta", generated.id);
assertEquals(supplied.service, generated.service);
assertEquals(supplied.className, generated.className);
assertEquals(supplied.properties.get("JdbcDriver"), generated.properties.get("JdbcDriver"));
assertEquals(supplied.properties.get("JdbcUrl"), generated.properties.get("JdbcUrl"));
assertEquals("true", generated.properties.get("JtaManaged"));
}
/**
* Existing data source "Orange", jta managed
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit">
* </persistence-unit>
*
* The <jta-data-source> should be auto linked
* to the Orange data source
*
* We should generate a <non-jta-data-source> based on
* the <jta-data-source>
*
* @throws Exception
*/
public void testEmptyUnitOneAvailableJtaDataSource() throws Exception {
ResourceInfo supplied = addDataSource("Orange", OrangeDriver.class, "jdbc:orange:some:stuff", true);
assertSame(supplied, resources.get(0));
PersistenceUnitInfo unitInfo = addPersistenceUnit("orange-unit", null, null);
assertNotNull(unitInfo);
ResourceInfo generated = resources.get(1);
assertEquals(supplied.id, unitInfo.jtaDataSource);
assertEquals(generated.id, unitInfo.nonJtaDataSource);
assertEquals(supplied.id + "NonJta", generated.id);
assertEquals(supplied.service, generated.service);
assertEquals(supplied.className, generated.className);
assertEquals(supplied.properties.get("JdbcDriver"), generated.properties.get("JdbcDriver"));
assertEquals(supplied.properties.get("JdbcUrl"), generated.properties.get("JdbcUrl"));
assertEquals("false", generated.properties.get("JtaManaged"));
}
// ---
/**
* Existing data source "Orange", not jta managed
*
* Persistence xml like so:
*
* <persistence-unit name="orange-unit">
* </persistence-unit>
*
* A set of default data sources should be generated
*
* The <non-jta-data-source> should be auto linked
* to the Default JDBC Database data source
*
* The <jta-data-source> should be auto linked
* to the Default Unmanaged JDBC Database data source
*
* @throws Exception
*/
public void testEmptyUnitNoAvailableDataSources() throws Exception {
assertEquals(0, resources.size());
PersistenceUnitInfo unitInfo = addPersistenceUnit("orange-unit", null, null);
assertNotNull(unitInfo);
ResourceInfo jta = resources.get(0);
ResourceInfo nonJta = resources.get(1);
assertEquals("Default JDBC Database", jta.id);
assertEquals("Default Unmanaged JDBC Database", nonJta.id);
assertEquals(jta.id, unitInfo.jtaDataSource);
assertEquals(nonJta.id, unitInfo.nonJtaDataSource);
}
// --------------------------------------------------------------------------------------------
// Convenience methods
// --------------------------------------------------------------------------------------------
private PersistenceUnitInfo addPersistenceUnit(String unitName, String jtaDataSource, String nonJtaDataSource) throws OpenEJBException, IOException, NamingException {
PersistenceUnit unit = new PersistenceUnit(unitName);
unit.setJtaDataSource(jtaDataSource);
unit.setNonJtaDataSource(nonJtaDataSource);
AppModule app = new AppModule(this.getClass().getClassLoader(), unitName + "-app");
app.addPersistenceModule(new PersistenceModule("root", new Persistence(unit)));
// Create app
AppInfo appInfo = config.configureApplication(app);
assembler.createApplication(appInfo);
// Check results
return appInfo.persistenceUnits.get(0);
}
private ResourceInfo addDataSource(String id, Class driver, String url, Boolean managed) throws OpenEJBException {
Resource resource = new Resource(id, "DataSource");
resource.getProperties().put("JdbcDriver", driver.getName());
resource.getProperties().put("JdbcUrl", url);
resource.getProperties().put("JtaManaged", managed + " "); // space should be trimmed later, this verifies that.
ResourceInfo resourceInfo = config.configureService(resource, ResourceInfo.class);
if (managed == null){
// Strip out the JtaManaged property so we can mimic
// datasources that we don't control
resourceInfo.properties.remove("JtaManaged");
}
assembler.createResource(resourceInfo);
return resourceInfo;
}
public static class Driver implements java.sql.Driver {
public boolean acceptsURL(String url) throws SQLException {
return false;
}
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
return null;
}
public Connection connect(String url, Properties info) throws SQLException {
return null;
}
public int getMajorVersion() {
return 0;
}
public int getMinorVersion() {
return 0;
}
public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException {
return new DriverPropertyInfo[0];
}
public boolean jdbcCompliant() {
return false;
}
}
public static class OrangeDriver extends Driver {}
public static class LimeDriver extends Driver {}
}
| [
"kdchamil@gmail.com"
] | kdchamil@gmail.com |
224dc168fece54bbddcf8c01d73e51c0f532a967 | 0093c72c887e12e845ae488594e3d504c14e668c | /src/java_network/udp/Messenger.java | 69b3e375ca03be74714500340f0eb91ad0fd318c | [] | no_license | JaeJinBae/java_network | 034f402cac46dc5c86e43684f6069f38976e2dae | 288cda04c505dbb7aaa4a675b3253fc1ced15f8b | refs/heads/master | 2021-07-04T13:54:15.096231 | 2017-09-27T00:42:42 | 2017-09-27T00:42:42 | 104,831,012 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,439 | java | package java_network.udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import javax.swing.JTextArea;
public class Messenger extends Thread {
private DatagramSocket socket;
private DatagramPacket packet;
private JTextArea textArea;
private InetAddress address;
private int otherPort;
public Messenger(int myPort, int otherPort, String address){
try {
socket=new DatagramSocket(myPort);
this.address=InetAddress.getByName(address);
this.otherPort=otherPort;
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
public void setTextArea(JTextArea textArea) {
this.textArea = textArea;
}
@Override
public void run(){
while(true){
byte[] buf=new byte[255];
packet=new DatagramPacket(buf, buf.length);
try {
socket.receive(packet);
textArea.append("RECEIVED: "+new String(buf)+"\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void sendMessage(String msg){
byte[] buf=msg.getBytes();
DatagramPacket packet=new DatagramPacket(buf, buf.length, address, otherPort);
try {
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| [
"bjj7425@naver.com"
] | bjj7425@naver.com |
f968c75c73fd01c970bca114c8610faece96930d | 9a9f029447a6beefb0ad71d7a308a81520bbcf5e | /src/main/java/my/pro/acommunity/web/entitys/JSONResponse.java | 021ea9efb80af9bde8181473737e169d7874fabb | [] | no_license | oopnull/mycommunity | 1dd6e24785243d98c8d061925b1523361baea14c | c5edb7afff78c2cfe92cb5c1dded6bf4fd48e7e9 | refs/heads/master | 2022-09-14T19:30:20.014916 | 2020-03-13T13:31:24 | 2020-03-13T13:31:24 | 234,834,606 | 0 | 0 | null | 2022-09-01T23:21:48 | 2020-01-19T03:29:19 | TSQL | UTF-8 | Java | false | false | 920 | java | package my.pro.acommunity.web.entitys;
public class JSONResponse {
private int status;
private String desc;
private Object data;
public static JSONResponse success(Object data) {
JSONResponse response = new JSONResponse();
response.setStatus(1);
response.setData(data);
return response;
}
public static JSONResponse error(String desc) {
JSONResponse response = new JSONResponse();
response.setStatus(0);
response.setDesc(desc);
return response;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
@Override
public String toString() {
return "JSONResponse [status=" + status + ", desc=" + desc + ", data=" + data + "]";
}
}
| [
"1056096898@qq,com"
] | 1056096898@qq,com |
b43f137d99b79f306f56c10f76ba86e114174b46 | 6c8cf2d23c1fa9d235392a6dd35fc48b4ac2a728 | /app/src/main/java/com/phdlabs/sungwon/heyoo/structure/invite/InviteController.java | b675ff3422d9a8b2569607ae8fefc6aa788319a8 | [] | no_license | Sungzors/heyoo | 6e576890850c323f74f60c195d094cfcddf05bcf | 109574b8edf8e367857fd6c58586706592604296 | refs/heads/master | 2020-03-18T20:20:45.504262 | 2017-08-02T17:53:24 | 2017-08-02T17:53:24 | 135,209,137 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 485 | java | package com.phdlabs.sungwon.heyoo.structure.invite;
/**
* Created by SungWon on 7/5/2017.
*/
public class InviteController implements InviteContract.Controller {
private InviteContract.View mView;
InviteController(InviteContract.View view){
mView = view;
}
@Override
public void onStart() {
}
@Override
public void onResume() {
}
@Override
public void onPause() {
}
@Override
public void onStop() {
}
}
| [
"s1chun3636@gmail.com"
] | s1chun3636@gmail.com |
00736909979da6c2152f841ffba0071f9c810167 | 7a9fb4d0a6ab68ff918276e991050768fe182133 | /src/gcv/web/ParametersController.java | 286bc2df3cea4d0beedf26c707888c742ba60e1b | [] | no_license | NicolasDesnoust/GCV | 51ba37fd95afb299ea1a43c7f48e01f9a060b6cd | 3e9d2f95605532419fe1611ef9921864c0945962 | refs/heads/master | 2022-07-07T01:30:17.571846 | 2020-01-19T19:17:10 | 2020-01-19T19:17:10 | 220,734,591 | 0 | 0 | null | 2022-06-21T02:40:13 | 2019-11-10T03:10:12 | Java | UTF-8 | Java | false | false | 1,182 | java | package gcv.web;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import java.io.IOException;
import java.util.UUID;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.omnifaces.cdi.Cookie;
import org.omnifaces.util.Faces;
@Named("parametersController")
@SessionScoped
public class ParametersController implements Serializable {
private static final long serialVersionUID = 1L;
@Inject @Named("languageController")
private LanguageController languageController;
@Inject @Named("themeController")
private ThemeController themeController;
public void initParameters() {
//languageController.init();
//themeController.init();
}
public void applyChanges() throws IOException {
themeController.changeCurrentTheme();
languageController.changeCountryLocaleCode();
Faces.refresh();
}
}
| [
"desnoust.nicolas451@gmail.com"
] | desnoust.nicolas451@gmail.com |
59e7295f083098a293551caef258127a411c04be | c7c4fe651d178ad66be26d85455d0db1a9069ac0 | /src/main/java/others/ye/DocSequence.java | 3b7c34ac4584b455adaa80d05939dd1030ea3123 | [] | no_license | makeDoBetter/DemoList | 89b3103aa5a635dd33b429d4ea1355afbb0ac83a | 966342e9cd70531f6f1887d6f4430c77c12a5cbf | refs/heads/main | 2023-07-03T02:20:54.726203 | 2021-08-03T00:40:27 | 2021-08-03T00:40:27 | 360,359,360 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,129 | java | package others.ye;
import org.springframework.util.StringUtils;
/**
* @author mingbin
* @version 1.0
* @ClassName DocSequence
* @description
* @date 2019/6/11 16:20
* @since JDK 1.8
*/
@SequenceEntity
public class DocSequence {
private static final long serialVersionUID = 5243672831877794655L;
@SeqNameField
private String docType;
@SeqNextValField
private Long nextSeqNumber;
private String pk1Value;
private String pk2Value;
private String pk3Value;
private String pk4Value;
private String pk5Value;
private Long tenantId;
public DocSequence() {
}
public DocSequence(String docType, Long nextSeqNumber){
this.docType = docType;
this.nextSeqNumber = nextSeqNumber;
}
public DocSequence(String docType, String pk1Value, String pk2Value, String pk3Value, String pk4Value, String pk5Value) {
this.docType = docType;
if (StringUtils.isEmpty(pk1Value)) {
this.pk1Value = "-1";
} else {
this.pk1Value = pk1Value;
}
if (StringUtils.isEmpty(pk2Value)) {
this.pk2Value = "-1";
} else {
this.pk2Value = pk2Value;
}
if (StringUtils.isEmpty(pk3Value)) {
this.pk3Value = "-1";
} else {
this.pk3Value = pk3Value;
}
if (StringUtils.isEmpty(pk4Value)) {
this.pk4Value = "-1";
} else {
this.pk4Value = pk4Value;
}
if (StringUtils.isEmpty(pk5Value)) {
this.pk5Value = "-1";
} else {
this.pk5Value = pk5Value;
}
}
public String getDocType() {
return this.docType;
}
public Long getNextSeqNumber() {
return this.nextSeqNumber;
}
public String getPk1Value() {
return this.pk1Value;
}
public String getPk2Value() {
return this.pk2Value;
}
public String getPk3Value() {
return this.pk3Value;
}
public String getPk4Value() {
return this.pk4Value;
}
public String getPk5Value() {
return this.pk5Value;
}
public void setDocType(String docType) {
this.docType = docType == null ? null : docType.trim();
}
public void setNextSeqNumber(Long nextSeqNumber) {
this.nextSeqNumber = nextSeqNumber;
}
public void setPk1Value(String pk1Value) {
this.pk1Value = pk1Value == null ? null : pk1Value.trim();
}
public void setPk2Value(String pk2Value) {
this.pk2Value = pk2Value == null ? null : pk2Value.trim();
}
public void setPk3Value(String pk3Value) {
this.pk3Value = pk3Value == null ? null : pk3Value.trim();
}
public void setPk4Value(String pk4Value) {
this.pk4Value = pk4Value == null ? null : pk4Value.trim();
}
public void setPk5Value(String pk5Value) {
this.pk5Value = pk5Value == null ? null : pk5Value.trim();
}
public Long getTenantId() {
return tenantId;
}
public void setTenantId(Long tenantId) {
this.tenantId = tenantId;
}
}
| [
"jirong.feng@hand-china.com"
] | jirong.feng@hand-china.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.