repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
highj/highj
src/main/java/org/highj/data/structural/compose/ComposeFunctor.java
701
package org.highj.data.structural.compose; import org.derive4j.hkt.__; import org.highj.Hkt; import org.highj.data.structural.Compose; import org.highj.typeclass1.functor.Functor; import java.util.function.Function; public interface ComposeFunctor<F, G> extends Functor<__<__<Compose.µ, F>, G>> { Functor<F> getF(); Functor<G> getG(); default <A, B> __<F, __<G, B>> __map(Function<A, B> fn, __<F, __<G, A>> nestedA) { return getF().map(ga -> getG().map(fn, ga), nestedA); } @Override default <A, B> Compose<F, G, B> map(Function<A, B> fn, __<__<__<Compose.µ, F>, G>, A> nestedA) { return new Compose<>(__map(fn, Hkt.asCompose(nestedA).get())); } }
mit
Coregraph/Ayllu
JigSaw - AYPUY - CS/BESA3/BESA3-SRC/BPOBESA/src/BESA/Mobile/Agents/PostMan/State/PostManAgentStateBPO.java
1938
package BESA.Mobile.Agents.PostMan.State; import BESA.Kernel.Agent.StateBESA; import BESA.Mobile.ConnectionsAdministrator.CommunicationChannelDirectoryBPO; import BESA.Mobile.Exceptions.ExceptionBESAConnectionsDirectoryFailedBPO; import BESA.Mobile.Message.MessageBPO; /** * * @author Andrea Barraza */ public class PostManAgentStateBPO extends StateBESA { private String remoteContainerID; private MailBoxBPO mailbox_forWriting; private MailBoxBPO mailbox_forReading; public PostManAgentStateBPO(String remoteContainerID) { this.remoteContainerID = remoteContainerID; mailbox_forWriting = new MailBoxBPO(remoteContainerID, true); mailbox_forReading = new MailBoxBPO(remoteContainerID, false); } public synchronized void sendMessage(MessageBPO message) { mailbox_forWriting.sendMessage(message); } public synchronized void sendACK(MessageBPO message) { mailbox_forReading.sendMessage(message); } public synchronized void messageTimedOut(MessageBPO message) { mailbox_forWriting.messageTimedOut(message); mailbox_forReading.messageTimedOut(message); //REVISAR - ACK could time-out ??? } public synchronized void changeWriteCommunicationChannel() throws ExceptionBESAConnectionsDirectoryFailedBPO { mailbox_forWriting.setCommunicationChannel(CommunicationChannelDirectoryBPO.get().getWriteCommunicationChannel(remoteContainerID)); } public synchronized void changeReadCommunicationChannel() throws ExceptionBESAConnectionsDirectoryFailedBPO { mailbox_forReading.setCommunicationChannel(CommunicationChannelDirectoryBPO.get().getReadCommunicationChannel(remoteContainerID)); } public synchronized void shutdownMailBox() { mailbox_forWriting.shutDown(); mailbox_forReading.shutDown(); } public String getRemoteContainerID() { return remoteContainerID; } }
mit
gcnew/MP2
tests/re/agiledesign/mp2/test/FunctionTest.java
4843
package re.agiledesign.mp2.test; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Ignore; import org.junit.Test; import re.agiledesign.mp2.exception.ParsingException; public class FunctionTest extends MP2Test { @Test public void lambda0() { assertEval("x = (x) => return 1 + x return x(9)", Integer.valueOf(10)); } @Test public void lambda1() { assertEval("return !(x) => { return 1 + x }(9)", Boolean.FALSE); } @Test public void lambda2() { assertEval("return ((x) => return 1 + x)(9)", Integer.valueOf(10)); } @Test public void lambda3() { assertEval("return (() => return 10)(1, 2, 3)", Integer.valueOf(10)); } @Test public void immediate() { final String script = // /**/"test = () => return [ () => return (1 .. 2) ]\n" + /**/"return test()[0]().size()"; assertEval(script, Integer.valueOf(2)); } @Test public void nested() { final String script = // /**/"test = () => return () => return (1 .. 2)\n" + /**/"return test()().size()"; assertEval(script, Integer.valueOf(2)); } @Test public void closure() { final String script = // /**/"x = 2\n" + /**/"addClosure = (x, y) => {\n" + /**/" var z = 2;\n" + /**/" return () => return z + x + y + 1\n" + /**/"}\n" + /**/"return addClosure(3, 4)()"; assertEval(script, Integer.valueOf(10)); } @Test public void localClosure() { assertException("local l = 4; return () => return l + 5;", ParsingException.class); } @Test @Ignore public void functionClosure() { final String script = // /**/"var n = 5;\n" + /**/"function test() {\n" + /**/" return n + 4;\n" + /**/"}\n" + /**/"\n" + /**/"return test()"; assertEval(script, Integer.valueOf(9)); } @Test public void nestedClosure() { final String script = // /**/"var n = 5;\n" + /**/"local test = (() => return () => return n + 4)();\n" + /**/"\n" + /**/"return test()"; assertEval(script, Integer.valueOf(9)); } @Test public void globalClosure() { final String script = // /**/"function f(x, y) { return x + y }\n" + /**/"local test = () => return f(9, 1);\n" + /**/"f = (x, y) => return x * y;\n" + /**/"return test()"; assertEval(script, Integer.valueOf(9)); } @Test public void lambdaImplicitReturn() { assertEval("return (() => 1 + 9)()", Integer.valueOf(10)); assertEval("return (() => for (local i = 0; false;) {})()", null); } @Test @Ignore public void lambdaImplicitReturnDeclaration() { assertEval("return (() => local x = 4)()", null); } @Test public void higherOrder() { final String script = // /**/"addOne = (x) => return 1 + x\n" + /**/"higherOrder = (x, f) => return f(x)\n" + /**/"return higherOrder(9, addOne)"; assertEval(script, Integer.valueOf(10)); } @Test @SuppressWarnings("boxing") public void recursiveMap() { final String script = // /**/"car = (l) => return !l || l.isEmpty() ? null : l[0]\n" + /**/"cdr = (l) => return !l || (l.size() < 2) ? null : l[1 -> l.size()]\n" + /**/"cons = (x, l) => { local retval = [x]; retval.addAll(l); return retval }\n" + /**/"map = (l, f) => return !l && [] || cons(f(car(l)), map(cdr(l), f))\n" + /**/"mul2 = (x) => return x * 2\n" + /**/"return map([1 .. 3], mul2)"; assertEval(script, Arrays.asList(2, 4, 6)); } @Test @SuppressWarnings("boxing") public void recursiveMap2() { final String script = // /**/"car = (l) => return l === null ? null : l.first()\n" + /**/"cdr = (l) => return l === null ? null : l.rest()\n" + /**/"cons = (x, l) => return (x : l)\n" + /**/"tcl = (l) => return (null : l).rest()\n" + /**/"map = (l, f) => return l === null ? null : cons(f(car(l)), map(cdr(l), f))\n" + /**/"mul2 = (x) => return x * 2\n" + /**/"return map(tcl((1 .. 3)), mul2)"; assertEval(script, Arrays.asList(2, 4, 6)); } @Test @SuppressWarnings({ "unchecked", "boxing" }) public void filter() { final String script = // /**/"function filter(l, f) {\n" + /**/" local i, retval = []\n" + /**/"\n" + /**/" for (i = 0; i < l.size(); i = i + 1)\n" + /**/" if (f(l[i]))\n" + /**/" retval.add(l[i])\n" + /**/"\n" + /**/" return retval\n" + /**/"}\n" + /**/"\n" + /**/"l = [1, 10, 100, 1000]\n" + /**/"return [\n" + /**/" filter(l, (x) => return x > 0),\n" + /**/" filter(l, (x) => return x > 10),\n" + /**/" filter(l, (x) => return x > 1000)\n" + /**/"]"; final List<Integer> list0 = Arrays.asList(1, 10, 100, 1000); final List<Integer> list1 = Arrays.asList(100, 1000); final List<Integer> list2 = Collections.emptyList(); assertEval(script, Arrays.<List<Integer>> asList(list0, list1, list2)); } }
mit
deki/jira-plugin
src/main/java/hudson/plugins/jira/JiraCreateIssueNotifier.java
15894
package hudson.plugins.jira; import com.atlassian.jira.rest.client.api.domain.BasicComponent; import com.atlassian.jira.rest.client.api.domain.Component; import com.atlassian.jira.rest.client.api.domain.Issue; import com.atlassian.jira.rest.client.api.domain.Status; import com.google.common.base.Splitter; import com.google.common.collect.Lists; import hudson.EnvVars; import hudson.Extension; import hudson.Launcher; import hudson.Util; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.model.Result; import hudson.model.TaskListener; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Notifier; import hudson.tasks.Publisher; import hudson.util.FormValidation; import net.sf.json.JSONObject; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Logger; /** * When a build fails it creates jira issues. * Repeated failures does not create a new issue but update the existing issue until the issue is closed. * * @author Rupali Behera rupali@vertisinfotech.com */ public class JiraCreateIssueNotifier extends Notifier { private static final Logger LOG = Logger.getLogger(JiraCreateIssueNotifier.class.getName()); private String projectKey; private String testDescription; private String assignee; private String component; enum finishedStatuses { Closed, Done, Resolved } @DataBoundConstructor public JiraCreateIssueNotifier(String projectKey, String testDescription, String assignee, String component) { if (projectKey == null) throw new IllegalArgumentException("Project key cannot be null"); this.projectKey = projectKey; this.testDescription = testDescription; this.assignee = assignee; this.component = component; } public String getProjectKey() { return projectKey; } public void setProjectKey(String projectKey) { this.projectKey = projectKey; } public String getTestDescription() { return testDescription; } public void setTestDescription(String testDescription) { this.testDescription = testDescription; } public String getAssignee() { return assignee; } public void setAssignee(String assignee) { this.assignee = assignee; } public String getComponent() { return component; } public void setComponent(String component) { this.component = component; } @Override public BuildStepDescriptor<Publisher> getDescriptor() { return DESCRIPTOR; } @Extension public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl(); public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.BUILD; } @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { String jobDirPath = build.getProject().getBuildDir().getPath(); String filename = jobDirPath + File.separator + "issue.txt"; EnvVars vars = build.getEnvironment(TaskListener.NULL); Result currentBuildResult = build.getResult(); Result previousBuildResult = null; AbstractBuild<?, ?> previousBuild = build.getPreviousBuild(); if (previousBuild != null) { previousBuildResult = previousBuild.getResult(); } if (currentBuildResult != Result.ABORTED && previousBuild != null) { if (currentBuildResult == Result.FAILURE) { currentBuildResultFailure(build, listener, previousBuildResult, filename, vars); } if (currentBuildResult == Result.SUCCESS) { currentBuildResultSuccess(build, listener, previousBuildResult, filename, vars); } } return true; } /** * It creates a issue in the given project, with the given description, assignee,components and summary. * The created issue ID is saved to the file at "filename". * * @param build * @param filename * @return issue id * @throws IOException * @throws InterruptedException */ private Issue createJiraIssue(AbstractBuild<?, ?> build, String filename) throws IOException, InterruptedException { EnvVars vars = build.getEnvironment(TaskListener.NULL); JiraSession session = getJiraSession(build); String buildName = getBuildName(vars); String summary = String.format("Build %s failed", buildName); String description = String.format( "%s\n\nThe build %s has failed.\nFirst failed run: %s", (this.testDescription.equals("")) ? "No description is provided" : this.testDescription, buildName, getBuildDetailsString(vars) ); Iterable<String> components = Splitter.on(",").trimResults().omitEmptyStrings().split(component); Issue issue = session.createIssue(projectKey, description, assignee, components, summary); writeInFile(filename, issue); return issue; } /** * Returns the status of the issue. * * @param build * @param id * @return Status of the issue * @throws IOException */ private Status getStatus(AbstractBuild<?, ?> build, String id) throws IOException { JiraSession session = getJiraSession(build); Issue issue = session.getIssueByKey(id); return issue.getStatus(); } /** * Adds a comment to the existing issue. * * @param build * @param id * @param comment * @throws IOException */ private void addComment(AbstractBuild<?, ?> build, String id, String comment) throws IOException { JiraSession session = getJiraSession(build); session.addCommentWithoutConstrains(id, comment); } /** * Returns an Array of componets given by the user * * @param build * @param component * @return Array of component * @throws IOException */ private List<BasicComponent> getJiraComponents(AbstractBuild<?, ?> build, String component) throws IOException { if (Util.fixEmpty(component) == null) { return Collections.emptyList(); } JiraSession session = getJiraSession(build); List<Component> availableComponents = session.getComponents(projectKey); //converting the user input as a string array Splitter splitter = Splitter.on(",").trimResults().omitEmptyStrings(); List<String> inputComponents = Lists.newArrayList(splitter.split(component)); int numberOfComponents = inputComponents.size(); final List<BasicComponent> jiraComponents = new ArrayList<BasicComponent>(numberOfComponents); for (final BasicComponent availableComponent : availableComponents) { if (inputComponents.contains(availableComponent.getName())) { jiraComponents.add(availableComponent); } } return jiraComponents; } /** * Returns the issue id * * @param filename * @return * @throws IOException * @throws InterruptedException */ private String getIssue(String filename) throws IOException, InterruptedException { String issueId = ""; BufferedReader br = null; try { String issue; br = new BufferedReader(new FileReader(filename)); while ((issue = br.readLine()) != null) { issueId = issue; } return issueId; } catch (FileNotFoundException e) { return null; } finally { if (br != null) { br.close(); } } } JiraSite getSiteForProject(AbstractProject<?, ?> project) { return JiraSite.get(project); } /** * Returns the jira session. * * @param build * @return JiraSession * @throws IOException */ private JiraSession getJiraSession(AbstractBuild<?, ?> build) throws IOException { JiraSite site = getSiteForProject(build.getProject()); if (site == null) { throw new IllegalStateException("JIRA site needs to be configured in the project " + build.getFullDisplayName()); } JiraSession session = site.getSession(); if (session == null) { throw new IllegalStateException("Remote access for JIRA isn't configured in Jenkins"); } return session; } /** * @param filename */ private void deleteFile(String filename) { File file = new File(filename); if (file.exists() && !file.delete()) { LOG.warning("WARNING: couldn't delete file: " + filename); } } /** * write's the issue id in the file, which is stored in the Job's directory * * @param Filename * @param issue * @throws FileNotFoundException */ private void writeInFile(String Filename, Issue issue) throws FileNotFoundException { PrintWriter writer = new PrintWriter(Filename); writer.println(issue.getKey()); writer.close(); } /** * when the current build fails it checks for the previous build's result, * creates jira issue if the result was "success" and adds comment if the result was "fail". * It adds comment until the previously created issue is closed. */ private void currentBuildResultFailure(AbstractBuild<?, ?> build, BuildListener listener, Result previousBuildResult, String filename, EnvVars vars) throws InterruptedException, IOException { if (previousBuildResult == Result.FAILURE) { String comment = String.format("Build is still failing.\nFailed run: %s", getBuildDetailsString(vars)); //Get the issue-id which was filed when the previous built failed String issueId = getIssue(filename); if (issueId != null) { try { //The status of the issue which was filed when the previous build failed Status status = getStatus(build, issueId); // Issue Closed, need to open new one if ( status.getName().equalsIgnoreCase(finishedStatuses.Closed.toString()) || status.getName().equalsIgnoreCase(finishedStatuses.Done.toString()) ) { listener.getLogger().println("The previous build also failed but the issue is closed"); deleteFile(filename); Issue issue = createJiraIssue(build, filename); LOG.info(String.format("[%s] created.", issue.getKey())); }else { addComment(build, issueId, comment); LOG.info(String.format("[%s] The previous build also failed, comment added.", issueId)); } } catch (IOException e) { LOG.warning(String.format("[%s] - error processing JIRA change: %s", issueId, e.getMessage())); } } } if (previousBuildResult == Result.SUCCESS || previousBuildResult == Result.ABORTED) { try { Issue issue = createJiraIssue(build, filename); listener.getLogger().println("Build failed, created JIRA issue " + issue.getKey()); } catch (IOException e) { listener.error("Error creating JIRA issue : " + e.getMessage()); LOG.warning("Error creating JIRA issue\n" + e.getMessage()); } } } /** * when the current build's result is "success", * it checks for the previous build's result and adds comment until the previously created issue is closed. * * @param build * @param previousBuildResult * @param filename * @param vars * @throws InterruptedException * @throws IOException */ private void currentBuildResultSuccess(AbstractBuild<?, ?> build, BuildListener listener, Result previousBuildResult, String filename, EnvVars vars) throws InterruptedException, IOException { if (previousBuildResult == Result.FAILURE || previousBuildResult == Result.SUCCESS) { String comment = String.format("Previously failing build now is OK.\n Passed run: %s", getBuildDetailsString(vars)); String issueId = getIssue(filename); //if issue exists it will check the status and comment or delete the file accordingly if (issueId != null) { try { Status status = getStatus(build, issueId); //if issue is in closed status if ( status.getName().equalsIgnoreCase(finishedStatuses.Closed.toString()) || status.getName().equalsIgnoreCase(finishedStatuses.Done.toString()) ) { LOG.info(String.format("%s is closed", issueId)); deleteFile(filename); } else { LOG.info(String.format("%s is not Closed, comment was added.", issueId)); addComment(build, issueId, comment); } } catch (IOException e) { listener.error("Error updating JIRA issue " + issueId + " : " + e.getMessage()); LOG.warning("Error updating JIRA issue " + issueId + "\n" + e); } } } } /** * Returns build details string in wiki format, with hyperlinks. * * @param vars * @return */ private String getBuildDetailsString(EnvVars vars){ final String buildURL = vars.get("BUILD_URL"); return String.format("[%s|%s] [console log|%s]", getBuildName(vars), buildURL, buildURL.concat("console")); } /** * Returns build name in format BUILD#10 * * @param vars * @return String */ private String getBuildName(EnvVars vars){ final String jobName = vars.get("JOB_NAME"); final String buildNumber = vars.get("BUILD_NUMBER"); return String.format("%s #%s", jobName, buildNumber); } public static class DescriptorImpl extends BuildStepDescriptor<Publisher> { public DescriptorImpl() { super(JiraCreateIssueNotifier.class); } public FormValidation doCheckProjectKey(@QueryParameter String value) throws IOException { if (value.length() == 0) { return FormValidation.error("Please set the project key"); } return FormValidation.ok(); } @Override public JiraCreateIssueNotifier newInstance(StaplerRequest req, JSONObject formData) throws FormException { return req.bindJSON(JiraCreateIssueNotifier.class, formData); } @Override public boolean isApplicable(Class<? extends AbstractProject> jobType) { return true; } @Override public String getDisplayName() { return Messages.JiraCreateIssueNotifier_DisplayName(); } @Override public String getHelpFile() { return "/plugin/jira/help-jira-create-issue.html"; } } }
mit
pengjinning/AppKeFu_Android_Demo_V4
EclipseDemo/src/com/appkefu/demo2/activity/MainActivity.java
18565
package com.appkefu.demo2.activity; import java.util.ArrayList; import com.appkefu.demo2.R; import com.appkefu.demo2.adapter.ApiAdapter; import com.appkefu.demo2.entity.ApiEntity; import com.appkefu.lib.interfaces.KFAPIs; import com.appkefu.lib.interfaces.KFCallBack; import com.appkefu.lib.service.KFMainService; import com.appkefu.lib.service.KFXmppManager; import com.appkefu.lib.utils.KFConstants; import com.appkefu.lib.utils.KFLog; import android.os.Bundle; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; /** * 微客服(AppKeFu.com) * 微客服,集成到您App里的在线客服 国内首款App里的在线客服,支持文字、表情、图片、语音聊天。 立志为移动开发者提供最好的在线客服 * 技术交流QQ 2群:474794719 * 客服开发文档: http://admin.appkefu.com/AppKeFu/tutorial-android3.html * */ public class MainActivity extends Activity { /** * 提示:如果已经运行过旧版的Demo,请先在手机上删除原先的App再重新运行此工程 * 更多使用帮助参见:http://admin.appkefu.com/AppKeFu/tutorial-android3.html * * 注意:开发者将SDK嵌入到自己的应用中之后,至少要修改两处: 1.appkey 2.客服工作组名称(参见函数:startChat) */ private TextView mTitle; private ListView mApiListView; private ArrayList<ApiEntity> mApiArray; private ApiAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); // 登录方式 KFAPIs.visitorLogin(this); // 第二种登录方式,传入user_id, 注意user_id中只能包含数字、字母和下划线_,不能含有汉字 // /KFAPIs.loginWithUserID("linkfull_test5", this); } @Override protected void onStart() { super.onStart(); IntentFilter intentFilter = new IntentFilter(); // 监听网络连接变化情况 intentFilter.addAction(KFConstants.ACTION_XMPP_CONNECTION_CHANGED); // 监听消息 intentFilter.addAction(KFConstants.ACTION_XMPP_MESSAGE_RECEIVED); // 工作组在线状态 intentFilter.addAction(KFConstants.ACTION_XMPP_WORKGROUP_ONLINESTATUS); registerReceiver(mXmppreceiver, intentFilter); } @Override protected void onResume() { super.onResume(); // 登录方式 KFAPIs.visitorLogin(this); // 第二种登录方式,传入user_id, 注意user_id中只能包含数字、字母和下划线_,不能含有汉字 // /KFAPIs.loginWithUserID("linkfull_test5", this); // ApiEntity entity = mApiArray.get(8); entity.setApiName(getString(R.string.unread_message_count) + ":"+KFAPIs.getUnreadMessageCount("wgdemo", this)); mAdapter.notifyDataSetChanged(); } @Override protected void onStop() { super.onStop(); unregisterReceiver(mXmppreceiver); } private void initView() { // 界面标题 mTitle = (TextView) findViewById(R.id.demo_title); mApiListView = (ListView) findViewById(R.id.api_list_view); mApiArray = new ArrayList<ApiEntity>(); mAdapter = new ApiAdapter(this, mApiArray); mApiListView.setAdapter(mAdapter); ApiEntity entity = new ApiEntity(1, getString(R.string.chat_with_kefu_before)); mApiArray.add(entity); entity = new ApiEntity(2, getString(R.string.chat_with_kefu_after)); mApiArray.add(entity); entity = new ApiEntity(3, getString(R.string.chat_with_e_commence)); mApiArray.add(entity); entity = new ApiEntity(4, getString(R.string.chat_with_robot)); mApiArray.add(entity); entity = new ApiEntity(5, getString(R.string.set_user_tags)); mApiArray.add(entity); entity = new ApiEntity(6, getString(R.string.clear_message_records)); mApiArray.add(entity); entity = new ApiEntity(7, getString(R.string.show_faq)); mApiArray.add(entity); entity = new ApiEntity(8, getString(R.string.leave_message)); mApiArray.add(entity); entity = new ApiEntity(9, getString(R.string.unread_message_count)); mApiArray.add(entity); mAdapter.notifyDataSetChanged(); mApiListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View view, int index, long id) { // TODO Auto-generated method stub ApiEntity entity = mApiArray.get(index); switch (entity.getId()) { case 1: startChat(); break; case 2: startChat2(); break; case 3: startECChat(); break; case 4: startChatRobot(); break; case 5: showTagList(); break; case 6: clearMessages(); break; case 7: showFAQ(); break; case 8: leaveMessage(); break; default: break; } ; } }); } // 1.咨询人工客服 private void startChat() { // KFAPIs.startChat(this, "wgdemo", // 1. 客服工作组ID(请务必保证大小写一致),请在管理后台分配 "客服小秘书", // 2. 会话界面标题,可自定义 null, // 3. 附加信息,在成功对接客服之后,会自动将此信息发送给客服; // 如果不想发送此信息,可以将此信息设置为""或者null true, // 4. 是否显示自定义菜单,如果设置为显示,请务必首先在管理后台设置自定义菜单, // 请务必至少分配三个且只分配三个自定义菜单,多于三个的暂时将不予显示 // 显示:true, 不显示:false 5, // 5. 默认显示消息数量 //修改SDK自带的头像有两种方式,1.直接替换appkefu_message_toitem和appkefu_message_fromitem.xml里面的头像,2.传递网络图片自定义 null, //"http://114.215.189.207/PHP/XMPP/gyfd/chat/web/img/kefu-avatar.png",//6. 修改默认客服头像,如果想显示客服真实头像,设置此参数为null "http://114.215.189.207/PHP/XMPP/gyfd/chat/web/img/user-avatar.png", //7. 修改默认用户头像, 如果不想修改默认头像,设置此参数为null false, // 8. 默认机器人应答 true, //9. 是否强制用户在关闭会话的时候 进行“满意度”评价, true:是, false:否 null); } // 2.咨询人工客服 private void startChat2() { KFAPIs.startChat(this, "wgdemo2", // 1. 客服工作组ID(请务必保证大小写一致),请在管理后台分配 "客服小秘书", // 2. 会话界面标题,可自定义 null, // 3. 设置为 null或者"" 将不发送此信息给客服 false, // 4. 是否显示自定义菜单,如果设置为显示,请务必首先在管理后台设置自定义菜单, // 请务必至少分配三个且只分配三个自定义菜单,多于三个的暂时将不予显示 // 显示:true, 不显示:false 0, // 5. 默认显示消息数量 null, // 6. 使用默认客服头像 null, // 7. 使用默认用户头像 false, // 8. 默认机器人应答 false, //9. 是否强制用户在关闭会话的时候 进行“满意度”评价, true:是, false:否 new KFCallBack() { // 10. 会话页面右上角回调函数, 如果想要保持默认,请设置为null @Override public Boolean useTopRightBtnDefaultAction() { return true; } @Override public void OnChatActivityTopRightButtonClicked() { // TODO Auto-generated method stub Log.d("KFMainActivity", "右上角回调接口调用"); Toast.makeText(MainActivity.this, "右上角回调接口调用", Toast.LENGTH_SHORT).show(); // 测试右上角回调接口调用 showTagList(); } @Override public void OnECGoodsImageViewClicked(String imageViewURL) { // TODO Auto-generated method stub Log.d("KFMainActivity", "OnECGoodsImageViewClicked"); } @Override public void OnECGoodsTitleDetailClicked( String titleDetailString) { // TODO Auto-generated method stub Log.d("KFMainActivity", "OnECGoodsIntroductionClicked"); } @Override public void OnECGoodsPriceClicked(String priceString) { // TODO Auto-generated method stub Log.d("KFMainActivity", "OnECGoodsPriceClicked"); } @Override public void OnEcGoodsInfoClicked(String callbackId) { // TODO Auto-generated method stub } /** * 用户点击会话页面下方“常见问题”按钮时,是否使用自定义action,如果返回true, * 则默认action将不起作用,会调用下方OnFaqButtonClicked函数 */ public Boolean userSelfFaqAction(){ return false; } /** * 用户点击“常见问题”按钮时,自定义action回调函数接口 */ @Override public void OnFaqButtonClicked() { Log.d("KFMainActivity", "OnFaqButtonClicked"); } } // 10. 会话页面右上角回调函数 ); } // 3.电商专用咨询页面 private void startECChat() { KFAPIs.startECChat(this, "wgdemo", //1. 客服工作组名称(请务必保证大小写一致),请在管理后台分配 "客服小秘书", //2. 会话界面标题,可自定义 "商品简介商品简介商品简介商品简介商品简介 100元 <img src=\"http://appkefu.com/AppKeFu/images/dingyue.jpg\">", //3. 附加信息,在成功对接客服之后,会自动将此信息发送给客服; // 如果不想发送此信息,可以将此信息设置为""或者null true, //4. 是否显示自定义菜单,如果设置为显示,请务必首先在管理后台设置自定义菜单, // 请务必至少分配三个且只分配三个自定义菜单,多于三个的暂时将不予显示 // 显示:true, 不显示:false 5, //5. 默认显示消息数量 null, //6. 修改默认客服头像,如果不想修改默认头像,设置此参数为null null, //7. 修改默认用户头像, 如果不想修改默认头像,设置此参数为null false, //8. 默认机器人应答 true, //9. 是否显示商品详情,显示:true;不显示:false "http://appkefu.com/AppKeFu/images/dingyue.jpg",//10.商品详情图片 "商品简介商品简介商品简介商品简介商品简介", //11.商品详情简介 "100元", //12.商品详情价格 "http://appkefu.com", //13.商品网址链接 "goodsCallbackId", //14.点击商品详情布局回调参数 false, //15.退出对话的时候是否强制评价,强制:true,不评价:false new KFCallBack() { //15. 会话页面右上角回调函数 /** * 16.是否使用对话界面右上角默认动作. 使用默认动作返回:true, 否则返回false */ @Override public Boolean useTopRightBtnDefaultAction() { return true; } /** * 17.点击对话界面右上角按钮动作,依赖于 上面一个函数的返回结果 */ @Override public void OnChatActivityTopRightButtonClicked() { // TODO Auto-generated method stub Log.d("KFMainActivity", "右上角回调接口调用"); Toast.makeText(MainActivity.this, "右上角回调接口调用", Toast.LENGTH_SHORT).show(); } /** * 18.点击商品详情图片回调函数 */ @Override public void OnECGoodsImageViewClicked(String imageViewURL) { // TODO Auto-generated method stub Log.d("KFMainActivity", "OnECGoodsImageViewClicked"+imageViewURL); } /** * 19.点击商品详情简介回调函数 */ @Override public void OnECGoodsTitleDetailClicked(String titleDetailString) { // TODO Auto-generated method stub Log.d("KFMainActivity", "OnECGoodsIntroductionClicked"+titleDetailString); } /** * 20.点击商品详情价格回调函数 */ @Override public void OnECGoodsPriceClicked(String priceString) { // TODO Auto-generated method stub Log.d("KFMainActivity", "OnECGoodsPriceClicked"+priceString); } /** * 21.点击商品详情布局回调函数 */ @Override public void OnEcGoodsInfoClicked(String callbackId) { // TODO Auto-generated method stub Log.d("KFMainActivity", "OnEcGoodsInfoClicked"+callbackId); } /** * 用户点击会话页面下方“常见问题”按钮时,是否使用自定义action,如果返回true, * 则默认action将不起作用,会调用下方OnFaqButtonClicked函数 */ public Boolean userSelfFaqAction(){ return false; } /** * 用户点击“常见问题”按钮时,自定义action回调函数接口 */ @Override public void OnFaqButtonClicked() { Log.d("KFMainActivity", "OnFaqButtonClicked"); } }); } // 4.默认开启机器人应答 private void startChatRobot() { KFAPIs.startChat(this, "wgdemo", // 1. 客服工作组ID(请务必保证大小写一致),请在管理后台分配 "客服小秘书", // 2. 会话界面标题,可自定义 null, // 3. 附加信息,在成功对接客服之后,会自动将此信息发送给客服; // 如果不想发送此信息,可以将此信息设置为""或者null false, // 4. 是否显示自定义菜单,如果设置为显示,请务必首先在管理后台设置自定义菜单, // 请务必至少分配三个且只分配三个自定义菜单,多于三个的暂时将不予显示 // 显示:true, 不显示:false 0, // 5. 默认显示消息数量 //修改SDK自带的头像有两种方式,1.直接替换appkefu_message_toitem和appkefu_message_fromitem.xml里面的头像,2.传递网络图片自定义 "http://114.215.189.207/PHP/XMPP/gyfd/chat/web/img/kefu-avatar.png", //6. 修改默认客服头像,如果不想修改默认头像,设置此参数为null "http://114.215.189.207/PHP/XMPP/gyfd/chat/web/img/user-avatar.png", //7. 修改默认用户头像, 如果不想修改默认头像,设置此参数为null true, // 8. 默认机器人应答 false, //9. 是否强制用户在关闭会话的时候 进行“满意度”评价, true:是, false:否 null ); } // 5.显示标签列表 private void showTagList() { Intent intent = new Intent(this, TagListActivity.class); startActivity(intent); } // 6.清空聊天记录 private void clearMessages() { KFAPIs.clearMessageRecords("wgdemo", this); Toast.makeText(this, "清空聊天记录", Toast.LENGTH_LONG).show(); } // 7.显示常见问题FAQ private void showFAQ() { KFAPIs.showFAQ(this, "wgdemo");//工作组ID } //8 留言页面 private void leaveMessage() { KFAPIs.startLeaveMessage(this, //Context, 上下文 "wgdemo"); //工作组ID } // // 监听:连接状态、即时通讯消息、客服在线状态 private BroadcastReceiver mXmppreceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); // 监听:连接状态 if (action.equals(KFConstants.ACTION_XMPP_CONNECTION_CHANGED))// 监听链接状态 { updateStatus(intent.getIntExtra("new_state", 0)); } // 监听:即时通讯消息 else if (action.equals(KFConstants.ACTION_XMPP_MESSAGE_RECEIVED))// 监听消息 { //消息内容 String body = intent.getStringExtra("body"); //消息来自于 String from = intent.getStringExtra("from"); KFLog.d("消息来自于:"+from+" 消息内容:"+body); // KFLog.d("未读消息数目:"+KFAPIs.getUnreadMessageCount(from, MainActivity.this)); ApiEntity entity = mApiArray.get(8); entity.setApiName(getString(R.string.unread_message_count) + ":"+KFAPIs.getUnreadMessageCount(from, MainActivity.this)); mAdapter.notifyDataSetChanged(); } // 客服工作组在线状态 else if (action.equals(KFConstants.ACTION_XMPP_WORKGROUP_ONLINESTATUS)) { String fromWorkgroupName = intent.getStringExtra("from"); String onlineStatus = intent.getStringExtra("onlinestatus"); KFLog.d("客服工作组:" + fromWorkgroupName + " 在线状态:" + onlineStatus);// online:在线;offline: // 离线 // 截获到客服工作组wgdemo的在线状态 if (fromWorkgroupName.equalsIgnoreCase("wgdemo")) { ApiEntity entity = mApiArray.get(0); if (onlineStatus.equals("online")) { entity.setApiName(getString(R.string.chat_with_kefu_before)+ "(在线)"); KFLog.d("online:" + entity.getApiName()); } else { entity.setApiName(getString(R.string.chat_with_kefu_before)+ "(离线)"); KFLog.d("offline:" + entity.getApiName()); } mApiArray.set(0, entity); } // 截获到客服工作组wgdemo2的在线状态 else { ApiEntity entity = mApiArray.get(1); if (onlineStatus.equals("online")) { entity.setApiName(getString(R.string.chat_with_kefu_after)+ "(在线)"); KFLog.d("online:" + entity.getApiName()); } else { entity.setApiName(getString(R.string.chat_with_kefu_after)+ "(离线)"); KFLog.d("offline:" + entity.getApiName()); } mApiArray.set(1, entity); } mAdapter.notifyDataSetChanged(); } } }; // 根据监听到的连接变化情况更新界面显示 private void updateStatus(int status) { switch (status) { case KFXmppManager.CONNECTED: mTitle.setText("微客服3(Demo)"); // 查询客服工作组在线状态,返回结果在BroadcastReceiver中返回 KFAPIs.checkKeFuIsOnlineAsync("wgdemo", this); KFAPIs.checkKeFuIsOnlineAsync("wgdemo2", this); break; case KFXmppManager.DISCONNECTED: mTitle.setText("微客服3(Demo)(未连接)"); break; case KFXmppManager.CONNECTING: mTitle.setText("微客服3(Demo)(登录中...)"); break; case KFXmppManager.DISCONNECTING: mTitle.setText("微客服3(Demo)(登出中...)"); break; case KFXmppManager.WAITING_TO_CONNECT: case KFXmppManager.WAITING_FOR_NETWORK: mTitle.setText("微客服3(Demo)(等待中)"); break; default: throw new IllegalStateException(); } } }
mit
gdimitris/ChessPuzzlerAndroid
app/src/main/java/dimitris/android/app/db/ReviewScheduleFetchTask.java
1001
package dimitris.android.app.db; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; /** * Created by dimitris on 21/07/16. */ public class ReviewScheduleFetchTask extends AsyncTask<String,Void,Void>{ private Context context; public ReviewScheduleFetchTask(Context context){ this.context = context; } @Override protected Void doInBackground(String... strings) { String reviewId = strings[0]; ContentResolver resolver = context.getContentResolver(); Uri reviewUri = ReviewDBTable.BASE_CONTENT_URI.buildUpon() .appendPath(ReviewDBTable.REVIEW_PATH) .appendPath(reviewId) .build(); Cursor cursor = resolver.query(reviewUri,null, null, null, null); return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); } }
mit
subwoofer359/AMCChessGame
src/test/java/org/amc/game/chessserver/UrlViewChessGameTest.java
6802
package org.amc.game.chessserver; import static org.mockito.Mockito.*; import org.amc.DAOException; import org.amc.dao.ServerChessGameDAO; import org.amc.game.chess.ChessGameFixture; import org.amc.game.chess.HumanPlayer; import org.amc.game.chess.Player; import org.amc.game.chessserver.AbstractServerChessGame.ServerGameStatus; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.test.web.ModelAndViewAssert; import org.springframework.web.servlet.ModelAndView; public class UrlViewChessGameTest { private UrlViewChessGameController urlController; private static final long GAME_UID = 4321L; private ChessGameFixture cgFixture; @Mock private TwoViewServerChessGame scgGame; @Mock private OneViewServerChessGame obscgGame; @Mock private ServerChessGameDAO serverChessGameDAO; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); cgFixture = new ChessGameFixture(); urlController = new UrlViewChessGameController(); urlController.setServerChessGameDAO(serverChessGameDAO); when(scgGame.getPlayer()).thenReturn(cgFixture.getWhitePlayer()); when(scgGame.getOpponent()).thenReturn(cgFixture.getBlackPlayer()); } @Test public void test() throws DAOException { when(serverChessGameDAO.getServerChessGame(eq(GAME_UID))).thenReturn(scgGame); when(scgGame.getCurrentStatus()).thenReturn(ServerGameStatus.IN_PROGRESS); when(scgGame.getPlayer(eq(cgFixture.getWhitePlayer()))).thenReturn(cgFixture.getWhitePlayer()); ModelAndView mav = urlController.viewChessGame(cgFixture.getWhitePlayer(), GAME_UID); verify(serverChessGameDAO, times(1)).getServerChessGame(GAME_UID); ModelAndViewAssert.assertViewName(mav, ServerJoinChessGameController.TWO_VIEW_CHESS_PAGE); ModelAndViewAssert.assertModelAttributeValue(mav, ServerConstants.GAME_UUID, GAME_UID); ModelAndViewAssert.assertModelAttributeValue(mav, ServerConstants.GAME, scgGame); ModelAndViewAssert.assertModelAttributeValue(mav, ServerConstants.CHESSPLAYER, cgFixture.getWhitePlayer()); } @Test public void opponentViewTest() throws DAOException { when(serverChessGameDAO.getServerChessGame(eq(GAME_UID))).thenReturn(scgGame); when(scgGame.getCurrentStatus()).thenReturn(ServerGameStatus.IN_PROGRESS); when(scgGame.getPlayer(eq(cgFixture.getBlackPlayer()))).thenReturn(cgFixture.getBlackPlayer()); ModelAndView mav = urlController.viewChessGame(cgFixture.getBlackPlayer(), GAME_UID); verify(serverChessGameDAO, times(1)).getServerChessGame(GAME_UID); ModelAndViewAssert.assertViewName(mav, ServerJoinChessGameController.TWO_VIEW_CHESS_PAGE); ModelAndViewAssert.assertModelAttributeValue(mav, ServerConstants.GAME_UUID, GAME_UID); ModelAndViewAssert.assertModelAttributeValue(mav, ServerConstants.GAME, scgGame); ModelAndViewAssert.assertModelAttributeValue(mav, ServerConstants.CHESSPLAYER, cgFixture.getBlackPlayer()); } @Test public void serverChessGameNotInProcessStateTest() throws DAOException { when(serverChessGameDAO.getServerChessGame(eq(GAME_UID))).thenReturn(scgGame); when(scgGame.getCurrentStatus()).thenReturn(ServerGameStatus.AWAITING_PLAYER); ModelAndView mav = urlController.viewChessGame(cgFixture.getWhitePlayer(), GAME_UID); verify(serverChessGameDAO, times(1)).getServerChessGame(GAME_UID); ModelAndViewAssert.assertViewName(mav, ServerJoinChessGameController.ERROR_REDIRECT_PAGE); ModelAndViewAssert.assertModelAttributeValue(mav, ServerConstants.ERRORS, String.format(UrlViewChessGameController.CANT_VIEW_CHESSGAME, GAME_UID)); } @Test public void serverChessGameInFinishedStateTest() throws DAOException { when(serverChessGameDAO.getServerChessGame(eq(GAME_UID))).thenReturn(scgGame); when(scgGame.getCurrentStatus()).thenReturn(ServerGameStatus.FINISHED); ModelAndView mav = urlController.viewChessGame(cgFixture.getWhitePlayer(), GAME_UID); verify(serverChessGameDAO, times(1)).getServerChessGame(GAME_UID); ModelAndViewAssert.assertViewName(mav, ServerJoinChessGameController.ERROR_REDIRECT_PAGE); ModelAndViewAssert.assertModelAttributeValue(mav, ServerConstants.ERRORS, String.format(UrlViewChessGameController.CANT_VIEW_CHESSGAME, GAME_UID)); } @Test public void serverChessGameIsNullTest() throws DAOException { when(serverChessGameDAO.getServerChessGame(eq(GAME_UID))).thenReturn(null); ModelAndView mav = urlController.viewChessGame(cgFixture.getWhitePlayer(), GAME_UID); verify(serverChessGameDAO, times(1)).getServerChessGame(GAME_UID); ModelAndViewAssert.assertViewName(mav, ServerJoinChessGameController.ERROR_REDIRECT_PAGE); ModelAndViewAssert.assertModelAttributeValue(mav, ServerConstants.ERRORS, String.format(UrlViewChessGameController.CANT_VIEW_CHESSGAME, GAME_UID)); } @Test public void serverChessGameIsNotTwoViewGameTest() throws DAOException { when(obscgGame.getCurrentStatus()).thenReturn(ServerGameStatus.IN_PROGRESS); when(serverChessGameDAO.getServerChessGame(eq(GAME_UID))).thenReturn(obscgGame); ModelAndView mav = urlController.viewChessGame(cgFixture.getWhitePlayer(), GAME_UID); verify(serverChessGameDAO, times(1)).getServerChessGame(GAME_UID); ModelAndViewAssert.assertViewName(mav, ServerJoinChessGameController.ERROR_REDIRECT_PAGE); ModelAndViewAssert.assertModelAttributeValue(mav, ServerConstants.ERRORS, String.format(UrlViewChessGameController.CANT_VIEW_CHESSGAME, GAME_UID)); } @Test public void wrongPlayerTest() throws DAOException { Player villian = new HumanPlayer("Villian"); when(serverChessGameDAO.getServerChessGame(eq(GAME_UID))).thenReturn(scgGame); when(scgGame.getCurrentStatus()).thenReturn(ServerGameStatus.IN_PROGRESS); when(scgGame.getPlayer(eq(cgFixture.getWhitePlayer()))).thenReturn(cgFixture.getWhitePlayer()); ModelAndView mav = urlController.viewChessGame(villian, GAME_UID); verify(serverChessGameDAO, times(1)).getServerChessGame(GAME_UID); ModelAndViewAssert.assertViewName(mav, ServerJoinChessGameController.ERROR_REDIRECT_PAGE); } }
mit
anubiann00b/StarfighterOld
src/game/network/client/NetworkHandler.java
4553
package game.network.client; import game.network.DataPacket; import game.network.PlayerData; import game.player.Player; import java.io.IOException; import java.io.InputStream; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.Socket; import java.net.SocketException; import java.net.UnknownHostException; import java.util.List; public class NetworkHandler { private DatagramSocket socket; private Thread get; private Thread send; private Player player; private volatile boolean running = true; private InetAddress ip; private int port = 0; private List<PlayerData> enemies; private int myClientId; private long responseTime = -1; public NetworkHandler(String newIp, int newPort, Player localPlayer, List<PlayerData> newEnemies) { this.enemies = newEnemies; try { this.ip = InetAddress.getByName(newIp); } catch (UnknownHostException e) { System.out.println("Unable to connect: " + e); return; } this.port = newPort; this.player = localPlayer; } public void start() { try { socket = new DatagramSocket(); } catch (SocketException e) { System.out.println("Error creating socket: " + e); } handshake(); get = new Thread(new Runnable() { @Override public void run() { byte[] recvData = new byte[DataPacket.MAX_SIZE]; DatagramPacket recvPacket = new DatagramPacket(recvData,recvData.length); while (running) { try { socket.receive(recvPacket); } catch (IOException e) { System.out.println("Error receiving packet: " + e); } responseTime = System.currentTimeMillis(); DataPacket recvDataPacket = new DataPacket(recvData); if (recvDataPacket.getClient() == myClientId) continue; boolean updated = false; for (PlayerData e : enemies) { if (recvDataPacket.getClient() == e.id) { e.update(recvDataPacket); updated = true; break; } } if (updated) continue; enemies.add(new PlayerData(recvDataPacket)); } } }); get.start(); send = new Thread(new Runnable() { @Override public void run() { byte[] sendData = new byte[DataPacket.MAX_SIZE]; while (running) { if (responseTime != -1 && System.currentTimeMillis()-responseTime > 1000) { System.out.println("Disconnecting."); running = false; } sendData = player.getBytes(myClientId); DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length,ip,port); try { socket.send(sendPacket); } catch (IOException e) { System.out.println("Error sending packet: " + e); } } if (socket != null && !socket.isClosed()) { System.out.println("Closing socket."); socket.close(); } } }); send.start(); } private void handshake() { Socket handshakeSocket = null; try { handshakeSocket = new Socket(ip.getHostAddress(),port); } catch (IOException e) { System.out.println("Error creating TCP socket: " + e); } InputStream in = null; try { in = handshakeSocket.getInputStream(); } catch (IOException e) { System.out.println("Error getting input stream: " + e); } try { myClientId = in.read(); } catch (IOException e) { System.out.println("Error recieving handshake data: " + e); } try { handshakeSocket.close(); } catch (IOException e) { System.out.println("Error closing handshake socket: " + e); } } }
mit
TallWorlds/CubicChunks
src/main/cubicchunks/server/WorldServerContext.java
4232
/* * This file is part of Tall Worlds, licensed under the MIT License (MIT). * * Copyright (c) 2014 Tall Worlds * * 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 cubicchunks.server; import java.util.Map; import net.minecraft.world.DimensionType; import net.minecraft.world.WorldServer; import com.google.common.collect.Maps; import cubicchunks.api.generators.ITerrainGenerator; import cubicchunks.generator.SurfaceProcessor; import cubicchunks.generator.FeatureProcessor; import cubicchunks.generator.GeneratorPipeline; import cubicchunks.generator.GeneratorStage; import cubicchunks.generator.StructureProcessor; import cubicchunks.generator.TerrainProcessor; import cubicchunks.generator.terrain.FlatTerrainGenerator; import cubicchunks.generator.terrain.VanillaTerrainGenerator; import cubicchunks.lighting.FirstLightProcessor; import cubicchunks.world.WorldContext; public class WorldServerContext extends WorldContext { private static Map<WorldServer, WorldServerContext> instances; static { instances = Maps.newHashMap(); } public static WorldServerContext get(final WorldServer worldServer) { return instances.get(worldServer); } public static void put(final WorldServer worldServer, final WorldServerContext worldServerContext) { instances.put(worldServer, worldServerContext); } public static void clear() { instances.clear(); } private WorldServer worldServer; private ServerCubeCache serverCubeCache; private GeneratorPipeline generatorPipeline; private ITerrainGenerator terrainGenerator; public WorldServerContext(final WorldServer worldServer, final ServerCubeCache serverCubeCache) { super(worldServer, serverCubeCache); this.worldServer = worldServer; this.serverCubeCache = serverCubeCache; this.generatorPipeline = new GeneratorPipeline(serverCubeCache); final long seed = this.worldServer.getSeed(); this.terrainGenerator = getTerrainGenerator(this.worldServer.dimension.dimensionType); // init the generator pipeline this.generatorPipeline.addStage(GeneratorStage.TERRAIN, new TerrainProcessor(this.serverCubeCache, 5, this.terrainGenerator)); this.generatorPipeline.addStage(GeneratorStage.SURFACE, new SurfaceProcessor(this.serverCubeCache, 10, seed)); this.generatorPipeline.addStage(GeneratorStage.STRUCTURES, new StructureProcessor("Features", this.serverCubeCache, 10)); this.generatorPipeline.addStage(GeneratorStage.LIGHTING, new FirstLightProcessor("Lighting", this.serverCubeCache, 5)); this.generatorPipeline.addStage(GeneratorStage.FEATURES, new FeatureProcessor("Population", worldServer, this.serverCubeCache, 100)); this.generatorPipeline.checkStages(); } @Override public WorldServer getWorld() { return this.worldServer; } @Override public ServerCubeCache getCubeCache() { return this.serverCubeCache; } public GeneratorPipeline getGeneratorPipeline() { return this.generatorPipeline; } public ITerrainGenerator getTerrainGenerator(final DimensionType dimensionType) { if (dimensionType == DimensionType.FLAT) { return new FlatTerrainGenerator(this.worldServer.getSeed()); } return new VanillaTerrainGenerator(this.worldServer.getSeed()); } }
mit
david-mcqueen/Android
Legacy Android Applications/Intents/src/co/uk/davemcqueen/IntentsActivity.java
3111
package co.uk.davemcqueen; import android.app.Activity; import android.os.Bundle; import android.content.Intent; import android.net.Uri; import android.provider.ContactsContract; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class IntentsActivity extends Activity { Button b1, b2, b3, b4, b5; int request_Code = 1; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //---Web Browser button--- b1 = (Button) findViewById(R.id.btn_webbrowser); b1.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://www.amazon.co.uk")); startActivity(i); } }); //--Make calls button--- b2 = (Button) findViewById(R.id.btn_makecalls); b2.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { Intent i = new Intent(android.content.Intent.ACTION_DIAL, Uri.parse("tel:+651234567")); startActivity(i); } }); //--Show Map button--- b3 = (Button) findViewById(R.id.btn_showMap); b3.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("geo:37.827500,-122.481670")); startActivity(i); } }); //--Choose Contact button--- b4 = (Button) findViewById(R.id.btn_chooseContact); b4.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { Intent i = new Intent(android.content.Intent.ACTION_PICK); i.setType(ContactsContract.Contacts.CONTENT_TYPE); startActivityForResult(i,request_Code); } }); b5 = (Button) findViewById(R.id.btn_launchMyBrowser); b5.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { Intent i = new Intent("co.uk.davemcqueen.MyBrowser"); i.setData(Uri.parse("http://www.amazon.co.uk")); i.addCategory("co.uk.davemcqueen.OtherApps"); startActivity(i); } }); } public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == request_Code) { if (resultCode == RESULT_OK) { Toast.makeText(this,data.getData().toString(),Toast.LENGTH_SHORT).show(); Intent i = new Intent ( android.content.Intent.ACTION_VIEW, Uri.parse(data.getData().toString())); startActivity(i); } } } }
mit
ivelin1936/Studing-SoftUni-
Java Fundamentals/Java OOP Advanced/Lab - Enumirations and Annotations/src/p03_coffeeMachine/Coin.java
379
package p03_coffeeMachine; public enum Coin { ONE(1), TWO(2), FIVE(5), TEN(10), TWENTY(20), FIFTY(50); private int value; Coin(int value) { this.value = value; } public int getValue() { return value; } @Override public String toString() { return this.name().charAt(0) + this.name().substring(1).toLowerCase(); } }
mit
kujtimiihoxha/todo-issue
src/test/java/com/kujtimhoxha/plugins/todo/finder/FileFinderTest.java
2016
package com.kujtimhoxha.plugins.todo.finder; import org.junit.Assert; import org.junit.Test; import java.io.File; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; /** * FileFinderTest. * * @author Kujtim Hoxha (kujtimii.h@gmail.com) * @version $Id$ * @since 0.1 */ public class FileFinderTest { /** * Tests if the File finder finds all files that meet * the configurations. * @throws Exception if something goes wrong. */ @Test public void testFind() throws Exception { final List<File> sources=new ArrayList<File>(); sources.add(new File(System.getProperty("user.dir")+"/src/test/resources/finder")); sources.add(new File(System.getProperty("user.dir")+"/src/test/resources/languages")); sources.add(new File(System.getProperty("user.dir")+"/src/test/resources/matcher/TestTodoPattern.java")); final List<String> types=new ArrayList<String>(); types.add(".java"); types.add(".js"); final List<File> excludes=new ArrayList<File>(); excludes.add(new File(System.getProperty("user.dir")+"/src/test/resources/languages/test.js")); final FileFinder finder=new FileFinder(sources,excludes,types); Assert.assertTrue(finder.find().size()==3); } /** * Tests if the File finder has duplicate files. * @throws Exception if something goes wrong. */ @Test public void testDuplicate() throws Exception { final List<File> sources=new ArrayList<File>(); sources.add(new File(System.getProperty("user.dir")+"/src/test/resources/finder")); sources.add(new File(System.getProperty("user.dir")+"/src/test/resources/finder/Test.java")); final List<String> types=new ArrayList<String>(); types.add(".java"); final List<File> excludes=new ArrayList<File>(); final FileFinder finder=new FileFinder(sources,excludes,types); Assert.assertTrue(finder.find().size()==1); } }
mit
AFR0N1NJAZ/Twilight-Forest-Rewrite
src/main/java/ninjaz/twilight/common/entities/passive/EntityTFTinyBird.java
8257
package twilightforest.entity.passive; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.DataWatcher; import net.minecraft.entity.Entity; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.EntityAILookIdle; import net.minecraft.entity.ai.EntityAITasks; import net.minecraft.entity.ai.EntityAITempt; import net.minecraft.entity.ai.EntityAIWander; import net.minecraft.entity.ai.EntityAIWatchClosest; import net.minecraft.entity.ai.attributes.IAttributeInstance; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.pathfinding.PathNavigate; import net.minecraft.util.ChunkCoordinates; import net.minecraft.util.DamageSource; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import twilightforest.TFAchievementPage; import twilightforest.entity.ai.EntityAITFBirdFly; public class EntityTFTinyBird extends EntityTFBird { private static final int DATA_BIRDTYPE = 16; private static final int DATA_BIRDFLAGS = 17; private ChunkCoordinates currentFlightTarget; private int currentFlightTime; public EntityTFTinyBird(World par1World) { super(par1World); func_70105_a(0.5F, 0.9F); func_70661_as().func_75491_a(true); field_70714_bg.func_75776_a(0, new EntityAITFBirdFly(this)); field_70714_bg.func_75776_a(1, new EntityAITempt(this, 1.0D, Items.field_151014_N, true)); field_70714_bg.func_75776_a(2, new EntityAIWander(this, 1.0D)); field_70714_bg.func_75776_a(3, new EntityAIWatchClosest(this, EntityPlayer.class, 6.0F)); field_70714_bg.func_75776_a(4, new EntityAILookIdle(this)); setBirdType(field_70146_Z.nextInt(4)); setIsBirdLanded(true); } protected void func_70088_a() { super.func_70088_a(); field_70180_af.func_75682_a(16, Byte.valueOf((byte)0)); field_70180_af.func_75682_a(17, Byte.valueOf((byte)0)); } protected void func_110147_ax() { super.func_110147_ax(); func_110148_a(SharedMonsterAttributes.field_111267_a).func_111128_a(1.0D); func_110148_a(SharedMonsterAttributes.field_111263_d).func_111128_a(0.20000001192092895D); } public void func_70014_b(NBTTagCompound par1NBTTagCompound) { super.func_70014_b(par1NBTTagCompound); par1NBTTagCompound.func_74768_a("BirdType", getBirdType()); } public void func_70037_a(NBTTagCompound par1NBTTagCompound) { super.func_70037_a(par1NBTTagCompound); setBirdType(par1NBTTagCompound.func_74762_e("BirdType")); } public int getBirdType() { return field_70180_af.func_75683_a(16); } public void setBirdType(int par1) { field_70180_af.func_75692_b(16, Byte.valueOf((byte)par1)); } protected String func_70639_aQ() { return "TwilightForest:mob.tinybird.chirp"; } protected String func_70621_aR() { return "TwilightForest:mob.tinybird.hurt"; } protected String func_70673_aS() { return "TwilightForest:mob.tinybird.hurt"; } public float func_70603_bj() { return 0.3F; } protected boolean func_70692_ba() { return false; } public float func_70783_a(int par1, int par2, int par3) { Material underMaterial = field_70170_p.func_147439_a(par1, par2 - 1, par3).func_149688_o(); if (underMaterial == Material.field_151584_j) { return 200.0F; } if (underMaterial == Material.field_151575_d) { return 15.0F; } if (underMaterial == Material.field_151577_b) { return 9.0F; } return field_70170_p.func_72801_o(par1, par2, par3) - 0.5F; } public void func_70645_a(DamageSource par1DamageSource) { super.func_70645_a(par1DamageSource); if ((par1DamageSource.func_76364_f() instanceof EntityPlayer)) { ((EntityPlayer)par1DamageSource.func_76364_f()).func_71029_a(TFAchievementPage.twilightHunter); } } public void func_70071_h_() { super.func_70071_h_(); if (!isBirdLanded()) { field_70181_x *= 0.6000000238418579D; } } protected void func_70619_bc() { super.func_70619_bc(); if (isBirdLanded()) { currentFlightTime = 0; if ((field_70146_Z.nextInt(200) == 0) && (!isLandableBlock(MathHelper.func_76128_c(field_70165_t), MathHelper.func_76128_c(field_70163_u - 1.0D), MathHelper.func_76128_c(field_70161_v)))) { setIsBirdLanded(false); field_70170_p.func_72889_a((EntityPlayer)null, 1015, (int)field_70165_t, (int)field_70163_u, (int)field_70161_v, 0); field_70181_x = 0.4D; } else if (isSpooked()) { setIsBirdLanded(false); field_70181_x = 0.4D; field_70170_p.func_72889_a((EntityPlayer)null, 1015, (int)field_70165_t, (int)field_70163_u, (int)field_70161_v, 0); } } else { currentFlightTime += 1; if ((currentFlightTarget != null) && ((!field_70170_p.func_147437_c(currentFlightTarget.field_71574_a, currentFlightTarget.field_71572_b, currentFlightTarget.field_71573_c)) || (currentFlightTarget.field_71572_b < 1))) { currentFlightTarget = null; } if ((currentFlightTarget == null) || (field_70146_Z.nextInt(30) == 0) || (currentFlightTarget.func_71569_e((int)field_70165_t, (int)field_70163_u, (int)field_70161_v) < 4.0F)) { int yTarget = currentFlightTime < 100 ? 2 : 4; currentFlightTarget = new ChunkCoordinates((int)field_70165_t + field_70146_Z.nextInt(7) - field_70146_Z.nextInt(7), (int)field_70163_u + field_70146_Z.nextInt(6) - yTarget, (int)field_70161_v + field_70146_Z.nextInt(7) - field_70146_Z.nextInt(7)); } double d0 = currentFlightTarget.field_71574_a + 0.5D - field_70165_t; double d1 = currentFlightTarget.field_71572_b + 0.1D - field_70163_u; double d2 = currentFlightTarget.field_71573_c + 0.5D - field_70161_v; field_70159_w += (Math.signum(d0) * 0.5D - field_70159_w) * 0.10000000149011612D; field_70181_x += (Math.signum(d1) * 0.699999988079071D - field_70181_x) * 0.10000000149011612D; field_70179_y += (Math.signum(d2) * 0.5D - field_70179_y) * 0.10000000149011612D; float f = (float)(Math.atan2(field_70179_y, field_70159_w) * 180.0D / 3.141592653589793D) - 90.0F; float f1 = MathHelper.func_76142_g(f - field_70177_z); field_70701_bs = 0.5F; field_70177_z += f1; if ((field_70146_Z.nextInt(10) == 0) && (isLandableBlock(MathHelper.func_76128_c(field_70165_t), MathHelper.func_76128_c(field_70163_u - 1.0D), MathHelper.func_76128_c(field_70161_v)))) { setIsBirdLanded(true); field_70181_x = 0.0D; } } } public boolean isSpooked() { EntityPlayer closestPlayer = field_70170_p.func_72890_a(this, 4.0D); return (field_70737_aN > 0) || ((closestPlayer != null) && ((field_71071_by.func_70448_g() == null) || (field_71071_by.func_70448_g().func_77973_b() != Items.field_151014_N))); } public boolean isLandableBlock(int x, int y, int z) { Block block = field_70170_p.func_147439_a(x, y, z); if (block == net.minecraft.init.Blocks.field_150350_a) { return false; } return (block.isLeaves(field_70170_p, x, y, z)) || (block.isSideSolid(field_70170_p, x, y, z, ForgeDirection.UP)); } public boolean isBirdLanded() { return (field_70180_af.func_75683_a(17) & 0x1) != 0; } public void setIsBirdLanded(boolean par1) { byte b0 = field_70180_af.func_75683_a(17); if (par1) { field_70180_af.func_75692_b(17, Byte.valueOf((byte)(b0 | 0x1))); } else { field_70180_af.func_75692_b(17, Byte.valueOf((byte)(b0 & 0xFFFFFFFE))); } } public boolean func_70104_M() { return false; } protected void func_82167_n(Entity par1Entity) {} protected void func_85033_bc() {} }
mit
EricSekyere/CSE3461-SketchPad
src/app/drawing/ImageDrawing.java
6414
package app.drawing; import java.io.*; import java.awt.*; import java.awt.geom.*; import java.awt.image.*; import javax.imageio.*; /** * This class implements a image drawing. * Defines draw methods that paint the image to * the graphics context. Enables transformations. */ public class ImageDrawing implements Drawing { private ShapeDrawing bound; private AffineTransform transform = new AffineTransform(); private BufferedImage image; /** * Create a new image drawing from a file source. * * @param source the image file * @param x the x position to place the image * @param y the y position to place the image */ public ImageDrawing(File source, double x, double y) { try { image = ImageIO.read(source); } catch (IOException e) { e.printStackTrace(); } bound = new RectangleDrawing(0, 0, image.getWidth(), image.getHeight()); this.translate(x, y); } /** * Create a new image drawing from a input source. * For use when deserializing from XML. * * @param source the input stream of the image * @param at transform to apply initially * @param bound the boundary shape of the image */ public ImageDrawing(InputStream source, AffineTransform at, Shape bound) { try { image = ImageIO.read(source); } catch (IOException e) { e.printStackTrace(); } this.bound = new PathDrawing(bound); this.transform = at; } public ImageDrawing(ImageDrawing img) { this.image = img.getImage(); this.transform = new AffineTransform(img.getTransform()); this.bound = new PathDrawing(img.getShapeBound()); } public BufferedImage getImage() { return image; } public AffineTransform getTransform() { return transform; } public ShapeDrawing getShapeBound() { return bound; } /** * Update the transformation matrix. * * @param at the new transform * @param the transformation applied */ public AffineTransform updateTransform(AffineTransform at) { transform.concatenate(at); return at; } @Override public void draw(Graphics2D g) { Graphics2D g2d = (Graphics2D)g.create(); g2d.transform(transform); g2d.drawImage(image, null, null); g2d.dispose(); } @Override public Rectangle getBounds() { return bound.getBounds();} @Override public Rectangle2D getBounds2D() { return bound.getBounds2D();} @Override public boolean contains(double x, double y) { return bound.contains(x, y);} @Override public boolean contains(Point2D p) { return bound.contains(p);} @Override public boolean intersects(double x, double y, double w, double h) { return bound.intersects(x, y, w, h);} @Override public boolean intersects(Rectangle2D r) { return bound.intersects(r);} @Override public boolean contains(double x, double y, double w, double h) { return bound.contains(x, y, w, h);} @Override public boolean contains(Rectangle2D r) { return bound.contains(r);} @Override public PathIterator getPathIterator(AffineTransform at) { return bound.getPathIterator(at);} @Override public PathIterator getPathIterator(AffineTransform at, double flatness) { return bound.getPathIterator(at, flatness);} @Override public AffineTransform transform(AffineTransform at) { return updateTransform(bound.transform(at));} @Override public AffineTransform transformOnCenter(AffineTransform at) { return updateTransform(bound.transformOnCenter(at));} @Override public AffineTransform transform(AffineTransform at, double anchorx, double anchory) { return updateTransform(bound.transform(at, anchorx, anchory));} @Override public AffineTransform translate(double tx, double ty) { return updateTransform(bound.translate(tx, ty));} @Override public AffineTransform rotate(double theta) { return updateTransform(bound.rotate(theta));} @Override public AffineTransform rotate(double theta, double anchorx, double anchory) { return updateTransform(bound.rotate(theta, anchorx, anchory));} @Override public AffineTransform rotate(double vecx, double vecy) { return updateTransform(bound.rotate(vecx, vecy));} @Override public AffineTransform rotate(double vecx, double vecy, double anchorx, double anchory) { return updateTransform(bound.rotate(vecx, vecy, anchorx, anchory));} @Override public AffineTransform quadrantRotate(int numquadrants) { return updateTransform(bound.quadrantRotate(numquadrants));} @Override public AffineTransform quadrantRotate(int numquadrants, double anchorx, double anchory) { return updateTransform(bound.quadrantRotate(numquadrants, anchorx, anchory));} @Override public AffineTransform scale(double sx, double sy) { return updateTransform(bound.scale(sx, sy));} @Override public AffineTransform scale(double sx, double sy, double anchorx, double anchory) { return updateTransform(bound.scale(sx, sy, anchorx, anchory));} @Override public AffineTransform scaleOnCenter(double sx, double sy) { return updateTransform(bound.scaleOnCenter(sx, sy));} @Override public AffineTransform shear(double shx, double shy) { return updateTransform(bound.shear(shx, shy));} @Override public AffineTransform shearOnCenter(double shx, double shy) { return updateTransform(bound.shearOnCenter(shx, shy));} @Override public AffineTransform shear(double shx, double shy, double anchorx, double anchory) { return updateTransform(bound.shear(shx, shy, anchorx, anchory));} @Override public AffineTransform reflectHorizontal(double y) { return updateTransform(bound.reflectHorizontal(y));} @Override public AffineTransform reflectHorizontal() { return updateTransform(bound.reflectHorizontal());} @Override public AffineTransform reflectVertical(double x) { return updateTransform(bound.reflectVertical(x));} @Override public AffineTransform reflectVertical() { return updateTransform(bound.reflectVertical());} } // ImageDrawing
mit
arielnetworks/lombok
test/transform/resource/after-delombok/DataPlain.java
6596
class Data1 { final int x; String name; @java.beans.ConstructorProperties({"x"}) @java.lang.SuppressWarnings("all") public Data1(final int x) { this.x = x; } @java.lang.SuppressWarnings("all") public int getX() { return this.x; } @java.lang.SuppressWarnings("all") public String getName() { return this.name; } @java.lang.SuppressWarnings("all") public void setName(final String name) { this.name = name; } @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof Data1)) return false; final Data1 other = (Data1)o; if (!other.canEqual((java.lang.Object)this)) return false; if (this.getX() != other.getX()) return false; if (this.getName() == null ? other.getName() != null : !this.getName().equals((java.lang.Object)other.getName())) return false; return true; } @java.lang.SuppressWarnings("all") public boolean canEqual(final java.lang.Object other) { return other instanceof Data1; } @java.lang.Override @java.lang.SuppressWarnings("all") public int hashCode() { final int PRIME = 31; int result = 1; result = result * PRIME + this.getX(); result = result * PRIME + (this.getName() == null ? 0 : this.getName().hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "Data1(x=" + this.getX() + ", name=" + this.getName() + ")"; } } class Data2 { final int x; String name; @java.beans.ConstructorProperties({"x"}) @java.lang.SuppressWarnings("all") public Data2(final int x) { this.x = x; } @java.lang.SuppressWarnings("all") public int getX() { return this.x; } @java.lang.SuppressWarnings("all") public String getName() { return this.name; } @java.lang.SuppressWarnings("all") public void setName(final String name) { this.name = name; } @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof Data2)) return false; final Data2 other = (Data2)o; if (!other.canEqual((java.lang.Object)this)) return false; if (this.getX() != other.getX()) return false; if (this.getName() == null ? other.getName() != null : !this.getName().equals((java.lang.Object)other.getName())) return false; return true; } @java.lang.SuppressWarnings("all") public boolean canEqual(final java.lang.Object other) { return other instanceof Data2; } @java.lang.Override @java.lang.SuppressWarnings("all") public int hashCode() { final int PRIME = 31; int result = 1; result = result * PRIME + this.getX(); result = result * PRIME + (this.getName() == null ? 0 : this.getName().hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "Data2(x=" + this.getX() + ", name=" + this.getName() + ")"; } } final class Data3 { final int x; String name; @java.beans.ConstructorProperties({"x"}) @java.lang.SuppressWarnings("all") public Data3(final int x) { this.x = x; } @java.lang.SuppressWarnings("all") public int getX() { return this.x; } @java.lang.SuppressWarnings("all") public String getName() { return this.name; } @java.lang.SuppressWarnings("all") public void setName(final String name) { this.name = name; } @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof Data3)) return false; final Data3 other = (Data3)o; if (this.getX() != other.getX()) return false; if (this.getName() == null ? other.getName() != null : !this.getName().equals((java.lang.Object)other.getName())) return false; return true; } @java.lang.Override @java.lang.SuppressWarnings("all") public int hashCode() { final int PRIME = 31; int result = 1; result = result * PRIME + this.getX(); result = result * PRIME + (this.getName() == null ? 0 : this.getName().hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "Data3(x=" + this.getX() + ", name=" + this.getName() + ")"; } } final class Data4 extends java.util.Timer { int x; Data4() { super(); } @java.lang.SuppressWarnings("all") public int getX() { return this.x; } @java.lang.SuppressWarnings("all") public void setX(final int x) { this.x = x; } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "Data4(x=" + this.getX() + ")"; } @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof Data4)) return false; final Data4 other = (Data4)o; if (!other.canEqual((java.lang.Object)this)) return false; if (!super.equals(o)) return false; if (this.getX() != other.getX()) return false; return true; } @java.lang.SuppressWarnings("all") public boolean canEqual(final java.lang.Object other) { return other instanceof Data4; } @java.lang.Override @java.lang.SuppressWarnings("all") public int hashCode() { final int PRIME = 31; int result = 1; result = result * PRIME + super.hashCode(); result = result * PRIME + this.getX(); return result; } } class Data5 { @java.lang.SuppressWarnings("all") public Data5() { } @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof Data5)) return false; final Data5 other = (Data5)o; if (!other.canEqual((java.lang.Object)this)) return false; return true; } @java.lang.SuppressWarnings("all") public boolean canEqual(final java.lang.Object other) { return other instanceof Data5; } @java.lang.Override @java.lang.SuppressWarnings("all") public int hashCode() { int result = 1; return result; } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "Data5()"; } } final class Data6 { @java.lang.SuppressWarnings("all") public Data6() { } @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof Data6)) return false; return true; } @java.lang.Override @java.lang.SuppressWarnings("all") public int hashCode() { int result = 1; return result; } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "Data6()"; } }
mit
g4s8/eo
eo-compiler/src/main/java/org/eolang/compiler/syntax/package-info.java
1295
/** * The MIT License (MIT) * * Copyright (c) 2016 eolang.org * * 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 NON-INFRINGEMENT. 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. */ /** * Syntax AST classes. * * @author Yegor Bugayenko (yegor256@gmail.com) * @version $Id$ * @since 0.1 */ package org.eolang.compiler.syntax;
mit
calliem/SLogo
src/model/Parser.java
7945
package model; import java.lang.reflect.InvocationTargetException; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.ConcurrentModificationException; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Observable; import java.util.Observer; import java.util.ResourceBundle; import java.util.regex.Pattern; import model.instructions.Constant; import model.instructions.Instruction; import model.instructions.ListInstruction; import model.instructions.StringInstruction; import model.instructions.UserRunningInstruction; import model.instructions.Variable; import view.SLogoView; import view.ViewUpdater; /** * This class is used as the primary backend class. The parser reads in a string value and creates an expression tree of instructions that * can are then executed. Valid instructions are given in an enum at the head of each instruction file, and are read into the Command Types array. * This class also handles enabing all other classes to observe the execution environment passed in to each instruction. * Note, our list implementation does not allow a list to return a value * @author Primary: Greg, Secondary: Sid */ public class Parser implements Observer{ private List<Entry<String, Pattern>> myPatterns; private Map<String,String> myCommandMap; private static final String[] COMMAND_TYPES = new String[]{"BooleanInstruction","ControlInstruction","FrontEndInstruction","MathInstruction","MovementInstruction","MultipleTurtlesInstruction","TurtleRequestInstruction"}; private int myFurthestDepth; private SLogoView mySLogoView; private ViewUpdater myViewUpdater; private ExecutionEnvironment myExecutionParameters; public Parser(SLogoView view){ mySLogoView = view; myPatterns = new ArrayList<>(); myCommandMap = new HashMap<String, String>(); myExecutionParameters = new ExecutionEnvironment(); myExecutionParameters.addObserver(this); myViewUpdater = new ViewUpdater(view); myExecutionParameters.addObserver(myViewUpdater); //create the viewupdater and store as global and pass to others view.setEnvironment(myExecutionParameters); addAllPatterns("English"); makeCommandMap(); } private void addAllPatterns(String language){ makePatterns("resources/languages/" + language); makePatterns("resources/languages/Syntax"); } private void makePatterns (String resourceInput) { ResourceBundle resources = ResourceBundle.getBundle(resourceInput); Enumeration<String> iter = resources.getKeys(); while (iter.hasMoreElements()) { String key = iter.nextElement(); String value = resources.getString(key); myPatterns.add(new SimpleEntry<String, Pattern>(key, Pattern.compile(value, Pattern.CASE_INSENSITIVE))); } } private void makeCommandMap() { for (String type : COMMAND_TYPES) { Class<?> classType = null; try { classType = Class.forName("model.instructions." + type + "$implementers"); } catch (ClassNotFoundException e) { e.printStackTrace(); } for (Object d : classType.getEnumConstants()) { myCommandMap.put(d.toString(), type); } myCommandMap.put("[", "ListInstruction"); myCommandMap.put("VARIABLE", "Variable"); } } public void parseAndExecute(String input) { try { System.out.println(input); myFurthestDepth = 0; String[] splitCommands = input.split("\\s+"); List<Node> nodeList = new ArrayList<Node>(); while (myFurthestDepth < splitCommands.length) { nodeList.add(makeTree(splitCommands)); } for (Node root : nodeList) { try{ for(int turtle:myExecutionParameters.getActiveList()){ myExecutionParameters.setActiveTurtle(turtle); root.getInstruction().execute(); } } catch (ConcurrentModificationException e){ } } } catch (Exception e) { e.printStackTrace(); mySLogoView.openDialog("Invalid input! Try again."); } } private Node makeTree(String[] command) throws ModelException{ int myVars = 0; int neededVars = -1; Node myNode = null; List<Instruction> futureInstructions = new ArrayList<Instruction>(); String match = testMatches(command[myFurthestDepth]).toUpperCase(); System.out.println("match " + match); switch (match){ //TODO: instead of while loop, find where closing bracket is //run until you hit that //have some way to account for nested loops case "LISTSTART": // count number of strings til you reach a ], thats number of dependencies myFurthestDepth++; myNode = new Node(new ListInstruction(futureInstructions, match,myViewUpdater, myExecutionParameters)); Node temp; while (true) { temp = makeTree(command); System.out.println("MAKING LIST " + temp); if (temp == null) break; myNode.addChild(temp); futureInstructions.add(temp.getInstruction()); } return myNode; case "COMMENT": myFurthestDepth++; return makeTree(command); case "CONSTANT": myFurthestDepth++; return new Node(new Constant(command[myFurthestDepth - 1], myExecutionParameters)); case "VARIABLE": myFurthestDepth++; Instruction tempInt = new Variable(command[myFurthestDepth - 1], myExecutionParameters); myExecutionParameters.addObserver(tempInt); return new Node(tempInt); case "COMMAND": myFurthestDepth++; if(myExecutionParameters.getUserCommandMap().containsKey(command[myFurthestDepth-1])&&(myFurthestDepth<2||myFurthestDepth>=2&&testMatches(command[myFurthestDepth-2]).toUpperCase()!="MAKEUSERINSTRUCTION")){ myNode = new Node(new UserRunningInstruction(futureInstructions, command[myFurthestDepth-1], myViewUpdater, myExecutionParameters)); System.out.println(" Node "+ myNode); neededVars = 1; } else{ myExecutionParameters.addCommand(command[myFurthestDepth-1], null); return new Node(new StringInstruction(command[myFurthestDepth-1], myExecutionParameters)); } break; case "LISTEND": myFurthestDepth++; return null; default: } //this is either a known command or invalid input. //instantiate the command, if reflection cannot find the file then must be invalid if(myNode==null){ Instruction myInt; try { myInt = Class.forName("model.instructions."+myCommandMap.get(match)).asSubclass(Instruction.class).getConstructor(new Class[]{List.class,String.class,ViewUpdater.class,ExecutionEnvironment.class}).newInstance(new Object[]{futureInstructions, match,myViewUpdater, myExecutionParameters}); myFurthestDepth++; myExecutionParameters.addObserver(myInt); myNode = new Node(myInt); neededVars = myInt.getNumberOfArguments(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException | ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } while(myVars<neededVars){ Node level = makeTree(command); myNode.addChild(level); myVars++; } for (Node child : myNode.getChildren()) { try { futureInstructions.add(child.getInstruction()); } catch (NullPointerException e) { mySLogoView.openDialog("Invalid input!"); throw new ModelException(); } } return myNode; } private boolean match (String input, Pattern regex) { return regex.matcher(input).matches(); } private String testMatches(String test) { if (test.trim().length() > 0) { for (Entry<String, Pattern> p : myPatterns) { if (match(test, p.getValue())) { return p.getKey(); } } } return "NONE"; } public void setLanguage(String language){ myPatterns = new ArrayList<>(); addAllPatterns(language); } @Override public void update(Observable o, Object arg) { myExecutionParameters = (ExecutionEnvironment) o; } }
mit
conveyal/analysis-backend
src/main/java/com/conveyal/gtfs/error/DuplicateStopError.java
772
package com.conveyal.gtfs.error; import com.conveyal.gtfs.validator.model.DuplicateStops; import java.io.Serializable; /** Indicates that a stop exists more than once in the feed. */ public class DuplicateStopError extends GTFSError implements Serializable { public static final long serialVersionUID = 1L; private final String message; public final DuplicateStops duplicateStop; public DuplicateStopError(DuplicateStops duplicateStop) { super("stop", duplicateStop.getDuplicatedStop().sourceFileLine, "stop_lat,stop_lon", duplicateStop.getDuplicatedStop().stop_id); this.message = duplicateStop.toString(); this.duplicateStop = duplicateStop; } @Override public String getMessage() { return message; } }
mit
graphql-java/graphql-java
src/main/java/graphql/GraphqlErrorBuilder.java
5448
package graphql; import graphql.execution.DataFetcherResult; import graphql.execution.ResultPath; import graphql.language.SourceLocation; import graphql.schema.DataFetchingEnvironment; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Map; import static graphql.Assert.assertNotNull; /** * This helps you build {@link graphql.GraphQLError}s and also has a quick way to make a {@link graphql.execution.DataFetcherResult}s * from that error. * * @param <B> this base class allows you to derive new classes from this base error builder */ @SuppressWarnings("unchecked") @PublicApi public class GraphqlErrorBuilder<B extends GraphqlErrorBuilder<B>> { private String message; private List<Object> path; private List<SourceLocation> locations = new ArrayList<>(); private ErrorClassification errorType = ErrorType.DataFetchingException; private Map<String, Object> extensions = null; public String getMessage() { return message; } @Nullable public List<Object> getPath() { return path; } @Nullable public List<SourceLocation> getLocations() { return locations; } public ErrorClassification getErrorType() { return errorType; } @Nullable public Map<String, Object> getExtensions() { return extensions; } /** * @return a builder of {@link graphql.GraphQLError}s */ public static GraphqlErrorBuilder<?> newError() { return new GraphqlErrorBuilder<>(); } /** * This will set up the {@link GraphQLError#getLocations()} and {@link graphql.GraphQLError#getPath()} for you from the * fetching environment. * * @param dataFetchingEnvironment the data fetching environment * * @return a builder of {@link graphql.GraphQLError}s */ public static GraphqlErrorBuilder<?> newError(DataFetchingEnvironment dataFetchingEnvironment) { return new GraphqlErrorBuilder<>() .location(dataFetchingEnvironment.getField().getSourceLocation()) .path(dataFetchingEnvironment.getExecutionStepInfo().getPath()); } protected GraphqlErrorBuilder() { } public B message(String message, Object... formatArgs) { if (formatArgs == null || formatArgs.length == 0) { this.message = assertNotNull(message); } else { this.message = String.format(assertNotNull(message), formatArgs); } return (B) this; } public B locations(@Nullable List<SourceLocation> locations) { if (locations != null) { this.locations.addAll(locations); } else { this.locations = null; } return (B) this; } public B location(@Nullable SourceLocation location) { if (locations != null) { this.locations.add(location); } return (B) this; } public B path(@Nullable ResultPath path) { if (path != null) { this.path = path.toList(); } else { this.path = null; } return (B) this; } public B path(@Nullable List<Object> path) { this.path = path; return (B) this; } public B errorType(ErrorClassification errorType) { this.errorType = assertNotNull(errorType); return (B) this; } public B extensions(@Nullable Map<String, Object> extensions) { this.extensions = extensions; return (B) this; } /** * @return a newly built GraphqlError */ public GraphQLError build() { assertNotNull(message, () -> "You must provide error message"); return new GraphqlErrorImpl(message, locations, errorType, path, extensions); } private static class GraphqlErrorImpl implements GraphQLError { private final String message; private final List<SourceLocation> locations; private final ErrorClassification errorType; private final List<Object> path; private final Map<String, Object> extensions; public GraphqlErrorImpl(String message, List<SourceLocation> locations, ErrorClassification errorType, List<Object> path, Map<String, Object> extensions) { this.message = message; this.locations = locations; this.errorType = errorType; this.path = path; this.extensions = extensions; } @Override public String getMessage() { return message; } @Override public List<SourceLocation> getLocations() { return locations; } @Override public ErrorClassification getErrorType() { return errorType; } @Override public List<Object> getPath() { return path; } @Override public Map<String, Object> getExtensions() { return extensions; } @Override public String toString() { return message; } } /** * A helper method that allows you to return this error as a {@link graphql.execution.DataFetcherResult} * * @return a new data fetcher result that contains the built error */ public DataFetcherResult<?> toResult() { return DataFetcherResult.newResult() .error(build()) .build(); } }
mit
kamalbindra14/Learning
src/com/spring/impl/Saxophone.java
240
package com.spring.impl; import com.spring.intf.Instrument; public class Saxophone implements Instrument { public Saxophone() { } @Override public void play() { System.out.println("PLING PLING PLING"); } }
mit
sparth9/E-MART
test/CartTest/AddtoCartTest.java
1964
/* * 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 CartTest; import com.emart.controllers.CurrentItem; import com.emart.controllers.ShoppingCart; import com.pojos.Product; import java.util.logging.Level; import java.util.logging.Logger; import org.junit.Assert; import static org.junit.Assert.fail; import org.junit.Before; import org.junit.Test; /** * * @author punker */ public class AddtoCartTest { private ShoppingCart sc; private CurrentItem cu; private Product p; public AddtoCartTest() { } @Before public void setUp() { sc = new ShoppingCart(); sc.initializeSet(); cu = new CurrentItem(); p = new Product(); p.setProductId(99); p.setProductName("TEST"); } @Test public void Add_To_Cart_Test() { try { sc.addItem(p, 1); Product temp_p = new Product(); temp_p.setProductId(99); temp_p.setProductName("TEST"); Assert.assertEquals(sc.getItems_map().get(99).getProductId(),temp_p.getProductId()); Assert.assertEquals(1, sc.getItem_qty_map().get(99).intValue()); Assert.assertEquals(sc.getItems_map().get(99).getProductName(),temp_p.getProductName()); } catch (Exception ex) { Logger.getLogger(AddtoCartTest.class.getName()).log(Level.SEVERE, null, ex); fail("Add to cart FAILED"); } } @Test public void Update_Cart_Test() { try { sc.addItem(p, 1); sc.updateItem(99, 100); Assert.assertEquals(100, sc.getItem_qty_map().get(99).intValue()); } catch (Exception ex) { Logger.getLogger(AddtoCartTest.class.getName()).log(Level.SEVERE, null, ex); fail("Update cart FAILED"); } } }
mit
Phenix246/Blaze_Land_Essential
common/fr/blaze_empire/phenix246/blaze_land_essential/network/packet/PacketPlayerMoney.java
3814
/******************************************************************************* * Copyright (c) 2014, Phenix246 * * This work is made available under the terms of the Creative Commons Attribution License: * http://creativecommons.org/licenses/by-nc-sa/4.0/deed.en * Contact the author for use the sources * * Cette œuvre est mise à disposition selon les termes de la Licence Creative Commons Attribution : * http://creativecommons.org/licenses/by-nc-sa/4.0/deed.fr * Contacter l'auteur pour utiliser les sources * * Este trabajo está disponible bajo los términos de la licencia Creative Commons Atribución : * http://creativecommons.org/licenses/by-nc-sa/4.0/deed.es * Contactar al autor para utilizar las fuentes * ******************************************************************************/ package fr.blaze_empire.phenix246.blaze_land_essential.network.packet; import io.netty.buffer.ByteBuf; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import fr.blaze_empire.phenix246.blaze_land_essential.entity.player.PlayerMoneyProperties; import fr.blaze_empire.phenix246.libs.network.BLPacket; public class PacketPlayerMoney extends BLPacket { private float copperCoins; private byte maxCopperCoins; private byte silverCoins; private byte maxSilverCoins; private short goldCoins; private short maxGoldCoins; private int emeraldCoins; private int maxEmeraldCoins; public PacketPlayerMoney() {} public PacketPlayerMoney(float copperCoins, byte maxCopperCoins, byte silverCoins, byte maxSilverCoins, short goldCoins, short maxGoldCoins, int emeraldCoins, int maxEmeraldCoins) { this.copperCoins = copperCoins; this.maxCopperCoins = maxCopperCoins; this.silverCoins = silverCoins; this.maxSilverCoins = maxSilverCoins; this.goldCoins = goldCoins; this.maxGoldCoins = maxGoldCoins; this.emeraldCoins = emeraldCoins; this.maxEmeraldCoins = maxEmeraldCoins; } @Override public void handleClientSide(EntityPlayer player) { PlayerMoneyProperties props = PlayerMoneyProperties.get(player); props.copperCoins = this.copperCoins; props.maxCopperCoins = this.maxCopperCoins; props.silverCoins = this.silverCoins; props.maxSilverCoins = this.maxSilverCoins; props.goldCoins = this.goldCoins; props.maxGoldCoins = this.maxGoldCoins; props.emeraldCoins = this.emeraldCoins; props.maxEmeraldCoins = this.maxEmeraldCoins; } @Override public void handleServerSide(EntityPlayer player) { PlayerMoneyProperties props = PlayerMoneyProperties.get(player); props.copperCoins = this.copperCoins; props.maxCopperCoins = this.maxCopperCoins; props.silverCoins = this.silverCoins; props.maxSilverCoins = this.maxSilverCoins; props.goldCoins = this.goldCoins; props.maxGoldCoins = this.maxGoldCoins; props.emeraldCoins = this.emeraldCoins; props.maxEmeraldCoins = this.maxEmeraldCoins; } @Override public void writeData(ByteBuf buffer) throws IOException { buffer.writeFloat(this.copperCoins); buffer.writeByte(this.maxCopperCoins); buffer.writeByte(this.silverCoins); buffer.writeByte(this.maxSilverCoins); buffer.writeShort(this.goldCoins); buffer.writeShort(this.maxGoldCoins); buffer.writeInt(this.emeraldCoins); buffer.writeInt(this.maxEmeraldCoins); } @Override public void readData(ByteBuf buffer) { this.copperCoins = buffer.readFloat(); this.maxCopperCoins = buffer.readByte(); this.silverCoins = buffer.readByte(); this.maxSilverCoins = buffer.readByte(); this.goldCoins = buffer.readShort(); this.maxGoldCoins = buffer.readShort(); this.emeraldCoins = buffer.readInt(); this.maxEmeraldCoins = buffer.readInt(); } }
mit
patrickneubauer/XMLIntellEdit
xmlintelledit/xmltext/src/main/java/isostdisois_13584_32ed_1techxmlschemaontomlSimplified/INTTYPE.java
1851
/** */ package isostdisois_13584_32ed_1techxmlschemaontomlSimplified; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>INTTYPE</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link isostdisois_13584_32ed_1techxmlschemaontomlSimplified.INTTYPE#getValueFormat <em>Value Format</em>}</li> * </ul> * * @see isostdisois_13584_32ed_1techxmlschemaontomlSimplified.Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage#getINTTYPE() * @model annotation="http://www.eclipse.org/emf/2002/Ecore constraints='maxLengthValueFormat'" * annotation="http://www.eclipse.org/emf/2002/Ecore/OCL/Pivot maxLengthValueFormat='(self.valueFormat = null) or self.valueFormat.size() &lt;= 80'" * @generated */ public interface INTTYPE extends ANYTYPE { /** * Returns the value of the '<em><b>Value Format</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Value Format</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Value Format</em>' attribute. * @see #setValueFormat(String) * @see isostdisois_13584_32ed_1techxmlschemaontomlSimplified.Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage#getINTTYPE_ValueFormat() * @model * @generated */ String getValueFormat(); /** * Sets the value of the '{@link isostdisois_13584_32ed_1techxmlschemaontomlSimplified.INTTYPE#getValueFormat <em>Value Format</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Value Format</em>' attribute. * @see #getValueFormat() * @generated */ void setValueFormat(String value); } // INTTYPE
mit
sblectric/EZExtended
src/main/java/com/ezextended/util/IntList.java
1050
package com.ezextended.util; /** A more useful integer list */ public class IntList extends JointList<Integer> { public IntList(){ super(); } /** Returns the average of the numbers in the list */ public int average() { int a = 0; for(int i : this) { a += i; } return a / this.size(); } /** returns the minimum of the numbers in this list */ public int min() { int a = Integer.MAX_VALUE; for(int i : this) { a = Math.min(a, i); } return a; } /** returns the maximum of the numbers in this list */ public int max() { int a = Integer.MIN_VALUE; for(int i : this) { a = Math.max(a, i); } return a; } /** returns the variance of numbers in this list */ public int variance() { return this.max() - this.min(); } /** Averages the average with the minimum in this list */ public int averageLowBias() { return (this.average() + this.min()) / 2; } /** Averages the average with the maximum in this list */ public int averageHighBias() { return (this.average() + this.max()) / 2; } }
mit
mntone/UniversityScheduleClient
JVM/univschedule-core/src/main/java/mntone/univschedule/core/Class.java
2888
package mntone.univschedule.core; import org.json.JSONObject; import java.util.Date; /** * Class */ public final class Class { private final String mHash; private final Date mDate; private final Period mPeriod; private final String mSubject; private final String mCampusName; private final String mDepartment; private final String mLecturer; private final String mGrade; private final String mMessage; /** * Initialize a new class. * * @param hash the hash * @param date the date * @param period the period * @param subject the subject * @param campusName the campus * @param department the department * @param lecturer the lecture * @param grade the grade * @param message the message */ Class( final String hash, final Date date, final Period period, final String subject, final String campusName, final String department, final String lecturer, final String grade, final String message ) { this.mHash = hash; this.mDate = date; this.mPeriod = period; this.mSubject = subject; this.mCampusName = campusName; this.mDepartment = department; this.mLecturer = lecturer; this.mGrade = grade; this.mMessage = message; } /** * Initialize a new Class. * * @param klass the json of class */ Class( final JSONObject klass ) { this.mHash = klass.getString( "hash" ); this.mDate = JsonUtil.convertStringToDateWithISO8601( klass.getString( "date" ) ); this.mPeriod = new Period( klass.getJSONObject( "period" ) ); this.mSubject = klass.getString( "subject" ); this.mCampusName = JsonUtil.getString( klass, "campus_name" ); this.mDepartment = JsonUtil.getString( klass, "department" ); this.mLecturer = JsonUtil.getString( klass, "lecturer" ); this.mGrade = JsonUtil.getString( klass, "grade" ); this.mMessage = JsonUtil.getString( klass, "note" ); } /** * Get hash. * * @return the hash */ public String getHash() { return this.mHash; } /** * Get date. * * @return the date */ public Date getDate() { return this.mDate; } /** * Get id. * * @return the id */ public Period getPeriod() { return this.mPeriod; } /** * Get subject. * * @return the subject */ public String getSubject() { return this.mSubject; } /** * Get campus name. * * @return the campusName */ public String getCampusName() { return this.mCampusName; } /** * Get department. * * @return the department */ public String getDepartment() { return this.mDepartment; } /** * Get lecturer. * * @return the lecturer */ public String getLecturer() { return this.mLecturer; } /** * Get grade. * * @return the grade */ public String getGrade() { return this.mGrade; } /** * Get message. * * @return the message */ public String getMessage() { return this.mMessage; } }
mit
cfoxleyevans/SpringMVCTemplate
src/main/java/com/chrisfoxleyevans/IndexController.java
473
package com.chrisfoxleyevans; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/") public class IndexController { @RequestMapping(method = RequestMethod.GET) @ResponseBody public String getIndex() { return "Server is active"; } }
mit
XudongFu/evolution
src/environment/IAddressable.java
222
package environment; /** * Created by 付旭东 on 2017/3/17. */ /** * 属性和函数都需要提供地址,所以将这个函数抽提为一个接口 */ public interface IAddressable { Address getAddress(); }
mit
falkoschumann/signalslot4java
src/test/java/de/muspellheim/signalslot/CounterSignalSlotTest.java
5252
/* * Copyright (c) 2013-2015 Falko Schumann <www.muspellheim.de> * Released under the terms of the MIT License. */ package de.muspellheim.signalslot; import org.junit.Test; import static org.junit.Assert.*; /** * Ported Qt simple example of signals and slots to Java. * * @author Falko Schumann &lt;falko.schumann@muspellheim.de&gt; */ public final class CounterSignalSlotTest { @Test public void testCounter() { final Counter a = new Counter(); final Counter b = new Counter(); a.valueChanged().connect(b::setValue); a.setValue(12); assertEquals(12, a.getValue()); assertEquals(12, b.getValue()); b.setValue(48); assertEquals(12, a.getValue()); assertEquals(48, b.getValue()); } @Test(expected = NullPointerException.class) public void testConnectNull() { final Counter a = new Counter(); a.valueChanged.connect(null); } @Test(expected = NullPointerException.class) public void testDisconnectNull() { final Counter a = new Counter(); a.valueChanged.disconnect(null); } @Test public void testChainSignals() { final Counter a = new Counter(); final Counter b = new Counter(); final Counter c = new Counter(); a.valueChanged().connect(b::setValue); b.valueChanged().connect(c::setValue); a.setValue(12); assertEquals(12, a.getValue()); assertEquals(12, b.getValue()); assertEquals(12, c.getValue()); } @Test public void testChainSignals_Variant() { final Signal1<String> signal1 = new Signal1<>(); final Signal1<String> signal2 = new Signal1<>(); signal1.connect(signal2); signal2.connect(s -> assertTrue("Foo".equals(s))); signal1.emit("Foo"); } @Test public void testSetSameValue_SecondTryEmitNoSignal() { final Counter a = new Counter(); final Counter b = new Counter(); final Counter c = new Counter(); a.valueChanged().connect(b::setValue); a.setValue(12); assertEquals(12, a.getValue()); assertEquals(12, b.getValue()); a.valueChanged().connect(c::setValue); a.setValue(12); assertEquals(12, a.getValue()); assertEquals(0, c.getValue()); } @Test(expected = AssertionError.class) public void testBehaviourIdentity() { final Counter a = new Counter(); final Slot1<Integer> s1 = a::setValue; final Slot1<Integer> s2 = a::setValue; assertSame(s1, s2); } @Test(expected = AssertionError.class) public void testBehaviourEquality() { final Counter a = new Counter(); final Slot1<Integer> s1 = a::setValue; final Slot1<Integer> s2 = a::setValue; assertEquals(s1, s2); } @Test public void testDisconnect() { final Counter a = new Counter(); final Counter b = new Counter(); final Slot1<Integer> slot = b::setValue; a.valueChanged().connect(slot); a.setValue(12); assertEquals(12, a.getValue()); assertEquals(12, b.getValue()); // TODO Workaround: to disconnect a slot, we must remember the method reference a.valueChanged().disconnect(slot); a.setValue(42); assertEquals(42, a.getValue()); assertEquals(12, b.getValue()); } @Test public void testDisconnect_Variant() { final Counter a = new Counter(); final Counter b = new Counter(); a.valueChanged().connect(b.setValue()); a.setValue(12); assertEquals(12, a.getValue()); assertEquals(12, b.getValue()); // TODO Workaround: to disconnect a slot, we must have reference a slot instance a.valueChanged().disconnect(b.setValue()); a.setValue(42); assertEquals(42, a.getValue()); assertEquals(12, b.getValue()); } @Test public void testBlockSignal() { final Counter a = new Counter(); final Counter b = new Counter(); a.valueChanged().connect(b::setValue); a.setValue(12); assertEquals(12, a.getValue()); assertEquals(12, b.getValue()); a.valueChanged().setBlocked(true); a.setValue(42); assertEquals(42, a.getValue()); assertEquals(12, b.getValue()); a.valueChanged().setBlocked(false); a.setValue(24); assertEquals(24, a.getValue()); assertEquals(24, b.getValue()); } /** * This class holds a integer value. */ public static final class Counter { private final Signal1<Integer> valueChanged = new Signal1<>(); private int value; private Slot1<Integer> valueSlot = this::setValue; public int getValue() { return value; } public void setValue(final int value) { if (value != this.value) { this.value = value; valueChanged().emit(value); } } public Signal1<Integer> valueChanged() { return valueChanged; } public Slot1<Integer> setValue() { return valueSlot; } } }
mit
Rojoss/Boxx
src/main/java/com/jroossien/boxx/options/single/EntityStackO.java
2688
/* * The MIT License (MIT) * * Copyright (c) 2016 Rojoss <http://jroossien.com> * Copyright (c) 2016 contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.jroossien.boxx.options.single; import com.jroossien.boxx.options.SingleOption; import com.jroossien.boxx.util.entity.EntityParser; import com.jroossien.boxx.util.entity.EntityStack; import org.bukkit.command.CommandSender; public class EntityStackO extends SingleOption<EntityStack, EntityStackO> { private Integer maxEntities = null; private boolean allowStacked = true; public EntityStackO max(Integer maxEntities) { this.maxEntities = maxEntities; return this; } public EntityStackO allowStacked(boolean allowStacked) { this.allowStacked = allowStacked; return this; } @Override public boolean parse(CommandSender sender, String input) { EntityParser parser = new EntityParser(input, sender, false, maxEntities, allowStacked); if (!parser.isValid()) { error = parser.getError(); return false; } value = parser.getEntities(); return true; } @Override public String serialize() { return serialize(getValue()); } public static String serialize(EntityStack entityStack) { return entityStack == null ? null : new EntityParser(entityStack.getBottom()).getString(); } @Override public String getTypeName() { return "EntityStack"; } @Override public EntityStackO clone() { return super.cloneData(new EntityStackO().max(maxEntities).allowStacked(allowStacked)); } }
mit
JabRef/jabref
src/main/java/org/jabref/model/pdf/search/PdfSearchResults.java
1539
package org.jabref.model.pdf.search; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; public final class PdfSearchResults { private final List<SearchResult> searchResults; public PdfSearchResults(List<SearchResult> search) { this.searchResults = Collections.unmodifiableList(search); } public PdfSearchResults() { this.searchResults = Collections.emptyList(); } public List<SearchResult> getSortedByScore() { List<SearchResult> sortedList = new ArrayList<>(searchResults); sortedList.sort((searchResult, t1) -> Float.compare(searchResult.getLuceneScore(), t1.getLuceneScore())); return Collections.unmodifiableList(sortedList); } public List<SearchResult> getSearchResults() { return this.searchResults; } public HashMap<String, List<SearchResult>> getSearchResultsByPath() { HashMap<String, List<SearchResult>> resultsByPath = new HashMap<>(); for (SearchResult result : searchResults) { if (resultsByPath.containsKey(result.getPath())) { resultsByPath.get(result.getPath()).add(result); } else { List<SearchResult> resultsForPath = new ArrayList<>(); resultsForPath.add(result); resultsByPath.put(result.getPath(), resultsForPath); } } return resultsByPath; } public int numSearchResults() { return this.searchResults.size(); } }
mit
Chirojeugd-Vlaanderen/ChiroApp
ChiroAppDev/obj/Release/android/src/mono/MonoPackageManager.java
1976
package mono; import java.io.*; import java.lang.String; import java.util.Locale; import java.util.HashSet; import java.util.zip.*; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.res.AssetManager; import android.util.Log; import mono.android.Runtime; public class MonoPackageManager { static Object lock = new Object (); static boolean initialized; public static void LoadApplication (Context context, String runtimeDataDir, String[] apks) { synchronized (lock) { if (!initialized) { System.loadLibrary("monodroid"); Locale locale = Locale.getDefault (); String language = locale.getLanguage () + "-" + locale.getCountry (); String filesDir = context.getFilesDir ().getAbsolutePath (); String cacheDir = context.getCacheDir ().getAbsolutePath (); String dataDir = context.getApplicationInfo ().dataDir + "/lib"; ClassLoader loader = context.getClassLoader (); Runtime.init ( language, apks, runtimeDataDir, new String[]{ filesDir, cacheDir, dataDir, }, loader, new java.io.File ( android.os.Environment.getExternalStorageDirectory (), "Android/data/" + context.getPackageName () + "/files/.__override__").getAbsolutePath (), MonoPackageManager_Resources.Assemblies); initialized = true; } } } public static String[] getAssemblies () { return MonoPackageManager_Resources.Assemblies; } public static String[] getDependencies () { return MonoPackageManager_Resources.Dependencies; } public static String getApiPackageName () { return MonoPackageManager_Resources.ApiPackageName; } } class MonoPackageManager_Resources { public static final String[] Assemblies = new String[]{ "OpBicak.dll", }; public static final String[] Dependencies = new String[]{ }; public static final String ApiPackageName = null; }
mit
karim/adila
database/src/main/java/adila/db/ot2d9815fgsm_alcatel20ot2d981a.java
229
// This file is automatically generated. package adila.db; /* * Alcatel * * DEVICE: OT-981_gsm * MODEL: Alcatel OT-981A */ final class ot2d9815fgsm_alcatel20ot2d981a { public static final String DATA = "Alcatel||"; }
mit
LAC-UNC/ChimpStudyCases
Barberia/src/com/resources/Barbero2.java
2532
package com.resources; import java.util.Random; import com.lac.annotations.Resource; @Resource public class Barbero2 { int n = 2; int countClientes = 0; int cantMax = 1; int cantMin = 0; Random rand = new Random(); public void sentarCliente() throws InterruptedException{ Random rand = new Random(); countClientes++; System.out.println("Barbero " + 1 + " - Sentando Cliente: " + countClientes + " Thread id: " + Thread.currentThread().getId()); Thread.sleep(rand.nextInt((1000 - 500) + 1) + 500); System.out.println("Barbero " + 1 + " - Cliente sentado: " + countClientes + " Thread id: " + Thread.currentThread().getId()); if(countClientes > cantMax ){ System.out.println("-------" + "ERROR Barbero sentando: " + countClientes + " Thread id: " + Thread.currentThread().getId() + "-------"); } } public void afeitar() throws InterruptedException{ System.out.println("Barbero " + n + " - Afeitando Cliente: " + countClientes + " Thread id: " + Thread.currentThread().getId()); Thread.sleep(rand.nextInt((5000 - 1000) + 1) + 1000); countClientes--; System.out.println("Barbero " + n + " - Termine de afeitar cliente: " + countClientes + " Thread id: " + Thread.currentThread().getId()); } public void cobrar() throws InterruptedException{ countClientes++; System.out.println("Barbero " + n + " - Cobrando Cliente: " + countClientes + " Thread id: " + Thread.currentThread().getId()); Thread.sleep(rand.nextInt((5000 - 2000) + 1) + 1000); countClientes--; System.out.println("Barbero " + n + " - Cliente Liberado: " + countClientes + " Thread id: " + Thread.currentThread().getId()); if(countClientes < cantMin ){ System.out.println("-------" + "ERROR Barbero cobrando: " + countClientes + " Thread id: " + Thread.currentThread().getId() + "-------"); } } // // public void tomarCliente(){ // countClientes++; // System.out.println("Tomando Cliente: " + countClientes + " Thread id: " + Thread.currentThread().getId()); // if(countClientes > cantMax-1 ){ // System.out.println("-------" + "ERROR Barbero: " + countClientes + " Thread id: " + Thread.currentThread().getId() + "-------"); // } // } // // public void liberarCliente(){ // countClientes--; // System.out.println("Liberando Cliente: " + countClientes + " Thread id: " + Thread.currentThread().getId()); // if(countClientes < cantMin ){ // System.out.println("-------" + "ERROR Barbero: " + countClientes + " Thread id: " + Thread.currentThread().getId() + "-------"); // } // } }
mit
plum-umd/pasket
example/gui/src/oreilly/ch05/JToggleButtonTest.java
269
package oreilly.ch05; import gov.nasa.jpf.awt.UIActionTree; import gov.nasa.jpf.util.event.Event; public class JToggleButtonTest extends UIActionTree { @Override public Event createEventTree() { return sequence( click("$Press_Me", true) ); } }
mit
PaulNoth/hackerrank
practice/java/introduction/java_static_initializer_block/Solution.java
581
import java.util.*; class Solution { private static int B; private static int H; private static boolean flag = false; static { Scanner stdin = new Scanner(System.in); B = stdin.nextInt(); H = stdin.nextInt(); flag = B > 0 && H > 0; if(!flag) { System.out.println("java.lang.Exception: Breadth and height must be positive"); } stdin.close(); } public static void main(String [] args) { if(flag){ int area = B * H; System.out.print(area); } } }
mit
Jacob-Swanson/poe4j
poe4j-gui/src/main/java/com/swandiggy/poe4j/gui/log/LogConfig.java
925
package com.swandiggy.poe4j.gui.log; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.ext.spring.ApplicationContextHolder; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author Jacob Swanson * @since 12/11/2015 */ @Configuration public class LogConfig { @Bean public ApplicationContextHolder applicationContextHolder() { return new ApplicationContextHolder(); } @Bean public static LoggerContext loggerContext() { return (LoggerContext) LoggerFactory.getILoggerFactory(); } @Bean(initMethod = "start", destroyMethod = "stop") public ObservableLogAppender logAppender(LoggerContext loggerContext) { ObservableLogAppender appender = new ObservableLogAppender(); appender.setContext(loggerContext); return appender; } }
mit
Sukora-Stas/JavaRushTasks
1.JavaSyntax/src/com/javarush/task/task09/task0913/Solution.java
958
package com.javarush.task.task09.task0913; import java.io.FileNotFoundException; import java.net.URISyntaxException; /* Исключения. Просто исключения. */ public class Solution { public static void main(String[] args) throws Exception { //напишите тут ваш код try { method1(); } catch (NullPointerException e) { } catch (FileNotFoundException e1) { } //напишите тут ваш код } public static void method1() throws NullPointerException, ArithmeticException, FileNotFoundException, URISyntaxException { int i = (int) (Math.random() * 4); if (i == 0) throw new NullPointerException(); if (i == 1) throw new ArithmeticException(); if (i == 2) throw new FileNotFoundException(); if (i == 3) throw new URISyntaxException("", ""); } }
mit
CS2103JAN2017-T09-B4/main
src/main/java/seedu/tache/storage/StorageManager.java
3735
package seedu.tache.storage; import java.io.IOException; import java.util.Optional; import java.util.logging.Logger; import com.google.common.eventbus.Subscribe; import seedu.tache.commons.core.ComponentManager; import seedu.tache.commons.core.LogsCenter; import seedu.tache.commons.events.model.TaskManagerChangedEvent; import seedu.tache.commons.events.storage.DataFileLocationChangedEvent; import seedu.tache.commons.events.storage.DataSavingExceptionEvent; import seedu.tache.commons.exceptions.DataConversionException; import seedu.tache.model.ReadOnlyTaskManager; import seedu.tache.model.UserPrefs; /** * Manages storage of Task Manager data in local storage. */ public class StorageManager extends ComponentManager implements Storage { private static final Logger logger = LogsCenter.getLogger(StorageManager.class); private TaskManagerStorage taskManagerStorage; private UserPrefsStorage userPrefsStorage; public StorageManager(TaskManagerStorage taskManagerStorage, UserPrefsStorage userPrefsStorage) { super(); this.taskManagerStorage = taskManagerStorage; this.userPrefsStorage = userPrefsStorage; } public StorageManager(String taskManagerFilePath, String userPrefsFilePath) { this(new XmlTaskManagerStorage(taskManagerFilePath), new JsonUserPrefsStorage(userPrefsFilePath)); } // ================ UserPrefs methods ============================== @Override public Optional<UserPrefs> readUserPrefs() throws DataConversionException, IOException { return userPrefsStorage.readUserPrefs(); } @Override public void saveUserPrefs(UserPrefs userPrefs) throws IOException { userPrefsStorage.saveUserPrefs(userPrefs); } // ================ TaskManager methods ============================== //@@author A0142255M /** * Updates the default file path of the task manager. * Raises a DataFileLocationChangedEvent to inform other components of this change. */ @Override public void setTaskManagerFilePath(String newPath) { assert newPath != null; this.taskManagerStorage.setTaskManagerFilePath(newPath); logger.fine("File path set as: " + newPath); raise(new DataFileLocationChangedEvent(newPath)); } //@@author @Override public String getTaskManagerFilePath() { return taskManagerStorage.getTaskManagerFilePath(); } @Override public Optional<ReadOnlyTaskManager> readTaskManager() throws DataConversionException, IOException { return readTaskManager(taskManagerStorage.getTaskManagerFilePath()); } @Override public Optional<ReadOnlyTaskManager> readTaskManager(String filePath) throws DataConversionException, IOException { logger.fine("Attempting to read data from file: " + filePath); return taskManagerStorage.readTaskManager(filePath); } @Override public void saveTaskManager(ReadOnlyTaskManager taskManager) throws IOException { saveTaskManager(taskManager, taskManagerStorage.getTaskManagerFilePath()); } @Override public void saveTaskManager(ReadOnlyTaskManager taskManager, String filePath) throws IOException { logger.fine("Attempting to write to data file: " + filePath); taskManagerStorage.saveTaskManager(taskManager, filePath); } @Override @Subscribe public void handleTaskManagerChangedEvent(TaskManagerChangedEvent event) { logger.info(LogsCenter.getEventHandlingLogMessage(event, "Local data changed, saving to file")); try { saveTaskManager(event.data); } catch (IOException e) { raise(new DataSavingExceptionEvent(e)); } } }
mit
CS2103AUG2016-T17-C3/main
src/test/java/guitests/DeleteCommandTest.java
2199
package guitests; import org.junit.Test; import seedu.task.testutil.TestTask; import seedu.task.testutil.TestUtil; import static org.junit.Assert.assertTrue; import static seedu.task.logic.commands.DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS; public class DeleteCommandTest extends TaskManagerGuiTest { @Test public void delete() { // delete the first in the list TestTask[] currentList = td.getTypicalTasks(); int targetIndex = 1; assertDeleteSuccess(targetIndex, currentList); // delete the last in the list currentList = TestUtil.removeTaskFromList(currentList, targetIndex); targetIndex = currentList.length; assertDeleteSuccess(targetIndex, currentList); // delete from the middle of the list currentList = TestUtil.removeTaskFromList(currentList, targetIndex); targetIndex = currentList.length / 2; assertDeleteSuccess(targetIndex, currentList); // invalid index commandBox.runCommand("delete " + currentList.length + 1); assertResultMessage("The task index provided is invalid"); } /** * Runs the delete command to delete the task at specified index and * confirms the result is correct. * * @param targetIndexOneIndexed * e.g. to delete the first task in the list, 1 should be given * as the target index. * @param currentList * A copy of the current list of tasks (before deletion). */ private void assertDeleteSuccess(int targetIndexOneIndexed, final TestTask[] currentList) { TestTask taskToDelete = currentList[targetIndexOneIndexed - 1]; // -1 because array uses zero indexing TestTask[] expectedRemainder = TestUtil.removeTaskFromList(currentList, targetIndexOneIndexed); commandBox.runCommand("delete " + targetIndexOneIndexed); // confirm the list now contains all previous persons except the deleted task assertTrue(taskListPanel.isListMatching(expectedRemainder)); // confirm the result message is correct assertResultMessage(String.format(MESSAGE_DELETE_TASK_SUCCESS, taskToDelete)); } }
mit
lvivasa/MuleSoft
src/test/java/PageObject/WindowsManage.java
492
package test.java.PageObject; import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class WindowsManage { private WebDriver driver; public WebDriver getAndOpenWindows(String URL){ driver=new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.get(URL); driver.manage().window().maximize(); return driver; } public void Close(){ driver.close(); } }
mit
499504777/spring-redis
redis-service/src/main/java/com/redis/exception/MyExceptionType.java
443
package com.redis.exception; public enum MyExceptionType implements ExceptionType { NO_DATA(-1,"未查询到您需要的数据"), PAID(0,"支付已成功") ; private int code; private String describe; private MyExceptionType(int code, String describe) { this.code = code; this.describe = describe; } @Override public int getCode() { return code; } @Override public String getDescribe() { return describe; } }
mit
nicoribeiro/java_efactura_uy
app/dgi/classes/reporte/KeyInfoType.java
5350
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.06.01 at 06:40:40 PM UYT // package dgi.classes.reporte; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlElementRefs; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlMixed; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.w3c.dom.Element; /** * <p>Java class for KeyInfoType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="KeyInfoType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;choice maxOccurs="unbounded"> * &lt;element ref="{http://www.w3.org/2000/09/xmldsig#}KeyName"/> * &lt;element ref="{http://www.w3.org/2000/09/xmldsig#}KeyValue"/> * &lt;element ref="{http://www.w3.org/2000/09/xmldsig#}RetrievalMethod"/> * &lt;element ref="{http://www.w3.org/2000/09/xmldsig#}X509Data"/> * &lt;element ref="{http://www.w3.org/2000/09/xmldsig#}PGPData"/> * &lt;element ref="{http://www.w3.org/2000/09/xmldsig#}SPKIData"/> * &lt;element ref="{http://www.w3.org/2000/09/xmldsig#}MgmtData"/> * &lt;any processContents='lax' namespace='##other'/> * &lt;/choice> * &lt;attribute name="Id" type="{http://www.w3.org/2001/XMLSchema}ID" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "KeyInfoType", namespace = "http://www.w3.org/2000/09/xmldsig#", propOrder = { "content" }) public class KeyInfoType { @XmlElementRefs({ @XmlElementRef(name = "PGPData", namespace = "http://www.w3.org/2000/09/xmldsig#", type = JAXBElement.class, required = false), @XmlElementRef(name = "SPKIData", namespace = "http://www.w3.org/2000/09/xmldsig#", type = JAXBElement.class, required = false), @XmlElementRef(name = "MgmtData", namespace = "http://www.w3.org/2000/09/xmldsig#", type = JAXBElement.class, required = false), @XmlElementRef(name = "X509Data", namespace = "http://www.w3.org/2000/09/xmldsig#", type = JAXBElement.class, required = false), @XmlElementRef(name = "RetrievalMethod", namespace = "http://www.w3.org/2000/09/xmldsig#", type = JAXBElement.class, required = false), @XmlElementRef(name = "KeyValue", namespace = "http://www.w3.org/2000/09/xmldsig#", type = JAXBElement.class, required = false), @XmlElementRef(name = "KeyName", namespace = "http://www.w3.org/2000/09/xmldsig#", type = JAXBElement.class, required = false) }) @XmlMixed @XmlAnyElement(lax = true) protected List<Object> content; @XmlAttribute(name = "Id") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected String id; /** * Gets the value of the content property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the content property. * * <p> * For example, to add a new item, do as follows: * <pre> * getContent().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Element } * {@link String } * {@link JAXBElement }{@code <}{@link PGPDataType }{@code >} * {@link Object } * {@link JAXBElement }{@code <}{@link SPKIDataType }{@code >} * {@link JAXBElement }{@code <}{@link String }{@code >} * {@link JAXBElement }{@code <}{@link X509DataType }{@code >} * {@link JAXBElement }{@code <}{@link RetrievalMethodType }{@code >} * {@link JAXBElement }{@code <}{@link KeyValueType }{@code >} * {@link JAXBElement }{@code <}{@link String }{@code >} * * */ public List<Object> getContent() { if (content == null) { content = new ArrayList<Object>(); } return this.content; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } }
mit
tbian7/pst
whiteboard/TernarySearchTrie.java
1092
public class TernarySearchTrie { public Node root; public void put(String s, int val) { this.root = this.put(this.root, s, 0, val); } private Node put(Node r, String s, int val) { if (r == null) { r = new Node(); if (s.length() > 0) r.middleChar = s.charAt(0); } if (s.length() == 0) { r.val = val; } else { if (r.middleChar == s.charAt(0)) { r.middle = put(r.middle, s.substring(1) val); } else if (r.middleChar < s.charAt(0)) { r.right = put(r.right, s, val); } else { r.left = put(r.left, s, val); } } return r; } public int get(String s) { Node x = this.get(this.root, s, 0); if (x == null) return -1; return x.val; } private Node get(Node r, String s) { if (r == null) return null; if (s.length() == 0) { return r; } char c = s.charAt(0); if (c == r.middleChar) { return get(r.middle, s.substring(1)); else if (c < r.middleChar) { return get(r.left, s); } else { return get(r.right, s); } } } class Node { public int val; char middleChar; Node left; Node right; Node middle; }
mit
programmerr47/discogs-api-java
src/library/com/github/programmerr47/discogs/responseobjects/marketplace/ListOrderMessages.java
2147
package library.com.github.programmerr47.discogs.responseobjects.marketplace; import library.com.github.programmerr47.discogs.responseobjects.summary.OrderMessage; import library.com.github.programmerr47.discogs.responseobjects.summary.Pagination; import library.org.json.JSONObject; import java.util.List; /** * @author Michael Spitsin * @since 2014-09-10 */ @SuppressWarnings("unused") public class ListOrderMessages { public static final String PAGINATION_TAG = "pagination"; public static final String MESSAGES_TAG = "messages"; private Pagination pagination; private List<OrderMessage> orderMessages; private ListOrderMessages(Builder builder) { this.pagination = builder.pagination; this.orderMessages = builder.orderMessages; } public Pagination getPagination() { return pagination; } public List<OrderMessage> getOrderMessages() { return orderMessages; } private static class Builder { private Pagination pagination; private List<OrderMessage> orderMessages; public Builder setPagination(Pagination pagination) { this.pagination = pagination; return this; } public Builder setOrderMessages(List<OrderMessage> orderMessages) { this.orderMessages = orderMessages; return this; } public ListOrderMessages build() { return new ListOrderMessages(this); } } /** * Creates {@link ListOrderMessages} object from its JSON Counterpart. * * @param jsonObject - given JSON object * @return new instance of listOrderMessages or null, if json is null */ public static ListOrderMessages getFromJSONObject(JSONObject jsonObject) { if (jsonObject == null) { return null; } else { return new Builder() .setPagination(Pagination.getFromJSONObject(jsonObject.optJSONObject(PAGINATION_TAG))) .setOrderMessages(OrderMessage.getFromJSONArray(jsonObject.optJSONArray(MESSAGES_TAG))) .build(); } } }
mit
DAC-2014-Equipe-3/sujet-2
sujet2/src/main/java/com/paypal/svcs/types/ap/PreapprovalDetailsResponse.java
19286
package com.paypal.svcs.types.ap; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.paypal.svcs.types.ap.AddressList; import com.paypal.svcs.types.ap.AgreementType; import com.paypal.svcs.types.ap.SenderIdentifier; import com.paypal.svcs.types.common.DayOfWeek; import com.paypal.svcs.types.common.ErrorData; import com.paypal.svcs.types.common.ResponseEnvelope; /** * The details of the Preapproval as specified in the * Preapproval operation. */ public class PreapprovalDetailsResponse{ /** * *@Required */ private ResponseEnvelope responseEnvelope; /** * *@Required */ private Boolean approved; /** * *@Required */ private String cancelUrl; /** * *@Required */ private Integer curPayments; /** * *@Required */ private Double curPaymentsAmount; /** * */ private Integer curPeriodAttempts; /** * */ private String curPeriodEndingDate; /** * *@Required */ private String currencyCode; /** * */ private Integer dateOfMonth; /** * */ private DayOfWeek dayOfWeek; /** * */ private String endingDate; /** * */ private Double maxAmountPerPayment; /** * */ private Integer maxNumberOfPayments; /** * */ private Integer maxNumberOfPaymentsPerPeriod; /** * */ private Double maxTotalAmountOfAllPayments; /** * */ private String paymentPeriod; /** * */ private String pinType; /** * *@Required */ private String returnUrl; /** * */ private String senderEmail; /** * */ private String memo; /** * *@Required */ private String startingDate; /** * *@Required */ private String status; /** * */ private String ipnNotificationUrl; /** * */ private AddressList addressList; /** * */ private String feesPayer; /** * */ private Boolean displayMaxTotalAmount; /** * */ private SenderIdentifier sender; /** * */ private AgreementType agreementType; /** * */ private List<ErrorData> error = new ArrayList<ErrorData>(); /** * Default Constructor */ public PreapprovalDetailsResponse (){ } /** * Getter for responseEnvelope */ public ResponseEnvelope getResponseEnvelope() { return responseEnvelope; } /** * Setter for responseEnvelope */ public void setResponseEnvelope(ResponseEnvelope responseEnvelope) { this.responseEnvelope = responseEnvelope; } /** * Getter for approved */ public Boolean getApproved() { return approved; } /** * Setter for approved */ public void setApproved(Boolean approved) { this.approved = approved; } /** * Getter for cancelUrl */ public String getCancelUrl() { return cancelUrl; } /** * Setter for cancelUrl */ public void setCancelUrl(String cancelUrl) { this.cancelUrl = cancelUrl; } /** * Getter for curPayments */ public Integer getCurPayments() { return curPayments; } /** * Setter for curPayments */ public void setCurPayments(Integer curPayments) { this.curPayments = curPayments; } /** * Getter for curPaymentsAmount */ public Double getCurPaymentsAmount() { return curPaymentsAmount; } /** * Setter for curPaymentsAmount */ public void setCurPaymentsAmount(Double curPaymentsAmount) { this.curPaymentsAmount = curPaymentsAmount; } /** * Getter for curPeriodAttempts */ public Integer getCurPeriodAttempts() { return curPeriodAttempts; } /** * Setter for curPeriodAttempts */ public void setCurPeriodAttempts(Integer curPeriodAttempts) { this.curPeriodAttempts = curPeriodAttempts; } /** * Getter for curPeriodEndingDate */ public String getCurPeriodEndingDate() { return curPeriodEndingDate; } /** * Setter for curPeriodEndingDate */ public void setCurPeriodEndingDate(String curPeriodEndingDate) { this.curPeriodEndingDate = curPeriodEndingDate; } /** * Getter for currencyCode */ public String getCurrencyCode() { return currencyCode; } /** * Setter for currencyCode */ public void setCurrencyCode(String currencyCode) { this.currencyCode = currencyCode; } /** * Getter for dateOfMonth */ public Integer getDateOfMonth() { return dateOfMonth; } /** * Setter for dateOfMonth */ public void setDateOfMonth(Integer dateOfMonth) { this.dateOfMonth = dateOfMonth; } /** * Getter for dayOfWeek */ public DayOfWeek getDayOfWeek() { return dayOfWeek; } /** * Setter for dayOfWeek */ public void setDayOfWeek(DayOfWeek dayOfWeek) { this.dayOfWeek = dayOfWeek; } /** * Getter for endingDate */ public String getEndingDate() { return endingDate; } /** * Setter for endingDate */ public void setEndingDate(String endingDate) { this.endingDate = endingDate; } /** * Getter for maxAmountPerPayment */ public Double getMaxAmountPerPayment() { return maxAmountPerPayment; } /** * Setter for maxAmountPerPayment */ public void setMaxAmountPerPayment(Double maxAmountPerPayment) { this.maxAmountPerPayment = maxAmountPerPayment; } /** * Getter for maxNumberOfPayments */ public Integer getMaxNumberOfPayments() { return maxNumberOfPayments; } /** * Setter for maxNumberOfPayments */ public void setMaxNumberOfPayments(Integer maxNumberOfPayments) { this.maxNumberOfPayments = maxNumberOfPayments; } /** * Getter for maxNumberOfPaymentsPerPeriod */ public Integer getMaxNumberOfPaymentsPerPeriod() { return maxNumberOfPaymentsPerPeriod; } /** * Setter for maxNumberOfPaymentsPerPeriod */ public void setMaxNumberOfPaymentsPerPeriod(Integer maxNumberOfPaymentsPerPeriod) { this.maxNumberOfPaymentsPerPeriod = maxNumberOfPaymentsPerPeriod; } /** * Getter for maxTotalAmountOfAllPayments */ public Double getMaxTotalAmountOfAllPayments() { return maxTotalAmountOfAllPayments; } /** * Setter for maxTotalAmountOfAllPayments */ public void setMaxTotalAmountOfAllPayments(Double maxTotalAmountOfAllPayments) { this.maxTotalAmountOfAllPayments = maxTotalAmountOfAllPayments; } /** * Getter for paymentPeriod */ public String getPaymentPeriod() { return paymentPeriod; } /** * Setter for paymentPeriod */ public void setPaymentPeriod(String paymentPeriod) { this.paymentPeriod = paymentPeriod; } /** * Getter for pinType */ public String getPinType() { return pinType; } /** * Setter for pinType */ public void setPinType(String pinType) { this.pinType = pinType; } /** * Getter for returnUrl */ public String getReturnUrl() { return returnUrl; } /** * Setter for returnUrl */ public void setReturnUrl(String returnUrl) { this.returnUrl = returnUrl; } /** * Getter for senderEmail */ public String getSenderEmail() { return senderEmail; } /** * Setter for senderEmail */ public void setSenderEmail(String senderEmail) { this.senderEmail = senderEmail; } /** * Getter for memo */ public String getMemo() { return memo; } /** * Setter for memo */ public void setMemo(String memo) { this.memo = memo; } /** * Getter for startingDate */ public String getStartingDate() { return startingDate; } /** * Setter for startingDate */ public void setStartingDate(String startingDate) { this.startingDate = startingDate; } /** * Getter for status */ public String getStatus() { return status; } /** * Setter for status */ public void setStatus(String status) { this.status = status; } /** * Getter for ipnNotificationUrl */ public String getIpnNotificationUrl() { return ipnNotificationUrl; } /** * Setter for ipnNotificationUrl */ public void setIpnNotificationUrl(String ipnNotificationUrl) { this.ipnNotificationUrl = ipnNotificationUrl; } /** * Getter for addressList */ public AddressList getAddressList() { return addressList; } /** * Setter for addressList */ public void setAddressList(AddressList addressList) { this.addressList = addressList; } /** * Getter for feesPayer */ public String getFeesPayer() { return feesPayer; } /** * Setter for feesPayer */ public void setFeesPayer(String feesPayer) { this.feesPayer = feesPayer; } /** * Getter for displayMaxTotalAmount */ public Boolean getDisplayMaxTotalAmount() { return displayMaxTotalAmount; } /** * Setter for displayMaxTotalAmount */ public void setDisplayMaxTotalAmount(Boolean displayMaxTotalAmount) { this.displayMaxTotalAmount = displayMaxTotalAmount; } /** * Getter for sender */ public SenderIdentifier getSender() { return sender; } /** * Setter for sender */ public void setSender(SenderIdentifier sender) { this.sender = sender; } /** * Getter for agreementType */ public AgreementType getAgreementType() { return agreementType; } /** * Setter for agreementType */ public void setAgreementType(AgreementType agreementType) { this.agreementType = agreementType; } /** * Getter for error */ public List<ErrorData> getError() { return error; } /** * Setter for error */ public void setError(List<ErrorData> error) { this.error = error; } public static com.paypal.svcs.types.ap.PreapprovalDetailsResponse createInstance(Map<String, String> map, String prefix, int index) { com.paypal.svcs.types.ap.PreapprovalDetailsResponse preapprovalDetailsResponse = null; int i = 0; if (index != -1) { if (prefix != null && prefix.length() != 0 && !prefix.endsWith(".")) { prefix = prefix + "(" + index + ")."; } } else { if (prefix != null && prefix.length() != 0 && !prefix.endsWith(".")) { prefix = prefix + "."; } } ResponseEnvelope responseEnvelope = ResponseEnvelope.createInstance(map, prefix + "responseEnvelope", -1); if (responseEnvelope != null) { preapprovalDetailsResponse = (preapprovalDetailsResponse == null) ? new com.paypal.svcs.types.ap.PreapprovalDetailsResponse() : preapprovalDetailsResponse; preapprovalDetailsResponse.setResponseEnvelope(responseEnvelope); } if (map.containsKey(prefix + "approved")) { preapprovalDetailsResponse = (preapprovalDetailsResponse == null) ? new com.paypal.svcs.types.ap.PreapprovalDetailsResponse() : preapprovalDetailsResponse; preapprovalDetailsResponse.setApproved(Boolean.valueOf(map.get(prefix + "approved"))); } if (map.containsKey(prefix + "cancelUrl")) { preapprovalDetailsResponse = (preapprovalDetailsResponse == null) ? new com.paypal.svcs.types.ap.PreapprovalDetailsResponse() : preapprovalDetailsResponse; preapprovalDetailsResponse.setCancelUrl(map.get(prefix + "cancelUrl")); } if (map.containsKey(prefix + "curPayments")) { preapprovalDetailsResponse = (preapprovalDetailsResponse == null) ? new com.paypal.svcs.types.ap.PreapprovalDetailsResponse() : preapprovalDetailsResponse; preapprovalDetailsResponse.setCurPayments(Integer.valueOf(map.get(prefix + "curPayments"))); } if (map.containsKey(prefix + "curPaymentsAmount")) { preapprovalDetailsResponse = (preapprovalDetailsResponse == null) ? new com.paypal.svcs.types.ap.PreapprovalDetailsResponse() : preapprovalDetailsResponse; preapprovalDetailsResponse.setCurPaymentsAmount(Double.valueOf(map.get(prefix + "curPaymentsAmount"))); } if (map.containsKey(prefix + "curPeriodAttempts")) { preapprovalDetailsResponse = (preapprovalDetailsResponse == null) ? new com.paypal.svcs.types.ap.PreapprovalDetailsResponse() : preapprovalDetailsResponse; preapprovalDetailsResponse.setCurPeriodAttempts(Integer.valueOf(map.get(prefix + "curPeriodAttempts"))); } if (map.containsKey(prefix + "curPeriodEndingDate")) { preapprovalDetailsResponse = (preapprovalDetailsResponse == null) ? new com.paypal.svcs.types.ap.PreapprovalDetailsResponse() : preapprovalDetailsResponse; preapprovalDetailsResponse.setCurPeriodEndingDate(map.get(prefix + "curPeriodEndingDate")); } if (map.containsKey(prefix + "currencyCode")) { preapprovalDetailsResponse = (preapprovalDetailsResponse == null) ? new com.paypal.svcs.types.ap.PreapprovalDetailsResponse() : preapprovalDetailsResponse; preapprovalDetailsResponse.setCurrencyCode(map.get(prefix + "currencyCode")); } if (map.containsKey(prefix + "dateOfMonth")) { preapprovalDetailsResponse = (preapprovalDetailsResponse == null) ? new com.paypal.svcs.types.ap.PreapprovalDetailsResponse() : preapprovalDetailsResponse; preapprovalDetailsResponse.setDateOfMonth(Integer.valueOf(map.get(prefix + "dateOfMonth"))); } if (map.containsKey(prefix + "dayOfWeek")) { preapprovalDetailsResponse = (preapprovalDetailsResponse == null) ? new com.paypal.svcs.types.ap.PreapprovalDetailsResponse() : preapprovalDetailsResponse; preapprovalDetailsResponse.setDayOfWeek(DayOfWeek.fromValue(map.get(prefix + "dayOfWeek"))); } if (map.containsKey(prefix + "endingDate")) { preapprovalDetailsResponse = (preapprovalDetailsResponse == null) ? new com.paypal.svcs.types.ap.PreapprovalDetailsResponse() : preapprovalDetailsResponse; preapprovalDetailsResponse.setEndingDate(map.get(prefix + "endingDate")); } if (map.containsKey(prefix + "maxAmountPerPayment")) { preapprovalDetailsResponse = (preapprovalDetailsResponse == null) ? new com.paypal.svcs.types.ap.PreapprovalDetailsResponse() : preapprovalDetailsResponse; preapprovalDetailsResponse.setMaxAmountPerPayment(Double.valueOf(map.get(prefix + "maxAmountPerPayment"))); } if (map.containsKey(prefix + "maxNumberOfPayments")) { preapprovalDetailsResponse = (preapprovalDetailsResponse == null) ? new com.paypal.svcs.types.ap.PreapprovalDetailsResponse() : preapprovalDetailsResponse; preapprovalDetailsResponse.setMaxNumberOfPayments(Integer.valueOf(map.get(prefix + "maxNumberOfPayments"))); } if (map.containsKey(prefix + "maxNumberOfPaymentsPerPeriod")) { preapprovalDetailsResponse = (preapprovalDetailsResponse == null) ? new com.paypal.svcs.types.ap.PreapprovalDetailsResponse() : preapprovalDetailsResponse; preapprovalDetailsResponse.setMaxNumberOfPaymentsPerPeriod(Integer.valueOf(map.get(prefix + "maxNumberOfPaymentsPerPeriod"))); } if (map.containsKey(prefix + "maxTotalAmountOfAllPayments")) { preapprovalDetailsResponse = (preapprovalDetailsResponse == null) ? new com.paypal.svcs.types.ap.PreapprovalDetailsResponse() : preapprovalDetailsResponse; preapprovalDetailsResponse.setMaxTotalAmountOfAllPayments(Double.valueOf(map.get(prefix + "maxTotalAmountOfAllPayments"))); } if (map.containsKey(prefix + "paymentPeriod")) { preapprovalDetailsResponse = (preapprovalDetailsResponse == null) ? new com.paypal.svcs.types.ap.PreapprovalDetailsResponse() : preapprovalDetailsResponse; preapprovalDetailsResponse.setPaymentPeriod(map.get(prefix + "paymentPeriod")); } if (map.containsKey(prefix + "pinType")) { preapprovalDetailsResponse = (preapprovalDetailsResponse == null) ? new com.paypal.svcs.types.ap.PreapprovalDetailsResponse() : preapprovalDetailsResponse; preapprovalDetailsResponse.setPinType(map.get(prefix + "pinType")); } if (map.containsKey(prefix + "returnUrl")) { preapprovalDetailsResponse = (preapprovalDetailsResponse == null) ? new com.paypal.svcs.types.ap.PreapprovalDetailsResponse() : preapprovalDetailsResponse; preapprovalDetailsResponse.setReturnUrl(map.get(prefix + "returnUrl")); } if (map.containsKey(prefix + "senderEmail")) { preapprovalDetailsResponse = (preapprovalDetailsResponse == null) ? new com.paypal.svcs.types.ap.PreapprovalDetailsResponse() : preapprovalDetailsResponse; preapprovalDetailsResponse.setSenderEmail(map.get(prefix + "senderEmail")); } if (map.containsKey(prefix + "memo")) { preapprovalDetailsResponse = (preapprovalDetailsResponse == null) ? new com.paypal.svcs.types.ap.PreapprovalDetailsResponse() : preapprovalDetailsResponse; preapprovalDetailsResponse.setMemo(map.get(prefix + "memo")); } if (map.containsKey(prefix + "startingDate")) { preapprovalDetailsResponse = (preapprovalDetailsResponse == null) ? new com.paypal.svcs.types.ap.PreapprovalDetailsResponse() : preapprovalDetailsResponse; preapprovalDetailsResponse.setStartingDate(map.get(prefix + "startingDate")); } if (map.containsKey(prefix + "status")) { preapprovalDetailsResponse = (preapprovalDetailsResponse == null) ? new com.paypal.svcs.types.ap.PreapprovalDetailsResponse() : preapprovalDetailsResponse; preapprovalDetailsResponse.setStatus(map.get(prefix + "status")); } if (map.containsKey(prefix + "ipnNotificationUrl")) { preapprovalDetailsResponse = (preapprovalDetailsResponse == null) ? new com.paypal.svcs.types.ap.PreapprovalDetailsResponse() : preapprovalDetailsResponse; preapprovalDetailsResponse.setIpnNotificationUrl(map.get(prefix + "ipnNotificationUrl")); } AddressList addressList = AddressList.createInstance(map, prefix + "addressList", -1); if (addressList != null) { preapprovalDetailsResponse = (preapprovalDetailsResponse == null) ? new com.paypal.svcs.types.ap.PreapprovalDetailsResponse() : preapprovalDetailsResponse; preapprovalDetailsResponse.setAddressList(addressList); } if (map.containsKey(prefix + "feesPayer")) { preapprovalDetailsResponse = (preapprovalDetailsResponse == null) ? new com.paypal.svcs.types.ap.PreapprovalDetailsResponse() : preapprovalDetailsResponse; preapprovalDetailsResponse.setFeesPayer(map.get(prefix + "feesPayer")); } if (map.containsKey(prefix + "displayMaxTotalAmount")) { preapprovalDetailsResponse = (preapprovalDetailsResponse == null) ? new com.paypal.svcs.types.ap.PreapprovalDetailsResponse() : preapprovalDetailsResponse; preapprovalDetailsResponse.setDisplayMaxTotalAmount(Boolean.valueOf(map.get(prefix + "displayMaxTotalAmount"))); } SenderIdentifier sender = SenderIdentifier.createInstance(map, prefix + "sender", -1); if (sender != null) { preapprovalDetailsResponse = (preapprovalDetailsResponse == null) ? new com.paypal.svcs.types.ap.PreapprovalDetailsResponse() : preapprovalDetailsResponse; preapprovalDetailsResponse.setSender(sender); } if (map.containsKey(prefix + "agreementType")) { preapprovalDetailsResponse = (preapprovalDetailsResponse == null) ? new com.paypal.svcs.types.ap.PreapprovalDetailsResponse() : preapprovalDetailsResponse; preapprovalDetailsResponse.setAgreementType(AgreementType.fromValue(map.get(prefix + "agreementType"))); } i = 0; while(true) { ErrorData error = ErrorData.createInstance(map, prefix + "error", i); if (error != null) { preapprovalDetailsResponse = (preapprovalDetailsResponse == null) ? new com.paypal.svcs.types.ap.PreapprovalDetailsResponse() : preapprovalDetailsResponse; preapprovalDetailsResponse.getError().add(error); i++; } else { break; } } return preapprovalDetailsResponse; } }
mit
a-wolf/depth-of-field
src/main/java/de/awolf/dof/DepthOfFieldCalculator.java
3477
package de.awolf.dof; /** * Depth of field calculation based on the formulas from wikipedia. * * @see <a href="http://en.wikipedia.org/wiki/Depth_of_field#DOF_formulas">http://en.wikipedia.org/wiki/Depth_of_field</a> */ public class DepthOfFieldCalculator { /** * Calculates hyperfocal distance, far and near limit. * * @param input input parameters * @return hyperfocal distance, far and near limit wrapped in a DofOutput object */ public DofOutput calculate(DofInput input) { double hyperfocalDistance = hyperfocalDistance(input.getfNumber(), input.getCircleOfConfusion(), input.getFocalLength()); double nearLimit = nearLimit(input.getfNumber(), input.getCircleOfConfusion(), input.getFocalLength(), input.getSubjectDistance()); double farLimit = farLimit(input.getfNumber(), input.getCircleOfConfusion(), input.getFocalLength(), input.getSubjectDistance()); return new DofOutput(hyperfocalDistance, nearLimit, farLimit); } /** * Calculates the hyperfocal distance. * * @param fNumber f-number given by focal length / diameter of the entrance pupil * @param circleOfConfusion circle of confusion in millimeter * @param focalLength focal length in millimeter * @return hyperfocal distance in millimeter */ protected double hyperfocalDistance(double fNumber, double circleOfConfusion, double focalLength) { return ((focalLength * focalLength) / (fNumber * circleOfConfusion)) + focalLength; } /** * Calculates the near limit. * * @param fNumber f-number given by focal length / diameter of the entrance pupil * @param circleOfConfusion circle of confusion in millimeter * @param focalLength focal length in millimeter * @param subjectDistance distance to subject in millimeter * @return near distance in millimeter */ protected double nearLimit(double fNumber, double circleOfConfusion, double focalLength, double subjectDistance) { double hyperfocalDistance = hyperfocalDistance(fNumber, circleOfConfusion, focalLength); double numerator = subjectDistance * (hyperfocalDistance - focalLength); double denominator = (hyperfocalDistance - focalLength) + (subjectDistance - focalLength); return numerator / denominator; } /** * Calculates the far limit. * Note: if subject distance is greater then the hyperfocal distance the far limit is infinite. * For easier usage i avoided throwing an exception and return Double.MAX_VALUE in this case. * * @param fNumber f-number given by focal length / diameter of the entrance pupil * @param circleOfConfusion circle of confusion in millimeter * @param focalLength focal length in millimeter * @param subjectDistance distance to subject in millimeter * @return far distance in millimeter */ protected double farLimit(double fNumber, double circleOfConfusion, double focalLength, double subjectDistance) { double hyperfocalDistance = hyperfocalDistance(fNumber, circleOfConfusion, focalLength); if (subjectDistance >= hyperfocalDistance) { return Double.MAX_VALUE; } else { double numerator = subjectDistance * (hyperfocalDistance - focalLength); double denominator = (hyperfocalDistance - focalLength) + (focalLength - subjectDistance); return numerator / denominator; } } }
mit
nicoribeiro/java_efactura_uy
app/dgi/soap/consultas/WSEFacturaConsultasEFACCONSULTARCFERECIBIDOSResponse.java
1831
package dgi.soap.consultas; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="Ackconsultacferecibidos" type="{http://dgi.gub.uy}ACKConsultaCFERecibidos"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "ackconsultacferecibidos" }) @XmlRootElement(name = "WS_eFactura_Consultas.EFACCONSULTARCFERECIBIDOSResponse") public class WSEFacturaConsultasEFACCONSULTARCFERECIBIDOSResponse { @XmlElement(name = "Ackconsultacferecibidos", required = true) protected ACKConsultaCFERecibidos ackconsultacferecibidos; /** * Gets the value of the ackconsultacferecibidos property. * * @return * possible object is * {@link ACKConsultaCFERecibidos } * */ public ACKConsultaCFERecibidos getAckconsultacferecibidos() { return ackconsultacferecibidos; } /** * Sets the value of the ackconsultacferecibidos property. * * @param value * allowed object is * {@link ACKConsultaCFERecibidos } * */ public void setAckconsultacferecibidos(ACKConsultaCFERecibidos value) { this.ackconsultacferecibidos = value; } }
mit
seed-0317/training
servlets/examples/servlets-example/src/main/java/com/example/filters/DogFilter.java
758
package com.example.filters; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; @WebFilter(urlPatterns={ "*.html", "/test" }) public class DogFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("DogFilter"); chain.doFilter(request, response); } @Override public void init(FilterConfig filterConfig) throws ServletException {} @Override public void destroy() {} }
mit
AlnaSoftware/eSaskaita
src/JAVA SRC/lt/registrucentras/esaskaita/service/invoice/ubl/sig/SignaturePropertyType.java
5830
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2017.07.24 at 05:36:05 PM EEST // package lt.registrucentras.esaskaita.service.invoice.ubl.sig; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlMixed; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import com.google.common.base.Objects; import org.w3c.dom.Element; /** * <p>Java class for SignaturePropertyType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="SignaturePropertyType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;choice maxOccurs="unbounded"> * &lt;any processContents='lax' namespace='##other'/> * &lt;/choice> * &lt;attribute name="Target" use="required" type="{http://www.w3.org/2001/XMLSchema}anyURI" /> * &lt;attribute name="Id" type="{http://www.w3.org/2001/XMLSchema}ID" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "SignaturePropertyType", propOrder = { "content" }) public class SignaturePropertyType implements Serializable { private final static long serialVersionUID = 1L; @XmlMixed @XmlAnyElement(lax = true) protected List<Object> content; @XmlAttribute(name = "Target", required = true) @XmlSchemaType(name = "anyURI") protected String target; @XmlAttribute(name = "Id") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected String id; /** * Default no-arg constructor * */ public SignaturePropertyType() { super(); } /** * Fully-initialising value constructor * */ public SignaturePropertyType(final List<Object> content, final String target, final String id) { this.content = content; this.target = target; this.id = id; } /** * Gets the value of the content property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the content property. * * <p> * For example, to add a new item, do as follows: * <pre> * getContent().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Element } * {@link Object } * {@link String } * * */ public List<Object> getContent() { if (content == null) { content = new ArrayList<Object>(); } return this.content; } /** * Gets the value of the target property. * * @return * possible object is * {@link String } * */ public String getTarget() { return target; } /** * Sets the value of the target property. * * @param value * allowed object is * {@link String } * */ public void setTarget(String value) { this.target = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } public SignaturePropertyType withContent(Object... values) { if (values!= null) { for (Object value: values) { getContent().add(value); } } return this; } public SignaturePropertyType withContent(Collection<Object> values) { if (values!= null) { getContent().addAll(values); } return this; } public SignaturePropertyType withTarget(String value) { setTarget(value); return this; } public SignaturePropertyType withId(String value) { setId(value); return this; } @Override public String toString() { return Objects.toStringHelper(this).add("content", content).add("target", target).add("id", id).toString(); } @Override public int hashCode() { return Objects.hashCode(content, target, id); } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null) { return false; } if (getClass()!= other.getClass()) { return false; } final SignaturePropertyType o = ((SignaturePropertyType) other); return ((Objects.equal(content, o.content)&&Objects.equal(target, o.target))&&Objects.equal(id, o.id)); } }
mit
antonlogvinenko/javelin
test-programs/javelin/MulOfIntegers.java
215
package javelin; public class MulOfIntegers { public static void main(String[] args) { int a = 3; int b = 4; int c = 5; int d = a * b * c; System.out.println(d); } }
mit
ochafik/nabab
src/main/java/com/ochafik/math/graph/impl/AbstractGraph.java
4692
/* * Copyright (C) 2006-2011 by Olivier Chafik (http://ochafik.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.ochafik.math.graph.impl; import java.util.ArrayList; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.List; import com.ochafik.math.graph.ConnectivityUtils; import com.ochafik.math.graph.EdgeSet; import com.ochafik.math.graph.Graph; import com.ochafik.math.graph.IntEdgeSet; public abstract class AbstractGraph<N extends Comparable<N>> implements Graph<N> { private final List<N> nodeList; private final boolean oriented; //protected ValuedEdgeSet<Integer> pathsLengths; protected IntEdgeSet pathsLengths; public AbstractGraph(Collection<? extends N> nodes, boolean oriented) { nodeList = new ArrayList<N>(nodes); this.oriented = oriented; } public IntEdgeSet getPathsLengths() { if (pathsLengths == null) { System.err.println("\tComputing path length global connectivity"); pathsLengths = ConnectivityUtils.computePathLengthGlobalConnectivity(getLocalConnectivity(), getNodeList().size()); } return pathsLengths; } public EdgeSet getGlobalConnectivity() { return getPathsLengths(); } protected void doAddEdge(int originIndex, int destinationIndex) { if (pathsLengths != null) { ConnectivityUtils.updatePathLengthGlobalConnectivityWithNewEdge(getPathsLengths(), originIndex, destinationIndex); } } protected void doRemoveEdge(int originIndex, int destinationIndex) { pathsLengths = null; } public List<N> getNodeList() { return Collections.unmodifiableList(nodeList); } public boolean isOriented() { return oriented; } public int getEdgeCount() { return getLocalConnectivity().size(); } public boolean hasEdge(int originIndex, int destinationIndex) { return getLocalConnectivity().contains(originIndex, destinationIndex); } public boolean hasPath(int originIndex, int destinationIndex) { return getGlobalConnectivity().contains(originIndex, destinationIndex); } public int getVertexCount() { return nodeList.size(); } public boolean isConnex() { return getLocalConnectivity().isConnex(); } public boolean isAcyclic() { int nodeCount = getVertexCount(); for (int node = nodeCount; node-- != 0;) { if (hasPath(node, node)) return false; } return true; } public boolean isTree() { if (!(isAcyclic() && isOriented())) return false; return isConnex(); } /** * Search in breadth first * @param originIndex * @param destinationIndex * @return length of shorted path between originIndex and destinationIndex (where a->b->c has length 3) */ public int computeShortestPathLength(int originIndex, int destinationIndex, int minimumLength) { int nNodes = getVertexCount(); BitSet isForbiddenNode = new BitSet(nNodes), isNextNode = new BitSet(nNodes), isNextNode2 = new BitSet(nNodes); isNextNode.set(originIndex); int currentLength = 1; int nNextNodes; do { nNextNodes = 0; currentLength++; for (int node = nNodes; node-- != 0;) { if (isNextNode.get(node)) { isNextNode.clear(node); isForbiddenNode.set(node); for (int nextNode : getLocalConnectivity().getEnds(node).toArray()) { if (nextNode == destinationIndex && currentLength >= minimumLength) { return currentLength; } else if (!isForbiddenNode.get(nextNode)) { isNextNode2.set(nextNode); nNextNodes++; } } } } // permute isNextNode and isNextNode2 BitSet t = isNextNode; isNextNode = isNextNode2; isNextNode2 = t; } while (nNextNodes > 0); return -1; } }
mit
krtt/oop
p2/hmw/Pract2a4p4_Methods.java
1165
public class Pract2a4p4_Methods { static int myMethod(int x1, int x2){ // signature: myMethod(int, int) return x1 + x2; } static double myMethod(double x){ // signature: myMethod(double) return Math.round(x*x); } static void myMethod(String s, int x){ // signature: myMethod(String, int) for (int i=0; i<x; i++) { System.out.print(s); } } public static void main(String[] args){ System.out.println("My method 1: " + myMethod(1, 2)); System.out.println("My method 2: " + myMethod(4)); System.out.print("My method 3: "); myMethod("lammas", 3); /* * book example - methods in a class: class KolmArvu { static double korrutaKolmArvu(double a, double b, double c){ return a*b*c; } static void valjasta(double a, double b, double c){ System.out.println("Antud arvud: " + a + ", " + b + ", " + c); } public static void main(String[] args) { double x = 1.5; double y = 2.25; double z = 3; valjasta(x, y, z); System.out.println("Nende korrutis: " + korrutaKolmArvu(x, y, z)); } } * */ } }
mit
GurudathReddy/stock-market-game
src/main/java/com/vsm/stockmarket/exception/BaseException.java
173
package com.vsm.stockmarket.exception; public class BaseException extends Exception { public BaseException(Exception e) { super(e); } public BaseException() { } }
mit
TomChen001/java-pattern
src/main/java/com/ikaimen/pattern/ProxyPattern/DynamlcProxy/MyInvocationHandler.java
604
package com.ikaimen.pattern.ProxyPattern.DynamlcProxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; /** * Created by ChenTao on 2017/7/15. * 动态代理handler类 */ public class MyInvocationHandler implements InvocationHandler{ //被代理的对象 private Object target = null; //通过构造函数传递一个对象 public MyInvocationHandler(Object o){ this.target = o; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return method.invoke(this.target,args); } }
mit
ZonCon/Ecommerce-Retronight-Android
app/src/main/java/com/megotechnologies/ecommerce_retronight/loading/ThreadStreams.java
18119
package com.megotechnologies.ecommerce_retronight.loading; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.BasicHttpParams; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.os.Looper; import com.megotechnologies.ecommerce_retronight.MainActivity; import com.megotechnologies.ecommerce_retronight.db.DbConnection; import com.megotechnologies.ecommerce_retronight.utilities.MLog; public class ThreadStreams extends Thread{ int CONN_TIMEOUT = 2000; int SOCK_TIMEOUT = 2000; String myCountryId = null; String myStateId = null; String myCityId = null; DbConnection dbC; public ThreadStreams(String idCountry, String idState, String idCity, DbConnection conn) { // TODO Auto-generated constructor stub myCountryId = idCountry; myStateId = idState; myCityId = idCity; dbC = conn; } @Override public void run() { // TODO Auto-generated method stub super.run(); MLog.log("Starting Stream thread.. "); Looper.prepare(); Thread t = Thread.currentThread(); String tName = t.getName(); String jsonStr = ""; HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. int timeoutConnection = CONN_TIMEOUT; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = SOCK_TIMEOUT; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpClient httpclient = new DefaultHttpClient(httpParameters); HttpPost httppost = null; httppost = new HttpPost(MainActivity.API_STREAMS); jsonStr = "[{\"idProject\": \"" + MainActivity.PID + "\", \"idCountry\": \"" + myCountryId + "\", \"idState\": \"" + myStateId + "\", \"idCity\": \"" + myCityId + "\"}]"; List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("params", jsonStr)); MLog.log("Stream API=" + jsonStr); String responseString = null; try { httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); out.close(); responseString = out.toString(); MLog.log(responseString); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { } if(responseString != null) { jsonStr = responseString; try { JSONObject jsonObj = new JSONObject(jsonStr); if(jsonObj.getString("result").equals("success")) { if(dbC.isOpen()) { dbC.isAvailale(); dbC.clearDynamicRecords(); } String valueStr = jsonObj.getString("value"); JSONArray jsonArr = new JSONArray(valueStr); for(int i = 0; i < jsonArr.length(); i++) { jsonObj = jsonArr.getJSONObject(i); if(jsonObj.has("productstream")) { JSONObject jsonObjStream = jsonObj.getJSONObject("productstream"); String idStreamContainer = jsonObjStream.getString("idProductstreamContainer"); String nameStream = jsonObjStream.getString("name"); MLog.log("Namestream " + nameStream); HashMap<String, String> map = new HashMap<String, String>(); map.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_STREAM); map.put(MainActivity.DB_COL_NAME, nameStream); map.put(MainActivity.DB_COL_SRV_ID, idStreamContainer); String _idStream = null; if(dbC.isOpen()) { dbC.isAvailale(); dbC.insertRecord(map); _idStream = dbC.retrieveId(map); } JSONArray jsonArrProductItems = jsonObj.getJSONArray("productitems"); for(int j = 0; j < jsonArrProductItems.length(); j++) { JSONObject jsonObjItems = jsonArrProductItems.getJSONObject(j).getJSONObject("items"); JSONArray jsonArrPictures = jsonArrProductItems.getJSONObject(j).getJSONArray("pictures"); JSONArray jsonArrUrls = jsonArrProductItems.getJSONObject(j).getJSONArray("urls"); JSONArray jsonArrLocations = jsonArrProductItems.getJSONObject(j).getJSONArray("locations"); JSONArray jsonArrContacts = jsonArrProductItems.getJSONObject(j).getJSONArray("contacts"); JSONArray jsonArrAttachments = jsonArrProductItems.getJSONObject(j).getJSONArray("attachments"); String priceMapped = jsonArrProductItems.getJSONObject(j).getString("price"); String discountMapped = jsonArrProductItems.getJSONObject(j).getString("discount"); String idSrvProductitems = jsonObjItems.getString("idProductitems"); String title = jsonObjItems.getString("title").replace("'", "''"); String subTitle = jsonObjItems.getString("subtitle").replace("'", "''"); String content = jsonObjItems.getString("content").replace("'", "''"); String timestamp = jsonObjItems.getString("timestampPublish"); String stock = jsonObjItems.getString("stockCurrent"); String size = jsonObjItems.getString("size"); String weight = jsonObjItems.getString("weight"); String sku = jsonObjItems.getString("sku"); String price = jsonObjItems.getString("price"); String extra1 = jsonObjItems.getString("extra1").replace("'", "''"); String extra2 = jsonObjItems.getString("extra2").replace("'", "''"); String extra3 = jsonObjItems.getString("extra3").replace("'", "''"); String extra4 = jsonObjItems.getString("extra4").replace("'", "''"); String extra5 = jsonObjItems.getString("extra5").replace("'", "''"); String extra6 = jsonObjItems.getString("extra6").replace("'", "''"); String extra7 = jsonObjItems.getString("extra7").replace("'", "''"); String extra8 = jsonObjItems.getString("extra8").replace("'", "''"); String extra9 = jsonObjItems.getString("extra9").replace("'", "''"); String extra10 = jsonObjItems.getString("extra10").replace("'", "''"); String booking = jsonObjItems.getString("bookingPrice"); String discount = jsonObjItems.getString("Discounts_idDiscounts"); if(!priceMapped.equals("-1")) { price = priceMapped; } if(!discountMapped.equals("-1")) { discount = discountMapped; } map = new HashMap<String, String>(); map.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_ITEM); map.put(MainActivity.DB_COL_TITLE, title); map.put(MainActivity.DB_COL_SRV_ID, idSrvProductitems); map.put(MainActivity.DB_COL_SUB, subTitle); map.put(MainActivity.DB_COL_CONTENT, content); map.put(MainActivity.DB_COL_TIMESTAMP, timestamp); map.put(MainActivity.DB_COL_STOCK, stock); map.put(MainActivity.DB_COL_SIZE, size); map.put(MainActivity.DB_COL_WEIGHT, weight); map.put(MainActivity.DB_COL_SKU, sku); map.put(MainActivity.DB_COL_PRICE, price); map.put(MainActivity.DB_COL_FOREIGN_KEY, _idStream); map.put(MainActivity.DB_COL_EXTRA_1, extra1); map.put(MainActivity.DB_COL_EXTRA_2, extra2); map.put(MainActivity.DB_COL_EXTRA_3, extra3); map.put(MainActivity.DB_COL_EXTRA_4, extra4); map.put(MainActivity.DB_COL_EXTRA_5, extra5); map.put(MainActivity.DB_COL_EXTRA_6, extra6); map.put(MainActivity.DB_COL_EXTRA_7, extra7); map.put(MainActivity.DB_COL_EXTRA_8, extra8); map.put(MainActivity.DB_COL_EXTRA_9, extra9); map.put(MainActivity.DB_COL_EXTRA_10, extra10); map.put(MainActivity.DB_COL_BOOKING, booking); map.put(MainActivity.DB_COL_DISCOUNT, discount); String _idItem = null; if(dbC.isOpen()) { dbC.isAvailale(); dbC.insertRecord(map); map = new HashMap<String, String>(); map.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_ITEM); map.put(MainActivity.DB_COL_SRV_ID, idSrvProductitems); map.put(MainActivity.DB_COL_TIMESTAMP, timestamp); map.put(MainActivity.DB_COL_FOREIGN_KEY, _idStream); _idItem = dbC.retrieveId(map); } MLog.log("Title=" + title + ", Pictures=" + jsonArrPictures.length() + ",_id=" + _idItem); if(jsonArrPictures.length() > 0) { for(int k = 0; k < jsonArrPictures.length(); k++) { JSONObject jsonObjPicture = jsonArrPictures.getJSONObject(k); String pathOrig = jsonObjPicture.getString("pathOriginal"); String pathProc = jsonObjPicture.getString("pathProcessed"); String pathTh = jsonObjPicture.getString("pathThumbnail"); String[] strArrOrig = pathOrig.split("/"); String[] strArrProc = pathProc.split("/"); String[] strArrTh = pathTh.split("/"); map = new HashMap<String, String>(); map.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_PICTURE); map.put(MainActivity.DB_COL_PATH_ORIG, strArrOrig[strArrOrig.length - 1]); map.put(MainActivity.DB_COL_PATH_PROC, strArrProc[strArrProc.length - 1]); map.put(MainActivity.DB_COL_PATH_TH, strArrTh[strArrTh.length - 1]); map.put(MainActivity.DB_COL_FOREIGN_KEY, _idItem); if(dbC.isOpen()) { dbC.isAvailale(); dbC.insertRecord(map); } } } if(jsonArrUrls.length() > 0) { for(int k = 0; k < jsonArrUrls.length(); k++) { JSONObject jsonObjUrl = jsonArrUrls.getJSONObject(k); String caption = jsonObjUrl.getString("caption"); String value = jsonObjUrl.getString("value"); map = new HashMap<String, String>(); map.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_URL); map.put(MainActivity.DB_COL_CAPTION, caption); map.put(MainActivity.DB_COL_URL, value); map.put(MainActivity.DB_COL_FOREIGN_KEY, _idItem); if(dbC.isOpen()) { dbC.isAvailale(); dbC.insertRecord(map); } } } if(jsonArrAttachments.length() > 0) { for(int k = 0; k < jsonArrAttachments.length(); k++) { JSONObject jsonObjAttachment = jsonArrAttachments.getJSONObject(k); String caption = jsonObjAttachment.getString("caption"); String value = jsonObjAttachment.getString("path"); map = new HashMap<String, String>(); map.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_ATTACHMENT); map.put(MainActivity.DB_COL_CAPTION, caption); map.put(MainActivity.DB_COL_URL, value); map.put(MainActivity.DB_COL_FOREIGN_KEY, _idItem); if(dbC.isOpen()) { dbC.isAvailale(); dbC.insertRecord(map); } } } if(jsonArrLocations.length() > 0) { for(int k = 0; k < jsonArrLocations.length(); k++) { JSONObject jsonObjLocation = jsonArrLocations.getJSONObject(k); String caption = jsonObjLocation.getString("caption"); String location = jsonObjLocation.getString("location"); map = new HashMap<String, String>(); map.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_LOCATION); map.put(MainActivity.DB_COL_CAPTION, caption); map.put(MainActivity.DB_COL_LOCATION, location); map.put(MainActivity.DB_COL_FOREIGN_KEY, _idItem); if(dbC.isOpen()) { dbC.isAvailale(); dbC.insertRecord(map); } } } if(jsonArrContacts.length() > 0) { for(int k = 0; k < jsonArrContacts.length(); k++) { JSONObject jsonObjContact = jsonArrContacts.getJSONObject(k); String name = jsonObjContact.getString("name"); String email = jsonObjContact.getString("email"); String phone = jsonObjContact.getString("phone"); map = new HashMap<String, String>(); map.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_CONTACT); map.put(MainActivity.DB_COL_NAME, name); map.put(MainActivity.DB_COL_EMAIL, email); map.put(MainActivity.DB_COL_PHONE, phone); map.put(MainActivity.DB_COL_FOREIGN_KEY, _idItem); if(dbC.isOpen()) { dbC.isAvailale(); dbC.insertRecord(map); } } } } } else if(jsonObj.has("discounts")) { JSONArray jsonObjDiscountArr = jsonObj.getJSONArray("discounts"); for(int j = 0; j < jsonObjDiscountArr.length(); j++) { JSONObject jsonObjDiscount = jsonObjDiscountArr.getJSONObject(j); String idDiscounts = jsonObjDiscount.getString("idDiscounts"); String code = jsonObjDiscount.getString("code").replace("'", "''"); String type = jsonObjDiscount.getString("type"); String timestamp = jsonObjDiscount.getString("timestamp"); String value = jsonObjDiscount.getString("value"); HashMap<String, String> map = new HashMap<String, String>(); map.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_DISCOUNT); map.put(MainActivity.DB_COL_NAME, code); map.put(MainActivity.DB_COL_TITLE, type); map.put(MainActivity.DB_COL_TIMESTAMP, timestamp); map.put(MainActivity.DB_COL_PRICE, value); map.put(MainActivity.DB_COL_SRV_ID, idDiscounts); if(dbC.isOpen()) { dbC.isAvailale(); dbC.insertRecord(map); } } } else if(jsonObj.has("coupons")) { JSONArray jsonObjCouponArr = jsonObj.getJSONArray("coupons"); for(int j = 0; j < jsonObjCouponArr.length(); j++) { JSONObject jsonObjCoupon = jsonObjCouponArr.getJSONObject(j); String idCoupons = jsonObjCoupon.getString("idCoupons"); String code = jsonObjCoupon.getString("code").replace("'", "''"); String type = jsonObjCoupon.getString("type"); String timestamp = jsonObjCoupon.getString("timestamp"); String value = jsonObjCoupon.getString("value"); String allowDouble = jsonObjCoupon.getString("allowDoubleDiscounting"); String maxVal = jsonObjCoupon.getString("maxVal"); String minPurchase = jsonObjCoupon.getString("minPurchase"); HashMap<String, String> map = new HashMap<String, String>(); map.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_COUPON); map.put(MainActivity.DB_COL_NAME, code); map.put(MainActivity.DB_COL_TITLE, type); map.put(MainActivity.DB_COL_TIMESTAMP, timestamp); map.put(MainActivity.DB_COL_PRICE, value); map.put(MainActivity.DB_COL_CAPTION, allowDouble); map.put(MainActivity.DB_COL_SRV_ID, idCoupons); map.put(MainActivity.DB_COL_EXTRA_1, maxVal); map.put(MainActivity.DB_COL_EXTRA_2, minPurchase); MLog.log("Coupon Found inserting " + maxVal + " " + minPurchase); if(dbC.isOpen()) { dbC.isAvailale(); dbC.insertRecord(map); } } } else if(jsonObj.has("taxes")) { try { JSONObject jsonObjCoupon = jsonObj.getJSONObject("taxes"); String taxLabel1 = jsonObjCoupon.getString("taxLabel1").replace("'", "''"); String taxValue1 = jsonObjCoupon.getString("taxValue1"); String taxLabel2 = jsonObjCoupon.getString("taxLabel2").replace("'", "''"); String taxValue2 = jsonObjCoupon.getString("taxValue2"); if(taxValue1.length() > 0 && taxLabel1.length() > 0) { if(!taxLabel1.equals("null") && !taxValue1.equals("null")) { double d = Double.parseDouble(taxValue1); HashMap<String, String> map = new HashMap<String, String>(); map.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_COUPON); map.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_TAX_1); map.put(MainActivity.DB_COL_TITLE, taxLabel1); map.put(MainActivity.DB_COL_SUB, taxValue1); if(dbC.isOpen()) { dbC.isAvailale(); dbC.insertRecord(map); } } } if(taxValue2.length() > 0 && taxLabel2.length() > 0) { if(!taxLabel2.equals("null") && !taxValue2.equals("null")) { double d = Double.parseDouble(taxValue1); HashMap<String, String> map = new HashMap<String, String>(); map.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_COUPON); map.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_TAX_2); map.put(MainActivity.DB_COL_TITLE, taxLabel2); map.put(MainActivity.DB_COL_SUB, taxValue2); if(dbC.isOpen()) { dbC.isAvailale(); dbC.insertRecord(map); } } } } catch (NumberFormatException e) { e.printStackTrace(); } } } if(dbC.isOpen()) { dbC.isAvailale(); dbC.printRecords(); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
cc0-1.0
CuriousSkeptic/ElementalEssences
src/main/java/com/elementalessence/api/rewind/BlockData.java
442
package com.elementalessence.api.rewind; import net.minecraft.block.Block; public class BlockData { public Block block; public int meta; public BlockData(Block b, int m) { block = b; meta = m; if (m > 16 || m < 0) meta = 0; } @Override public boolean equals(Object o) { if (!(o instanceof BlockData)) return false; if (((BlockData) o).block != block || ((BlockData) o).meta != meta) return false; return true; } }
cc0-1.0
CodeFX-org/demo-java-9
src/main/java/org/codefx/demo/java9/internal/string/CompactionPerformance.java
1447
package org.codefx.demo.java9.internal.string; import java.util.List; import java.util.stream.IntStream; import static java.util.stream.Collectors.toList; public class CompactionPerformance { // To play around with this: // (1) compile using `compile.sh` // (2) run with either of the following lines // // WITH COMPACT STRINGS (enabled by default): // java9 -cp out org.codefx.demo.java9.internal.string.CompactionPerformance // // WITHOUT COMPACT STRINGS: // java9 -cp out -XX:-CompactStrings org.codefx.demo.java9.internal.string.CompactionPerformance // // This is just for fun! Use JMH for a serious/reliable performance examination. public static void main(String[] args) throws InterruptedException { // time to connect profiler (at least JVisualVM doesn't want to :( ) // Thread.sleep(5_000); long launchTime = System.currentTimeMillis(); List<String> strings = IntStream.rangeClosed(1, 10_000_000) .mapToObj(Integer::toString) .collect(toList()); long runTime = System.currentTimeMillis() - launchTime; System.out.println("Generated " + strings.size() + " strings in " + runTime + " ms."); launchTime = System.currentTimeMillis(); String appended = strings.stream() .limit(100_000) .reduce("", (left, right) -> left + right); runTime = System.currentTimeMillis() - launchTime; System.out.println("Created string of length " + appended.length() + " in " + runTime + " ms."); } }
cc0-1.0
iCONEXT/SMI_Travel
src/java/com/smi/travel/datalayer/service/ProductService.java
4988
/* * 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.smi.travel.datalayer.service; import com.smi.travel.datalayer.dao.MListItemDao; import com.smi.travel.datalayer.dao.ProductDao; import com.smi.travel.datalayer.dao.ProductDetailDao; import com.smi.travel.datalayer.entity.MProductType; import com.smi.travel.datalayer.entity.Product; import com.smi.travel.datalayer.entity.ProductDetail; import com.smi.travel.datalayer.view.dao.ProductPriceDetailDao; import com.smi.travel.datalayer.view.entity.ProductPriceDetail; import java.util.List; /** * * @author Surachai */ public class ProductService { private ProductDao productDao; private ProductDetailDao productdetailDao; private MListItemDao listItemDao; private ProductPriceDetailDao productPriceDetailDao; public String validateProduct(Product Vproduct, String operation) { String validate = ""; Product product = new Product(); // product.setName(Vproduct.getName()); product.setCode(Vproduct.getCode()); List<Product> list = productDao.validateProduct(product); if (list != null) { if ("update".equalsIgnoreCase(operation)) { System.out.println(list.get(0).getId() +" , "+Vproduct.getId()); if (!(list.get(0).getId().equalsIgnoreCase(Vproduct.getId()))) { validate = "product code already exist"; } } else { validate = "product code already exist"; } } // product.setName(Vproduct.getName()); // product.setCode(null); // list = productDao.searchProduct(product, 1); // if (list != null) { // if ("update".equalsIgnoreCase(operation)) { // if (!(list.get(0).getId().equalsIgnoreCase(Vproduct.getId()))) { // validate = "product name already exist"; // } // } else { // validate = "product name already exist"; // } // } return validate; } public Product getProductFromcode(String productCode){ return productDao.getProductFromCode(productCode); } public List<ProductPriceDetail> getListProductPriceDetail(ProductPriceDetail productPriceDetail,int option){ return productPriceDetailDao.getListProductPriceDetail(productPriceDetail, option); } public ProductPriceDetail getListProductPriceDetailFromID(String productID){ return productPriceDetailDao.getListProductPriceDetailFromID(productID); } public List<Product> searchProduct(Product product, int option) { return productDao.searchProduct(product, option); } public int insertProduct(Product product) { return productDao.insertProduct(product); } public int updateProduct(Product product) { return productDao.updateProduct(product); } public int deleteProduct(Product product) { return productDao.DeleteProduct(product); } public int insertProductDetail(ProductDetail priceitem) { return productdetailDao.insertProductDetail(priceitem); } public int updateProductDetail(ProductDetail priceitem) { return productdetailDao.updateProductDetail(priceitem); } public int deleteProductDetail(ProductDetail priceitem) { return productdetailDao.DeleteProductDetail(priceitem); } public Product getProductFromID(String ProductID){ return productDao.getProductFromID(ProductID); } public List<MProductType> getListMasterProductType() { return listItemDao.getListMasterProductType(); } public ProductDao getProductDao() { return productDao; } public void setProductDao(ProductDao productDao) { this.productDao = productDao; } public ProductDetailDao getProductdetailDao() { return productdetailDao; } public void setProductdetailDao(ProductDetailDao productdetailDao) { this.productdetailDao = productdetailDao; } public MListItemDao getListItemDao() { return listItemDao; } public void setListItemDao(MListItemDao listItemDao) { this.listItemDao = listItemDao; } public ProductPriceDetailDao getProductPriceDetailDao() { return productPriceDetailDao; } public void setProductPriceDetailDao(ProductPriceDetailDao productPriceDetailDao) { this.productPriceDetailDao = productPriceDetailDao; } public String checkProductIsStock(String productId) { return productdetailDao.checkProductIsStock(productId); } }
cc0-1.0
sebhoss/memoization.java
memoization-guava/src/test/java/de/xn__ho_hia/memoization/guava/GuavaCacheBasedToLongFunctionMemoizerTest.java
3227
/* * This file is part of memoization.java. It is subject to the license terms in the LICENSE file found in the top-level * directory of this distribution and at http://creativecommons.org/publicdomain/zero/1.0/. No part of memoization.java, * including this file, may be copied, modified, propagated, or distributed except according to the terms contained * in the LICENSE file. */ package de.xn__ho_hia.memoization.guava; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.any; import java.util.concurrent.ExecutionException; import java.util.function.Function; import java.util.function.ToLongFunction; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mockito; import de.xn__ho_hia.memoization.shared.MemoizationException; import de.xn__ho_hia.quality.suppression.CompilerWarnings; /** * * */ @SuppressWarnings({ CompilerWarnings.NLS, CompilerWarnings.STATIC_METHOD }) public class GuavaCacheBasedToLongFunctionMemoizerTest { /** Captures expected exceptions. */ @Rule public ExpectedException thrown = ExpectedException.none(); /** * */ @Test public void shouldAcceptLoadingCache() { // given final ToLongFunction<String> function = a -> 123; final Function<String, String> keyFunction = Function.identity(); final Cache<String, Long> cache = CacheBuilder.newBuilder().build(); // when final GuavaCacheBasedToLongFunctionMemoizer<String, String> memoizer = new GuavaCacheBasedToLongFunctionMemoizer<>( cache, keyFunction, function); // then Assert.assertNotNull(memoizer); } /** * */ @Test public void shouldTransformInput() { // given final ToLongFunction<String> function = a -> 123; final Function<String, String> keyFunction = Function.identity(); final Cache<String, Long> cache = CacheBuilder.newBuilder().build(); // when final GuavaCacheBasedToLongFunctionMemoizer<String, String> memoizer = new GuavaCacheBasedToLongFunctionMemoizer<>( cache, keyFunction, function); // then Assert.assertEquals("Memoized value does not match expectation", 123, memoizer.applyAsLong("test")); } /** * @throws ExecutionException * Added for the call to 'cache.get(..)'. */ @Test @SuppressWarnings(CompilerWarnings.UNCHECKED) public void shouldWrapExecutionExceptionInMemoizationException() throws ExecutionException { // given final Function<String, String> keyFunction = Function.identity(); final Cache<String, Long> cache = Mockito.mock(Cache.class); given(cache.get(any(), any())).willThrow(ExecutionException.class); final GuavaCacheBasedToLongFunctionMemoizer<String, String> memoizer = new GuavaCacheBasedToLongFunctionMemoizer<>( cache, keyFunction, null); // when thrown.expect(MemoizationException.class); // then memoizer.applyAsLong("test"); } }
cc0-1.0
colinpalmer/dawnsci
org.eclipse.dawnsci.plotting.examples/src/org/eclipse/dawnsci/plotting/examples/XYUpdateExample.java
4395
/*- ******************************************************************************* * Copyright (c) 2011, 2014 Diamond Light Source Ltd. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Matthew Gerring - initial API and implementation and/or initial documentation *******************************************************************************/ package org.eclipse.dawnsci.plotting.examples; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.dawnsci.analysis.api.dataset.IDataset; import org.eclipse.dawnsci.analysis.dataset.impl.DoubleDataset; import org.eclipse.dawnsci.plotting.api.PlotType; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; /** * View which creates a sector selection region * and listens to that region moving. * * @author Matthew Gerring * */ public class XYUpdateExample extends PlotExample { private boolean buttonPressed = false; public void createExampleContent(Composite parent) { parent.setLayout(new GridLayout(1, false)); try { final Composite buttons = new Composite(parent, SWT.NONE); buttons.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); buttons.setLayout(new GridLayout(2, false)); // We create a button which when pressed, does updates final Button updates = new Button(buttons, SWT.CHECK); updates.setText("Append data every 200ms"); updates.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false)); final Button clear = new Button(buttons, SWT.PUSH); clear.setText("Reset"); clear.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false)); // We create a basic plot system.createPlotPart(parent, "XY Update Example", getViewSite().getActionBars(), PlotType.XY, this); system.getPlotComposite().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); // Make 3x100 values of first order List<IDataset> ys = getInitialData(); // Plot them system.createPlot1D(null, ys, new NullProgressMonitor()); // Add a listener to append data updates.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e){ buttonPressed = updates.getSelection(); if (!updates.getSelection()) return; // Or better with an Eclipse job... createUpdateThread(); } }); clear.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e){ buttonPressed = false; updates.setSelection(false); // Removed the last updated plots system.clear(); system.createPlot1D(null, getInitialData(), new NullProgressMonitor()); } }); } catch (Throwable ne) { ne.printStackTrace(); // Or your favourite logging. } } protected void createUpdateThread() { Thread thread = new Thread(new Runnable() { public void run() { while(buttonPressed) { try { // Thread safe update of y for (int n=2; n<5; ++n) { int size = system.getTrace("y"+n).getData().getSize(); system.append("y"+n, size, Math.pow(size*n, 2), new NullProgressMonitor()); } system.repaint(true); } catch (Exception e) { e.printStackTrace(); // Or your favourite logging. } finally { try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); // Or your favourite logging. } } } } }); thread.setDaemon(true); thread.start(); } private List<IDataset> getInitialData() { List<IDataset> ys = new ArrayList<IDataset>(3); for (int n=2; n<5; ++n) { double[] data = new double[100]; for (int i = 0; i < data.length; i++) data[i] = Math.pow(i*n, 2); IDataset y = new DoubleDataset(data, data.length); y.setName("y"+n); ys.add(y); } return ys; } @Override protected String getFileName() { return null; // Not file data } }
epl-1.0
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/platform/xml/XMLParser.java
2493
/******************************************************************************* * Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.platform.xml; import java.io.File; import java.io.InputStream; import java.io.Reader; import java.net.URL; import javax.xml.transform.Source; import javax.xml.validation.Schema; import org.w3c.dom.Document; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; public interface XMLParser { public static final int NONVALIDATING = 0; public static final int DTD_VALIDATION = 2; public static final int SCHEMA_VALIDATION = 3; public void setNamespaceAware(boolean isNamespaceAware); public void setWhitespacePreserving(boolean isWhitespacePreserving); public int getValidationMode(); public void setValidationMode(int validationMode); public EntityResolver getEntityResolver(); public void setEntityResolver(EntityResolver entityResolver); public ErrorHandler getErrorHandler(); public void setErrorHandler(ErrorHandler errorHandler); public void setXMLSchema(URL url) throws XMLPlatformException; public void setXMLSchemas(Object[] schemas) throws XMLPlatformException; public void setXMLSchema(Schema schema) throws XMLPlatformException; public Schema getXMLSchema() throws XMLPlatformException; public Document parse(InputSource inputSource) throws XMLPlatformException; public Document parse(File file) throws XMLPlatformException; public Document parse(InputStream inputStream) throws XMLPlatformException; public Document parse(Reader reader) throws XMLPlatformException; public Document parse(Source source) throws XMLPlatformException; public Document parse(URL url) throws XMLPlatformException; }
epl-1.0
tobiasbaum/reviewtool
de.setsoftware.reviewtool.core/src/de/setsoftware/reviewtool/model/changestructure/TourElement.java
954
package de.setsoftware.reviewtool.model.changestructure; import java.util.List; import de.setsoftware.reviewtool.model.api.IClassification; /** * Super type for elements that can be contained in a review tour. */ public abstract class TourElement { protected abstract void fillStopsInto(List<Stop> buffer); public abstract IClassification[] getClassification(); /** * Returns a string with the classifications of this element. * Adds a line break to the end when there are classifications. */ public final String getClassificationFormatted() { final IClassification[] cl = this.getClassification(); if (cl.length == 0) { return ""; } final StringBuilder ret = new StringBuilder(cl[0].getName()); for (int i = 1; i < cl.length; i++) { ret.append(", ").append(cl[i].getName()); } ret.append('\n'); return ret.toString(); } }
epl-1.0
sleshchenko/che
ide/che-core-ide-ui/src/test/java/org/eclipse/che/ide/ui/dialogs/input/InputDialogPresenterTest.java
6584
/* * Copyright (c) 2012-2018 Red Hat, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation */ package org.eclipse.che.ide.ui.dialogs.input; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.eclipse.che.ide.ui.UILocalizationConstant; import org.eclipse.che.ide.ui.dialogs.BaseTest; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; /** * Testing {@link InputDialogPresenter} functionality. * * @author Artem Zatsarynnyi * @author Roman Nikitenko */ public class InputDialogPresenterTest extends BaseTest { private static final String CORRECT_INPUT_VALUE = "testInputValue"; private static final String INCORRECT_INPUT_VALUE = "test input value"; private static final String ERROR_MESSAGE = "ERROR"; @Mock UILocalizationConstant localizationConstant; @Mock private InputDialogView view; private InputDialogPresenter presenter; @Before @Override public void setUp() { super.setUp(); presenter = new InputDialogPresenter( view, TITLE, MESSAGE, inputCallback, cancelCallback, localizationConstant); } @Test public void shouldCallCallbackOnCanceled() throws Exception { presenter.cancelled(); verify(view).closeDialog(); verify(cancelCallback).cancelled(); } @Test public void shouldNotCallCallbackOnCanceled() throws Exception { presenter = new InputDialogPresenter(view, TITLE, MESSAGE, inputCallback, null, localizationConstant); presenter.cancelled(); verify(view).closeDialog(); verify(cancelCallback, never()).cancelled(); } @Test public void shouldCallCallbackOnAccepted() throws Exception { presenter.accepted(); verify(view).closeDialog(); verify(view).getValue(); verify(inputCallback).accepted(nullable(String.class)); } @Test public void shouldNotCallCallbackOnAccepted() throws Exception { presenter = new InputDialogPresenter(view, TITLE, MESSAGE, null, cancelCallback, localizationConstant); presenter.accepted(); verify(view).closeDialog(); verify(inputCallback, never()).accepted(anyString()); } @Test public void shouldShowView() throws Exception { when(view.getValue()).thenReturn(CORRECT_INPUT_VALUE); presenter.show(); verify(view).showDialog(); } @Test public void shouldShowErrorHintWhenEmptyValue() throws Exception { reset(view); when(view.getValue()).thenReturn(""); presenter.inputValueChanged(); verify(view).showErrorHint(eq("")); verify(view, never()).hideErrorHint(); verify(view, never()).setValue(anyString()); } @Test public void shouldShowErrorHintWhenValueIsIncorrect() throws Exception { reset(view); when(view.getValue()).thenReturn(INCORRECT_INPUT_VALUE); InputValidator inputValidator = mock(InputValidator.class); InputValidator.Violation violation = mock(InputValidator.Violation.class); when(inputValidator.validate(INCORRECT_INPUT_VALUE)).thenReturn(violation); when(violation.getMessage()).thenReturn(ERROR_MESSAGE); presenter.withValidator(inputValidator); presenter.inputValueChanged(); verify(view).showErrorHint(anyString()); verify(view, never()).hideErrorHint(); verify(view, never()).setValue(anyString()); } @Test public void shouldNotShowErrorHintWhenViolationHasCorrectValue() throws Exception { reset(view); when(view.getValue()).thenReturn(INCORRECT_INPUT_VALUE); InputValidator inputValidator = mock(InputValidator.class); InputValidator.Violation violation = mock(InputValidator.Violation.class); when(inputValidator.validate(INCORRECT_INPUT_VALUE)).thenReturn(violation); when(violation.getMessage()).thenReturn(null); when(violation.getCorrectedValue()).thenReturn(CORRECT_INPUT_VALUE); presenter.withValidator(inputValidator); presenter.inputValueChanged(); verify(view, never()).showErrorHint(anyString()); verify(view).hideErrorHint(); verify(view).setValue(eq(CORRECT_INPUT_VALUE)); } @Test public void onEnterClickedWhenOkButtonInFocus() throws Exception { reset(view); when(view.isOkButtonInFocus()).thenReturn(true); presenter.onEnterClicked(); verify(view, never()).showErrorHint(anyString()); verify(view).closeDialog(); verify(inputCallback).accepted(nullable(String.class)); } @Test public void onEnterClickedWhenCancelButtonInFocus() throws Exception { reset(view); when(view.isCancelButtonInFocus()).thenReturn(true); presenter.onEnterClicked(); verify(view, never()).showErrorHint(anyString()); verify(inputCallback, never()).accepted(anyString()); verify(view).closeDialog(); verify(cancelCallback).cancelled(); } @Test public void onEnterClickedWhenInputValueIsCorrect() throws Exception { reset(view); when(view.getValue()).thenReturn(CORRECT_INPUT_VALUE); InputValidator inputValidator = mock(InputValidator.class); when(inputValidator.validate(CORRECT_INPUT_VALUE)).thenReturn(null); presenter.withValidator(inputValidator); presenter.onEnterClicked(); verify(view, never()).showErrorHint(anyString()); verify(view).hideErrorHint(); verify(view).closeDialog(); verify(inputCallback).accepted(eq(CORRECT_INPUT_VALUE)); } @Test public void onEnterClickedWhenInputValueIsIncorrect() throws Exception { reset(view); when(view.getValue()).thenReturn(INCORRECT_INPUT_VALUE); InputValidator inputValidator = mock(InputValidator.class); InputValidator.Violation violation = mock(InputValidator.Violation.class); when(inputValidator.validate(INCORRECT_INPUT_VALUE)).thenReturn(violation); when(violation.getMessage()).thenReturn(ERROR_MESSAGE); presenter.withValidator(inputValidator); presenter.onEnterClicked(); verify(view).showErrorHint(anyString()); verify(view, never()).hideErrorHint(); verify(view, never()).setValue(anyString()); verify(inputCallback, never()).accepted(anyString()); } }
epl-1.0
maxeler/eclipse
eclipse.jdt.core/org.eclipse.jdt.compiler.tool.tests/src/org/eclipse/jdt/compiler/tool/tests/CompilerToolTests.java
35272
/******************************************************************************* * Copyright (c) 2006, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Jesper Steen Moeller - Contributions for: * Bug 407297: [1.8][compiler] Control generation of parameter names by option *******************************************************************************/ package org.eclipse.jdt.compiler.tool.tests; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.ServiceLoader; import java.util.Set; import javax.tools.Diagnostic; import javax.tools.FileObject; import javax.tools.ForwardingJavaFileManager; import javax.tools.JavaCompiler; import javax.tools.JavaFileManager; import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.StandardLocation; import javax.tools.ToolProvider; import javax.tools.JavaCompiler.CompilationTask; import javax.tools.JavaFileObject.Kind; import junit.framework.TestCase; import junit.framework.TestSuite; import org.eclipse.jdt.compiler.tool.tests.AbstractCompilerToolTest.CompilerInvocationDiagnosticListener; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader; import org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException; import org.eclipse.jdt.internal.compiler.tool.EclipseCompiler; public class CompilerToolTests extends TestCase { private static final boolean DEBUG = false; public CompilerToolTests(String name) { super(name); } public static TestSuite suite() { TestSuite suite = new TestSuite(); suite.addTest(new CompilerToolTests("testInitializeJavaCompiler")); suite.addTest(new CompilerToolTests("testFileManager")); suite.addTest(new CompilerToolTests("testFileManager2")); suite.addTest(new CompilerToolTests("testInferBinaryName")); suite.addTest(new CompilerToolTests("testCheckOptions")); suite.addTest(new CompilerToolTests("testCompilerOneClassWithSystemCompiler")); // suite.addTest(new CompilerToolTests("testCompilerOneClassWithSystemCompiler2")); suite.addTest(new CompilerToolTests("testCompilerOneClassWithEclipseCompiler")); suite.addTest(new CompilerToolTests("testCompilerOneClassWithEclipseCompiler2")); suite.addTest(new CompilerToolTests("testCompilerOneClassWithEclipseCompiler3")); suite.addTest(new CompilerToolTests("testCompilerOneClassWithEclipseCompiler4")); suite.addTest(new CompilerToolTests("testCompilerOneClassWithEclipseCompiler5")); suite.addTest(new CompilerToolTests("testCompilerOneClassWithEclipseCompiler6")); suite.addTest(new CompilerToolTests("testCompilerOneClassWithEclipseCompiler7")); suite.addTest(new CompilerToolTests("testCleanUp")); return suite; } private static JavaCompiler Compiler; static final String[] ONE_ARG_OPTIONS = { "-cp", "-classpath", "-bootclasspath", "-sourcepath", "-extdirs", "-endorseddirs", "-d", "-encoding", "-source", "-target", "-maxProblems", "-log", "-repeat", "-processorpath", "-s", "-processor", "-classNames" }; static final String[] ZERO_ARG_OPTIONS = { "-1.3", "-1.4", "-1.5", "-1.6", "-1.7", "-7", "-7.0", "-6", "-6.0", "-5", "-5.0", "-deprecation", "-nowarn", "-warn:none", "-?:warn", "-g", "-g:lines", "-g:source", "-g:vars", "-g:lines,vars", "-g:none", "-preserveAllLocals", "-X", "-O", "-proceedOnError", "-proceedOnError:Fatal", "-verbose", "-referenceInfo", "-progress", "-time", "-noExit", "-inlineJSR", "-enableJavadoc", "-Xemacs", "-?", "-help", "-v", "-version", "-showversion", "-XprintRounds", "-XprintProcessorInfo", "-proc:none", "-proc:only", "-parameters", "-genericsignature" }; static final String[] FAKE_ZERO_ARG_OPTIONS = new String[] { // a series of fake options to test the behavior upon ignored and // pass-through options "-Jignore", "-Xignore", "-Akey=value", }; private void displayLocation(StandardJavaFileManager manager, StandardLocation standardLocation) { System.out.println(standardLocation.getName()); Iterable<? extends File> location = manager.getLocation(standardLocation); if (location == null) return; for (File f : location) { System.out.println(f.getAbsolutePath()); } } /* * Initialize the compiler for all the tests */ public void testInitializeJavaCompiler() { ServiceLoader<JavaCompiler> javaCompilerLoader = ServiceLoader.load(JavaCompiler.class);//, EclipseCompiler.class.getClassLoader()); int compilerCounter = 0; for (JavaCompiler javaCompiler : javaCompilerLoader) { compilerCounter++; if (javaCompiler instanceof EclipseCompiler) { Compiler = javaCompiler; } } assertEquals("Only one compiler available", 1, compilerCounter); } public void testCheckOptions() { assertNotNull("No compiler found", Compiler); for (String option : ONE_ARG_OPTIONS) { assertEquals(option + " requires 1 argument", 1, Compiler.isSupportedOption(option)); } for (String option : ZERO_ARG_OPTIONS) { assertEquals(option + " requires no argument", 0, Compiler.isSupportedOption(option)); } for (String option : FAKE_ZERO_ARG_OPTIONS) { assertEquals(option + " requires no argument", 0, Compiler.isSupportedOption(option)); } } public void testCompilerOneClassWithSystemCompiler() { JavaCompiler systemCompiler = ToolProvider.getSystemJavaCompiler(); if (systemCompiler == null) { System.out.println("No system java compiler available"); return; } String tmpFolder = System.getProperty("java.io.tmpdir"); File inputFile = new File(tmpFolder, "X.java"); BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(inputFile)); writer.write( "package p;\n" + "public class X {}"); writer.flush(); writer.close(); } catch (IOException e) { // ignore } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { // ignore } } } // System compiler StandardJavaFileManager manager = systemCompiler.getStandardFileManager(null, Locale.getDefault(), Charset.defaultCharset()); ForwardingJavaFileManager<StandardJavaFileManager> forwardingJavaFileManager = new ForwardingJavaFileManager<StandardJavaFileManager>(manager) { @Override public FileObject getFileForInput(Location location, String packageName, String relativeName) throws IOException { if (DEBUG) { System.out.println("Create file for input : " + packageName + " " + relativeName + " in location " + location); } return super.getFileForInput(location, packageName, relativeName); } @Override public JavaFileObject getJavaFileForInput(Location location, String className, Kind kind) throws IOException { if (DEBUG) { System.out.println("Create java file for input : " + className + " in location " + location); } return super.getJavaFileForInput(location, className, kind); } @Override public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException { if (DEBUG) { System.out.println("Create .class file for " + className + " in location " + location + " with sibling " + sibling.toUri()); } JavaFileObject javaFileForOutput = super.getJavaFileForOutput(location, className, kind, sibling); if (DEBUG) { System.out.println(javaFileForOutput.toUri()); } return javaFileForOutput; } }; // create new list containing inputfile List<File> files = new ArrayList<File>(); files.add(inputFile); Iterable<? extends JavaFileObject> units = manager.getJavaFileObjectsFromFiles(files); StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); List<String> options = new ArrayList<String>(); options.add("-d"); options.add(tmpFolder); CompilationTask task = systemCompiler.getTask(printWriter, forwardingJavaFileManager, null, options, null, units); assertTrue("Has location CLASS_OUPUT ", forwardingJavaFileManager.hasLocation(StandardLocation.CLASS_OUTPUT)); Boolean result = task.call(); if (!result.booleanValue()) { System.err.println("Compilation failed: " + stringWriter.getBuffer().toString()); assertTrue("Compilation failed ", false); } // check that the .class file exist for X assertTrue("delete failed", inputFile.delete()); } /* * Run the system compiler using the Eclipse java file manager * TODO need to investigate why rt.jar gets removed from the PLATFORM_CLASSPATH location */ public void _testCompilerOneClassWithSystemCompiler2() { // System compiler JavaCompiler systemCompiler = ToolProvider.getSystemJavaCompiler(); if (systemCompiler == null) { System.out.println("No system java compiler available"); return; } String tmpFolder = System.getProperty("java.io.tmpdir"); File inputFile = new File(tmpFolder, "X.java"); BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(inputFile)); writer.write( "package p;\n" + "public class X {}"); writer.flush(); writer.close(); } catch (IOException e) { // ignore } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { // ignore } } } StandardJavaFileManager manager = Compiler.getStandardFileManager(null, Locale.getDefault(), Charset.defaultCharset()); @SuppressWarnings("resource") ForwardingJavaFileManager<StandardJavaFileManager> forwardingJavaFileManager = new ForwardingJavaFileManager<StandardJavaFileManager>(manager) { @Override public FileObject getFileForInput(Location location, String packageName, String relativeName) throws IOException { if (DEBUG) { System.out.println("Create file for input : " + packageName + " " + relativeName + " in location " + location); } return super.getFileForInput(location, packageName, relativeName); } @Override public JavaFileObject getJavaFileForInput(Location location, String className, Kind kind) throws IOException { if (DEBUG) { System.out.println("Create java file for input : " + className + " in location " + location); } return super.getJavaFileForInput(location, className, kind); } @Override public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException { if (DEBUG) { System.out.println("Create .class file for " + className + " in location " + location + " with sibling " + sibling.toUri()); } JavaFileObject javaFileForOutput = super.getJavaFileForOutput(location, className, kind, sibling); if (DEBUG) { System.out.println(javaFileForOutput.toUri()); } return javaFileForOutput; } }; // create new list containing inputfile List<File> files = new ArrayList<File>(); files.add(inputFile); Iterable<? extends JavaFileObject> units = manager.getJavaFileObjectsFromFiles(files); StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); List<String> options = new ArrayList<String>(); options.add("-d"); options.add(tmpFolder); CompilationTask task = systemCompiler.getTask(printWriter, manager, null, options, null, units); if (DEBUG) { System.out.println("Has location CLASS_OUPUT : " + forwardingJavaFileManager.hasLocation(StandardLocation.CLASS_OUTPUT)); } Boolean result = task.call(); displayLocation(manager, StandardLocation.CLASS_PATH); displayLocation(manager, StandardLocation.PLATFORM_CLASS_PATH); if (!result.booleanValue()) { System.err.println("Compilation failed: " + stringWriter.getBuffer().toString()); assertTrue("Compilation failed ", false); } // check that the .class file exist for X assertTrue("delete failed", inputFile.delete()); } public void testCompilerOneClassWithEclipseCompiler() { String tmpFolder = System.getProperty("java.io.tmpdir"); File inputFile = new File(tmpFolder, "X.java"); BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(inputFile)); writer.write( "package p;\n" + "public class X {}"); writer.flush(); writer.close(); } catch (IOException e) { // ignore } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { // ignore } } } // System compiler StandardJavaFileManager manager = Compiler.getStandardFileManager(null, Locale.getDefault(), Charset.defaultCharset()); ForwardingJavaFileManager<StandardJavaFileManager> forwardingJavaFileManager = new ForwardingJavaFileManager<StandardJavaFileManager>(manager) { @Override public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException { if (DEBUG) { System.out.println("EC: Create .class file for " + className + " in location " + location + " with sibling " + sibling.toUri()); } JavaFileObject javaFileForOutput = super.getJavaFileForOutput(location, className, kind, sibling); if (DEBUG) { System.out.println(javaFileForOutput.toUri()); } return javaFileForOutput; } }; // create new list containing inputfile List<File> files = new ArrayList<File>(); files.add(inputFile); Iterable<? extends JavaFileObject> units = manager.getJavaFileObjectsFromFiles(files); StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); List<String> options = new ArrayList<String>(); options.add("-d"); options.add(tmpFolder); CompilationTask task = Compiler.getTask(printWriter, forwardingJavaFileManager, null, options, null, units); // check the classpath location assertTrue("Has no location CLASS_OUPUT", forwardingJavaFileManager.hasLocation(StandardLocation.CLASS_OUTPUT)); Boolean result = task.call(); printWriter.flush(); printWriter.close(); if (!result.booleanValue()) { System.err.println("Compilation failed: " + stringWriter.getBuffer().toString()); assertTrue("Compilation failed ", false); } ClassFileReader reader = null; try { reader = ClassFileReader.read(new File(tmpFolder, "p/X.class"), true); } catch (ClassFormatException e) { assertTrue("Should not happen", false); } catch (IOException e) { assertTrue("Should not happen", false); } assertNotNull("No reader", reader); assertEquals("Wrong value", ClassFileConstants.JDK1_6, reader.getVersion()); // check that the .class file exist for X assertTrue("delete failed", inputFile.delete()); } public void testCompilerOneClassWithEclipseCompiler2() { String tmpFolder = System.getProperty("java.io.tmpdir"); File inputFile = new File(tmpFolder, "X.java"); BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(inputFile)); writer.write( "package p;\n" + "public class X {}"); writer.flush(); writer.close(); } catch (IOException e) { // ignore } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { // ignore } } } // System compiler StandardJavaFileManager manager = Compiler.getStandardFileManager(null, Locale.getDefault(), Charset.defaultCharset()); ForwardingJavaFileManager<StandardJavaFileManager> forwardingJavaFileManager = new ForwardingJavaFileManager<StandardJavaFileManager>(manager) { @Override public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException { if (DEBUG) { System.out.println("EC: Create .class file for " + className + " in location " + location + " with sibling " + sibling.toUri()); } JavaFileObject javaFileForOutput = super.getJavaFileForOutput(location, className, kind, sibling); if (DEBUG) { System.out.println(javaFileForOutput.toUri()); } return javaFileForOutput; } }; // create new list containing inputfile List<File> files = new ArrayList<File>(); files.add(inputFile); Iterable<? extends JavaFileObject> units = manager.getJavaFileObjectsFromFiles(files); StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); List<String> options = new ArrayList<String>(); options.add("-d"); options.add(tmpFolder); options.add("-1.5"); CompilationTask task = Compiler.getTask(printWriter, forwardingJavaFileManager, null, options, null, units); // check the classpath location assertTrue("Has no location CLASS_OUPUT", forwardingJavaFileManager.hasLocation(StandardLocation.CLASS_OUTPUT)); Boolean result = task.call(); printWriter.flush(); printWriter.close(); if (!result.booleanValue()) { System.err.println("Compilation failed: " + stringWriter.getBuffer().toString()); assertTrue("Compilation failed ", false); } File outputFile = new File(tmpFolder, "p/X.class"); assertTrue(outputFile.exists()); ClassFileReader reader = null; try { reader = ClassFileReader.read(outputFile); } catch (ClassFormatException e) { assertTrue("Should not happen", false); } catch (IOException e) { assertTrue("Should not happen", false); } assertNotNull("No reader", reader); assertEquals("Not a 1.5 .class file", ClassFileConstants.JDK1_5, reader.getVersion()); stringWriter = new StringWriter(); printWriter = new PrintWriter(stringWriter); task = Compiler.getTask(printWriter, forwardingJavaFileManager, null, options, null, units); // check the classpath location assertTrue("Has no location CLASS_OUPUT", forwardingJavaFileManager.hasLocation(StandardLocation.CLASS_OUTPUT)); result = task.call(); printWriter.flush(); printWriter.close(); if (!result.booleanValue()) { System.err.println("Compilation failed: " + stringWriter.getBuffer().toString()); assertTrue("Compilation failed ", false); } // check that the .class file exist for X assertTrue("delete failed", inputFile.delete()); } public void testCompilerOneClassWithEclipseCompiler3() { String tmpFolder = System.getProperty("java.io.tmpdir"); File inputFile = new File(tmpFolder, "X.java"); BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(inputFile)); writer.write( "package p;\n" + "public class X {}"); writer.flush(); writer.close(); } catch (IOException e) { // ignore } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { // ignore } } } // System compiler StandardJavaFileManager manager = Compiler.getStandardFileManager(null, Locale.getDefault(), Charset.defaultCharset()); @SuppressWarnings("resource") ForwardingJavaFileManager<StandardJavaFileManager> forwardingJavaFileManager = new ForwardingJavaFileManager<StandardJavaFileManager>(manager) { @Override public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException { if (DEBUG) { System.out.println("Create .class file for " + className + " in location " + location + " with sibling " + sibling.toUri()); } JavaFileObject javaFileForOutput = super.getJavaFileForOutput(location, className, kind, sibling); if (DEBUG) { System.out.println(javaFileForOutput.toUri()); } return javaFileForOutput; } }; // create new list containing inputfile List<File> files = new ArrayList<File>(); files.add(inputFile); Iterable<? extends JavaFileObject> units = manager.getJavaFileObjectsFromFiles(files); StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); List<String> options = new ArrayList<String>(); options.add("-d"); options.add(tmpFolder); CompilationTask task = Compiler.getTask(printWriter, manager, null, options, null, units); // check the classpath location assertTrue("Has no location CLASS_OUPUT", forwardingJavaFileManager.hasLocation(StandardLocation.CLASS_OUTPUT)); Boolean result = task.call(); printWriter.flush(); printWriter.close(); if (!result.booleanValue()) { System.err.println("Compilation failed: " + stringWriter.getBuffer().toString()); assertTrue("Compilation failed ", false); } try { task.call(); assertTrue("Should not get there", false); } catch (IllegalStateException e) { // ignore: expected } // check that the .class file exist for X assertTrue("delete failed", inputFile.delete()); } public void testCompilerOneClassWithEclipseCompiler4() throws IOException { JavaCompiler systemCompiler = ToolProvider.getSystemJavaCompiler(); if (systemCompiler == null) { System.out.println("No system java compiler available"); return; } String tmpFolder = System.getProperty("java.io.tmpdir"); File inputFile = new File(tmpFolder, "X.java"); BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(inputFile)); writer.write( "package p;\n" + "public class X {}"); writer.flush(); writer.close(); } catch (IOException e) { // ignore } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { // ignore } } } // create new list containing inputfile List<File> files = new ArrayList<File>(); files.add(inputFile); StandardJavaFileManager manager = systemCompiler.getStandardFileManager(null, Locale.getDefault(), Charset.defaultCharset()); Iterable<? extends JavaFileObject> units = manager.getJavaFileObjectsFromFiles(files); StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); List<String> options = new ArrayList<String>(); options.add("-d"); options.add(tmpFolder); CompilationTask task = Compiler.getTask(null, null, null, options, null, units); // check the classpath location Boolean result = task.call(); printWriter.flush(); printWriter.close(); if (!result.booleanValue()) { System.err.println("Compilation failed: " + stringWriter.getBuffer().toString()); assertTrue("Compilation failed ", false); } // check that the .class file exist for X assertTrue("delete failed", inputFile.delete()); manager.close(); } public void testCompilerOneClassWithEclipseCompiler5() { String tmpFolder = System.getProperty("java.io.tmpdir"); File inputFile = new File(tmpFolder, "X.java"); BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(inputFile)); writer.write( "package p;\n" + "public class X extends File {}"); writer.flush(); writer.close(); } catch (IOException e) { // ignore } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { // ignore } } } // System compiler StandardJavaFileManager manager = Compiler.getStandardFileManager(null, Locale.getDefault(), Charset.defaultCharset()); List<File> files = new ArrayList<File>(); files.add(inputFile); Iterable<? extends JavaFileObject> units = manager.getJavaFileObjectsFromFiles(files); List<String> options = new ArrayList<String>(); options.add("-d"); options.add(tmpFolder); ByteArrayOutputStream errBuffer = new ByteArrayOutputStream(); PrintWriter err = new PrintWriter(errBuffer); CompilerInvocationDiagnosticListener compilerInvocationDiagnosticListener = new CompilerInvocationDiagnosticListener(err); CompilationTask task = Compiler.getTask(null, manager, compilerInvocationDiagnosticListener, options, null, units); // check the classpath location Boolean result = task.call(); err.flush(); err.close(); assertFalse(errBuffer.toString().isEmpty()); assertTrue(compilerInvocationDiagnosticListener.kind != CompilerInvocationDiagnosticListener.NONE); if (!result.booleanValue()) { assertFalse("Compilation did not fail", false); } // check that the .class file exist for X assertTrue("delete failed", inputFile.delete()); } public void testCompilerOneClassWithEclipseCompiler6() { String tmpFolder = System.getProperty("java.io.tmpdir"); File packageFolder = new File(tmpFolder, "p"); if (!packageFolder.mkdirs()) { return; } File inputFile = new File(packageFolder, "X.java"); BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(inputFile)); writer.write( "package p;\n" + "public class X extends File {}"); writer.flush(); writer.close(); } catch (IOException e) { // ignore } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { // ignore } } } // System compiler StandardJavaFileManager manager = Compiler.getStandardFileManager(null, Locale.getDefault(), Charset.defaultCharset()); List<File> files = new ArrayList<File>(); files.add(inputFile); Iterable<? extends JavaFileObject> units = manager.getJavaFileObjectsFromFiles(files); List<String> options = new ArrayList<String>(); options.add("-d"); options.add(tmpFolder); options.add("-sourcepath"); options.add(tmpFolder); ByteArrayOutputStream errBuffer = new ByteArrayOutputStream(); PrintWriter err = new PrintWriter(errBuffer); CompilerInvocationDiagnosticListener compilerInvocationDiagnosticListener = new CompilerInvocationDiagnosticListener(err) { @Override public void report(Diagnostic<? extends JavaFileObject> diagnostic) { JavaFileObject source = diagnostic.getSource(); assertNotNull("No source", source); super.report(diagnostic); } }; CompilationTask task = Compiler.getTask(null, manager, compilerInvocationDiagnosticListener, options, null, units); // check the classpath location Boolean result = task.call(); err.flush(); err.close(); assertFalse(errBuffer.toString().isEmpty()); assertTrue(compilerInvocationDiagnosticListener.kind != CompilerInvocationDiagnosticListener.NONE); if (!result.booleanValue()) { assertFalse("Compilation did not fail", false); } // check that the .class file exist for X assertTrue("delete failed", inputFile.delete()); assertTrue("delete failed", packageFolder.delete()); } public void testCompilerOneClassWithEclipseCompiler7() { String tmpFolder = System.getProperty("java.io.tmpdir"); File inputFile = new File(tmpFolder, "X.java"); BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(inputFile)); writer.write( "package p;\n" + "public class X extends File {}"); writer.flush(); writer.close(); } catch (IOException e) { // ignore } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { // ignore } } } // System compiler StandardJavaFileManager manager = Compiler.getStandardFileManager(null, Locale.getDefault(), Charset.defaultCharset()); List<File> files = new ArrayList<File>(); files.add(inputFile); Iterable<? extends JavaFileObject> units = manager.getJavaFileObjectsFromFiles(files); List<String> options = new ArrayList<String>(); options.add("-d"); options.add(tmpFolder); options.add("-sourcepath"); options.add(tmpFolder); ByteArrayOutputStream errBuffer = new ByteArrayOutputStream(); PrintWriter err = new PrintWriter(errBuffer); CompilerInvocationDiagnosticListener compilerInvocationDiagnosticListener = new CompilerInvocationDiagnosticListener(err) { @Override public void report(Diagnostic<? extends JavaFileObject> diagnostic) { JavaFileObject source = diagnostic.getSource(); assertNotNull("No source", source); super.report(diagnostic); } }; CompilationTask task = Compiler.getTask(null, manager, compilerInvocationDiagnosticListener, options, null, units); // check the classpath location Boolean result = task.call(); err.flush(); err.close(); assertFalse(errBuffer.toString().isEmpty()); assertTrue(compilerInvocationDiagnosticListener.kind != CompilerInvocationDiagnosticListener.NONE); if (!result.booleanValue()) { assertFalse("Compilation did not fail", false); } // check that the .class file exist for X assertTrue("delete failed", inputFile.delete()); } // Test that JavaFileManager#inferBinaryName returns null for invalid file public void testInferBinaryName() { String tmpFolder = System.getProperty("java.io.tmpdir"); File dir = new File(tmpFolder, "src" + System.currentTimeMillis()); dir.mkdirs(); File inputFile = new File(dir, "test.txt"); BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(inputFile)); writer.write("This is not a valid Java file"); writer.flush(); writer.close(); } catch (IOException e) { } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { } } } try { StandardJavaFileManager fileManager = Compiler.getStandardFileManager(null, Locale.getDefault(), Charset.defaultCharset()); List<File> fins = new ArrayList<File>(); fins.add(dir); JavaFileManager.Location sourceLoc = javax.tools.StandardLocation.SOURCE_PATH; fileManager.setLocation(sourceLoc, fins); Set<JavaFileObject.Kind> fileTypes = new HashSet<JavaFileObject.Kind>(); fileTypes.add(JavaFileObject.Kind.OTHER); Iterable<? extends JavaFileObject> compilationUnits = fileManager.list(sourceLoc, "", fileTypes, true); JavaFileObject invalid = null; for (JavaFileObject javaFileObject : compilationUnits) { invalid = javaFileObject; break; } String inferredName = fileManager.inferBinaryName(sourceLoc, invalid); fileManager.close(); assertNull("Should return null for invalid file", inferredName); } catch (IOException e) { e.printStackTrace(); } assertTrue("delete failed", inputFile.delete()); assertTrue("delete failed", dir.delete()); } public void testFileManager() { String tmpFolder = System.getProperty("java.io.tmpdir"); File dir = new File(tmpFolder, "src" + System.currentTimeMillis()); dir.mkdirs(); File inputFile = new File(dir, "X.java"); BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(inputFile)); writer.write("public class X {}"); writer.flush(); writer.close(); } catch (IOException e) { // ignore } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { // ignore } } } try { //JavaCompiler systemCompiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = Compiler.getStandardFileManager(null, Locale.getDefault(), Charset.defaultCharset()); List<File> fins = new ArrayList<File>(); fins.add(dir); JavaFileManager.Location sourceLoc = javax.tools.StandardLocation.SOURCE_PATH; fileManager.setLocation(sourceLoc, fins); Set<JavaFileObject.Kind> fileTypes = new HashSet<JavaFileObject.Kind>(); fileTypes.add(JavaFileObject.Kind.SOURCE); Iterable<? extends JavaFileObject> compilationUnits = fileManager.list(sourceLoc, "", fileTypes, true); Iterator<? extends JavaFileObject> it = compilationUnits.iterator(); StringBuilder builder = new StringBuilder(); while (it.hasNext()) { JavaFileObject next = it.next(); String name = next.getName(); name = name.replace('\\', '/'); int lastIndexOf = name.lastIndexOf('/'); builder.append(name.substring(lastIndexOf + 1)); } assertEquals("Wrong contents", "X.java", String.valueOf(builder)); List<File> files = new ArrayList<File>(); files.add(dir); try { fileManager.getJavaFileObjectsFromFiles(files); fail("IllegalArgumentException should be thrown but not"); } catch(IllegalArgumentException iae) { // Do nothing } fileManager.close(); } catch (IOException e) { e.printStackTrace(); } // check that the .class file exist for X assertTrue("delete failed", inputFile.delete()); assertTrue("delete failed", dir.delete()); } public void testFileManager2() { String tmpFolder = System.getProperty("java.io.tmpdir"); File dir = new File(tmpFolder, "src" + System.currentTimeMillis()); dir.mkdirs(); File dir2 = new File(dir, "src2"); dir2.mkdirs(); File inputFile = new File(dir, "X.java"); BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(inputFile)); writer.write("public class X {}"); writer.flush(); writer.close(); } catch (IOException e) { // ignore } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { // ignore } } } File inputFile2 = new File(dir2, "X2.java"); writer = null; try { writer = new BufferedWriter(new FileWriter(inputFile2)); writer.write("public class X2 {}"); writer.flush(); writer.close(); } catch (IOException e) { // ignore } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { // ignore } } } try { //JavaCompiler systemCompiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = Compiler.getStandardFileManager(null, Locale.getDefault(), Charset.defaultCharset()); List<File> fins = new ArrayList<File>(); fins.add(dir); JavaFileManager.Location sourceLoc = javax.tools.StandardLocation.SOURCE_PATH; fileManager.setLocation(sourceLoc, fins); Set<JavaFileObject.Kind> fileTypes = new HashSet<JavaFileObject.Kind>(); fileTypes.add(JavaFileObject.Kind.SOURCE); Iterable<? extends JavaFileObject> compilationUnits = fileManager.list(sourceLoc, "", fileTypes, true); Iterator<? extends JavaFileObject> it = compilationUnits.iterator(); List<String> names = new ArrayList<String>(); while (it.hasNext()) { JavaFileObject next = it.next(); String name = next.getName(); name = name.replace('\\', '/'); int lastIndexOf = name.lastIndexOf('/'); names.add(name.substring(lastIndexOf + 1)); } Collections.sort(names); assertEquals("Wrong contents", "[X.java, X2.java]", names.toString()); fileManager.close(); } catch (IOException e) { e.printStackTrace(); } // check that the .class file exist for X assertTrue("delete failed", inputFile2.delete()); assertTrue("delete failed", dir2.delete()); assertTrue("delete failed", inputFile.delete()); assertTrue("delete failed", dir.delete()); } /* * Clean up the compiler */ public void testCleanUp() { Compiler = null; } }
epl-1.0
ascharfi/Clarity-Capella-DocGenerator
Core/fr.obeo.dsl.designer.documentation.generator/src/fr/obeo/dsl/designer/documentation/generator/internal/extensions/GeneratorExtensionListener.java
2520
/******************************************************************************* * Copyright (c) 2014 Obeo. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Obeo - initial API and implementation *******************************************************************************/ package fr.obeo.dsl.designer.documentation.generator.internal.extensions; import static fr.obeo.dsl.designer.documentation.generator.DocumentationGeneratorPlugin.logError; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.ILog; import fr.obeo.dsl.designer.documentation.generator.DocumentationGeneratorPlugin; import fr.obeo.dsl.designer.documentation.generator.generator.IDocumentationGeneratorDescriptor; /** * Listener in charge of filling the {@link GeneratorRegistry}. * * @author adaussy */ public class GeneratorExtensionListener extends AbstractRegistryEventListener { public static final String DOCUMENTATION_GENERATOR_EXT_POINT = "documentationGenerator"; private static final String DESCRIPTOR_IMPL_ATTR = "impl"; private final GeneratorRegistry registry; public GeneratorExtensionListener(ILog log, GeneratorRegistry registry) { super(DocumentationGeneratorPlugin.PLUGIN_ID, DOCUMENTATION_GENERATOR_EXT_POINT, log); this.registry = registry; } @Override protected boolean validateExtensionElement(IConfigurationElement element) { try { Object impl = element.createExecutableExtension(DESCRIPTOR_IMPL_ATTR); if (impl instanceof IDocumentationGeneratorDescriptor) { return true; } } catch (CoreException e) { logError("Incorrect documentation generator provided from" + element.getContributor().getName(), e); } return false; } @Override protected boolean addedValid(IConfigurationElement element) { try { registry.add((IDocumentationGeneratorDescriptor)element .createExecutableExtension(DESCRIPTOR_IMPL_ATTR)); } catch (CoreException e) { // Should never happen since check in validateExtension } return true; } @Override protected boolean removedValid(IConfigurationElement element) { return registry.remove(element.getAttribute(DESCRIPTOR_IMPL_ATTR)) != null; } }
epl-1.0
eliericha/atlanalyser
fr.tpt.atlanalyser/src/fr/tpt/atlanalyser/AtlParser.java
6720
/******************************************************************************* * Copyright (c) 2014-2015 TELECOM ParisTech and AdaCore. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Elie Richa - initial implementation *******************************************************************************/ package fr.tpt.atlanalyser; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EEnumLiteral; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl; import org.eclipse.m2m.atl.core.ATLCoreException; import fr.tpt.atlanalyser.atl.ATL.ATLFactory; import fr.tpt.atlanalyser.atl.ATL.ATLPackage; import fr.tpt.atlanalyser.atl.ATL.Module; import fr.tpt.atlanalyser.atl.OCL.OCLFactory; import fr.tpt.atlanalyser.atl.OCL.OCLPackage; import fr.tpt.atlanalyser.atl.PrimitiveTypes.PrimitiveTypesFactory; import fr.tpt.atlanalyser.atl.PrimitiveTypes.PrimitiveTypesPackage; public class AtlParser { private static final Logger LOGGER = LogManager.getLogger(AtlParser.class .getSimpleName()); private ResourceSet atlResourceSet; private Map<String, Module> moduleNameToModule; private ATLEnvironment env; public AtlParser() { this(new ResourceSetImpl(), new ATLEnvironment()); } public AtlParser(ResourceSet rs) { this(rs, new ATLEnvironment()); } public AtlParser(ResourceSet rs, ATLEnvironment env) { atlResourceSet = rs; this.env = env; registerAtlMetamodels(atlResourceSet); moduleNameToModule = new HashMap<String, Module>(); } public ATLEnvironment getEnv() { return env; } public Module parseAtlTransformation(File atlTranformation) throws FileNotFoundException, ATLAnalyserException { return parseAtlTransformation(new FileInputStream(atlTranformation)); } public Module parseAtlTransformation(InputStream atlTransformation) throws ATLAnalyserException { org.eclipse.m2m.atl.engine.parser.AtlParser atlParser = org.eclipse.m2m.atl.engine.parser.AtlParser .getDefault(); try { EObject[] parseResult = atlParser .parseWithProblems(atlTransformation); EObject module = parseResult[0]; if (module == null) { // Parse error for (int i = 1; i < parseResult.length; i++) { EObject problem = parseResult[i]; EEnumLiteral severity = (EEnumLiteral) problem.eGet(problem .eClass().getEStructuralFeature("severity")); String location = (String) problem.eGet(problem.eClass() .getEStructuralFeature("location")); String desc = (String) problem.eGet(problem.eClass() .getEStructuralFeature("description")); LOGGER.error("{} - {} - {}", severity.getLiteral(), location, desc); } System.exit(1); } String moduleName = (String) module.eGet(module.eClass() .getEStructuralFeature("name")); // Convert to a better typed model by saving it and reloading it // after having registered the ATL packages. Resource res = module.eResource(); ByteArrayOutputStream tempOutStream = new ByteArrayOutputStream(); res.save(tempOutStream, Collections.EMPTY_MAP); tempOutStream.close(); Resource newRes = atlResourceSet.createResource(URI .createURI(moduleName)); newRes.load(new ByteArrayInputStream(tempOutStream.toByteArray()), Collections.EMPTY_MAP); Module wellTypedModule = null; for (EObject obj : newRes.getContents()) { if (obj instanceof Module) { wellTypedModule = (Module) obj; break; } } if (wellTypedModule != null) { if (moduleNameToModule.containsKey(wellTypedModule.getName())) { LOGGER.warn(String .format("Module %s was already parsed. Keeping previous parsed version.", wellTypedModule.getName())); wellTypedModule = moduleNameToModule.get(wellTypedModule .getName()); } else { moduleNameToModule.put(wellTypedModule.getName(), wellTypedModule); } env.add(wellTypedModule); return wellTypedModule; } else { throw new ATLAnalyserException( "ATL transformation did not contain a Module element"); } } catch (ATLCoreException e) { LOGGER.error("Failed to parse ATL transformation"); LOGGER.error(e.getMessage()); e.printStackTrace(); } catch (IOException e) { LOGGER.error("Failed to convert ATL transformation to well typed model"); e.printStackTrace(); } return null; } public static void registerAtlMetamodels(ResourceSet targetResSet) { EPackage.Registry reg = targetResSet.getPackageRegistry(); reg.put(ATLPackage.eNS_URI, ATLFactory.eINSTANCE); reg.put(OCLPackage.eNS_URI, OCLFactory.eINSTANCE); reg.put(PrimitiveTypesPackage.eNS_URI, PrimitiveTypesFactory.eINSTANCE); targetResSet .getResourceFactoryRegistry() .getExtensionToFactoryMap() .put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl()); } }
epl-1.0
mhddurrah/kura
kura/org.eclipse.kura.net.admin/src/main/java/org/eclipse/kura/net/admin/visitor/linux/FirewallNatConfigWriter.java
6932
/** * Copyright (c) 2011, 2014 Eurotech and/or its affiliates * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Eurotech */ package org.eclipse.kura.net.admin.visitor.linux; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Properties; import org.eclipse.kura.KuraErrorCode; import org.eclipse.kura.KuraException; import org.eclipse.kura.core.net.NetworkConfiguration; import org.eclipse.kura.core.net.NetworkConfigurationVisitor; import org.eclipse.kura.linux.net.iptables.LinuxFirewall; import org.eclipse.kura.linux.net.iptables.NATRule; import org.eclipse.kura.net.NetConfig; import org.eclipse.kura.net.NetConfigIP4; import org.eclipse.kura.net.NetInterfaceAddressConfig; import org.eclipse.kura.net.NetInterfaceConfig; import org.eclipse.kura.net.NetInterfaceStatus; import org.eclipse.kura.net.NetInterfaceType; import org.eclipse.kura.net.admin.visitor.linux.util.KuranetConfig; import org.eclipse.kura.net.firewall.FirewallNatConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FirewallNatConfigWriter implements NetworkConfigurationVisitor { private static final Logger s_logger = LoggerFactory.getLogger(FirewallNatConfigWriter.class); private static FirewallNatConfigWriter s_instance; public static FirewallNatConfigWriter getInstance() { if (s_instance == null) { s_instance = new FirewallNatConfigWriter(); } return s_instance; } @Override public void visit(NetworkConfiguration config) throws KuraException { List<NetInterfaceConfig<? extends NetInterfaceAddressConfig>> netInterfaceConfigs = config.getModifiedNetInterfaceConfigs(); for (NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig : netInterfaceConfigs) { if (netInterfaceConfig.getType() == NetInterfaceType.ETHERNET || netInterfaceConfig.getType() == NetInterfaceType.WIFI) { writeConfig(netInterfaceConfig, KuranetConfig.getProperties()); } } applyNatConfig(config); } private void writeConfig( NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig, Properties kuraProps) throws KuraException { String interfaceName = netInterfaceConfig.getName(); s_logger.debug("Writing NAT config for " + interfaceName); List<? extends NetInterfaceAddressConfig> netInterfaceAddressConfigs = null; netInterfaceAddressConfigs = netInterfaceConfig.getNetInterfaceAddresses(); boolean natEnabled = false; boolean useMasquerade = false; String srcIface = null; String dstIface = null; if(netInterfaceAddressConfigs != null && netInterfaceAddressConfigs.size() > 0) { for(NetInterfaceAddressConfig netInterfaceAddressConfig : netInterfaceAddressConfigs) { List<NetConfig> netConfigs = netInterfaceAddressConfig.getConfigs(); if(netConfigs != null && netConfigs.size() > 0) { for(int i=0; i<netConfigs.size(); i++) { NetConfig netConfig = netConfigs.get(i); if(netConfig instanceof FirewallNatConfig) { natEnabled = true; srcIface = ((FirewallNatConfig) netConfig).getSourceInterface(); dstIface = ((FirewallNatConfig) netConfig).getDestinationInterface(); useMasquerade = ((FirewallNatConfig) netConfig).isMasquerade(); } } } } } //set it all if(kuraProps == null) { s_logger.debug("kuraExtendedProps was null"); kuraProps = new Properties(); } StringBuilder sb = new StringBuilder().append("net.interface.").append(netInterfaceConfig.getName()).append(".config.nat.enabled"); kuraProps.put(sb.toString(), Boolean.toString(natEnabled)); if (natEnabled && (srcIface != null) && (dstIface != null)) { sb = new StringBuilder().append("net.interface.").append(netInterfaceConfig.getName()).append(".config.nat.dst.interface"); kuraProps.put(sb.toString(), dstIface); sb = new StringBuilder().append("net.interface.").append(netInterfaceConfig.getName()).append(".config.nat.masquerade"); kuraProps.put(sb.toString(), Boolean.toString(useMasquerade)); } //write it if(kuraProps != null && !kuraProps.isEmpty()) { try { KuranetConfig.storeProperties(kuraProps); } catch (Exception e) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e); } } } private void applyNatConfig(NetworkConfiguration networkConfig) throws KuraException { LinuxFirewall firewall = LinuxFirewall.getInstance(); firewall.replaceAllNatRules(getNatConfigs(networkConfig)); firewall.enable(); } private LinkedHashSet<NATRule> getNatConfigs(NetworkConfiguration networkConfig) { LinkedHashSet<NATRule> natConfigs = new LinkedHashSet<NATRule>(); if(networkConfig != null) { ArrayList<String> wanList = new ArrayList<String>(); ArrayList<String> natList = new ArrayList<String>(); // get relevant interfaces for(NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig : networkConfig.getNetInterfaceConfigs()) { String interfaceName = netInterfaceConfig.getName(); NetInterfaceStatus status = NetInterfaceStatus.netIPv4StatusUnknown; boolean isNat = false; for(NetInterfaceAddressConfig addressConfig : netInterfaceConfig.getNetInterfaceAddresses()) { for(NetConfig netConfig : addressConfig.getConfigs()) { if(netConfig instanceof NetConfigIP4) { status = ((NetConfigIP4)netConfig).getStatus(); } else if(netConfig instanceof FirewallNatConfig) { isNat = true; } } } if(NetInterfaceStatus.netIPv4StatusEnabledWAN.equals(status)) { wanList.add(interfaceName); } else if(NetInterfaceStatus.netIPv4StatusEnabledLAN.equals(status) && isNat) { natList.add(interfaceName); } } // create a nat rule for each interface to all potential wan interfaces for(String sourceInterface : natList) { for(String destinationInterface : wanList) { s_logger.debug("Got NAT rule for source: " + sourceInterface +", destination: " + destinationInterface); natConfigs.add(new NATRule(sourceInterface, destinationInterface, true)); } } } return natConfigs; } }
epl-1.0
kumarshantanu/bitumen
src/main/java/net/sf/bitumen/util/IFactory.java
96
package net.sf.bitumen.util; public interface IFactory<T> { public T createInstance(); }
epl-1.0
sunmaolin/test
test-hibernate/src/test/java/rugal/JUnitSpringTestBase.java
784
package rugal; import org.junit.Ignore; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * This is a base test class for non-controller class in testing stage<BR/> * with the assistance of this test base class, there is no need to redeploy web * server over and over again, which is * too time wastage.<BR/> * any class that extends this class could have the capability to test without * web server deployment * <p> * @author Rugal Bernstein */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = config.ApplicationContext.class) @Ignore public abstract class JUnitSpringTestBase { public JUnitSpringTestBase() { } }
epl-1.0
parraman/micobs
mesp/es.uah.aut.srg.micobs.mesp/src/es/uah/aut/srg/micobs/mesp/library/mesplibrary/provider/MMESPVersionedItemPlatformSwPackageItemProvider.java
3477
/******************************************************************************* * Copyright (c) 2013-2015 UAH Space Research Group. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * MICOBS SRG Team - Initial API and implementation ******************************************************************************/ package es.uah.aut.srg.micobs.mesp.library.mesplibrary.provider; import java.util.Collection; import java.util.List; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.edit.provider.IEditingDomainItemProvider; import org.eclipse.emf.edit.provider.IItemLabelProvider; import org.eclipse.emf.edit.provider.IItemPropertyDescriptor; import org.eclipse.emf.edit.provider.IItemPropertySource; import org.eclipse.emf.edit.provider.IStructuredItemContentProvider; import org.eclipse.emf.edit.provider.ITreeItemContentProvider; import es.uah.aut.srg.micobs.mesp.library.mesplibrary.MMESPVersionedItemPlatformSwPackage; /** * This is the item provider adapter for a {@link es.uah.aut.srg.micobs.mesp.library.mesplibrary.MMESPVersionedItemPlatformSwPackage} object. * @generated */ public class MMESPVersionedItemPlatformSwPackageItemProvider extends MMESPPackageVersionedItemWithRepositoryItemProvider implements IEditingDomainItemProvider, IStructuredItemContentProvider, ITreeItemContentProvider, IItemLabelProvider, IItemPropertySource { /** * This constructs an instance from a factory and a notifier. * @generated */ public MMESPVersionedItemPlatformSwPackageItemProvider(AdapterFactory adapterFactory) { super(adapterFactory); } /** * This returns the property descriptors for the adapted class. * @generated */ @Override public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { if (itemPropertyDescriptors == null) { super.getPropertyDescriptors(object); } return itemPropertyDescriptors; } /** * This returns MMESPVersionedItemPlatformSwPackage.gif. * @generated NOT */ @Override public Object getImage(Object object) { return overlayImage(object, getResourceLocator().getImage("full/obj16/Version")); } /** * This returns the label text for the adapted class. * @generated NOT */ @Override public String getText(Object object) { String label = ((MMESPVersionedItemPlatformSwPackage)object).getVersion(); return label == null || label.length() == 0 ? getString("_UI_MMESPVersionedItem_version") : getString("_UI_MMESPVersionedItem_version") + ": " + label; } /** * This handles model notifications by calling {@link #updateChildren} to update any cached * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}. * @generated */ @Override public void notifyChanged(Notification notification) { updateChildren(notification); super.notifyChanged(notification); } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children * that can be created under this object. * @generated */ @Override protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); } }
epl-1.0
debabratahazra/DS
designstudio/components/workbench/core/com.odcgroup.workbench.core/src/main/java/com/odcgroup/workbench/core/preferences/ProjectPreferences.java
4663
package com.odcgroup.workbench.core.preferences; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ProjectScope; import org.eclipse.core.runtime.preferences.DefaultScope; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.eclipse.core.runtime.preferences.IEclipsePreferences.IPreferenceChangeListener; import org.eclipse.core.runtime.preferences.InstanceScope; import org.osgi.service.prefs.BackingStoreException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This is a convenience class for not having to deal with default, instance and project scope preferences directly. * Please note that instances of this class should not be cached or treated as singletons (per project and namespace), * as the preference nodes can "expire", e.g. if a project is removed from the workspace and reimported (see DS-2617). * * So instead of caching the instances, new ones should be created, whenever preferences should be accessed; * the creation of an instance should not be too costly. * * @author Kai Kreuzer * * @since 1.40.0 */ public class ProjectPreferences { private static final Logger logger = LoggerFactory.getLogger(ProjectPreferences.class); private IEclipsePreferences projectPreferences; private IEclipsePreferences defaultPreferences; public ProjectPreferences(IProject project, String namespace) { initPreferenceNodes(project, namespace); } private void initPreferenceNodes(IProject project, String namespace) { if(project!=null) { projectPreferences = new ProjectScope(project).getNode(namespace); } else { projectPreferences = new InstanceScope().getNode(namespace); } defaultPreferences = new DefaultScope().getNode(namespace); } public void addPreferenceChangeListener(IPreferenceChangeListener listener) { projectPreferences.addPreferenceChangeListener(listener); defaultPreferences.addPreferenceChangeListener(listener); } public void removePreferenceChangeListener( IPreferenceChangeListener listener) { try { projectPreferences.removePreferenceChangeListener(listener); } catch(IllegalStateException e) { // ignore if the node has already been removed } try { defaultPreferences.removePreferenceChangeListener(listener); } catch(IllegalStateException e) { // ignore if the node has already been removed } } public void clear() { try { projectPreferences.clear(); } catch (BackingStoreException e) { logger.error("clear() failed with a BackingStoreException", e); } } public void flush() { try { projectPreferences.flush(); } catch (BackingStoreException e) { logger.error("flush() failed with a BackingStoreException", e); } } public String get(String key, String def) { return projectPreferences.get(key, defaultPreferences.get(key, def)); } public boolean getBoolean(String key, boolean def) { return projectPreferences.getBoolean(key, defaultPreferences.getBoolean(key, def)); } public byte[] getByteArray(String key, byte[] def) { return projectPreferences.getByteArray(key, defaultPreferences.getByteArray(key, def)); } public double getDouble(String key, double def) { return projectPreferences.getDouble(key, defaultPreferences.getDouble(key, def)); } public float getFloat(String key, float def) { return projectPreferences.getFloat(key, defaultPreferences.getFloat(key, def)); } public int getInt(String key, int def) { return projectPreferences.getInt(key, defaultPreferences.getInt(key, def)); } public long getLong(String key, long def) { return projectPreferences.getLong(key, defaultPreferences.getLong(key, def)); } public void put(String key, String value) { projectPreferences.put(key, value); } public void putBoolean(String key, boolean value) { projectPreferences.putBoolean(key, value); } public void putByteArray(String key, byte[] value) { projectPreferences.putByteArray(key, value); } public void putDouble(String key, double value) { projectPreferences.putDouble(key, value); } public void putFloat(String key, float value) { projectPreferences.putFloat(key, value); } public void putInt(String key, int value) { projectPreferences.putInt(key, value); } public void putLong(String key, long value) { projectPreferences.putLong(key, value); } public void remove(String key) { projectPreferences.remove(key); } public String[] getAllKeys() { try { return projectPreferences.keys(); } catch (BackingStoreException e) { logger.error("getAllKeys() failed with a BackingStoreException (returning empty list)", e); return new String[0]; } } }
epl-1.0
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/json/rootlevellist/WithXmlRootElementJAXBElementNoRootTestCases.java
3234
/******************************************************************************* * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Denise Smith - 2.4 - April 2012 ******************************************************************************/ package org.eclipse.persistence.testing.jaxb.json.rootlevellist; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import javax.xml.bind.JAXBElement; import javax.xml.namespace.QName; import org.eclipse.persistence.jaxb.MarshallerProperties; import org.eclipse.persistence.jaxb.UnmarshallerProperties; import org.eclipse.persistence.testing.jaxb.json.JSONMarshalUnmarshalTestCases; public class WithXmlRootElementJAXBElementNoRootTestCases extends JSONMarshalUnmarshalTestCases { private static final String CONTROL_JSON = "org/eclipse/persistence/testing/jaxb/json/rootlevellist/WithoutXmlRootElement.json"; public WithXmlRootElementJAXBElementNoRootTestCases(String name) throws Exception { super(name); setClasses(new Class[] {WithXmlRootElementRoot.class}); setControlJSON(CONTROL_JSON); jsonMarshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false); jsonUnmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); } public Class getUnmarshalClass(){ return WithXmlRootElementRoot.class; } @Override protected Collection<JAXBElement<WithXmlRootElementRoot>> getControlObject() { Collection<JAXBElement<WithXmlRootElementRoot>> list = new LinkedHashSet<JAXBElement<WithXmlRootElementRoot>>(2); WithXmlRootElementRoot foo = new WithXmlRootElementRoot(); foo.setName("FOO"); JAXBElement<WithXmlRootElementRoot> jbe1 = new JAXBElement<WithXmlRootElementRoot>(new QName("roottest1"), WithXmlRootElementRoot.class, foo); list.add(jbe1); WithXmlRootElementRoot bar = new WithXmlRootElementRoot(); bar.setName("BAR"); JAXBElement<WithXmlRootElementRoot> jbe2 = new JAXBElement<WithXmlRootElementRoot>(new QName("roottest2"), WithXmlRootElementRoot.class, bar); list.add(jbe2); return list; } @Override public Object getReadControlObject() { List<WithXmlRootElementRoot> list = new ArrayList<WithXmlRootElementRoot>(2); WithXmlRootElementRoot foo = new WithXmlRootElementRoot(); foo.setName("FOO"); list.add(foo); WithXmlRootElementRoot bar = new WithXmlRootElementRoot(); bar.setName("BAR"); list.add(bar); JAXBElement elem = new JAXBElement(new QName(""),WithXmlRootElementRoot.class, list ); return elem; } }
epl-1.0
debabratahazra/DS
designstudio/components/basic/ui/com.odcgroup.basic.ui/src/main/java/com/temenos/t24/tools/eclipse/basic/dialogs/remote/RemoteOperationDialog.java
12222
package com.temenos.t24.tools.eclipse.basic.dialogs.remote; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.InputDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import com.temenos.t24.tools.eclipse.basic.protocols.ftp.RemoteOperationsManager; import com.temenos.t24.tools.eclipse.basic.protocols.ftp.RemoteSite; import com.temenos.t24.tools.eclipse.basic.protocols.ftp.RemoteSitesManager; /** * Abstract class for Remote Operations dialog * * @author vsanjai * */ public abstract class RemoteOperationDialog extends Dialog { protected Text fileNameText; protected Text serverDirText; protected Combo siteNameCombo; protected Combo locationCombo; protected String siteName = ""; protected String fileName = ""; protected String serverDir = ""; protected String folderName = ""; protected Button newFolderButton; protected Button moveFolderButton; protected String currentLocation = null; protected RemoteSite remoteSite = null; protected RemoteSitesManager remoteSitesManager = RemoteSitesManager.getInstance(); protected RemoteOperationsManager remoteOperationsManager = RemoteOperationsManager.getInstance(); protected RemoteSite oldRemoteSite = null; protected Button okButton; protected Label locationLabel; private boolean canEnable = false; protected abstract void initializeDialog(); public RemoteOperationDialog(Shell parentShell) { super(parentShell); } protected void createButtonsForButtonBar(Composite parent) { super.createButtonsForButtonBar(parent); okButton = super.getButton(IDialogConstants.OK_ID); if (okButton != null) { okButton.setEnabled(canEnable); } } protected Control createDialogArea(Composite parent) { Composite container = (Composite) super.createDialogArea(parent); final GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 4; container.setLayout(gridLayout); final Label dialogLabel = new Label(container, SWT.NONE); dialogLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 4, 1)); dialogLabel.setText("Enter the details of remote site"); final Label fileNameLabel = new Label(container, SWT.NONE); fileNameLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false)); fileNameLabel.setText("File Name :"); fileNameLabel.setToolTipText("Name of the remote file"); fileNameText = new Text(container, SWT.BORDER); GridData data = new GridData(GridData.BEGINNING, GridData.BEGINNING, true, false, 3, 1); data.minimumWidth = 150; data.grabExcessVerticalSpace = true; data.minimumHeight = 20; fileNameText.setLayoutData(data); final Label siteNameLabel = new Label(container, SWT.NONE); siteNameLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false)); siteNameLabel.setText("Site Name :"); siteNameLabel.setToolTipText("Name of the remote site"); siteNameCombo = new Combo(container, SWT.DROP_DOWN | SWT.READ_ONLY); GridData siteNameCombData = new GridData(GridData.BEGINNING, GridData.CENTER, true, false, 2, 1); siteNameCombData.minimumWidth = 125; siteNameCombo.setLayoutData(siteNameCombData); new Label(container, SWT.NONE); final Label serverDirLabel = new Label(container, SWT.NONE); serverDirLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false)); serverDirLabel.setText("Directory:"); serverDirLabel.setToolTipText("Server Directory in the remote site. Eg. BP"); serverDirText = new Text(container, SWT.BORDER); serverDirText.setLayoutData(data); locationLabel = new Label(container, SWT.NONE); locationLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false)); locationLabel.setText("Remote Location :"); locationLabel.setToolTipText("Folder location of the file in the remote site"); locationCombo = new Combo(container, SWT.DROP_DOWN | SWT.SIMPLE | SWT.READ_ONLY); GridData locationCombodata = new GridData(GridData.BEGINNING, GridData.CENTER, true, false); locationCombodata.minimumWidth = 350; locationCombo.setLayoutData(locationCombodata); moveFolderButton = new Button(container, SWT.BUTTON1); moveFolderButton.setText(".."); moveFolderButton.setToolTipText("Navigate remote folder"); newFolderButton = new Button(container, SWT.BUTTON1); newFolderButton.setText("New Folder"); newFolderButton.setToolTipText("Create new remote folder"); setupListeners(); initializeDialog(); updateButtons(); return container; } private void setupListeners() { fileNameText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { fileName = fileNameText.getText(); updateButtons(); } }); serverDirText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { serverDir = serverDirText.getText().trim(); if (serverDir.length() <= 0) { locationCombo.setEnabled(true); moveFolderButton.setEnabled(true); newFolderButton.setEnabled(true); } updateButtons(); } }); siteNameCombo.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String siteName = siteNameCombo.getText(); if (siteName == null || siteName.length() <= 0) { return; } if (!RemoteSitesManager.getInstance().connect(siteName)) { if (!remoteOperationsManager.isShowDialog()) { MessageDialog.openError(Display.getDefault().getActiveShell(), "Unable to Connect", "Unable to connect to the " + siteName + " server."); } if(remoteSite != null){ int index = siteNameCombo.indexOf(remoteSite.getSiteName()); if(index != -1){ siteNameCombo.select(index); } }else { siteNameCombo.deselectAll(); } return; } remoteSite = RemoteSitesManager.getInstance().getRemoteSiteFromName(siteName); String location = RemoteOperationsManager.getInstance().getHomeDirectory(remoteSite); currentLocation = location; String[] items = RemoteOperationsManager.getInstance().getDirectoryNames(remoteSite, location); locationCombo.setItems(items); locationCombo.setText(location); updateButtons(); } }); locationCombo.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // Nothing to do } public void widgetSelected(SelectionEvent e) { String location = locationCombo.getText(); if (location.equals(currentLocation)) { return; } currentLocation = location; String[] items = RemoteOperationsManager.getInstance().getDirectoryNames(remoteSite, location); locationCombo.removeAll(); locationCombo.setItems(items); locationCombo.setText(currentLocation); updateButtons(); } }); moveFolderButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // Nothing to do } public void widgetSelected(SelectionEvent e) { siteName = siteNameCombo.getText(); String location = remoteOperationsManager.getParentDirectory(remoteSitesManager.getRemoteSiteFromName(siteName), currentLocation); String[] items = RemoteOperationsManager.getInstance().getDirectoryNames(remoteSite, location); currentLocation = location; locationCombo.setItems(items); locationCombo.setText(currentLocation); updateButtons(); } }); newFolderButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { } public void widgetSelected(SelectionEvent e) { folderName = newFolderButton.getText(); siteName = siteNameCombo.getText(); IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); RemoteSiteNewFolderDialog dialog = new RemoteSiteNewFolderDialog(window.getShell()); if (dialog.open() != InputDialog.OK) { return; } else { String newFolderName = dialog.getFolderName(); newFolderName = currentLocation + "/" + newFolderName; if (remoteOperationsManager.createNewDirectory(newFolderName, remoteSitesManager .getRemoteSiteFromName(siteName))) { String[] items = RemoteOperationsManager.getInstance().getDirectoryNames(remoteSite, currentLocation); locationCombo.setItems(items); locationCombo.setText(currentLocation); updateButtons(); } } } }); } public String getSiteName() { return siteName; } public String getCurrentLocation() { return currentLocation; } public String getFileName() { return fileName; } public String getServerDir() { return serverDir; } private void updateButtons() { siteName = siteNameCombo.getText().trim(); currentLocation = locationCombo.getText().trim(); fileName = fileNameText.getText().trim(); serverDir = serverDirText.getText().trim(); disableAllButtons(); if (currentLocation.length() > 0 && locationCombo.isEnabled()) { moveFolderButton.setEnabled(true); } if (locationCombo.isEnabled() && currentLocation.length() > 0 && siteName.length() > 0) { newFolderButton.setEnabled(true); } if (siteName.length() > 0 && fileName.length() > 0 && ((serverDirText.isEnabled() && serverDir.length() > 0) || currentLocation.length() > 0)) { enableOKButton(true); } } private void disableAllButtons() { moveFolderButton.setEnabled(false); newFolderButton.setEnabled(false); enableOKButton(false); } private void enableOKButton(boolean value) { if (value == true) { canEnable = true; } if (okButton != null) { okButton.setEnabled(value); } } }
epl-1.0
sonatype/nexus-public
components/nexus-security/src/main/java/org/sonatype/nexus/security/internal/NexusAuthenticationEventAuditor.java
3144
/* * Sonatype Nexus (TM) Open Source Version * Copyright (c) 2008-present Sonatype, Inc. * All rights reserved. Includes the third-party code listed at http://links.sonatype.com/products/nexus/oss/attributions. * * This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0, * which accompanies this distribution and is available at http://www.eclipse.org/legal/epl-v10.html. * * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. "Sonatype" and "Sonatype Nexus" are trademarks * of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the * Eclipse Foundation. All other trademarks are the property of their respective owners. */ package org.sonatype.nexus.security.internal; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.inject.Named; import javax.inject.Singleton; import org.sonatype.nexus.audit.AuditData; import org.sonatype.nexus.audit.AuditorSupport; import org.sonatype.nexus.common.event.EventAware; import org.sonatype.nexus.security.ClientInfo; import org.sonatype.nexus.security.authc.AuthenticationFailureReason; import org.sonatype.nexus.security.authc.NexusAuthenticationEvent; import com.google.common.collect.Sets; import com.google.common.eventbus.AllowConcurrentEvents; import com.google.common.eventbus.Subscribe; /** * Writes to the audit log for fired {@link NexusAuthenticationEvent} * * @since 3.22 */ @Named @Singleton public class NexusAuthenticationEventAuditor extends AuditorSupport implements EventAware { private static final String DOMAIN = "security.user"; /* for now only log a subset of failure reasons */ private static Set<AuthenticationFailureReason> AUDITABLE_FAILURE_REASONS = new HashSet<>(); static { AUDITABLE_FAILURE_REASONS.add(AuthenticationFailureReason.INCORRECT_CREDENTIALS); } @Subscribe @AllowConcurrentEvents public void on(final NexusAuthenticationEvent event) { Set<AuthenticationFailureReason> failureReasonsToLog = getFailureReasonsToLog(event); if (isRecording() && !failureReasonsToLog.isEmpty()) { AuditData auditData = new AuditData(); auditData.setType("authentication"); auditData.setDomain(DOMAIN); auditData.setTimestamp(event.getEventDate()); Map<String, Object> attributes = auditData.getAttributes(); attributes.put("failureReasons", failureReasonsToLog); attributes.put("wasSuccessful", event.isSuccessful()); if (event.getClientInfo() != null) { ClientInfo clientInfo = event.getClientInfo(); attributes.put("userId", clientInfo.getUserid()); attributes.put("remoteIp", clientInfo.getRemoteIP()); attributes.put("userAgent", clientInfo.getUserAgent()); attributes.put("path", clientInfo.getPath()); } record(auditData); } } private Set<AuthenticationFailureReason> getFailureReasonsToLog(NexusAuthenticationEvent event) { return Sets.intersection(event.getAuthenticationFailureReasons(), AUDITABLE_FAILURE_REASONS); } }
epl-1.0
eNBeWe/elk
plugins/org.eclipse.elk.alg.layered/src/org/eclipse/elk/alg/layered/intermediate/EndLabelPostprocessor.java
3448
/******************************************************************************* * Copyright (c) 2012, 2017 Kiel University and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.elk.alg.layered.intermediate; import java.util.List; import org.eclipse.elk.alg.common.nodespacing.cellsystem.LabelCell; import org.eclipse.elk.alg.layered.graph.LGraph; import org.eclipse.elk.alg.layered.graph.LNode; import org.eclipse.elk.alg.layered.graph.LNode.NodeType; import org.eclipse.elk.alg.layered.options.InternalProperties; import org.eclipse.elk.core.alg.ILayoutProcessor; import org.eclipse.elk.core.math.ElkRectangle; import org.eclipse.elk.core.math.KVector; import org.eclipse.elk.core.util.IElkProgressMonitor; /** * <p>After the {@link EndLabelPreprocessor} has done all the major work for us, each node may have a list of label * cells full of edge end labels associated with it, along with proper label cell coordinates. The problem is that * when the preprocessor was run, the final coordinates of all the nodes (and with that, the final coordinates of all * the edges) were not known yet. Now they are, so the label cell coordinates can be offset accordingly and label * coordinates can be applied.</p> * * <dl> * <dt>Precondition:</dt> * <dd>a layered graph</dd> * <dd>end labels of all edges are contained in label cells associated with nodes</dd> * <dd>label cells have correct sizes and settings and are placed relative to their node's upper left corner</dd> * <dt>Postcondition:</dt> * <dd>end labels have proper coordinates assigned to them</dd> * <dt>Slots:</dt> * <dd>After phase 5.</dd> * <dt>Same-slot dependencies:</dt> * <dd>none</dd> * </dl> */ public final class EndLabelPostprocessor implements ILayoutProcessor<LGraph> { /** * {@inheritDoc} */ public void process(final LGraph layeredGraph, final IElkProgressMonitor monitor) { monitor.begin("End label post-processing", 1); // We iterate over each node's label cells and offset and place them layeredGraph.getLayers().stream() .flatMap(layer -> layer.getNodes().stream()) .filter(node -> node.getType() == NodeType.NORMAL && node.hasProperty(InternalProperties.END_LABELS)) .forEach(node -> processNode(node)); monitor.done(); } private void processNode(final LNode node) { assert node.hasProperty(InternalProperties.END_LABELS); // The node should have a non-empty list of label cells, or something went TERRIBLY WRONG!!! List<LabelCell> endLabelCells = node.getProperty(InternalProperties.END_LABELS); assert !endLabelCells.isEmpty(); KVector nodePos = node.getPosition(); for (LabelCell labelCell : endLabelCells) { ElkRectangle labelCellRect = labelCell.getCellRectangle(); labelCellRect.move(nodePos); labelCell.applyLabelLayout(); } // Remove label cells node.setProperty(InternalProperties.END_LABELS, null); } }
epl-1.0
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/dynamic/util/PersonCustomizer.java
1407
/******************************************************************************* * Copyright (c) 2011, 2012 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * rbarkhouse - 2.2 - initial implementation ******************************************************************************/ package org.eclipse.persistence.testing.jaxb.dynamic.util; import org.eclipse.persistence.config.DescriptorCustomizer; import org.eclipse.persistence.descriptors.ClassDescriptor; import org.eclipse.persistence.oxm.XMLField; import org.eclipse.persistence.oxm.mappings.XMLDirectMapping; public class PersonCustomizer implements DescriptorCustomizer { public void customize(ClassDescriptor descriptor) throws Exception { XMLDirectMapping nameMapping = (XMLDirectMapping) descriptor.getMappingForAttributeName("name"); XMLField nameField = (XMLField) nameMapping.getField(); nameField.setXPath("contact-info/personal-info/name/text()"); } }
epl-1.0
diverse-project/melange
tests/samples/fr.inria.diverse.melange.test.renaming.model/src/some/basepackage/root/subpackage/impl/SubpackageFactoryImpl.java
2568
/** */ package some.basepackage.root.subpackage.impl; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.impl.EFactoryImpl; import org.eclipse.emf.ecore.plugin.EcorePlugin; import some.basepackage.root.subpackage.*; /** * <!-- begin-user-doc --> * An implementation of the model <b>Factory</b>. * <!-- end-user-doc --> * @generated */ public class SubpackageFactoryImpl extends EFactoryImpl implements SubpackageFactory { /** * Creates the default factory implementation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static SubpackageFactory init() { try { SubpackageFactory theSubpackageFactory = (SubpackageFactory)EPackage.Registry.INSTANCE.getEFactory(SubpackagePackage.eNS_URI); if (theSubpackageFactory != null) { return theSubpackageFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new SubpackageFactoryImpl(); } /** * Creates an instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public SubpackageFactoryImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EObject create(EClass eClass) { switch (eClass.getClassifierID()) { case SubpackagePackage.CLASS_B: return createClassB(); case SubpackagePackage.SUPER_B: return createSuperB(); case SubpackagePackage.SUB_A: return createSubA(); default: throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier"); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ClassB createClassB() { ClassBImpl classB = new ClassBImpl(); return classB; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public SuperB createSuperB() { SuperBImpl superB = new SuperBImpl(); return superB; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public SubA createSubA() { SubAImpl subA = new SubAImpl(); return subA; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public SubpackagePackage getSubpackagePackage() { return (SubpackagePackage)getEPackage(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @deprecated * @generated */ @Deprecated public static SubpackagePackage getPackage() { return SubpackagePackage.eINSTANCE; } } //SubpackageFactoryImpl
epl-1.0
tobiasb/CodeFinder
plugins/org.eclipse.recommenders.codesearch.rcp.index/src/org/eclipse/recommenders/codesearch/rcp/index/indexer/interfaces/IClassIndexer.java
647
/** * Copyright (c) 2012 Tobias Boehm. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Tobias Boehm - initial API and implementation. */ package org.eclipse.recommenders.codesearch.rcp.index.indexer.interfaces; import org.apache.lucene.document.Document; import org.eclipse.jdt.core.dom.TypeDeclaration; public interface IClassIndexer extends IIndexer { void indexType(Document document, TypeDeclaration type); }
epl-1.0
NABUCCO/org.nabucco.framework.generator
org.nabucco.framework.generator.compiler/src/main/org/nabucco/framework/generator/compiler/transformation/java/visitor/util/spp/StructuredPropertyPathViewModelElementFactory.java
10144
/* * Copyright 2012 PRODYNA AG * * Licensed under the Eclipse Public License (EPL), Version 1.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.opensource.org/licenses/eclipse-1.0.php or * http://www.nabucco.org/License.html * * 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.nabucco.framework.generator.compiler.transformation.java.visitor.util.spp; import java.util.Arrays; import java.util.Collections; import java.util.StringTokenizer; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.FieldReference; import org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.ThisReference; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.nabucco.framework.generator.compiler.transformation.util.NabuccoTransformationUtility; import org.nabucco.framework.mda.model.java.JavaModelException; import org.nabucco.framework.mda.model.java.ast.element.JavaAstElementFactory; import org.nabucco.framework.mda.model.java.ast.produce.JavaAstModelProducer; /** * StructuredPropertyPathElementFactory * * @author Silas Schwarz PRODYNA AG */ public class StructuredPropertyPathViewModelElementFactory { private static StructuredPropertyPathViewModelElementFactory instance; /** * @return Returns the instance. */ public static StructuredPropertyPathViewModelElementFactory getInstance() { if (instance == null) { instance = new StructuredPropertyPathViewModelElementFactory(); } return instance; } private StructuredPropertyPathViewModelElementFactory() { } /** * Creates a getter method for a given {@link StructuredPropertyPath} root element and a * absolute name. This method checks several conditions in order to determinate how the method * should look like. taken in to account are the element type * {@link StructuredPropertyPathEntryType} the multiplicity and location in the path (special * treatment for cases such as the parent is a set) * * @param root * the root element of the {@link StructuredPropertyPath} * @param name * the absolute mapped property name * @return a getter methods * @throws JavaModelException */ public MethodDeclaration createGetter(StructuredPropertyPathEntry root, String name) throws JavaModelException { String orginalPath = name; StructuredPropertyPathEntry entry = root.getEntry(name); JavaAstModelProducer modelProducer = JavaAstModelProducer.getInstance(); JavaAstElementFactory elementFactory = JavaAstElementFactory.getInstance(); name = OperationType.GETTER.format(convertToMethodName(name)); MethodDeclaration methodDeclaration = modelProducer.createMethodDeclaration(name, null, false); switch (entry.getEntryType()) { case BASETYPE: { elementFactory.getJavaAstMethod().setReturnType(methodDeclaration, modelProducer.createTypeReference("String", false)); if (!isParentSet(root, orginalPath)) { methodDeclaration.statements = new Statement[] { modelProducer .createReturnStatement(CommonOperationSupport.createNullSaveGetterChain( modelProducer.createThisReference(), orginalPath.concat(".value"))) }; } else { methodDeclaration.statements = new Statement[] { modelProducer.createReturnStatement(modelProducer .createFieldThisReference(convertToMethodName(orginalPath))) }; } break; } case ENUMERATION: { elementFactory.getJavaAstMethod().setReturnType(methodDeclaration, modelProducer.createTypeReference("String", false)); MessageSend getterChain = CommonOperationSupport.createGetterChain(modelProducer.createThisReference(), orginalPath); getterChain = modelProducer.createMessageSend("name", getterChain, Collections.<Expression> emptyList()); methodDeclaration.statements = new Statement[] { modelProducer.createReturnStatement(CommonOperationSupport .getNullChecks(getterChain, OperationType.GETTER)) }; break; } case DATATYPE: { if (entry.isMultiple()) { TypeReference parameterizedTypeReference = modelProducer.createParameterizedTypeReference("Set", false, Arrays.asList(new TypeReference[] { entry.getTypeReference() })); elementFactory.getJavaAstMethod().setReturnType(methodDeclaration, parameterizedTypeReference); } else { elementFactory.getJavaAstMethod().setReturnType(methodDeclaration, entry.getTypeReference()); if (isRootEntry(root, orginalPath)) { methodDeclaration.statements = new Statement[] { modelProducer.createReturnStatement(modelProducer .createFieldThisReference(orginalPath)) }; } // no else case only getter for rooted datatypes } break; } case ROOT: default: { throw new IllegalStateException("unreachable access in create getter for structured property support"); } } return methodDeclaration; } /** * Creates a setter method for a given {@link StructuredPropertyPath} root element and a * absolute name. This method checks several conditions in order to determinate how the method * should look like. taken in to account are the element type * {@link StructuredPropertyPathEntryType} the multiplicity and location in the path (special * treatment for cases such as the parent is a set) * * @param root * the root element of the {@link StructuredPropertyPath} * @param name * the absolute mapped property name * @return a setter methods * @throws JavaModelException */ public MethodDeclaration createSetter(StructuredPropertyPathEntry root, String name) throws JavaModelException { String orginalPath = name; StructuredPropertyPathEntry entry = root.getEntry(name); JavaAstModelProducer modelProducer = JavaAstModelProducer.getInstance(); JavaAstElementFactory elementFactory = JavaAstElementFactory.getInstance(); String propertyName = NabuccoTransformationUtility.firstToLower(convertToMethodName(name)); name = OperationType.SETTER.format(propertyName); MethodDeclaration methodDeclaration = modelProducer.createMethodDeclaration(name, null, false); switch (entry.getEntryType()) { case BASETYPE: { if (isParentSet(root, orginalPath)) { elementFactory.getJavaAstMethod().addArgument(methodDeclaration, modelProducer.createArgument(propertyName, modelProducer.createTypeReference("String", false))); ThisReference thisReference = modelProducer.createThisReference(); FieldReference fieldReference = modelProducer.createFieldThisReference(propertyName); SingleNameReference parameterReference = modelProducer.createSingleNameReference(propertyName); methodDeclaration.statements = new Statement[] { modelProducer .createMessageSend("updateProperty", thisReference, Arrays.asList(new Expression[] { fieldReference, modelProducer.createAssignment(fieldReference, modelProducer .createConditionalExpression( CommonOperationSupport.createNullCheck(parameterReference), parameterReference, CommonOperationSupport.getEmptyStringLiteral())) })) }; } else { } break; } case DATATYPE: { if (entry.isMultiple()) { } else { elementFactory.getJavaAstMethod().addArgument( methodDeclaration, modelProducer.createArgument(propertyName, modelProducer.createTypeReference(entry.getTypeReference().toString(), false))); } break; } case ENUMERATION: { break; } case ROOT: break; default: { } } return methodDeclaration; } /** * @param root * @param orginalPath * @return */ private boolean isParentSet(StructuredPropertyPathEntry root, String orginalPath) { int index = orginalPath.lastIndexOf(StructuredPropertyPathEntry.SEPARATOR); if (index > 0) { return root.getEntry(orginalPath.substring(0, index)).isMultiple(); } return false; } private String convertToMethodName(String path) { StringTokenizer st = new StringTokenizer(path, StructuredPropertyPathEntry.SEPARATOR.toString()); path = ""; while (st.hasMoreTokens()) { path = path.concat(NabuccoTransformationUtility.firstToUpper(st.nextToken())); } return path; } private boolean isRootEntry(StructuredPropertyPathEntry root, String path) { return !(path.split("\\" + StructuredPropertyPathEntry.SEPARATOR.toString()).length > 1); } }
epl-1.0
NABUCCO/org.nabucco.framework.generator
org.nabucco.framework.generator/conf/nbc/templates/java/browserview/BrowserViewHelperTemplate.java
2017
/* * Copyright 2012 PRODYNA AG * * Licensed under the Eclipse Public License (EPL), Version 1.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.opensource.org/licenses/eclipse-1.0.php or * http://www.nabucco.org/License.html * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2010 PRODYNA AG * * Licensed under the Eclipse Public License (EPL), Version 1.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.opensource.org/licenses/eclipse-1.0.php or * http://nabuccosource.org/License.html * * 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. */ /** * BrowserViewHelperTemplate. * * @author Stefanie Feld, PRODYNA AG */ public class BrowserViewHelperTemplate{ public void getValues() { result.put(EditViewModel.PROPERTY, viewModel.getProperty()); } protected void createChildrenList() { if (datatype.getPropertyList().size() > 0) { Datatype datatype[] = datatype.getDatatypeList().toArray( new Datatype[0]); super.addBrowserElement(new DatatypeListBrowserElement(datatype)); } } protected void createChildren() { if(datatype.getProperty() != null){ super.addBrowserElement(new DatatypeBrowserElement(datatype.getProperty())); } } }
epl-1.0
bluezio/simplified-bpmn-example
org.eclipse.epsilon.eugenia.bpmn.diagram/src/SimpleBPMN/diagram/edit/commands/ORCreateCommand.java
2529
/* * */ package SimpleBPMN.diagram.edit.commands; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.emf.ecore.EObject; import org.eclipse.gmf.runtime.common.core.command.CommandResult; import org.eclipse.gmf.runtime.common.core.command.ICommand; import org.eclipse.gmf.runtime.emf.type.core.IElementType; import org.eclipse.gmf.runtime.emf.type.core.commands.EditElementCommand; import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest; import org.eclipse.gmf.runtime.emf.type.core.requests.CreateElementRequest; import org.eclipse.gmf.runtime.notation.View; /** * @generated */ public class ORCreateCommand extends EditElementCommand { /** * @generated */ public ORCreateCommand(CreateElementRequest req) { super(req.getLabel(), null, req); } /** * FIXME: replace with setElementToEdit() * @generated */ protected EObject getElementToEdit() { EObject container = ((CreateElementRequest) getRequest()) .getContainer(); if (container instanceof View) { container = ((View) container).getElement(); } return container; } /** * @generated */ public boolean canExecute() { return true; } /** * @generated */ protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { SimpleBPMN.OR newElement = SimpleBPMN.SimpleBPMNFactory.eINSTANCE .createOR(); SimpleBPMN.BusinessProcessDiagram owner = (SimpleBPMN.BusinessProcessDiagram) getElementToEdit(); owner.getElements().add(newElement); doConfigure(newElement, monitor, info); ((CreateElementRequest) getRequest()).setNewElement(newElement); return CommandResult.newOKCommandResult(newElement); } /** * @generated */ protected void doConfigure(SimpleBPMN.OR newElement, IProgressMonitor monitor, IAdaptable info) throws ExecutionException { IElementType elementType = ((CreateElementRequest) getRequest()) .getElementType(); ConfigureRequest configureRequest = new ConfigureRequest( getEditingDomain(), newElement, elementType); configureRequest.setClientContext(((CreateElementRequest) getRequest()) .getClientContext()); configureRequest.addParameters(getRequest().getParameters()); ICommand configureCommand = elementType .getEditCommand(configureRequest); if (configureCommand != null && configureCommand.canExecute()) { configureCommand.execute(monitor, info); } } }
epl-1.0
TIYdoc/AutoRefactor
samples/src/test/java/org/autorefactor/refactoring/rules/samples_out/PrimitiveWrapperCreationSample.java
3219
/* * AutoRefactor - Eclipse plugin to automatically refactor Java code bases. * * Copyright (C) 2013 Jean-Noël Rouvignac - initial API and implementation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program under LICENSE-GNUGPL. If not, see * <http://www.gnu.org/licenses/>. * * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution under LICENSE-ECLIPSE, and is * available at http://www.eclipse.org/legal/epl-v10.html */ package org.autorefactor.refactoring.rules.samples_out; public class PrimitiveWrapperCreationSample { public static void replaceWrapperConstructorsWithValueOf() { // Replace all calls to wrapper constructors with calls to .valueOf() methods byte b = 4; Byte by = Byte.valueOf(b); Boolean bo = Boolean.valueOf(true); Character c = Character.valueOf('c'); Double d = Double.valueOf(1); Float f = Float.valueOf(1); Long l = Long.valueOf(1); short s = 1; Short sh = Short.valueOf(s); Integer i = Integer.valueOf(1); } public static void removeUnnecessaryObjectCreation() { Byte.parseByte("0"); Boolean.valueOf("true"); Integer.parseInt("42"); Long.parseLong("42"); // nothing for Short? Float.parseFloat("42.42"); Double.parseDouble("42.42"); } public static void convertValueOfCallsToParseCallsInPrimitiveContext() { byte by1 = Byte.parseByte("0"); byte by2 = Byte.parseByte("0", 10); boolean bo = Boolean.parseBoolean("true"); int i1 = Integer.parseInt("42"); int i2 = Integer.parseInt("42", 10); long l1 = Long.parseLong("42"); long l2 = Long.parseLong("42", 10); short s1 = Short.parseShort("42"); short s2 = Short.parseShort("42", 10); float f = Float.parseFloat("42.42"); double d = Double.parseDouble("42.42"); } public static void removeUnnecessaryValueOfCallsInPrimitiveContext() { byte by = (byte) 0; boolean bo1 = true; boolean bo2 = true; int i = 42; long l = 42; short s = (short) 42; float f = 42.42F; double d = 42.42; } public static void removeUnnecessaryConstructorInvocationsInPrimitiveContext() { byte by = (byte) 0; boolean bo = true; int i = 42; long l = 42; short s = (short) 42; float f = 42.42F; double d = 42.42; } }
epl-1.0
CloudScale-Project/Environment
plugins/org.scaledl.overview/src/org/scaledl/overview/specification/impl/SpecificationPackageImpl.java
38978
/** */ package org.scaledl.overview.specification.impl; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.impl.EPackageImpl; import org.scaledl.overview.OverviewPackage; import org.scaledl.overview.application.ApplicationPackage; import org.scaledl.overview.application.impl.ApplicationPackageImpl; import org.scaledl.overview.architecture.ArchitecturePackage; import org.scaledl.overview.architecture.impl.ArchitecturePackageImpl; import org.scaledl.overview.core.CorePackage; import org.scaledl.overview.core.impl.CorePackageImpl; import org.scaledl.overview.deployment.DeploymentPackage; import org.scaledl.overview.deployment.impl.DeploymentPackageImpl; import org.scaledl.overview.impl.OverviewPackageImpl; import org.scaledl.overview.parametertype.ParametertypePackage; import org.scaledl.overview.parametertype.impl.ParametertypePackageImpl; import org.scaledl.overview.specification.AvailabilityZoneDescriptor; import org.scaledl.overview.specification.CloudEnvironmentDescriptor; import org.scaledl.overview.specification.CloudSpecification; import org.scaledl.overview.specification.ComputingInfrastructureServiceDescriptor; import org.scaledl.overview.specification.ComputingResourceDescriptor; import org.scaledl.overview.specification.ExternalSoftwareServiceDescriptor; import org.scaledl.overview.specification.InfrastructureServiceDescriptor; import org.scaledl.overview.specification.NetworkInfrastructureServiceDescriptor; import org.scaledl.overview.specification.PlatformRuntimeServiceDescriptor; import org.scaledl.overview.specification.PlatformServiceDescriptor; import org.scaledl.overview.specification.PlatformSupportServiceDescriptor; import org.scaledl.overview.specification.ProvidedPlatformRuntimeServiceDescriptor; import org.scaledl.overview.specification.ProvidedPlatformServiceDescriptor; import org.scaledl.overview.specification.ProvidedPlatformSupportServiceDescriptor; import org.scaledl.overview.specification.ProvidedServiceDescriptor; import org.scaledl.overview.specification.ProvidedSoftwareServiceDescriptor; import org.scaledl.overview.specification.RegionDescriptor; import org.scaledl.overview.specification.ServiceDescriptor; import org.scaledl.overview.specification.ServiceSpecification; import org.scaledl.overview.specification.SoftwareServiceDescriptor; import org.scaledl.overview.specification.Specification; import org.scaledl.overview.specification.SpecificationFactory; import org.scaledl.overview.specification.SpecificationPackage; import org.scaledl.overview.specification.SystemSpecification; import org.scaledl.overview.specification.sla.SlaPackage; import org.scaledl.overview.specification.sla.impl.SlaPackageImpl; /** * <!-- begin-user-doc --> * An implementation of the model <b>Package</b>. * <!-- end-user-doc --> * @generated */ public class SpecificationPackageImpl extends EPackageImpl implements SpecificationPackage { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass specificationEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass systemSpecificationEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass cloudSpecificationEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass serviceSpecificationEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass descriptorEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass cloudEnvironmentDescriptorEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass regionDescriptorEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass availabilityZoneDescriptorEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass serviceDescriptorEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass providedServiceDescriptorEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass infrastructureServiceDescriptorEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass networkInfrastructureServiceDescriptorEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass computingInfrastructureServiceDescriptorEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass computingResourceDescriptorEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass platformServiceDescriptorEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass platformRuntimeServiceDescriptorEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass platformSupportServiceDescriptorEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass providedPlatformServiceDescriptorEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass providedPlatformRuntimeServiceDescriptorEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass providedPlatformSupportServiceDescriptorEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass softwareServiceDescriptorEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass providedSoftwareServiceDescriptorEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass externalSoftwareServiceDescriptorEClass = null; /** * Creates an instance of the model <b>Package</b>, registered with * {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package * package URI value. * <p>Note: the correct way to create the package is via the static * factory method {@link #init init()}, which also performs * initialization of the package, or returns the registered package, * if one already exists. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.eclipse.emf.ecore.EPackage.Registry * @see org.scaledl.overview.specification.SpecificationPackage#eNS_URI * @see #init() * @generated */ private SpecificationPackageImpl() { super(eNS_URI, SpecificationFactory.eINSTANCE); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static boolean isInited = false; /** * Creates, registers, and initializes the <b>Package</b> for this model, and for any others upon which it depends. * * <p>This method is used to initialize {@link SpecificationPackage#eINSTANCE} when that field is accessed. * Clients should not invoke it directly. Instead, they should simply access that field to obtain the package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #eNS_URI * @see #createPackageContents() * @see #initializePackageContents() * @generated */ public static SpecificationPackage init() { if (isInited) return (SpecificationPackage)EPackage.Registry.INSTANCE.getEPackage(SpecificationPackage.eNS_URI); // Obtain or create and register package SpecificationPackageImpl theSpecificationPackage = (SpecificationPackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof SpecificationPackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new SpecificationPackageImpl()); isInited = true; // Obtain or create and register interdependencies OverviewPackageImpl theOverviewPackage = (OverviewPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(OverviewPackage.eNS_URI) instanceof OverviewPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(OverviewPackage.eNS_URI) : OverviewPackage.eINSTANCE); CorePackageImpl theCorePackage = (CorePackageImpl)(EPackage.Registry.INSTANCE.getEPackage(CorePackage.eNS_URI) instanceof CorePackageImpl ? EPackage.Registry.INSTANCE.getEPackage(CorePackage.eNS_URI) : CorePackage.eINSTANCE); ApplicationPackageImpl theApplicationPackage = (ApplicationPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(ApplicationPackage.eNS_URI) instanceof ApplicationPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(ApplicationPackage.eNS_URI) : ApplicationPackage.eINSTANCE); ArchitecturePackageImpl theArchitecturePackage = (ArchitecturePackageImpl)(EPackage.Registry.INSTANCE.getEPackage(ArchitecturePackage.eNS_URI) instanceof ArchitecturePackageImpl ? EPackage.Registry.INSTANCE.getEPackage(ArchitecturePackage.eNS_URI) : ArchitecturePackage.eINSTANCE); DeploymentPackageImpl theDeploymentPackage = (DeploymentPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(DeploymentPackage.eNS_URI) instanceof DeploymentPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(DeploymentPackage.eNS_URI) : DeploymentPackage.eINSTANCE); SlaPackageImpl theSlaPackage = (SlaPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(SlaPackage.eNS_URI) instanceof SlaPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(SlaPackage.eNS_URI) : SlaPackage.eINSTANCE); ParametertypePackageImpl theParametertypePackage = (ParametertypePackageImpl)(EPackage.Registry.INSTANCE.getEPackage(ParametertypePackage.eNS_URI) instanceof ParametertypePackageImpl ? EPackage.Registry.INSTANCE.getEPackage(ParametertypePackage.eNS_URI) : ParametertypePackage.eINSTANCE); // Create package meta-data objects theSpecificationPackage.createPackageContents(); theOverviewPackage.createPackageContents(); theCorePackage.createPackageContents(); theApplicationPackage.createPackageContents(); theArchitecturePackage.createPackageContents(); theDeploymentPackage.createPackageContents(); theSlaPackage.createPackageContents(); theParametertypePackage.createPackageContents(); // Initialize created meta-data theSpecificationPackage.initializePackageContents(); theOverviewPackage.initializePackageContents(); theCorePackage.initializePackageContents(); theApplicationPackage.initializePackageContents(); theArchitecturePackage.initializePackageContents(); theDeploymentPackage.initializePackageContents(); theSlaPackage.initializePackageContents(); theParametertypePackage.initializePackageContents(); // Mark meta-data to indicate it can't be changed theSpecificationPackage.freeze(); // Update the registry and return the package EPackage.Registry.INSTANCE.put(SpecificationPackage.eNS_URI, theSpecificationPackage); return theSpecificationPackage; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getSpecification() { return specificationEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getSystemSpecification() { return systemSpecificationEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getSystemSpecification_Descriptors() { return (EReference)systemSpecificationEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getCloudSpecification() { return cloudSpecificationEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getCloudSpecification_Descriptor() { return (EReference)cloudSpecificationEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getCloudSpecification_InfrastructureServiceDescriptors() { return (EReference)cloudSpecificationEClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getCloudSpecification_PlatformServiceDescriptors() { return (EReference)cloudSpecificationEClass.getEStructuralFeatures().get(2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getCloudSpecification_SoftwareServiceDescriptors() { return (EReference)cloudSpecificationEClass.getEStructuralFeatures().get(3); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getServiceSpecification() { return serviceSpecificationEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getServiceSpecification_ServiceDescriptors() { return (EReference)serviceSpecificationEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getDescriptor() { return descriptorEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getDescriptor_ProviderID() { return (EAttribute)descriptorEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getCloudEnvironmentDescriptor() { return cloudEnvironmentDescriptorEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getCloudEnvironmentDescriptor_AvailabilityZones() { return (EReference)cloudEnvironmentDescriptorEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getCloudEnvironmentDescriptor_Regions() { return (EReference)cloudEnvironmentDescriptorEClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getRegionDescriptor() { return regionDescriptorEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getAvailabilityZoneDescriptor() { return availabilityZoneDescriptorEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getAvailabilityZoneDescriptor_NetworkInfrastructureServiceDescriptor() { return (EReference)availabilityZoneDescriptorEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getServiceDescriptor() { return serviceDescriptorEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getProvidedServiceDescriptor() { return providedServiceDescriptorEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getProvidedServiceDescriptor_Sla() { return (EReference)providedServiceDescriptorEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getInfrastructureServiceDescriptor() { return infrastructureServiceDescriptorEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getNetworkInfrastructureServiceDescriptor() { return networkInfrastructureServiceDescriptorEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getNetworkInfrastructureServiceDescriptor_Bandwidth() { return (EAttribute)networkInfrastructureServiceDescriptorEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getNetworkInfrastructureServiceDescriptor_Latency() { return (EAttribute)networkInfrastructureServiceDescriptorEClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getComputingInfrastructureServiceDescriptor() { return computingInfrastructureServiceDescriptorEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getComputingInfrastructureServiceDescriptor_ComputingResourceDescriptors() { return (EReference)computingInfrastructureServiceDescriptorEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getComputingInfrastructureServiceDescriptor_GeneralPurpose() { return (EAttribute)computingInfrastructureServiceDescriptorEClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getComputingResourceDescriptor() { return computingResourceDescriptorEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getComputingResourceDescriptor_Editable() { return (EAttribute)computingResourceDescriptorEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getComputingResourceDescriptor_Memory() { return (EAttribute)computingResourceDescriptorEClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getComputingResourceDescriptor_Cpu() { return (EAttribute)computingResourceDescriptorEClass.getEStructuralFeatures().get(2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getComputingResourceDescriptor_CpuUnits() { return (EAttribute)computingResourceDescriptorEClass.getEStructuralFeatures().get(3); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getComputingResourceDescriptor_Storage() { return (EAttribute)computingResourceDescriptorEClass.getEStructuralFeatures().get(4); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getPlatformServiceDescriptor() { return platformServiceDescriptorEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getPlatformRuntimeServiceDescriptor() { return platformRuntimeServiceDescriptorEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getPlatformSupportServiceDescriptor() { return platformSupportServiceDescriptorEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getProvidedPlatformServiceDescriptor() { return providedPlatformServiceDescriptorEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getProvidedPlatformServiceDescriptor_InfrastructureServiceDescriptor() { return (EReference)providedPlatformServiceDescriptorEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getProvidedPlatformRuntimeServiceDescriptor() { return providedPlatformRuntimeServiceDescriptorEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getProvidedPlatformSupportServiceDescriptor() { return providedPlatformSupportServiceDescriptorEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getSoftwareServiceDescriptor() { return softwareServiceDescriptorEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getProvidedSoftwareServiceDescriptor() { return providedSoftwareServiceDescriptorEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getProvidedSoftwareServiceDescriptor_Operations() { return (EReference)providedSoftwareServiceDescriptorEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getExternalSoftwareServiceDescriptor() { return externalSoftwareServiceDescriptorEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public SpecificationFactory getSpecificationFactory() { return (SpecificationFactory)getEFactoryInstance(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private boolean isCreated = false; /** * Creates the meta-model objects for the package. This method is * guarded to have no affect on any invocation but its first. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void createPackageContents() { if (isCreated) return; isCreated = true; // Create classes and their features specificationEClass = createEClass(SPECIFICATION); systemSpecificationEClass = createEClass(SYSTEM_SPECIFICATION); createEReference(systemSpecificationEClass, SYSTEM_SPECIFICATION__DESCRIPTORS); cloudSpecificationEClass = createEClass(CLOUD_SPECIFICATION); createEReference(cloudSpecificationEClass, CLOUD_SPECIFICATION__DESCRIPTOR); createEReference(cloudSpecificationEClass, CLOUD_SPECIFICATION__INFRASTRUCTURE_SERVICE_DESCRIPTORS); createEReference(cloudSpecificationEClass, CLOUD_SPECIFICATION__PLATFORM_SERVICE_DESCRIPTORS); createEReference(cloudSpecificationEClass, CLOUD_SPECIFICATION__SOFTWARE_SERVICE_DESCRIPTORS); serviceSpecificationEClass = createEClass(SERVICE_SPECIFICATION); createEReference(serviceSpecificationEClass, SERVICE_SPECIFICATION__SERVICE_DESCRIPTORS); descriptorEClass = createEClass(DESCRIPTOR); createEAttribute(descriptorEClass, DESCRIPTOR__PROVIDER_ID); cloudEnvironmentDescriptorEClass = createEClass(CLOUD_ENVIRONMENT_DESCRIPTOR); createEReference(cloudEnvironmentDescriptorEClass, CLOUD_ENVIRONMENT_DESCRIPTOR__AVAILABILITY_ZONES); createEReference(cloudEnvironmentDescriptorEClass, CLOUD_ENVIRONMENT_DESCRIPTOR__REGIONS); regionDescriptorEClass = createEClass(REGION_DESCRIPTOR); availabilityZoneDescriptorEClass = createEClass(AVAILABILITY_ZONE_DESCRIPTOR); createEReference(availabilityZoneDescriptorEClass, AVAILABILITY_ZONE_DESCRIPTOR__NETWORK_INFRASTRUCTURE_SERVICE_DESCRIPTOR); serviceDescriptorEClass = createEClass(SERVICE_DESCRIPTOR); providedServiceDescriptorEClass = createEClass(PROVIDED_SERVICE_DESCRIPTOR); createEReference(providedServiceDescriptorEClass, PROVIDED_SERVICE_DESCRIPTOR__SLA); infrastructureServiceDescriptorEClass = createEClass(INFRASTRUCTURE_SERVICE_DESCRIPTOR); networkInfrastructureServiceDescriptorEClass = createEClass(NETWORK_INFRASTRUCTURE_SERVICE_DESCRIPTOR); createEAttribute(networkInfrastructureServiceDescriptorEClass, NETWORK_INFRASTRUCTURE_SERVICE_DESCRIPTOR__BANDWIDTH); createEAttribute(networkInfrastructureServiceDescriptorEClass, NETWORK_INFRASTRUCTURE_SERVICE_DESCRIPTOR__LATENCY); computingInfrastructureServiceDescriptorEClass = createEClass(COMPUTING_INFRASTRUCTURE_SERVICE_DESCRIPTOR); createEReference(computingInfrastructureServiceDescriptorEClass, COMPUTING_INFRASTRUCTURE_SERVICE_DESCRIPTOR__COMPUTING_RESOURCE_DESCRIPTORS); createEAttribute(computingInfrastructureServiceDescriptorEClass, COMPUTING_INFRASTRUCTURE_SERVICE_DESCRIPTOR__GENERAL_PURPOSE); computingResourceDescriptorEClass = createEClass(COMPUTING_RESOURCE_DESCRIPTOR); createEAttribute(computingResourceDescriptorEClass, COMPUTING_RESOURCE_DESCRIPTOR__EDITABLE); createEAttribute(computingResourceDescriptorEClass, COMPUTING_RESOURCE_DESCRIPTOR__MEMORY); createEAttribute(computingResourceDescriptorEClass, COMPUTING_RESOURCE_DESCRIPTOR__CPU); createEAttribute(computingResourceDescriptorEClass, COMPUTING_RESOURCE_DESCRIPTOR__CPU_UNITS); createEAttribute(computingResourceDescriptorEClass, COMPUTING_RESOURCE_DESCRIPTOR__STORAGE); platformServiceDescriptorEClass = createEClass(PLATFORM_SERVICE_DESCRIPTOR); platformRuntimeServiceDescriptorEClass = createEClass(PLATFORM_RUNTIME_SERVICE_DESCRIPTOR); platformSupportServiceDescriptorEClass = createEClass(PLATFORM_SUPPORT_SERVICE_DESCRIPTOR); providedPlatformServiceDescriptorEClass = createEClass(PROVIDED_PLATFORM_SERVICE_DESCRIPTOR); createEReference(providedPlatformServiceDescriptorEClass, PROVIDED_PLATFORM_SERVICE_DESCRIPTOR__INFRASTRUCTURE_SERVICE_DESCRIPTOR); providedPlatformRuntimeServiceDescriptorEClass = createEClass(PROVIDED_PLATFORM_RUNTIME_SERVICE_DESCRIPTOR); providedPlatformSupportServiceDescriptorEClass = createEClass(PROVIDED_PLATFORM_SUPPORT_SERVICE_DESCRIPTOR); softwareServiceDescriptorEClass = createEClass(SOFTWARE_SERVICE_DESCRIPTOR); providedSoftwareServiceDescriptorEClass = createEClass(PROVIDED_SOFTWARE_SERVICE_DESCRIPTOR); createEReference(providedSoftwareServiceDescriptorEClass, PROVIDED_SOFTWARE_SERVICE_DESCRIPTOR__OPERATIONS); externalSoftwareServiceDescriptorEClass = createEClass(EXTERNAL_SOFTWARE_SERVICE_DESCRIPTOR); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private boolean isInitialized = false; /** * Complete the initialization of the package and its meta-model. This * method is guarded to have no affect on any invocation but its first. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void initializePackageContents() { if (isInitialized) return; isInitialized = true; // Initialize package setName(eNAME); setNsPrefix(eNS_PREFIX); setNsURI(eNS_URI); // Obtain other dependent packages SlaPackage theSlaPackage = (SlaPackage)EPackage.Registry.INSTANCE.getEPackage(SlaPackage.eNS_URI); CorePackage theCorePackage = (CorePackage)EPackage.Registry.INSTANCE.getEPackage(CorePackage.eNS_URI); ApplicationPackage theApplicationPackage = (ApplicationPackage)EPackage.Registry.INSTANCE.getEPackage(ApplicationPackage.eNS_URI); // Add subpackages getESubpackages().add(theSlaPackage); // Create type parameters // Set bounds for type parameters // Add supertypes to classes systemSpecificationEClass.getESuperTypes().add(this.getSpecification()); cloudSpecificationEClass.getESuperTypes().add(this.getSpecification()); serviceSpecificationEClass.getESuperTypes().add(this.getSpecification()); descriptorEClass.getESuperTypes().add(theCorePackage.getEntity()); cloudEnvironmentDescriptorEClass.getESuperTypes().add(this.getDescriptor()); regionDescriptorEClass.getESuperTypes().add(this.getDescriptor()); availabilityZoneDescriptorEClass.getESuperTypes().add(this.getDescriptor()); serviceDescriptorEClass.getESuperTypes().add(this.getDescriptor()); providedServiceDescriptorEClass.getESuperTypes().add(this.getDescriptor()); infrastructureServiceDescriptorEClass.getESuperTypes().add(this.getProvidedServiceDescriptor()); networkInfrastructureServiceDescriptorEClass.getESuperTypes().add(this.getInfrastructureServiceDescriptor()); computingInfrastructureServiceDescriptorEClass.getESuperTypes().add(this.getInfrastructureServiceDescriptor()); computingResourceDescriptorEClass.getESuperTypes().add(this.getDescriptor()); platformServiceDescriptorEClass.getESuperTypes().add(this.getServiceDescriptor()); platformRuntimeServiceDescriptorEClass.getESuperTypes().add(this.getPlatformServiceDescriptor()); platformSupportServiceDescriptorEClass.getESuperTypes().add(this.getPlatformServiceDescriptor()); providedPlatformServiceDescriptorEClass.getESuperTypes().add(this.getPlatformServiceDescriptor()); providedPlatformServiceDescriptorEClass.getESuperTypes().add(this.getProvidedServiceDescriptor()); providedPlatformRuntimeServiceDescriptorEClass.getESuperTypes().add(this.getProvidedPlatformServiceDescriptor()); providedPlatformSupportServiceDescriptorEClass.getESuperTypes().add(this.getProvidedPlatformServiceDescriptor()); softwareServiceDescriptorEClass.getESuperTypes().add(this.getServiceDescriptor()); providedSoftwareServiceDescriptorEClass.getESuperTypes().add(this.getSoftwareServiceDescriptor()); providedSoftwareServiceDescriptorEClass.getESuperTypes().add(this.getProvidedServiceDescriptor()); externalSoftwareServiceDescriptorEClass.getESuperTypes().add(this.getProvidedSoftwareServiceDescriptor()); // Initialize classes and features; add operations and parameters initEClass(specificationEClass, Specification.class, "Specification", IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEClass(systemSpecificationEClass, SystemSpecification.class, "SystemSpecification", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getSystemSpecification_Descriptors(), this.getDescriptor(), null, "descriptors", null, 0, -1, SystemSpecification.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(cloudSpecificationEClass, CloudSpecification.class, "CloudSpecification", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getCloudSpecification_Descriptor(), this.getCloudEnvironmentDescriptor(), null, "descriptor", null, 1, 1, CloudSpecification.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getCloudSpecification_InfrastructureServiceDescriptors(), this.getInfrastructureServiceDescriptor(), null, "infrastructureServiceDescriptors", null, 0, -1, CloudSpecification.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getCloudSpecification_PlatformServiceDescriptors(), this.getProvidedServiceDescriptor(), null, "platformServiceDescriptors", null, 0, -1, CloudSpecification.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getCloudSpecification_SoftwareServiceDescriptors(), this.getProvidedServiceDescriptor(), null, "softwareServiceDescriptors", null, 0, -1, CloudSpecification.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(serviceSpecificationEClass, ServiceSpecification.class, "ServiceSpecification", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getServiceSpecification_ServiceDescriptors(), this.getServiceDescriptor(), null, "serviceDescriptors", null, 0, -1, ServiceSpecification.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(descriptorEClass, org.scaledl.overview.specification.Descriptor.class, "Descriptor", IS_ABSTRACT, IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getDescriptor_ProviderID(), ecorePackage.getEString(), "providerID", null, 0, 1, org.scaledl.overview.specification.Descriptor.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(cloudEnvironmentDescriptorEClass, CloudEnvironmentDescriptor.class, "CloudEnvironmentDescriptor", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getCloudEnvironmentDescriptor_AvailabilityZones(), this.getAvailabilityZoneDescriptor(), null, "availabilityZones", null, 0, -1, CloudEnvironmentDescriptor.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getCloudEnvironmentDescriptor_Regions(), this.getRegionDescriptor(), null, "regions", null, 0, -1, CloudEnvironmentDescriptor.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(regionDescriptorEClass, RegionDescriptor.class, "RegionDescriptor", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEClass(availabilityZoneDescriptorEClass, AvailabilityZoneDescriptor.class, "AvailabilityZoneDescriptor", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getAvailabilityZoneDescriptor_NetworkInfrastructureServiceDescriptor(), this.getNetworkInfrastructureServiceDescriptor(), null, "networkInfrastructureServiceDescriptor", null, 1, 1, AvailabilityZoneDescriptor.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(serviceDescriptorEClass, ServiceDescriptor.class, "ServiceDescriptor", IS_ABSTRACT, IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEClass(providedServiceDescriptorEClass, ProvidedServiceDescriptor.class, "ProvidedServiceDescriptor", IS_ABSTRACT, IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getProvidedServiceDescriptor_Sla(), theSlaPackage.getSla(), null, "sla", null, 0, 1, ProvidedServiceDescriptor.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(infrastructureServiceDescriptorEClass, InfrastructureServiceDescriptor.class, "InfrastructureServiceDescriptor", IS_ABSTRACT, IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEClass(networkInfrastructureServiceDescriptorEClass, NetworkInfrastructureServiceDescriptor.class, "NetworkInfrastructureServiceDescriptor", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getNetworkInfrastructureServiceDescriptor_Bandwidth(), ecorePackage.getEInt(), "bandwidth", null, 0, 1, NetworkInfrastructureServiceDescriptor.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getNetworkInfrastructureServiceDescriptor_Latency(), ecorePackage.getEInt(), "latency", null, 0, 1, NetworkInfrastructureServiceDescriptor.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(computingInfrastructureServiceDescriptorEClass, ComputingInfrastructureServiceDescriptor.class, "ComputingInfrastructureServiceDescriptor", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getComputingInfrastructureServiceDescriptor_ComputingResourceDescriptors(), this.getComputingResourceDescriptor(), null, "computingResourceDescriptors", null, 0, -1, ComputingInfrastructureServiceDescriptor.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getComputingInfrastructureServiceDescriptor_GeneralPurpose(), ecorePackage.getEBoolean(), "generalPurpose", null, 0, 1, ComputingInfrastructureServiceDescriptor.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(computingResourceDescriptorEClass, ComputingResourceDescriptor.class, "ComputingResourceDescriptor", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getComputingResourceDescriptor_Editable(), ecorePackage.getEBoolean(), "editable", null, 0, 1, ComputingResourceDescriptor.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getComputingResourceDescriptor_Memory(), ecorePackage.getEInt(), "memory", null, 0, 1, ComputingResourceDescriptor.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getComputingResourceDescriptor_Cpu(), ecorePackage.getEInt(), "cpu", null, 0, 1, ComputingResourceDescriptor.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getComputingResourceDescriptor_CpuUnits(), ecorePackage.getEInt(), "cpuUnits", null, 0, 1, ComputingResourceDescriptor.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getComputingResourceDescriptor_Storage(), ecorePackage.getEInt(), "storage", null, 0, 1, ComputingResourceDescriptor.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(platformServiceDescriptorEClass, PlatformServiceDescriptor.class, "PlatformServiceDescriptor", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEClass(platformRuntimeServiceDescriptorEClass, PlatformRuntimeServiceDescriptor.class, "PlatformRuntimeServiceDescriptor", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEClass(platformSupportServiceDescriptorEClass, PlatformSupportServiceDescriptor.class, "PlatformSupportServiceDescriptor", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEClass(providedPlatformServiceDescriptorEClass, ProvidedPlatformServiceDescriptor.class, "ProvidedPlatformServiceDescriptor", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getProvidedPlatformServiceDescriptor_InfrastructureServiceDescriptor(), this.getComputingInfrastructureServiceDescriptor(), null, "infrastructureServiceDescriptor", null, 0, 1, ProvidedPlatformServiceDescriptor.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(providedPlatformRuntimeServiceDescriptorEClass, ProvidedPlatformRuntimeServiceDescriptor.class, "ProvidedPlatformRuntimeServiceDescriptor", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEClass(providedPlatformSupportServiceDescriptorEClass, ProvidedPlatformSupportServiceDescriptor.class, "ProvidedPlatformSupportServiceDescriptor", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEClass(softwareServiceDescriptorEClass, SoftwareServiceDescriptor.class, "SoftwareServiceDescriptor", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEClass(providedSoftwareServiceDescriptorEClass, ProvidedSoftwareServiceDescriptor.class, "ProvidedSoftwareServiceDescriptor", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getProvidedSoftwareServiceDescriptor_Operations(), theApplicationPackage.getOperation(), null, "operations", null, 1, -1, ProvidedSoftwareServiceDescriptor.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(externalSoftwareServiceDescriptorEClass, ExternalSoftwareServiceDescriptor.class, "ExternalSoftwareServiceDescriptor", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); } } //SpecificationPackageImpl
epl-1.0
maxeler/eclipse
eclipse.jdt.ui/org.eclipse.jdt.junit.core/src/org/eclipse/jdt/internal/junit/model/ITestRunSessionListener.java
816
/******************************************************************************* * Copyright (c) 2000, 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.junit.model; public interface ITestRunSessionListener { /** * @param testRunSession the new session, or <code>null</code> */ void sessionAdded(TestRunSession testRunSession); void sessionRemoved(TestRunSession testRunSession); }
epl-1.0
miklossy/xtext-core
org.eclipse.xtext/src/org/eclipse/xtext/resource/impl/ResourceDescriptionChangeEvent.java
1140
/******************************************************************************* * Copyright (c) 2009 itemis AG (http://www.itemis.eu) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.xtext.resource.impl; import org.eclipse.xtext.resource.IResourceDescription; import org.eclipse.xtext.resource.IResourceDescription.Delta; import com.google.common.collect.ImmutableList; /** * @author Sebastian Zarnekow - Initial contribution and API */ public class ResourceDescriptionChangeEvent implements IResourceDescription.Event { private final ImmutableList<Delta> delta; /** * @since 2.5 */ public ResourceDescriptionChangeEvent(Iterable<IResourceDescription.Delta> delta) { this.delta = ImmutableList.copyOf(delta); } @Override public ImmutableList<IResourceDescription.Delta> getDeltas() { return delta; } }
epl-1.0
fqqb/yamcs-studio
bundles/org.csstudio.ui.util/src/org/csstudio/ui/util/widgets/ImagePreview.java
5149
/******************************************************************************* * Copyright (c) 2010 Oak Ridge National Laboratory. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ package org.csstudio.ui.util.widgets; import java.io.FileInputStream; import java.io.InputStream; import org.csstudio.ui.util.dialogs.ExceptionDetailsErrorDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; /** Widget that displays an image. * * <p>Similar to a Label with image, but image is resized to fit the widget. * * <p>Image can be provided as {@link InputStream}. * * <p>As a shortcut, the widget can also read a file. * * <p>Setting the {@link Image} directly is not supported * to avoid issues with ownership and disposal of such an image. * * @author Kay Kasemir */ public class ImagePreview extends Canvas implements DisposeListener, PaintListener { /** Image or <code>null</code> */ private Image image = null; /** Additional short message or <code>null</code> */ private String message = null; /** Initialize empty * @param parent Parent widget */ public ImagePreview(final Composite parent) { super(parent, 0); addDisposeListener(this); addPaintListener(this); } /** Set image to display * @param image_filename Full path to image file or <code>null</code> for no image */ public void setImage(final String image_filename) { if (image_filename == null) setImage((InputStream) null); else { try { setImage(new FileInputStream(image_filename)); } catch (Exception ex) { ExceptionDetailsErrorDialog.openError(getShell(), "Error", ex); } } } /** Set image to display * @param image_stream Image stream */ public void setImage(final InputStream image_stream) { // Remove previous image, if there was one if (image != null) { image.dispose(); image = null; setToolTipText(""); } if (image_stream == null) return; image = new Image(getDisplay(), image_stream); redraw(); } /** Set a message that is displayed on top of the image * @param message Message to display or <code>null</code> */ public void setMessage(final String message) { this.message = message; redraw(); } // Note that this is supported by Canvas // public void setToolTipText(final String tooltip); /** @see Control */ @Override public Point computeSize(final int wHint, final int hHint) { if (image == null) return new Point(1, 1); return new Point(200, 200); } /** @see PaintListener */ @Override public void paintControl(final PaintEvent e) { final Rectangle bounds = getBounds(); final GC gc = e.gc; if (image != null) { // Draw image to fit widget bounds, maintaining // aspect ratio final Rectangle img = image.getBounds(); // Start with original size int width = img.width; int height = img.height; int destX = 0; int destY = 0; if (width > bounds.width) { // Too wide? width = bounds.width; height = width * img.height / img.width; } if (height > bounds.height) { // Too high? height = bounds.height; width = height * img.width / img.height; } destX = (bounds.width - width) / 2; destY = (bounds.height - height) / 2; gc.drawImage(image, 0, 0, img.width, img.height, destX, destY, width, height); } if (message != null) { // Show message final Point extend = gc.textExtent(message, SWT.DRAW_DELIMITER); final int x = (bounds.width - extend.x) / 2; final int y = (bounds.height - extend.y) / 2; gc.drawText(message, x, y, SWT.DRAW_DELIMITER | SWT.DRAW_TRANSPARENT); return; } } /** @see DisposeListener */ @Override public void widgetDisposed(final DisposeEvent e) { if (image != null) image.dispose(); } }
epl-1.0
debrief/debrief
org.mwc.cmap.core/src/org/mwc/cmap/core/property_support/lengtheditor/LengthPropertyDescriptor.java
2127
/******************************************************************************* * Debrief - the Open Source Maritime Analysis Application * http://debrief.info * * (C) 2000-2020, Deep Blue C Technology Ltd * * This library is free software; you can redistribute it and/or * modify it under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html) * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *******************************************************************************/ package org.mwc.cmap.core.property_support.lengtheditor; import org.eclipse.jface.viewers.CellEditor; import org.eclipse.jface.viewers.ICellEditorValidator; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.views.properties.TextPropertyDescriptor; import MWC.GenericData.WorldDistance; import MWC.Utilities.ReaderWriter.XML.MWCXMLReader; public class LengthPropertyDescriptor extends TextPropertyDescriptor { public LengthPropertyDescriptor(final Object id, final String displayName) { super(id, displayName); setValidator(new ICellEditorValidator() { @Override public String isValid(final Object value) { if (value instanceof String == false) { return Messages.LengthPropertyDescriptor_InvalidValueType; } String str = (String) value; try { // right, do we end in metres? if so, ditch it if (str.endsWith("m")) str = str.substring(0, str.length() - 2); final double thisLen = MWCXMLReader.readThisDouble(str); new WorldDistance.ArrayLength(thisLen); return null; } catch (final Exception e) { return Messages.LengthPropertyDescriptor_NotValid; } } }); } @Override public CellEditor createPropertyEditor(final Composite parent) { final CellEditor editor = new LengthPropertyCellEditor(parent); if (getValidator() != null) { editor.setValidator(getValidator()); } return editor; } }
epl-1.0
MorphiusYT/MorphCraft
src/main/java/com/morphius/morphcraft/items/materials/ingots/TinIngot.java
388
package com.morphius.morphcraft.items; import com.morphius.morphcraft.MorphCraft; import com.morphius.morphcraft.reference.Reference; import net.minecraft.item.Item; public class TinIngot extends Item { public TinIngot(){ super(); this.setCreativeTab(MorphCraft.TabMorphCraft); this.setUnlocalizedName("TinIngot"); this.setTextureName(Reference.MOD_ID + ":IngotTin"); } }
epl-1.0
sschafer/atomic
org.allmyinfo.opmeta.nodes.core/src/org/allmyinfo/opmeta/nodes/core/GetNodeByKeyDescriptor.java
3959
package org.allmyinfo.opmeta.nodes.core; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.allmyinfo.nodes.NodeKey; import org.allmyinfo.operation.BaseOperation; import org.allmyinfo.operation.MethodDefinition; import org.allmyinfo.operation.Operation; import org.allmyinfo.operation.meta.BaseOperationDescriptorImpl; import org.allmyinfo.operation.meta.BaseSimpleOperandDescriptor; import org.allmyinfo.operation.meta.FactoryContext; import org.allmyinfo.operation.meta.OperandConflictException; import org.allmyinfo.operation.meta.OperandDescriptor; import org.allmyinfo.operation.meta.OperandReader; import org.allmyinfo.operation.meta.OperandWriter; import org.allmyinfo.operation.nodes.core.GetNodeByKey; import org.allmyinfo.operation.nodes.core.GetNodeByKeyWithCreateOption; import org.allmyinfo.operation.nodes.core.GetNodeByKeyWithHandler; import org.eclipse.jdt.annotation.NonNull; public class GetNodeByKeyDescriptor extends BaseOperationDescriptorImpl { private final @NonNull Set<OperandDescriptor> operands; public final @NonNull OperandDescriptor keyOperand = new BaseSimpleOperandDescriptor() { @Override public @NonNull String getName() { return "key"; } @Override protected @NonNull Class<?> getDataType() { return NodeKey.class; } }; public final @NonNull OperandDescriptor handlerOperand = new BaseSimpleOperandDescriptor() { @Override public @NonNull String getName() { return "handler"; } @Override protected @NonNull Class<?> getDataType() { return MethodDefinition.class; } @Override public boolean isRequired() { return false; } }; public final @NonNull OperandDescriptor createOperand = new BaseSimpleOperandDescriptor() { @Override public @NonNull String getName() { return "create"; } @Override protected @NonNull Class<?> getDataType() { return Boolean.class; } @Override public boolean isRequired() { return false; } }; public GetNodeByKeyDescriptor() { final Set<OperandDescriptor> map = new HashSet<OperandDescriptor>(); map.add(keyOperand); map.add(handlerOperand); map.add(createOperand); @SuppressWarnings("null") final @NonNull Set<OperandDescriptor> operands = Collections.unmodifiableSet(map); this.operands = operands; } @Override public @NonNull String getName() { return "getNodeByKey"; } @Override public @NonNull Set<OperandDescriptor> getOperands() { return operands; } @Override public @NonNull Operation getOperation(final @NonNull FactoryContext context, final @NonNull OperandReader reader) { context.setOperation(this); final Operation keyOperation = require(context, reader, keyOperand); final Operation handlerOperation = get(context, reader, handlerOperand); final Operation createOperation = get(context, reader, createOperand); if (handlerOperation != null) { if (createOperation != null) throw new OperandConflictException(handlerOperand, createOperand, this); return new GetNodeByKeyWithHandler(keyOperation, handlerOperation); } if (createOperation != null) return new GetNodeByKeyWithCreateOption(keyOperation, createOperation); return new GetNodeByKey(keyOperation); } @Override public void writeOperation(final @NonNull BaseOperation operation, final @NonNull OperandWriter writer) { if (operation instanceof GetNodeByKeyWithHandler) { final GetNodeByKeyWithHandler castOp = (GetNodeByKeyWithHandler) operation; writer.writeSimpleOperand("key", castOp.keyOp); writer.writeSimpleOperand("handler", castOp.handlerOp); } if (operation instanceof GetNodeByKeyWithCreateOption) { final GetNodeByKeyWithCreateOption castOp = (GetNodeByKeyWithCreateOption) operation; writer.writeSimpleOperand("key", castOp.keyOp); writer.writeSimpleOperand("create", castOp.createOp); } final GetNodeByKey castOp = (GetNodeByKey) operation; writer.writeSimpleOperand("key", castOp.keyOp); } }
epl-1.0
ControlSystemStudio/cs-studio
thirdparty/plugins/org.csstudio.platform.libs.hibernate/project/annotations/src/main/java/org/hibernate/annotations/AnyMetaDefs.java
1583
/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Middleware LLC. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.annotations; import static java.lang.annotation.ElementType.PACKAGE; import static java.lang.annotation.ElementType.TYPE; import java.lang.annotation.Retention; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * Defines @Any and @ManyToAny set of metadata. * Can be defined at the entity level or the package level * * @author Emmanuel Bernard */ @java.lang.annotation.Target( { PACKAGE, TYPE } ) @Retention( RUNTIME ) public @interface AnyMetaDefs { AnyMetaDef[] value(); }
epl-1.0
elucash/eclipse-oxygen
org.eclipse.jdt.core/src/org/eclipse/jdt/internal/core/nd/java/NdMethodParameter.java
3536
/******************************************************************************* * Copyright (c) 2016 Google, Inc and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Stefan Xenos (Google) - Initial implementation *******************************************************************************/ package org.eclipse.jdt.internal.core.nd.java; import java.util.List; import org.eclipse.jdt.internal.core.nd.Nd; import org.eclipse.jdt.internal.core.nd.NdStruct; import org.eclipse.jdt.internal.core.nd.db.IString; import org.eclipse.jdt.internal.core.nd.field.FieldByte; import org.eclipse.jdt.internal.core.nd.field.FieldList; import org.eclipse.jdt.internal.core.nd.field.FieldManyToOne; import org.eclipse.jdt.internal.core.nd.field.FieldString; import org.eclipse.jdt.internal.core.nd.field.StructDef; import org.eclipse.jdt.internal.core.util.CharArrayBuffer; public class NdMethodParameter extends NdStruct { public static final FieldManyToOne<NdTypeSignature> ARGUMENT_TYPE; public static final FieldString NAME; public static final FieldList<NdAnnotation> ANNOTATIONS; public static final FieldByte FLAGS; private static final byte FLG_COMPILER_DEFINED = 0x01; @SuppressWarnings("hiding") public static StructDef<NdMethodParameter> type; static { type = StructDef.create(NdMethodParameter.class); ARGUMENT_TYPE = FieldManyToOne.create(type, NdTypeSignature.USED_AS_METHOD_ARGUMENT); NAME = type.addString(); ANNOTATIONS = FieldList.create(type, NdAnnotation.type); FLAGS = type.addByte(); type.done(); } public NdMethodParameter(Nd nd, long address) { super(nd, address); } public void setType(NdTypeSignature argumentType) { ARGUMENT_TYPE.put(getNd(), this.address, argumentType); } public NdTypeSignature getType() { return ARGUMENT_TYPE.get(getNd(), this.address); } public void setName(char[] name) { NAME.put(getNd(), this.address, name); } public IString getName() { return NAME.get(getNd(), this.address); } public List<NdAnnotation> getAnnotations() { return ANNOTATIONS.asList(getNd(), this.address); } private void setFlag(byte flagConstant, boolean value) { int oldFlags = FLAGS.get(getNd(), this.address); int newFlags = ((oldFlags & ~flagConstant) | (value ? flagConstant : 0)); FLAGS.put(getNd(), this.address, (byte) newFlags); } private boolean getFlag(byte flagConstant) { return (FLAGS.get(getNd(), this.address) & flagConstant) != 0; } public void setCompilerDefined(boolean isCompilerDefined) { setFlag(FLG_COMPILER_DEFINED, isCompilerDefined); } public boolean isCompilerDefined() { return getFlag(FLG_COMPILER_DEFINED); } public String toString() { try { CharArrayBuffer buf = new CharArrayBuffer(); buf.append(getType().toString()); buf.append(" "); //$NON-NLS-1$ buf.append(getName().toString()); return buf.toString(); } catch (RuntimeException e) { // This is called most often from the debugger, so we want to return something meaningful even // if the code is buggy, the database is corrupt, or we don't have a read lock. return super.toString(); } } public NdAnnotation createAnnotation() { return ANNOTATIONS.append(getNd(), getAddress()); } public void allocateAnnotations(int length) { ANNOTATIONS.allocate(getNd(), getAddress(), length); } }
epl-1.0
elucash/eclipse-oxygen
org.eclipse.jdt.core/src/org/eclipse/jdt/internal/core/nd/indexer/WorkspaceSnapshot.java
8427
/******************************************************************************* * Copyright (c) 2017 Google, Inc and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Stefan Xenos (Google) - Initial implementation *******************************************************************************/ package org.eclipse.jdt.internal.core.nd.indexer; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.IParent; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.core.nd.java.JavaIndex; /** * Represents a snapshot of all the indexable objects in the workspace at a given moment in time. */ public final class WorkspaceSnapshot { private Map<IPath, List<IJavaElement>> allIndexables; /** * Enable this to index the content of output folders, in cases where that content exists and is up-to-date. This is * much faster than indexing source files directly. */ public static boolean EXPERIMENTAL_INDEX_OUTPUT_FOLDERS; private WorkspaceSnapshot(Map<IPath, List<IJavaElement>> allIndexables) { this.allIndexables = allIndexables; } public Map<IPath, List<IJavaElement>> getAllIndexables() { return this.allIndexables; } public Set<IPath> allLocations() { return this.allIndexables.keySet(); } public List<IJavaElement> get(IPath next) { List<IJavaElement> result = this.allIndexables.get(next); if (result == null) { return Collections.emptyList(); } return result; } public static WorkspaceSnapshot create(IWorkspaceRoot root, IProgressMonitor monitor) throws CoreException { SubMonitor subMonitor = SubMonitor.convert(monitor); List<IJavaElement> unfilteredIndexables = getAllIndexableObjectsInWorkspace(root, subMonitor.split(3)); // Remove all duplicate indexables (jars which are referenced by more than one project) Map<IPath, List<IJavaElement>> allIndexables = removeDuplicatePaths(unfilteredIndexables); return new WorkspaceSnapshot(allIndexables); } private static IPath getWorkspacePathForRoot(IJavaElement next) { IResource resource = next.getResource(); if (resource != null) { return resource.getFullPath(); } return Path.EMPTY; } private static Map<IPath, List<IJavaElement>> removeDuplicatePaths(List<IJavaElement> allIndexables) { Map<IPath, List<IJavaElement>> paths = new HashMap<>(); HashSet<IPath> workspacePaths = new HashSet<IPath>(); for (IJavaElement next : allIndexables) { IPath nextPath = JavaIndex.getLocationForElement(next); IPath workspacePath = getWorkspacePathForRoot(next); List<IJavaElement> value = paths.get(nextPath); if (value == null) { value = new ArrayList<IJavaElement>(); paths.put(nextPath, value); } else { if (workspacePath != null) { if (workspacePaths.contains(workspacePath)) { continue; } if (!workspacePath.isEmpty()) { Package.logInfo("Found duplicate workspace path for " + workspacePath.toString()); //$NON-NLS-1$ } workspacePaths.add(workspacePath); } } value.add(next); } return paths; } private static List<IJavaElement> getAllIndexableObjectsInWorkspace(IWorkspaceRoot root, IProgressMonitor monitor) throws CoreException { SubMonitor subMonitor = SubMonitor.convert(monitor, 2); List<IJavaElement> allIndexables = new ArrayList<>(); IProject[] projects = root.getProjects(); List<IProject> projectsToScan = new ArrayList<>(); for (IProject next : projects) { if (next.isOpen()) { projectsToScan.add(next); } } Set<IPath> scannedPaths = new HashSet<>(); Set<IResource> resourcesToScan = new HashSet<>(); SubMonitor projectLoopMonitor = subMonitor.split(1).setWorkRemaining(projectsToScan.size()); for (IProject project : projectsToScan) { SubMonitor iterationMonitor = projectLoopMonitor.split(1); try { if (project.isOpen() && project.isNatureEnabled(JavaCore.NATURE_ID)) { IJavaProject javaProject = JavaCore.create(project); IClasspathEntry[] entries = javaProject.getRawClasspath(); if (EXPERIMENTAL_INDEX_OUTPUT_FOLDERS) { IPath defaultOutputLocation = javaProject.getOutputLocation(); for (IClasspathEntry next : entries) { IPath nextOutputLocation = next.getOutputLocation(); if (nextOutputLocation == null) { nextOutputLocation = defaultOutputLocation; } IResource resource = root.findMember(nextOutputLocation); if (resource != null) { resourcesToScan.add(resource); } } } IPackageFragmentRoot[] projectRoots = javaProject.getAllPackageFragmentRoots(); SubMonitor rootLoopMonitor = iterationMonitor.setWorkRemaining(projectRoots.length); for (IPackageFragmentRoot nextRoot : projectRoots) { rootLoopMonitor.split(1); if (!nextRoot.exists()) { continue; } IPath filesystemPath = JavaIndex.getLocationForElement(nextRoot); if (scannedPaths.contains(filesystemPath)) { continue; } scannedPaths.add(filesystemPath); if (nextRoot.getKind() == IPackageFragmentRoot.K_BINARY) { if (nextRoot.isArchive()) { allIndexables.add(nextRoot); } else { collectAllClassFiles(root, allIndexables, nextRoot); } } else { collectAllClassFiles(root, allIndexables, nextRoot); } } } } catch (CoreException e) { Package.log(e); } } collectAllClassFiles(root, allIndexables, resourcesToScan, subMonitor.split(1)); return allIndexables; } private static void collectAllClassFiles(IWorkspaceRoot root, List<? super IClassFile> result, Collection<? extends IResource> toScan, IProgressMonitor monitor) { SubMonitor subMonitor = SubMonitor.convert(monitor); ArrayDeque<IResource> resources = new ArrayDeque<>(); resources.addAll(toScan); while (!resources.isEmpty()) { subMonitor.setWorkRemaining(Math.max(resources.size(), 3000)).split(1); IResource next = resources.removeFirst(); if (next instanceof IContainer) { IContainer container = (IContainer)next; try { for (IResource nextChild : container.members()) { resources.addLast(nextChild); } } catch (CoreException e) { // If an error occurs in one resource, skip it and move on to the next Package.log(e); } } else if (next instanceof IFile) { IFile file = (IFile) next; String extension = file.getFileExtension(); if (Objects.equals(extension, "class")) { //$NON-NLS-1$ IJavaElement element = JavaCore.create(file); if (element instanceof IClassFile) { result.add((IClassFile)element); } } } } } private static void collectAllClassFiles(IWorkspaceRoot root, List<? super IClassFile> result, IParent nextRoot) throws CoreException { for (IJavaElement child : nextRoot.getChildren()) { try { int type = child.getElementType(); if (type == IJavaElement.COMPILATION_UNIT) { continue; } if (!child.exists()) { continue; } if (type == IJavaElement.CLASS_FILE) { result.add((IClassFile)child); } else if (child instanceof IParent) { IParent parent = (IParent) child; collectAllClassFiles(root, result, parent); } } catch (CoreException e) { // Log exceptions, then continue with the next child Package.log(e); } } } }
epl-1.0
stormc/hawkbit
hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLActionFieldsTest.java
4085
/** * Copyright (c) 2015 Bosch Software Innovations GmbH and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.hawkbit.repository.jpa.rsql; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import org.eclipse.hawkbit.repository.ActionFields; import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException; import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest; import org.eclipse.hawkbit.repository.jpa.model.JpaAction; import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action.ActionType; import org.eclipse.hawkbit.repository.model.Action.Status; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.junit.Before; import org.junit.Test; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Slice; import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; @Features("Component Tests - Repository") @Stories("RSQL filter actions") public class RSQLActionFieldsTest extends AbstractJpaIntegrationTest { private JpaTarget target; private JpaAction action; @Before public void setupBeforeTest() { final DistributionSet dsA = testdataFactory.createDistributionSet("daA"); target = (JpaTarget) targetManagement .create(entityFactory.target().create().controllerId("targetId123").description("targetId123")); action = new JpaAction(); action.setActionType(ActionType.SOFT); action.setDistributionSet(dsA); action.setTarget(target); action.setStatus(Status.RUNNING); target.addAction(action); actionRepository.save(action); for (int i = 0; i < 10; i++) { final JpaAction newAction = new JpaAction(); newAction.setActionType(ActionType.SOFT); newAction.setDistributionSet(dsA); newAction.setActive(i % 2 == 0); newAction.setStatus(Status.RUNNING); newAction.setTarget(target); actionRepository.save(newAction); target.addAction(newAction); } } @Test @Description("Test filter action by id") public void testFilterByParameterId() { assertRSQLQuery(ActionFields.ID.name() + "==" + action.getId(), 1); assertRSQLQuery(ActionFields.ID.name() + "==noExist*", 0); assertRSQLQuery(ActionFields.ID.name() + "=in=(" + action.getId() + ",1000000)", 1); assertRSQLQuery(ActionFields.ID.name() + "=out=(" + action.getId() + ",1000000)", 10); } @Test @Description("Test action by status") public void testFilterByParameterStatus() { assertRSQLQuery(ActionFields.STATUS.name() + "==pending", 5); assertRSQLQuery(ActionFields.STATUS.name() + "=in=(pending)", 5); assertRSQLQuery(ActionFields.STATUS.name() + "=out=(pending)", 6); try { assertRSQLQuery(ActionFields.STATUS.name() + "==true", 5); fail("Missing expected RSQLParameterUnsupportedFieldException because status cannot be compared with 'true'"); } catch (final RSQLParameterUnsupportedFieldException e) { } } private void assertRSQLQuery(final String rsqlParam, final long expectedEntities) { final Slice<Action> findEnitity = deploymentManagement.findActionsByTarget(rsqlParam, target.getControllerId(), new PageRequest(0, 100)); final long countAllEntities = deploymentManagement.countActionsByTarget(rsqlParam, target.getControllerId()); assertThat(findEnitity).isNotNull(); assertThat(countAllEntities).isEqualTo(expectedEntities); } }
epl-1.0
vboar/ERPClient
src/ui/purchaseui/PurchaseDocumentPanel.java
1069
package ui.purchaseui; import java.awt.Image; import javax.swing.JFrame; import javax.swing.JPanel; import ui.util.CommodityTablePane; import ui.util.MyButton; import ui.util.MyComboBox; import ui.util.MyLabel; import ui.util.MySpecialTextField; import ui.util.MyTextArea; import config.PanelConfig; @SuppressWarnings("serial") public abstract class PurchaseDocumentPanel extends JPanel{ protected Image bg; protected MyButton addBtn; protected MyButton deleteBtn; protected MyButton addCustomer; protected MyLabel documentId; protected MyLabel customerIdLab; protected MyLabel customerNameLab; protected MyLabel totalLab; protected MyLabel tip; protected MyComboBox storage; protected MySpecialTextField customerTxt; protected MyTextArea remarkTxt; protected CommodityTablePane commodityTable; protected JFrame frame; protected PanelConfig cfg; protected boolean isreturn; public PurchaseDocumentPanel(JFrame frame, boolean isreturn){ this.frame = frame; this.isreturn = isreturn; } abstract protected void initComponent(); }
epl-1.0
ossmeter/ossmeter
platform-extensions/org.ossmeter.platform.metricmanager.rascal/src/org/ossmeter/metricprovider/rascal/trans/model/DatetimeMeasurement.java
2552
/******************************************************************************* * Copyright (c) 2014 OSSMETER Partners. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Jurgen Vinju - Implementation. *******************************************************************************/ package org.ossmeter.metricprovider.rascal.trans.model; import com.googlecode.pongo.runtime.querying.NumericalQueryProducer; import com.googlecode.pongo.runtime.querying.StringQueryProducer; public class DatetimeMeasurement extends Measurement { public DatetimeMeasurement() { super(); super.setSuperTypes("org.ossmeter.metricprovider.rascal.trans.model.Measurement"); URI.setOwningType("org.ossmeter.metricprovider.rascal.trans.model.DatetimeMeasurement"); VALUE.setOwningType("org.ossmeter.metricprovider.rascal.trans.model.DatetimeMeasurement"); TIME_ZONE_HOURS.setOwningType("org.ossmeter.metricprovider.rascal.trans.model.DatetimeMeasurement"); TIME_ZONE_MINS.setOwningType("org.ossmeter.metricprovider.rascal.trans.model.DatetimeMeasurement"); } private static final String VALUE_KEY = "value"; private static final String TIME_ZONE_HOURS_KEY = "tz_hours"; private static final String TIME_ZONE_MINS_KEY = "tz_mins"; public static StringQueryProducer URI = new StringQueryProducer("uri"); public static NumericalQueryProducer VALUE = new NumericalQueryProducer(VALUE_KEY); public static NumericalQueryProducer TIME_ZONE_HOURS = new NumericalQueryProducer(TIME_ZONE_HOURS_KEY); public static NumericalQueryProducer TIME_ZONE_MINS = new NumericalQueryProducer(TIME_ZONE_MINS_KEY); public long getValue() { return parseLong(dbObject.get(VALUE_KEY)+"", 0); } public int getTimezoneHours() { if (dbObject.containsField(TIME_ZONE_HOURS_KEY)) { return parseInteger(dbObject.get(TIME_ZONE_HOURS_KEY) + "", 0); } else { return 0; } } public int getTimezoneMinutes() { if (dbObject.containsField(TIME_ZONE_MINS_KEY)) { return parseInteger(dbObject.get(TIME_ZONE_MINS_KEY) + "", 0); } else { return 0; } } public DatetimeMeasurement setValue(long value, int timezoneHours, int timezoneMinutes) { dbObject.put(VALUE_KEY, value); dbObject.put(TIME_ZONE_HOURS_KEY, timezoneHours); dbObject.put(TIME_ZONE_MINS_KEY, timezoneMinutes); notifyChanged(); return this; } }
epl-1.0
stormc/hawkbit
hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/layouts/CreateUpdateTypeLayout.java
10191
/** * Copyright (c) 2015 Bosch Software Innovations GmbH and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.hawkbit.ui.layouts; import java.util.Optional; import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.model.NamedEntity; import org.eclipse.hawkbit.ui.SpPermissionChecker; import org.eclipse.hawkbit.ui.colorpicker.ColorPickerConstants; import org.eclipse.hawkbit.ui.colorpicker.ColorPickerHelper; import org.eclipse.hawkbit.ui.common.builder.LabelBuilder; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.UIComponentIdProvider; import org.eclipse.hawkbit.ui.utils.UINotification; import org.eclipse.hawkbit.ui.utils.VaadinMessageSource; import org.vaadin.spring.events.EventBus.UIEventBus; import com.vaadin.data.Property.ValueChangeEvent; import com.vaadin.server.Page; import com.vaadin.shared.ui.colorpicker.Color; import com.vaadin.ui.Button; import com.vaadin.ui.TextArea; import com.vaadin.ui.TextField; import com.vaadin.ui.components.colorpicker.ColorChangeEvent; import com.vaadin.ui.components.colorpicker.ColorSelector; /** * Superclass defining common properties and methods for creating/updating * types. */ public abstract class CreateUpdateTypeLayout<E extends NamedEntity> extends AbstractCreateUpdateTagLayout<E> { private static final long serialVersionUID = 5732904956185988397L; protected TextField typeKey; private static final String TYPE_NAME_DYNAMIC_STYLE = "new-tag-name"; private static final String TYPE_DESC_DYNAMIC_STYLE = "new-tag-desc"; public CreateUpdateTypeLayout(final VaadinMessageSource i18n, final EntityFactory entityFactory, final UIEventBus eventBus, final SpPermissionChecker permChecker, final UINotification uiNotification) { super(i18n, entityFactory, eventBus, permChecker, uiNotification); } @Override protected void addListeners() { super.addListeners(); optiongroup.addValueChangeListener(this::optionValueChanged); } @Override protected void createRequiredComponents() { createTagStr = i18n.getMessage("label.create.type"); updateTagStr = i18n.getMessage("label.update.type"); comboLabel = new LabelBuilder().name(i18n.getMessage("label.choose.type")).buildLabel(); colorLabel = new LabelBuilder().name(i18n.getMessage("label.choose.type.color")).buildLabel(); colorLabel.addStyleName(SPUIDefinitions.COLOR_LABEL_STYLE); tagNameComboBox = SPUIComponentProvider.getComboBox(i18n.getMessage("label.combobox.type"), "", null, null, false, "", i18n.getMessage("label.combobox.type")); tagNameComboBox.setId(SPUIDefinitions.NEW_DISTRIBUTION_SET_TYPE_NAME_COMBO); tagNameComboBox.addStyleName(SPUIDefinitions.FILTER_TYPE_COMBO_STYLE); tagNameComboBox.setImmediate(true); tagNameComboBox.setPageLength(SPUIDefinitions.DIST_TYPE_SIZE); tagColorPreviewBtn = new Button(); tagColorPreviewBtn.setId(UIComponentIdProvider.TAG_COLOR_PREVIEW_ID); getPreviewButtonColor(ColorPickerConstants.DEFAULT_COLOR); tagColorPreviewBtn.setStyleName(TAG_DYNAMIC_STYLE); createOptionGroup(permChecker.hasCreateRepositoryPermission(), permChecker.hasUpdateRepositoryPermission()); } @Override protected void setColorToComponents(final Color newColor) { super.setColorToComponents(newColor); createDynamicStyleForComponents(tagName, typeKey, tagDesc, newColor.getCSS()); } /** * Set tag name and desc field border color based on chosen color. * * @param tagName * @param tagDesc * @param taregtTagColor */ private void createDynamicStyleForComponents(final TextField tagName, final TextField typeKey, final TextArea typeDesc, final String typeTagColor) { tagName.removeStyleName(SPUIDefinitions.TYPE_NAME); typeKey.removeStyleName(SPUIDefinitions.TYPE_KEY); typeDesc.removeStyleName(SPUIDefinitions.TYPE_DESC); getDynamicStyles(typeTagColor); tagName.addStyleName(TYPE_NAME_DYNAMIC_STYLE); typeKey.addStyleName(TYPE_NAME_DYNAMIC_STYLE); typeDesc.addStyleName(TYPE_DESC_DYNAMIC_STYLE); } /** * Get target style - Dynamically as per the color picked, cannot be done * from the static css. * * @param colorPickedPreview */ private void getDynamicStyles(final String colorPickedPreview) { Page.getCurrent().getJavaScript() .execute(HawkbitCommonUtil.changeToNewSelectedPreviewColor(colorPickedPreview)); } /** * reset the components. */ @Override protected void reset() { super.reset(); typeKey.clear(); restoreComponentStyles(); setOptionGroupDefaultValue(permChecker.hasCreateRepositoryPermission(), permChecker.hasUpdateRepositoryPermission()); } /** * Listener for option group - Create tag/Update. * * @param event * ValueChangeEvent */ @Override protected void optionValueChanged(final ValueChangeEvent event) { if (updateTagStr.equals(event.getProperty().getValue())) { tagName.clear(); tagDesc.clear(); typeKey.clear(); typeKey.setEnabled(false); tagName.setEnabled(false); populateTagNameCombo(); comboLayout.addComponent(comboLabel); comboLayout.addComponent(tagNameComboBox); } else { typeKey.setEnabled(true); tagName.setEnabled(true); tagName.clear(); tagDesc.clear(); typeKey.clear(); comboLayout.removeComponent(comboLabel); comboLayout.removeComponent(tagNameComboBox); } restoreComponentStyles(); getPreviewButtonColor(ColorPickerConstants.DEFAULT_COLOR); getColorPickerLayout().getSelPreview() .setColor(ColorPickerHelper.rgbToColorConverter(ColorPickerConstants.DEFAULT_COLOR)); } /* * (non-Javadoc) * * @see * com.vaadin.ui.components.colorpicker.ColorSelector#setColor(com.vaadin. * shared.ui.colorpicker .Color) */ @Override public void setColor(final Color color) { if (color == null) { return; } getColorPickerLayout().setSelectedColor(color); getColorPickerLayout().getSelPreview().setColor(getColorPickerLayout().getSelectedColor()); final String colorPickedPreview = getColorPickerLayout().getSelPreview().getColor().getCSS(); if (tagName.isEnabled() && null != getColorPickerLayout().getColorSelect()) { createDynamicStyleForComponents(tagName, typeKey, tagDesc, colorPickedPreview); getColorPickerLayout().getColorSelect().setColor(getColorPickerLayout().getSelPreview().getColor()); } } /** * reset the tag name and tag description component border color. */ @Override protected void restoreComponentStyles() { super.restoreComponentStyles(); typeKey.removeStyleName(TYPE_NAME_DYNAMIC_STYLE); typeKey.addStyleName(SPUIDefinitions.TYPE_KEY); } protected void setColorPickerComponentsColor(final String color) { if (null == color) { getColorPickerLayout() .setSelectedColor(ColorPickerHelper.rgbToColorConverter(ColorPickerConstants.DEFAULT_COLOR)); getColorPickerLayout().getSelPreview().setColor(getColorPickerLayout().getSelectedColor()); getColorPickerLayout().getColorSelect().setColor(getColorPickerLayout().getSelectedColor()); createDynamicStyleForComponents(tagName, typeKey, tagDesc, ColorPickerConstants.DEFAULT_COLOR); getPreviewButtonColor(ColorPickerConstants.DEFAULT_COLOR); } else { getColorPickerLayout().setSelectedColor(ColorPickerHelper.rgbToColorConverter(color)); getColorPickerLayout().getSelPreview().setColor(getColorPickerLayout().getSelectedColor()); getColorPickerLayout().getColorSelect().setColor(getColorPickerLayout().getSelectedColor()); createDynamicStyleForComponents(tagName, typeKey, tagDesc, color); getPreviewButtonColor(color); } } @Override public void colorChanged(final ColorChangeEvent event) { setColor(event.getColor()); for (final ColorSelector select : getColorPickerLayout().getSelectors()) { if (!event.getSource().equals(select) && select.equals(this) && !select.getColor().equals(getColorPickerLayout().getSelectedColor())) { select.setColor(getColorPickerLayout().getSelectedColor()); } } ColorPickerHelper.setRgbSliderValues(getColorPickerLayout()); getPreviewButtonColor(event.getColor().getCSS()); createDynamicStyleForComponents(tagName, typeKey, tagDesc, event.getColor().getCSS()); } private boolean isDuplicateByKey() { final Optional<E> existingType = findEntityByKey(); existingType.ifPresent(type -> uiNotification.displayValidationError(getDuplicateKeyErrorMessage(type))); return existingType.isPresent(); } @Override protected boolean isDuplicate() { return isDuplicateByKey() || super.isDuplicate(); } protected abstract Optional<E> findEntityByKey(); protected abstract String getDuplicateKeyErrorMessage(E existingType); @Override protected void populateTagNameCombo() { // is implemented in the inherited class } @Override protected void setTagDetails(final String tagSelected) { // is implemented in the inherited class } }
epl-1.0
opendaylight/yangtools
model/yang-model-ri/src/main/java/org/opendaylight/yangtools/yang/model/ri/stmt/impl/ref/RefErrorAppTagStatement.java
892
/* * Copyright (c) 2021 PANTHEON.tech, s.r.o. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.yangtools.yang.model.ri.stmt.impl.ref; import org.opendaylight.yangtools.yang.model.api.meta.DeclarationReference; import org.opendaylight.yangtools.yang.model.api.stmt.ErrorAppTagStatement; import org.opendaylight.yangtools.yang.model.spi.meta.AbstractRefStatement; public final class RefErrorAppTagStatement extends AbstractRefStatement<String, ErrorAppTagStatement> implements ErrorAppTagStatement { public RefErrorAppTagStatement(final ErrorAppTagStatement delegate, final DeclarationReference ref) { super(delegate, ref); } }
epl-1.0
opendaylight/packetcable
packetcable-driver/src/main/java/org/pcmm/gates/impl/GateState.java
2490
/* * Copyright (c) 2015 CableLabs and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.pcmm.gates.impl; import com.google.common.base.Objects; import org.pcmm.base.impl.PCMMBaseObject; import org.pcmm.gates.IGateState; import org.umu.cops.stack.COPSMsgParser; /** * Implementation of the IGateID interface */ public class GateState extends PCMMBaseObject implements IGateState { /** * The Gate State value (unsigned 32 bit integer) */ final GateStateType gateState; /** * The Gate State value (unsigned 32 bit integer) */ final GateStateReasonType gateStateReason; /** * Constructor */ public GateState(final GateStateType gateState, final GateStateReasonType gateStateReason) { super(SNum.GATE_STATE, STYPE); this.gateState = gateState; this.gateStateReason = gateStateReason; } @Override public GateStateType getGateState() { return gateState; } @Override public GateStateReasonType getGateStateReason() { return gateStateReason; } @Override protected byte[] getBytes() { return COPSMsgParser.shortToBytes(gateState.getValue()); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof GateID)) { return false; } if (!super.equals(o)) { return false; } final GateState gateSTATE = (GateState) o; return gateState == gateSTATE.gateState; } @Override public int hashCode() { return Objects.hashCode(super.hashCode(), gateState, gateStateReason); } @Override public String toString() { return String.format("%s/%s", gateState.toString(), gateStateReason.toString()); } /** * Returns a GateState object from a byte array * @param data - the data to parse * @return - the object * TODO - make me more robust as RuntimeExceptions can be thrown here. */ public static GateState parse(final byte[] data) { return new GateState(GateStateType.valueOf(COPSMsgParser.bytesToShort(data[0], data[1])), GateStateReasonType.valueOf(COPSMsgParser.bytesToShort(data[2], data[3]))); } }
epl-1.0
miklossy/xtext-core
org.eclipse.xtext.tests/src/org/eclipse/xtext/nodemodel/AbstractNodeTest.java
8268
/******************************************************************************* * Copyright (c) 2010 itemis AG (http://www.itemis.eu) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.xtext.nodemodel; import java.util.NoSuchElementException; import org.eclipse.xtext.nodemodel.impl.AbstractNode; import org.eclipse.xtext.nodemodel.impl.NodeModelBuilder; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * @author Sebastian Zarnekow - Initial contribution and API */ public abstract class AbstractNodeTest extends Assert { protected NodeModelBuilder builder; @Before public void setUp() throws Exception { builder = new NodeModelBuilder(); } @After public void tearDown() throws Exception { builder = null; } protected abstract AbstractNode createNode(); @Test public void testGetParent() { AbstractNode node = createNode(); ICompositeNode parent = builder.newRootNode("input"); builder.addChild(parent, node); assertSame(parent, node.getParent()); } @Test public void testGetParent_NoParent() { AbstractNode node = createNode(); assertNull(node.getParent()); } @Test public void testGetRootNode() { AbstractNode node = createNode(); ICompositeNode rootNode = builder.newRootNode("My input"); builder.addChild(rootNode, node); assertSame(rootNode, node.getRootNode()); } @Test public void testGetRootNode_Parent() { AbstractNode node = createNode(); ICompositeNode rootNode = builder.newRootNode("My input"); ICompositeNode parent = builder.newCompositeNode(null, 0, rootNode); builder.addChild(parent, node); assertSame(rootNode, node.getRootNode()); } @Test public void testGetRootNode_NoParent() { AbstractNode node = createNode(); assertNull(node.getRootNode()); } @Test public void testGetRootNode_NoRoot() { AbstractNode node = createNode(); ICompositeNode parent = new CompositeNode(); builder.addChild(parent, node); assertNull(node.getRootNode()); } @Test public void testIterator_Next() { AbstractNode node = createNode(); BidiIterator<INode> iterator = node.iterator(); assertTrue(iterator.hasNext()); assertSame(node, iterator.next()); assertFalse(iterator.hasNext()); try { iterator.next(); fail("Expected NoSuchElementException"); } catch(NoSuchElementException e) { // ok } } @Test public void testIterator_Previous() { AbstractNode node = createNode(); BidiIterator<INode> iterator = node.iterator(); assertTrue(iterator.hasPrevious()); assertSame(node, iterator.previous()); assertFalse(iterator.hasPrevious()); try { iterator.previous(); fail("Expected NoSuchElementException"); } catch(NoSuchElementException e) { // ok } } @Test public void testIterator_Bidi() { AbstractNode node = createNode(); BidiIterator<INode> iterator = node.iterator(); assertSame(node, iterator.next()); assertTrue(iterator.hasPrevious()); assertSame(node, iterator.previous()); assertTrue(iterator.hasNext()); } @Test public void testTreeIterator_Next() { ICompositeNode rootNode = builder.newRootNode("input"); AbstractNode node = createNode(); builder.addChild(rootNode, node); BidiIterator<INode> iterator = node.iterator(); assertTrue(iterator.hasNext()); assertSame(node, iterator.next()); assertFalse(iterator.hasNext()); try { iterator.next(); fail("Expected NoSuchElementException"); } catch(NoSuchElementException e) { // ok } } @Test public void testTreeIterator_Next_NoParent() { AbstractNode node = createNode(); BidiIterator<INode> iterator = node.iterator(); assertTrue(iterator.hasNext()); assertSame(node, iterator.next()); assertFalse(iterator.hasNext()); try { iterator.next(); fail("Expected NoSuchElementException"); } catch(NoSuchElementException e) { // ok } } @Test public void testTreeIterator_Previous() { ICompositeNode rootNode = builder.newRootNode("input"); AbstractNode node = createNode(); builder.addChild(rootNode, node); BidiIterator<INode> iterator = node.iterator(); assertTrue(iterator.hasPrevious()); assertSame(node, iterator.previous()); assertFalse(iterator.hasPrevious()); try { iterator.previous(); fail("Expected NoSuchElementException"); } catch(NoSuchElementException e) { // ok } } @Test public void testTreeIterator_Previous_NoParent() { AbstractNode node = createNode(); BidiIterator<INode> iterator = node.iterator(); assertTrue(iterator.hasPrevious()); assertSame(node, iterator.previous()); assertFalse(iterator.hasPrevious()); try { iterator.previous(); fail("Expected NoSuchElementException"); } catch(NoSuchElementException e) { // ok } } @Test public void testTreeIterator_Bidi() { ICompositeNode rootNode = builder.newRootNode("input"); AbstractNode node = createNode(); builder.addChild(rootNode, node); BidiIterator<INode> iterator = node.iterator(); assertSame(node, iterator.next()); assertTrue(iterator.hasPrevious()); assertSame(node, iterator.previous()); assertTrue(iterator.hasNext()); } @Test public void testTreeIterator_Bidi_NoParent() { AbstractNode node = createNode(); BidiIterator<INode> iterator = node.iterator(); assertSame(node, iterator.next()); assertTrue(iterator.hasPrevious()); assertSame(node, iterator.previous()); assertTrue(iterator.hasNext()); } public abstract void testGetText_Default(); @Test public void testGetText_NoParent() { AbstractNode node = createNode(); assertNull(node.getText()); } public abstract void testGetText_Empty(); public abstract void testTotalOffset(); public abstract void testTotalEndOffset(); public abstract void testTotalLength(); public abstract void testGetGrammarElement(); public abstract void testGetSyntaxErrorMessage(); public abstract void testGetSemanticElement(); @Test public void testGetNextSibling_SingleChild() { ICompositeNode rootNode = builder.newRootNode("input"); AbstractNode node = createNode(); builder.addChild(rootNode, node); assertFalse(node.hasNextSibling()); assertNull(node.getNextSibling()); } @Test public void testGetNextSibling_FirstChild() { ICompositeNode rootNode = builder.newRootNode("input"); AbstractNode first = createNode(); AbstractNode second = createNode(); builder.addChild(rootNode, first); builder.addChild(rootNode, second); assertTrue(first.hasNextSibling()); assertSame(second, first.getNextSibling()); } @Test public void testGetNextSibling_LastChild() { ICompositeNode rootNode = builder.newRootNode("input"); AbstractNode first = createNode(); AbstractNode second = createNode(); builder.addChild(rootNode, first); builder.addChild(rootNode, second); assertFalse(second.hasNextSibling()); assertNull(second.getNextSibling()); } @Test public void testGetPreviousSibling_SingleChild() { ICompositeNode rootNode = builder.newRootNode("input"); AbstractNode node = createNode(); builder.addChild(rootNode, node); assertFalse(node.hasPreviousSibling()); assertNull(node.getPreviousSibling()); assertFalse(node.hasSiblings()); } @Test public void testGetPreviousSibling_FirstChild() { ICompositeNode rootNode = builder.newRootNode("input"); AbstractNode first = createNode(); AbstractNode second = createNode(); builder.addChild(rootNode, first); builder.addChild(rootNode, second); assertFalse(first.hasPreviousSibling()); assertNull(first.getPreviousSibling()); assertTrue(first.hasSiblings()); } @Test public void testGetPreviousSibling_LastChild() { ICompositeNode rootNode = builder.newRootNode("input"); AbstractNode first = createNode(); AbstractNode second = createNode(); builder.addChild(rootNode, first); builder.addChild(rootNode, second); assertTrue(second.hasPreviousSibling()); assertSame(first, second.getPreviousSibling()); assertTrue(second.hasSiblings()); } }
epl-1.0
miklossy/xtext-core
org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parser/terminalrules/xtextTerminalsTestLanguage/Alternatives.java
1447
/** * generated by Xtext */ package org.eclipse.xtext.parser.terminalrules.xtextTerminalsTestLanguage; import org.eclipse.emf.common.util.EList; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Alternatives</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link org.eclipse.xtext.parser.terminalrules.xtextTerminalsTestLanguage.Alternatives#getGroups <em>Groups</em>}</li> * </ul> * * @see org.eclipse.xtext.parser.terminalrules.xtextTerminalsTestLanguage.XtextTerminalsTestLanguagePackage#getAlternatives() * @model * @generated */ public interface Alternatives extends AbstractElement { /** * Returns the value of the '<em><b>Groups</b></em>' containment reference list. * The list contents are of type {@link org.eclipse.xtext.parser.terminalrules.xtextTerminalsTestLanguage.AbstractElement}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Groups</em>' containment reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Groups</em>' containment reference list. * @see org.eclipse.xtext.parser.terminalrules.xtextTerminalsTestLanguage.XtextTerminalsTestLanguagePackage#getAlternatives_Groups() * @model containment="true" * @generated */ EList<AbstractElement> getGroups(); } // Alternatives
epl-1.0