diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/src/com/android/photos/GalleryActivity.java b/src/com/android/photos/GalleryActivity.java index e62262666..420fc3d51 100644 --- a/src/com/android/photos/GalleryActivity.java +++ b/src/com/android/photos/GalleryActivity.java @@ -1,180 +1,180 @@ /* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.photos; import android.app.ActionBar; import android.app.ActionBar.Tab; import android.app.Activity; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v13.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.Menu; import android.view.MenuItem; import com.android.camera.CameraActivity; import com.android.gallery3d.R; import java.util.ArrayList; public class GalleryActivity extends Activity { private SelectionManager mSelectionManager; private ViewPager mViewPager; private TabsAdapter mTabsAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mViewPager = new ViewPager(this); - mViewPager.setId(R.id.root_view); + mViewPager.setId(R.id.viewpager); setContentView(mViewPager); ActionBar ab = getActionBar(); ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); ab.setDisplayShowHomeEnabled(false); ab.setDisplayShowTitleEnabled(false); mTabsAdapter = new TabsAdapter(this, mViewPager); mTabsAdapter.addTab(ab.newTab().setText(R.string.tab_photos), PhotoSetFragment.class, null); mTabsAdapter.addTab(ab.newTab().setText(R.string.tab_albums), AlbumSetFragment.class, null); if (savedInstanceState != null) { ab.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0)); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("tab", getActionBar().getSelectedNavigationIndex()); } protected SelectionManager getSelectionManager() { if (mSelectionManager == null) { mSelectionManager = new SelectionManager(this); } return mSelectionManager; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.gallery, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_camera: Intent intent = new Intent(this, CameraActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } public static class TabsAdapter extends FragmentPagerAdapter implements ActionBar.TabListener, ViewPager.OnPageChangeListener { private final Context mContext; private final ActionBar mActionBar; private final ViewPager mViewPager; private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>(); static final class TabInfo { private final Class<?> clss; private final Bundle args; TabInfo(Class<?> _class, Bundle _args) { clss = _class; args = _args; } } public TabsAdapter(Activity activity, ViewPager pager) { super(activity.getFragmentManager()); mContext = activity; mActionBar = activity.getActionBar(); mViewPager = pager; mViewPager.setAdapter(this); mViewPager.setOnPageChangeListener(this); } public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) { TabInfo info = new TabInfo(clss, args); tab.setTag(info); tab.setTabListener(this); mTabs.add(info); mActionBar.addTab(tab); notifyDataSetChanged(); } @Override public int getCount() { return mTabs.size(); } @Override public Fragment getItem(int position) { TabInfo info = mTabs.get(position); return Fragment.instantiate(mContext, info.clss.getName(), info.args); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { mActionBar.setSelectedNavigationItem(position); } @Override public void onPageScrollStateChanged(int state) { } @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { Object tag = tab.getTag(); for (int i = 0; i < mTabs.size(); i++) { if (mTabs.get(i) == tag) { mViewPager.setCurrentItem(i); } } } @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { } @Override public void onTabReselected(Tab tab, FragmentTransaction ft) { } } }
true
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mViewPager = new ViewPager(this); mViewPager.setId(R.id.root_view); setContentView(mViewPager); ActionBar ab = getActionBar(); ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); ab.setDisplayShowHomeEnabled(false); ab.setDisplayShowTitleEnabled(false); mTabsAdapter = new TabsAdapter(this, mViewPager); mTabsAdapter.addTab(ab.newTab().setText(R.string.tab_photos), PhotoSetFragment.class, null); mTabsAdapter.addTab(ab.newTab().setText(R.string.tab_albums), AlbumSetFragment.class, null); if (savedInstanceState != null) { ab.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0)); } }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mViewPager = new ViewPager(this); mViewPager.setId(R.id.viewpager); setContentView(mViewPager); ActionBar ab = getActionBar(); ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); ab.setDisplayShowHomeEnabled(false); ab.setDisplayShowTitleEnabled(false); mTabsAdapter = new TabsAdapter(this, mViewPager); mTabsAdapter.addTab(ab.newTab().setText(R.string.tab_photos), PhotoSetFragment.class, null); mTabsAdapter.addTab(ab.newTab().setText(R.string.tab_albums), AlbumSetFragment.class, null); if (savedInstanceState != null) { ab.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0)); } }
diff --git a/SimplePVPToggle/src/com/gmail/jameshealey1994/simplepvptoggle/commands/SimplePVPToggleCommandExecutor.java b/SimplePVPToggle/src/com/gmail/jameshealey1994/simplepvptoggle/commands/SimplePVPToggleCommandExecutor.java index 0b79a59..6e3e313 100644 --- a/SimplePVPToggle/src/com/gmail/jameshealey1994/simplepvptoggle/commands/SimplePVPToggleCommandExecutor.java +++ b/SimplePVPToggle/src/com/gmail/jameshealey1994/simplepvptoggle/commands/SimplePVPToggleCommandExecutor.java @@ -1,52 +1,52 @@ package com.gmail.jameshealey1994.simplepvptoggle.commands; import com.gmail.jameshealey1994.simplepvptoggle.SimplePVPToggle; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; /** * Command executor for the SimplePVPToggle plugin. * @author JamesHealey94 <jameshealey1994.gmail.com> */ public class SimplePVPToggleCommandExecutor implements CommandExecutor { /** * Plugin the commands are executed for. */ private SimplePVPToggle plugin; /** * The default command, executed when no arguments are given. * Can be null, in which case no command is executed. */ private SimplePVPToggleCommand defaultCommand; /** * Constructor to set plugin instance variable. * @param plugin The plugin used to set internal plugin value * @param defaultCommand The default command, executed when no arguments are given. */ public SimplePVPToggleCommandExecutor(SimplePVPToggle plugin, SimplePVPToggleCommand defaultCommand) { this.plugin = plugin; this.defaultCommand = defaultCommand; } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (args.length > 0) { for (SimplePVPToggleCommand command : plugin.getCommands()) { - if (command.getAliases().contains(args[1].toLowerCase())) { + if (command.getAliases().contains(args[0].toLowerCase())) { return command.execute(plugin, sender, label, args); } } } else { // No args given if (defaultCommand == null) { return false; } else { return defaultCommand.execute(plugin, sender, label, args); } } return false; } }
true
true
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (args.length > 0) { for (SimplePVPToggleCommand command : plugin.getCommands()) { if (command.getAliases().contains(args[1].toLowerCase())) { return command.execute(plugin, sender, label, args); } } } else { // No args given if (defaultCommand == null) { return false; } else { return defaultCommand.execute(plugin, sender, label, args); } } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (args.length > 0) { for (SimplePVPToggleCommand command : plugin.getCommands()) { if (command.getAliases().contains(args[0].toLowerCase())) { return command.execute(plugin, sender, label, args); } } } else { // No args given if (defaultCommand == null) { return false; } else { return defaultCommand.execute(plugin, sender, label, args); } } return false; }
diff --git a/orbisgis-ui/src/main/java/org/orbisgis/core/ui/plugins/sql/SQLFunctionsPlugIn.java b/orbisgis-ui/src/main/java/org/orbisgis/core/ui/plugins/sql/SQLFunctionsPlugIn.java index 79c301191..d9d2675b4 100644 --- a/orbisgis-ui/src/main/java/org/orbisgis/core/ui/plugins/sql/SQLFunctionsPlugIn.java +++ b/orbisgis-ui/src/main/java/org/orbisgis/core/ui/plugins/sql/SQLFunctionsPlugIn.java @@ -1,63 +1,63 @@ /* * OrbisGIS is a GIS application dedicated to scientific spatial simulation. * This cross-platform GIS is developed at French IRSTV institute and is able to * manipulate and create vector and raster spatial information. OrbisGIS is * distributed under GPL 3 license. It is produced by the "Atelier SIG" team of * the IRSTV Institute <http://www.irstv.cnrs.fr/> CNRS FR 2488. * * * Team leader Erwan BOCHER, scientific researcher, * * * * Copyright (C) 2007 Erwan BOCHER, Fernando GONZALEZ CORTES, Thomas LEDUC * * Copyright (C) 2010 Erwan BOCHER, Alexis GUEGANNO, Antoine GOURLAY, Adelin PIAU, Gwendall PETIT * * This file is part of OrbisGIS. * * OrbisGIS 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 (at your option) any later * version. * * OrbisGIS 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 * OrbisGIS. If not, see <http://www.gnu.org/licenses/>. * * For more information, please consult: <http://www.orbisgis.org/> * * or contact directly: * info _at_ orbisgis.org */ package org.orbisgis.core.ui.plugins.sql; import org.orbisgis.core.ui.pluginSystem.AbstractPlugIn; import org.orbisgis.core.ui.pluginSystem.PlugInContext; /** * * @author ebocher */ public class SQLFunctionsPlugIn extends AbstractPlugIn { @Override public void initialize(PlugInContext context) throws Exception { context.getFeatureInstaller().addRegisterFunction(MapContext_BBox.class); context.getFeatureInstaller().addRegisterFunction(MapContext_AddLayer.class); - context.getFeatureInstaller().addRegisterFunction(MapContext_ZoomTo.class); + // context.getFeatureInstaller().addRegisterFunction(MapContext_ZoomTo.class); } @Override public boolean execute(PlugInContext context) throws Exception { return true; } @Override public boolean isEnabled() { return true; } }
true
true
public void initialize(PlugInContext context) throws Exception { context.getFeatureInstaller().addRegisterFunction(MapContext_BBox.class); context.getFeatureInstaller().addRegisterFunction(MapContext_AddLayer.class); context.getFeatureInstaller().addRegisterFunction(MapContext_ZoomTo.class); }
public void initialize(PlugInContext context) throws Exception { context.getFeatureInstaller().addRegisterFunction(MapContext_BBox.class); context.getFeatureInstaller().addRegisterFunction(MapContext_AddLayer.class); // context.getFeatureInstaller().addRegisterFunction(MapContext_ZoomTo.class); }
diff --git a/app/controllers/IssueApp.java b/app/controllers/IssueApp.java index e5331b3d..634f3aa4 100644 --- a/app/controllers/IssueApp.java +++ b/app/controllers/IssueApp.java @@ -1,391 +1,389 @@ package controllers; import models.*; import models.enumeration.*; import play.data.DynamicForm; import play.mvc.Http; import views.html.issue.edit; import views.html.issue.view; import views.html.issue.list; import views.html.issue.create; import views.html.error.notfound; import views.html.error.forbidden; import utils.AccessControl; import utils.Callback; import utils.JodaDateUtil; import utils.HttpUtil; import play.data.Form; import play.mvc.Call; import play.mvc.Result; import jxl.write.WriteException; import org.apache.tika.Tika; import com.avaje.ebean.Page; import com.avaje.ebean.ExpressionList; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import static com.avaje.ebean.Expr.icontains; public class IssueApp extends AbstractPostingApp { public static class SearchCondition extends AbstractPostingApp.SearchCondition { public String state; public Boolean commentedCheck; public Long milestoneId; public Set<Long> labelIds; public String authorLoginId; public Long assigneeId; public SearchCondition() { super(); milestoneId = null; state = State.OPEN.name(); commentedCheck = false; } private ExpressionList<Issue> asExpressionList(Project project) { ExpressionList<Issue> el = Issue.finder.where().eq("project.id", project.id); if (filter != null) { el.or(icontains("title", filter), icontains("body", filter)); } if (authorLoginId != null && !authorLoginId.isEmpty()) { User user = User.findByLoginId(authorLoginId); if (!user.isAnonymous()) { el.eq("authorId", user.id); } else { List<Long> ids = new ArrayList<Long>(); for (User u : User.find.where().icontains("loginId", authorLoginId).findList()) { ids.add(u.id); } el.in("authorId", ids); } } if (assigneeId != null) { el.eq("assignee.user.id", assigneeId); el.eq("assignee.project.id", project.id); } if (milestoneId != null) { el.eq("milestone.id", milestoneId); } if (labelIds != null) { for (Long labelId : labelIds) { el.eq("labels.id", labelId); } } if (commentedCheck) { el.ge("numOfComments", AbstractPosting.NUMBER_OF_ONE_MORE_COMMENTS); } State st = State.getValue(state); if (st.equals(State.OPEN) || st.equals(State.CLOSED)) { el.eq("state", st); } if (orderBy != null) { el.orderBy(orderBy + " " + orderDir); } return el; } } /** * νŽ˜μ΄μ§€ 처리된 μ΄μŠˆλ“€μ˜ 리슀트λ₯Ό 보여쀀닀. * * @param projectName * ν”„λ‘œμ νŠΈ 이름 * @param state * 이슈 ν•΄κ²° μƒνƒœ * @return * @throws IOException * @throws WriteException */ public static Result issues(String userName, String projectName, String state, String format, int pageNum) throws WriteException, IOException { Project project = ProjectApp.getProject(userName, projectName); if (!AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.READ)) { return forbidden(views.html.error.forbidden.render(project)); } Form<SearchCondition> issueParamForm = new Form<SearchCondition>(SearchCondition.class); SearchCondition searchCondition = issueParamForm.bindFromRequest().get(); searchCondition.pageNum = pageNum - 1; searchCondition.state = state; String[] labelIds = request().queryString().get("labelIds"); if (labelIds != null) { for (String labelId : labelIds) { searchCondition.labelIds.add(Long.valueOf(labelId)); } } ExpressionList<Issue> el = searchCondition.asExpressionList(project); if (format.equals("xls")) { return issuesAsExcel(el, project); } else { Page<Issue> issues = el .findPagingList(ITEMS_PER_PAGE).getPage(searchCondition.pageNum); return ok(list.render("title.issueList", issues, searchCondition, project)); } } public static Result issuesAsExcel(ExpressionList<Issue> el, Project project) throws WriteException, IOException, UnsupportedEncodingException { byte[] excelData = Issue.excelFrom(el.findList()); String filename = HttpUtil.encodeContentDisposition( project.name + "_issues_" + JodaDateUtil.today().getTime() + ".xls"); response().setHeader("Content-Type", new Tika().detect(filename)); response().setHeader("Content-Disposition", "attachment; " + filename); return ok(excelData); } public static Result issue(String userName, String projectName, Long number) { Project project = ProjectApp.getProject(userName, projectName); Issue issueInfo = Issue.findByNumber(project, number); if (issueInfo == null) { return notFound(views.html.error.notfound.render("error.notfound", project, "issue")); } if (!AccessControl.isAllowed(UserApp.currentUser(), issueInfo.asResource(), Operation.READ)) { return forbidden(views.html.error.forbidden.render(project)); } for (IssueLabel label: issueInfo.labels) { label.refresh(); } Form<Comment> commentForm = new Form<Comment>(Comment.class); Form<Issue> editForm = new Form<Issue>(Issue.class).fill(Issue.findByNumber(project, number)); return ok(view.render("title.issueDetail", issueInfo, editForm, commentForm, project)); } public static Result newIssueForm(String userName, String projectName) { Project project = ProjectApp.getProject(userName, projectName); return newPostingForm(project, ResourceType.ISSUE_POST, create.render("title.newIssue", new Form<Issue>(Issue.class), project)); } /** * μ—¬λŸ¬ 이슈λ₯Ό ν•œλ²ˆμ— κ°±μ‹ ν•˜λ €λŠ” μš”μ²­μ— μ‘λ‹΅ν•œλ‹€. * * when: 이슈 λͺ©λ‘ νŽ˜μ΄μ§€μ—μ„œ 이슈λ₯Ό μ²΄ν¬ν•˜κ³  μƒλ‹¨μ˜ κ°±μ‹  λ“œλ‘­λ°•μŠ€λ₯Ό μ΄μš©ν•΄ μ²΄ν¬ν•œ μ΄μŠˆλ“€μ„ κ°±μ‹ ν•  λ•Œ * * 갱신을 μ‹œλ„ν•œ μ΄μŠˆλ“€ 쀑 ν•˜λ‚˜ 이상 갱신에 μ„±κ³΅ν–ˆλ‹€λ©΄ 이슈 λͺ©λ‘ νŽ˜μ΄μ§€λ‘œ λ¦¬λ‹€μ΄λ ‰νŠΈν•œλ‹€. (303 See Other) * μ–΄λ–€ μ΄μŠˆμ— λŒ€ν•œ κ°±μ‹  μš”μ²­μ΄λ“  λͺ¨λ‘ μ‹€νŒ¨ν–ˆμœΌλ©°, κ·Έ 쀑 κΆŒν•œ 문제둜 μ‹€νŒ¨ν•œ 것이 ν•œ 개 이상 μžˆλ‹€λ©΄ 403 * Forbidden 으둜 μ‘λ‹΅ν•œλ‹€. * κ°±μ‹  μš”μ²­μ΄ 잘λͺ»λœ κ²½μš°μ—” 400 Bad Request 둜 μ‘λ‹΅ν•œλ‹€. * * @param ownerName ν”„λ‘œμ νŠΈ μ†Œμœ μž 이름 * @param projectName ν”„λ‘œμ νŠΈ 이름 * @return * @throws IOException */ public static Result massUpdate(String ownerName, String projectName) throws IOException { Form<IssueMassUpdate> issueMassUpdateForm = new Form<IssueMassUpdate>(IssueMassUpdate.class).bindFromRequest(); if (issueMassUpdateForm.hasErrors()) { return badRequest(issueMassUpdateForm.errorsAsJson()); } IssueMassUpdate issueMassUpdate = issueMassUpdateForm.get(); Project project = Project.findByOwnerAndProjectName(ownerName, projectName); int updatedItems = 0; int rejectedByPermission = 0; for (Issue issue : issueMassUpdate.issues) { issue.refresh(); if (!AccessControl.isAllowed(UserApp.currentUser(), issue.asResource(), Operation.UPDATE)) { rejectedByPermission++; continue; } if (issueMassUpdate.assignee != null) { if (issueMassUpdate.assignee.isAnonymous()) { issue.assignee = null; } else { issue.assignee = Assignee.add(issueMassUpdate.assignee.id, project.id); } } if (issueMassUpdate.state != null) { issue.state = issueMassUpdate.state; } if (issueMassUpdate.milestone != null) { issue.milestone = issueMassUpdate.milestone; } if (issueMassUpdate.attachingLabel != null) { - issue.refresh(); issue.labels.add(issueMassUpdate.attachingLabel); } if (issueMassUpdate.detachingLabel != null) { - issue.refresh(); issue.labels.remove(issueMassUpdate.detachingLabel); } issue.update(); updatedItems++; } if (updatedItems == 0 && rejectedByPermission > 0) { return forbidden(views.html.error.forbidden.render(project)); } return redirect( routes.IssueApp.issues(ownerName, projectName, "all", "html", 1)); } public static Result newIssue(String ownerName, String projectName) throws IOException { Form<Issue> issueForm = new Form<Issue>(Issue.class).bindFromRequest(); Project project = ProjectApp.getProject(ownerName, projectName); if (!AccessControl.isProjectResourceCreatable(UserApp.currentUser(), project, ResourceType.ISSUE_POST)) { return forbidden(views.html.error.forbidden.render(project)); } if (issueForm.hasErrors()) { return badRequest(create.render(issueForm.errors().toString(), issueForm, project)); } Issue newIssue = issueForm.get(); newIssue.createdDate = JodaDateUtil.now(); newIssue.setAuthor(UserApp.currentUser()); newIssue.project = project; newIssue.state = State.OPEN; addLabels(newIssue.labels, request()); setMilestone(issueForm, newIssue); newIssue.save(); // Attach all of the files in the current user's temporary storage. Attachment.moveAll(UserApp.currentUser().asResource(), newIssue.asResource()); return redirect(routes.IssueApp.issue(project.owner, project.name, newIssue.getNumber())); } public static Result editIssueForm(String userName, String projectName, Long number) { Project project = ProjectApp.getProject(userName, projectName); Issue issue = Issue.findByNumber(project, number); if (!AccessControl.isAllowed(UserApp.currentUser(), issue.asResource(), Operation.UPDATE)) { return forbidden(views.html.error.forbidden.render(project)); } Form<Issue> editForm = new Form<Issue>(Issue.class).fill(issue); return ok(edit.render("title.editIssue", editForm, issue, project)); } public static Result editIssue(String userName, String projectName, Long number) throws IOException { Form<Issue> issueForm = new Form<Issue>(Issue.class).bindFromRequest(); final Issue issue = issueForm.get(); setMilestone(issueForm, issue); final Project project = ProjectApp.getProject(userName, projectName); final Issue originalIssue = Issue.findByNumber(project, number); Call redirectTo = routes.IssueApp.issue(project.owner, project.name, number); // updateIssueBeforeSave.run would be called just before this issue is saved. // It updates some properties only for issues, such as assignee or labels, but not for non-issues. Callback updateIssueBeforeSave = new Callback() { @Override public void run() { issue.comments = originalIssue.comments; addLabels(issue.labels, request()); } }; return editPosting(originalIssue, issue, issueForm, redirectTo, updateIssueBeforeSave); } private static void setMilestone(Form<Issue> issueForm, Issue issue) { String milestoneId = issueForm.data().get("milestoneId"); if(milestoneId != null && !milestoneId.isEmpty()) { issue.milestone = Milestone.findById(Long.parseLong(milestoneId)); } } public static Result deleteIssue(String userName, String projectName, Long number) { Project project = ProjectApp.getProject(userName, projectName); Issue issue = Issue.findByNumber(project, number); Call redirectTo = routes.IssueApp.issues(project.owner, project.name, State.OPEN.state(), "html", 1); return delete(issue, issue.asResource(), redirectTo); } public static Result newComment(String ownerName, String projectName, Long number) throws IOException { Project project = Project.findByOwnerAndProjectName(ownerName, projectName); final Issue issue = Issue.findByNumber(project, number); Call redirectTo = routes.IssueApp.issue(project.owner, project.name, number); Form<IssueComment> commentForm = new Form<IssueComment>(IssueComment.class) .bindFromRequest(); if (commentForm.hasErrors()) { return badRequest(commentForm.errors().toString()); } final IssueComment comment = commentForm.get(); return newComment(comment, commentForm, redirectTo, new Callback() { @Override public void run() { comment.issue = issue; } }); } public static Result deleteComment(String userName, String projectName, Long issueNumber, Long commentId) { Comment comment = IssueComment.find.byId(commentId); Project project = comment.asResource().getProject(); Call redirectTo = routes.IssueApp.issue(project.owner, project.name, comment.getParent().id); return delete(comment, comment.asResource(), redirectTo); } public static void addLabels(Set<IssueLabel> labels, Http.Request request) { Http.MultipartFormData multipart = request.body().asMultipartFormData(); Map<String, String[]> form; if (multipart != null) { form = multipart.asFormUrlEncoded(); } else { form = request.body().asFormUrlEncoded(); } String[] labelIds = form.get("labelIds"); if (labelIds != null) { for (String labelId : labelIds) { labels.add(IssueLabel.finder.byId(Long.parseLong(labelId))); } } } }
false
true
public static Result massUpdate(String ownerName, String projectName) throws IOException { Form<IssueMassUpdate> issueMassUpdateForm = new Form<IssueMassUpdate>(IssueMassUpdate.class).bindFromRequest(); if (issueMassUpdateForm.hasErrors()) { return badRequest(issueMassUpdateForm.errorsAsJson()); } IssueMassUpdate issueMassUpdate = issueMassUpdateForm.get(); Project project = Project.findByOwnerAndProjectName(ownerName, projectName); int updatedItems = 0; int rejectedByPermission = 0; for (Issue issue : issueMassUpdate.issues) { issue.refresh(); if (!AccessControl.isAllowed(UserApp.currentUser(), issue.asResource(), Operation.UPDATE)) { rejectedByPermission++; continue; } if (issueMassUpdate.assignee != null) { if (issueMassUpdate.assignee.isAnonymous()) { issue.assignee = null; } else { issue.assignee = Assignee.add(issueMassUpdate.assignee.id, project.id); } } if (issueMassUpdate.state != null) { issue.state = issueMassUpdate.state; } if (issueMassUpdate.milestone != null) { issue.milestone = issueMassUpdate.milestone; } if (issueMassUpdate.attachingLabel != null) { issue.refresh(); issue.labels.add(issueMassUpdate.attachingLabel); } if (issueMassUpdate.detachingLabel != null) { issue.refresh(); issue.labels.remove(issueMassUpdate.detachingLabel); } issue.update(); updatedItems++; } if (updatedItems == 0 && rejectedByPermission > 0) { return forbidden(views.html.error.forbidden.render(project)); } return redirect( routes.IssueApp.issues(ownerName, projectName, "all", "html", 1)); }
public static Result massUpdate(String ownerName, String projectName) throws IOException { Form<IssueMassUpdate> issueMassUpdateForm = new Form<IssueMassUpdate>(IssueMassUpdate.class).bindFromRequest(); if (issueMassUpdateForm.hasErrors()) { return badRequest(issueMassUpdateForm.errorsAsJson()); } IssueMassUpdate issueMassUpdate = issueMassUpdateForm.get(); Project project = Project.findByOwnerAndProjectName(ownerName, projectName); int updatedItems = 0; int rejectedByPermission = 0; for (Issue issue : issueMassUpdate.issues) { issue.refresh(); if (!AccessControl.isAllowed(UserApp.currentUser(), issue.asResource(), Operation.UPDATE)) { rejectedByPermission++; continue; } if (issueMassUpdate.assignee != null) { if (issueMassUpdate.assignee.isAnonymous()) { issue.assignee = null; } else { issue.assignee = Assignee.add(issueMassUpdate.assignee.id, project.id); } } if (issueMassUpdate.state != null) { issue.state = issueMassUpdate.state; } if (issueMassUpdate.milestone != null) { issue.milestone = issueMassUpdate.milestone; } if (issueMassUpdate.attachingLabel != null) { issue.labels.add(issueMassUpdate.attachingLabel); } if (issueMassUpdate.detachingLabel != null) { issue.labels.remove(issueMassUpdate.detachingLabel); } issue.update(); updatedItems++; } if (updatedItems == 0 && rejectedByPermission > 0) { return forbidden(views.html.error.forbidden.render(project)); } return redirect( routes.IssueApp.issues(ownerName, projectName, "all", "html", 1)); }
diff --git a/src/net/java/sip/communicator/impl/neomedia/codec/video/SwScaler.java b/src/net/java/sip/communicator/impl/neomedia/codec/video/SwScaler.java index e85320e0b..452c83ddd 100644 --- a/src/net/java/sip/communicator/impl/neomedia/codec/video/SwScaler.java +++ b/src/net/java/sip/communicator/impl/neomedia/codec/video/SwScaler.java @@ -1,379 +1,386 @@ /* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.neomedia.codec.video; import java.awt.*; import javax.media.*; import javax.media.format.*; import net.java.sip.communicator.util.*; import net.sf.fmj.media.*; /** * Implements a <tt>Codec</tt> which uses libswscale to scale images and convert * between color spaces (typically, RGB and YUV). * * @author Sebastien Vincent * @author Lubomir Marinov */ public class SwScaler extends AbstractCodec { private static final Logger logger = Logger.getLogger(SwScaler.class); /** * Supported input formats. */ private final Format[] supportedInputFormats = new Format[] { new RGBFormat(null, -1, Format.byteArray, -1.0f, 32, -1, -1, -1), new RGBFormat(null, -1, Format.intArray, -1.0f, 32, -1, -1, -1), new RGBFormat(null, -1, Format.shortArray, -1.0f, 32, -1, -1, -1), new RGBFormat(null, -1, Format.byteArray, -1.0f, 24, -1, -1, -1), new RGBFormat(null, -1, Format.intArray, -1.0f, 24, -1, -1, -1), new RGBFormat(null, -1, Format.shortArray, -1.0f, 24, -1, -1, -1), new YUVFormat(null, -1, Format.byteArray, -1.0f, YUVFormat.YUV_420, -1, -1, 0, -1, -1), new YUVFormat(null, -1, Format.intArray, -1.0f, YUVFormat.YUV_420, -1, -1, 0, -1, -1), new YUVFormat(null, -1, Format.shortArray, -1.0f, YUVFormat.YUV_420, -1, -1, 0, -1, -1), }; /** * Supported output formats. */ private Format[] supportedOutputFormats = new Format[] { new YUVFormat(null, -1, Format.byteArray, -1.0f, YUVFormat.YUV_420, -1, -1, 0, -1, -1), new YUVFormat(null, -1, Format.intArray, -1.0f, YUVFormat.YUV_420, -1, -1, 0, -1, -1), new YUVFormat(null, -1, Format.shortArray, -1.0f, YUVFormat.YUV_420, -1, -1, 0, -1, -1), new RGBFormat(null, -1, Format.byteArray, -1.0f, 32, -1, -1, -1), new RGBFormat(null, -1, Format.intArray, -1.0f, 32, -1, -1, -1), new RGBFormat(null, -1, Format.shortArray, -1.0f, 32, -1, -1, -1), new RGBFormat(null, -1, Format.byteArray, -1.0f, 24, -1, -1, -1), new RGBFormat(null, -1, Format.intArray, -1.0f, 24, -1, -1, -1), new RGBFormat(null, -1, Format.shortArray, -1.0f, 24, -1, -1, -1), }; /** * Sets the <tt>Format</tt> in which this <tt>Codec</tt> is to output media * data. * * @param format the <tt>Format</tt> in which this <tt>Codec</tt> is to * output media data * @return the <tt>Format</tt> in which this <tt>Codec</tt> is currently * configured to output media data or <tt>null</tt> if <tt>format</tt> was * found to be incompatible with this <tt>Codec</tt> */ @Override public Format setOutputFormat(Format format) { Format outputFormat = super.setOutputFormat(format); if (logger.isDebugEnabled() && (outputFormat != null)) logger.debug( "SwScaler set to output with size " + ((VideoFormat) outputFormat).getSize()); return outputFormat; } /** * Sets output size. * * @param size size to set */ public void setOutputSize(Dimension size) { if(size == null) size = new Dimension(640, 480); supportedOutputFormats[0] = new YUVFormat(size, -1, Format.byteArray, -1.0f, YUVFormat.YUV_420, -1, -1, 0, -1, -1); supportedOutputFormats[1] = new YUVFormat(size, -1, Format.intArray, -1.0f, YUVFormat.YUV_420, -1, -1, 0, -1, -1); supportedOutputFormats[2] = new YUVFormat(size, -1, Format.shortArray, -1.0f, YUVFormat.YUV_420, -1, -1, 0, -1, -1); supportedOutputFormats[3] = new RGBFormat(size, -1, Format.byteArray, -1.0f, 32, -1, -1, -1); supportedOutputFormats[4] = new RGBFormat(size, -1, Format.intArray, -1.0f, 32, -1, -1, -1); supportedOutputFormats[5] = new RGBFormat(size, -1, Format.shortArray, -1.0f, 32, -1, -1, -1); supportedOutputFormats[6] = new RGBFormat(size, -1, Format.byteArray, -1.0f, 24, -1, -1, -1); supportedOutputFormats[7] = new RGBFormat(size, -1, Format.intArray, -1.0f, 24, -1, -1, -1); supportedOutputFormats[8] = new RGBFormat(size, -1, Format.shortArray, -1.0f, 24, -1, -1, -1); // Set the size to the outputFormat as well. VideoFormat outputFormat = (VideoFormat) this.outputFormat; if (outputFormat != null) setOutputFormat( new VideoFormat( outputFormat.getEncoding(), size, outputFormat.getMaxDataLength(), outputFormat.getDataType(), outputFormat.getFrameRate()) .intersects(outputFormat)); } /** * Gets the <tt>Format</tt> in which this <tt>Codec</tt> is currently * configured to accept input media data. * <p> * Make the protected super implementation public. * </p> * * @return the <tt>Format</tt> in which this <tt>Codec</tt> is currently * configured to accept input media data * @see AbstractCodec#getInputFormat() */ @Override public Format getInputFormat() { return super.getInputFormat(); } public Dimension getOutputSize() { Format outputFormat = getOutputFormat(); if (outputFormat == null) { // They all have one and the same size. outputFormat = supportedOutputFormats[0]; } return ((VideoFormat) outputFormat).getSize(); } /** * Gets the supported input formats. * * @return array of supported input format */ @Override public Format[] getSupportedInputFormats() { return supportedInputFormats; } /** * Gets the supported output formats for an input one. * * @param input input format to get supported output ones for * @return array of supported output formats */ @Override public Format[] getSupportedOutputFormats(Format input) { if(input == null) return supportedOutputFormats; /* if size is set for element 0 (YUVFormat), it is also set * for element 1 (RGBFormat) and so on... */ Dimension size = ((VideoFormat)supportedOutputFormats[0]).getSize(); if(size != null) return supportedOutputFormats; /* no specified size set so return the same size as input * in output format supported */ size = ((VideoFormat)input).getSize(); return new Format[] { new YUVFormat(size, -1, Format.byteArray, -1.0f, YUVFormat.YUV_420, -1, -1, 0, -1, -1), new YUVFormat(size, -1, Format.intArray, -1.0f, YUVFormat.YUV_420, -1, -1, 0, -1, -1), new YUVFormat(size, -1, Format.shortArray, -1.0f, YUVFormat.YUV_420, -1, -1, 0, -1, -1), new RGBFormat(size, -1, Format.byteArray, -1.0f, 32, -1, -1, -1), new RGBFormat(size, -1, Format.intArray, -1.0f, 32, -1, -1, -1), new RGBFormat(size, -1, Format.shortArray, -1.0f, 32, -1, -1, -1), new RGBFormat(size, -1, Format.byteArray, -1.0f, 24, -1, -1, -1), new RGBFormat(size, -1, Format.intArray, -1.0f, 24, -1, -1, -1), new RGBFormat(size, -1, Format.shortArray, -1.0f, 24, -1, -1, -1), }; } /** * Sets the input format. * * @param format format to set * @return format */ @Override public Format setInputFormat(Format format) { VideoFormat videoFormat = (VideoFormat) format; if (videoFormat.getSize() == null) return null; // must set a size. return super.setInputFormat(format); } /** * Gets native (FFMPEG) RGB format. * * @param rgb JMF <tt>RGBFormat</tt> * @return native RGB format */ public static int getNativeRGBFormat(RGBFormat rgb) { int fmt; if(rgb.getBitsPerPixel() == 32) switch(rgb.getRedMask()) { case 1: case 0xff: fmt = FFMPEG.PIX_FMT_BGR32; break; case 2: case (0xff << 8): fmt = FFMPEG.PIX_FMT_BGR32_1; break; case 3: case (0xff << 16): fmt = FFMPEG.PIX_FMT_RGB32; break; case 4: case (0xff << 24): fmt = FFMPEG.PIX_FMT_RGB32_1; break; default: /* assume ARGB ? */ fmt = FFMPEG.PIX_FMT_RGB32; break; } else fmt = FFMPEG.PIX_FMT_RGB24; return fmt; } /** * Processes (converts color space and/or scales) a buffer. * * @param input input buffer * @param output output buffer * @return <tt>BUFFER_PROCESSED_OK</tt> if buffer has been successfully * processed */ @Override public int process(Buffer input, Buffer output) { if (!checkInputBuffer(input)) return BUFFER_PROCESSED_FAILED; if (isEOM(input)) { propagateEOM(output); // TODO: what about data? can there be any? return BUFFER_PROCESSED_OK; } - VideoFormat outputFormat = (VideoFormat)output.getFormat(); + VideoFormat outputFormat = (VideoFormat) getOutputFormat(); if(outputFormat == null) { - outputFormat = (VideoFormat)this.outputFormat; + /* + * The format of the output Buffer is not documented to be used as + * input to the #process method. Anyway, we're trying to use it in + * case this Codec doesn't have an outputFormat set which is + * unlikely to ever happen. + */ + outputFormat = (VideoFormat) output.getFormat(); if (outputFormat == null) // first buffer has no output format set return BUFFER_PROCESSED_FAILED; } int dstFmt; int dstLength; Dimension outputSize = outputFormat.getSize(); int outputWidth = outputSize.width; int outputHeight = outputSize.height; /* determine output format and output size needed */ if(outputFormat instanceof YUVFormat) { dstFmt = FFMPEG.PIX_FMT_YUV420P; /* YUV420P is 12 bpp (bit per pixel) => 1,5 bytes */ dstLength = (int)(outputWidth * outputHeight * 1.5); } else /* RGB format */ { dstFmt = FFMPEG.PIX_FMT_RGB32; dstLength = (outputWidth * outputHeight * 4); } /* determine input format */ VideoFormat inputFormat = (VideoFormat)input.getFormat(); int srcFmt; if(inputFormat instanceof YUVFormat) srcFmt = FFMPEG.PIX_FMT_YUV420P; else // RGBFormat srcFmt = getNativeRGBFormat((RGBFormat)inputFormat); Class<?> outputDataType = outputFormat.getDataType(); Object dst = output.getData(); if(Format.byteArray.equals(outputDataType)) { if(dst == null || ((byte[])dst).length < dstLength) dst = new byte[dstLength]; } else if(Format.intArray.equals(outputDataType)) { /* Java int is always 4 bytes */ dstLength = (dstLength % 4) + dstLength / 4; if(dst == null || ((int[])dst).length < dstLength) dst = new int[dstLength]; } else if(Format.shortArray.equals(outputDataType)) { /* Java short is always 2 bytes */ dstLength = (dstLength % 2) + dstLength / 2; if(dst == null || ((short[])dst).length < dstLength) dst = new short[dstLength]; } else { logger.error("Unknown data type " + outputDataType); return BUFFER_PROCESSED_FAILED; } Object src = input.getData(); synchronized(src) { /* conversion! */ Dimension inputSize = inputFormat.getSize(); FFMPEG.img_convert( dst, dstFmt, src, srcFmt, inputSize.width, inputSize.height, outputWidth, outputHeight); } output.setData(dst); + output.setFormat(outputFormat); output.setLength(dstLength); output.setOffset(0); return BUFFER_PROCESSED_OK; } }
false
true
public int process(Buffer input, Buffer output) { if (!checkInputBuffer(input)) return BUFFER_PROCESSED_FAILED; if (isEOM(input)) { propagateEOM(output); // TODO: what about data? can there be any? return BUFFER_PROCESSED_OK; } VideoFormat outputFormat = (VideoFormat)output.getFormat(); if(outputFormat == null) { outputFormat = (VideoFormat)this.outputFormat; if (outputFormat == null) // first buffer has no output format set return BUFFER_PROCESSED_FAILED; } int dstFmt; int dstLength; Dimension outputSize = outputFormat.getSize(); int outputWidth = outputSize.width; int outputHeight = outputSize.height; /* determine output format and output size needed */ if(outputFormat instanceof YUVFormat) { dstFmt = FFMPEG.PIX_FMT_YUV420P; /* YUV420P is 12 bpp (bit per pixel) => 1,5 bytes */ dstLength = (int)(outputWidth * outputHeight * 1.5); } else /* RGB format */ { dstFmt = FFMPEG.PIX_FMT_RGB32; dstLength = (outputWidth * outputHeight * 4); } /* determine input format */ VideoFormat inputFormat = (VideoFormat)input.getFormat(); int srcFmt; if(inputFormat instanceof YUVFormat) srcFmt = FFMPEG.PIX_FMT_YUV420P; else // RGBFormat srcFmt = getNativeRGBFormat((RGBFormat)inputFormat); Class<?> outputDataType = outputFormat.getDataType(); Object dst = output.getData(); if(Format.byteArray.equals(outputDataType)) { if(dst == null || ((byte[])dst).length < dstLength) dst = new byte[dstLength]; } else if(Format.intArray.equals(outputDataType)) { /* Java int is always 4 bytes */ dstLength = (dstLength % 4) + dstLength / 4; if(dst == null || ((int[])dst).length < dstLength) dst = new int[dstLength]; } else if(Format.shortArray.equals(outputDataType)) { /* Java short is always 2 bytes */ dstLength = (dstLength % 2) + dstLength / 2; if(dst == null || ((short[])dst).length < dstLength) dst = new short[dstLength]; } else { logger.error("Unknown data type " + outputDataType); return BUFFER_PROCESSED_FAILED; } Object src = input.getData(); synchronized(src) { /* conversion! */ Dimension inputSize = inputFormat.getSize(); FFMPEG.img_convert( dst, dstFmt, src, srcFmt, inputSize.width, inputSize.height, outputWidth, outputHeight); } output.setData(dst); output.setLength(dstLength); output.setOffset(0); return BUFFER_PROCESSED_OK; }
public int process(Buffer input, Buffer output) { if (!checkInputBuffer(input)) return BUFFER_PROCESSED_FAILED; if (isEOM(input)) { propagateEOM(output); // TODO: what about data? can there be any? return BUFFER_PROCESSED_OK; } VideoFormat outputFormat = (VideoFormat) getOutputFormat(); if(outputFormat == null) { /* * The format of the output Buffer is not documented to be used as * input to the #process method. Anyway, we're trying to use it in * case this Codec doesn't have an outputFormat set which is * unlikely to ever happen. */ outputFormat = (VideoFormat) output.getFormat(); if (outputFormat == null) // first buffer has no output format set return BUFFER_PROCESSED_FAILED; } int dstFmt; int dstLength; Dimension outputSize = outputFormat.getSize(); int outputWidth = outputSize.width; int outputHeight = outputSize.height; /* determine output format and output size needed */ if(outputFormat instanceof YUVFormat) { dstFmt = FFMPEG.PIX_FMT_YUV420P; /* YUV420P is 12 bpp (bit per pixel) => 1,5 bytes */ dstLength = (int)(outputWidth * outputHeight * 1.5); } else /* RGB format */ { dstFmt = FFMPEG.PIX_FMT_RGB32; dstLength = (outputWidth * outputHeight * 4); } /* determine input format */ VideoFormat inputFormat = (VideoFormat)input.getFormat(); int srcFmt; if(inputFormat instanceof YUVFormat) srcFmt = FFMPEG.PIX_FMT_YUV420P; else // RGBFormat srcFmt = getNativeRGBFormat((RGBFormat)inputFormat); Class<?> outputDataType = outputFormat.getDataType(); Object dst = output.getData(); if(Format.byteArray.equals(outputDataType)) { if(dst == null || ((byte[])dst).length < dstLength) dst = new byte[dstLength]; } else if(Format.intArray.equals(outputDataType)) { /* Java int is always 4 bytes */ dstLength = (dstLength % 4) + dstLength / 4; if(dst == null || ((int[])dst).length < dstLength) dst = new int[dstLength]; } else if(Format.shortArray.equals(outputDataType)) { /* Java short is always 2 bytes */ dstLength = (dstLength % 2) + dstLength / 2; if(dst == null || ((short[])dst).length < dstLength) dst = new short[dstLength]; } else { logger.error("Unknown data type " + outputDataType); return BUFFER_PROCESSED_FAILED; } Object src = input.getData(); synchronized(src) { /* conversion! */ Dimension inputSize = inputFormat.getSize(); FFMPEG.img_convert( dst, dstFmt, src, srcFmt, inputSize.width, inputSize.height, outputWidth, outputHeight); } output.setData(dst); output.setFormat(outputFormat); output.setLength(dstLength); output.setOffset(0); return BUFFER_PROCESSED_OK; }
diff --git a/src/main/java/liquibase/ext/ora/addcheck/AddCheckGenerator.java b/src/main/java/liquibase/ext/ora/addcheck/AddCheckGenerator.java index 6714747..8438283 100644 --- a/src/main/java/liquibase/ext/ora/addcheck/AddCheckGenerator.java +++ b/src/main/java/liquibase/ext/ora/addcheck/AddCheckGenerator.java @@ -1,61 +1,61 @@ package liquibase.ext.ora.addcheck; import liquibase.database.Database; import liquibase.database.core.OracleDatabase; import liquibase.database.core.SQLiteDatabase; import liquibase.exception.ValidationErrors; import liquibase.sql.Sql; import liquibase.sql.UnparsedSql; import liquibase.sqlgenerator.SqlGeneratorChain; import liquibase.sqlgenerator.core.AbstractSqlGenerator; import liquibase.structure.core.Table; public class AddCheckGenerator extends AbstractSqlGenerator<AddCheckStatement> { public Sql[] generateSql(AddCheckStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuilder sql = new StringBuilder(); sql.append("ALTER TABLE ").append(database.escapeTableName(null, statement.getSchemaName(), statement.getTableName())).append(" "); sql.append("ADD "); if (database.escapeObjectName(statement.getConstraintName(), Table.class) != null) sql.append("CONSTRAINT ").append(database.escapeConstraintName(statement.getConstraintName())).append(" "); - sql.append("CHECK(").append(database.escapeObjectName(statement.getCondition(), Table.class)).append(")"); + sql.append("CHECK(").append(statement.getCondition()).append(")"); if (statement.getDeferrable() != null) { if (statement.getDeferrable()) sql.append(" DEFERRABLE"); else sql.append(" NOT DEFERRABLE"); } if (statement.getInitiallyDeferred() != null) { if (statement.getInitiallyDeferred()) sql.append(" INITIALLY DEFERRED"); else sql.append(" INITIALLY IMMEDIATE"); } if (statement.getDisable() != null) { if (statement.getDisable()) sql.append(" DISABLE"); else sql.append(" ENABLE"); } if (statement.getRely() != null) { if (statement.getRely()) sql.append(" RELY"); } if (statement.getValidate() != null) { if (statement.getValidate()) sql.append(" VALIDATE"); } return new Sql[]{new UnparsedSql(sql.toString())}; } public boolean supports(AddCheckStatement statement, Database database) { return database instanceof OracleDatabase; } public ValidationErrors validate(AddCheckStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { ValidationErrors validationErrors = new ValidationErrors(); validationErrors.checkRequiredField("tableName", statement.getTableName()); validationErrors.checkRequiredField("condition", statement.getCondition()); return validationErrors; } }
true
true
public Sql[] generateSql(AddCheckStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuilder sql = new StringBuilder(); sql.append("ALTER TABLE ").append(database.escapeTableName(null, statement.getSchemaName(), statement.getTableName())).append(" "); sql.append("ADD "); if (database.escapeObjectName(statement.getConstraintName(), Table.class) != null) sql.append("CONSTRAINT ").append(database.escapeConstraintName(statement.getConstraintName())).append(" "); sql.append("CHECK(").append(database.escapeObjectName(statement.getCondition(), Table.class)).append(")"); if (statement.getDeferrable() != null) { if (statement.getDeferrable()) sql.append(" DEFERRABLE"); else sql.append(" NOT DEFERRABLE"); } if (statement.getInitiallyDeferred() != null) { if (statement.getInitiallyDeferred()) sql.append(" INITIALLY DEFERRED"); else sql.append(" INITIALLY IMMEDIATE"); } if (statement.getDisable() != null) { if (statement.getDisable()) sql.append(" DISABLE"); else sql.append(" ENABLE"); } if (statement.getRely() != null) { if (statement.getRely()) sql.append(" RELY"); } if (statement.getValidate() != null) { if (statement.getValidate()) sql.append(" VALIDATE"); } return new Sql[]{new UnparsedSql(sql.toString())}; }
public Sql[] generateSql(AddCheckStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuilder sql = new StringBuilder(); sql.append("ALTER TABLE ").append(database.escapeTableName(null, statement.getSchemaName(), statement.getTableName())).append(" "); sql.append("ADD "); if (database.escapeObjectName(statement.getConstraintName(), Table.class) != null) sql.append("CONSTRAINT ").append(database.escapeConstraintName(statement.getConstraintName())).append(" "); sql.append("CHECK(").append(statement.getCondition()).append(")"); if (statement.getDeferrable() != null) { if (statement.getDeferrable()) sql.append(" DEFERRABLE"); else sql.append(" NOT DEFERRABLE"); } if (statement.getInitiallyDeferred() != null) { if (statement.getInitiallyDeferred()) sql.append(" INITIALLY DEFERRED"); else sql.append(" INITIALLY IMMEDIATE"); } if (statement.getDisable() != null) { if (statement.getDisable()) sql.append(" DISABLE"); else sql.append(" ENABLE"); } if (statement.getRely() != null) { if (statement.getRely()) sql.append(" RELY"); } if (statement.getValidate() != null) { if (statement.getValidate()) sql.append(" VALIDATE"); } return new Sql[]{new UnparsedSql(sql.toString())}; }
diff --git a/src/BotClientSender.java b/src/BotClientSender.java index b079209..8397e18 100644 --- a/src/BotClientSender.java +++ b/src/BotClientSender.java @@ -1,33 +1,33 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author geza */ import maslab.telemetry.*; import maslab.telemetry.channel.*; import java.util.*; import javax.swing.*; import java.awt.*; import java.awt.image.*; public class BotClientSender extends java.lang.Thread { public ImageChannel origim = new ImageChannel("origim"); public ImageChannel procim = new ImageChannel("procim"); public BufferedImage origI = null; public BufferedImage procI = null; public void start() { try { + java.lang.Thread.sleep(1000); origim.publish(origI); origim.publish(procI); - java.lang.Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } } }
false
true
public void start() { try { origim.publish(origI); origim.publish(procI); java.lang.Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } }
public void start() { try { java.lang.Thread.sleep(1000); origim.publish(origI); origim.publish(procI); } catch (Exception e) { e.printStackTrace(); } }
diff --git a/src/com/android/gallery3d/filtershow/PanelController.java b/src/com/android/gallery3d/filtershow/PanelController.java index 6694e37f6..2a97e7e53 100644 --- a/src/com/android/gallery3d/filtershow/PanelController.java +++ b/src/com/android/gallery3d/filtershow/PanelController.java @@ -1,588 +1,588 @@ /* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.gallery3d.filtershow; import android.content.Context; import android.text.Html; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewPropertyAnimator; import android.widget.LinearLayout; import android.widget.TextView; import com.android.gallery3d.R; import com.android.gallery3d.filtershow.editors.Editor; import com.android.gallery3d.filtershow.filters.ImageFilter; import com.android.gallery3d.filtershow.filters.ImageFilterTinyPlanet; import com.android.gallery3d.filtershow.imageshow.ImageCrop; import com.android.gallery3d.filtershow.imageshow.ImageShow; import com.android.gallery3d.filtershow.imageshow.MasterImage; import com.android.gallery3d.filtershow.presets.ImagePreset; import com.android.gallery3d.filtershow.ui.FilterIconButton; import com.android.gallery3d.filtershow.ui.FramedTextButton; import java.util.HashMap; import java.util.Vector; public class PanelController implements OnClickListener { private static int PANEL = 0; private static int COMPONENT = 1; private static int VERTICAL_MOVE = 0; private static int HORIZONTAL_MOVE = 1; private static final int ANIM_DURATION = 200; private static final String LOGTAG = "PanelController"; private boolean mDisableFilterButtons = false; private boolean mFixedAspect = false; public void setFixedAspect(boolean t) { mFixedAspect = t; } class Panel { private final View mView; private final View mContainer; private int mPosition = 0; private final Vector<View> mSubviews = new Vector<View>(); public Panel(View view, View container, int position) { mView = view; mContainer = container; mPosition = position; } public void addView(View view) { mSubviews.add(view); } public int getPosition() { return mPosition; } public ViewPropertyAnimator unselect(int newPos, int move) { ViewPropertyAnimator anim = mContainer.animate(); mView.setSelected(false); mContainer.setX(0); mContainer.setY(0); int delta = 0; int w = mRowPanel.getWidth(); int h = mRowPanel.getHeight(); if (move == HORIZONTAL_MOVE) { if (newPos > mPosition) { delta = -w; } else { delta = w; } anim.x(delta); } else if (move == VERTICAL_MOVE) { anim.y(h); } anim.setDuration(ANIM_DURATION).withLayer().withEndAction(new Runnable() { @Override public void run() { mContainer.setVisibility(View.GONE); } }); return anim; } public ViewPropertyAnimator select(int oldPos, int move) { mView.setSelected(true); mContainer.setVisibility(View.VISIBLE); mContainer.setX(0); mContainer.setY(0); ViewPropertyAnimator anim = mContainer.animate(); int w = mRowPanel.getWidth(); int h = mRowPanel.getHeight(); if (move == HORIZONTAL_MOVE) { if (oldPos < mPosition) { mContainer.setX(w); } else { mContainer.setX(-w); } anim.x(0); } else if (move == VERTICAL_MOVE) { mContainer.setY(h); anim.y(0); } anim.setDuration(ANIM_DURATION).withLayer(); return anim; } } class UtilityPanel { private final Context mContext; private final View mView; private final LinearLayout mAccessoryViewList; private Vector<View> mAccessoryViews = new Vector<View>(); private final TextView mTextView; private boolean mSelected = false; private String mEffectName = null; private int mParameterValue = 0; private boolean mShowParameterValue = false; boolean firstTimeCropDisplayed = true; public UtilityPanel(Context context, View view, View accessoryViewList, View textView) { mContext = context; mView = view; mAccessoryViewList = (LinearLayout) accessoryViewList; mTextView = (TextView) textView; } public boolean selected() { return mSelected; } public void hideAccessoryViews() { int childCount = mAccessoryViewList.getChildCount(); for (int i = 0; i < childCount; i++) { View child = mAccessoryViewList.getChildAt(i); child.setVisibility(View.GONE); } } public void onNewValue(int value) { mParameterValue = value; updateText(); } public void setEffectName(String effectName) { mEffectName = effectName; setShowParameter(true); } public void setShowParameter(boolean s) { mShowParameterValue = s; updateText(); } public void updateText() { String apply = mContext.getString(R.string.apply_effect); if (mShowParameterValue) { mTextView.setText(Html.fromHtml(apply + " " + mEffectName + " " + mParameterValue)); } else { mTextView.setText(Html.fromHtml(apply + " " + mEffectName)); } } public ViewPropertyAnimator unselect() { ViewPropertyAnimator anim = mView.animate(); mView.setX(0); mView.setY(0); int h = mRowPanel.getHeight(); anim.y(-h); anim.setDuration(ANIM_DURATION).withLayer().withEndAction(new Runnable() { @Override public void run() { mView.setVisibility(View.GONE); } }); mSelected = false; return anim; } public ViewPropertyAnimator select() { mView.setVisibility(View.VISIBLE); int h = mRowPanel.getHeight(); mView.setX(0); mView.setY(-h); updateText(); ViewPropertyAnimator anim = mView.animate(); anim.y(0); anim.setDuration(ANIM_DURATION).withLayer(); mSelected = true; return anim; } } class ViewType { private final int mType; private final View mView; public ViewType(View view, int type) { mView = view; mType = type; } public int type() { return mType; } } private final HashMap<View, Panel> mPanels = new HashMap<View, Panel>(); private final HashMap<View, ViewType> mViews = new HashMap<View, ViewType>(); private final HashMap<String, ImageFilter> mFilters = new HashMap<String, ImageFilter>(); private final Vector<View> mImageViews = new Vector<View>(); private View mCurrentPanel = null; private View mRowPanel = null; private UtilityPanel mUtilityPanel = null; private MasterImage mMasterImage = MasterImage.getImage(); private ImageShow mCurrentImage = null; private Editor mCurrentEditor = null; private FilterShowActivity mActivity = null; private EditorPlaceHolder mEditorPlaceHolder = null; public void setActivity(FilterShowActivity activity) { mActivity = activity; } public void addView(View view) { view.setOnClickListener(this); mViews.put(view, new ViewType(view, COMPONENT)); } public void addPanel(View view, View container, int position) { mPanels.put(view, new Panel(view, container, position)); view.setOnClickListener(this); mViews.put(view, new ViewType(view, PANEL)); } public void addComponent(View aPanel, View component) { Panel panel = mPanels.get(aPanel); if (panel == null) { return; } panel.addView(component); component.setOnClickListener(this); mViews.put(component, new ViewType(component, COMPONENT)); } public void addFilter(ImageFilter filter) { mFilters.put(filter.getName(), filter); } public void addImageView(View view) { mImageViews.add(view); ImageShow imageShow = (ImageShow) view; imageShow.setPanelController(this); } public void resetParameters() { showPanel(mCurrentPanel); if (mCurrentImage != null) { mCurrentImage.resetParameter(); mCurrentImage.select(); if (mCurrentEditor != null) { mCurrentEditor.reflectCurrentFilter(); } } if (mDisableFilterButtons) { mActivity.enableFilterButtons(); mDisableFilterButtons = false; } } public boolean onBackPressed() { if (mUtilityPanel == null || !mUtilityPanel.selected()) { return true; } HistoryAdapter adapter = mMasterImage.getHistory(); int position = adapter.undo(); mMasterImage.onHistoryItemClick(position); showPanel(mCurrentPanel); mCurrentImage.select(); if (mCurrentEditor != null) { mCurrentEditor.reflectCurrentFilter(); } if (mDisableFilterButtons) { mActivity.enableFilterButtons(); mActivity.resetHistory(); mDisableFilterButtons = false; } return false; } public void onNewValue(int value) { mUtilityPanel.onNewValue(value); } public void showParameter(boolean s) { mUtilityPanel.setShowParameter(s); } public void setCurrentPanel(View panel) { showPanel(panel); } public void setRowPanel(View rowPanel) { mRowPanel = rowPanel; } public void setUtilityPanel(Context context, View utilityPanel, View accessoryViewList, View textView) { mUtilityPanel = new UtilityPanel(context, utilityPanel, accessoryViewList, textView); } @Override public void onClick(View view) { ViewType type = mViews.get(view); if (type.type() == PANEL) { showPanel(view); } else if (type.type() == COMPONENT) { showComponent(view); } } public ImageShow showImageView(int id) { ImageShow image = null; mActivity.hideImageViews(); for (View view : mImageViews) { if (view.getId() == id) { view.setVisibility(View.VISIBLE); image = (ImageShow) view; } else { view.setVisibility(View.GONE); } } return image; } public void showDefaultImageView() { showImageView(R.id.imageShow).setShowControls(false); mMasterImage.setCurrentFilter(null); mMasterImage.setCurrentFilterRepresentation(null); } public void showPanel(View view) { view.setVisibility(View.VISIBLE); boolean removedUtilityPanel = false; Panel current = mPanels.get(mCurrentPanel); if (mUtilityPanel != null && mUtilityPanel.selected()) { ViewPropertyAnimator anim1 = mUtilityPanel.unselect(); removedUtilityPanel = true; anim1.start(); if (mCurrentPanel == view) { ViewPropertyAnimator anim2 = current.select(-1, VERTICAL_MOVE); anim2.start(); showDefaultImageView(); } } if (mCurrentPanel == view) { return; } Panel panel = mPanels.get(view); if (!removedUtilityPanel) { int currentPos = -1; if (current != null) { currentPos = current.getPosition(); } ViewPropertyAnimator anim1 = panel.select(currentPos, HORIZONTAL_MOVE); anim1.start(); if (current != null) { ViewPropertyAnimator anim2 = current.unselect(panel.getPosition(), HORIZONTAL_MOVE); anim2.start(); } } else { ViewPropertyAnimator anim = panel.select(-1, VERTICAL_MOVE); anim.start(); } showDefaultImageView(); mCurrentPanel = view; } public ImagePreset getImagePreset() { return mMasterImage.getPreset(); } /** public ImageFilter setImagePreset(ImageFilter filter, String name) { ImagePreset copy = new ImagePreset(getImagePreset()); copy.add(filter); copy.setHistoryName(name); copy.setIsFx(false); mMasterImage.setPreset(copy, true); return filter; } */ // TODO: remove this. public void ensureFilter(String name) { /* ImagePreset preset = getImagePreset(); ImageFilter filter = preset.getFilter(name); if (filter != null) { // If we already have a filter, we might still want // to push it onto the history stack. ImagePreset copy = new ImagePreset(getImagePreset()); copy.setHistoryName(name); mMasterImage.setPreset(copy, true); filter = copy.getFilter(name); } if (filter == null) { ImageFilter filterInstance = mFilters.get(name); if (filterInstance != null) { try { ImageFilter newFilter = filterInstance.clone(); newFilter.reset(); filter = setImagePreset(newFilter, name); } catch (CloneNotSupportedException e) { e.printStackTrace(); } } } if (filter != null) { mMasterImage.setCurrentFilter(filter); } */ } public void showComponent(View view) { boolean doPanelTransition = true; if (view instanceof FilterIconButton) { ImageFilter f = ((FilterIconButton) view).getImageFilter(); if (f != null) { // FIXME: this check shouldn't be necessary doPanelTransition = f.showUtilityPanel(); } } if (mUtilityPanel != null && !mUtilityPanel.selected() && doPanelTransition ) { Panel current = mPanels.get(mCurrentPanel); ViewPropertyAnimator anim1 = current.unselect(-1, VERTICAL_MOVE); anim1.start(); if (mUtilityPanel != null) { ViewPropertyAnimator anim2 = mUtilityPanel.select(); anim2.start(); } } if (mCurrentImage != null) { mCurrentImage.unselect(); } mUtilityPanel.hideAccessoryViews(); if (view instanceof FilterIconButton) { mCurrentEditor = null; FilterIconButton component = (FilterIconButton) view; ImageFilter filter = component.getImageFilter(); - if (filter.getEditingViewId() != 0) { + if (filter != null && filter.getEditingViewId() != 0) { if (mEditorPlaceHolder.contains(filter.getEditingViewId())) { mCurrentEditor = mEditorPlaceHolder.showEditor(filter.getEditingViewId()); mCurrentImage = mCurrentEditor.getImageShow(); mCurrentEditor.setPanelController(this); } else { mCurrentImage = showImageView(filter.getEditingViewId()); } mCurrentImage.setShowControls(filter.showEditingControls()); if (filter.getTextId() != 0) { String ename = mCurrentImage.getContext().getString(filter.getTextId()); mUtilityPanel.setEffectName(ename); } mUtilityPanel.setShowParameter(filter.showParameterValue()); mCurrentImage.select(); if (mCurrentEditor != null) { mCurrentEditor.reflectCurrentFilter(); if (mCurrentEditor.useUtilityPanel()) { mCurrentEditor.openUtilityPanel(mUtilityPanel.mAccessoryViewList); } } else if (mCurrentImage.useUtilityPanel()) { mCurrentImage.openUtilityPanel(mUtilityPanel.mAccessoryViewList); } } return; } switch (view.getId()) { case R.id.tinyplanetButton: { mCurrentImage = showImageView(R.id.imageTinyPlanet).setShowControls(true); String ename = mCurrentImage.getContext().getString(R.string.tinyplanet); mUtilityPanel.setEffectName(ename); ensureFilter(ename); if (!mDisableFilterButtons) { mActivity.disableFilterButtons(); mDisableFilterButtons = true; } break; } case R.id.straightenButton: { mCurrentImage = showImageView(R.id.imageStraighten); String ename = mCurrentImage.getContext().getString(R.string.straighten); mUtilityPanel.setEffectName(ename); break; } case R.id.cropButton: { mCurrentImage = showImageView(R.id.imageCrop); String ename = mCurrentImage.getContext().getString(R.string.crop); mUtilityPanel.setEffectName(ename); mUtilityPanel.setShowParameter(false); if (mCurrentImage instanceof ImageCrop && mUtilityPanel.firstTimeCropDisplayed) { ((ImageCrop) mCurrentImage).clear(); mUtilityPanel.firstTimeCropDisplayed = false; } ((ImageCrop) mCurrentImage).setFixedAspect(mFixedAspect); break; } case R.id.rotateButton: { mCurrentImage = showImageView(R.id.imageRotate); String ename = mCurrentImage.getContext().getString(R.string.rotate); mUtilityPanel.setEffectName(ename); break; } case R.id.flipButton: { mCurrentImage = showImageView(R.id.imageFlip); String ename = mCurrentImage.getContext().getString(R.string.mirror); mUtilityPanel.setEffectName(ename); mUtilityPanel.setShowParameter(false); break; } case R.id.redEyeButton: { mCurrentImage = showImageView(R.id.imageRedEyes).setShowControls(true); String ename = mCurrentImage.getContext().getString(R.string.redeye); mUtilityPanel.setEffectName(ename); ensureFilter(ename); break; } case R.id.applyEffect: { if (mMasterImage.getCurrentFilter() instanceof ImageFilterTinyPlanet) { mActivity.saveImage(); } else { if (mCurrentImage instanceof ImageCrop) { ((ImageCrop) mCurrentImage).saveAndSetPreset(); } showPanel(mCurrentPanel); } MasterImage.getImage().invalidateFiltersOnly(); break; } } mCurrentImage.select(); if (mCurrentEditor != null) { mCurrentEditor.reflectCurrentFilter(); if (mCurrentEditor.useUtilityPanel()) { mCurrentEditor.openUtilityPanel(mUtilityPanel.mAccessoryViewList); } } else if (mCurrentImage.useUtilityPanel()) { mCurrentImage.openUtilityPanel(mUtilityPanel.mAccessoryViewList); } } public void setEditorPlaceHolder(EditorPlaceHolder editorPlaceHolder) { mEditorPlaceHolder = editorPlaceHolder; } }
true
true
public void showComponent(View view) { boolean doPanelTransition = true; if (view instanceof FilterIconButton) { ImageFilter f = ((FilterIconButton) view).getImageFilter(); if (f != null) { // FIXME: this check shouldn't be necessary doPanelTransition = f.showUtilityPanel(); } } if (mUtilityPanel != null && !mUtilityPanel.selected() && doPanelTransition ) { Panel current = mPanels.get(mCurrentPanel); ViewPropertyAnimator anim1 = current.unselect(-1, VERTICAL_MOVE); anim1.start(); if (mUtilityPanel != null) { ViewPropertyAnimator anim2 = mUtilityPanel.select(); anim2.start(); } } if (mCurrentImage != null) { mCurrentImage.unselect(); } mUtilityPanel.hideAccessoryViews(); if (view instanceof FilterIconButton) { mCurrentEditor = null; FilterIconButton component = (FilterIconButton) view; ImageFilter filter = component.getImageFilter(); if (filter.getEditingViewId() != 0) { if (mEditorPlaceHolder.contains(filter.getEditingViewId())) { mCurrentEditor = mEditorPlaceHolder.showEditor(filter.getEditingViewId()); mCurrentImage = mCurrentEditor.getImageShow(); mCurrentEditor.setPanelController(this); } else { mCurrentImage = showImageView(filter.getEditingViewId()); } mCurrentImage.setShowControls(filter.showEditingControls()); if (filter.getTextId() != 0) { String ename = mCurrentImage.getContext().getString(filter.getTextId()); mUtilityPanel.setEffectName(ename); } mUtilityPanel.setShowParameter(filter.showParameterValue()); mCurrentImage.select(); if (mCurrentEditor != null) { mCurrentEditor.reflectCurrentFilter(); if (mCurrentEditor.useUtilityPanel()) { mCurrentEditor.openUtilityPanel(mUtilityPanel.mAccessoryViewList); } } else if (mCurrentImage.useUtilityPanel()) { mCurrentImage.openUtilityPanel(mUtilityPanel.mAccessoryViewList); } } return; } switch (view.getId()) { case R.id.tinyplanetButton: { mCurrentImage = showImageView(R.id.imageTinyPlanet).setShowControls(true); String ename = mCurrentImage.getContext().getString(R.string.tinyplanet); mUtilityPanel.setEffectName(ename); ensureFilter(ename); if (!mDisableFilterButtons) { mActivity.disableFilterButtons(); mDisableFilterButtons = true; } break; } case R.id.straightenButton: { mCurrentImage = showImageView(R.id.imageStraighten); String ename = mCurrentImage.getContext().getString(R.string.straighten); mUtilityPanel.setEffectName(ename); break; } case R.id.cropButton: { mCurrentImage = showImageView(R.id.imageCrop); String ename = mCurrentImage.getContext().getString(R.string.crop); mUtilityPanel.setEffectName(ename); mUtilityPanel.setShowParameter(false); if (mCurrentImage instanceof ImageCrop && mUtilityPanel.firstTimeCropDisplayed) { ((ImageCrop) mCurrentImage).clear(); mUtilityPanel.firstTimeCropDisplayed = false; } ((ImageCrop) mCurrentImage).setFixedAspect(mFixedAspect); break; } case R.id.rotateButton: { mCurrentImage = showImageView(R.id.imageRotate); String ename = mCurrentImage.getContext().getString(R.string.rotate); mUtilityPanel.setEffectName(ename); break; } case R.id.flipButton: { mCurrentImage = showImageView(R.id.imageFlip); String ename = mCurrentImage.getContext().getString(R.string.mirror); mUtilityPanel.setEffectName(ename); mUtilityPanel.setShowParameter(false); break; } case R.id.redEyeButton: { mCurrentImage = showImageView(R.id.imageRedEyes).setShowControls(true); String ename = mCurrentImage.getContext().getString(R.string.redeye); mUtilityPanel.setEffectName(ename); ensureFilter(ename); break; } case R.id.applyEffect: { if (mMasterImage.getCurrentFilter() instanceof ImageFilterTinyPlanet) { mActivity.saveImage(); } else { if (mCurrentImage instanceof ImageCrop) { ((ImageCrop) mCurrentImage).saveAndSetPreset(); } showPanel(mCurrentPanel); } MasterImage.getImage().invalidateFiltersOnly(); break; } } mCurrentImage.select(); if (mCurrentEditor != null) { mCurrentEditor.reflectCurrentFilter(); if (mCurrentEditor.useUtilityPanel()) { mCurrentEditor.openUtilityPanel(mUtilityPanel.mAccessoryViewList); } } else if (mCurrentImage.useUtilityPanel()) { mCurrentImage.openUtilityPanel(mUtilityPanel.mAccessoryViewList); } }
public void showComponent(View view) { boolean doPanelTransition = true; if (view instanceof FilterIconButton) { ImageFilter f = ((FilterIconButton) view).getImageFilter(); if (f != null) { // FIXME: this check shouldn't be necessary doPanelTransition = f.showUtilityPanel(); } } if (mUtilityPanel != null && !mUtilityPanel.selected() && doPanelTransition ) { Panel current = mPanels.get(mCurrentPanel); ViewPropertyAnimator anim1 = current.unselect(-1, VERTICAL_MOVE); anim1.start(); if (mUtilityPanel != null) { ViewPropertyAnimator anim2 = mUtilityPanel.select(); anim2.start(); } } if (mCurrentImage != null) { mCurrentImage.unselect(); } mUtilityPanel.hideAccessoryViews(); if (view instanceof FilterIconButton) { mCurrentEditor = null; FilterIconButton component = (FilterIconButton) view; ImageFilter filter = component.getImageFilter(); if (filter != null && filter.getEditingViewId() != 0) { if (mEditorPlaceHolder.contains(filter.getEditingViewId())) { mCurrentEditor = mEditorPlaceHolder.showEditor(filter.getEditingViewId()); mCurrentImage = mCurrentEditor.getImageShow(); mCurrentEditor.setPanelController(this); } else { mCurrentImage = showImageView(filter.getEditingViewId()); } mCurrentImage.setShowControls(filter.showEditingControls()); if (filter.getTextId() != 0) { String ename = mCurrentImage.getContext().getString(filter.getTextId()); mUtilityPanel.setEffectName(ename); } mUtilityPanel.setShowParameter(filter.showParameterValue()); mCurrentImage.select(); if (mCurrentEditor != null) { mCurrentEditor.reflectCurrentFilter(); if (mCurrentEditor.useUtilityPanel()) { mCurrentEditor.openUtilityPanel(mUtilityPanel.mAccessoryViewList); } } else if (mCurrentImage.useUtilityPanel()) { mCurrentImage.openUtilityPanel(mUtilityPanel.mAccessoryViewList); } } return; } switch (view.getId()) { case R.id.tinyplanetButton: { mCurrentImage = showImageView(R.id.imageTinyPlanet).setShowControls(true); String ename = mCurrentImage.getContext().getString(R.string.tinyplanet); mUtilityPanel.setEffectName(ename); ensureFilter(ename); if (!mDisableFilterButtons) { mActivity.disableFilterButtons(); mDisableFilterButtons = true; } break; } case R.id.straightenButton: { mCurrentImage = showImageView(R.id.imageStraighten); String ename = mCurrentImage.getContext().getString(R.string.straighten); mUtilityPanel.setEffectName(ename); break; } case R.id.cropButton: { mCurrentImage = showImageView(R.id.imageCrop); String ename = mCurrentImage.getContext().getString(R.string.crop); mUtilityPanel.setEffectName(ename); mUtilityPanel.setShowParameter(false); if (mCurrentImage instanceof ImageCrop && mUtilityPanel.firstTimeCropDisplayed) { ((ImageCrop) mCurrentImage).clear(); mUtilityPanel.firstTimeCropDisplayed = false; } ((ImageCrop) mCurrentImage).setFixedAspect(mFixedAspect); break; } case R.id.rotateButton: { mCurrentImage = showImageView(R.id.imageRotate); String ename = mCurrentImage.getContext().getString(R.string.rotate); mUtilityPanel.setEffectName(ename); break; } case R.id.flipButton: { mCurrentImage = showImageView(R.id.imageFlip); String ename = mCurrentImage.getContext().getString(R.string.mirror); mUtilityPanel.setEffectName(ename); mUtilityPanel.setShowParameter(false); break; } case R.id.redEyeButton: { mCurrentImage = showImageView(R.id.imageRedEyes).setShowControls(true); String ename = mCurrentImage.getContext().getString(R.string.redeye); mUtilityPanel.setEffectName(ename); ensureFilter(ename); break; } case R.id.applyEffect: { if (mMasterImage.getCurrentFilter() instanceof ImageFilterTinyPlanet) { mActivity.saveImage(); } else { if (mCurrentImage instanceof ImageCrop) { ((ImageCrop) mCurrentImage).saveAndSetPreset(); } showPanel(mCurrentPanel); } MasterImage.getImage().invalidateFiltersOnly(); break; } } mCurrentImage.select(); if (mCurrentEditor != null) { mCurrentEditor.reflectCurrentFilter(); if (mCurrentEditor.useUtilityPanel()) { mCurrentEditor.openUtilityPanel(mUtilityPanel.mAccessoryViewList); } } else if (mCurrentImage.useUtilityPanel()) { mCurrentImage.openUtilityPanel(mUtilityPanel.mAccessoryViewList); } }
diff --git a/MODSRC/vazkii/tinkerer/client/render/tile/RenderTileWardChest.java b/MODSRC/vazkii/tinkerer/client/render/tile/RenderTileWardChest.java index b30bdd6f..0194da80 100644 --- a/MODSRC/vazkii/tinkerer/client/render/tile/RenderTileWardChest.java +++ b/MODSRC/vazkii/tinkerer/client/render/tile/RenderTileWardChest.java @@ -1,109 +1,111 @@ /** * This class was created by <Vazkii>. It's distributed as * part of the ThaumicTinkerer Mod. * * ThaumicTinkerer is Open Source and distributed under a * Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License * (http://creativecommons.org/licenses/by-nc-sa/3.0/deed.en_GB) * * ThaumicTinkerer is a Derivative Work on Thaumcraft 3. * Thaumcraft 3 οΏ½ Azanor 2012 * (http://www.minecraftforum.net/topic/1585216-) * * File Created @ [5 May 2013, 18:23:31 (GMT)] */ package vazkii.tinkerer.client.render.tile; import net.minecraft.client.Minecraft; import net.minecraft.client.model.ModelChest; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.tileentity.TileEntity; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import vazkii.tinkerer.client.util.handler.ClientTickHandler; import vazkii.tinkerer.lib.LibMisc; import vazkii.tinkerer.lib.LibResources; import vazkii.tinkerer.tile.TileEntityWardChest; import vazkii.tinkerer.util.helper.MiscHelper; public class RenderTileWardChest extends TileEntitySpecialRenderer { ModelChest chestModel; public RenderTileWardChest() { chestModel = new ModelChest(); } @Override public void renderTileEntityAt(TileEntity tileentity, double x, double y, double z, float f) { int meta = tileentity.worldObj == null ? 3 : tileentity.getBlockMetadata(); int rotation = meta == 2 ? 180 : meta == 3 ? 0 : meta == 4 ? 90 : 270; GL11.glPushMatrix(); GL11.glEnable(GL12.GL_RESCALE_NORMAL); GL11.glColor4f(1F, 1F, 1F, 1F); GL11.glTranslatef((float)x, (float)y , (float)z); bindTextureByName(LibResources.MODEL_WARD_CHEST); GL11.glTranslatef(0F, 1F, 1F); GL11.glScalef(1F, -1F, -1F); GL11.glTranslatef(0.5F, 0.5F, 0.5F); GL11.glRotatef(rotation, 0F, 1F, 0F); GL11.glTranslatef(-0.5F, -0.5F, -0.5F); chestModel.chestBelow.render(LibMisc.MODEL_DEFAULT_RENDER_SCALE); chestModel.chestKnob.render(LibMisc.MODEL_DEFAULT_RENDER_SCALE); GL11.glDisable(GL12.GL_RESCALE_NORMAL); GL11.glPopMatrix(); GL11.glColor4f(1F, 1F, 1F, 1F); GL11.glTranslatef((float) x, (float) y, (float) z); renderOverlay((TileEntityWardChest) tileentity); GL11.glTranslatef((float) -x, (float) -y, (float) -z); bindTextureByName(LibResources.MODEL_WARD_CHEST); GL11.glPushMatrix(); GL11.glEnable(GL12.GL_RESCALE_NORMAL); GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glDepthMask(false); GL11.glColor4f(1F, 1F, 1F, 1F); GL11.glTranslatef((float)x, (float)y , (float)z); bindTextureByName(LibResources.MODEL_WARD_CHEST); GL11.glTranslatef(0F, 1F, 1F); GL11.glScalef(1F, -1F, -1F); GL11.glTranslatef(0.5F, 0.5F, 0.5F); GL11.glRotatef(rotation, 0F, 1F, 0F); GL11.glTranslatef(-0.5F, -0.5F, -0.5F); chestModel.chestLid.render(LibMisc.MODEL_DEFAULT_RENDER_SCALE); GL11.glDisable(GL12.GL_RESCALE_NORMAL); GL11.glDisable(GL11.GL_BLEND); + GL11.glDepthMask(true); GL11.glPopMatrix(); GL11.glColor4f(1F, 1F, 1F, 1F); } private void renderOverlay(TileEntityWardChest chest) { Minecraft mc = MiscHelper.getMc(); mc.renderEngine.bindTexture(LibResources.MISC_WARD_CHEST_OVERLAY); GL11.glPushMatrix(); GL11.glDisable(GL11.GL_LIGHTING); GL11.glEnable(GL11.GL_BLEND); GL11.glTranslatef(0.5F, 0.65F, 0.5F); float deg = (float) ((chest.worldObj == null ? ClientTickHandler.clientTicksElapsed : chest.ticksExisted) % 360F); GL11.glRotatef(deg, 0F, 1F, 0F); GL11.glColor4f(1F, 1F, 1F, 1F); Tessellator tess = Tessellator.instance; tess.startDrawingQuads(); tess.addVertexWithUV(-0.45, 0, 0.45, 0, 1); tess.addVertexWithUV(0.45, 0, 0.45, 1, 1); tess.addVertexWithUV(0.45, 0, -0.45, 1, 0); tess.addVertexWithUV(-0.45, 0, -0.45, 0, 0); tess.draw(); GL11.glEnable(GL11.GL_LIGHTING); GL11.glDisable(GL11.GL_BLEND); GL11.glPopMatrix(); } }
false
true
public void renderTileEntityAt(TileEntity tileentity, double x, double y, double z, float f) { int meta = tileentity.worldObj == null ? 3 : tileentity.getBlockMetadata(); int rotation = meta == 2 ? 180 : meta == 3 ? 0 : meta == 4 ? 90 : 270; GL11.glPushMatrix(); GL11.glEnable(GL12.GL_RESCALE_NORMAL); GL11.glColor4f(1F, 1F, 1F, 1F); GL11.glTranslatef((float)x, (float)y , (float)z); bindTextureByName(LibResources.MODEL_WARD_CHEST); GL11.glTranslatef(0F, 1F, 1F); GL11.glScalef(1F, -1F, -1F); GL11.glTranslatef(0.5F, 0.5F, 0.5F); GL11.glRotatef(rotation, 0F, 1F, 0F); GL11.glTranslatef(-0.5F, -0.5F, -0.5F); chestModel.chestBelow.render(LibMisc.MODEL_DEFAULT_RENDER_SCALE); chestModel.chestKnob.render(LibMisc.MODEL_DEFAULT_RENDER_SCALE); GL11.glDisable(GL12.GL_RESCALE_NORMAL); GL11.glPopMatrix(); GL11.glColor4f(1F, 1F, 1F, 1F); GL11.glTranslatef((float) x, (float) y, (float) z); renderOverlay((TileEntityWardChest) tileentity); GL11.glTranslatef((float) -x, (float) -y, (float) -z); bindTextureByName(LibResources.MODEL_WARD_CHEST); GL11.glPushMatrix(); GL11.glEnable(GL12.GL_RESCALE_NORMAL); GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glColor4f(1F, 1F, 1F, 1F); GL11.glTranslatef((float)x, (float)y , (float)z); bindTextureByName(LibResources.MODEL_WARD_CHEST); GL11.glTranslatef(0F, 1F, 1F); GL11.glScalef(1F, -1F, -1F); GL11.glTranslatef(0.5F, 0.5F, 0.5F); GL11.glRotatef(rotation, 0F, 1F, 0F); GL11.glTranslatef(-0.5F, -0.5F, -0.5F); chestModel.chestLid.render(LibMisc.MODEL_DEFAULT_RENDER_SCALE); GL11.glDisable(GL12.GL_RESCALE_NORMAL); GL11.glDisable(GL11.GL_BLEND); GL11.glPopMatrix(); GL11.glColor4f(1F, 1F, 1F, 1F); }
public void renderTileEntityAt(TileEntity tileentity, double x, double y, double z, float f) { int meta = tileentity.worldObj == null ? 3 : tileentity.getBlockMetadata(); int rotation = meta == 2 ? 180 : meta == 3 ? 0 : meta == 4 ? 90 : 270; GL11.glPushMatrix(); GL11.glEnable(GL12.GL_RESCALE_NORMAL); GL11.glColor4f(1F, 1F, 1F, 1F); GL11.glTranslatef((float)x, (float)y , (float)z); bindTextureByName(LibResources.MODEL_WARD_CHEST); GL11.glTranslatef(0F, 1F, 1F); GL11.glScalef(1F, -1F, -1F); GL11.glTranslatef(0.5F, 0.5F, 0.5F); GL11.glRotatef(rotation, 0F, 1F, 0F); GL11.glTranslatef(-0.5F, -0.5F, -0.5F); chestModel.chestBelow.render(LibMisc.MODEL_DEFAULT_RENDER_SCALE); chestModel.chestKnob.render(LibMisc.MODEL_DEFAULT_RENDER_SCALE); GL11.glDisable(GL12.GL_RESCALE_NORMAL); GL11.glPopMatrix(); GL11.glColor4f(1F, 1F, 1F, 1F); GL11.glTranslatef((float) x, (float) y, (float) z); renderOverlay((TileEntityWardChest) tileentity); GL11.glTranslatef((float) -x, (float) -y, (float) -z); bindTextureByName(LibResources.MODEL_WARD_CHEST); GL11.glPushMatrix(); GL11.glEnable(GL12.GL_RESCALE_NORMAL); GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glDepthMask(false); GL11.glColor4f(1F, 1F, 1F, 1F); GL11.glTranslatef((float)x, (float)y , (float)z); bindTextureByName(LibResources.MODEL_WARD_CHEST); GL11.glTranslatef(0F, 1F, 1F); GL11.glScalef(1F, -1F, -1F); GL11.glTranslatef(0.5F, 0.5F, 0.5F); GL11.glRotatef(rotation, 0F, 1F, 0F); GL11.glTranslatef(-0.5F, -0.5F, -0.5F); chestModel.chestLid.render(LibMisc.MODEL_DEFAULT_RENDER_SCALE); GL11.glDisable(GL12.GL_RESCALE_NORMAL); GL11.glDisable(GL11.GL_BLEND); GL11.glDepthMask(true); GL11.glPopMatrix(); GL11.glColor4f(1F, 1F, 1F, 1F); }
diff --git a/source/com/mucommander/ui/icon/IconManager.java b/source/com/mucommander/ui/icon/IconManager.java index 9cb25e1b..c114ccaf 100644 --- a/source/com/mucommander/ui/icon/IconManager.java +++ b/source/com/mucommander/ui/icon/IconManager.java @@ -1,190 +1,191 @@ package com.mucommander.ui.icon; import com.mucommander.file.util.ResourceLoader; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.net.URL; import java.util.Hashtable; /** * IconManager takes care of loading, caching, rescaling the icons contained inside the application's JAR file. * * @author Maxence Bernard */ public class IconManager { /** Singleton instance */ private final static IconManager instance = new IconManager(); /** Class instance used to retrieve JAR resource files */ private final static Class classInstance = instance.getClass(); /** Caches for the different icon sets */ private final static Hashtable caches[]; /** Designates the file icon set */ public final static int FILE_ICON_SET = 0; /** Designates the action icon set */ public final static int ACTION_ICON_SET = 1; /** Designates the toolbar icon set */ public final static int STATUS_BAR_ICON_SET = 2; /** Designates the table icon set */ public final static int COMMON_ICON_SET = 3; /** Designates the preferences icon set */ public final static int PREFERENCES_ICON_SET = 4; /** Designates the progress icon set */ public final static int PROGRESS_ICON_SET = 5; /** Icon sets folders within the application's JAR file */ private final static String ICON_SET_FOLDERS[] = { "/file/", "/action/", "/status_bar/", "/common/", "/preferences/", "/progress/" }; /** Number of icon sets */ private final static int NB_ICON_SETS = 6; static { // Initialize caches for icon sets that need it. // Icons which are displayed once in a while like preferences icons don't need to be cached caches = new Hashtable[NB_ICON_SETS]; caches[FILE_ICON_SET] = new Hashtable(); caches[ACTION_ICON_SET] = new Hashtable(); caches[STATUS_BAR_ICON_SET] = new Hashtable(); caches[COMMON_ICON_SET] = new Hashtable(); caches[PROGRESS_ICON_SET] = new Hashtable(); } /** * Creates a new instance of IconManager. */ private IconManager() { } /** * Creates and returns an ImageIcon instance using the specified icon path and scale factor. No caching. * * @param iconPath path of the icon resource inside the application's JAR file * @param scaleFactor the icon scale factor, <code>1.0f</code> to have the icon in its original size (no rescaling) */ public static ImageIcon getIcon(String iconPath, float scaleFactor) { URL resourceURL = ResourceLoader.getResource(iconPath); if(resourceURL==null) { if(com.mucommander.Debug.ON) com.mucommander.Debug.trace("Warning: attempt to load non-existing icon: "+iconPath+" , icon missing ?"); return null; } ImageIcon icon = new ImageIcon(resourceURL); return scaleFactor==1.0f?icon:getScaledIcon(icon, scaleFactor); } /** * Convenience method, calls and returns the result of {@link #getIcon(String, float) getIcon(iconPath, scaleFactor)} * with a scale factor of 1.0f (no rescaling). */ public static ImageIcon getIcon(String iconPath) { return getIcon(iconPath, 1.0f); } /** * Returns a scaled version of the given ImageIcon instance, using the specified scale factor. * * @param icon the icon to scale. * @param scaleFactor the icon scale factor, <code>1.0f</code> to have the icon in its original size (no rescaling) */ public static ImageIcon getScaledIcon(ImageIcon icon, float scaleFactor) { if(scaleFactor==1.0f || icon==null) return icon; Image image = icon.getImage(); return new ImageIcon(image.getScaledInstance((int)(scaleFactor*image.getWidth(null)), (int)(scaleFactor*image.getHeight(null)), Image.SCALE_AREA_AVERAGING)); } /** * Returns an icon in the specified icon set and with the given name. If a scale factor other than 1.0f is passed, * the return icon will be scaled accordingly. * * <p>If the icon set has a cache, first looks for an existing instance in the cache, and if it couldn't be found, * create an instance and store it in the cache for future access. Note that the cached icon is unscaled, i.e. * the scaled icon is not cached.</p> * * @param iconSet an icon set (see public constants for possible values) * @param iconName filename of the icon to retrieve * @param scaleFactor the icon scale factor, <code>1.0f</code> to have the icon in its original size (no rescaling) * @return an ImageIcon instance corresponding to the specified icon set, name and scale factor, * <code>null</code> if the image wasn't found or couldn't be loaded */ public static ImageIcon getIcon(int iconSet, String iconName, float scaleFactor) { Hashtable cache = caches[iconSet]; ImageIcon icon; if(cache==null) { // No caching, simply create the icon icon = getIcon(ICON_SET_FOLDERS[iconSet]+iconName); } else { // Look for the icon in the cache icon = (ImageIcon)cache.get(iconName); if(icon==null) { // Icon is not in the cache, let's create it icon = getIcon(ICON_SET_FOLDERS[iconSet]+iconName); - // and add it to the cache - cache.put(iconName, icon); + // and add it to the cache if icon exists + if(icon!=null) + cache.put(iconName, icon); } } if(icon==null) return null; return scaleFactor==1.0f?icon:getScaledIcon(icon, scaleFactor); } /** * Convenience method, calls and returns the result of {@link #getIcon(int, String, float) getIcon(iconSet, iconName, scaleFactor)} * with a scale factor of 1.0f (no rescaling). */ public static ImageIcon getIcon(int iconSet, String iconName) { return getIcon(iconSet, iconName, 1.0f); } /** * Creates and returns an ImageIcon with the same content and dimensions. This method is useful when an ImageIcon * is needed and only an Icon is available. * * <p>If the given Icon is already an ImageIcon, the same instance is returned. If it is not, a new ImageIcon is * created and returned. */ public static ImageIcon getImageIcon(Icon icon) { if(icon instanceof ImageIcon) return (ImageIcon)icon; BufferedImage bi = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB); icon.paintIcon(null, bi.getGraphics(), 0, 0); return new ImageIcon(bi); } /** * Returns the path to the folder that contains the image resource files of the given icon set. * The returned path is relative to the application JAR file's root and contains a trailing slash. * * @param iconSet an icon set (see public constants for possible values) */ public static String getIconSetFolder(int iconSet) { return ICON_SET_FOLDERS[iconSet]; } }
true
true
public static ImageIcon getIcon(int iconSet, String iconName, float scaleFactor) { Hashtable cache = caches[iconSet]; ImageIcon icon; if(cache==null) { // No caching, simply create the icon icon = getIcon(ICON_SET_FOLDERS[iconSet]+iconName); } else { // Look for the icon in the cache icon = (ImageIcon)cache.get(iconName); if(icon==null) { // Icon is not in the cache, let's create it icon = getIcon(ICON_SET_FOLDERS[iconSet]+iconName); // and add it to the cache cache.put(iconName, icon); } } if(icon==null) return null; return scaleFactor==1.0f?icon:getScaledIcon(icon, scaleFactor); }
public static ImageIcon getIcon(int iconSet, String iconName, float scaleFactor) { Hashtable cache = caches[iconSet]; ImageIcon icon; if(cache==null) { // No caching, simply create the icon icon = getIcon(ICON_SET_FOLDERS[iconSet]+iconName); } else { // Look for the icon in the cache icon = (ImageIcon)cache.get(iconName); if(icon==null) { // Icon is not in the cache, let's create it icon = getIcon(ICON_SET_FOLDERS[iconSet]+iconName); // and add it to the cache if icon exists if(icon!=null) cache.put(iconName, icon); } } if(icon==null) return null; return scaleFactor==1.0f?icon:getScaledIcon(icon, scaleFactor); }
diff --git a/src/org/eclipse/core/tests/resources/NatureTest.java b/src/org/eclipse/core/tests/resources/NatureTest.java index cfb8117..8c9d96f 100644 --- a/src/org/eclipse/core/tests/resources/NatureTest.java +++ b/src/org/eclipse/core/tests/resources/NatureTest.java @@ -1,348 +1,348 @@ /******************************************************************************* * Copyright (c) 2000, 2010 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.core.tests.resources; import java.io.*; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.core.filesystem.EFS; import org.eclipse.core.filesystem.IFileStore; import org.eclipse.core.internal.resources.File; import org.eclipse.core.internal.resources.Project; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.jobs.IJobManager; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.tests.internal.resources.SimpleNature; /** * Tests all aspects of project natures. These tests only * exercise API classes and methods. Note that the nature-related * APIs on IWorkspace are tested by IWorkspaceTest. */ public class NatureTest extends ResourceTest { /** * Constructor for NatureTest. */ public NatureTest() { super(); } /** * Constructor for NatureTest. * @param name */ public NatureTest(String name) { super(name); } public static Test suite() { return new TestSuite(NatureTest.class); } /** * Sets the given set of natures for the project. If success * does not match the "shouldFail" argument, an assertion error * with the given message is thrown. */ protected void setNatures(String message, IProject project, String[] natures, boolean shouldFail) { setNatures(message, project, natures, shouldFail, false); } /** * Sets the given set of natures for the project. If success * does not match the "shouldFail" argument, an assertion error * with the given message is thrown. */ protected void setNatures(String message, IProject project, String[] natures, boolean shouldFail, boolean silent) { try { IProjectDescription desc = project.getDescription(); desc.setNatureIds(natures); int flags = IResource.KEEP_HISTORY; if (silent) flags |= IResource.AVOID_NATURE_CONFIG; project.setDescription(desc, flags, getMonitor()); if (shouldFail) fail(message); } catch (CoreException e) { if (!shouldFail) fail(message, e); } } protected void tearDown() throws Exception { super.tearDown(); getWorkspace().getRoot().refreshLocal(IResource.DEPTH_INFINITE, null); ensureDoesNotExistInWorkspace(getWorkspace().getRoot()); } /** * Tests invalid additions to the set of natures for a project. */ public void testInvalidAdditions() { IWorkspace ws = ResourcesPlugin.getWorkspace(); IProject project = ws.getRoot().getProject("Project"); ensureExistsInWorkspace(project, true); setNatures("1.0", project, new String[] {NATURE_SIMPLE}, false); //Adding a nature that is not available. setNatures("2.0", project, new String[] {NATURE_SIMPLE, NATURE_MISSING}, true); try { assertTrue("2.1", project.hasNature(NATURE_SIMPLE)); assertTrue("2.2", !project.hasNature(NATURE_MISSING)); assertTrue("2.3", project.isNatureEnabled(NATURE_SIMPLE)); assertTrue("2.4", !project.isNatureEnabled(NATURE_MISSING)); } catch (CoreException e) { fail("2.99", e); } //Adding a nature that has a missing prerequisite. setNatures("3.0", project, new String[] {NATURE_SIMPLE, NATURE_SNOW}, true); try { assertTrue("3.1", project.hasNature(NATURE_SIMPLE)); assertTrue("3.2", !project.hasNature(NATURE_SNOW)); assertTrue("3.3", project.isNatureEnabled(NATURE_SIMPLE)); assertTrue("3.4", !project.isNatureEnabled(NATURE_SNOW)); } catch (CoreException e) { fail("3.99", e); } //Adding a nature that creates a duplicated set member. setNatures("4.0", project, new String[] {NATURE_EARTH}, false); setNatures("4.1", project, new String[] {NATURE_EARTH, NATURE_WATER}, true); try { assertTrue("3.1", project.hasNature(NATURE_EARTH)); assertTrue("3.2", !project.hasNature(NATURE_WATER)); assertTrue("3.3", project.isNatureEnabled(NATURE_EARTH)); assertTrue("3.4", !project.isNatureEnabled(NATURE_WATER)); } catch (CoreException e) { fail("3.99", e); } } /** * Tests invalid removals from the set of natures for a project. */ public void testInvalidRemovals() { IWorkspace ws = ResourcesPlugin.getWorkspace(); IProject project = ws.getRoot().getProject("Project"); ensureExistsInWorkspace(project, true); //Removing a nature that still has dependents. setNatures("1.0", project, new String[] {NATURE_WATER, NATURE_SNOW}, false); setNatures("2.0", project, new String[] {NATURE_SNOW}, true); try { assertTrue("2.1", project.hasNature(NATURE_WATER)); assertTrue("2.2", project.hasNature(NATURE_SNOW)); assertTrue("2.3", project.isNatureEnabled(NATURE_WATER)); assertTrue("2.4", project.isNatureEnabled(NATURE_SNOW)); } catch (CoreException e) { fail("2.99", e); } } public void testNatureLifecyle() { IWorkspace ws = ResourcesPlugin.getWorkspace(); IProject project = ws.getRoot().getProject("Project"); ensureExistsInWorkspace(project, true); //add simple nature setNatures("1.0", project, new String[] {NATURE_SIMPLE}, false); SimpleNature instance = SimpleNature.getInstance(); assertTrue("1.1", instance.wasConfigured); assertTrue("1.2", !instance.wasDeconfigured); instance.reset(); //remove simple nature setNatures("1.3", project, new String[0], false); instance = SimpleNature.getInstance(); assertTrue("1.4", !instance.wasConfigured); assertTrue("1.5", instance.wasDeconfigured); //add with AVOID_NATURE_CONFIG instance.reset(); setNatures("2.0", project, new String[] {NATURE_SIMPLE}, false, true); instance = SimpleNature.getInstance(); assertTrue("2.1", !instance.wasConfigured); assertTrue("2.2", !instance.wasDeconfigured); try { assertTrue("2.3", project.hasNature(NATURE_SIMPLE)); } catch (CoreException e) { fail("1.99", e); } //remove with AVOID_NATURE_CONFIG instance.reset(); setNatures("2.3", project, new String[0], false, true); instance = SimpleNature.getInstance(); assertTrue("2.4", !instance.wasConfigured); assertTrue("2.5", !instance.wasDeconfigured); try { assertTrue("2.6", !project.hasNature(NATURE_SIMPLE)); } catch (CoreException e) { fail("2.99", e); } } /** * Test simple addition and removal of natures. */ public void testSimpleNature() { IWorkspace ws = ResourcesPlugin.getWorkspace(); IProject project = ws.getRoot().getProject("Project"); ensureExistsInWorkspace(project, true); String[][] valid = getValidNatureSets(); for (int i = 0; i < valid.length; i++) { setNatures("valid: " + i, project, valid[i], false); } //configure a valid nature before starting invalid tests String[] currentSet = new String[] {NATURE_SIMPLE}; setNatures("1.0", project, currentSet, false); //now do invalid tests and ensure simple nature is still configured String[][] invalid = getInvalidNatureSets(); for (int i = 0; i < invalid.length; i++) { setNatures("invalid: " + i, project, invalid[i], true); try { assertTrue("2.0", project.hasNature(NATURE_SIMPLE)); assertTrue("2.1", !project.hasNature(NATURE_EARTH)); assertTrue("2.2", project.isNatureEnabled(NATURE_SIMPLE)); assertTrue("2.3", !project.isNatureEnabled(NATURE_EARTH)); assertEquals("2.4", project.getDescription().getNatureIds(), currentSet); } catch (CoreException e) { fail("2.99", e); } } } /** * Test addition of nature that requires the workspace root. * See bugs 127562 and 128709. */ public void testBug127562Nature() { IWorkspace ws = ResourcesPlugin.getWorkspace(); IProject project = ws.getRoot().getProject("Project"); ensureExistsInWorkspace(project, true); String[][] valid = getValidNatureSets(); for (int i = 0; i < valid.length; i++) { setNatures("valid: " + i, project, valid[i], false); } // add with AVOID_NATURE_CONFIG String[] currentSet = new String[] {NATURE_127562}; setNatures("1.0", project, currentSet, false, true); // configure the nature using a conflicting scheduling rule IJobManager manager = Job.getJobManager(); try { manager.beginRule(ws.getRuleFactory().modifyRule(project), null); project.getNature(NATURE_127562).configure(); fail("2.0"); } catch (CoreException ex) { fail("2.1"); } catch (IllegalArgumentException ex) { // should throw this kind of exception } finally { manager.endRule(ws.getRuleFactory().modifyRule(project)); } // configure the nature using a non-conflicting scheduling rule try { manager.beginRule(ws.getRoot(), null); project.getNature(NATURE_127562).configure(); } catch (CoreException ex) { fail("3.0"); } finally { manager.endRule(ws.getRoot()); } } public void testBug297871() { IWorkspace ws = ResourcesPlugin.getWorkspace(); Project project = (Project) ws.getRoot().getProject("Project"); ensureExistsInWorkspace(project, true); java.io.File desc = null; try { IFileStore descStore = ((File) project.getFile(IProjectDescription.DESCRIPTION_FILE_NAME)).getStore(); desc = descStore.toLocalFile(EFS.NONE, getMonitor()); } catch (CoreException e) { fail("1.0"); } java.io.File descTmp = new java.io.File(desc.getPath() + ".tmp"); try { copy(desc, descTmp); } catch (IOException e) { fail("2.0", e); } setNatures("valid ", project, new String[] {NATURE_EARTH}, false); try { assertNotNull(project.getNature(NATURE_EARTH)); } catch (CoreException e) { fail("3.0", e); } try { assertTrue(project.hasNature(NATURE_EARTH)); } catch (CoreException e) { fail("4.0", e); } try { // Make sure enough time has past to bump file's // timestamp during the copy - Thread.currentThread().sleep(1000); + Thread.sleep(1000); } catch (InterruptedException e) { fail("5.0", e); } try { copy(descTmp, desc); } catch (IOException e) { fail("6.0", e); } try { project.refreshLocal(IResource.DEPTH_INFINITE, getMonitor()); } catch (CoreException e) { fail("7.0", e); } try { assertNull(project.getNature(NATURE_EARTH)); } catch (CoreException e) { fail("8.0", e); } try { assertFalse(project.hasNature(NATURE_EARTH)); } catch (CoreException e) { fail("9.0", e); } } private void copy(java.io.File src, java.io.File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) > 0) { out.write(buffer, 0, read); } in.close(); out.close(); } }
true
true
public void testBug297871() { IWorkspace ws = ResourcesPlugin.getWorkspace(); Project project = (Project) ws.getRoot().getProject("Project"); ensureExistsInWorkspace(project, true); java.io.File desc = null; try { IFileStore descStore = ((File) project.getFile(IProjectDescription.DESCRIPTION_FILE_NAME)).getStore(); desc = descStore.toLocalFile(EFS.NONE, getMonitor()); } catch (CoreException e) { fail("1.0"); } java.io.File descTmp = new java.io.File(desc.getPath() + ".tmp"); try { copy(desc, descTmp); } catch (IOException e) { fail("2.0", e); } setNatures("valid ", project, new String[] {NATURE_EARTH}, false); try { assertNotNull(project.getNature(NATURE_EARTH)); } catch (CoreException e) { fail("3.0", e); } try { assertTrue(project.hasNature(NATURE_EARTH)); } catch (CoreException e) { fail("4.0", e); } try { // Make sure enough time has past to bump file's // timestamp during the copy Thread.currentThread().sleep(1000); } catch (InterruptedException e) { fail("5.0", e); } try { copy(descTmp, desc); } catch (IOException e) { fail("6.0", e); } try { project.refreshLocal(IResource.DEPTH_INFINITE, getMonitor()); } catch (CoreException e) { fail("7.0", e); } try { assertNull(project.getNature(NATURE_EARTH)); } catch (CoreException e) { fail("8.0", e); } try { assertFalse(project.hasNature(NATURE_EARTH)); } catch (CoreException e) { fail("9.0", e); } }
public void testBug297871() { IWorkspace ws = ResourcesPlugin.getWorkspace(); Project project = (Project) ws.getRoot().getProject("Project"); ensureExistsInWorkspace(project, true); java.io.File desc = null; try { IFileStore descStore = ((File) project.getFile(IProjectDescription.DESCRIPTION_FILE_NAME)).getStore(); desc = descStore.toLocalFile(EFS.NONE, getMonitor()); } catch (CoreException e) { fail("1.0"); } java.io.File descTmp = new java.io.File(desc.getPath() + ".tmp"); try { copy(desc, descTmp); } catch (IOException e) { fail("2.0", e); } setNatures("valid ", project, new String[] {NATURE_EARTH}, false); try { assertNotNull(project.getNature(NATURE_EARTH)); } catch (CoreException e) { fail("3.0", e); } try { assertTrue(project.hasNature(NATURE_EARTH)); } catch (CoreException e) { fail("4.0", e); } try { // Make sure enough time has past to bump file's // timestamp during the copy Thread.sleep(1000); } catch (InterruptedException e) { fail("5.0", e); } try { copy(descTmp, desc); } catch (IOException e) { fail("6.0", e); } try { project.refreshLocal(IResource.DEPTH_INFINITE, getMonitor()); } catch (CoreException e) { fail("7.0", e); } try { assertNull(project.getNature(NATURE_EARTH)); } catch (CoreException e) { fail("8.0", e); } try { assertFalse(project.hasNature(NATURE_EARTH)); } catch (CoreException e) { fail("9.0", e); } }
diff --git a/RallyInterviewExercise/src/Spiral.java b/RallyInterviewExercise/src/Spiral.java index e6fd74d..40aba5b 100644 --- a/RallyInterviewExercise/src/Spiral.java +++ b/RallyInterviewExercise/src/Spiral.java @@ -1,85 +1,85 @@ /** * The Class Spiral. */ public class Spiral { // the number of integers to display in the spiral int spiralLength = 25; // CHANGE THIS TO INCREASE OR DECREASE THE SPIRAL LENGTH // calculate the dimension of the square spiral int dimensions = (int) Math.ceil(Math.sqrt(spiralLength)); // The buffer to build the spiral for display Integer[][] displayMatrix = new Integer[dimensions][dimensions]; // find the center of the matrix and handle even number dim int center = (dimensions / 2) - ((dimensions % 2 == 1) ? 0 : 1); // initial coordinates int x = center; int y = center; // our steps for spiraling outwards int layer = 1; // our counter int count = 1; /** * Insert into matrix. * add the count value to the matrix given the direction of forward or backwards with respect to the x,y coordinates * @param isForward * */ private void insertIntoMatrix(boolean isForward) { // x motion for (int j = 0; j < layer && count < spiralLength; j++) displayMatrix[y][x += (isForward) ? 1 : -1] = count++; // y motion for (int j = 0; j < layer && count < spiralLength; j++) displayMatrix[y += (isForward) ? 1 : -1][x] = count++; // layer steps layer++; } /** * Show spiral list. Display the initial array list, call function to create the display matrix , and display the spiral. */ private void showSpiralList() { displayMatrix[center][center] = 0; - // create the spiral in a display matrix to be show later + // create the spiral in a display matrix to be shown later while (count < spiralLength) { insertIntoMatrix(true); insertIntoMatrix(false); } // used to evaluate the display length for each number int numberWidth = String.valueOf(spiralLength).length(); System.out.println("\nThe sprial ..."); // display the matrix for (int i = (displayMatrix[0][0] == null) ? 1 : 0; i < displayMatrix.length; i++) { for (int j = 0; j < displayMatrix[i].length; j++) System.out.printf("%" + numberWidth + "s ", (displayMatrix[i][j] == null) ? "" : displayMatrix[i][j]); System.out.println(); } System.out.println("Done!"); } /** * The main method. */ public static void main(String[] args) { System.out.println("Exercise number three : number spiral"); new Spiral().showSpiralList(); } }
true
true
private void showSpiralList() { displayMatrix[center][center] = 0; // create the spiral in a display matrix to be show later while (count < spiralLength) { insertIntoMatrix(true); insertIntoMatrix(false); } // used to evaluate the display length for each number int numberWidth = String.valueOf(spiralLength).length(); System.out.println("\nThe sprial ..."); // display the matrix for (int i = (displayMatrix[0][0] == null) ? 1 : 0; i < displayMatrix.length; i++) { for (int j = 0; j < displayMatrix[i].length; j++) System.out.printf("%" + numberWidth + "s ", (displayMatrix[i][j] == null) ? "" : displayMatrix[i][j]); System.out.println(); } System.out.println("Done!"); }
private void showSpiralList() { displayMatrix[center][center] = 0; // create the spiral in a display matrix to be shown later while (count < spiralLength) { insertIntoMatrix(true); insertIntoMatrix(false); } // used to evaluate the display length for each number int numberWidth = String.valueOf(spiralLength).length(); System.out.println("\nThe sprial ..."); // display the matrix for (int i = (displayMatrix[0][0] == null) ? 1 : 0; i < displayMatrix.length; i++) { for (int j = 0; j < displayMatrix[i].length; j++) System.out.printf("%" + numberWidth + "s ", (displayMatrix[i][j] == null) ? "" : displayMatrix[i][j]); System.out.println(); } System.out.println("Done!"); }
diff --git a/src/plugins/floghelper/ui/FlogListToadlet.java b/src/plugins/floghelper/ui/FlogListToadlet.java index fc9ef0d..4f1e453 100644 --- a/src/plugins/floghelper/ui/FlogListToadlet.java +++ b/src/plugins/floghelper/ui/FlogListToadlet.java @@ -1,239 +1,239 @@ /* FlogHelper, Freenet plugin to create flogs * Copyright (C) 2009 Romain "Artefact2" Dalmaso * * 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 * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package plugins.floghelper.ui; import freenet.client.async.DatabaseDisabledException; import freenet.pluginmanager.PluginNotFoundException; import plugins.floghelper.data.DataFormatter; import freenet.client.HighLevelSimpleClient; import freenet.clients.http.PageNode; import freenet.clients.http.ToadletContext; import freenet.clients.http.ToadletContextClosedException; import freenet.support.Base64; import freenet.support.HTMLNode; import freenet.support.Logger; import freenet.support.api.HTTPRequest; import java.io.IOException; import java.net.URI; import plugins.floghelper.FlogHelper; import plugins.floghelper.data.Activelink; import plugins.floghelper.data.Flog; import plugins.floghelper.data.pluginstore.PluginStoreFlog; import plugins.floghelper.ui.flog.FlogFactory; /** * This toadlet shows the list of all the flogs, it's also the main index * page of the plugin. * * @author Artefact2 */ public class FlogListToadlet extends FlogHelperToadlet { public static final String MY_URI = "/"; public FlogListToadlet(final HighLevelSimpleClient hlsc) { super(hlsc, MY_URI); } public void getPageGet(final PageNode pageNode, final URI uri, final HTTPRequest request, final ToadletContext ctx) throws ToadletContextClosedException, IOException { final HTMLNode table = this.getPM().getInfobox(null, FlogHelper.getBaseL10n().getString("FlogList"), pageNode.content).addChild("table"); final HTMLNode tHead = table.addChild("thead"); final HTMLNode tFoot = table.addChild("tfoot"); final HTMLNode tBody = table.addChild("tbody"); final HTMLNode actionsRow = new HTMLNode("tr"); final HTMLNode formCreateNew = FlogHelper.getPR().addFormChild(actionsRow.addChild("th", "colspan", "7"), FlogHelperToadlet.BASE_URI + CreateOrEditFlogToadlet.MY_URI, "CreateNewFlog"); formCreateNew.addAttribute("method", "get"); formCreateNew.addChild("input", new String[]{"type", "value"}, new String[]{"submit", FlogHelper.getBaseL10n().getString("CreateFlog")}); final HTMLNode formImport = FlogHelper.getPR().addFormChild(actionsRow.addChild("th"), FlogHelperToadlet.BASE_URI + ImportFlogToadlet.MY_URI, "ImportFlog"); formImport.addAttribute("method", "get"); formImport.addChild("input", new String[]{"type", "value"}, new String[]{"submit", FlogHelper.getBaseL10n().getString("Import")}); final HTMLNode headersRow = new HTMLNode("tr"); headersRow.addChild("th", FlogHelper.getBaseL10n().getString("ID")); headersRow.addChild("th", FlogHelper.getBaseL10n().getString("Activelink")); headersRow.addChild("th", FlogHelper.getBaseL10n().getString("Title")); headersRow.addChild("th", FlogHelper.getBaseL10n().getString("Author")); headersRow.addChild("th", FlogHelper.getBaseL10n().getString("SmallDescription")); headersRow.addChild("th", FlogHelper.getBaseL10n().getString("NumberOfEntries")); headersRow.addChild("th", "colspan", "2", FlogHelper.getBaseL10n().getString("Actions")); tHead.addChild(actionsRow); tHead.addChild(headersRow); tFoot.addChild(headersRow); if (FlogHelper.getStore().subStores.isEmpty()) { tBody.addChild("tr").addChild("td", "colspan", "8", FlogHelper.getBaseL10n().getString("NoFlogsYet")); } for (final Flog flog : PluginStoreFlog.getFlogs()) { final String author = flog.getAuthorName(); final HTMLNode activelinkP = new HTMLNode("td"); if (flog.hasActivelink()) { HTMLNode activelinkImg = new HTMLNode("img"); final String base64str = Base64.encodeStandard(flog.getActivelink()); activelinkImg.addAttribute("src", "data:" + Activelink.MIMETYPE + ";base64," + base64str); activelinkImg.addAttribute("width", Integer.toString(Activelink.WIDTH)); activelinkImg.addAttribute("height", Integer.toString(Activelink.HEIGHT)); activelinkImg.addAttribute("alt", FlogHelper.getBaseL10n().getString("ActivelinkAlt")); activelinkImg.addAttribute("style", "vertical-align: middle;"); activelinkP.addChild(activelinkImg); } final HTMLNode row = tBody.addChild("tr"); row.addChild("td").addChild("pre", DataFormatter.toString(flog.getID())); row.addChild(activelinkP); try { row.addChild("td").addChild("a", "href", "/" + flog.getRequestURI()).addChild("%", DataFormatter.htmlSpecialChars(DataFormatter.toString(flog.getTitle()))); } catch (Exception ex) { Logger.error(this, "", ex); } row.addChild("td", DataFormatter.toString(author)); row.addChild("td", flog.getShortDescription()); row.addChild("td", DataFormatter.toString(flog.getNumberOfContents())); HTMLNode actions = row.addChild("td", "align", "center"); final HTMLNode formDetails = FlogHelper.getPR().addFormChild(actions, FlogHelperToadlet.BASE_URI + ContentListToadlet.MY_URI, "FlogDetails-" + flog.getID()); formDetails.addAttribute("method", "get"); formDetails.addChild("input", new String[]{"type", "value"}, new String[]{"submit", FlogHelper.getBaseL10n().getString("Entries")}); formDetails.addChild("input", new String[]{"type", "name", "value"}, new String[]{"hidden", "FlogID", DataFormatter.toString(flog.getID())}); final HTMLNode formPreview = FlogHelper.getPR().addFormChild(actions, FlogHelperToadlet.BASE_URI + PreviewToadlet.MY_URI + flog.getID() + "/index.html", "PreviewFlog-" + flog.getID()); formPreview.addAttribute("method", "get"); formPreview.addChild("input", new String[]{"type", "value", "name"}, new String[]{"submit", FlogHelper.getBaseL10n().getString("Preview"), "Preview"}); final HTMLNode formDelete = FlogHelper.getPR().addFormChild(actions, this.path(), "DeleteFlog-" + flog.getID()); formDelete.addChild("input", new String[]{"type", "value"}, new String[]{"submit", FlogHelper.getBaseL10n().getString("Delete")}); formDelete.addChild("input", new String[]{"type", "name", "value"}, new String[]{"hidden", "FlogToDelete", DataFormatter.toString(flog.getID())}); final HTMLNode formEdit = FlogHelper.getPR().addFormChild(actions, FlogHelperToadlet.BASE_URI + CreateOrEditFlogToadlet.MY_URI, "EditFlog-" + flog.getID()); formEdit.addAttribute("method", "get"); formEdit.addChild("input", new String[]{"type", "value"}, new String[]{"submit", FlogHelper.getBaseL10n().getString("Edit")}); formEdit.addChild("input", new String[]{"type", "name", "value"}, new String[]{"hidden", "FlogID", DataFormatter.toString(flog.getID())}); final HTMLNode formInsert = FlogHelper.getPR().addFormChild(actions, FlogHelperToadlet.BASE_URI + FlogListToadlet.MY_URI, "InsertFlog-" + flog.getID()); formInsert.addAttribute("method", "post"); formInsert.addChild("input", new String[]{"type", "value", "name"}, new String[]{"submit", FlogHelper.getBaseL10n().getString("Insert"), "Insert"}); formInsert.addChild("input", new String[]{"type", "name", "value"}, new String[]{"hidden", "FlogID", DataFormatter.toString(flog.getID())}); final HTMLNode formAttachments = FlogHelper.getPR().addFormChild(actions, FlogHelperToadlet.BASE_URI + AttachmentsToadlet.MY_URI, "Attachments-" + flog.getID()); formAttachments.addAttribute("method", "get"); formAttachments.addChild("input", new String[]{"type", "value"}, new String[]{"submit", FlogHelper.getBaseL10n().getString("Attachments")}); formAttachments.addChild("input", new String[]{"type", "name", "value"}, new String[]{"hidden", "FlogID", DataFormatter.toString(flog.getID())}); final HTMLNode formExport = FlogHelper.getPR().addFormChild(row.addChild("td"), FlogHelperToadlet.BASE_URI + ExportFlogToadlet.MY_URI, "EditFlog-" + flog.getID()); formExport.addAttribute("method", "get"); formExport.addChild("input", new String[]{"type", "value"}, new String[]{"submit", FlogHelper.getBaseL10n().getString("Export")}); formExport.addChild("input", new String[]{"type", "name", "value"}, new String[]{"hidden", "FlogID", DataFormatter.toString(flog.getID())}); } // This is only debug code to see what is in the PluginStore. //this.getPM().getInfobox("infobox-minor", "DEBUG PluginStore Dump", pageNode.content).addChild("pre", DataFormatter.printStore(FlogHelper.getStore())); writeHTMLReply(ctx, 200, "OK", null, pageNode.outer.generate()); } public void getPagePost(final PageNode pageNode, final URI uri, final HTTPRequest request, final ToadletContext ctx) throws ToadletContextClosedException, IOException { if (request.isPartSet("FlogToDelete") || request.isPartSet("FlogToReallyDelete")) { final String idToDelete = request.getPartAsString("FlogToDelete", 7); final String idToReallyDelete = request.getPartAsString("FlogToReallyDelete", 7); if (idToReallyDelete != null && !idToReallyDelete.equals("")) { - if (request.getPartAsString("Yes", 3).equals("Yes")) { + if (request.isPartSet("Yes")) { FlogHelper.getStore().subStores.remove(idToReallyDelete); FlogHelper.putStore(); this.handleMethodGET(uri, request, ctx); return; } else { this.handleMethodGET(uri, request, ctx); return; } } if (idToDelete != null && !idToDelete.equals("")) { final HTMLNode confirm = this.getPM().getInfobox("infobox-alert", FlogHelper.getBaseL10n().getString("ReallyDelete"), pageNode.content); final HTMLNode form = FlogHelper.getPR().addFormChild(confirm, this.path(), "ReallyDelete-" + idToDelete); form.addChild("p", FlogHelper.getBaseL10n().getString("ReallyDeleteFlogLong").replace("${FlogID}", idToDelete)); final HTMLNode buttons = form.addChild("p"); buttons.addChild("input", new String[]{"type", "name", "value"}, new String[]{"hidden", "FlogToReallyDelete", idToDelete}); buttons.addChild("input", new String[]{"type", "name", "value"}, new String[]{"submit", "Yes", FlogHelper.getBaseL10n().getString("Yes")}); buttons.addChild("input", new String[]{"type", "name", "value"}, new String[]{"submit", "No", FlogHelper.getBaseL10n().getString("No")}); } writeHTMLReply(ctx, 200, "OK", null, pageNode.outer.generate()); } else if(request.isPartSet("Insert") && request.isPartSet("FlogID")) { final FlogFactory fFactory = new FlogFactory(new PluginStoreFlog(request.getPartAsString("FlogID", 7))); if(fFactory.getContentsTreeMap(false).size() == 0) { HTMLNode infobox = this.getPM().getInfobox("infobox-error", FlogHelper.getBaseL10n().getString("RefusingToInsertEmplyFlog"), pageNode.content); infobox.addChild("p", FlogHelper.getBaseL10n().getString("RefusingToInsertEmplyFlogLong")); HTMLNode links = infobox.addChild("p"); links.addChild("a", "href", FlogHelperToadlet.BASE_URI + FlogListToadlet.MY_URI, FlogHelper.getBaseL10n().getString("ReturnToFlogList")); } else { try { fFactory.insert(); } catch (PluginNotFoundException ex) { // Won't happen } catch (DatabaseDisabledException ex) { // Won't happen } HTMLNode infobox = this.getPM().getInfobox(null, FlogHelper.getBaseL10n().getString("InsertInProgress"), pageNode.content); infobox.addChild("p", FlogHelper.getBaseL10n().getString("FlogIsInsertingLong")); HTMLNode links = infobox.addChild("p"); links.addChild("strong").addChild("a", "href", "/uploads/", FlogHelper.getBaseL10n().getString("GoToInsertsPage")); links.addChild("br"); links.addChild("a", "href", FlogHelperToadlet.BASE_URI + FlogListToadlet.MY_URI, FlogHelper.getBaseL10n().getString("ReturnToFlogList")); } writeHTMLReply(ctx, 200, "OK", null, pageNode.outer.generate()); } } }
true
true
public void getPagePost(final PageNode pageNode, final URI uri, final HTTPRequest request, final ToadletContext ctx) throws ToadletContextClosedException, IOException { if (request.isPartSet("FlogToDelete") || request.isPartSet("FlogToReallyDelete")) { final String idToDelete = request.getPartAsString("FlogToDelete", 7); final String idToReallyDelete = request.getPartAsString("FlogToReallyDelete", 7); if (idToReallyDelete != null && !idToReallyDelete.equals("")) { if (request.getPartAsString("Yes", 3).equals("Yes")) { FlogHelper.getStore().subStores.remove(idToReallyDelete); FlogHelper.putStore(); this.handleMethodGET(uri, request, ctx); return; } else { this.handleMethodGET(uri, request, ctx); return; } } if (idToDelete != null && !idToDelete.equals("")) { final HTMLNode confirm = this.getPM().getInfobox("infobox-alert", FlogHelper.getBaseL10n().getString("ReallyDelete"), pageNode.content); final HTMLNode form = FlogHelper.getPR().addFormChild(confirm, this.path(), "ReallyDelete-" + idToDelete); form.addChild("p", FlogHelper.getBaseL10n().getString("ReallyDeleteFlogLong").replace("${FlogID}", idToDelete)); final HTMLNode buttons = form.addChild("p"); buttons.addChild("input", new String[]{"type", "name", "value"}, new String[]{"hidden", "FlogToReallyDelete", idToDelete}); buttons.addChild("input", new String[]{"type", "name", "value"}, new String[]{"submit", "Yes", FlogHelper.getBaseL10n().getString("Yes")}); buttons.addChild("input", new String[]{"type", "name", "value"},
public void getPagePost(final PageNode pageNode, final URI uri, final HTTPRequest request, final ToadletContext ctx) throws ToadletContextClosedException, IOException { if (request.isPartSet("FlogToDelete") || request.isPartSet("FlogToReallyDelete")) { final String idToDelete = request.getPartAsString("FlogToDelete", 7); final String idToReallyDelete = request.getPartAsString("FlogToReallyDelete", 7); if (idToReallyDelete != null && !idToReallyDelete.equals("")) { if (request.isPartSet("Yes")) { FlogHelper.getStore().subStores.remove(idToReallyDelete); FlogHelper.putStore(); this.handleMethodGET(uri, request, ctx); return; } else { this.handleMethodGET(uri, request, ctx); return; } } if (idToDelete != null && !idToDelete.equals("")) { final HTMLNode confirm = this.getPM().getInfobox("infobox-alert", FlogHelper.getBaseL10n().getString("ReallyDelete"), pageNode.content); final HTMLNode form = FlogHelper.getPR().addFormChild(confirm, this.path(), "ReallyDelete-" + idToDelete); form.addChild("p", FlogHelper.getBaseL10n().getString("ReallyDeleteFlogLong").replace("${FlogID}", idToDelete)); final HTMLNode buttons = form.addChild("p"); buttons.addChild("input", new String[]{"type", "name", "value"}, new String[]{"hidden", "FlogToReallyDelete", idToDelete}); buttons.addChild("input", new String[]{"type", "name", "value"}, new String[]{"submit", "Yes", FlogHelper.getBaseL10n().getString("Yes")}); buttons.addChild("input", new String[]{"type", "name", "value"},
diff --git a/SWADroid/src/es/ugr/swad/swadroid/modules/notifications/NotificationsCursorAdapter.java b/SWADroid/src/es/ugr/swad/swadroid/modules/notifications/NotificationsCursorAdapter.java index dbe290b3..ffac7665 100644 --- a/SWADroid/src/es/ugr/swad/swadroid/modules/notifications/NotificationsCursorAdapter.java +++ b/SWADroid/src/es/ugr/swad/swadroid/modules/notifications/NotificationsCursorAdapter.java @@ -1,234 +1,234 @@ /* * This file is part of SWADroid. * * Copyright (C) 2010 Juan Miguel Boyero Corral <[email protected]> * * SWADroid 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 * (at your option) any later version. * * SWADroid 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 SWADroid. If not, see <http://www.gnu.org/licenses/>. */ package es.ugr.swad.swadroid.modules.notifications; import java.util.Date; import es.ugr.swad.swadroid.R; import es.ugr.swad.swadroid.modules.Messages; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ImageView; import android.widget.TextView; /** * Custom adapter for display notifications * @author Juan Miguel Boyero Corral <[email protected]> * */ public class NotificationsCursorAdapter extends CursorAdapter { private boolean [] contentVisible; Context ctx; /** * Constructor * @param context Application context * @param c Database cursor */ public NotificationsCursorAdapter(Context context, Cursor c) { super(context, c); ctx = context; int numRows = c.getCount(); contentVisible = new boolean[numRows]; for(int i=0; i<numRows; i++) { contentVisible[i] = false; } } /** * Constructor * @param context Application context * @param c Database cursor * @param autoRequery Flag to set autoRequery function */ public NotificationsCursorAdapter(Context context, Cursor c, boolean autoRequery) { super(context, c, autoRequery); } @Override public void bindView(View view, Context context, Cursor cursor) { final Context ctx = context; final Long notificationCode = cursor.getLong(cursor.getColumnIndex("id")); long unixTime; String type, sender, senderFirstname, senderSurname1, senderSurname2, summaryText; String contentText; String[] dateContent; Date d; int numRows = cursor.getCount(); if(contentVisible.length == 0) { contentVisible = new boolean[numRows]; } view.setScrollContainer(false); TextView eventType = (TextView) view.findViewById(R.id.eventType); TextView eventDate = (TextView) view.findViewById(R.id.eventDate); TextView eventTime = (TextView) view.findViewById(R.id.eventTime); TextView eventSender = (TextView) view.findViewById(R.id.eventSender); TextView location = (TextView) view.findViewById(R.id.eventLocation); final TextView summary = (TextView) view.findViewById(R.id.eventSummary); TextView content = (TextView) view.findViewById(R.id.eventText); ImageView notificationIcon = (ImageView) view.findViewById(R.id.notificationIcon); ImageView messageReplyButton = (ImageView) view.findViewById(R.id.messageReplyButton); OnClickListener replyMessageListener = new OnClickListener() { public void onClick(View v) { Intent activity = new Intent(ctx.getApplicationContext(), Messages.class); activity.putExtra("notificationCode", notificationCode); activity.putExtra("summary", summary.getText().toString()); ctx.startActivity(activity); } }; if(eventType != null) { type = cursor.getString(cursor.getColumnIndex("eventType")); messageReplyButton.setVisibility(View.GONE); if(type.equals("examAnnouncement")) { type = context.getString(R.string.examAnnouncement); notificationIcon.setImageResource(R.drawable.announce); } else if(type.equals("marksFile")) { type = context.getString(R.string.marksFile); notificationIcon.setImageResource(R.drawable.grades); } else if(type.equals("notice")) { type = context.getString(R.string.notice); notificationIcon.setImageResource(R.drawable.note); } else if(type.equals("message")) { type = context.getString(R.string.message); notificationIcon.setImageResource(R.drawable.recmsg); messageReplyButton.setOnClickListener(replyMessageListener); messageReplyButton.setVisibility(View.VISIBLE); } else if(type.equals("forumReply")) { type = context.getString(R.string.forumReply); notificationIcon.setImageResource(R.drawable.forum); } else if(type.equals("assignment")) { type = context.getString(R.string.assignment); notificationIcon.setImageResource(R.drawable.desk); } else if(type.equals("survey")) { type = context.getString(R.string.survey); notificationIcon.setImageResource(R.drawable.survey); } else { type = context.getString(R.string.unknownNotification); notificationIcon.setImageResource(R.drawable.ic_launcher_swadroid); } eventType.setText(type); } if((eventDate != null) && (eventTime != null)){ unixTime = Long.parseLong(cursor.getString(cursor.getColumnIndex("eventTime"))); d = new Date(unixTime * 1000); dateContent = d.toLocaleString().split(" "); eventDate.setText(dateContent[0]); eventTime.setText(dateContent[1]); } if(eventSender != null){ sender = ""; senderFirstname = cursor.getString(cursor.getColumnIndex("userFirstname")); senderSurname1 = cursor.getString(cursor.getColumnIndex("userSurname1")); senderSurname2 = cursor.getString(cursor.getColumnIndex("userSurname2")); //Empty fields checking if(!senderFirstname.equals("anyType{}")) sender += senderFirstname + " "; if(!senderSurname1.equals("anyType{}")) sender += senderSurname1 + " "; if(!senderSurname2.equals("anyType{}")) sender += senderSurname2; eventSender.setText(sender); } if(location != null) { location.setText(cursor.getString(cursor.getColumnIndex("location"))); } if(summary != null){ summaryText = cursor.getString(cursor.getColumnIndex("summary")); //Empty field checking if(summaryText.equals("anyType{}")) summaryText = context.getString(R.string.noSubjectMsg); summary.setText(Html.fromHtml(summaryText)); } if((content != null)){ contentText = cursor.getString(cursor.getColumnIndex("content")); //Empty field checking if(contentText.equals("anyType{}")) contentText = context.getString(R.string.noContentMsg); - content.setText(Html.fromHtml(contentText)); + content.setText(contentText); if(contentVisible[cursor.getPosition()]) { content.setVisibility(View.VISIBLE); } else { content.setVisibility(View.GONE); } } } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { LayoutInflater vi = LayoutInflater.from(context); View v = vi.inflate(R.layout.notifications_list_item, parent, false); return v; } /** * If the notification is not a mark, shows or hides its content * If the notification is a mark, launches a WebView activity to show it * @param position Notification position in the ListView */ /*public void toggleContentVisibility(int position) { String viewType, marksType; View view = this.getView(position, null, null); TextView eventType = (TextView) view.findViewById(R.id.eventType); TextView content = (TextView) view.findViewById(R.id.eventText); viewType = String.valueOf(eventType.getText()); marksType = ctx.getString(R.string.marksFile); if(viewType.equals(marksType)) { Intent activity = new Intent(ctx.getApplicationContext(), NotificationItem.class); activity.putExtra("content", content.getText().toString()); ctx.startActivity(activity); } else { contentVisible[position] = !contentVisible[position]; this.notifyDataSetChanged(); } }*/ }
true
true
public void bindView(View view, Context context, Cursor cursor) { final Context ctx = context; final Long notificationCode = cursor.getLong(cursor.getColumnIndex("id")); long unixTime; String type, sender, senderFirstname, senderSurname1, senderSurname2, summaryText; String contentText; String[] dateContent; Date d; int numRows = cursor.getCount(); if(contentVisible.length == 0) { contentVisible = new boolean[numRows]; } view.setScrollContainer(false); TextView eventType = (TextView) view.findViewById(R.id.eventType); TextView eventDate = (TextView) view.findViewById(R.id.eventDate); TextView eventTime = (TextView) view.findViewById(R.id.eventTime); TextView eventSender = (TextView) view.findViewById(R.id.eventSender); TextView location = (TextView) view.findViewById(R.id.eventLocation); final TextView summary = (TextView) view.findViewById(R.id.eventSummary); TextView content = (TextView) view.findViewById(R.id.eventText); ImageView notificationIcon = (ImageView) view.findViewById(R.id.notificationIcon); ImageView messageReplyButton = (ImageView) view.findViewById(R.id.messageReplyButton); OnClickListener replyMessageListener = new OnClickListener() { public void onClick(View v) { Intent activity = new Intent(ctx.getApplicationContext(), Messages.class); activity.putExtra("notificationCode", notificationCode); activity.putExtra("summary", summary.getText().toString()); ctx.startActivity(activity); } }; if(eventType != null) { type = cursor.getString(cursor.getColumnIndex("eventType")); messageReplyButton.setVisibility(View.GONE); if(type.equals("examAnnouncement")) { type = context.getString(R.string.examAnnouncement); notificationIcon.setImageResource(R.drawable.announce); } else if(type.equals("marksFile")) { type = context.getString(R.string.marksFile); notificationIcon.setImageResource(R.drawable.grades); } else if(type.equals("notice")) { type = context.getString(R.string.notice); notificationIcon.setImageResource(R.drawable.note); } else if(type.equals("message")) { type = context.getString(R.string.message); notificationIcon.setImageResource(R.drawable.recmsg); messageReplyButton.setOnClickListener(replyMessageListener); messageReplyButton.setVisibility(View.VISIBLE); } else if(type.equals("forumReply")) { type = context.getString(R.string.forumReply); notificationIcon.setImageResource(R.drawable.forum); } else if(type.equals("assignment")) { type = context.getString(R.string.assignment); notificationIcon.setImageResource(R.drawable.desk); } else if(type.equals("survey")) { type = context.getString(R.string.survey); notificationIcon.setImageResource(R.drawable.survey); } else { type = context.getString(R.string.unknownNotification); notificationIcon.setImageResource(R.drawable.ic_launcher_swadroid); } eventType.setText(type); } if((eventDate != null) && (eventTime != null)){ unixTime = Long.parseLong(cursor.getString(cursor.getColumnIndex("eventTime"))); d = new Date(unixTime * 1000); dateContent = d.toLocaleString().split(" "); eventDate.setText(dateContent[0]); eventTime.setText(dateContent[1]); } if(eventSender != null){ sender = ""; senderFirstname = cursor.getString(cursor.getColumnIndex("userFirstname")); senderSurname1 = cursor.getString(cursor.getColumnIndex("userSurname1")); senderSurname2 = cursor.getString(cursor.getColumnIndex("userSurname2")); //Empty fields checking if(!senderFirstname.equals("anyType{}")) sender += senderFirstname + " "; if(!senderSurname1.equals("anyType{}")) sender += senderSurname1 + " "; if(!senderSurname2.equals("anyType{}")) sender += senderSurname2; eventSender.setText(sender); } if(location != null) { location.setText(cursor.getString(cursor.getColumnIndex("location"))); } if(summary != null){ summaryText = cursor.getString(cursor.getColumnIndex("summary")); //Empty field checking if(summaryText.equals("anyType{}")) summaryText = context.getString(R.string.noSubjectMsg); summary.setText(Html.fromHtml(summaryText)); } if((content != null)){ contentText = cursor.getString(cursor.getColumnIndex("content")); //Empty field checking if(contentText.equals("anyType{}")) contentText = context.getString(R.string.noContentMsg); content.setText(Html.fromHtml(contentText)); if(contentVisible[cursor.getPosition()]) { content.setVisibility(View.VISIBLE); } else { content.setVisibility(View.GONE); } } }
public void bindView(View view, Context context, Cursor cursor) { final Context ctx = context; final Long notificationCode = cursor.getLong(cursor.getColumnIndex("id")); long unixTime; String type, sender, senderFirstname, senderSurname1, senderSurname2, summaryText; String contentText; String[] dateContent; Date d; int numRows = cursor.getCount(); if(contentVisible.length == 0) { contentVisible = new boolean[numRows]; } view.setScrollContainer(false); TextView eventType = (TextView) view.findViewById(R.id.eventType); TextView eventDate = (TextView) view.findViewById(R.id.eventDate); TextView eventTime = (TextView) view.findViewById(R.id.eventTime); TextView eventSender = (TextView) view.findViewById(R.id.eventSender); TextView location = (TextView) view.findViewById(R.id.eventLocation); final TextView summary = (TextView) view.findViewById(R.id.eventSummary); TextView content = (TextView) view.findViewById(R.id.eventText); ImageView notificationIcon = (ImageView) view.findViewById(R.id.notificationIcon); ImageView messageReplyButton = (ImageView) view.findViewById(R.id.messageReplyButton); OnClickListener replyMessageListener = new OnClickListener() { public void onClick(View v) { Intent activity = new Intent(ctx.getApplicationContext(), Messages.class); activity.putExtra("notificationCode", notificationCode); activity.putExtra("summary", summary.getText().toString()); ctx.startActivity(activity); } }; if(eventType != null) { type = cursor.getString(cursor.getColumnIndex("eventType")); messageReplyButton.setVisibility(View.GONE); if(type.equals("examAnnouncement")) { type = context.getString(R.string.examAnnouncement); notificationIcon.setImageResource(R.drawable.announce); } else if(type.equals("marksFile")) { type = context.getString(R.string.marksFile); notificationIcon.setImageResource(R.drawable.grades); } else if(type.equals("notice")) { type = context.getString(R.string.notice); notificationIcon.setImageResource(R.drawable.note); } else if(type.equals("message")) { type = context.getString(R.string.message); notificationIcon.setImageResource(R.drawable.recmsg); messageReplyButton.setOnClickListener(replyMessageListener); messageReplyButton.setVisibility(View.VISIBLE); } else if(type.equals("forumReply")) { type = context.getString(R.string.forumReply); notificationIcon.setImageResource(R.drawable.forum); } else if(type.equals("assignment")) { type = context.getString(R.string.assignment); notificationIcon.setImageResource(R.drawable.desk); } else if(type.equals("survey")) { type = context.getString(R.string.survey); notificationIcon.setImageResource(R.drawable.survey); } else { type = context.getString(R.string.unknownNotification); notificationIcon.setImageResource(R.drawable.ic_launcher_swadroid); } eventType.setText(type); } if((eventDate != null) && (eventTime != null)){ unixTime = Long.parseLong(cursor.getString(cursor.getColumnIndex("eventTime"))); d = new Date(unixTime * 1000); dateContent = d.toLocaleString().split(" "); eventDate.setText(dateContent[0]); eventTime.setText(dateContent[1]); } if(eventSender != null){ sender = ""; senderFirstname = cursor.getString(cursor.getColumnIndex("userFirstname")); senderSurname1 = cursor.getString(cursor.getColumnIndex("userSurname1")); senderSurname2 = cursor.getString(cursor.getColumnIndex("userSurname2")); //Empty fields checking if(!senderFirstname.equals("anyType{}")) sender += senderFirstname + " "; if(!senderSurname1.equals("anyType{}")) sender += senderSurname1 + " "; if(!senderSurname2.equals("anyType{}")) sender += senderSurname2; eventSender.setText(sender); } if(location != null) { location.setText(cursor.getString(cursor.getColumnIndex("location"))); } if(summary != null){ summaryText = cursor.getString(cursor.getColumnIndex("summary")); //Empty field checking if(summaryText.equals("anyType{}")) summaryText = context.getString(R.string.noSubjectMsg); summary.setText(Html.fromHtml(summaryText)); } if((content != null)){ contentText = cursor.getString(cursor.getColumnIndex("content")); //Empty field checking if(contentText.equals("anyType{}")) contentText = context.getString(R.string.noContentMsg); content.setText(contentText); if(contentVisible[cursor.getPosition()]) { content.setVisibility(View.VISIBLE); } else { content.setVisibility(View.GONE); } } }
diff --git a/src/main/java/com/thoughtworks/lirenlab/interfaces/common/filters/SetCharacterEncodingFilter.java b/src/main/java/com/thoughtworks/lirenlab/interfaces/common/filters/SetCharacterEncodingFilter.java index 86d0a1c..abbab64 100644 --- a/src/main/java/com/thoughtworks/lirenlab/interfaces/common/filters/SetCharacterEncodingFilter.java +++ b/src/main/java/com/thoughtworks/lirenlab/interfaces/common/filters/SetCharacterEncodingFilter.java @@ -1,34 +1,34 @@ package com.thoughtworks.lirenlab.interfaces.common.filters; 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 java.io.IOException; import static com.google.common.base.Preconditions.checkState; public class SetCharacterEncodingFilter implements Filter { public static final String ENCODING = "encoding"; private String encoding; @Override public void init(final FilterConfig filterConfig) throws ServletException { - String encoding = filterConfig.getInitParameter(ENCODING); + encoding = filterConfig.getInitParameter(ENCODING); checkState(encoding != null, "encoding must be set"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding(encoding); chain.doFilter(request, response); } @Override public void destroy() { encoding = null; } }
true
true
public void init(final FilterConfig filterConfig) throws ServletException { String encoding = filterConfig.getInitParameter(ENCODING); checkState(encoding != null, "encoding must be set"); }
public void init(final FilterConfig filterConfig) throws ServletException { encoding = filterConfig.getInitParameter(ENCODING); checkState(encoding != null, "encoding must be set"); }
diff --git a/drools-core/src/main/java/org/drools/audit/WorkingMemoryLogger.java b/drools-core/src/main/java/org/drools/audit/WorkingMemoryLogger.java index 8f7ed0f284..71cf7839df 100644 --- a/drools-core/src/main/java/org/drools/audit/WorkingMemoryLogger.java +++ b/drools-core/src/main/java/org/drools/audit/WorkingMemoryLogger.java @@ -1,495 +1,495 @@ package org.drools.audit; /* * Copyright 2005 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.io.ObjectOutput; import java.io.IOException; import java.io.ObjectInput; import org.drools.WorkingMemoryEventManager; import org.drools.FactHandle; import org.drools.WorkingMemory; import org.drools.audit.event.ActivationLogEvent; import org.drools.audit.event.ILogEventFilter; import org.drools.audit.event.LogEvent; import org.drools.audit.event.ObjectLogEvent; import org.drools.audit.event.RuleBaseLogEvent; import org.drools.audit.event.RuleFlowGroupLogEvent; import org.drools.audit.event.RuleFlowLogEvent; import org.drools.audit.event.RuleFlowNodeLogEvent; import org.drools.common.InternalFactHandle; import org.drools.common.InternalWorkingMemory; import org.drools.event.ActivationCancelledEvent; import org.drools.event.ActivationCreatedEvent; import org.drools.event.AfterActivationFiredEvent; import org.drools.event.AfterFunctionRemovedEvent; import org.drools.event.AfterPackageAddedEvent; import org.drools.event.AfterPackageRemovedEvent; import org.drools.event.AfterRuleAddedEvent; import org.drools.event.AfterRuleBaseLockedEvent; import org.drools.event.AfterRuleBaseUnlockedEvent; import org.drools.event.AfterRuleRemovedEvent; import org.drools.event.AgendaEventListener; import org.drools.event.AgendaGroupPoppedEvent; import org.drools.event.AgendaGroupPushedEvent; import org.drools.event.BeforeActivationFiredEvent; import org.drools.event.BeforeFunctionRemovedEvent; import org.drools.event.BeforePackageAddedEvent; import org.drools.event.BeforePackageRemovedEvent; import org.drools.event.BeforeRuleAddedEvent; import org.drools.event.BeforeRuleBaseLockedEvent; import org.drools.event.BeforeRuleBaseUnlockedEvent; import org.drools.event.BeforeRuleRemovedEvent; import org.drools.event.ObjectInsertedEvent; import org.drools.event.ObjectUpdatedEvent; import org.drools.event.ObjectRetractedEvent; import org.drools.event.RuleBaseEventListener; import org.drools.event.RuleFlowCompletedEvent; import org.drools.event.RuleFlowEventListener; import org.drools.event.RuleFlowGroupActivatedEvent; import org.drools.event.RuleFlowGroupDeactivatedEvent; import org.drools.event.RuleFlowNodeTriggeredEvent; import org.drools.event.RuleFlowStartedEvent; import org.drools.event.WorkingMemoryEventListener; import org.drools.rule.Declaration; import org.drools.spi.Activation; import org.drools.spi.Tuple; /** * A logger of events generated by a working memory. * It listens to the events generated by the working memory and * creates associated log event (containing a snapshot of the * state of the working event at that time). * * Filters can be used to filter out unwanted events. * * Subclasses of this class should implement the logEventCreated(LogEvent) * method and store this information, like for example log to file * or database. * * @author <a href="mailto:[email protected]">Kris Verlaenen </a> */ public abstract class WorkingMemoryLogger implements WorkingMemoryEventListener, AgendaEventListener, RuleFlowEventListener, RuleBaseEventListener { private List filters = new ArrayList(); public WorkingMemoryLogger() { } /** * Creates a new working memory logger for the given working memory. * * @param workingMemory */ public WorkingMemoryLogger(final WorkingMemoryEventManager workingMemoryEventManager) { workingMemoryEventManager.addEventListener( (WorkingMemoryEventListener) this ); workingMemoryEventManager.addEventListener( (AgendaEventListener) this ); workingMemoryEventManager.addEventListener( (RuleFlowEventListener) this ); workingMemoryEventManager.addEventListener( (RuleBaseEventListener) this ); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { filters = (List)in.readObject(); } public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(filters); } /** * This method is invoked every time a new log event is created. * Subclasses should implement this method and store the event, * like for example log to a file or database. * * @param logEvent */ public abstract void logEventCreated(LogEvent logEvent); /** * This method is invoked every time a new log event is created. * It filters out unwanted events. * * @param logEvent */ private void filterLogEvent(final LogEvent logEvent) { final Iterator iterator = this.filters.iterator(); while ( iterator.hasNext() ) { final ILogEventFilter filter = (ILogEventFilter) iterator.next(); // do nothing if one of the filters doesn't accept the event if ( !filter.acceptEvent( logEvent ) ) { return; } } // if all the filters accepted the event, signal the creation // of the event logEventCreated( logEvent ); } /** * Adds the given filter to the list of filters for this event log. * A log event must be accepted by all the filters to be entered in * the event log. * * @param filter The filter that should be added. */ public void addFilter(final ILogEventFilter filter) { if ( filter == null ) { throw new NullPointerException(); } this.filters.add( filter ); } /** * Removes the given filter from the list of filters for this event log. * If the given filter was not a filter of this event log, nothing * happens. * * @param filter The filter that should be removed. */ public void removeFilter(final ILogEventFilter filter) { this.filters.remove( filter ); } /** * Clears all filters of this event log. */ public void clearFilters() { this.filters.clear(); } /** * @see org.drools.event.WorkingMemoryEventListener */ public void objectInserted(final ObjectInsertedEvent event) { filterLogEvent( new ObjectLogEvent( LogEvent.INSERTED, ((InternalFactHandle) event.getFactHandle()).getId(), event.getObject().toString() ) ); } /** * @see org.drools.event.WorkingMemoryEventListener */ public void objectUpdated(final ObjectUpdatedEvent event) { filterLogEvent( new ObjectLogEvent( LogEvent.UPDATED, ((InternalFactHandle) event.getFactHandle()).getId(), event.getObject().toString() ) ); } /** * @see org.drools.event.WorkingMemoryEventListener */ public void objectRetracted(final ObjectRetractedEvent event) { filterLogEvent( new ObjectLogEvent( LogEvent.RETRACTED, ((InternalFactHandle) event.getFactHandle()).getId(), event.getOldObject().toString() ) ); } /** * @see org.drools.event.AgendaEventListener */ public void activationCreated(final ActivationCreatedEvent event, final WorkingMemory workingMemory) { filterLogEvent( new ActivationLogEvent( LogEvent.ACTIVATION_CREATED, getActivationId( event.getActivation() ), event.getActivation().getRule().getName(), extractDeclarations( event.getActivation(), workingMemory ), event.getActivation().getRule().getRuleFlowGroup() ) ); } /** * @see org.drools.event.AgendaEventListener */ public void activationCancelled(final ActivationCancelledEvent event, final WorkingMemory workingMemory) { filterLogEvent( new ActivationLogEvent( LogEvent.ACTIVATION_CANCELLED, getActivationId( event.getActivation() ), event.getActivation().getRule().getName(), extractDeclarations( event.getActivation(), workingMemory ), event.getActivation().getRule().getRuleFlowGroup() ) ); } /** * @see org.drools.event.AgendaEventListener */ public void beforeActivationFired(final BeforeActivationFiredEvent event, final WorkingMemory workingMemory) { filterLogEvent( new ActivationLogEvent( LogEvent.BEFORE_ACTIVATION_FIRE, getActivationId( event.getActivation() ), event.getActivation().getRule().getName(), extractDeclarations( event.getActivation(), workingMemory ), event.getActivation().getRule().getRuleFlowGroup() ) ); } /** * @see org.drools.event.AgendaEventListener */ public void afterActivationFired(final AfterActivationFiredEvent event, final WorkingMemory workingMemory) { filterLogEvent( new ActivationLogEvent( LogEvent.AFTER_ACTIVATION_FIRE, getActivationId( event.getActivation() ), event.getActivation().getRule().getName(), extractDeclarations( event.getActivation(), workingMemory ), event.getActivation().getRule().getRuleFlowGroup() ) ); } /** * Creates a string representation of the declarations of an activation. * This is a list of name-value-pairs for each of the declarations in the * tuple of the activation. The name is the identifier (=name) of the * declaration, and the value is a toString of the value of the * parameter, followed by the id of the fact between parentheses. * * @param activation The activation from which the declarations should be extracted * @return A String represetation of the declarations of the activation. */ private String extractDeclarations(final Activation activation, final WorkingMemory workingMemory) { final StringBuffer result = new StringBuffer(); final Tuple tuple = activation.getTuple(); final Map declarations = activation.getSubRule().getOuterDeclarations(); for ( Iterator it = declarations.values().iterator(); it.hasNext(); ) { final Declaration declaration = (Declaration) it.next(); final FactHandle handle = tuple.get( declaration ); if ( handle instanceof InternalFactHandle ) { final InternalFactHandle handleImpl = (InternalFactHandle) handle; if ( handleImpl.getId() == -1 ) { // This handle is now invalid, probably due to an fact retraction continue; } - final Object value = declaration.getValue( (InternalWorkingMemory) workingMemory, workingMemory.getObject( handle ) ); + final Object value = declaration.getValue( (InternalWorkingMemory) workingMemory, handleImpl.getObject() ); result.append( declaration.getIdentifier() ); result.append( "=" ); if ( value == null ) { // this should never occur result.append( "null" ); } else { result.append( value ); result.append( "(" ); result.append( handleImpl.getId() ); result.append( ")" ); } } if ( it.hasNext() ) { result.append( "; " ); } } return result.toString(); } /** * Returns a String that can be used as unique identifier for an * activation. Since the activationId is the same for all assertions * that are created during a single insert, update or retract, the * key of the tuple of the activation is added too (which is a set * of fact handle ids). * * @param activation The activation for which a unique id should be generated * @return A unique id for the activation */ private static String getActivationId(final Activation activation) { final StringBuffer result = new StringBuffer( activation.getRule().getName() ); result.append( " [" ); final Tuple tuple = activation.getTuple(); final FactHandle[] handles = tuple.getFactHandles(); for ( int i = 0; i < handles.length; i++ ) { result.append( ((InternalFactHandle) handles[i]).getId() ); if ( i < handles.length - 1 ) { result.append( ", " ); } } return result.append( "]" ).toString(); } public void agendaGroupPopped(final AgendaGroupPoppedEvent event, final WorkingMemory workingMemory) { // we don't audit this yet } public void agendaGroupPushed(final AgendaGroupPushedEvent event, final WorkingMemory workingMemory) { // we don't audit this yet } public void beforeRuleFlowStarted(RuleFlowStartedEvent event, WorkingMemory workingMemory) { filterLogEvent( new RuleFlowLogEvent( LogEvent.BEFORE_RULEFLOW_CREATED, event.getRuleFlowProcessInstance().getProcess().getId(), event.getRuleFlowProcessInstance().getProcess().getName() ) ); } public void afterRuleFlowStarted(RuleFlowStartedEvent event, WorkingMemory workingMemory) { filterLogEvent(new RuleFlowLogEvent(LogEvent.AFTER_RULEFLOW_CREATED, event.getRuleFlowProcessInstance().getProcess().getId(), event.getRuleFlowProcessInstance().getProcess().getName())); } public void beforeRuleFlowCompleted(RuleFlowCompletedEvent event, WorkingMemory workingMemory) { filterLogEvent( new RuleFlowLogEvent( LogEvent.BEFORE_RULEFLOW_COMPLETED, event.getRuleFlowProcessInstance().getProcess().getId(), event.getRuleFlowProcessInstance().getProcess().getName() ) ); } public void afterRuleFlowCompleted(RuleFlowCompletedEvent event, WorkingMemory workingMemory) { filterLogEvent(new RuleFlowLogEvent(LogEvent.AFTER_RULEFLOW_COMPLETED, event.getRuleFlowProcessInstance().getProcess().getId(), event.getRuleFlowProcessInstance().getProcess().getName())); } public void beforeRuleFlowGroupActivated( RuleFlowGroupActivatedEvent event, WorkingMemory workingMemory) { filterLogEvent(new RuleFlowGroupLogEvent( LogEvent.BEFORE_RULEFLOW_GROUP_ACTIVATED, event .getRuleFlowGroup().getName(), event.getRuleFlowGroup() .size())); } public void afterRuleFlowGroupActivated( RuleFlowGroupActivatedEvent event, WorkingMemory workingMemory) { filterLogEvent(new RuleFlowGroupLogEvent( LogEvent.AFTER_RULEFLOW_GROUP_ACTIVATED, event.getRuleFlowGroup().getName(), event.getRuleFlowGroup().size())); } public void beforeRuleFlowGroupDeactivated( RuleFlowGroupDeactivatedEvent event, WorkingMemory workingMemory) { filterLogEvent(new RuleFlowGroupLogEvent( LogEvent.BEFORE_RULEFLOW_GROUP_DEACTIVATED, event.getRuleFlowGroup().getName(), event.getRuleFlowGroup().size())); } public void afterRuleFlowGroupDeactivated( RuleFlowGroupDeactivatedEvent event, WorkingMemory workingMemory) { filterLogEvent(new RuleFlowGroupLogEvent( LogEvent.AFTER_RULEFLOW_GROUP_DEACTIVATED, event.getRuleFlowGroup().getName(), event.getRuleFlowGroup().size())); } public void beforeRuleFlowNodeTriggered(RuleFlowNodeTriggeredEvent event, WorkingMemory workingMemory) { filterLogEvent(new RuleFlowNodeLogEvent(LogEvent.BEFORE_RULEFLOW_NODE_TRIGGERED, event.getRuleFlowNodeInstance().getId() + "", event.getRuleFlowNodeInstance().getNode().getName(), event.getRuleFlowProcessInstance().getProcess().getId(), event .getRuleFlowProcessInstance().getProcess().getName())); } public void afterRuleFlowNodeTriggered(RuleFlowNodeTriggeredEvent event, WorkingMemory workingMemory) { filterLogEvent(new RuleFlowNodeLogEvent(LogEvent.AFTER_RULEFLOW_NODE_TRIGGERED, event.getRuleFlowNodeInstance().getId() + "", event.getRuleFlowNodeInstance().getNode().getName(), event.getRuleFlowProcessInstance().getProcess().getId(), event .getRuleFlowProcessInstance().getProcess().getName())); } public void afterPackageAdded(AfterPackageAddedEvent event) { filterLogEvent( new RuleBaseLogEvent( LogEvent.AFTER_PACKAGE_ADDED, event.getPackage().getName(), null ) ); } public void afterPackageRemoved(AfterPackageRemovedEvent event) { filterLogEvent( new RuleBaseLogEvent( LogEvent.AFTER_PACKAGE_REMOVED, event.getPackage().getName(), null ) ); } public void afterRuleAdded(AfterRuleAddedEvent event) { filterLogEvent( new RuleBaseLogEvent( LogEvent.AFTER_RULE_ADDED, event.getPackage().getName(), event.getRule().getName() ) ); } public void afterRuleRemoved(AfterRuleRemovedEvent event) { filterLogEvent( new RuleBaseLogEvent( LogEvent.AFTER_RULE_REMOVED, event.getPackage().getName(), event.getRule().getName() ) ); } public void beforePackageAdded(BeforePackageAddedEvent event) { filterLogEvent( new RuleBaseLogEvent( LogEvent.BEFORE_PACKAGE_ADDED, event.getPackage().getName(), null ) ); } public void beforePackageRemoved(BeforePackageRemovedEvent event) { filterLogEvent( new RuleBaseLogEvent( LogEvent.BEFORE_PACKAGE_REMOVED, event.getPackage().getName(), null ) ); } public void beforeRuleAdded(BeforeRuleAddedEvent event) { filterLogEvent( new RuleBaseLogEvent( LogEvent.BEFORE_RULE_ADDED, event.getPackage().getName(), event.getRule().getName() ) ); } public void beforeRuleRemoved(BeforeRuleRemovedEvent event) { filterLogEvent( new RuleBaseLogEvent( LogEvent.BEFORE_RULE_REMOVED, event.getPackage().getName(), event.getRule().getName() ) ); } public void afterFunctionRemoved(AfterFunctionRemovedEvent event) { // TODO Auto-generated method stub } public void afterRuleBaseLocked(AfterRuleBaseLockedEvent event) { // TODO Auto-generated method stub } public void afterRuleBaseUnlocked(AfterRuleBaseUnlockedEvent event) { // TODO Auto-generated method stub } public void beforeFunctionRemoved(BeforeFunctionRemovedEvent event) { // TODO Auto-generated method stub } public void beforeRuleBaseLocked(BeforeRuleBaseLockedEvent event) { // TODO Auto-generated method stub } public void beforeRuleBaseUnlocked(BeforeRuleBaseUnlockedEvent event) { // TODO Auto-generated method stub } }
true
true
private String extractDeclarations(final Activation activation, final WorkingMemory workingMemory) { final StringBuffer result = new StringBuffer(); final Tuple tuple = activation.getTuple(); final Map declarations = activation.getSubRule().getOuterDeclarations(); for ( Iterator it = declarations.values().iterator(); it.hasNext(); ) { final Declaration declaration = (Declaration) it.next(); final FactHandle handle = tuple.get( declaration ); if ( handle instanceof InternalFactHandle ) { final InternalFactHandle handleImpl = (InternalFactHandle) handle; if ( handleImpl.getId() == -1 ) { // This handle is now invalid, probably due to an fact retraction continue; } final Object value = declaration.getValue( (InternalWorkingMemory) workingMemory, workingMemory.getObject( handle ) ); result.append( declaration.getIdentifier() ); result.append( "=" ); if ( value == null ) { // this should never occur result.append( "null" ); } else { result.append( value ); result.append( "(" ); result.append( handleImpl.getId() ); result.append( ")" ); } } if ( it.hasNext() ) { result.append( "; " ); } } return result.toString(); }
private String extractDeclarations(final Activation activation, final WorkingMemory workingMemory) { final StringBuffer result = new StringBuffer(); final Tuple tuple = activation.getTuple(); final Map declarations = activation.getSubRule().getOuterDeclarations(); for ( Iterator it = declarations.values().iterator(); it.hasNext(); ) { final Declaration declaration = (Declaration) it.next(); final FactHandle handle = tuple.get( declaration ); if ( handle instanceof InternalFactHandle ) { final InternalFactHandle handleImpl = (InternalFactHandle) handle; if ( handleImpl.getId() == -1 ) { // This handle is now invalid, probably due to an fact retraction continue; } final Object value = declaration.getValue( (InternalWorkingMemory) workingMemory, handleImpl.getObject() ); result.append( declaration.getIdentifier() ); result.append( "=" ); if ( value == null ) { // this should never occur result.append( "null" ); } else { result.append( value ); result.append( "(" ); result.append( handleImpl.getId() ); result.append( ")" ); } } if ( it.hasNext() ) { result.append( "; " ); } } return result.toString(); }
diff --git a/cq-package-plugin/src/test/java/com/sixdimensions/wcm/cq/pack/PackageManagerServiceImplTest.java b/cq-package-plugin/src/test/java/com/sixdimensions/wcm/cq/pack/PackageManagerServiceImplTest.java index 71995e1..26f4a4d 100644 --- a/cq-package-plugin/src/test/java/com/sixdimensions/wcm/cq/pack/PackageManagerServiceImplTest.java +++ b/cq-package-plugin/src/test/java/com/sixdimensions/wcm/cq/pack/PackageManagerServiceImplTest.java @@ -1,67 +1,67 @@ package com.sixdimensions.wcm.cq.pack; import java.io.File; import java.net.URLDecoder; import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugin.logging.SystemStreamLog; import org.junit.Before; import org.junit.Test; import com.sixdimensions.wcm.cq.pack.service.PackageManagerConfig; import com.sixdimensions.wcm.cq.pack.service.PackageManagerService; public class PackageManagerServiceImplTest { private PackageManagerService packageManagerSvc; private Log log = new SystemStreamLog(); @Before public void init(){ log.info("Init"); PackageManagerConfig config = new PackageManagerConfig(); config.setHost("http://poc.crownpartners.com"); config.setPort("4502"); config.setUseLegacy(false); config.setUser("admin"); config.setPassword("admin"); - config.setErrorOnFailure(true); + config.setErrorOnFailure(false); config.setLog(log); packageManagerSvc = PackageManagerService.Factory.getPackageMgr(config); log.info("Init Complete"); } @Test public void testUpload() throws Exception{ log.info("Testing Upload"); File f = new File(URLDecoder.decode(getClass().getClassLoader() .getResource("test-1.0.0.zip").getPath(), "UTF-8")); packageManagerSvc.upload("test/test-1.0.0.zip",f); log.info("Test Successful"); } @Test public void testDryRun() throws Exception{ log.info("Testing Dry Run"); packageManagerSvc.dryRun("test/test-1.0.0.zip"); log.info("Test Successful"); } @Test public void testInstall() throws Exception{ log.info("Testing Install"); packageManagerSvc.install("test/test-1.0.0.zip"); log.info("Test Successful"); } @Test public void testDelete() throws Exception{ log.info("Testing Delete"); packageManagerSvc.delete("test/test-1.0.0.zip"); log.info("Test Successful"); } }
true
true
public void init(){ log.info("Init"); PackageManagerConfig config = new PackageManagerConfig(); config.setHost("http://poc.crownpartners.com"); config.setPort("4502"); config.setUseLegacy(false); config.setUser("admin"); config.setPassword("admin"); config.setErrorOnFailure(true); config.setLog(log); packageManagerSvc = PackageManagerService.Factory.getPackageMgr(config); log.info("Init Complete"); }
public void init(){ log.info("Init"); PackageManagerConfig config = new PackageManagerConfig(); config.setHost("http://poc.crownpartners.com"); config.setPort("4502"); config.setUseLegacy(false); config.setUser("admin"); config.setPassword("admin"); config.setErrorOnFailure(false); config.setLog(log); packageManagerSvc = PackageManagerService.Factory.getPackageMgr(config); log.info("Init Complete"); }
diff --git a/opentripplanner-updater/src/main/java/org/opentripplanner/updater/UpdateHandler.java b/opentripplanner-updater/src/main/java/org/opentripplanner/updater/UpdateHandler.java index 228422a2a..294696d3c 100644 --- a/opentripplanner-updater/src/main/java/org/opentripplanner/updater/UpdateHandler.java +++ b/opentripplanner-updater/src/main/java/org/opentripplanner/updater/UpdateHandler.java @@ -1,134 +1,134 @@ package org.opentripplanner.updater; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import org.onebusaway.gtfs.model.AgencyAndId; import org.opentripplanner.routing.core.Graph; import org.opentripplanner.routing.patch.Alert; import org.opentripplanner.routing.patch.AlertPatch; import org.opentripplanner.routing.patch.TimePeriod; import org.opentripplanner.routing.patch.TranslatedString; import org.opentripplanner.routing.services.GraphService; import org.opentripplanner.routing.services.PatchService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.transit.realtime.GtfsRealtime; import com.google.transit.realtime.GtfsRealtime.EntitySelector; import com.google.transit.realtime.GtfsRealtime.FeedEntity; import com.google.transit.realtime.GtfsRealtime.FeedMessage; import com.google.transit.realtime.GtfsRealtime.TimeRange; import com.google.transit.realtime.GtfsRealtime.TranslatedString.Translation; public class UpdateHandler { private static final Logger log = LoggerFactory.getLogger(UpdateHandler.class); private FeedMessage message; private String defaultAgencyId; private Set<String> patchIds = new HashSet<String>(); private Graph graph; private GraphService graphService; private PatchService patchService; public UpdateHandler(FeedMessage message) { this.message = message; } public void update() { graph = graphService.getGraph(); for (FeedEntity entity : message.getEntityList()) { if (!entity.hasAlert()) { continue; } GtfsRealtime.Alert alert = entity.getAlert(); String id = entity.getId(); handleAlert(id, alert); } patchService.expireAllExcept(patchIds); } private void handleAlert(String id, GtfsRealtime.Alert alert) { Alert alertText = new Alert(); alertText.alertDescriptionText = deBuffer(alert.getDescriptionText()); alertText.alertHeaderText = deBuffer(alert.getHeaderText()); alertText.alertUrl = deBuffer(alert.getUrl()); ArrayList<TimePeriod> periods = new ArrayList<TimePeriod>(); for (TimeRange activePeriod : alert.getActivePeriodList()) { final long start = activePeriod.hasStart() ? activePeriod.getStart() : 0; final long end = activePeriod.hasEnd() ? activePeriod.getEnd() : Long.MAX_VALUE; periods.add(new TimePeriod(start, end)); } for (EntitySelector informed : alert.getInformedEntityList()) { String routeId = null; if (informed.hasRouteId()) { routeId = informed.getRouteId(); } String stopId = null; if (informed.hasStopId()) { stopId = informed.getStopId(); } String agencyId = informed.getAgencyId(); if (informed.hasAgencyId()) { agencyId = informed.getAgencyId().intern(); } else { agencyId = defaultAgencyId; } if (agencyId == null) { log.error("Empty agency id (and no default set) in feed; other ids are route " + routeId + " and stop " + stopId); continue; } agencyId = agencyId.intern(); AlertPatch patch = new AlertPatch(); if (routeId != null) { patch.setRoute(new AgencyAndId(agencyId, routeId)); } if (stopId != null) { patch.setStop(new AgencyAndId(agencyId, stopId)); } patch.setTimePeriods(periods); patch.setId(id); patch.setAlert(alertText); - patch.apply(graph); + patchService.apply(patch); patchIds.add(id); } } /** * convert a protobuf TranslatedString to a OTP TranslatedString * * @return */ private TranslatedString deBuffer(GtfsRealtime.TranslatedString buffered) { TranslatedString result = new TranslatedString(); for (Translation translation : buffered.getTranslationList()) { String language = translation.getLanguage(); String string = translation.getText(); result.addTranslation(language, string); } return result; } public void setDefaultAgencyId(String defaultAgencyId) { this.defaultAgencyId = defaultAgencyId.intern(); } public void setGraphService(GraphService graphService) { this.graphService = graphService; } public void setPatchService(PatchService patchService) { this.patchService = patchService; } }
true
true
private void handleAlert(String id, GtfsRealtime.Alert alert) { Alert alertText = new Alert(); alertText.alertDescriptionText = deBuffer(alert.getDescriptionText()); alertText.alertHeaderText = deBuffer(alert.getHeaderText()); alertText.alertUrl = deBuffer(alert.getUrl()); ArrayList<TimePeriod> periods = new ArrayList<TimePeriod>(); for (TimeRange activePeriod : alert.getActivePeriodList()) { final long start = activePeriod.hasStart() ? activePeriod.getStart() : 0; final long end = activePeriod.hasEnd() ? activePeriod.getEnd() : Long.MAX_VALUE; periods.add(new TimePeriod(start, end)); } for (EntitySelector informed : alert.getInformedEntityList()) { String routeId = null; if (informed.hasRouteId()) { routeId = informed.getRouteId(); } String stopId = null; if (informed.hasStopId()) { stopId = informed.getStopId(); } String agencyId = informed.getAgencyId(); if (informed.hasAgencyId()) { agencyId = informed.getAgencyId().intern(); } else { agencyId = defaultAgencyId; } if (agencyId == null) { log.error("Empty agency id (and no default set) in feed; other ids are route " + routeId + " and stop " + stopId); continue; } agencyId = agencyId.intern(); AlertPatch patch = new AlertPatch(); if (routeId != null) { patch.setRoute(new AgencyAndId(agencyId, routeId)); } if (stopId != null) { patch.setStop(new AgencyAndId(agencyId, stopId)); } patch.setTimePeriods(periods); patch.setId(id); patch.setAlert(alertText); patch.apply(graph); patchIds.add(id); } }
private void handleAlert(String id, GtfsRealtime.Alert alert) { Alert alertText = new Alert(); alertText.alertDescriptionText = deBuffer(alert.getDescriptionText()); alertText.alertHeaderText = deBuffer(alert.getHeaderText()); alertText.alertUrl = deBuffer(alert.getUrl()); ArrayList<TimePeriod> periods = new ArrayList<TimePeriod>(); for (TimeRange activePeriod : alert.getActivePeriodList()) { final long start = activePeriod.hasStart() ? activePeriod.getStart() : 0; final long end = activePeriod.hasEnd() ? activePeriod.getEnd() : Long.MAX_VALUE; periods.add(new TimePeriod(start, end)); } for (EntitySelector informed : alert.getInformedEntityList()) { String routeId = null; if (informed.hasRouteId()) { routeId = informed.getRouteId(); } String stopId = null; if (informed.hasStopId()) { stopId = informed.getStopId(); } String agencyId = informed.getAgencyId(); if (informed.hasAgencyId()) { agencyId = informed.getAgencyId().intern(); } else { agencyId = defaultAgencyId; } if (agencyId == null) { log.error("Empty agency id (and no default set) in feed; other ids are route " + routeId + " and stop " + stopId); continue; } agencyId = agencyId.intern(); AlertPatch patch = new AlertPatch(); if (routeId != null) { patch.setRoute(new AgencyAndId(agencyId, routeId)); } if (stopId != null) { patch.setStop(new AgencyAndId(agencyId, stopId)); } patch.setTimePeriods(periods); patch.setId(id); patch.setAlert(alertText); patchService.apply(patch); patchIds.add(id); } }
diff --git a/dependency-shot-aop/src/main/java/cx/ath/mancel01/dependencyshot/aop/ProxyHelper.java b/dependency-shot-aop/src/main/java/cx/ath/mancel01/dependencyshot/aop/ProxyHelper.java index ef41ee5..796c1c8 100644 --- a/dependency-shot-aop/src/main/java/cx/ath/mancel01/dependencyshot/aop/ProxyHelper.java +++ b/dependency-shot-aop/src/main/java/cx/ath/mancel01/dependencyshot/aop/ProxyHelper.java @@ -1,51 +1,50 @@ /* * Copyright 2010 mathieuancelin. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * under the License. */ package cx.ath.mancel01.dependencyshot.aop; import javassist.util.proxy.ProxyFactory; import javassist.util.proxy.ProxyObject; /** * Helper for proxy creation. * * @author Mathieu ANCELIN */ public class ProxyHelper { public static <T> T createProxy( Object bean, MethodInvocationHandler handler) { ProxyFactory fact = new ProxyFactory(); Class<T> from = handler.getFrom(); Class<? extends T> to = handler.getTo(); if (from.isInterface()) { fact.setInterfaces(new Class[] {from}); } fact.setSuperclass(to); fact.setFilter(handler); Class newBeanClass = fact.createClass(); T scopedObject = null; try { scopedObject = (T) newBeanClass.cast(newBeanClass.newInstance()); } catch (Exception ex) { - ex.printStackTrace(); throw new IllegalStateException("Unable to create proxy for object " + from.getSimpleName(), ex); } ((ProxyObject) scopedObject).setHandler(handler); return scopedObject; } }
true
true
public static <T> T createProxy( Object bean, MethodInvocationHandler handler) { ProxyFactory fact = new ProxyFactory(); Class<T> from = handler.getFrom(); Class<? extends T> to = handler.getTo(); if (from.isInterface()) { fact.setInterfaces(new Class[] {from}); } fact.setSuperclass(to); fact.setFilter(handler); Class newBeanClass = fact.createClass(); T scopedObject = null; try { scopedObject = (T) newBeanClass.cast(newBeanClass.newInstance()); } catch (Exception ex) { ex.printStackTrace(); throw new IllegalStateException("Unable to create proxy for object " + from.getSimpleName(), ex); } ((ProxyObject) scopedObject).setHandler(handler); return scopedObject; }
public static <T> T createProxy( Object bean, MethodInvocationHandler handler) { ProxyFactory fact = new ProxyFactory(); Class<T> from = handler.getFrom(); Class<? extends T> to = handler.getTo(); if (from.isInterface()) { fact.setInterfaces(new Class[] {from}); } fact.setSuperclass(to); fact.setFilter(handler); Class newBeanClass = fact.createClass(); T scopedObject = null; try { scopedObject = (T) newBeanClass.cast(newBeanClass.newInstance()); } catch (Exception ex) { throw new IllegalStateException("Unable to create proxy for object " + from.getSimpleName(), ex); } ((ProxyObject) scopedObject).setHandler(handler); return scopedObject; }
diff --git a/bundles/org.eclipse.orion.server.servlets/src/org/eclipse/orion/internal/server/servlets/workspace/ProjectParentDecorator.java b/bundles/org.eclipse.orion.server.servlets/src/org/eclipse/orion/internal/server/servlets/workspace/ProjectParentDecorator.java index 17429165..b3715310 100644 --- a/bundles/org.eclipse.orion.server.servlets/src/org/eclipse/orion/internal/server/servlets/workspace/ProjectParentDecorator.java +++ b/bundles/org.eclipse.orion.server.servlets/src/org/eclipse/orion/internal/server/servlets/workspace/ProjectParentDecorator.java @@ -1,107 +1,107 @@ /******************************************************************************* * Copyright (c) 2010, 2011 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.orion.internal.server.servlets.workspace; import java.net.URI; import java.net.URISyntaxException; import javax.servlet.http.HttpServletRequest; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.orion.internal.server.core.IWebResourceDecorator; import org.eclipse.orion.internal.server.servlets.ProtocolConstants; import org.eclipse.orion.server.core.LogHelper; import org.json.*; /** * Augments a file resource with information about parents up to the level * of the project. */ public class ProjectParentDecorator implements IWebResourceDecorator { public ProjectParentDecorator() { super(); } /*(non-Javadoc) * @see org.eclipse.orion.internal.server.core.IWebResourceDecorator#addAtributesFor(java.net.URI, org.json.JSONObject) */ public void addAtributesFor(HttpServletRequest request, URI resource, JSONObject representation) { IPath resourcePath = new Path(resource.getPath()); if (!"/file".equals(request.getServletPath())) //$NON-NLS-1$ return; try { if (resourcePath.hasTrailingSeparator() && !representation.getBoolean(ProtocolConstants.KEY_DIRECTORY)) { resourcePath = resourcePath.append(representation.getString(ProtocolConstants.KEY_NAME)); } addParents(resource, representation, resourcePath); //set the name of the project file to be the project name if (resourcePath.segmentCount() == 3) { WebWorkspace workspace = WebWorkspace.fromId(resourcePath.segment(1)); WebProject project = workspace.getProjectByName(resourcePath.segment(2)); String projectName = project.getName(); if (projectName != null) representation.put(ProtocolConstants.KEY_NAME, projectName); } } catch (JSONException e) { //Shouldn't happen because names and locations should be valid JSON. //Since we are just decorating some else's response we shouldn't cause a failure LogHelper.log(e); } } private void addParents(URI resource, JSONObject representation, IPath resourcePath) throws JSONException { //start at parent of current resource resourcePath = resourcePath.removeLastSegments(1).addTrailingSeparator(); JSONArray parents = new JSONArray(); //for all but the project we can just manipulate the path to get the name and location while (resourcePath.segmentCount() > 3) { try { URI uri = resource.resolve(new URI(null, resourcePath.toString(), null)); addParent(parents, resourcePath.lastSegment(), new URI(null, null, null, -1, uri.getPath(), uri.getQuery(), uri.getFragment())); } catch (URISyntaxException e) { //ignore this parent LogHelper.log(e); } resourcePath = resourcePath.removeLastSegments(1); } //add the project if (resourcePath.segmentCount() == 3) { WebWorkspace workspace = WebWorkspace.fromId(resourcePath.segment(1)); WebProject project = workspace.getProjectByName(resourcePath.segment(2)); - URI uri = resource.resolve(resourcePath.toString()); try { + URI uri = resource.resolve(new URI(null, resourcePath.toString(), null)); addParent(parents, project.getName(), new URI(null, null, null, -1, uri.getPath(), uri.getQuery(), uri.getFragment())); } catch (URISyntaxException e) { //ignore this project LogHelper.log(e); } } representation.put(ProtocolConstants.KEY_PARENTS, parents); } /** * Adds a parent resource representation to the parent array */ private void addParent(JSONArray parents, String name, URI location) throws JSONException { JSONObject parent = new JSONObject(); parent.put(ProtocolConstants.KEY_NAME, name); parent.put(ProtocolConstants.KEY_LOCATION, location); URI childLocation; try { childLocation = new URI(location.getScheme(), location.getUserInfo(), location.getHost(), location.getPort(), location.getPath(), "depth=1", location.getFragment()); //$NON-NLS-1$ } catch (URISyntaxException e) { throw new RuntimeException(e); } parent.put(ProtocolConstants.KEY_CHILDREN_LOCATION, childLocation); parents.put(parent); } }
false
true
private void addParents(URI resource, JSONObject representation, IPath resourcePath) throws JSONException { //start at parent of current resource resourcePath = resourcePath.removeLastSegments(1).addTrailingSeparator(); JSONArray parents = new JSONArray(); //for all but the project we can just manipulate the path to get the name and location while (resourcePath.segmentCount() > 3) { try { URI uri = resource.resolve(new URI(null, resourcePath.toString(), null)); addParent(parents, resourcePath.lastSegment(), new URI(null, null, null, -1, uri.getPath(), uri.getQuery(), uri.getFragment())); } catch (URISyntaxException e) { //ignore this parent LogHelper.log(e); } resourcePath = resourcePath.removeLastSegments(1); } //add the project if (resourcePath.segmentCount() == 3) { WebWorkspace workspace = WebWorkspace.fromId(resourcePath.segment(1)); WebProject project = workspace.getProjectByName(resourcePath.segment(2)); URI uri = resource.resolve(resourcePath.toString()); try { addParent(parents, project.getName(), new URI(null, null, null, -1, uri.getPath(), uri.getQuery(), uri.getFragment())); } catch (URISyntaxException e) { //ignore this project LogHelper.log(e); } } representation.put(ProtocolConstants.KEY_PARENTS, parents); }
private void addParents(URI resource, JSONObject representation, IPath resourcePath) throws JSONException { //start at parent of current resource resourcePath = resourcePath.removeLastSegments(1).addTrailingSeparator(); JSONArray parents = new JSONArray(); //for all but the project we can just manipulate the path to get the name and location while (resourcePath.segmentCount() > 3) { try { URI uri = resource.resolve(new URI(null, resourcePath.toString(), null)); addParent(parents, resourcePath.lastSegment(), new URI(null, null, null, -1, uri.getPath(), uri.getQuery(), uri.getFragment())); } catch (URISyntaxException e) { //ignore this parent LogHelper.log(e); } resourcePath = resourcePath.removeLastSegments(1); } //add the project if (resourcePath.segmentCount() == 3) { WebWorkspace workspace = WebWorkspace.fromId(resourcePath.segment(1)); WebProject project = workspace.getProjectByName(resourcePath.segment(2)); try { URI uri = resource.resolve(new URI(null, resourcePath.toString(), null)); addParent(parents, project.getName(), new URI(null, null, null, -1, uri.getPath(), uri.getQuery(), uri.getFragment())); } catch (URISyntaxException e) { //ignore this project LogHelper.log(e); } } representation.put(ProtocolConstants.KEY_PARENTS, parents); }
diff --git a/src/main/java/com/ning/http/util/AsyncHttpProviderUtils.java b/src/main/java/com/ning/http/util/AsyncHttpProviderUtils.java index c9e88506b..c0dcc5e83 100644 --- a/src/main/java/com/ning/http/util/AsyncHttpProviderUtils.java +++ b/src/main/java/com/ning/http/util/AsyncHttpProviderUtils.java @@ -1,494 +1,494 @@ /* * Copyright (c) 2010-2011 Sonatype, Inc. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package com.ning.http.util; import com.ning.http.client.AsyncHttpProvider; import com.ning.http.client.ByteArrayPart; import com.ning.http.client.Cookie; import com.ning.http.client.FilePart; import com.ning.http.client.FluentStringsMap; import com.ning.http.client.HttpResponseBodyPart; import com.ning.http.client.Part; import com.ning.http.client.StringPart; import com.ning.http.multipart.ByteArrayPartSource; import com.ning.http.multipart.MultipartRequestEntity; import com.ning.http.multipart.PartSource; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.List; import java.util.Locale; /** * {@link com.ning.http.client.AsyncHttpProvider} common utilities. * <p/> * The cookies's handling code is from the Netty framework. */ public class AsyncHttpProviderUtils { public final static String DEFAULT_CHARSET = "ISO-8859-1"; private final static String BODY_NOT_COMPUTED = "Response's body hasn't been computed by your AsyncHandler."; protected final static ThreadLocal<SimpleDateFormat[]> simpleDateFormat = new ThreadLocal<SimpleDateFormat[]>() { protected SimpleDateFormat[] initialValue() { return new SimpleDateFormat[] { new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy", Locale.US), //ASCTIME new SimpleDateFormat("EEEE, dd-MMM-yy HH:mm:ss zzz", Locale.US), //RFC1036 new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US), new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss z", Locale.US), new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US), new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss Z", Locale.US), new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US) // RFC1123 }; } }; public final static SimpleDateFormat[] get() { return simpleDateFormat.get(); } //space ' ' static final byte SP = 32; //tab ' ' static final byte HT = 9; /** * Carriage return */ static final byte CR = 13; /** * Equals '=' */ static final byte EQUALS = 61; /** * Line feed character */ static final byte LF = 10; /** * carriage return line feed */ static final byte[] CRLF = new byte[]{CR, LF}; /** * Colon ':' */ static final byte COLON = 58; /** * Semicolon ';' */ static final byte SEMICOLON = 59; /** * comma ',' */ static final byte COMMA = 44; static final byte DOUBLE_QUOTE = '"'; static final String PATH = "Path"; static final String EXPIRES = "Expires"; static final String MAX_AGE = "Max-Age"; static final String DOMAIN = "Domain"; static final String SECURE = "Secure"; static final String HTTPONLY = "HTTPOnly"; static final String COMMENT = "Comment"; static final String COMMENTURL = "CommentURL"; static final String DISCARD = "Discard"; static final String PORT = "Port"; static final String VERSION = "Version"; public final static URI createUri(String u) { URI uri = URI.create(u); final String scheme = uri.getScheme(); if (scheme == null || !scheme.equalsIgnoreCase("http") && !scheme.equalsIgnoreCase("https")) { throw new IllegalArgumentException("The URI scheme, of the URI " + u + ", must be equal (ignoring case) to 'http' or 'https'"); } String path = uri.getPath(); if (path == null) { throw new IllegalArgumentException("The URI path, of the URI " + uri + ", must be non-null"); } else if (path.length() > 0 && path.charAt(0) != '/') { throw new IllegalArgumentException("The URI path, of the URI " + uri + ". must start with a '/'"); } else if (path.length() == 0) { return URI.create(u + "/"); } return uri; } public final static String getBaseUrl(URI uri) { String url = uri.getScheme() + "://" + uri.getAuthority(); int port = uri.getPort(); if (port == -1) { port = getPort(uri); url += ":" + port; } return url; } public final static String getAuthority(URI uri) { String url = uri.getAuthority(); int port = uri.getPort(); if (port == -1) { port = getPort(uri); url += ":" + port; } return url; } public final static URI getRedirectUri(URI uri, String location) { URI newUri = uri.resolve(location); String scheme = newUri.getScheme(); if (scheme == null || !scheme.equalsIgnoreCase("http") && !scheme.equalsIgnoreCase("https")) { throw new IllegalArgumentException("The URI scheme, of the URI " + newUri + ", must be equal (ignoring case) to 'http' or 'https'"); } return newUri; } public final static int getPort(URI uri) { int port = uri.getPort(); if (port == -1) port = uri.getScheme().equals("http") ? 80 : 443; return port; } /** * This is quite ugly as our internal names are duplicated, but we build on top of HTTP Client implementation. * * @param params * @param methodParams * @return a MultipartRequestEntity. * @throws java.io.FileNotFoundException */ public final static MultipartRequestEntity createMultipartRequestEntity(List<Part> params, FluentStringsMap methodParams) throws FileNotFoundException { com.ning.http.multipart.Part[] parts = new com.ning.http.multipart.Part[params.size()]; int i = 0; for (Part part : params) { if (part instanceof com.ning.http.multipart.Part) { parts[i] = (com.ning.http.multipart.Part) part; } else if (part instanceof StringPart) { parts[i] = new com.ning.http.multipart.StringPart(part.getName(), ((StringPart) part).getValue(), "UTF-8"); } else if (part instanceof FilePart) { parts[i] = new com.ning.http.multipart.FilePart(part.getName(), ((FilePart) part).getFile(), ((FilePart) part).getMimeType(), ((FilePart) part).getCharSet()); } else if (part instanceof ByteArrayPart) { PartSource source = new ByteArrayPartSource(((ByteArrayPart) part).getFileName(), ((ByteArrayPart) part).getData()); parts[i] = new com.ning.http.multipart.FilePart(part.getName(), source, ((ByteArrayPart) part).getMimeType(), ((ByteArrayPart) part).getCharSet()); } else if (part == null) { throw new NullPointerException("Part cannot be null"); } else { throw new IllegalArgumentException(String.format("Unsupported part type for multipart parameter %s", part.getName())); } ++i; } return new MultipartRequestEntity(parts, methodParams); } public final static byte[] readFully(InputStream in, int[] lengthWrapper) throws IOException { // just in case available() returns bogus (or -1), allocate non-trivial chunk byte[] b = new byte[Math.max(512, in.available())]; int offset = 0; while (true) { int left = b.length - offset; int count = in.read(b, offset, left); if (count < 0) { // EOF break; } offset += count; if (count == left) { // full buffer, need to expand b = doubleUp(b); } } // wish Java had Tuple return type... lengthWrapper[0] = offset; return b; } private static byte[] doubleUp(byte[] b) { int len = b.length; byte[] b2 = new byte[len + len]; System.arraycopy(b, 0, b2, 0, len); return b2; } public static String encodeCookies(Collection<Cookie> cookies) { StringBuilder sb = new StringBuilder(); for (Cookie cookie : cookies) { if (cookie.getVersion() >= 1) { add(sb, '$' + VERSION, 1); } add(sb, cookie.getName(), cookie.getValue()); if (cookie.getPath() != null) { add(sb, '$' + PATH, cookie.getPath()); } if (cookie.getDomain() != null) { add(sb, '$' + DOMAIN, cookie.getDomain()); } if (cookie.getVersion() >= 1) { if (!cookie.getPorts().isEmpty()) { sb.append('$'); sb.append(PORT); sb.append((char) EQUALS); sb.append((char) DOUBLE_QUOTE); for (int port : cookie.getPorts()) { sb.append(port); sb.append((char) COMMA); } sb.setCharAt(sb.length() - 1, (char) DOUBLE_QUOTE); sb.append((char) SEMICOLON); } } } sb.setLength(sb.length() - 1); return sb.toString(); } private static void add(StringBuilder sb, String name, String val) { if (val == null) { addQuoted(sb, name, ""); return; } for (int i = 0; i < val.length(); i++) { char c = val.charAt(i); switch (c) { case '\t': case ' ': case '"': case '(': case ')': case ',': case '/': case ':': case ';': case '<': case '=': case '>': case '?': case '@': case '[': case '\\': case ']': case '{': case '}': addQuoted(sb, name, val); return; } } addUnquoted(sb, name, val); } private static void addUnquoted(StringBuilder sb, String name, String val) { sb.append(name); sb.append((char) EQUALS); sb.append(val); sb.append((char) SEMICOLON); } private static void addQuoted(StringBuilder sb, String name, String val) { if (val == null) { val = ""; } sb.append(name); sb.append((char) EQUALS); sb.append((char) DOUBLE_QUOTE); sb.append(val.replace("\\", "\\\\").replace("\"", "\\\"")); sb.append((char) DOUBLE_QUOTE); sb.append((char) SEMICOLON); } private static void add(StringBuilder sb, String name, int val) { sb.append(name); sb.append((char) EQUALS); sb.append(val); sb.append((char) SEMICOLON); } public static String constructUserAgent(Class<? extends AsyncHttpProvider> httpProvider) { StringBuffer b = new StringBuffer("AsyncHttpClient/1.0") .append(" ") .append("(") .append(httpProvider.getSimpleName()) .append(" - ") .append(System.getProperty("os.name")) .append(" - ") .append(System.getProperty("os.version")) .append(" - ") .append(System.getProperty("java.version")) .append(" - ") .append(Runtime.getRuntime().availableProcessors()) .append(" core(s))"); return b.toString(); } public static String parseCharset(String contentType) { for (String part : contentType.split(";")) { if (part.trim().startsWith("charset=")) { String[] val = part.split("="); if (val[1] != null) { return val[1].trim(); } } } return null; } public static Cookie parseCookie(String value) { String[] fields = value.split(";\\s*"); String[] cookie = fields[0].split("="); String cookieName = cookie[0]; String cookieValue = cookie[1]; int maxAge = -1; String path = null; String domain = null; boolean secure = false; boolean maxAgeSet = false; boolean expiresSet = false; for (int j = 1; j < fields.length; j++) { if ("secure".equalsIgnoreCase(fields[j])) { secure = true; } else if (fields[j].indexOf('=') > 0) { String[] f = fields[j].split("="); // favor 'max-age' field over 'expires' if (!maxAgeSet && "max-age".equalsIgnoreCase(f[0])) { try { - maxAge = Integer.valueOf(f[1]); + maxAge = Integer.valueOf(removeQuote(f[1])); } catch (NumberFormatException e1) { // ignore failure to parse -> treat as session cookie // invalidate a previously parsed expires-field maxAge = -1; } maxAgeSet = true; } else if (!maxAgeSet && !expiresSet && "expires".equalsIgnoreCase(f[0])) { try { maxAge = convertExpireField(f[1]); } catch (Exception e) { // original behavior, is this correct at all (expires field with max-age semantics)? try { maxAge = Integer.valueOf(f[1]); } catch (NumberFormatException e1) { // ignore failure to parse -> treat as session cookie } } expiresSet = true; } else if ("domain".equalsIgnoreCase(f[0])) { domain = f[1]; } else if ("path".equalsIgnoreCase(f[0])) { path = f[1]; } } } if (maxAge < -1) { maxAge = -1; } return new Cookie(domain, cookieName, cookieValue, path, maxAge, secure); } private static int convertExpireField(String timestring) throws Exception { Exception exception = null; for (SimpleDateFormat sdf : simpleDateFormat.get()) { try { long expire = sdf.parse(removeQuote(timestring.trim())).getTime(); return (int) ((expire - System.currentTimeMillis()) / 1000); } catch (ParseException e) { exception = e; } catch (NumberFormatException e) { exception = e; } } throw exception; } private final static String removeQuote(String s) { if (s.startsWith("\"")) { s = s.substring(1); } if (s.endsWith("\"")) { s = s.substring(0,s.length() -1); } return s; } public static void checkBodyParts(int statusCode, Collection<HttpResponseBodyPart> bodyParts) { if (bodyParts == null || bodyParts.size() == 0) { // We allow empty body on 204 if (statusCode == 204) return; throw new IllegalStateException(BODY_NOT_COMPUTED); } } }
true
true
public static Cookie parseCookie(String value) { String[] fields = value.split(";\\s*"); String[] cookie = fields[0].split("="); String cookieName = cookie[0]; String cookieValue = cookie[1]; int maxAge = -1; String path = null; String domain = null; boolean secure = false; boolean maxAgeSet = false; boolean expiresSet = false; for (int j = 1; j < fields.length; j++) { if ("secure".equalsIgnoreCase(fields[j])) { secure = true; } else if (fields[j].indexOf('=') > 0) { String[] f = fields[j].split("="); // favor 'max-age' field over 'expires' if (!maxAgeSet && "max-age".equalsIgnoreCase(f[0])) { try { maxAge = Integer.valueOf(f[1]); } catch (NumberFormatException e1) { // ignore failure to parse -> treat as session cookie // invalidate a previously parsed expires-field maxAge = -1; } maxAgeSet = true; } else if (!maxAgeSet && !expiresSet && "expires".equalsIgnoreCase(f[0])) { try { maxAge = convertExpireField(f[1]); } catch (Exception e) { // original behavior, is this correct at all (expires field with max-age semantics)? try { maxAge = Integer.valueOf(f[1]); } catch (NumberFormatException e1) { // ignore failure to parse -> treat as session cookie } } expiresSet = true; } else if ("domain".equalsIgnoreCase(f[0])) { domain = f[1]; } else if ("path".equalsIgnoreCase(f[0])) { path = f[1]; } } } if (maxAge < -1) { maxAge = -1; } return new Cookie(domain, cookieName, cookieValue, path, maxAge, secure); }
public static Cookie parseCookie(String value) { String[] fields = value.split(";\\s*"); String[] cookie = fields[0].split("="); String cookieName = cookie[0]; String cookieValue = cookie[1]; int maxAge = -1; String path = null; String domain = null; boolean secure = false; boolean maxAgeSet = false; boolean expiresSet = false; for (int j = 1; j < fields.length; j++) { if ("secure".equalsIgnoreCase(fields[j])) { secure = true; } else if (fields[j].indexOf('=') > 0) { String[] f = fields[j].split("="); // favor 'max-age' field over 'expires' if (!maxAgeSet && "max-age".equalsIgnoreCase(f[0])) { try { maxAge = Integer.valueOf(removeQuote(f[1])); } catch (NumberFormatException e1) { // ignore failure to parse -> treat as session cookie // invalidate a previously parsed expires-field maxAge = -1; } maxAgeSet = true; } else if (!maxAgeSet && !expiresSet && "expires".equalsIgnoreCase(f[0])) { try { maxAge = convertExpireField(f[1]); } catch (Exception e) { // original behavior, is this correct at all (expires field with max-age semantics)? try { maxAge = Integer.valueOf(f[1]); } catch (NumberFormatException e1) { // ignore failure to parse -> treat as session cookie } } expiresSet = true; } else if ("domain".equalsIgnoreCase(f[0])) { domain = f[1]; } else if ("path".equalsIgnoreCase(f[0])) { path = f[1]; } } } if (maxAge < -1) { maxAge = -1; } return new Cookie(domain, cookieName, cookieValue, path, maxAge, secure); }
diff --git a/main/src/org/gameflow/utils/ImageRef.java b/main/src/org/gameflow/utils/ImageRef.java index c74f357..594a883 100644 --- a/main/src/org/gameflow/utils/ImageRef.java +++ b/main/src/org/gameflow/utils/ImageRef.java @@ -1,161 +1,163 @@ package org.gameflow.utils; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureAtlas; /** * Caches the image region with a specific name, as well as the size and other parameters on how to render it. */ public class ImageRef { public static final int NO_INDEX = -1; private String imageName = null; private int imageIndex = NO_INDEX; private double scaleX = 1; private double scaleY = 1; private double angleTurns = 0; private double turnPointX = 0.5; private double turnPointY = 0.5; private boolean mirrorX = false; private boolean mirrorY = false; private transient TextureAtlas.AtlasRegion image = null; public ImageRef(String imageName) { this.imageName = imageName; } public ImageRef(String imageName, int imageIndex) { this.imageName = imageName; this.imageIndex = imageIndex; } public ImageRef(String imageName, int imageIndex, double scaleX, double scaleY) { this.imageName = imageName; this.imageIndex = imageIndex; this.scaleX = scaleX; this.scaleY = scaleY; } public ImageRef(String imageName, int imageIndex, double scaleX, double scaleY, double angleTurns) { this.imageName = imageName; this.imageIndex = imageIndex; this.scaleX = scaleX; this.scaleY = scaleY; this.angleTurns = angleTurns; } public ImageRef(String imageName, int imageIndex, double scaleX, double scaleY, double angleTurns, double turnPointX, double turnPointY) { this.imageName = imageName; this.imageIndex = imageIndex; this.scaleX = scaleX; this.scaleY = scaleY; this.angleTurns = angleTurns; this.turnPointX = turnPointX; this.turnPointY = turnPointY; } public String getImageName() { return imageName; } public void setImageName(String imageName) { this.imageName = imageName; image = null; } public void setImageIndex(int imageIndex) { this.imageIndex = imageIndex; image = null; } public void setImage(String imageName, int imageIndex) { this.imageName = imageName; this.imageIndex = imageIndex; image = null; } public void setScale(double scale) { this.scaleX = scale; this.scaleY = scale; } public double getScaleX() { return scaleX; } public void setScaleX(double scaleX) { this.scaleX = scaleX; } public double getScaleY() { return scaleY; } public void setScaleY(double scaleY) { this.scaleY = scaleY; } public double getAngleTurns() { return angleTurns; } public void setAngleTurns(double angleTurns) { this.angleTurns = angleTurns; } public boolean isMirrorX() { return mirrorX; } public void setMirrorX(boolean mirrorX) { this.mirrorX = mirrorX; } public boolean isMirrorY() { return mirrorY; } public void setMirrorY(boolean mirrorY) { this.mirrorY = mirrorY; } /** * The point around with the image should be rotated. * 0 = left / bottom edge, 1 = right upper edge. */ public void setTurnPoint(double turnPointX, double turnPointY) { this.turnPointX = turnPointX; this.turnPointY = turnPointY; } public double getTurnPointX() { return turnPointX; } public double getTurnPointY() { return turnPointY; } public void render(float x, float y, TextureAtlas atlas, SpriteBatch spriteBatch) { if (imageName != null) { if (image == null) image = atlas.findRegion(imageName, imageIndex); - float w = image.getRegionWidth(); - float h = image.getRegionHeight(); - float originY = (float) (h * turnPointY); - float originX = (float) (w * turnPointX); - spriteBatch.draw( - image.getTexture(), - x, y, - originX, originY, - w, h, - (float) scaleX, (float) scaleY, - MathTools.toDegrees(angleTurns * MathTools.Tau), - image.getRegionX(), image.getRegionY(), image.getRegionWidth(), image.getRegionHeight(), - isMirrorX(), isMirrorY()); + if (image != null) { + float w = image.getRegionWidth(); + float h = image.getRegionHeight(); + float originY = (float) (h * turnPointY); + float originX = (float) (w * turnPointX); + spriteBatch.draw( + image.getTexture(), + x, y, + originX, originY, + w, h, + (float) scaleX, (float) scaleY, + MathTools.toDegrees(angleTurns * MathTools.Tau), + image.getRegionX(), image.getRegionY(), image.getRegionWidth(), image.getRegionHeight(), + isMirrorX(), isMirrorY()); + } } } }
true
true
public void render(float x, float y, TextureAtlas atlas, SpriteBatch spriteBatch) { if (imageName != null) { if (image == null) image = atlas.findRegion(imageName, imageIndex); float w = image.getRegionWidth(); float h = image.getRegionHeight(); float originY = (float) (h * turnPointY); float originX = (float) (w * turnPointX); spriteBatch.draw( image.getTexture(), x, y, originX, originY, w, h, (float) scaleX, (float) scaleY, MathTools.toDegrees(angleTurns * MathTools.Tau), image.getRegionX(), image.getRegionY(), image.getRegionWidth(), image.getRegionHeight(), isMirrorX(), isMirrorY()); } }
public void render(float x, float y, TextureAtlas atlas, SpriteBatch spriteBatch) { if (imageName != null) { if (image == null) image = atlas.findRegion(imageName, imageIndex); if (image != null) { float w = image.getRegionWidth(); float h = image.getRegionHeight(); float originY = (float) (h * turnPointY); float originX = (float) (w * turnPointX); spriteBatch.draw( image.getTexture(), x, y, originX, originY, w, h, (float) scaleX, (float) scaleY, MathTools.toDegrees(angleTurns * MathTools.Tau), image.getRegionX(), image.getRegionY(), image.getRegionWidth(), image.getRegionHeight(), isMirrorX(), isMirrorY()); } } }
diff --git a/dspace-api/src/main/java/org/dspace/app/statistics/LogAnalyser.java b/dspace-api/src/main/java/org/dspace/app/statistics/LogAnalyser.java index 9a2bc5ab2..03f750834 100644 --- a/dspace-api/src/main/java/org/dspace/app/statistics/LogAnalyser.java +++ b/dspace-api/src/main/java/org/dspace/app/statistics/LogAnalyser.java @@ -1,1344 +1,1344 @@ /* * LogAnalyser.java * * Version: $Revision$ * * Date: $Date$ * * Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts * Institute of Technology. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of the Hewlett-Packard Company nor the name of the * Massachusetts Institute of Technology nor the names of their * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package org.dspace.app.statistics; import org.dspace.app.statistics.LogLine; import org.dspace.core.ConfigurationManager; import org.dspace.core.Context; import org.dspace.storage.rdbms.DatabaseManager; import org.dspace.storage.rdbms.TableRow; import java.sql.SQLException; import java.lang.Long; import java.lang.StringBuffer; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; /** * This class performs all the actual analysis of a given set of DSpace log * files. Most input can be configured; use the -help flag for a full list * of usage information. * * The output of this file is plain text and forms an "aggregation" file which * can then be used for display purposes using the related ReportGenerator * class. * * @author Richard Jones */ public class LogAnalyser { // set up our class globals // FIXME: there are so many of these perhaps they should exist in a static // object of their own ///////////////// // aggregators ///////////////// /** aggregator for all actions performed in the system */ private static Map actionAggregator; /** aggregator for all searches performed */ private static Map searchAggregator; /** aggregator for user logins */ private static Map userAggregator; /** aggregator for item views */ private static Map itemAggregator; /** aggregator for current archive state statistics */ private static Map archiveStats; /** warning counter */ private static int warnCount = 0; /** log line counter */ private static int lineCount = 0; ////////////////// // config data ////////////////// /** list of actions to be included in the general summary */ private static List generalSummary; /** list of words not to be aggregated */ private static List excludeWords; /** list of search types to be ignored, such as "author:" */ private static List excludeTypes; /** list of characters to be excluded */ private static List excludeChars; /** list of item types to be reported on in the current state */ private static List itemTypes; /** bottom limit to output for search word analysis */ private static int searchFloor; /** bottom limit to output for item view analysis */ private static int itemFloor; /** number of items from most popular to be looked up in the database */ private static int itemLookup; /** mode to use for user email display */ private static String userEmail; /** URL of the service being analysed */ private static String url; /** Name of the service being analysed */ private static String name; /** Name of the service being analysed */ private static String hostName; /** the average number of views per item */ private static int views = 0; /////////////////////// // regular expressions /////////////////////// /** Exclude characters regular expression pattern */ private static Pattern excludeCharRX = null; /** handle indicator string regular expression pattern */ private static Pattern handleRX = null; /** item id indicator string regular expression pattern */ private static Pattern itemRX = null; /** query string indicator regular expression pattern */ private static Pattern queryRX = null; /** collection indicator regular expression pattern */ private static Pattern collectionRX = null; /** community indicator regular expression pattern */ private static Pattern communityRX = null; /** results indicator regular expression pattern */ private static Pattern resultsRX = null; /** single character regular expression pattern */ private static Pattern singleRX = null; /** a pattern to match a valid version 1.3 log file line */ private static Pattern valid13 = null; /** a pattern to match a valid version 1.4 log file line */ private static Pattern valid14 = null; /** pattern to match valid log file names */ private static Pattern logRegex = null; /** pattern to match commented out lines from the config file */ private static Pattern comment = Pattern.compile("^#"); /** pattern to match genuine lines from the config file */ private static Pattern real = Pattern.compile("^(.+)=(.+)"); /** pattern to match all search types */ private static Pattern typeRX = null; /** pattern to match all search types */ private static Pattern wordRX = null; ////////////////////////// // Miscellaneous variables ////////////////////////// /** process timing clock */ private static Calendar startTime = null; ///////////////////////// // command line options //////////////////////// /** the log directory to be analysed */ private static String logDir = ConfigurationManager.getProperty("dspace.dir") + File.separator + "log"; /** the regex to describe the file name format */ private static String fileTemplate = "dspace\\.log.*"; /** the config file from which to configure the analyser */ private static String configFile = ConfigurationManager.getProperty("dspace.dir") + File.separator + "config" + File.separator + "dstat.cfg"; /** the output file to which to write aggregation data */ private static String outFile = ConfigurationManager.getProperty("dspace.dir") + File.separator + "log" + File.separator + "dstat.dat"; /** the starting date of the report */ private static Date startDate = null; /** the end date of the report */ private static Date endDate = null; /** the starting date of the report as obtained from the log files */ private static Date logStartDate = null; /** the end date of the report as obtained from the log files */ private static Date logEndDate = null; /** are we looking stuff up in the database */ private static boolean lookUp = false; /** * main method to be run from command line. See usage information for * details as to how to use the command line flags (-help) */ public static void main(String [] argv) throws Exception, SQLException { // first, start the processing clock startTime = new GregorianCalendar(); // create context as super user Context context = new Context(); context.setIgnoreAuthorization(true); // set up our command line variables String myLogDir = null; String myFileTemplate = null; String myConfigFile = null; String myOutFile = null; Date myStartDate = null; Date myEndDate = null; boolean myLookUp = false; // read in our command line options for (int i = 0; i < argv.length; i++) { if (argv[i].equals("-log")) { myLogDir = argv[i+1]; } if (argv[i].equals("-file")) { myFileTemplate = argv[i+1]; } if (argv[i].equals("-cfg")) { myConfigFile = argv[i+1]; } if (argv[i].equals("-out")) { myOutFile = argv[i+1]; } if (argv[i].equals("-help")) { LogAnalyser.usage(); System.exit(0); } if (argv[i].equals("-start")) { myStartDate = parseDate(argv[i+1]); } if (argv[i].equals("-end")) { myEndDate = parseDate(argv[i+1]); } if (argv[i].equals("-lookup")) { myLookUp = true; } } // now call the method which actually processes the logs processLogs(context, myLogDir, myFileTemplate, myConfigFile, myOutFile, myStartDate, myEndDate, myLookUp); } /** * using the pre-configuration information passed here, analyse the logs * and produce the aggregation file * * @param context the DSpace context object this occurs under * @param myLogDir the passed log directory. Uses default if null * @param myFileTemplate the passed file name regex. Uses default if null * @param myConfigFile the DStat config file. Uses default if null * @param myOutFile the file to which to output aggregation data. Uses default if null * @param myStartDate the desired start of the analysis. Starts from the beginning otherwise * @param myEndDate the desired end of the analysis. Goes to the end otherwise * @param myLookUp force a lookup of the database */ public static void processLogs(Context context, String myLogDir, String myFileTemplate, String myConfigFile, String myOutFile, Date myStartDate, Date myEndDate, boolean myLookUp) throws IOException, SQLException { // FIXME: perhaps we should have all parameters and aggregators put // together in a single aggregating object // if the timer has not yet been started, then start it startTime = new GregorianCalendar(); //instantiate aggregators actionAggregator = new HashMap(); searchAggregator = new HashMap(); userAggregator = new HashMap(); itemAggregator = new HashMap(); archiveStats = new HashMap(); //instantiate lists generalSummary = new ArrayList(); excludeWords = new ArrayList(); excludeTypes = new ArrayList(); excludeChars = new ArrayList(); itemTypes = new ArrayList(); // set the parameters for this analysis setParameters(myLogDir, myFileTemplate, myConfigFile, myOutFile, myStartDate, myEndDate, myLookUp); // pre prepare our standard file readers and buffered readers FileReader fr = null; BufferedReader br = null; // read in the config information, throwing an error if we fail to open // the given config file readConfig(configFile); // assemble the regular expressions for later use (requires the file // template to build the regex to match it setRegex(fileTemplate); // get the log files File[] logFiles = getLogFiles(logDir); // standard loop counter int i = 0; // for every log file do analysis // FIXME: it is easy to implement not processing log files after the // dates exceed the end boundary, but is there an easy way to do it // for the start of the file? Note that we can assume that the contents // of the log file are sequential, but can we assume the files are // provided in a data sequence? for (i = 0; i < logFiles.length; i++) { // check to see if this file is a log file agains the global regex Matcher matchRegex = logRegex.matcher(logFiles[i].getName()); if (matchRegex.matches()) { // if it is a log file, open it up and lets have a look at the // contents. try { fr = new FileReader(logFiles[i].toString()); br = new BufferedReader(fr); } catch (IOException e) { System.out.println("Failed to read log file " + logFiles[i].toString()); System.exit(0); } // for each line in the file do the analysis // FIXME: perhaps each section needs to be dolled out to an // analysing class to allow pluggability of other methods of // analysis, and ease of code reading too - Pending further thought String line = null; while ((line = br.readLine()) != null) { // get the log line object LogLine logLine = getLogLine(line); // if there are line segments get on with the analysis if (logLine != null) { // first find out if we are constraining by date and // if so apply the restrictions if (logLine.beforeDate(startDate)) { continue; } if (logLine.afterDate(endDate)) { break; } // count the number of lines parsed lineCount++; // if we are not constrained by date, register the date // as the start/end date if it is the earliest/latest so far // FIXME: this should probably have a method of its own if (startDate == null) { if (logStartDate != null) { if (logLine.beforeDate(logStartDate)) { logStartDate = logLine.getDate(); } } else { logStartDate = logLine.getDate(); } } if (endDate == null) { if (logEndDate != null) { if (logLine.afterDate(logEndDate)) { logEndDate = logLine.getDate(); } } else { logEndDate = logLine.getDate(); } } // count the warnings if (logLine.isLevel("WARN")) { // FIXME: really, this ought to be some kind of level // aggregator warnCount++; } // is the action a search? if (logLine.isAction("search")) { // get back all the valid search words from the query String[] words = analyseQuery(logLine.getParams()); // for each search word add to the aggregator or // increment the aggregator's counter for (int j = 0; j < words.length; j++) { // FIXME: perhaps aggregators ought to be objects // themselves searchAggregator.put(words[j], increment(searchAggregator, words[j])); } } // is the action a login, and are we counting user logins? if (logLine.isAction("login") && !userEmail.equals("off")) { userAggregator.put(logLine.getUser(), increment(userAggregator, logLine.getUser())); } // is the action an item view? if (logLine.isAction("view_item")) { String handle = logLine.getParams(); // strip the handle string Matcher matchHandle = handleRX.matcher(handle); handle = matchHandle.replaceAll(""); // strip the item id string Matcher matchItem = itemRX.matcher(handle); handle = matchItem.replaceAll(""); handle.trim(); // either add the handle to the aggregator or // increment its counter itemAggregator.put(handle, increment(itemAggregator, handle)); } // log all the activity actionAggregator.put(logLine.getAction(), increment(actionAggregator, logLine.getAction())); } } // close the file reading buffers br.close(); fr.close(); } } // do we want to do a database lookup? Do so only if the start and // end dates are null or lookUp is true // FIXME: this is a kind of separate section. Would it be worth building // the summary string separately and then inserting it into the real // summary later? Especially if we make the archive analysis more complex archiveStats.put("All Items", getNumItems(context)); for (i = 0; i < itemTypes.size(); i++) { archiveStats.put(itemTypes.get(i), getNumItems(context, (String) itemTypes.get(i))); } // now do the host name and url lookup hostName = ConfigurationManager.getProperty("dspace.hostname").trim(); name = ConfigurationManager.getProperty("dspace.name").trim(); - url = ConfigurationManager.getProperties("dspace.url").trim(); + url = ConfigurationManager.getProperty("dspace.url").trim(); if ((url != null) && (!url.endsWith("/"))) { url = url + "/"; } // do the average views analysis if (((Integer) archiveStats.get("All Items")).intValue() != 0) { // FIXME: this is dependent on their being a query on the db, which // there might not always be if it becomes configurable Double avg = new Double( Math.ceil( ((Integer) actionAggregator.get("view_item")).intValue() / ((Integer) archiveStats.get("All Items")).intValue())); views = avg.intValue(); } // finally, write the output createOutput(); return; } /** * set the passed parameters up as global class variables. This has to * be done in a separate method because the API permits for running from * the command line with args or calling the processLogs method statically * from elsewhere * * @param myLogDir the log file directory to be analysed * @param myFileTemplate regex for log file names * @param myConfigFile config file to use for dstat * @param myOutFile file to write the aggregation into * @param myStartDate requested log reporting start date * @param myEndDate requested log reporting end date * @param myLookUp requested look up force flag */ public static void setParameters(String myLogDir, String myFileTemplate, String myConfigFile, String myOutFile, Date myStartDate, Date myEndDate, boolean myLookUp) { if (myLogDir != null) { logDir = myLogDir; } if (myFileTemplate != null) { fileTemplate = myFileTemplate; } if (myConfigFile != null) { configFile = myConfigFile; } if (myStartDate != null) { startDate = myStartDate; } if (myEndDate != null) { endDate = myEndDate; } if (myLogDir != null) { lookUp = myLookUp; } if (myOutFile != null) { outFile = myOutFile; } return; } /** * generate the analyser's output to the specified out file */ public static void createOutput() { // start a string buffer to hold the final output StringBuffer summary = new StringBuffer(); // define an iterator that will be used to go over the hashmap keys Iterator keys = null; // output the number of lines parsed summary.append("log_lines=" + Integer.toString(lineCount) + "\n"); // output the number of warnings encountered summary.append("warnings=" + Integer.toString(warnCount) + "\n"); // set the general summary config up in the aggregator file for (int i = 0; i < generalSummary.size(); i++) { summary.append("general_summary=" + generalSummary.get(i) + "\n"); } // output the host name summary.append("server_name=" + hostName + "\n"); // output the service name summary.append("service_name=" + name + "\n"); // output the date information if necessary SimpleDateFormat sdf = new SimpleDateFormat("dd'/'MM'/'yyyy"); if (startDate != null) { summary.append("start_date=" + sdf.format(startDate) + "\n"); } else if (logStartDate != null) { summary.append("start_date=" + sdf.format(logStartDate) + "\n"); } if (endDate != null) { summary.append("end_date=" + sdf.format(endDate) + "\n"); } else if (logEndDate != null) { summary.append("end_date=" + sdf.format(logEndDate) + "\n"); } // write out the archive stats keys = archiveStats.keySet().iterator(); while (keys.hasNext()) { String key = (String) keys.next(); summary.append("archive." + key + "=" + archiveStats.get(key) + "\n"); } // write out the action aggregation results keys = actionAggregator.keySet().iterator(); while (keys.hasNext()) { String key = (String) keys.next(); summary.append("action." + key + "=" + actionAggregator.get(key) + "\n"); } // depending on the config settings for reporting on emails output the // login information summary.append("user_email=" + userEmail + "\n"); int address = 1; keys = userAggregator.keySet().iterator(); // for each email address either write out the address and the count // or alias it with an "Address X" label, to keep the data confidential // FIXME: the users reporting should also have a floor value while (keys.hasNext()) { String key = (String) keys.next(); summary.append("user."); if (userEmail.equals("on")) { summary.append(key + "=" + userAggregator.get(key) + "\n"); } else if (userEmail.equals("alias")) { summary.append("Address " + Integer.toString(address++) + "=" + userAggregator.get(key) + "\n"); } } // FIXME: all values which have floors set should provide an "other" // record which counts how many other things which didn't make it into // the listing there are // output the search word information summary.append("search_floor=" + searchFloor + "\n"); keys = searchAggregator.keySet().iterator(); while (keys.hasNext()) { String key = (String) keys.next(); if (((Integer) searchAggregator.get(key)).intValue() >= searchFloor) { summary.append("search." + key + "=" + searchAggregator.get(key) + "\n"); } } // FIXME: we should do a lot more with the search aggregator // Possible feature list: // - constrain by collection/community perhaps? // - we should consider building our own aggregator class which can // be full of rich data. Perhaps this and the Stats class should // be the same thing. // item viewing information summary.append("item_floor=" + itemFloor + "\n"); summary.append("host_url=" + url + "\n"); summary.append("item_lookup=" + itemLookup + "\n"); // write out the item access information keys = itemAggregator.keySet().iterator(); while (keys.hasNext()) { String key = (String) keys.next(); if (((Integer) itemAggregator.get(key)).intValue() >= itemFloor) { summary.append("item." + key + "=" + itemAggregator.get(key) + "\n"); } } // output the average views per item if (views > 0) { summary.append("avg_item_views=" + views + "\n"); } // insert the analysis processing time information Calendar endTime = new GregorianCalendar(); long timeInMillis = (endTime.getTimeInMillis() - startTime.getTimeInMillis()); summary.append("analysis_process_time=" + Long.toString(timeInMillis / 1000) + "\n"); // finally write the string into the output file try { BufferedWriter out = new BufferedWriter(new FileWriter(outFile)); out.write(summary.toString()); out.flush(); out.close(); } catch (IOException e) { System.out.println("Unable to write to output file " + outFile); System.exit(0); } return; } /** * get an array of file objects representing the passed log directory * * @param logDir the log directory in which to pick up files * * @return an array of file objects representing the given logDir */ public static File[] getLogFiles(String logDir) { // open the log files directory, read in the files, check that they // match the passed regular expression then analyse the content File logs = new File(logDir); // if log dir is not a directory throw and error and exit if (!logs.isDirectory()) { System.out.println("Passed log directory is not a directory"); System.exit(0); } // get the files in the directory return logs.listFiles(); } /** * set up the regular expressions to be used by this analyser. Mostly this * exists to provide a degree of segregation and readability to the code * and to ensure that you only need to set up the regular expressions to * be used once * * @param fileTemplate the regex to be used to identify dspace log files */ public static void setRegex(String fileTemplate) { // build the exclude characters regular expression StringBuffer charRegEx = new StringBuffer(); charRegEx.append("["); for (int i = 0; i < excludeChars.size(); i++) { charRegEx.append("\\" + (String) excludeChars.get(i)); } charRegEx.append("]"); excludeCharRX = Pattern.compile(charRegEx.toString()); // regular expression to find handle indicators in strings handleRX = Pattern.compile("handle="); // regular expression to find item_id indicators in strings itemRX = Pattern.compile(",item_id=.*$"); // regular expression to find query indicators in strings queryRX = Pattern.compile("query="); // regular expression to find collections in strings collectionRX = Pattern.compile("collection_id=[0-9]*,"); // regular expression to find communities in strings communityRX = Pattern.compile("community_id=[0-9]*,"); // regular expression to find search result sets resultsRX = Pattern.compile(",results=(.*)"); // regular expressions to find single characters anywhere in the string singleRX = Pattern.compile("( . |^. | .$)"); // set up the standard log file line regular expression String logLine13 = "^(\\d\\d\\d\\d-\\d\\d\\-\\d\\d) \\d\\d:\\d\\d:\\d\\d,\\d\\d\\d (\\w+)\\s+\\S+ @ ([^:]+):[^:]+:([^:]+):(.*)"; String logLine14 = "^(\\d\\d\\d\\d-\\d\\d\\-\\d\\d) \\d\\d:\\d\\d:\\d\\d,\\d\\d\\d (\\w+)\\s+\\S+ @ ([^:]+):[^:]+:[^:]+:([^:]+):(.*)"; valid13 = Pattern.compile(logLine13); valid14 = Pattern.compile(logLine14); // set up the pattern for validating log file names logRegex = Pattern.compile(fileTemplate); // set up the pattern for matching any of the query types StringBuffer typeRXString = new StringBuffer(); typeRXString.append("("); for (int i = 0; i < excludeTypes.size(); i++) { if (i > 0) { typeRXString.append("|"); } typeRXString.append((String) excludeTypes.get(i)); } typeRXString.append(")"); typeRX = Pattern.compile(typeRXString.toString()); // set up the pattern for matching any of the words to exclude StringBuffer wordRXString = new StringBuffer(); wordRXString.append("("); for (int i = 0; i < excludeWords.size(); i++) { if (i > 0) { wordRXString.append("|"); } wordRXString.append(" " + (String) excludeWords.get(i) + " "); wordRXString.append("|"); wordRXString.append("^" + (String) excludeWords.get(i) + " "); wordRXString.append("|"); wordRXString.append(" " + (String) excludeWords.get(i) + "$"); } wordRXString.append(")"); wordRX = Pattern.compile(wordRXString.toString()); return; } /** * read in the given config file and populate the class globals * * @param configFile the config file to read in */ public static void readConfig(String configFile) throws IOException { // prepare our standard file readers and buffered readers FileReader fr = null; BufferedReader br = null; String record = null; try { fr = new FileReader(configFile); br = new BufferedReader(fr); } catch (IOException e) { System.out.println("Failed to read config file: " + configFile); System.exit(0); } // read in the config file and set up our instance variables while ((record = br.readLine()) != null) { // check to see what kind of line we have Matcher matchComment = comment.matcher(record); Matcher matchReal = real.matcher(record); // if the line is not a comment and is real, read it in if (!matchComment.matches() && matchReal.matches()) { // lift the values out of the matcher's result groups String key = matchReal.group(1).trim(); String value = matchReal.group(2).trim(); // read the config values into our instance variables (see // documentation for more info on config params) if (key.equals("general.summary")) { actionAggregator.put(value, new Integer(0)); generalSummary.add(value); } if (key.equals("exclude.word")) { excludeWords.add(value); } if (key.equals("exclude.type")) { excludeTypes.add(value); } if (key.equals("exclude.character")) { excludeChars.add(value); } if (key.equals("item.type")) { itemTypes.add(value); } if (key.equals("item.floor")) { itemFloor = Integer.parseInt(value); } if (key.equals("search.floor")) { searchFloor = Integer.parseInt(value); } if (key.equals("item.lookup")) { itemLookup = Integer.parseInt(value); } if (key.equals("user.email")) { userEmail = value; } } } // close the inputs br.close(); fr.close(); return; } /** * increment the value of the given map at the given key by one. * * @param map the map whose value we want to increase * @param key the key of the map whose value to increase * * @return an integer object containing the new value */ public static Integer increment(Map map, String key) { Integer newValue = null; if (map.containsKey(key)) { // FIXME: this seems like a ridiculous way to add Integers newValue = new Integer(((Integer) map.get(key)).intValue() + 1); } else { newValue = new Integer(1); } return newValue; } /** * Take the standard date string requested at the command line and convert * it into a Date object. Throws and error and exits if the date does * not parse * * @param date the string representation of the date * * @return a date object containing the date, with the time set to * 00:00:00 */ public static Date parseDate(String date) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy'-'MM'-'dd"); Date parsedDate = null; try { parsedDate = sdf.parse(date); } catch (ParseException e) { System.out.println("The date is not in the correct format"); System.exit(0); } return parsedDate; } /** * Take the date object and convert it into a string of the form YYYY-MM-DD * * @param date the date to be converted * * @return A string of the form YYYY-MM-DD */ public static String unParseDate(Date date) { // Use SimpleDateFormat SimpleDateFormat sdf = new SimpleDateFormat("yyyy'-'MM'-'dd"); return sdf.format(date); } /** * Take a search query string and pull out all of the meaningful information * from it, giving the results in the form of a String array, a single word * to each element * * @param query the search query to be analysed * * @return the string array containing meaningful search terms */ public static String[] analyseQuery(String query) { // register our standard loop counter int i = 0; // make the query string totally lower case, to ensure we don't miss out // on matches due to capitalisation query = query.toLowerCase(); // now perform successive find and replace operations using pre-defined // global regular expressions Matcher matchQuery = queryRX.matcher(query); query = matchQuery.replaceAll(" "); Matcher matchCollection = collectionRX.matcher(query); query = matchCollection.replaceAll(" "); Matcher matchCommunity = communityRX.matcher(query); query = matchCommunity.replaceAll(" "); Matcher matchResults = resultsRX.matcher(query); query = matchResults.replaceAll(" "); Matcher matchTypes = typeRX.matcher(query); query = matchTypes.replaceAll(" "); Matcher matchChars = excludeCharRX.matcher(query); query = matchChars.replaceAll(" "); Matcher matchWords = wordRX.matcher(query); query = matchWords.replaceAll(" "); Matcher single = singleRX.matcher(query); query = single.replaceAll(" "); // split the remaining string by whitespace, trim and stuff into an // array to be returned StringTokenizer st = new StringTokenizer(query); String[] words = new String[st.countTokens()]; for (i = 0; i < words.length; i++) { words[i] = st.nextToken().trim(); } // FIXME: some single characters are still slipping through the net; // why? and how do we fix it? return words; } /** * split the given line into it's relevant segments if applicable (i.e. the * line matches the required regular expression. * * @param line the line to be segmented * @return a Log Line object for the given line */ public static LogLine getLogLine(String line) { // FIXME: consider moving this code into the LogLine class. To do this // we need to much more carefully define the structure and behaviour // of the LogLine class Matcher match; if (line.indexOf(":ip_addr") > 0) { match = valid14.matcher(line); } else { match = valid13.matcher(line); } if (match.matches()) { // set up a new log line object LogLine logLine = new LogLine(parseDate(match.group(1).trim()), match.group(2).trim(), match.group(3).trim(), match.group(4).trim(), match.group(5).trim()); return logLine; } else { return null; } } /** * get the number of items in the archive which were accessioned between * the provided start and end dates, with the given value for the DC field * 'type' (unqualified) * * @param context the DSpace context for the action * @param type value for DC field 'type' (unqualified) * * @return an integer containing the relevant count */ public static Integer getNumItems(Context context, String type) throws SQLException { boolean oracle = false; if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) { oracle = true; } // FIXME: this method is clearly not optimised // FIXME: we don't yet collect total statistics, such as number of items // withdrawn, number in process of submission etc. We should probably do // that // start the type constraint String typeQuery = null; if (type != null) { typeQuery = "SELECT item_id " + "FROM metadatavalue " + "WHERE text_value LIKE '%" + type + "%' " + "AND metadata_field_id = (" + " SELECT metadata_field_id " + " FROM metadatafieldregistry " + " WHERE element = 'type' " + " AND qualifier IS NULL) "; } // start the date constraint query buffer StringBuffer dateQuery = new StringBuffer(); dateQuery.append("SELECT item_id " + "FROM metadatavalue " + "WHERE metadata_field_id = (" + " SELECT metadata_field_id " + " FROM metadatafieldregistry " + " WHERE element = 'date' " + " AND qualifier = 'accessioned') "); if (startDate != null) { if (oracle) { dateQuery.append(" AND TO_TIMESTAMP( TO_CHAR(text_value), "+ "'yyyy-mm-dd\"T\"hh24:mi:ss\"Z\"' ) > TO_DATE('" + unParseDate(startDate) + "', 'yyyy-MM-dd') "); } else { dateQuery.append(" AND text_value::timestamp > '" + unParseDate(startDate) + "'::timestamp "); } } if (endDate != null) { if (oracle) { dateQuery.append(" AND TO_TIMESTAMP( TO_CHAR(text_value), "+ "'yyyy-mm-dd\"T\"hh24:mi:ss\"Z\"' ) < TO_DATE('" + unParseDate(endDate) + "', 'yyyy-MM-dd') "); } else { dateQuery.append(" AND text_value::timestamp < '" + unParseDate(endDate) + "'::timestamp "); } } // build the final query StringBuffer query = new StringBuffer(); query.append("SELECT COUNT(*) AS num " + "FROM item " + "WHERE in_archive = " + (oracle ? "1 " : "true ") + "AND withdrawn = " + (oracle ? "0 " : "false ")); if (startDate != null || endDate != null) { query.append(" AND item_id IN ( " + dateQuery.toString() + ") "); } if (type != null) { query.append(" AND item_id IN ( " + typeQuery + ") "); } TableRow row = DatabaseManager.querySingle(context, query.toString()); Integer numItems; if (oracle) { numItems = new Integer(row.getIntColumn("num")); } else { // for some reason the number column is of "long" data type! Long count = new Long(row.getLongColumn("num")); numItems = new Integer(count.intValue()); } return numItems; } /** * get the total number of items in the archive at time of execution, * ignoring all other constraints * * @param context the DSpace context the action is being performed in * * @return an Integer containing the number of items in the * archive */ public static Integer getNumItems(Context context) throws SQLException { return getNumItems(context, null); } /** * print out the usage information for this class to the standard out */ public static void usage() { String usage = "Usage Information:\n" + "LogAnalyser [options [parameters]]\n" + "-log [log directory]\n" + "\tOptional\n" + "\tSpecify a directory containing log files\n" + "\tDefault uses [dspace.dir]/log from dspace.cfg\n" + "-file [file name regex]\n" + "\tOptional\n" + "\tSpecify a regular expression as the file name template.\n" + "\tCurrently this needs to be correctly escaped for Java string handling (FIXME)\n" + "\tDefault uses dspace.log*\n" + "-cfg [config file path]\n" + "\tOptional\n" + "\tSpecify a config file to be used\n" + "\tDefault uses dstat.cfg in dspace config directory\n" + "-out [output file path]\n" + "\tOptional\n" + "\tSpecify an output file to write results into\n" + "\tDefault uses dstat.dat in dspace log directory\n" + "-start [YYYY-MM-DD]\n" + "\tOptional\n" + "\tSpecify the start date of the analysis\n" + "\tIf a start date is specified then no attempt to gather \n" + "\tcurrent database statistics will be made unless -lookup is\n" + "\talso passed\n" + "\tDefault is to start from the earliest date records exist for\n" + "-end [YYYY-MM-DD]\n" + "\tOptional\n" + "\tSpecify the end date of the analysis\n" + "\tIf an end date is specified then no attempt to gather \n" + "\tcurrent database statistics will be made unless -lookup is\n" + "\talso passed\n" + "\tDefault is to work up to the last date records exist for\n" + "-lookup\n" + "\tOptional\n" + "\tForce a lookup of the current database statistics\n" + "\tOnly needs to be used if date constraints are also in place\n" + "-help\n" + "\tdisplay this usage information\n"; System.out.println(usage); } }
true
true
public static void processLogs(Context context, String myLogDir, String myFileTemplate, String myConfigFile, String myOutFile, Date myStartDate, Date myEndDate, boolean myLookUp) throws IOException, SQLException { // FIXME: perhaps we should have all parameters and aggregators put // together in a single aggregating object // if the timer has not yet been started, then start it startTime = new GregorianCalendar(); //instantiate aggregators actionAggregator = new HashMap(); searchAggregator = new HashMap(); userAggregator = new HashMap(); itemAggregator = new HashMap(); archiveStats = new HashMap(); //instantiate lists generalSummary = new ArrayList(); excludeWords = new ArrayList(); excludeTypes = new ArrayList(); excludeChars = new ArrayList(); itemTypes = new ArrayList(); // set the parameters for this analysis setParameters(myLogDir, myFileTemplate, myConfigFile, myOutFile, myStartDate, myEndDate, myLookUp); // pre prepare our standard file readers and buffered readers FileReader fr = null; BufferedReader br = null; // read in the config information, throwing an error if we fail to open // the given config file readConfig(configFile); // assemble the regular expressions for later use (requires the file // template to build the regex to match it setRegex(fileTemplate); // get the log files File[] logFiles = getLogFiles(logDir); // standard loop counter int i = 0; // for every log file do analysis // FIXME: it is easy to implement not processing log files after the // dates exceed the end boundary, but is there an easy way to do it // for the start of the file? Note that we can assume that the contents // of the log file are sequential, but can we assume the files are // provided in a data sequence? for (i = 0; i < logFiles.length; i++) { // check to see if this file is a log file agains the global regex Matcher matchRegex = logRegex.matcher(logFiles[i].getName()); if (matchRegex.matches()) { // if it is a log file, open it up and lets have a look at the // contents. try { fr = new FileReader(logFiles[i].toString()); br = new BufferedReader(fr); } catch (IOException e) { System.out.println("Failed to read log file " + logFiles[i].toString()); System.exit(0); } // for each line in the file do the analysis // FIXME: perhaps each section needs to be dolled out to an // analysing class to allow pluggability of other methods of // analysis, and ease of code reading too - Pending further thought String line = null; while ((line = br.readLine()) != null) { // get the log line object LogLine logLine = getLogLine(line); // if there are line segments get on with the analysis if (logLine != null) { // first find out if we are constraining by date and // if so apply the restrictions if (logLine.beforeDate(startDate)) { continue; } if (logLine.afterDate(endDate)) { break; } // count the number of lines parsed lineCount++; // if we are not constrained by date, register the date // as the start/end date if it is the earliest/latest so far // FIXME: this should probably have a method of its own if (startDate == null) { if (logStartDate != null) { if (logLine.beforeDate(logStartDate)) { logStartDate = logLine.getDate(); } } else { logStartDate = logLine.getDate(); } } if (endDate == null) { if (logEndDate != null) { if (logLine.afterDate(logEndDate)) { logEndDate = logLine.getDate(); } } else { logEndDate = logLine.getDate(); } } // count the warnings if (logLine.isLevel("WARN")) { // FIXME: really, this ought to be some kind of level // aggregator warnCount++; } // is the action a search? if (logLine.isAction("search")) { // get back all the valid search words from the query String[] words = analyseQuery(logLine.getParams()); // for each search word add to the aggregator or // increment the aggregator's counter for (int j = 0; j < words.length; j++) { // FIXME: perhaps aggregators ought to be objects // themselves searchAggregator.put(words[j], increment(searchAggregator, words[j])); } } // is the action a login, and are we counting user logins? if (logLine.isAction("login") && !userEmail.equals("off")) { userAggregator.put(logLine.getUser(), increment(userAggregator, logLine.getUser())); } // is the action an item view? if (logLine.isAction("view_item")) { String handle = logLine.getParams(); // strip the handle string Matcher matchHandle = handleRX.matcher(handle); handle = matchHandle.replaceAll(""); // strip the item id string Matcher matchItem = itemRX.matcher(handle); handle = matchItem.replaceAll(""); handle.trim(); // either add the handle to the aggregator or // increment its counter itemAggregator.put(handle, increment(itemAggregator, handle)); } // log all the activity actionAggregator.put(logLine.getAction(), increment(actionAggregator, logLine.getAction())); } } // close the file reading buffers br.close(); fr.close(); } } // do we want to do a database lookup? Do so only if the start and // end dates are null or lookUp is true // FIXME: this is a kind of separate section. Would it be worth building // the summary string separately and then inserting it into the real // summary later? Especially if we make the archive analysis more complex archiveStats.put("All Items", getNumItems(context)); for (i = 0; i < itemTypes.size(); i++) { archiveStats.put(itemTypes.get(i), getNumItems(context, (String) itemTypes.get(i))); } // now do the host name and url lookup hostName = ConfigurationManager.getProperty("dspace.hostname").trim(); name = ConfigurationManager.getProperty("dspace.name").trim(); url = ConfigurationManager.getProperties("dspace.url").trim(); if ((url != null) && (!url.endsWith("/"))) { url = url + "/"; } // do the average views analysis if (((Integer) archiveStats.get("All Items")).intValue() != 0) { // FIXME: this is dependent on their being a query on the db, which // there might not always be if it becomes configurable Double avg = new Double( Math.ceil( ((Integer) actionAggregator.get("view_item")).intValue() / ((Integer) archiveStats.get("All Items")).intValue())); views = avg.intValue(); } // finally, write the output createOutput(); return; }
public static void processLogs(Context context, String myLogDir, String myFileTemplate, String myConfigFile, String myOutFile, Date myStartDate, Date myEndDate, boolean myLookUp) throws IOException, SQLException { // FIXME: perhaps we should have all parameters and aggregators put // together in a single aggregating object // if the timer has not yet been started, then start it startTime = new GregorianCalendar(); //instantiate aggregators actionAggregator = new HashMap(); searchAggregator = new HashMap(); userAggregator = new HashMap(); itemAggregator = new HashMap(); archiveStats = new HashMap(); //instantiate lists generalSummary = new ArrayList(); excludeWords = new ArrayList(); excludeTypes = new ArrayList(); excludeChars = new ArrayList(); itemTypes = new ArrayList(); // set the parameters for this analysis setParameters(myLogDir, myFileTemplate, myConfigFile, myOutFile, myStartDate, myEndDate, myLookUp); // pre prepare our standard file readers and buffered readers FileReader fr = null; BufferedReader br = null; // read in the config information, throwing an error if we fail to open // the given config file readConfig(configFile); // assemble the regular expressions for later use (requires the file // template to build the regex to match it setRegex(fileTemplate); // get the log files File[] logFiles = getLogFiles(logDir); // standard loop counter int i = 0; // for every log file do analysis // FIXME: it is easy to implement not processing log files after the // dates exceed the end boundary, but is there an easy way to do it // for the start of the file? Note that we can assume that the contents // of the log file are sequential, but can we assume the files are // provided in a data sequence? for (i = 0; i < logFiles.length; i++) { // check to see if this file is a log file agains the global regex Matcher matchRegex = logRegex.matcher(logFiles[i].getName()); if (matchRegex.matches()) { // if it is a log file, open it up and lets have a look at the // contents. try { fr = new FileReader(logFiles[i].toString()); br = new BufferedReader(fr); } catch (IOException e) { System.out.println("Failed to read log file " + logFiles[i].toString()); System.exit(0); } // for each line in the file do the analysis // FIXME: perhaps each section needs to be dolled out to an // analysing class to allow pluggability of other methods of // analysis, and ease of code reading too - Pending further thought String line = null; while ((line = br.readLine()) != null) { // get the log line object LogLine logLine = getLogLine(line); // if there are line segments get on with the analysis if (logLine != null) { // first find out if we are constraining by date and // if so apply the restrictions if (logLine.beforeDate(startDate)) { continue; } if (logLine.afterDate(endDate)) { break; } // count the number of lines parsed lineCount++; // if we are not constrained by date, register the date // as the start/end date if it is the earliest/latest so far // FIXME: this should probably have a method of its own if (startDate == null) { if (logStartDate != null) { if (logLine.beforeDate(logStartDate)) { logStartDate = logLine.getDate(); } } else { logStartDate = logLine.getDate(); } } if (endDate == null) { if (logEndDate != null) { if (logLine.afterDate(logEndDate)) { logEndDate = logLine.getDate(); } } else { logEndDate = logLine.getDate(); } } // count the warnings if (logLine.isLevel("WARN")) { // FIXME: really, this ought to be some kind of level // aggregator warnCount++; } // is the action a search? if (logLine.isAction("search")) { // get back all the valid search words from the query String[] words = analyseQuery(logLine.getParams()); // for each search word add to the aggregator or // increment the aggregator's counter for (int j = 0; j < words.length; j++) { // FIXME: perhaps aggregators ought to be objects // themselves searchAggregator.put(words[j], increment(searchAggregator, words[j])); } } // is the action a login, and are we counting user logins? if (logLine.isAction("login") && !userEmail.equals("off")) { userAggregator.put(logLine.getUser(), increment(userAggregator, logLine.getUser())); } // is the action an item view? if (logLine.isAction("view_item")) { String handle = logLine.getParams(); // strip the handle string Matcher matchHandle = handleRX.matcher(handle); handle = matchHandle.replaceAll(""); // strip the item id string Matcher matchItem = itemRX.matcher(handle); handle = matchItem.replaceAll(""); handle.trim(); // either add the handle to the aggregator or // increment its counter itemAggregator.put(handle, increment(itemAggregator, handle)); } // log all the activity actionAggregator.put(logLine.getAction(), increment(actionAggregator, logLine.getAction())); } } // close the file reading buffers br.close(); fr.close(); } } // do we want to do a database lookup? Do so only if the start and // end dates are null or lookUp is true // FIXME: this is a kind of separate section. Would it be worth building // the summary string separately and then inserting it into the real // summary later? Especially if we make the archive analysis more complex archiveStats.put("All Items", getNumItems(context)); for (i = 0; i < itemTypes.size(); i++) { archiveStats.put(itemTypes.get(i), getNumItems(context, (String) itemTypes.get(i))); } // now do the host name and url lookup hostName = ConfigurationManager.getProperty("dspace.hostname").trim(); name = ConfigurationManager.getProperty("dspace.name").trim(); url = ConfigurationManager.getProperty("dspace.url").trim(); if ((url != null) && (!url.endsWith("/"))) { url = url + "/"; } // do the average views analysis if (((Integer) archiveStats.get("All Items")).intValue() != 0) { // FIXME: this is dependent on their being a query on the db, which // there might not always be if it becomes configurable Double avg = new Double( Math.ceil( ((Integer) actionAggregator.get("view_item")).intValue() / ((Integer) archiveStats.get("All Items")).intValue())); views = avg.intValue(); } // finally, write the output createOutput(); return; }
diff --git a/phone/com/android/internal/policy/impl/PhoneWindowManager.java b/phone/com/android/internal/policy/impl/PhoneWindowManager.java index d376341..135dc83 100755 --- a/phone/com/android/internal/policy/impl/PhoneWindowManager.java +++ b/phone/com/android/internal/policy/impl/PhoneWindowManager.java @@ -1,2227 +1,2230 @@ /* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.internal.policy.impl; import android.app.Activity; import android.app.ActivityManagerNative; import android.app.IActivityManager; import android.app.IStatusBar; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.content.res.Resources; import android.database.ContentObserver; import android.graphics.Rect; import android.os.BatteryManager; import android.os.Handler; import android.os.IBinder; import android.os.LocalPowerManager; import android.os.PowerManager; import android.os.RemoteException; import android.os.ServiceManager; import android.os.SystemClock; import android.os.SystemProperties; import android.os.Vibrator; import android.provider.Settings; import com.android.internal.policy.PolicyManager; import com.android.internal.telephony.ITelephony; import android.util.Config; import android.util.EventLog; import android.util.Log; import android.view.Display; import android.view.Gravity; import android.view.HapticFeedbackConstants; import android.view.IWindowManager; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.WindowOrientationListener; import android.view.RawInputEvent; import android.view.Surface; import android.view.View; import android.view.ViewConfiguration; import android.view.Window; import android.view.WindowManager; import static android.view.WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW; import static android.view.WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN; import static android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN; import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN; import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR; import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS; import static android.view.WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED; import static android.view.WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD; import static android.view.WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST; import static android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE; import static android.view.WindowManager.LayoutParams.LAST_APPLICATION_WINDOW; import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA; import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA_OVERLAY; import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_PANEL; import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL; import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG; import static android.view.WindowManager.LayoutParams.TYPE_KEYGUARD; import static android.view.WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG; import static android.view.WindowManager.LayoutParams.TYPE_PHONE; import static android.view.WindowManager.LayoutParams.TYPE_PRIORITY_PHONE; import static android.view.WindowManager.LayoutParams.TYPE_SEARCH_BAR; import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR; import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL; import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_ALERT; import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_ERROR; import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD; import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG; import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY; import static android.view.WindowManager.LayoutParams.TYPE_TOAST; import static android.view.WindowManager.LayoutParams.TYPE_WALLPAPER; import android.view.WindowManagerImpl; import android.view.WindowManagerPolicy; import android.view.WindowManagerPolicy.WindowState; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.media.IAudioService; import android.media.AudioManager; /** * WindowManagerPolicy implementation for the Android phone UI. This * introduces a new method suffix, Lp, for an internal lock of the * PhoneWindowManager. This is used to protect some internal state, and * can be acquired with either thw Lw and Li lock held, so has the restrictions * of both of those when held. */ public class PhoneWindowManager implements WindowManagerPolicy { static final String TAG = "WindowManager"; static final boolean DEBUG = false; static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV; static final boolean DEBUG_LAYOUT = false; static final boolean SHOW_STARTING_ANIMATIONS = true; static final boolean SHOW_PROCESSES_ON_ALT_MENU = false; // wallpaper is at the bottom, though the window manager may move it. static final int WALLPAPER_LAYER = 2; static final int APPLICATION_LAYER = 2; static final int PHONE_LAYER = 3; static final int SEARCH_BAR_LAYER = 4; static final int STATUS_BAR_PANEL_LAYER = 5; // toasts and the plugged-in battery thing static final int TOAST_LAYER = 6; static final int STATUS_BAR_LAYER = 7; // SIM errors and unlock. Not sure if this really should be in a high layer. static final int PRIORITY_PHONE_LAYER = 8; // like the ANR / app crashed dialogs static final int SYSTEM_ALERT_LAYER = 9; // system-level error dialogs static final int SYSTEM_ERROR_LAYER = 10; // on-screen keyboards and other such input method user interfaces go here. static final int INPUT_METHOD_LAYER = 11; // on-screen keyboards and other such input method user interfaces go here. static final int INPUT_METHOD_DIALOG_LAYER = 12; // the keyguard; nothing on top of these can take focus, since they are // responsible for power management when displayed. static final int KEYGUARD_LAYER = 13; static final int KEYGUARD_DIALOG_LAYER = 14; // things in here CAN NOT take focus, but are shown on top of everything else. static final int SYSTEM_OVERLAY_LAYER = 15; static final int APPLICATION_MEDIA_SUBLAYER = -2; static final int APPLICATION_MEDIA_OVERLAY_SUBLAYER = -1; static final int APPLICATION_PANEL_SUBLAYER = 1; static final int APPLICATION_SUB_PANEL_SUBLAYER = 2; static final float SLIDE_TOUCH_EVENT_SIZE_LIMIT = 0.6f; // Debugging: set this to have the system act like there is no hard keyboard. static final boolean KEYBOARD_ALWAYS_HIDDEN = false; static public final String SYSTEM_DIALOG_REASON_KEY = "reason"; static public final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions"; static public final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps"; final Object mLock = new Object(); Context mContext; IWindowManager mWindowManager; LocalPowerManager mPowerManager; Vibrator mVibrator; // Vibrator for giving feedback of orientation changes // Vibrator pattern for haptic feedback of a long press. long[] mLongPressVibePattern; // Vibrator pattern for haptic feedback of virtual key press. long[] mVirtualKeyVibePattern; // Vibrator pattern for haptic feedback during boot when safe mode is disabled. long[] mSafeModeDisabledVibePattern; // Vibrator pattern for haptic feedback during boot when safe mode is enabled. long[] mSafeModeEnabledVibePattern; /** If true, hitting shift & menu will broadcast Intent.ACTION_BUG_REPORT */ boolean mEnableShiftMenuBugReports = false; boolean mSafeMode; WindowState mStatusBar = null; WindowState mKeyguard = null; KeyguardViewMediator mKeyguardMediator; GlobalActions mGlobalActions; boolean mShouldTurnOffOnKeyUp; RecentApplicationsDialog mRecentAppsDialog; Handler mHandler; final IntentFilter mBatteryStatusFilter = new IntentFilter(); boolean mLidOpen; int mPlugged; boolean mRegisteredBatteryReceiver; int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED; int mLidOpenRotation; int mCarDockRotation; int mDeskDockRotation; int mCarDockKeepsScreenOn; int mDeskDockKeepsScreenOn; boolean mCarDockEnablesAccelerometer; boolean mDeskDockEnablesAccelerometer; int mLidKeyboardAccessibility; int mLidNavigationAccessibility; boolean mScreenOn = false; boolean mOrientationSensorEnabled = false; int mCurrentAppOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; static final int DEFAULT_ACCELEROMETER_ROTATION = 0; int mAccelerometerDefault = DEFAULT_ACCELEROMETER_ROTATION; boolean mHasSoftInput = false; // The current size of the screen. int mW, mH; // During layout, the current screen borders with all outer decoration // (status bar, input method dock) accounted for. int mCurLeft, mCurTop, mCurRight, mCurBottom; // During layout, the frame in which content should be displayed // to the user, accounting for all screen decoration except for any // space they deem as available for other content. This is usually // the same as mCur*, but may be larger if the screen decor has supplied // content insets. int mContentLeft, mContentTop, mContentRight, mContentBottom; // During layout, the current screen borders along with input method // windows are placed. int mDockLeft, mDockTop, mDockRight, mDockBottom; // During layout, the layer at which the doc window is placed. int mDockLayer; static final Rect mTmpParentFrame = new Rect(); static final Rect mTmpDisplayFrame = new Rect(); static final Rect mTmpContentFrame = new Rect(); static final Rect mTmpVisibleFrame = new Rect(); WindowState mTopFullscreenOpaqueWindowState; boolean mForceStatusBar; boolean mHideLockScreen; boolean mDismissKeyguard; boolean mHomePressed; Intent mHomeIntent; Intent mCarDockIntent; Intent mDeskDockIntent; boolean mSearchKeyPressed; boolean mConsumeSearchKeyUp; static final int ENDCALL_HOME = 0x1; static final int ENDCALL_SLEEPS = 0x2; static final int DEFAULT_ENDCALL_BEHAVIOR = ENDCALL_SLEEPS; int mEndcallBehavior; int mLandscapeRotation = -1; int mPortraitRotation = -1; // Nothing to see here, move along... int mFancyRotationAnimation; ShortcutManager mShortcutManager; PowerManager.WakeLock mBroadcastWakeLock; PowerManager.WakeLock mDockWakeLock; class SettingsObserver extends ContentObserver { SettingsObserver(Handler handler) { super(handler); } void observe() { ContentResolver resolver = mContext.getContentResolver(); resolver.registerContentObserver(Settings.System.getUriFor( Settings.System.END_BUTTON_BEHAVIOR), false, this); resolver.registerContentObserver(Settings.System.getUriFor( Settings.System.ACCELEROMETER_ROTATION), false, this); resolver.registerContentObserver(Settings.Secure.getUriFor( Settings.Secure.DEFAULT_INPUT_METHOD), false, this); resolver.registerContentObserver(Settings.System.getUriFor( "fancy_rotation_anim"), false, this); update(); } @Override public void onChange(boolean selfChange) { update(); try { mWindowManager.setRotation(USE_LAST_ROTATION, false, mFancyRotationAnimation); } catch (RemoteException e) { // Ignore } } public void update() { ContentResolver resolver = mContext.getContentResolver(); boolean updateRotation = false; synchronized (mLock) { mEndcallBehavior = Settings.System.getInt(resolver, Settings.System.END_BUTTON_BEHAVIOR, DEFAULT_ENDCALL_BEHAVIOR); mFancyRotationAnimation = Settings.System.getInt(resolver, "fancy_rotation_anim", 0) != 0 ? 0x80 : 0; int accelerometerDefault = Settings.System.getInt(resolver, Settings.System.ACCELEROMETER_ROTATION, DEFAULT_ACCELEROMETER_ROTATION); if (mAccelerometerDefault != accelerometerDefault) { mAccelerometerDefault = accelerometerDefault; updateOrientationListenerLp(); } String imId = Settings.Secure.getString(resolver, Settings.Secure.DEFAULT_INPUT_METHOD); boolean hasSoftInput = imId != null && imId.length() > 0; if (mHasSoftInput != hasSoftInput) { mHasSoftInput = hasSoftInput; updateRotation = true; } } if (updateRotation) { updateRotation(0); } } } class MyOrientationListener extends WindowOrientationListener { MyOrientationListener(Context context) { super(context); } @Override public void onOrientationChanged(int rotation) { // Send updates based on orientation value if (localLOGV) Log.v(TAG, "onOrientationChanged, rotation changed to " +rotation); try { mWindowManager.setRotation(rotation, false, mFancyRotationAnimation); } catch (RemoteException e) { // Ignore } } } MyOrientationListener mOrientationListener; boolean useSensorForOrientationLp(int appOrientation) { // The app says use the sensor. if (appOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR) { return true; } // The user preference says we can rotate, and the app is willing to rotate. if (mAccelerometerDefault != 0 && (appOrientation == ActivityInfo.SCREEN_ORIENTATION_USER || appOrientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)) { return true; } // We're in a dock that has a rotation affinity, an the app is willing to rotate. if ((mCarDockEnablesAccelerometer && mDockState == Intent.EXTRA_DOCK_STATE_CAR) || (mDeskDockEnablesAccelerometer && mDockState == Intent.EXTRA_DOCK_STATE_DESK)) { // Note we override the nosensor flag here. if (appOrientation == ActivityInfo.SCREEN_ORIENTATION_USER || appOrientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED || appOrientation == ActivityInfo.SCREEN_ORIENTATION_NOSENSOR) { return true; } } // Else, don't use the sensor. return false; } /* * We always let the sensor be switched on by default except when * the user has explicitly disabled sensor based rotation or when the * screen is switched off. */ boolean needSensorRunningLp() { if (mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR) { // If the application has explicitly requested to follow the // orientation, then we need to turn the sensor or. return true; } if ((mCarDockEnablesAccelerometer && mDockState == Intent.EXTRA_DOCK_STATE_CAR) || (mDeskDockEnablesAccelerometer && mDockState == Intent.EXTRA_DOCK_STATE_DESK)) { // enable accelerometer if we are docked in a dock that enables accelerometer // orientation management, return true; } if (mAccelerometerDefault == 0) { // If the setting for using the sensor by default is enabled, then // we will always leave it on. Note that the user could go to // a window that forces an orientation that does not use the // sensor and in theory we could turn it off... however, when next // turning it on we won't have a good value for the current // orientation for a little bit, which can cause orientation // changes to lag, so we'd like to keep it always on. (It will // still be turned off when the screen is off.) return false; } return true; } /* * Various use cases for invoking this function * screen turning off, should always disable listeners if already enabled * screen turned on and current app has sensor based orientation, enable listeners * if not already enabled * screen turned on and current app does not have sensor orientation, disable listeners if * already enabled * screen turning on and current app has sensor based orientation, enable listeners if needed * screen turning on and current app has nosensor based orientation, do nothing */ void updateOrientationListenerLp() { if (!mOrientationListener.canDetectOrientation()) { // If sensor is turned off or nonexistent for some reason return; } //Could have been invoked due to screen turning on or off or //change of the currently visible window's orientation if (localLOGV) Log.v(TAG, "Screen status="+mScreenOn+ ", current orientation="+mCurrentAppOrientation+ ", SensorEnabled="+mOrientationSensorEnabled); boolean disable = true; if (mScreenOn) { if (needSensorRunningLp()) { disable = false; //enable listener if not already enabled if (!mOrientationSensorEnabled) { mOrientationListener.enable(); if(localLOGV) Log.v(TAG, "Enabling listeners"); mOrientationSensorEnabled = true; } } } //check if sensors need to be disabled if (disable && mOrientationSensorEnabled) { mOrientationListener.disable(); if(localLOGV) Log.v(TAG, "Disabling listeners"); mOrientationSensorEnabled = false; } } Runnable mPowerLongPress = new Runnable() { public void run() { mShouldTurnOffOnKeyUp = false; performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false); sendCloseSystemWindows(SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS); showGlobalActionsDialog(); } }; void showGlobalActionsDialog() { if (mGlobalActions == null) { mGlobalActions = new GlobalActions(mContext); } final boolean keyguardShowing = mKeyguardMediator.isShowing(); mGlobalActions.showDialog(keyguardShowing, isDeviceProvisioned()); if (keyguardShowing) { // since it took two seconds of long press to bring this up, // poke the wake lock so they have some time to see the dialog. mKeyguardMediator.pokeWakelock(); } } boolean isDeviceProvisioned() { return Settings.Secure.getInt( mContext.getContentResolver(), Settings.Secure.DEVICE_PROVISIONED, 0) != 0; } /** * When a home-key longpress expires, close other system windows and launch the recent apps */ Runnable mHomeLongPress = new Runnable() { public void run() { /* * Eat the longpress so it won't dismiss the recent apps dialog when * the user lets go of the home key */ mHomePressed = false; performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false); sendCloseSystemWindows(SYSTEM_DIALOG_REASON_RECENT_APPS); showRecentAppsDialog(); } }; /** * Create (if necessary) and launch the recent apps dialog */ void showRecentAppsDialog() { if (mRecentAppsDialog == null) { mRecentAppsDialog = new RecentApplicationsDialog(mContext); } mRecentAppsDialog.show(); } /** {@inheritDoc} */ public void init(Context context, IWindowManager windowManager, LocalPowerManager powerManager) { mContext = context; mWindowManager = windowManager; mPowerManager = powerManager; mKeyguardMediator = new KeyguardViewMediator(context, this, powerManager); mHandler = new Handler(); mOrientationListener = new MyOrientationListener(mContext); SettingsObserver settingsObserver = new SettingsObserver(mHandler); settingsObserver.observe(); mShortcutManager = new ShortcutManager(context, mHandler); mShortcutManager.observe(); mHomeIntent = new Intent(Intent.ACTION_MAIN, null); mHomeIntent.addCategory(Intent.CATEGORY_HOME); mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mCarDockIntent = new Intent(Intent.ACTION_MAIN, null); mCarDockIntent.addCategory(Intent.CATEGORY_CAR_DOCK); mCarDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mDeskDockIntent = new Intent(Intent.ACTION_MAIN, null); mDeskDockIntent.addCategory(Intent.CATEGORY_DESK_DOCK); mDeskDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE); mBroadcastWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "PhoneWindowManager.mBroadcastWakeLock"); mDockWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "PhoneWindowManager.mDockWakeLock"); mDockWakeLock.setReferenceCounted(false); mEnableShiftMenuBugReports = "1".equals(SystemProperties.get("ro.debuggable")); mLidOpenRotation = readRotation( com.android.internal.R.integer.config_lidOpenRotation); mCarDockRotation = readRotation( com.android.internal.R.integer.config_carDockRotation); mDeskDockRotation = readRotation( com.android.internal.R.integer.config_deskDockRotation); mCarDockKeepsScreenOn = mContext.getResources().getInteger( com.android.internal.R.integer.config_carDockKeepsScreenOn); mDeskDockKeepsScreenOn = mContext.getResources().getInteger( com.android.internal.R.integer.config_deskDockKeepsScreenOn); mCarDockEnablesAccelerometer = mContext.getResources().getBoolean( com.android.internal.R.bool.config_carDockEnablesAccelerometer); mDeskDockEnablesAccelerometer = mContext.getResources().getBoolean( com.android.internal.R.bool.config_deskDockEnablesAccelerometer); mLidKeyboardAccessibility = mContext.getResources().getInteger( com.android.internal.R.integer.config_lidKeyboardAccessibility); mLidNavigationAccessibility = mContext.getResources().getInteger( com.android.internal.R.integer.config_lidNavigationAccessibility); // register for battery events mBatteryStatusFilter.addAction(Intent.ACTION_BATTERY_CHANGED); mPlugged = 0; updatePlugged(context.registerReceiver(null, mBatteryStatusFilter)); // register for dock events context.registerReceiver(mDockReceiver, new IntentFilter(Intent.ACTION_DOCK_EVENT)); mVibrator = new Vibrator(); mLongPressVibePattern = getLongIntArray(mContext.getResources(), com.android.internal.R.array.config_longPressVibePattern); mVirtualKeyVibePattern = getLongIntArray(mContext.getResources(), com.android.internal.R.array.config_virtualKeyVibePattern); mSafeModeDisabledVibePattern = getLongIntArray(mContext.getResources(), com.android.internal.R.array.config_safeModeDisabledVibePattern); mSafeModeEnabledVibePattern = getLongIntArray(mContext.getResources(), com.android.internal.R.array.config_safeModeEnabledVibePattern); } void updatePlugged(Intent powerIntent) { if (localLOGV) Log.v(TAG, "New battery status: " + powerIntent.getExtras()); if (powerIntent != null) { mPlugged = powerIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0); if (localLOGV) Log.v(TAG, "PLUGGED: " + mPlugged); } } private int readRotation(int resID) { try { int rotation = mContext.getResources().getInteger(resID); switch (rotation) { case 0: return Surface.ROTATION_0; case 90: return Surface.ROTATION_90; case 180: return Surface.ROTATION_180; case 270: return Surface.ROTATION_270; } } catch (Resources.NotFoundException e) { // fall through } return -1; } /** {@inheritDoc} */ public int checkAddPermission(WindowManager.LayoutParams attrs) { int type = attrs.type; if (type < WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW || type > WindowManager.LayoutParams.LAST_SYSTEM_WINDOW) { return WindowManagerImpl.ADD_OKAY; } String permission = null; switch (type) { case TYPE_TOAST: // XXX right now the app process has complete control over // this... should introduce a token to let the system // monitor/control what they are doing. break; case TYPE_INPUT_METHOD: case TYPE_WALLPAPER: // The window manager will check these. break; case TYPE_PHONE: case TYPE_PRIORITY_PHONE: case TYPE_SYSTEM_ALERT: case TYPE_SYSTEM_ERROR: case TYPE_SYSTEM_OVERLAY: permission = android.Manifest.permission.SYSTEM_ALERT_WINDOW; break; default: permission = android.Manifest.permission.INTERNAL_SYSTEM_WINDOW; } if (permission != null) { if (mContext.checkCallingOrSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { return WindowManagerImpl.ADD_PERMISSION_DENIED; } } return WindowManagerImpl.ADD_OKAY; } public void adjustWindowParamsLw(WindowManager.LayoutParams attrs) { switch (attrs.type) { case TYPE_SYSTEM_OVERLAY: case TYPE_TOAST: // These types of windows can't receive input events. attrs.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; break; } } void readLidState() { try { int sw = mWindowManager.getSwitchState(RawInputEvent.SW_LID); if (sw >= 0) { mLidOpen = sw == 0; } } catch (RemoteException e) { // Ignore } } private int determineHiddenState(boolean lidOpen, int mode, int hiddenValue, int visibleValue) { switch (mode) { case 1: return lidOpen ? visibleValue : hiddenValue; case 2: return lidOpen ? hiddenValue : visibleValue; } return visibleValue; } /** {@inheritDoc} */ public void adjustConfigurationLw(Configuration config) { readLidState(); final boolean lidOpen = !KEYBOARD_ALWAYS_HIDDEN && mLidOpen; mPowerManager.setKeyboardVisibility(lidOpen); config.hardKeyboardHidden = determineHiddenState(lidOpen, mLidKeyboardAccessibility, Configuration.HARDKEYBOARDHIDDEN_YES, Configuration.HARDKEYBOARDHIDDEN_NO); config.navigationHidden = determineHiddenState(lidOpen, mLidNavigationAccessibility, Configuration.NAVIGATIONHIDDEN_YES, Configuration.NAVIGATIONHIDDEN_NO); config.keyboardHidden = (config.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO || mHasSoftInput) ? Configuration.KEYBOARDHIDDEN_NO : Configuration.KEYBOARDHIDDEN_YES; } public boolean isCheekPressedAgainstScreen(MotionEvent ev) { if(ev.getSize() > SLIDE_TOUCH_EVENT_SIZE_LIMIT) { return true; } int size = ev.getHistorySize(); for(int i = 0; i < size; i++) { if(ev.getHistoricalSize(i) > SLIDE_TOUCH_EVENT_SIZE_LIMIT) { return true; } } return false; } /** {@inheritDoc} */ public int windowTypeToLayerLw(int type) { if (type >= FIRST_APPLICATION_WINDOW && type <= LAST_APPLICATION_WINDOW) { return APPLICATION_LAYER; } switch (type) { case TYPE_STATUS_BAR: return STATUS_BAR_LAYER; case TYPE_STATUS_BAR_PANEL: return STATUS_BAR_PANEL_LAYER; case TYPE_SEARCH_BAR: return SEARCH_BAR_LAYER; case TYPE_PHONE: return PHONE_LAYER; case TYPE_KEYGUARD: return KEYGUARD_LAYER; case TYPE_KEYGUARD_DIALOG: return KEYGUARD_DIALOG_LAYER; case TYPE_SYSTEM_ALERT: return SYSTEM_ALERT_LAYER; case TYPE_SYSTEM_ERROR: return SYSTEM_ERROR_LAYER; case TYPE_INPUT_METHOD: return INPUT_METHOD_LAYER; case TYPE_INPUT_METHOD_DIALOG: return INPUT_METHOD_DIALOG_LAYER; case TYPE_SYSTEM_OVERLAY: return SYSTEM_OVERLAY_LAYER; case TYPE_PRIORITY_PHONE: return PRIORITY_PHONE_LAYER; case TYPE_TOAST: return TOAST_LAYER; case TYPE_WALLPAPER: return WALLPAPER_LAYER; } Log.e(TAG, "Unknown window type: " + type); return APPLICATION_LAYER; } /** {@inheritDoc} */ public int subWindowTypeToLayerLw(int type) { switch (type) { case TYPE_APPLICATION_PANEL: case TYPE_APPLICATION_ATTACHED_DIALOG: return APPLICATION_PANEL_SUBLAYER; case TYPE_APPLICATION_MEDIA: return APPLICATION_MEDIA_SUBLAYER; case TYPE_APPLICATION_MEDIA_OVERLAY: return APPLICATION_MEDIA_OVERLAY_SUBLAYER; case TYPE_APPLICATION_SUB_PANEL: return APPLICATION_SUB_PANEL_SUBLAYER; } Log.e(TAG, "Unknown sub-window type: " + type); return 0; } public int getMaxWallpaperLayer() { return STATUS_BAR_LAYER; } public boolean doesForceHide(WindowState win, WindowManager.LayoutParams attrs) { return attrs.type == WindowManager.LayoutParams.TYPE_KEYGUARD; } public boolean canBeForceHidden(WindowState win, WindowManager.LayoutParams attrs) { return attrs.type != WindowManager.LayoutParams.TYPE_STATUS_BAR && attrs.type != WindowManager.LayoutParams.TYPE_WALLPAPER; } /** {@inheritDoc} */ public View addStartingWindow(IBinder appToken, String packageName, int theme, CharSequence nonLocalizedLabel, int labelRes, int icon) { if (!SHOW_STARTING_ANIMATIONS) { return null; } if (packageName == null) { return null; } Context context = mContext; boolean setTheme = false; //Log.i(TAG, "addStartingWindow " + packageName + ": nonLocalizedLabel=" // + nonLocalizedLabel + " theme=" + Integer.toHexString(theme)); if (theme != 0 || labelRes != 0) { try { context = context.createPackageContext(packageName, 0); if (theme != 0) { context.setTheme(theme); setTheme = true; } } catch (PackageManager.NameNotFoundException e) { // Ignore } } if (!setTheme) { context.setTheme(com.android.internal.R.style.Theme); } Window win = PolicyManager.makeNewWindow(context); if (win.getWindowStyle().getBoolean( com.android.internal.R.styleable.Window_windowDisablePreview, false)) { return null; } Resources r = context.getResources(); win.setTitle(r.getText(labelRes, nonLocalizedLabel)); win.setType( WindowManager.LayoutParams.TYPE_APPLICATION_STARTING); // Force the window flags: this is a fake window, so it is not really // touchable or focusable by the user. We also add in the ALT_FOCUSABLE_IM // flag because we do know that the next window will take input // focus, so we want to get the IME window up on top of us right away. win.setFlags( WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE| WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE| WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); win.setLayout(WindowManager.LayoutParams.FILL_PARENT, WindowManager.LayoutParams.FILL_PARENT); final WindowManager.LayoutParams params = win.getAttributes(); params.token = appToken; params.packageName = packageName; params.windowAnimations = win.getWindowStyle().getResourceId( com.android.internal.R.styleable.Window_windowAnimationStyle, 0); params.setTitle("Starting " + packageName); try { WindowManagerImpl wm = (WindowManagerImpl) context.getSystemService(Context.WINDOW_SERVICE); View view = win.getDecorView(); if (win.isFloating()) { // Whoops, there is no way to display an animation/preview // of such a thing! After all that work... let's skip it. // (Note that we must do this here because it is in // getDecorView() where the theme is evaluated... maybe // we should peek the floating attribute from the theme // earlier.) return null; } if (localLOGV) Log.v( TAG, "Adding starting window for " + packageName + " / " + appToken + ": " + (view.getParent() != null ? view : null)); wm.addView(view, params); // Only return the view if it was successfully added to the // window manager... which we can tell by it having a parent. return view.getParent() != null ? view : null; } catch (WindowManagerImpl.BadTokenException e) { // ignore Log.w(TAG, appToken + " already running, starting window not displayed"); } return null; } /** {@inheritDoc} */ public void removeStartingWindow(IBinder appToken, View window) { // RuntimeException e = new RuntimeException(); // Log.i(TAG, "remove " + appToken + " " + window, e); if (localLOGV) Log.v( TAG, "Removing starting window for " + appToken + ": " + window); if (window != null) { WindowManagerImpl wm = (WindowManagerImpl) mContext.getSystemService(Context.WINDOW_SERVICE); wm.removeView(window); } } /** * Preflight adding a window to the system. * * Currently enforces that three window types are singletons: * <ul> * <li>STATUS_BAR_TYPE</li> * <li>KEYGUARD_TYPE</li> * </ul> * * @param win The window to be added * @param attrs Information about the window to be added * * @return If ok, WindowManagerImpl.ADD_OKAY. If too many singletons, WindowManagerImpl.ADD_MULTIPLE_SINGLETON */ public int prepareAddWindowLw(WindowState win, WindowManager.LayoutParams attrs) { switch (attrs.type) { case TYPE_STATUS_BAR: if (mStatusBar != null) { return WindowManagerImpl.ADD_MULTIPLE_SINGLETON; } mStatusBar = win; break; case TYPE_KEYGUARD: if (mKeyguard != null) { return WindowManagerImpl.ADD_MULTIPLE_SINGLETON; } mKeyguard = win; break; } return WindowManagerImpl.ADD_OKAY; } /** {@inheritDoc} */ public void removeWindowLw(WindowState win) { if (mStatusBar == win) { mStatusBar = null; } else if (mKeyguard == win) { mKeyguard = null; } } static final boolean PRINT_ANIM = false; /** {@inheritDoc} */ public int selectAnimationLw(WindowState win, int transit) { if (PRINT_ANIM) Log.i(TAG, "selectAnimation in " + win + ": transit=" + transit); if (transit == TRANSIT_PREVIEW_DONE) { if (win.hasAppShownWindows()) { if (PRINT_ANIM) Log.i(TAG, "**** STARTING EXIT"); return com.android.internal.R.anim.app_starting_exit; } } return 0; } public Animation createForceHideEnterAnimation() { return AnimationUtils.loadAnimation(mContext, com.android.internal.R.anim.lock_screen_behind_enter); } static ITelephony getPhoneInterface() { return ITelephony.Stub.asInterface(ServiceManager.checkService(Context.TELEPHONY_SERVICE)); } static IAudioService getAudioInterface() { return IAudioService.Stub.asInterface(ServiceManager.checkService(Context.AUDIO_SERVICE)); } boolean keyguardOn() { return keyguardIsShowingTq() || inKeyguardRestrictedKeyInputMode(); } private static final int[] WINDOW_TYPES_WHERE_HOME_DOESNT_WORK = { WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, WindowManager.LayoutParams.TYPE_SYSTEM_ERROR, }; /** {@inheritDoc} */ public boolean interceptKeyTi(WindowState win, int code, int metaKeys, boolean down, int repeatCount, int flags) { boolean keyguardOn = keyguardOn(); if (false) { Log.d(TAG, "interceptKeyTi code=" + code + " down=" + down + " repeatCount=" + repeatCount + " keyguardOn=" + keyguardOn + " mHomePressed=" + mHomePressed); } // Clear a pending HOME longpress if the user releases Home // TODO: This could probably be inside the next bit of logic, but that code // turned out to be a bit fragile so I'm doing it here explicitly, for now. if ((code == KeyEvent.KEYCODE_HOME) && !down) { mHandler.removeCallbacks(mHomeLongPress); } // If the HOME button is currently being held, then we do special // chording with it. if (mHomePressed) { // If we have released the home key, and didn't do anything else // while it was pressed, then it is time to go home! if (code == KeyEvent.KEYCODE_HOME) { if (!down) { mHomePressed = false; if ((flags&KeyEvent.FLAG_CANCELED) == 0) { // If an incoming call is ringing, HOME is totally disabled. // (The user is already on the InCallScreen at this point, // and his ONLY options are to answer or reject the call.) boolean incomingRinging = false; try { ITelephony phoneServ = getPhoneInterface(); if (phoneServ != null) { incomingRinging = phoneServ.isRinging(); } else { Log.w(TAG, "Unable to find ITelephony interface"); } } catch (RemoteException ex) { Log.w(TAG, "RemoteException from getPhoneInterface()", ex); } if (incomingRinging) { Log.i(TAG, "Ignoring HOME; there's a ringing incoming call."); } else { launchHomeFromHotKey(); } } else { Log.i(TAG, "Ignoring HOME; event canceled."); } } } return true; } // First we always handle the home key here, so applications // can never break it, although if keyguard is on, we do let // it handle it, because that gives us the correct 5 second // timeout. if (code == KeyEvent.KEYCODE_HOME) { // If a system window has focus, then it doesn't make sense // right now to interact with applications. WindowManager.LayoutParams attrs = win != null ? win.getAttrs() : null; if (attrs != null) { final int type = attrs.type; if (type == WindowManager.LayoutParams.TYPE_KEYGUARD || type == WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG) { // the "app" is keyguard, so give it the key return false; } final int typeCount = WINDOW_TYPES_WHERE_HOME_DOESNT_WORK.length; for (int i=0; i<typeCount; i++) { if (type == WINDOW_TYPES_WHERE_HOME_DOESNT_WORK[i]) { // don't do anything, but also don't pass it to the app return true; } } } if (down && repeatCount == 0) { if (!keyguardOn) { mHandler.postDelayed(mHomeLongPress, ViewConfiguration.getGlobalActionKeyTimeout()); } mHomePressed = true; } return true; } else if (code == KeyEvent.KEYCODE_MENU) { // Hijack modified menu keys for debugging features final int chordBug = KeyEvent.META_SHIFT_ON; if (down && repeatCount == 0) { if (mEnableShiftMenuBugReports && (metaKeys & chordBug) == chordBug) { Intent intent = new Intent(Intent.ACTION_BUG_REPORT); mContext.sendOrderedBroadcast(intent, null); return true; } else if (SHOW_PROCESSES_ON_ALT_MENU && (metaKeys & KeyEvent.META_ALT_ON) == KeyEvent.META_ALT_ON) { Intent service = new Intent(); service.setClassName(mContext, "com.android.server.LoadAverageService"); ContentResolver res = mContext.getContentResolver(); boolean shown = Settings.System.getInt( res, Settings.System.SHOW_PROCESSES, 0) != 0; if (!shown) { mContext.startService(service); } else { mContext.stopService(service); } Settings.System.putInt( res, Settings.System.SHOW_PROCESSES, shown ? 0 : 1); return true; } } } else if (code == KeyEvent.KEYCODE_NOTIFICATION) { if (down) { // this key doesn't exist on current hardware, but if a device // didn't have a touchscreen, it would want one of these to open // the status bar. IStatusBar sbs = IStatusBar.Stub.asInterface(ServiceManager.getService("statusbar")); if (sbs != null) { try { sbs.toggle(); } catch (RemoteException e) { // we're screwed anyway, since it's in this process throw new RuntimeException(e); } } } return true; } else if (code == KeyEvent.KEYCODE_SEARCH) { if (down) { if (repeatCount == 0) { mSearchKeyPressed = true; } } else { mSearchKeyPressed = false; if (mConsumeSearchKeyUp) { // Consume the up-event mConsumeSearchKeyUp = false; return true; } } } // Shortcuts are invoked through Search+key, so intercept those here if (mSearchKeyPressed) { if (down && repeatCount == 0 && !keyguardOn) { Intent shortcutIntent = mShortcutManager.getIntent(code, metaKeys); if (shortcutIntent != null) { shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(shortcutIntent); /* * We launched an app, so the up-event of the search key * should be consumed */ mConsumeSearchKeyUp = true; return true; } } } return false; } /** * A home key -> launch home action was detected. Take the appropriate action * given the situation with the keyguard. */ void launchHomeFromHotKey() { if (!mHideLockScreen && mKeyguardMediator.isShowing()) { // don't launch home if keyguard showing } else if (!mHideLockScreen && mKeyguardMediator.isInputRestricted()) { // when in keyguard restricted mode, must first verify unlock // before launching home mKeyguardMediator.verifyUnlock(new OnKeyguardExitResult() { public void onKeyguardExitResult(boolean success) { if (success) { try { ActivityManagerNative.getDefault().stopAppSwitches(); } catch (RemoteException e) { } sendCloseSystemWindows(); startDockOrHome(); } } }); } else { // no keyguard stuff to worry about, just launch home! try { ActivityManagerNative.getDefault().stopAppSwitches(); } catch (RemoteException e) { } sendCloseSystemWindows(); startDockOrHome(); } } public void getContentInsetHintLw(WindowManager.LayoutParams attrs, Rect contentInset) { final int fl = attrs.flags; if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_FULLSCREEN | FLAG_LAYOUT_INSET_DECOR)) == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) { contentInset.set(mCurLeft, mCurTop, mW - mCurRight, mH - mCurBottom); } else { contentInset.setEmpty(); } } /** {@inheritDoc} */ public void beginLayoutLw(int displayWidth, int displayHeight) { mW = displayWidth; mH = displayHeight; mDockLeft = mContentLeft = mCurLeft = 0; mDockTop = mContentTop = mCurTop = 0; mDockRight = mContentRight = mCurRight = displayWidth; mDockBottom = mContentBottom = mCurBottom = displayHeight; mDockLayer = 0x10000000; mTopFullscreenOpaqueWindowState = null; mForceStatusBar = false; mHideLockScreen = false; mDismissKeyguard = false; // decide where the status bar goes ahead of time if (mStatusBar != null) { final Rect pf = mTmpParentFrame; final Rect df = mTmpDisplayFrame; final Rect vf = mTmpVisibleFrame; pf.left = df.left = vf.left = 0; pf.top = df.top = vf.top = 0; pf.right = df.right = vf.right = displayWidth; pf.bottom = df.bottom = vf.bottom = displayHeight; mStatusBar.computeFrameLw(pf, df, vf, vf); if (mStatusBar.isVisibleLw()) { // If the status bar is hidden, we don't want to cause // windows behind it to scroll. mDockTop = mContentTop = mCurTop = mStatusBar.getFrameLw().bottom; if (DEBUG_LAYOUT) Log.v(TAG, "Status bar: mDockBottom=" + mDockBottom + " mContentBottom=" + mContentBottom + " mCurBottom=" + mCurBottom); } } } void setAttachedWindowFrames(WindowState win, int fl, int sim, WindowState attached, boolean insetDecors, Rect pf, Rect df, Rect cf, Rect vf) { if (win.getSurfaceLayer() > mDockLayer && attached.getSurfaceLayer() < mDockLayer) { // Here's a special case: if this attached window is a panel that is // above the dock window, and the window it is attached to is below // the dock window, then the frames we computed for the window it is // attached to can not be used because the dock is effectively part // of the underlying window and the attached window is floating on top // of the whole thing. So, we ignore the attached window and explicitly // compute the frames that would be appropriate without the dock. df.left = cf.left = vf.left = mDockLeft; df.top = cf.top = vf.top = mDockTop; df.right = cf.right = vf.right = mDockRight; df.bottom = cf.bottom = vf.bottom = mDockBottom; } else { // The effective display frame of the attached window depends on // whether it is taking care of insetting its content. If not, // we need to use the parent's content frame so that the entire // window is positioned within that content. Otherwise we can use // the display frame and let the attached window take care of // positioning its content appropriately. if ((sim & SOFT_INPUT_MASK_ADJUST) != SOFT_INPUT_ADJUST_RESIZE) { cf.set(attached.getDisplayFrameLw()); } else { // If the window is resizing, then we want to base the content // frame on our attached content frame to resize... however, // things can be tricky if the attached window is NOT in resize // mode, in which case its content frame will be larger. // Ungh. So to deal with that, make sure the content frame // we end up using is not covering the IM dock. cf.set(attached.getContentFrameLw()); if (attached.getSurfaceLayer() < mDockLayer) { if (cf.left < mContentLeft) cf.left = mContentLeft; if (cf.top < mContentTop) cf.top = mContentTop; if (cf.right > mContentRight) cf.right = mContentRight; if (cf.bottom > mContentBottom) cf.bottom = mContentBottom; } } df.set(insetDecors ? attached.getDisplayFrameLw() : cf); vf.set(attached.getVisibleFrameLw()); } // The LAYOUT_IN_SCREEN flag is used to determine whether the attached // window should be positioned relative to its parent or the entire // screen. pf.set((fl & FLAG_LAYOUT_IN_SCREEN) == 0 ? attached.getFrameLw() : df); } /** {@inheritDoc} */ public void layoutWindowLw(WindowState win, WindowManager.LayoutParams attrs, WindowState attached) { // we've already done the status bar if (win == mStatusBar) { return; } if (false) { if ("com.google.android.youtube".equals(attrs.packageName) && attrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_PANEL) { Log.i(TAG, "GOTCHA!"); } } final int fl = attrs.flags; final int sim = attrs.softInputMode; final Rect pf = mTmpParentFrame; final Rect df = mTmpDisplayFrame; final Rect cf = mTmpContentFrame; final Rect vf = mTmpVisibleFrame; if (attrs.type == TYPE_INPUT_METHOD) { pf.left = df.left = cf.left = vf.left = mDockLeft; pf.top = df.top = cf.top = vf.top = mDockTop; pf.right = df.right = cf.right = vf.right = mDockRight; pf.bottom = df.bottom = cf.bottom = vf.bottom = mDockBottom; // IM dock windows always go to the bottom of the screen. attrs.gravity = Gravity.BOTTOM; mDockLayer = win.getSurfaceLayer(); } else { if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_FULLSCREEN | FLAG_LAYOUT_INSET_DECOR)) == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) { // This is the case for a normal activity window: we want it // to cover all of the screen space, and it can take care of // moving its contents to account for screen decorations that // intrude into that space. if (attached != null) { // If this window is attached to another, our display // frame is the same as the one we are attached to. setAttachedWindowFrames(win, fl, sim, attached, true, pf, df, cf, vf); } else { pf.left = df.left = 0; pf.top = df.top = 0; pf.right = df.right = mW; pf.bottom = df.bottom = mH; if ((sim & SOFT_INPUT_MASK_ADJUST) != SOFT_INPUT_ADJUST_RESIZE) { cf.left = mDockLeft; cf.top = mDockTop; cf.right = mDockRight; cf.bottom = mDockBottom; } else { cf.left = mContentLeft; cf.top = mContentTop; cf.right = mContentRight; cf.bottom = mContentBottom; } vf.left = mCurLeft; vf.top = mCurTop; vf.right = mCurRight; vf.bottom = mCurBottom; } } else if ((fl & FLAG_LAYOUT_IN_SCREEN) != 0) { // A window that has requested to fill the entire screen just // gets everything, period. pf.left = df.left = cf.left = 0; pf.top = df.top = cf.top = 0; pf.right = df.right = cf.right = mW; pf.bottom = df.bottom = cf.bottom = mH; vf.left = mCurLeft; vf.top = mCurTop; vf.right = mCurRight; vf.bottom = mCurBottom; } else if (attached != null) { // A child window should be placed inside of the same visible // frame that its parent had. setAttachedWindowFrames(win, fl, sim, attached, false, pf, df, cf, vf); } else { // Otherwise, a normal window must be placed inside the content // of all screen decorations. pf.left = mContentLeft; pf.top = mContentTop; pf.right = mContentRight; pf.bottom = mContentBottom; if ((sim & SOFT_INPUT_MASK_ADJUST) != SOFT_INPUT_ADJUST_RESIZE) { df.left = cf.left = mDockLeft; df.top = cf.top = mDockTop; df.right = cf.right = mDockRight; df.bottom = cf.bottom = mDockBottom; } else { df.left = cf.left = mContentLeft; df.top = cf.top = mContentTop; df.right = cf.right = mContentRight; df.bottom = cf.bottom = mContentBottom; } vf.left = mCurLeft; vf.top = mCurTop; vf.right = mCurRight; vf.bottom = mCurBottom; } } if ((fl & FLAG_LAYOUT_NO_LIMITS) != 0) { df.left = df.top = cf.left = cf.top = vf.left = vf.top = -10000; df.right = df.bottom = cf.right = cf.bottom = vf.right = vf.bottom = 10000; } if (DEBUG_LAYOUT) Log.v(TAG, "Compute frame " + attrs.getTitle() + ": sim=#" + Integer.toHexString(sim) + " pf=" + pf.toShortString() + " df=" + df.toShortString() + " cf=" + cf.toShortString() + " vf=" + vf.toShortString()); if (false) { if ("com.google.android.youtube".equals(attrs.packageName) && attrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_PANEL) { if (true || localLOGV) Log.v(TAG, "Computing frame of " + win + ": sim=#" + Integer.toHexString(sim) + " pf=" + pf.toShortString() + " df=" + df.toShortString() + " cf=" + cf.toShortString() + " vf=" + vf.toShortString()); } } win.computeFrameLw(pf, df, cf, vf); if (mTopFullscreenOpaqueWindowState == null && win.isVisibleOrBehindKeyguardLw()) { if ((attrs.flags & FLAG_FORCE_NOT_FULLSCREEN) != 0) { mForceStatusBar = true; } if (attrs.type >= FIRST_APPLICATION_WINDOW && attrs.type <= LAST_APPLICATION_WINDOW && win.fillsScreenLw(mW, mH, false, false)) { if (DEBUG_LAYOUT) Log.v(TAG, "Fullscreen window: " + win); mTopFullscreenOpaqueWindowState = win; if ((attrs.flags & FLAG_SHOW_WHEN_LOCKED) != 0) { if (localLOGV) Log.v(TAG, "Setting mHideLockScreen to true by win " + win); mHideLockScreen = true; } } if ((attrs.flags & FLAG_DISMISS_KEYGUARD) != 0) { if (localLOGV) Log.v(TAG, "Setting mDismissKeyguard to true by win " + win); mDismissKeyguard = true; } } // Dock windows carve out the bottom of the screen, so normal windows // can't appear underneath them. if (attrs.type == TYPE_INPUT_METHOD && !win.getGivenInsetsPendingLw()) { int top = win.getContentFrameLw().top; top += win.getGivenContentInsetsLw().top; if (mContentBottom > top) { mContentBottom = top; } top = win.getVisibleFrameLw().top; top += win.getGivenVisibleInsetsLw().top; if (mCurBottom > top) { mCurBottom = top; } if (DEBUG_LAYOUT) Log.v(TAG, "Input method: mDockBottom=" + mDockBottom + " mContentBottom=" + mContentBottom + " mCurBottom=" + mCurBottom); } } /** {@inheritDoc} */ public int finishLayoutLw() { int changes = 0; boolean hiding = false; if (mStatusBar != null) { if (localLOGV) Log.i(TAG, "force=" + mForceStatusBar + " top=" + mTopFullscreenOpaqueWindowState); if (mForceStatusBar) { if (DEBUG_LAYOUT) Log.v(TAG, "Showing status bar"); if (mStatusBar.showLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT; } else if (mTopFullscreenOpaqueWindowState != null) { //Log.i(TAG, "frame: " + mTopFullscreenOpaqueWindowState.getFrameLw() // + " shown frame: " + mTopFullscreenOpaqueWindowState.getShownFrameLw()); //Log.i(TAG, "attr: " + mTopFullscreenOpaqueWindowState.getAttrs()); WindowManager.LayoutParams lp = mTopFullscreenOpaqueWindowState.getAttrs(); boolean hideStatusBar = (lp.flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0; if (hideStatusBar) { if (DEBUG_LAYOUT) Log.v(TAG, "Hiding status bar"); if (mStatusBar.hideLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT; hiding = true; } else { if (DEBUG_LAYOUT) Log.v(TAG, "Showing status bar"); if (mStatusBar.showLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT; } } } // Hide the key guard if a visible window explicitly specifies that it wants to be displayed // when the screen is locked if (mKeyguard != null) { if (localLOGV) Log.v(TAG, "finishLayoutLw::mHideKeyguard="+mHideLockScreen); if (mDismissKeyguard && !mKeyguardMediator.isSecure()) { if (mKeyguard.hideLw(false)) { changes |= FINISH_LAYOUT_REDO_LAYOUT | FINISH_LAYOUT_REDO_CONFIG | FINISH_LAYOUT_REDO_WALLPAPER; } if (mKeyguardMediator.isShowing()) { mHandler.post(new Runnable() { public void run() { mKeyguardMediator.keyguardDone(false, false); } }); } } else if (mHideLockScreen) { if (mKeyguard.hideLw(false)) { changes |= FINISH_LAYOUT_REDO_LAYOUT | FINISH_LAYOUT_REDO_CONFIG | FINISH_LAYOUT_REDO_WALLPAPER; } } else { if (mKeyguard.showLw(false)) { changes |= FINISH_LAYOUT_REDO_LAYOUT | FINISH_LAYOUT_REDO_CONFIG | FINISH_LAYOUT_REDO_WALLPAPER; } } } if (changes != 0 && hiding) { IStatusBar sbs = IStatusBar.Stub.asInterface(ServiceManager.getService("statusbar")); if (sbs != null) { try { // Make sure the window shade is hidden. sbs.deactivate(); } catch (RemoteException e) { } } } return changes; } /** {@inheritDoc} */ public void beginAnimationLw(int displayWidth, int displayHeight) { } /** {@inheritDoc} */ public void animatingWindowLw(WindowState win, WindowManager.LayoutParams attrs) { } /** {@inheritDoc} */ public boolean finishAnimationLw() { return false; } /** {@inheritDoc} */ public boolean preprocessInputEventTq(RawInputEvent event) { switch (event.type) { case RawInputEvent.EV_SW: if (event.keycode == RawInputEvent.SW_LID) { // lid changed state mLidOpen = event.value == 0; boolean awakeNow = mKeyguardMediator.doLidChangeTq(mLidOpen); updateRotation(Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE); if (awakeNow) { // If the lid opening and we don't have to keep the // keyguard up, then we can turn on the screen // immediately. mKeyguardMediator.pokeWakelock(); } else if (keyguardIsShowingTq()) { if (mLidOpen) { // If we are opening the lid and not hiding the // keyguard, then we need to have it turn on the // screen once it is shown. mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq( KeyEvent.KEYCODE_POWER); } } else { // Light up the keyboard if we are sliding up. if (mLidOpen) { mPowerManager.userActivity(SystemClock.uptimeMillis(), false, LocalPowerManager.BUTTON_EVENT); } else { mPowerManager.userActivity(SystemClock.uptimeMillis(), false, LocalPowerManager.OTHER_EVENT); } } } } return false; } /** {@inheritDoc} */ public boolean isAppSwitchKeyTqTiLwLi(int keycode) { return keycode == KeyEvent.KEYCODE_HOME || keycode == KeyEvent.KEYCODE_ENDCALL; } /** {@inheritDoc} */ public boolean isMovementKeyTi(int keycode) { switch (keycode) { case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_DPAD_DOWN: case KeyEvent.KEYCODE_DPAD_LEFT: case KeyEvent.KEYCODE_DPAD_RIGHT: return true; } return false; } /** * @return Whether a telephone call is in progress right now. */ boolean isInCall() { final ITelephony phone = getPhoneInterface(); if (phone == null) { Log.w(TAG, "couldn't get ITelephony reference"); return false; } try { return phone.isOffhook(); } catch (RemoteException e) { Log.w(TAG, "ITelephony.isOffhhook threw RemoteException " + e); return false; } } /** * @return Whether music is being played right now. */ boolean isMusicActive() { final AudioManager am = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE); if (am == null) { Log.w(TAG, "isMusicActive: couldn't get AudioManager reference"); return false; } return am.isMusicActive(); } /** * Tell the audio service to adjust the volume appropriate to the event. * @param keycode */ void handleVolumeKey(int stream, int keycode) { final IAudioService audio = getAudioInterface(); if (audio == null) { Log.w(TAG, "handleVolumeKey: couldn't get IAudioService reference"); return; } try { // since audio is playing, we shouldn't have to hold a wake lock // during the call, but we do it as a precaution for the rare possibility // that the music stops right before we call this mBroadcastWakeLock.acquire(); audio.adjustStreamVolume(stream, keycode == KeyEvent.KEYCODE_VOLUME_UP ? AudioManager.ADJUST_RAISE : AudioManager.ADJUST_LOWER, 0); } catch (RemoteException e) { Log.w(TAG, "IAudioService.adjustStreamVolume() threw RemoteException " + e); } finally { mBroadcastWakeLock.release(); } } static boolean isMediaKey(int code) { if (code == KeyEvent.KEYCODE_HEADSETHOOK || code == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE || code == KeyEvent.KEYCODE_MEDIA_STOP || code == KeyEvent.KEYCODE_MEDIA_NEXT || code == KeyEvent.KEYCODE_MEDIA_PREVIOUS || code == KeyEvent.KEYCODE_MEDIA_PREVIOUS || code == KeyEvent.KEYCODE_MEDIA_FAST_FORWARD) { return true; } return false; } /** {@inheritDoc} */ public int interceptKeyTq(RawInputEvent event, boolean screenIsOn) { int result = ACTION_PASS_TO_USER; final boolean isWakeKey = isWakeKeyTq(event); final boolean keyguardShowing = keyguardIsShowingTq(); if (false) { Log.d(TAG, "interceptKeyTq event=" + event + " keycode=" + event.keycode + " screenIsOn=" + screenIsOn + " keyguardShowing=" + keyguardShowing); } if (keyguardShowing) { if (screenIsOn) { // when the screen is on, always give the event to the keyguard result |= ACTION_PASS_TO_USER; } else { // otherwise, don't pass it to the user result &= ~ACTION_PASS_TO_USER; final boolean isKeyDown = (event.type == RawInputEvent.EV_KEY) && (event.value != 0); if (isWakeKey && isKeyDown) { // tell the mediator about a wake key, it may decide to // turn on the screen depending on whether the key is // appropriate. if (!mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(event.keycode) && (event.keycode == KeyEvent.KEYCODE_VOLUME_DOWN || event.keycode == KeyEvent.KEYCODE_VOLUME_UP)) { if (isInCall()) { // if the keyguard didn't wake the device, we are in call, and // it is a volume key, turn on the screen so that the user // can more easily adjust the in call volume. mKeyguardMediator.pokeWakelock(); } else if (isMusicActive()) { // when keyguard is showing and screen off, we need // to handle the volume key for music here handleVolumeKey(AudioManager.STREAM_MUSIC, event.keycode); } } } } } else if (!screenIsOn) { // If we are in-call with screen off and keyguard is not showing, // then handle the volume key ourselves. // This is necessary because the phone app will disable the keyguard // when the proximity sensor is in use. if (isInCall() && event.type == RawInputEvent.EV_KEY && (event.keycode == KeyEvent.KEYCODE_VOLUME_DOWN || event.keycode == KeyEvent.KEYCODE_VOLUME_UP)) { result &= ~ACTION_PASS_TO_USER; handleVolumeKey(AudioManager.STREAM_VOICE_CALL, event.keycode); } if (isWakeKey) { // a wake key has a sole purpose of waking the device; don't pass // it to the user result |= ACTION_POKE_USER_ACTIVITY; result &= ~ACTION_PASS_TO_USER; } } int type = event.type; int code = event.keycode; boolean down = event.value != 0; if (type == RawInputEvent.EV_KEY) { if (code == KeyEvent.KEYCODE_ENDCALL || code == KeyEvent.KEYCODE_POWER) { if (down) { boolean hungUp = false; // key repeats are generated by the window manager, and we don't see them // here, so unless the driver is doing something it shouldn't be, we know // this is the real press event. - if (code == KeyEvent.KEYCODE_ENDCALL) { + ITelephony phoneServ = getPhoneInterface(); + if (phoneServ != null) { try { - ITelephony phoneServ = getPhoneInterface(); - if (phoneServ != null) { + // power button should hang up only when ringing + // but not after the call has been answered + if (code == KeyEvent.KEYCODE_ENDCALL || phoneServ.isRinging()) { hungUp = phoneServ.endCall(); - } else { - Log.w(TAG, "!!! Unable to find ITelephony interface !!!"); } } catch (RemoteException ex) { - Log.w(TAG, "ITelephony.endCall() threw RemoteException" + ex); + Log.w(TAG, "ITelephony threw RemoteException" + ex); } + } else { + Log.w(TAG, "!!! Unable to find ITelephony interface !!!"); } - if (hungUp || !screenIsOn) { + // power button should turn off screen in addition to hanging up the phone + if ((hungUp && code != KeyEvent.KEYCODE_POWER) || !screenIsOn) { mShouldTurnOffOnKeyUp = false; } else { // only try to turn off the screen if we didn't already hang up mShouldTurnOffOnKeyUp = true; mHandler.postDelayed(mPowerLongPress, ViewConfiguration.getGlobalActionKeyTimeout()); result &= ~ACTION_PASS_TO_USER; } } else { mHandler.removeCallbacks(mPowerLongPress); if (mShouldTurnOffOnKeyUp) { mShouldTurnOffOnKeyUp = false; boolean gohome = (mEndcallBehavior & ENDCALL_HOME) != 0; boolean sleeps = (mEndcallBehavior & ENDCALL_SLEEPS) != 0; if (keyguardShowing || (sleeps && !gohome) || (gohome && !goHome() && sleeps)) { // they must already be on the keyguad or home screen, // go to sleep instead Log.d(TAG, "I'm tired mEndcallBehavior=0x" + Integer.toHexString(mEndcallBehavior)); result &= ~ACTION_POKE_USER_ACTIVITY; result |= ACTION_GO_TO_SLEEP; } result &= ~ACTION_PASS_TO_USER; } } } else if (isMediaKey(code)) { // This key needs to be handled even if the screen is off. // If others need to be handled while it's off, this is a reasonable // pattern to follow. if ((result & ACTION_PASS_TO_USER) == 0) { // Only do this if we would otherwise not pass it to the user. In that // case, the PhoneWindow class will do the same thing, except it will // only do it if the showing app doesn't process the key on its own. KeyEvent keyEvent = new KeyEvent(event.when, event.when, down ? KeyEvent.ACTION_DOWN : KeyEvent.ACTION_UP, code, 0); mBroadcastWakeLock.acquire(); mHandler.post(new PassHeadsetKey(keyEvent)); } } else if (code == KeyEvent.KEYCODE_CALL) { // If an incoming call is ringing, answer it! // (We handle this key here, rather than in the InCallScreen, to make // sure we'll respond to the key even if the InCallScreen hasn't come to // the foreground yet.) // We answer the call on the DOWN event, to agree with // the "fallback" behavior in the InCallScreen. if (down) { try { ITelephony phoneServ = getPhoneInterface(); if (phoneServ != null) { if (phoneServ.isRinging()) { Log.i(TAG, "interceptKeyTq:" + " CALL key-down while ringing: Answer the call!"); phoneServ.answerRingingCall(); // And *don't* pass this key thru to the current activity // (which is presumably the InCallScreen.) result &= ~ACTION_PASS_TO_USER; } } else { Log.w(TAG, "CALL button: Unable to find ITelephony interface"); } } catch (RemoteException ex) { Log.w(TAG, "CALL button: RemoteException from getPhoneInterface()", ex); } } } else if ((code == KeyEvent.KEYCODE_VOLUME_UP) || (code == KeyEvent.KEYCODE_VOLUME_DOWN)) { // If an incoming call is ringing, either VOLUME key means // "silence ringer". We handle these keys here, rather than // in the InCallScreen, to make sure we'll respond to them // even if the InCallScreen hasn't come to the foreground yet. // Look for the DOWN event here, to agree with the "fallback" // behavior in the InCallScreen. if (down) { try { ITelephony phoneServ = getPhoneInterface(); if (phoneServ != null) { if (phoneServ.isRinging()) { Log.i(TAG, "interceptKeyTq:" + " VOLUME key-down while ringing: Silence ringer!"); // Silence the ringer. (It's safe to call this // even if the ringer has already been silenced.) phoneServ.silenceRinger(); // And *don't* pass this key thru to the current activity // (which is probably the InCallScreen.) result &= ~ACTION_PASS_TO_USER; } } else { Log.w(TAG, "VOLUME button: Unable to find ITelephony interface"); } } catch (RemoteException ex) { Log.w(TAG, "VOLUME button: RemoteException from getPhoneInterface()", ex); } } } } return result; } class PassHeadsetKey implements Runnable { KeyEvent mKeyEvent; PassHeadsetKey(KeyEvent keyEvent) { mKeyEvent = keyEvent; } public void run() { if (ActivityManagerNative.isSystemReady()) { Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON, null); intent.putExtra(Intent.EXTRA_KEY_EVENT, mKeyEvent); mContext.sendOrderedBroadcast(intent, null, mBroadcastDone, mHandler, Activity.RESULT_OK, null, null); } } } BroadcastReceiver mBroadcastDone = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { mBroadcastWakeLock.release(); } }; BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { updatePlugged(intent); updateDockKeepingScreenOn(); } }; BroadcastReceiver mDockReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { mDockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE, Intent.EXTRA_DOCK_STATE_UNDOCKED); boolean watchBattery = mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED; if (watchBattery != mRegisteredBatteryReceiver) { mRegisteredBatteryReceiver = watchBattery; if (watchBattery) { updatePlugged(mContext.registerReceiver(mBatteryReceiver, mBatteryStatusFilter)); } else { mContext.unregisterReceiver(mBatteryReceiver); } } updateRotation(Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE); updateDockKeepingScreenOn(); updateOrientationListenerLp(); } }; /** {@inheritDoc} */ public boolean isWakeRelMovementTq(int device, int classes, RawInputEvent event) { // if it's tagged with one of the wake bits, it wakes up the device return ((event.flags & (FLAG_WAKE | FLAG_WAKE_DROPPED)) != 0); } /** {@inheritDoc} */ public boolean isWakeAbsMovementTq(int device, int classes, RawInputEvent event) { // if it's tagged with one of the wake bits, it wakes up the device return ((event.flags & (FLAG_WAKE | FLAG_WAKE_DROPPED)) != 0); } /** * Given the current state of the world, should this key wake up the device? */ protected boolean isWakeKeyTq(RawInputEvent event) { // There are not key maps for trackball devices, but we'd still // like to have pressing it wake the device up, so force it here. int keycode = event.keycode; int flags = event.flags; if (keycode == RawInputEvent.BTN_MOUSE) { flags |= WindowManagerPolicy.FLAG_WAKE; } return (flags & (WindowManagerPolicy.FLAG_WAKE | WindowManagerPolicy.FLAG_WAKE_DROPPED)) != 0; } /** {@inheritDoc} */ public void screenTurnedOff(int why) { EventLog.writeEvent(70000, 0); mKeyguardMediator.onScreenTurnedOff(why); synchronized (mLock) { mScreenOn = false; updateOrientationListenerLp(); } } /** {@inheritDoc} */ public void screenTurnedOn() { EventLog.writeEvent(70000, 1); mKeyguardMediator.onScreenTurnedOn(); synchronized (mLock) { mScreenOn = true; updateOrientationListenerLp(); } } /** {@inheritDoc} */ public void enableKeyguard(boolean enabled) { mKeyguardMediator.setKeyguardEnabled(enabled); } /** {@inheritDoc} */ public void exitKeyguardSecurely(OnKeyguardExitResult callback) { mKeyguardMediator.verifyUnlock(callback); } /** {@inheritDoc} */ public boolean keyguardIsShowingTq() { return mKeyguardMediator.isShowing(); } /** {@inheritDoc} */ public boolean inKeyguardRestrictedKeyInputMode() { return mKeyguardMediator.isInputRestricted(); } void sendCloseSystemWindows() { sendCloseSystemWindows(mContext, null); } void sendCloseSystemWindows(String reason) { sendCloseSystemWindows(mContext, reason); } static void sendCloseSystemWindows(Context context, String reason) { if (ActivityManagerNative.isSystemReady()) { try { ActivityManagerNative.getDefault().closeSystemDialogs(reason); } catch (RemoteException e) { } } } public int rotationForOrientationLw(int orientation, int lastRotation, boolean displayEnabled) { if (mPortraitRotation < 0) { // Initialize the rotation angles for each orientation once. Display d = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay(); if (d.getWidth() > d.getHeight()) { mPortraitRotation = Surface.ROTATION_90; mLandscapeRotation = Surface.ROTATION_0; } else { mPortraitRotation = Surface.ROTATION_0; mLandscapeRotation = Surface.ROTATION_90; } } synchronized (mLock) { switch (orientation) { case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE: //always return landscape if orientation set to landscape return mLandscapeRotation; case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT: //always return portrait if orientation set to portrait return mPortraitRotation; } // case for nosensor meaning ignore sensor and consider only lid // or orientation sensor disabled //or case.unspecified if (mLidOpen) { return mLidOpenRotation; } else if (mDockState == Intent.EXTRA_DOCK_STATE_CAR && mCarDockRotation >= 0) { return mCarDockRotation; } else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK && mDeskDockRotation >= 0) { return mDeskDockRotation; } else { if (useSensorForOrientationLp(orientation)) { // If the user has enabled auto rotation by default, do it. int curRotation = mOrientationListener.getCurrentRotation(); return curRotation >= 0 ? curRotation : lastRotation; } return Surface.ROTATION_0; } } } public boolean detectSafeMode() { try { int menuState = mWindowManager.getKeycodeState(KeyEvent.KEYCODE_MENU); int sState = mWindowManager.getKeycodeState(KeyEvent.KEYCODE_S); int dpadState = mWindowManager.getKeycodeState(KeyEvent.KEYCODE_DPAD_CENTER); int trackballState = mWindowManager.getScancodeState(RawInputEvent.BTN_MOUSE); mSafeMode = menuState > 0 || sState > 0 || dpadState > 0 || trackballState > 0; performHapticFeedbackLw(null, mSafeMode ? HapticFeedbackConstants.SAFE_MODE_ENABLED : HapticFeedbackConstants.SAFE_MODE_DISABLED, true); if (mSafeMode) { Log.i(TAG, "SAFE MODE ENABLED (menu=" + menuState + " s=" + sState + " dpad=" + dpadState + " trackball=" + trackballState + ")"); } else { Log.i(TAG, "SAFE MODE not enabled"); } return mSafeMode; } catch (RemoteException e) { // Doom! (it's also local) throw new RuntimeException("window manager dead"); } } static long[] getLongIntArray(Resources r, int resid) { int[] ar = r.getIntArray(resid); if (ar == null) { return null; } long[] out = new long[ar.length]; for (int i=0; i<ar.length; i++) { out[i] = ar[i]; } return out; } /** {@inheritDoc} */ public void systemReady() { // tell the keyguard mKeyguardMediator.onSystemReady(); android.os.SystemProperties.set("dev.bootcomplete", "1"); synchronized (mLock) { updateOrientationListenerLp(); } } /** {@inheritDoc} */ public void enableScreenAfterBoot() { readLidState(); updateRotation(Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE); } void updateDockKeepingScreenOn() { if (mPlugged != 0) { if (localLOGV) Log.v(TAG, "Update: mDockState=" + mDockState + " mPlugged=" + mPlugged + " mCarDockKeepsScreenOn" + mCarDockKeepsScreenOn + " mDeskDockKeepsScreenOn" + mDeskDockKeepsScreenOn); if (mDockState == Intent.EXTRA_DOCK_STATE_CAR && (mPlugged&mCarDockKeepsScreenOn) != 0) { if (!mDockWakeLock.isHeld()) { mDockWakeLock.acquire(); } return; } else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK && (mPlugged&mDeskDockKeepsScreenOn) != 0) { if (!mDockWakeLock.isHeld()) { mDockWakeLock.acquire(); } return; } } if (mDockWakeLock.isHeld()) { mDockWakeLock.release(); } } void updateRotation(int animFlags) { mPowerManager.setKeyboardVisibility(mLidOpen); int rotation = Surface.ROTATION_0; if (mLidOpen) { rotation = mLidOpenRotation; } else if (mDockState == Intent.EXTRA_DOCK_STATE_CAR && mCarDockRotation >= 0) { rotation = mCarDockRotation; } else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK && mDeskDockRotation >= 0) { rotation = mDeskDockRotation; } //if lid is closed orientation will be portrait try { //set orientation on WindowManager mWindowManager.setRotation(rotation, true, mFancyRotationAnimation | animFlags); } catch (RemoteException e) { // Ignore } } /** * Return an Intent to launch the currently active dock as home. Returns * null if the standard home should be launched. * @return */ Intent createHomeDockIntent() { if (mDockState == Intent.EXTRA_DOCK_STATE_UNDOCKED) { return null; } Intent intent; if (mDockState == Intent.EXTRA_DOCK_STATE_CAR) { intent = mCarDockIntent; } else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK) { intent = mDeskDockIntent; } else { Log.w(TAG, "Unknown dock state: " + mDockState); return null; } ActivityInfo ai = intent.resolveActivityInfo( mContext.getPackageManager(), PackageManager.GET_META_DATA); if (ai == null) { return null; } if (ai.metaData != null && ai.metaData.getBoolean(Intent.METADATA_DOCK_HOME)) { intent = new Intent(intent); intent.setClassName(ai.packageName, ai.name); return intent; } return null; } void startDockOrHome() { Intent dock = createHomeDockIntent(); if (dock != null) { try { mContext.startActivity(dock); return; } catch (ActivityNotFoundException e) { } } mContext.startActivity(mHomeIntent); } /** * goes to the home screen * @return whether it did anything */ boolean goHome() { if (false) { // This code always brings home to the front. try { ActivityManagerNative.getDefault().stopAppSwitches(); } catch (RemoteException e) { } sendCloseSystemWindows(); startDockOrHome(); } else { // This code brings home to the front or, if it is already // at the front, puts the device to sleep. try { ActivityManagerNative.getDefault().stopAppSwitches(); sendCloseSystemWindows(); Intent dock = createHomeDockIntent(); if (dock != null) { int result = ActivityManagerNative.getDefault() .startActivity(null, dock, dock.resolveTypeIfNeeded(mContext.getContentResolver()), null, 0, null, null, 0, true /* onlyIfNeeded*/, false); if (result == IActivityManager.START_RETURN_INTENT_TO_CALLER) { return false; } } int result = ActivityManagerNative.getDefault() .startActivity(null, mHomeIntent, mHomeIntent.resolveTypeIfNeeded(mContext.getContentResolver()), null, 0, null, null, 0, true /* onlyIfNeeded*/, false); if (result == IActivityManager.START_RETURN_INTENT_TO_CALLER) { return false; } } catch (RemoteException ex) { // bummer, the activity manager, which is in this process, is dead } } return true; } public void setCurrentOrientationLw(int newOrientation) { synchronized (mLock) { if (newOrientation != mCurrentAppOrientation) { mCurrentAppOrientation = newOrientation; updateOrientationListenerLp(); } } } public boolean performHapticFeedbackLw(WindowState win, int effectId, boolean always) { if (!always && Settings.System.getInt(mContext.getContentResolver(), Settings.System.HAPTIC_FEEDBACK_ENABLED, 0) == 0) { return false; } switch (effectId) { case HapticFeedbackConstants.LONG_PRESS: mVibrator.vibrate(mLongPressVibePattern, -1); return true; case HapticFeedbackConstants.VIRTUAL_KEY: mVibrator.vibrate(mVirtualKeyVibePattern, -1); return true; case HapticFeedbackConstants.SAFE_MODE_DISABLED: mVibrator.vibrate(mSafeModeDisabledVibePattern, -1); return true; case HapticFeedbackConstants.SAFE_MODE_ENABLED: mVibrator.vibrate(mSafeModeEnabledVibePattern, -1); return true; } return false; } public void keyFeedbackFromInput(KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN && (event.getFlags()&KeyEvent.FLAG_VIRTUAL_HARD_KEY) != 0) { performHapticFeedbackLw(null, HapticFeedbackConstants.VIRTUAL_KEY, false); } } public void screenOnStoppedLw() { if (!mKeyguardMediator.isShowing()) { long curTime = SystemClock.uptimeMillis(); mPowerManager.userActivity(curTime, false, LocalPowerManager.OTHER_EVENT); } } public boolean allowKeyRepeat() { // disable key repeat when screen is off return mScreenOn; } }
false
true
public int interceptKeyTq(RawInputEvent event, boolean screenIsOn) { int result = ACTION_PASS_TO_USER; final boolean isWakeKey = isWakeKeyTq(event); final boolean keyguardShowing = keyguardIsShowingTq(); if (false) { Log.d(TAG, "interceptKeyTq event=" + event + " keycode=" + event.keycode + " screenIsOn=" + screenIsOn + " keyguardShowing=" + keyguardShowing); } if (keyguardShowing) { if (screenIsOn) { // when the screen is on, always give the event to the keyguard result |= ACTION_PASS_TO_USER; } else { // otherwise, don't pass it to the user result &= ~ACTION_PASS_TO_USER; final boolean isKeyDown = (event.type == RawInputEvent.EV_KEY) && (event.value != 0); if (isWakeKey && isKeyDown) { // tell the mediator about a wake key, it may decide to // turn on the screen depending on whether the key is // appropriate. if (!mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(event.keycode) && (event.keycode == KeyEvent.KEYCODE_VOLUME_DOWN || event.keycode == KeyEvent.KEYCODE_VOLUME_UP)) { if (isInCall()) { // if the keyguard didn't wake the device, we are in call, and // it is a volume key, turn on the screen so that the user // can more easily adjust the in call volume. mKeyguardMediator.pokeWakelock(); } else if (isMusicActive()) { // when keyguard is showing and screen off, we need // to handle the volume key for music here handleVolumeKey(AudioManager.STREAM_MUSIC, event.keycode); } } } } } else if (!screenIsOn) { // If we are in-call with screen off and keyguard is not showing, // then handle the volume key ourselves. // This is necessary because the phone app will disable the keyguard // when the proximity sensor is in use. if (isInCall() && event.type == RawInputEvent.EV_KEY && (event.keycode == KeyEvent.KEYCODE_VOLUME_DOWN || event.keycode == KeyEvent.KEYCODE_VOLUME_UP)) { result &= ~ACTION_PASS_TO_USER; handleVolumeKey(AudioManager.STREAM_VOICE_CALL, event.keycode); } if (isWakeKey) { // a wake key has a sole purpose of waking the device; don't pass // it to the user result |= ACTION_POKE_USER_ACTIVITY; result &= ~ACTION_PASS_TO_USER; } } int type = event.type; int code = event.keycode; boolean down = event.value != 0; if (type == RawInputEvent.EV_KEY) { if (code == KeyEvent.KEYCODE_ENDCALL || code == KeyEvent.KEYCODE_POWER) { if (down) { boolean hungUp = false; // key repeats are generated by the window manager, and we don't see them // here, so unless the driver is doing something it shouldn't be, we know // this is the real press event. if (code == KeyEvent.KEYCODE_ENDCALL) { try { ITelephony phoneServ = getPhoneInterface(); if (phoneServ != null) { hungUp = phoneServ.endCall(); } else { Log.w(TAG, "!!! Unable to find ITelephony interface !!!"); } } catch (RemoteException ex) { Log.w(TAG, "ITelephony.endCall() threw RemoteException" + ex); } } if (hungUp || !screenIsOn) { mShouldTurnOffOnKeyUp = false; } else { // only try to turn off the screen if we didn't already hang up mShouldTurnOffOnKeyUp = true; mHandler.postDelayed(mPowerLongPress, ViewConfiguration.getGlobalActionKeyTimeout()); result &= ~ACTION_PASS_TO_USER; } } else { mHandler.removeCallbacks(mPowerLongPress); if (mShouldTurnOffOnKeyUp) { mShouldTurnOffOnKeyUp = false; boolean gohome = (mEndcallBehavior & ENDCALL_HOME) != 0; boolean sleeps = (mEndcallBehavior & ENDCALL_SLEEPS) != 0; if (keyguardShowing || (sleeps && !gohome) || (gohome && !goHome() && sleeps)) { // they must already be on the keyguad or home screen, // go to sleep instead Log.d(TAG, "I'm tired mEndcallBehavior=0x" + Integer.toHexString(mEndcallBehavior)); result &= ~ACTION_POKE_USER_ACTIVITY; result |= ACTION_GO_TO_SLEEP; } result &= ~ACTION_PASS_TO_USER; } } } else if (isMediaKey(code)) { // This key needs to be handled even if the screen is off. // If others need to be handled while it's off, this is a reasonable // pattern to follow. if ((result & ACTION_PASS_TO_USER) == 0) { // Only do this if we would otherwise not pass it to the user. In that // case, the PhoneWindow class will do the same thing, except it will // only do it if the showing app doesn't process the key on its own. KeyEvent keyEvent = new KeyEvent(event.when, event.when, down ? KeyEvent.ACTION_DOWN : KeyEvent.ACTION_UP, code, 0); mBroadcastWakeLock.acquire(); mHandler.post(new PassHeadsetKey(keyEvent)); } } else if (code == KeyEvent.KEYCODE_CALL) { // If an incoming call is ringing, answer it! // (We handle this key here, rather than in the InCallScreen, to make // sure we'll respond to the key even if the InCallScreen hasn't come to // the foreground yet.) // We answer the call on the DOWN event, to agree with // the "fallback" behavior in the InCallScreen. if (down) { try { ITelephony phoneServ = getPhoneInterface(); if (phoneServ != null) { if (phoneServ.isRinging()) { Log.i(TAG, "interceptKeyTq:" + " CALL key-down while ringing: Answer the call!"); phoneServ.answerRingingCall(); // And *don't* pass this key thru to the current activity // (which is presumably the InCallScreen.) result &= ~ACTION_PASS_TO_USER; } } else { Log.w(TAG, "CALL button: Unable to find ITelephony interface"); } } catch (RemoteException ex) { Log.w(TAG, "CALL button: RemoteException from getPhoneInterface()", ex); } } } else if ((code == KeyEvent.KEYCODE_VOLUME_UP) || (code == KeyEvent.KEYCODE_VOLUME_DOWN)) { // If an incoming call is ringing, either VOLUME key means // "silence ringer". We handle these keys here, rather than // in the InCallScreen, to make sure we'll respond to them // even if the InCallScreen hasn't come to the foreground yet. // Look for the DOWN event here, to agree with the "fallback" // behavior in the InCallScreen. if (down) { try { ITelephony phoneServ = getPhoneInterface(); if (phoneServ != null) { if (phoneServ.isRinging()) { Log.i(TAG, "interceptKeyTq:" + " VOLUME key-down while ringing: Silence ringer!"); // Silence the ringer. (It's safe to call this // even if the ringer has already been silenced.) phoneServ.silenceRinger(); // And *don't* pass this key thru to the current activity // (which is probably the InCallScreen.) result &= ~ACTION_PASS_TO_USER; } } else { Log.w(TAG, "VOLUME button: Unable to find ITelephony interface"); } } catch (RemoteException ex) { Log.w(TAG, "VOLUME button: RemoteException from getPhoneInterface()", ex); } } } } return result; }
public int interceptKeyTq(RawInputEvent event, boolean screenIsOn) { int result = ACTION_PASS_TO_USER; final boolean isWakeKey = isWakeKeyTq(event); final boolean keyguardShowing = keyguardIsShowingTq(); if (false) { Log.d(TAG, "interceptKeyTq event=" + event + " keycode=" + event.keycode + " screenIsOn=" + screenIsOn + " keyguardShowing=" + keyguardShowing); } if (keyguardShowing) { if (screenIsOn) { // when the screen is on, always give the event to the keyguard result |= ACTION_PASS_TO_USER; } else { // otherwise, don't pass it to the user result &= ~ACTION_PASS_TO_USER; final boolean isKeyDown = (event.type == RawInputEvent.EV_KEY) && (event.value != 0); if (isWakeKey && isKeyDown) { // tell the mediator about a wake key, it may decide to // turn on the screen depending on whether the key is // appropriate. if (!mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(event.keycode) && (event.keycode == KeyEvent.KEYCODE_VOLUME_DOWN || event.keycode == KeyEvent.KEYCODE_VOLUME_UP)) { if (isInCall()) { // if the keyguard didn't wake the device, we are in call, and // it is a volume key, turn on the screen so that the user // can more easily adjust the in call volume. mKeyguardMediator.pokeWakelock(); } else if (isMusicActive()) { // when keyguard is showing and screen off, we need // to handle the volume key for music here handleVolumeKey(AudioManager.STREAM_MUSIC, event.keycode); } } } } } else if (!screenIsOn) { // If we are in-call with screen off and keyguard is not showing, // then handle the volume key ourselves. // This is necessary because the phone app will disable the keyguard // when the proximity sensor is in use. if (isInCall() && event.type == RawInputEvent.EV_KEY && (event.keycode == KeyEvent.KEYCODE_VOLUME_DOWN || event.keycode == KeyEvent.KEYCODE_VOLUME_UP)) { result &= ~ACTION_PASS_TO_USER; handleVolumeKey(AudioManager.STREAM_VOICE_CALL, event.keycode); } if (isWakeKey) { // a wake key has a sole purpose of waking the device; don't pass // it to the user result |= ACTION_POKE_USER_ACTIVITY; result &= ~ACTION_PASS_TO_USER; } } int type = event.type; int code = event.keycode; boolean down = event.value != 0; if (type == RawInputEvent.EV_KEY) { if (code == KeyEvent.KEYCODE_ENDCALL || code == KeyEvent.KEYCODE_POWER) { if (down) { boolean hungUp = false; // key repeats are generated by the window manager, and we don't see them // here, so unless the driver is doing something it shouldn't be, we know // this is the real press event. ITelephony phoneServ = getPhoneInterface(); if (phoneServ != null) { try { // power button should hang up only when ringing // but not after the call has been answered if (code == KeyEvent.KEYCODE_ENDCALL || phoneServ.isRinging()) { hungUp = phoneServ.endCall(); } } catch (RemoteException ex) { Log.w(TAG, "ITelephony threw RemoteException" + ex); } } else { Log.w(TAG, "!!! Unable to find ITelephony interface !!!"); } // power button should turn off screen in addition to hanging up the phone if ((hungUp && code != KeyEvent.KEYCODE_POWER) || !screenIsOn) { mShouldTurnOffOnKeyUp = false; } else { // only try to turn off the screen if we didn't already hang up mShouldTurnOffOnKeyUp = true; mHandler.postDelayed(mPowerLongPress, ViewConfiguration.getGlobalActionKeyTimeout()); result &= ~ACTION_PASS_TO_USER; } } else { mHandler.removeCallbacks(mPowerLongPress); if (mShouldTurnOffOnKeyUp) { mShouldTurnOffOnKeyUp = false; boolean gohome = (mEndcallBehavior & ENDCALL_HOME) != 0; boolean sleeps = (mEndcallBehavior & ENDCALL_SLEEPS) != 0; if (keyguardShowing || (sleeps && !gohome) || (gohome && !goHome() && sleeps)) { // they must already be on the keyguad or home screen, // go to sleep instead Log.d(TAG, "I'm tired mEndcallBehavior=0x" + Integer.toHexString(mEndcallBehavior)); result &= ~ACTION_POKE_USER_ACTIVITY; result |= ACTION_GO_TO_SLEEP; } result &= ~ACTION_PASS_TO_USER; } } } else if (isMediaKey(code)) { // This key needs to be handled even if the screen is off. // If others need to be handled while it's off, this is a reasonable // pattern to follow. if ((result & ACTION_PASS_TO_USER) == 0) { // Only do this if we would otherwise not pass it to the user. In that // case, the PhoneWindow class will do the same thing, except it will // only do it if the showing app doesn't process the key on its own. KeyEvent keyEvent = new KeyEvent(event.when, event.when, down ? KeyEvent.ACTION_DOWN : KeyEvent.ACTION_UP, code, 0); mBroadcastWakeLock.acquire(); mHandler.post(new PassHeadsetKey(keyEvent)); } } else if (code == KeyEvent.KEYCODE_CALL) { // If an incoming call is ringing, answer it! // (We handle this key here, rather than in the InCallScreen, to make // sure we'll respond to the key even if the InCallScreen hasn't come to // the foreground yet.) // We answer the call on the DOWN event, to agree with // the "fallback" behavior in the InCallScreen. if (down) { try { ITelephony phoneServ = getPhoneInterface(); if (phoneServ != null) { if (phoneServ.isRinging()) { Log.i(TAG, "interceptKeyTq:" + " CALL key-down while ringing: Answer the call!"); phoneServ.answerRingingCall(); // And *don't* pass this key thru to the current activity // (which is presumably the InCallScreen.) result &= ~ACTION_PASS_TO_USER; } } else { Log.w(TAG, "CALL button: Unable to find ITelephony interface"); } } catch (RemoteException ex) { Log.w(TAG, "CALL button: RemoteException from getPhoneInterface()", ex); } } } else if ((code == KeyEvent.KEYCODE_VOLUME_UP) || (code == KeyEvent.KEYCODE_VOLUME_DOWN)) { // If an incoming call is ringing, either VOLUME key means // "silence ringer". We handle these keys here, rather than // in the InCallScreen, to make sure we'll respond to them // even if the InCallScreen hasn't come to the foreground yet. // Look for the DOWN event here, to agree with the "fallback" // behavior in the InCallScreen. if (down) { try { ITelephony phoneServ = getPhoneInterface(); if (phoneServ != null) { if (phoneServ.isRinging()) { Log.i(TAG, "interceptKeyTq:" + " VOLUME key-down while ringing: Silence ringer!"); // Silence the ringer. (It's safe to call this // even if the ringer has already been silenced.) phoneServ.silenceRinger(); // And *don't* pass this key thru to the current activity // (which is probably the InCallScreen.) result &= ~ACTION_PASS_TO_USER; } } else { Log.w(TAG, "VOLUME button: Unable to find ITelephony interface"); } } catch (RemoteException ex) { Log.w(TAG, "VOLUME button: RemoteException from getPhoneInterface()", ex); } } } } return result; }
diff --git a/messages-core/src/main/java/org/ybiquitous/messages/Utils.java b/messages-core/src/main/java/org/ybiquitous/messages/Utils.java index 1010256..5fb7c49 100644 --- a/messages-core/src/main/java/org/ybiquitous/messages/Utils.java +++ b/messages-core/src/main/java/org/ybiquitous/messages/Utils.java @@ -1,42 +1,42 @@ package org.ybiquitous.messages; import javax.annotation.Nonnull; import javax.annotation.Nullable; public final class Utils { public static @Nonnull <T> T notNull( - @Nullable T obj, + @Nonnull T obj, @Nullable String name) throws NullPointerException { if (obj == null) { if (name == null) { throw new NullPointerException(); } else { throw new NullPointerException(name + " is required"); } } return obj; } public static @Nonnull <T> T notNullOrElse( @Nullable T obj, @Nonnull T defaultValue) throws NullPointerException { return (obj != null) ? obj : notNull(defaultValue, "defaultValue"); } public static @Nonnull <T> T notNullOrElse( @Nullable T obj, @Nonnull Factory<T> defaultValueFactory) throws NullPointerException { return (obj != null) ? obj : notNull(defaultValueFactory, "defaultValueFactory").get(); } public static boolean isEmpty(@Nullable String str) { return (str == null || str.isEmpty() || str.trim().isEmpty()); } private Utils() { } }
true
true
public static @Nonnull <T> T notNull( @Nullable T obj, @Nullable String name) throws NullPointerException { if (obj == null) { if (name == null) { throw new NullPointerException(); } else { throw new NullPointerException(name + " is required"); } } return obj; }
public static @Nonnull <T> T notNull( @Nonnull T obj, @Nullable String name) throws NullPointerException { if (obj == null) { if (name == null) { throw new NullPointerException(); } else { throw new NullPointerException(name + " is required"); } } return obj; }
diff --git a/openejb/tomee/tomee-webapp/src/main/java/org/apache/tomee/webapp/JsonExecutor.java b/openejb/tomee/tomee-webapp/src/main/java/org/apache/tomee/webapp/JsonExecutor.java index e19a0b4ee..bc1aba0be 100644 --- a/openejb/tomee/tomee-webapp/src/main/java/org/apache/tomee/webapp/JsonExecutor.java +++ b/openejb/tomee/tomee-webapp/src/main/java/org/apache/tomee/webapp/JsonExecutor.java @@ -1,50 +1,51 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomee.webapp; import com.google.gson.Gson; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; public class JsonExecutor { private JsonExecutor() { //NO INSTANCE } public interface Executor { void call(Map<String, Object> json) throws Exception; } public static void execute(final HttpServletResponse resp, final Executor executor) { try { final Map<String, Object> result = new HashMap<String, Object>(); executor.call(result); resp.setContentType("application/json"); resp.setCharacterEncoding("UTF-8"); resp.getWriter().write(new Gson().toJson(result)); } catch (Exception e) { + //this will redirect the result to the ErrorServlet throw new TomeeException(e); } } }
true
true
public static void execute(final HttpServletResponse resp, final Executor executor) { try { final Map<String, Object> result = new HashMap<String, Object>(); executor.call(result); resp.setContentType("application/json"); resp.setCharacterEncoding("UTF-8"); resp.getWriter().write(new Gson().toJson(result)); } catch (Exception e) { throw new TomeeException(e); } }
public static void execute(final HttpServletResponse resp, final Executor executor) { try { final Map<String, Object> result = new HashMap<String, Object>(); executor.call(result); resp.setContentType("application/json"); resp.setCharacterEncoding("UTF-8"); resp.getWriter().write(new Gson().toJson(result)); } catch (Exception e) { //this will redirect the result to the ErrorServlet throw new TomeeException(e); } }
diff --git a/backend/transparent/core/Core.java b/backend/transparent/core/Core.java index 4071fde..1910de8 100644 --- a/backend/transparent/core/Core.java +++ b/backend/transparent/core/Core.java @@ -1,844 +1,846 @@ package transparent.core; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.math.BigInteger; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.IntField; import org.apache.lucene.document.StoredField; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.Term; import org.apache.lucene.queryparser.flexible.core.QueryNodeException; import org.apache.lucene.queryparser.flexible.standard.StandardQueryParser; import org.apache.lucene.queryparser.flexible.standard.config.StandardQueryConfigHandler.Operator; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.store.RAMDirectory; import org.apache.lucene.util.Version; import org.fusesource.jansi.AnsiConsole; import org.simpleframework.http.core.ContainerServer; import org.simpleframework.transport.connect.Connection; import org.simpleframework.transport.connect.SocketConnection; import transparent.core.database.Database; import transparent.core.database.MariaDBDriver; public class Core { public static final byte PRODUCT_LIST_REQUEST = 0; public static final byte PRODUCT_INFO_REQUEST = 1; public static final String NEWLINE = System.getProperty("line.separator"); private static final String SEED_KEY = "seed"; private static final String MODULE_COUNT = "modules.count"; private static final String RUNNING_TASKS = "running"; private static final String QUEUED_TASKS = "queued"; private static final String SCRIPT_FLAG = "--script"; private static final String HELP_FLAG = "--help"; private static final String PRODUCT_NAME_FIELD = "name"; private static final String PRODUCT_ID_FIELD = "id"; private static final String ROW_ID_FIELD = "row"; private static final String PRICE_FIELD = "price"; private static final int THREAD_POOL_SIZE = 64; private static final int SEARCH_LIMIT = 256; private static final int HTTP_SERVER_PORT = 16317; private static final String DEFAULT_SCRIPT = "rc.transparent"; private static final Sandbox sandbox = new NoSandbox(); private static Database database; private static ScheduledExecutorService dispatcher = Executors.newScheduledThreadPool(THREAD_POOL_SIZE); private static ReentrantLock tasksLock = new ReentrantLock(); private static long seed = 0; /* needed to print unsigned 64-bit long values */ private static final BigInteger B64 = BigInteger.ZERO.setBit(64); /* data structures to keep track of modules */ private static ReentrantLock modulesLock = new ReentrantLock(); private static ConcurrentHashMap<Long, Module> modules = new ConcurrentHashMap<Long, Module>(); /* represents the list encoding of modules in the database */ private static ArrayList<Module> moduleList = new ArrayList<Module>(); /* represents the list encoding of tasks in the database */ private static ArrayList<Task> queuedList = new ArrayList<Task>(); private static ArrayList<Task> runningList = new ArrayList<Task>(); /* for product name search indexing */ private static IndexWriter indexWriter = null; private static IndexSearcher searcher = null; private static StandardQueryParser parser = null; public static InetAddress FRONTEND_ADDRESS = null; public static String toUnsignedString(long value) { if (value >= 0) return String.valueOf(value); return BigInteger.valueOf(value).add(B64).toString(); } /** * Bit-shift random number generator with period 2^64 - 1. * @see http://www.javamex.com/tutorials/random_numbers/xorshift.shtml */ public static long random() { seed ^= (seed << 21); seed ^= (seed >>> 35); seed ^= (seed << 4); if (database != null && !database.setMetadata("seed", toUnsignedString(seed))) Console.printWarning("Core", "random", "Cannot save new seed."); return seed; } private static void loadSeed() { if (database == null) { Console.printError("Core", "loadSeed", "No database available. Generating temporary seed..."); while (seed == 0) seed = System.nanoTime(); return; } String seedValue = database.getMetadata(SEED_KEY); if (seedValue == null) { Console.printWarning("Core", "loadSeed", "No stored seed, regenerating..."); while (seed == 0) seed = System.nanoTime(); database.setMetadata(SEED_KEY, Long.toString(seed)); } else { try { seed = Long.parseLong(seedValue); } catch (NumberFormatException e) { Console.printWarning("Core", "loadSeed", "Unable to read seed, regenerating..."); while (seed == 0) seed = System.nanoTime(); database.setMetadata(SEED_KEY, Long.toString(seed)); } } Console.flush(); } public static void execute(Runnable task) { dispatcher.execute(task); } public static void addToIndex(String productName, ProductID id, int price) { if (indexWriter == null) return; Document doc = new Document(); TextField nameField = new TextField( PRODUCT_NAME_FIELD, productName, Field.Store.YES); TextField productIdField = new TextField( PRODUCT_ID_FIELD, id.getModuleProductId(), Field.Store.YES); StoredField rowField = new StoredField( ROW_ID_FIELD, id.getRowId()); IntField priceField = new IntField( PRICE_FIELD, price, Field.Store.YES); doc.add(nameField); doc.add(productIdField); doc.add(rowField); doc.add(priceField); /* TODO: only the lowest price of a product should be kept */ try { indexWriter.updateDocument(new Term(PRODUCT_ID_FIELD, id.getModuleProductId()), doc); } catch (IOException e) { Console.printError("Core", "addToIndex", "Error adding " + "product name to search index.", e); } } private static HashSet<Character> special = new HashSet<Character>(Arrays.asList( '&', '|', '!', '(', ')', '{', '}', '[', ']', '^', '"', '~', ':', '\\', '/')); private static String sanitize(String search) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < search.length(); i++) { if (special.contains(search.charAt(i))) builder.append('\\'); builder.append(search.charAt(i)); } return builder.toString(); } public static Iterator<ProductID> searchProductName( String term, String sortby, boolean descending) { Query query = null; try { query = parser.parse(term, PRODUCT_NAME_FIELD); } catch (QueryNodeException e) { try { query = parser.parse(sanitize(term), PRODUCT_NAME_FIELD); } catch (QueryNodeException e2) { Console.printError("Core", "searchProductName", "Unable to parse search query.", e2); return null; } } try { Sort sort = new Sort(); if (sortby != null && sortby.equals("price")) sort = new Sort(new SortField(PRICE_FIELD, SortField.Type.INT, descending)); return new SearchIterator(query, sort); } catch (IOException e) { Console.printError("Core", "searchProductName", "Error occurred during search.", e); return null; } } public static boolean loadModules() { if (database == null) { Console.printError("Core", "loadModules", "No database available. No modules loaded."); return false; } modulesLock.lock(); try { Console.println("Loading modules..."); String moduleCountString = database.getMetadata(MODULE_COUNT); if (moduleCountString == null) { Console.printError("Core", "loadModules", "No modules stored."); return false; } int moduleCount; try { moduleCount = Integer.parseInt(moduleCountString); } catch (NumberFormatException e) { Console.printError("Core", "loadModules", "Could not parse module count."); return false; } Console.println("Found " + moduleCount + " modules."); moduleList.ensureCapacity(moduleCount); for (int i = 0; i < moduleCount; i++) { Module module = Module.load(database, i); if (module == null) { Console.printError("Core", "loadModules", "Error loading module at index " + i + "."); return false; } Console.println("Loaded module '" + module.getModuleName() + "' (id: " + module.getIdString() + ")"); Module old = modules.put(module.getId(), module); if (old != null) { Console.printError("Core", "loadModules", "Module with id " + old.getIdString() + " (name: '" + old.getModuleName() + "')" + " already exists. Skipping..."); modules.put(module.getId(), old); continue; } moduleList.add(module); } } finally { modulesLock.unlock(); } Console.println("Done loading modules."); return true; } public static boolean addModule(Module module) { modulesLock.lock(); try { Module old = modules.put(module.getId(), module); if (old != null) { modules.put(old.getId(), old); Console.printError("Core", "addModule", "Module with id " + module.getIdString() + " already exists. " + "(name: '" + old.getModuleName() + "')"); return false; } else { moduleList.add(module); return true; } } finally { modulesLock.unlock(); } } public static boolean removeModule(Module module) { modulesLock.lock(); try { int index = module.getIndex(); if (modules.remove(module.getId()) == null || index == -1) { Console.printWarning("Core", "removeModule", "Specified module does not exist."); return false; } /* move the last module into the removed module's place */ if (moduleList.isEmpty()) return true; Module last = moduleList.remove(moduleList.size() - 1); module.setIndex(-1); if (index != moduleList.size()) { moduleList.set(index, last); last.setIndex(index); } return true; } finally { modulesLock.unlock(); } } public static boolean saveModules() { modulesLock.lock(); try { boolean success = true; for (int index = 0; index < moduleList.size(); index++) { Module module = moduleList.get(index); if ((module.getIndex() == -1 || module.getPersistentIndex() != module.getIndex()) && !module.save(database, index)) { Console.printError("Core", "saveModules", "Unable to save module '" + module.getModuleName() + "' (id: " + module.getIdString() + ") at position " + index + "."); moduleList.set(index, null); module.setIndex(-1); success = false; } else { moduleList.set(index, module); } } if (database == null) success = false; else success &= database.setMetadata( MODULE_COUNT, Integer.toString(moduleList.size())); return success; } finally { modulesLock.unlock(); } } private static boolean loadQueue(String queue, ArrayList<Task> list) { int taskCount; try { String taskCountString = database.getMetadata(queue + ".count"); if (taskCountString == null) { Console.printError("Core", "loadQueue", "No tasks stored."); return false; } taskCount = Integer.parseInt(taskCountString); } catch (NumberFormatException e) { Console.printError("Core", "loadQueue", "Unable to parse task count."); return false; } list.ensureCapacity(taskCount); for (int i = 0; i < taskCount; i++) { if (list.size() > i && list.get(i) != null) { Console.printError("Core", "loadQueue", "A task already exists at index " + i + "."); continue; } Task task = Task.load(database, queue, i); if (task != null) list.add(task); } return true; } private static boolean saveQueue( boolean isRunning, ArrayList<Task> list) { String queue = getQueueName(isRunning); boolean success = true; for (int index = 0; index < list.size(); index++) { Task task = list.get(index); if (!task.save(database, isRunning, index)) { Module module = task.getModule(); Console.printError("Core", "saveQueue", "Unable to save task (module name: '" + module.getModuleName() + "', id: " + module.getIdString() + ") at position " + index + "."); task.setIndex(-1); list.set(index, null); success = false; } else { list.set(index, task); } } if (database == null) success = false; else success &= database.setMetadata( queue + ".count", Integer.toString(list.size())); return success; } public static boolean loadQueue() { if (database == null) { Console.printError("Core", "loadQueue", "No database available. No tasks loaded."); return false; } tasksLock.lock(); try { boolean success = (loadQueue("running", runningList) && loadQueue("queued", queuedList)); /* dispatch all tasks in the queue */ for (Task task : runningList) { task.setRunning(true); dispatchTask(task); } for (Task task : queuedList) dispatchTask(task); return success; } finally { tasksLock.unlock(); } } public static boolean saveQueue() { if (database == null) { Console.printError("Core", "loadQueue", "No database available. No tasks loaded."); return false; } tasksLock.lock(); try { return (saveQueue(true, runningList) && saveQueue(false, queuedList)); } finally { tasksLock.unlock(); } } public static String getQueueName(boolean isRunning) { return (isRunning ? RUNNING_TASKS : QUEUED_TASKS); } public static Module getModule(long moduleId) { return modules.get(moduleId); } public static List<Module> getModules() { /* to ensure we get a thread-safe snapshot of the current modules */ modulesLock.lock(); try { return new ArrayList<Module>(modules.values()); } finally { modulesLock.unlock(); } } public static int getModuleCount() { return modules.size(); } public static int getTaskCount() { modulesLock.lock(); try { return queuedList.size() + runningList.size(); } finally { modulesLock.unlock(); } } public static List<Task> getQueuedTasks() { /* to ensure we get a thread-safe snapshot of the queued tasks */ tasksLock.lock(); try { return new ArrayList<Task>(queuedList); } finally { tasksLock.unlock(); } } public static List<Task> getRunningTasks() { /* to ensure we get a thread-safe snapshot of the running tasks */ tasksLock.lock(); try { return new ArrayList<Task>(runningList); } finally { tasksLock.unlock(); } } public static Database getDatabase() { return database; } public static Sandbox getSandbox() { return sandbox; } public static void queueTask(Task task) { if (task.isRunning() || task.getIndex() != -1) return; tasksLock.lock(); try { task.setRunning(false); task.setIndex(queuedList.size()); queuedList.add(task); dispatchTask(task); } finally { tasksLock.unlock(); } } public static void startTask(Task task) { if (task.isRunning()) return; tasksLock.lock(); try { int index = task.getIndex(); if (index < 0 || index >= queuedList.size()) return; queuedList.remove(index); task.setRunning(true); task.setIndex(runningList.size()); runningList.add(task); if (!saveQueue()) Console.printError("Core", "startTask", "Unable to save tasks."); } finally { tasksLock.unlock(); } } private static void removeTask(ArrayList<Task> tasks, Task task) { int index = task.getIndex(); if (index < 0 || index >= tasks.size()) return; tasks.remove(index); task.setRunning(false); /* move the last module into the removed module's place */ if (tasks.isEmpty()) return; Task last = tasks.remove(tasks.size() - 1); task.setIndex(-1); if (index != tasks.size()) { tasks.set(index, last); last.setIndex(index); } } public static void stopTask(Task task, boolean cancelRescheduling) { tasksLock.lock(); try { if (task.isRunning()) removeTask(runningList, task); else removeTask(queuedList, task); Task.removeTask(task.getId()); /* interrupt the thread if it is running */ ScheduledFuture<Object> thread = task.getFuture(); task.stop(cancelRescheduling); thread.cancel(true); } finally { tasksLock.unlock(); } } private static void dispatchTask(Task task) { long delta = task.getTime() - System.currentTimeMillis(); ScheduledFuture<Object> future = dispatcher.schedule(task, Math.max(delta, 0), TimeUnit.MILLISECONDS); task.setFuture(future); } public static void main(String[] args) { AnsiConsole.systemInstall(); /* parse argument flags */ String script = DEFAULT_SCRIPT; for (int i = 0; i < args.length; i++) { if (args[i].equals(SCRIPT_FLAG)) { if (i + 1 < args.length) { i++; script = args[i]; } else { Console.printError("Core", "main", "Unspecified script filepath."); } } else if (args[i].equals(HELP_FLAG)) { /* TODO: implement this */ } else { Console.printError("Core", "main", "Unrecognized flag '" + args[i] + "'."); } } try { database = new MariaDBDriver(); } catch (Exception e) { Console.printError("Core", "main", "Cannot " + "connect to database.", e); } /* load random number generator seed */ loadSeed(); /* load search index for product names */ Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_42); IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_42, analyzer); Directory directory = null; try { File index = new File("index"); if (!index.exists()) { if (!index.mkdir()) { Console.printError("Core", "main", "Unable to create directory 'index'."); } else { directory = FSDirectory.open(index); indexWriter = new IndexWriter(directory, config); searcher = new IndexSearcher(DirectoryReader.open(indexWriter, false)); } } else if (!index.isDirectory()) { Console.printError("Core", "main", "A file named 'index' already exists."); } else { directory = FSDirectory.open(index); indexWriter = new IndexWriter(directory, config); searcher = new IndexSearcher(DirectoryReader.open(indexWriter, false)); } } catch (IOException e) { Console.printError("Core", "main", "Unable to open " + "directory 'index'. Using memory index...", e); try { Directory indexDirectory = new RAMDirectory(); indexWriter = new IndexWriter(indexDirectory, config); searcher = new IndexSearcher(DirectoryReader.open(indexWriter, false)); } catch (IOException e2) { Console.printError("Core", "main", "Unable to " + "create memory index.", e2); } } parser = new StandardQueryParser(analyzer); parser.setDefaultOperator(Operator.AND); /* load the script engine */ boolean consoleReady = Console.initConsole(); if (!consoleReady) Console.printError("Core", "main", "Unable to initialize script engine."); /* run the user-specified script */ if (consoleReady && script != null) { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(script)); String line; while ((line = reader.readLine()) != null) { if (!Console.parseCommand(line)) return; } } catch (FileNotFoundException e) { Console.printError("Core", "main", "Script file '" + script + "' not found."); } catch (IOException e) { Console.printError("Core", "main", "Error occured" + " while reading script.", e); } finally { try { if (reader != null) reader.close(); } catch (IOException e) { } } } /* find the front-end server */ try { FRONTEND_ADDRESS = InetAddress.getByName("54.244.112.184"); } catch (UnknownHostException e) { Console.printError("Core", "main", "Cannot find front-end server." + " Queries will not be processed."); } /* start the back-end HTTP server */ Connection connection = null; try { connection = new SocketConnection(new ContainerServer(new Server())); connection.connect(new InetSocketAddress(HTTP_SERVER_PORT)); } catch (IOException e) { Console.printError("Core", "main", "Cannot start HTTP server." + " Queries will not be processed."); } /* start the main loop */ - dispatcher.scheduleWithFixedDelay( - new BackgroundWorker(), 10, 10, TimeUnit.SECONDS); + BackgroundWorker worker = new BackgroundWorker(); + ScheduledFuture<?> future = + dispatcher.scheduleWithFixedDelay(worker, 10, 10, TimeUnit.SECONDS); if (consoleReady) Console.runConsole(); /* tell all tasks to end */ + future.cancel(true); tasksLock.lock(); try { for (Task task : runningList) { if (task != null) { task.stop(true); if (task.getFuture() != null) task.getFuture().cancel(true); } } } finally { tasksLock.unlock(); } dispatcher.shutdown(); /* shutdown the HTTP server */ try { if (connection != null) connection.close(); } catch (IOException e) { Console.printError("Core", "main", "Unable " + "to shutdown HTTP server.", e); } /* close the search index */ try { if (indexWriter != null) indexWriter.close(); if (directory != null) directory.close(); } catch (IOException e) { Console.printError("Core", "main", "Unable " + "to close search index.", e); } } private static class SearchIterator implements Iterator<ProductID> { private ScoreDoc[] results; private Query query; private Sort sort; private int index; public SearchIterator(Query query, Sort sort) throws IOException { this.query = query; this.sort = sort; this.index = 0; this.results = searcher.search(query, SEARCH_LIMIT, sort).scoreDocs; if (results.length == 0) results = null; } @Override public boolean hasNext() { return (results != null); } @Override public ProductID next() { if (results == null) throw new NoSuchElementException(); ProductID product = null; try { Document doc = searcher.doc(results[index].doc); String moduleProductId = doc.getField(PRODUCT_ID_FIELD).stringValue(); int row = doc.getField(ROW_ID_FIELD).numericValue().intValue(); product = new ProductID(row, moduleProductId); } catch (IOException e) { } index++; if (index == results.length) { try { results = searcher.searchAfter( results[index - 1], query, SEARCH_LIMIT, sort).scoreDocs; } catch (IOException e) { results = null; } index = 0; if (results.length == 0) results = null; } return product; } @Override public void remove() { throw new UnsupportedOperationException(); } } private static class BackgroundWorker implements Runnable { @Override public void run() { try { if (indexWriter != null) searcher = new IndexSearcher(DirectoryReader.open(indexWriter, false)); } catch (IOException e) { Console.printError("Core", "addToIndex", "Error refreshing " + " search index.", e); } saveQueue(); } } }
false
true
public static void main(String[] args) { AnsiConsole.systemInstall(); /* parse argument flags */ String script = DEFAULT_SCRIPT; for (int i = 0; i < args.length; i++) { if (args[i].equals(SCRIPT_FLAG)) { if (i + 1 < args.length) { i++; script = args[i]; } else { Console.printError("Core", "main", "Unspecified script filepath."); } } else if (args[i].equals(HELP_FLAG)) { /* TODO: implement this */ } else { Console.printError("Core", "main", "Unrecognized flag '" + args[i] + "'."); } } try { database = new MariaDBDriver(); } catch (Exception e) { Console.printError("Core", "main", "Cannot " + "connect to database.", e); } /* load random number generator seed */ loadSeed(); /* load search index for product names */ Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_42); IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_42, analyzer); Directory directory = null; try { File index = new File("index"); if (!index.exists()) { if (!index.mkdir()) { Console.printError("Core", "main", "Unable to create directory 'index'."); } else { directory = FSDirectory.open(index); indexWriter = new IndexWriter(directory, config); searcher = new IndexSearcher(DirectoryReader.open(indexWriter, false)); } } else if (!index.isDirectory()) { Console.printError("Core", "main", "A file named 'index' already exists."); } else { directory = FSDirectory.open(index); indexWriter = new IndexWriter(directory, config); searcher = new IndexSearcher(DirectoryReader.open(indexWriter, false)); } } catch (IOException e) { Console.printError("Core", "main", "Unable to open " + "directory 'index'. Using memory index...", e); try { Directory indexDirectory = new RAMDirectory(); indexWriter = new IndexWriter(indexDirectory, config); searcher = new IndexSearcher(DirectoryReader.open(indexWriter, false)); } catch (IOException e2) { Console.printError("Core", "main", "Unable to " + "create memory index.", e2); } } parser = new StandardQueryParser(analyzer); parser.setDefaultOperator(Operator.AND); /* load the script engine */ boolean consoleReady = Console.initConsole(); if (!consoleReady) Console.printError("Core", "main", "Unable to initialize script engine."); /* run the user-specified script */ if (consoleReady && script != null) { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(script)); String line; while ((line = reader.readLine()) != null) { if (!Console.parseCommand(line)) return; } } catch (FileNotFoundException e) { Console.printError("Core", "main", "Script file '" + script + "' not found."); } catch (IOException e) { Console.printError("Core", "main", "Error occured" + " while reading script.", e); } finally { try { if (reader != null) reader.close(); } catch (IOException e) { } } } /* find the front-end server */ try { FRONTEND_ADDRESS = InetAddress.getByName("54.244.112.184"); } catch (UnknownHostException e) { Console.printError("Core", "main", "Cannot find front-end server." + " Queries will not be processed."); } /* start the back-end HTTP server */ Connection connection = null; try { connection = new SocketConnection(new ContainerServer(new Server())); connection.connect(new InetSocketAddress(HTTP_SERVER_PORT)); } catch (IOException e) { Console.printError("Core", "main", "Cannot start HTTP server." + " Queries will not be processed."); } /* start the main loop */ dispatcher.scheduleWithFixedDelay( new BackgroundWorker(), 10, 10, TimeUnit.SECONDS); if (consoleReady) Console.runConsole(); /* tell all tasks to end */ tasksLock.lock(); try { for (Task task : runningList) { if (task != null) { task.stop(true); if (task.getFuture() != null) task.getFuture().cancel(true); } } } finally { tasksLock.unlock(); } dispatcher.shutdown(); /* shutdown the HTTP server */ try { if (connection != null) connection.close(); } catch (IOException e) { Console.printError("Core", "main", "Unable " + "to shutdown HTTP server.", e); } /* close the search index */ try { if (indexWriter != null) indexWriter.close(); if (directory != null) directory.close(); } catch (IOException e) { Console.printError("Core", "main", "Unable " + "to close search index.", e); } }
public static void main(String[] args) { AnsiConsole.systemInstall(); /* parse argument flags */ String script = DEFAULT_SCRIPT; for (int i = 0; i < args.length; i++) { if (args[i].equals(SCRIPT_FLAG)) { if (i + 1 < args.length) { i++; script = args[i]; } else { Console.printError("Core", "main", "Unspecified script filepath."); } } else if (args[i].equals(HELP_FLAG)) { /* TODO: implement this */ } else { Console.printError("Core", "main", "Unrecognized flag '" + args[i] + "'."); } } try { database = new MariaDBDriver(); } catch (Exception e) { Console.printError("Core", "main", "Cannot " + "connect to database.", e); } /* load random number generator seed */ loadSeed(); /* load search index for product names */ Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_42); IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_42, analyzer); Directory directory = null; try { File index = new File("index"); if (!index.exists()) { if (!index.mkdir()) { Console.printError("Core", "main", "Unable to create directory 'index'."); } else { directory = FSDirectory.open(index); indexWriter = new IndexWriter(directory, config); searcher = new IndexSearcher(DirectoryReader.open(indexWriter, false)); } } else if (!index.isDirectory()) { Console.printError("Core", "main", "A file named 'index' already exists."); } else { directory = FSDirectory.open(index); indexWriter = new IndexWriter(directory, config); searcher = new IndexSearcher(DirectoryReader.open(indexWriter, false)); } } catch (IOException e) { Console.printError("Core", "main", "Unable to open " + "directory 'index'. Using memory index...", e); try { Directory indexDirectory = new RAMDirectory(); indexWriter = new IndexWriter(indexDirectory, config); searcher = new IndexSearcher(DirectoryReader.open(indexWriter, false)); } catch (IOException e2) { Console.printError("Core", "main", "Unable to " + "create memory index.", e2); } } parser = new StandardQueryParser(analyzer); parser.setDefaultOperator(Operator.AND); /* load the script engine */ boolean consoleReady = Console.initConsole(); if (!consoleReady) Console.printError("Core", "main", "Unable to initialize script engine."); /* run the user-specified script */ if (consoleReady && script != null) { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(script)); String line; while ((line = reader.readLine()) != null) { if (!Console.parseCommand(line)) return; } } catch (FileNotFoundException e) { Console.printError("Core", "main", "Script file '" + script + "' not found."); } catch (IOException e) { Console.printError("Core", "main", "Error occured" + " while reading script.", e); } finally { try { if (reader != null) reader.close(); } catch (IOException e) { } } } /* find the front-end server */ try { FRONTEND_ADDRESS = InetAddress.getByName("54.244.112.184"); } catch (UnknownHostException e) { Console.printError("Core", "main", "Cannot find front-end server." + " Queries will not be processed."); } /* start the back-end HTTP server */ Connection connection = null; try { connection = new SocketConnection(new ContainerServer(new Server())); connection.connect(new InetSocketAddress(HTTP_SERVER_PORT)); } catch (IOException e) { Console.printError("Core", "main", "Cannot start HTTP server." + " Queries will not be processed."); } /* start the main loop */ BackgroundWorker worker = new BackgroundWorker(); ScheduledFuture<?> future = dispatcher.scheduleWithFixedDelay(worker, 10, 10, TimeUnit.SECONDS); if (consoleReady) Console.runConsole(); /* tell all tasks to end */ future.cancel(true); tasksLock.lock(); try { for (Task task : runningList) { if (task != null) { task.stop(true); if (task.getFuture() != null) task.getFuture().cancel(true); } } } finally { tasksLock.unlock(); } dispatcher.shutdown(); /* shutdown the HTTP server */ try { if (connection != null) connection.close(); } catch (IOException e) { Console.printError("Core", "main", "Unable " + "to shutdown HTTP server.", e); } /* close the search index */ try { if (indexWriter != null) indexWriter.close(); if (directory != null) directory.close(); } catch (IOException e) { Console.printError("Core", "main", "Unable " + "to close search index.", e); } }
diff --git a/src/org/ohmage/triggers/types/location/LocTrigSettingsActivity.java b/src/org/ohmage/triggers/types/location/LocTrigSettingsActivity.java index b18b40a..d230f83 100644 --- a/src/org/ohmage/triggers/types/location/LocTrigSettingsActivity.java +++ b/src/org/ohmage/triggers/types/location/LocTrigSettingsActivity.java @@ -1,479 +1,479 @@ /******************************************************************************* * Copyright 2011 The Regents of the University of California * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package org.ohmage.triggers.types.location; import java.util.HashSet; import java.util.LinkedList; import org.ohmage.R; import org.ohmage.db.DbHelper; import org.ohmage.db.Models.Campaign; import org.ohmage.triggers.config.TrigUserConfig; import org.ohmage.triggers.utils.TrigTextInput; import android.app.AlertDialog; import android.app.Dialog; import android.app.ListActivity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.view.View.OnClickListener; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import android.widget.AdapterView.AdapterContextMenuInfo; /* * Location triggers settings activity. * Displays the list of categories (places). The number of locations * under each category as well the number of surveys associated with * each place are also displayed. Provides options to manage the * categories (add, delete, rename and modify surveys) */ public class LocTrigSettingsActivity extends ListActivity implements OnClickListener, TextWatcher { private static final String DEBUG_TAG = "LocationTrigger"; /* Menu ids */ private static final int MENU_DELETE_CATEG = Menu.FIRST; private static final int MENU_RENAME_CATEG = Menu.FIRST + 1; private static final int DIALOG_DELETE = 0; private static final int DIALOG_RENAME = 1; private static final String KEY_SAVE_DIALOG_CATEG = "dialog_category"; private static final String KEY_SAVE_DIALOG_TEXT = "dialog_text"; public static final String KEY_ADMIN_MODE = "admin_mode"; //Db instance private LocTrigDB mDb; //The list cursor private Cursor mCursor; private HashSet<String> mCategNames; private final LocationTrigger mLocTrigger = new LocationTrigger(); private int mDialogCategId = -1; private String mDialogText = null; private boolean mAdminMode = false; @Override public void onCreate(Bundle savedInstanceState) { Log.i(DEBUG_TAG, "Main: onCreate"); super.onCreate(savedInstanceState); setContentView(R.layout.trigger_loc_settings); Button bAdd = (Button) findViewById(R.id.trigger_button_add_categ); bAdd.setOnClickListener(this); bAdd.setEnabled(false); EditText et = (EditText) findViewById(R.id.trigger_text_add_categ); et.addTextChangedListener(this); mAdminMode = getIntent().getBooleanExtra(KEY_ADMIN_MODE, false); if(!mAdminMode && !TrigUserConfig.editLocationTriggerPlace) { et.setEnabled(false); et.setClickable(false); et.setFocusable(false); } mDb = new LocTrigDB(this); mDb.open(); mCategNames = new HashSet<String>(); populateCategoryNames(); initializeList(); registerForContextMenu(getListView()); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(KEY_SAVE_DIALOG_CATEG, mDialogCategId); if(mDialogText != null && mDialogText.length() != 0) { outState.putString(KEY_SAVE_DIALOG_TEXT, mDialogText); } } @Override protected void onRestoreInstanceState(Bundle state) { super.onRestoreInstanceState(state); mDialogCategId = state.getInt(KEY_SAVE_DIALOG_CATEG, -1); mDialogText = state.getString(KEY_SAVE_DIALOG_TEXT); } @Override public void onDestroy() { Log.i(DEBUG_TAG, "Main: onDestroy"); mCategNames.clear(); mCursor.close(); mDb.close(); System.gc(); super.onDestroy(); } private void populateCategoryNames() { mCategNames.clear(); Cursor c = mDb.getAllCategories(); if(c.moveToFirst()) { do { String name = c.getString( c.getColumnIndexOrThrow(LocTrigDB.KEY_NAME)); mCategNames.add(name.toLowerCase()); } while(c.moveToNext()); } c.close(); } private boolean checkIfCategNameValid(String name) { if(name == null) { return false; } String text = name.trim(); if(text.length() == 0 || mCategNames.contains(text.toLowerCase())) { return false; } return true; } private void updateTriggerDescriptions(String oldName, String newName) { LinkedList<Integer> trigIds = new LinkedList<Integer>(); DbHelper dbHelper = new DbHelper(this); for (Campaign c : dbHelper.getReadyCampaigns()) { trigIds.addAll(mLocTrigger.getAllActiveTriggerIds(this, c.mUrn)); } for(int trigId : trigIds) { LocTrigDesc desc = new LocTrigDesc(); desc.loadString(mLocTrigger.getTrigger(this, trigId)); if(desc.getLocation().equals(oldName)) { desc.setLocation(newName); mLocTrigger.updateTrigger(this, trigId, desc.toString()); } } trigIds.clear(); } private void removeTriggers(String categName) { LinkedList<Integer> trigIds = new LinkedList<Integer>(); DbHelper dbHelper = new DbHelper(this); for (Campaign c : dbHelper.getReadyCampaigns()) { trigIds.addAll(mLocTrigger.getAllActiveTriggerIds(this, c.mUrn)); } for(int trigId : trigIds) { LocTrigDesc desc = new LocTrigDesc(); desc.loadString(mLocTrigger.getTrigger(this, trigId)); if(desc.getLocation().equals(categName)) { mLocTrigger.deleteTrigger(this, trigId); } } trigIds.clear(); } /* Populate the categories listview */ private void initializeList() { //The viewbinder class to define each list item class CategListViewBinder implements SimpleCursorAdapter.ViewBinder { @Override public boolean setViewValue(View view, Cursor c, int colIndex) { switch(view.getId()) { case R.id.text2: //locations count TextView tv = (TextView) view; Cursor cLocs = mDb.getLocations(c.getInt(colIndex)); int nLocs = cLocs.getCount(); cLocs.close(); String locStr = (nLocs == 1) ? " " + getString(R.string.location_on_map) : " " + getString(R.string.locations_on_map); tv.setText("" + nLocs + locStr); return true; } return false; } } mCursor = mDb.getAllCategories(); mCursor.moveToFirst(); startManagingCursor(mCursor); String[] from = new String[] {LocTrigDB.KEY_NAME, LocTrigDB.KEY_ID}; int[] to = new int[] {R.id.text1, R.id.text2}; SimpleCursorAdapter categories = new SimpleCursorAdapter(this, R.layout.trigger_loc_settings_row, mCursor, from, to); categories.setViewBinder(new CategListViewBinder()); setListAdapter(categories); } private void refreshList() { mCursor.requery(); populateCategoryNames(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); int builtInStatus = mCursor.getInt( mCursor.getColumnIndexOrThrow(LocTrigDB.KEY_BUILT_IN)); boolean isBuiltIn = (builtInStatus == 1) ? true : false; menu.add(0, MENU_DELETE_CATEG, 0, R.string.menu_delete) .setEnabled(!isBuiltIn && (mAdminMode || TrigUserConfig.editLocationTriggerPlace)); menu.add(0, MENU_RENAME_CATEG, 0, R.string.menu_rename) .setEnabled(!isBuiltIn && (mAdminMode || TrigUserConfig.editLocationTriggerPlace)); } private void deleteCategory(int categId) { String categName = mDb.getCategoryName(categId); mDb.removeCategory(categId); refreshList(); removeTriggers(categName); Intent i = new Intent(this, LocTrigService.class); i.setAction(LocTrigService.ACTION_UPDATE_LOCATIONS); startService(i); } private void renameCategory(int trigId, String newName) { if(newName == null || newName.length() == 0) { return; } String oldName = mDb.getCategoryName(mDialogCategId); mDb.renameCategory(mDialogCategId, newName); refreshList(); updateTriggerDescriptions(oldName, newName); } @Override protected Dialog onCreateDialog(int id) { switch(id) { case DIALOG_DELETE: AlertDialog dialog = new AlertDialog.Builder(this) .setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if(which == AlertDialog.BUTTON_POSITIVE) { deleteCategory(mDialogCategId); } } }) .setNegativeButton(R.string.cancel, null) - .setTitle(R.string.delete + mDb.getCategoryName(mDialogCategId) + "?") + .setTitle(getString(R.string.delete_msg, mDb.getCategoryName(mDialogCategId) + "?")) .setMessage(R.string.trigger_loc_remove_location_text) .create(); return dialog; case DIALOG_RENAME: TrigTextInput ti = new TrigTextInput(this); ti.setPositiveButtonText(getString(R.string.done)); ti.setNegativeButtonText(getString(R.string.cancel)); String name = mDb.getCategoryName(mDialogCategId); ti.setTitle(getString(R.string.rename_msg, name)); if(mDialogText != null) { ti.setText(mDialogText); } else { ti.setText(name); } ti.setOnClickListener(new TrigTextInput.onClickListener() { @Override public void onClick(TrigTextInput ti, int which) { if(which == TrigTextInput.BUTTON_POSITIVE) { renameCategory(mDialogCategId, ti.getText()); } } }); ti.setOnTextChangedListener(new TrigTextInput.onTextChangedListener() { @Override public boolean onTextChanged(TrigTextInput ti, String text) { mDialogText = text; //If the text change to the same name, return true if(text.trim().equalsIgnoreCase(mDb.getCategoryName(mDialogCategId))) { return true; } return checkIfCategNameValid(text); } }); return ti.createDialog(); default: return null; } } @Override public boolean onContextItemSelected(MenuItem item) { int pos = ((AdapterContextMenuInfo) item.getMenuInfo()).position; mCursor.moveToPosition(pos); int categId = mCursor.getInt( mCursor.getColumnIndexOrThrow(LocTrigDB.KEY_ID)); switch(item.getItemId()) { case MENU_DELETE_CATEG: mDialogCategId = categId; mDialogText = null; removeDialog(DIALOG_DELETE); showDialog(DIALOG_DELETE); return true; case MENU_RENAME_CATEG: //Rename category mDialogCategId = categId; removeDialog(DIALOG_RENAME); showDialog(DIALOG_RENAME); return true; default: break; } return super.onContextItemSelected(item); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); if(!mCursor.moveToPosition(position)) { //TODO this should not happen. log return; } //start the maps activity Intent i = new Intent(this, LocTrigMapsActivity.class); i.putExtra(LocTrigDB.KEY_ID, (int)id); startActivity(i); } private void addNewCategory() { EditText et = (EditText) findViewById(R.id.trigger_text_add_categ); mDb.addCategory(et.getText().toString().trim()); refreshList(); //Hide the onscreen keyboard InputMethodManager imm = (InputMethodManager)getSystemService( Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(et.getWindowToken(), 0); //Clear the edit text et.setText(""); } @Override public void onClick(View v) { if(v.getId() == R.id.trigger_button_add_categ) { addNewCategory(); } } @Override public void afterTextChanged(Editable s) { boolean buttonStatus = true; if(!checkIfCategNameValid(s.toString())) { buttonStatus = false; } Button bAdd = (Button) findViewById(R.id.trigger_button_add_categ); bAdd.setEnabled(buttonStatus); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } }
true
true
protected Dialog onCreateDialog(int id) { switch(id) { case DIALOG_DELETE: AlertDialog dialog = new AlertDialog.Builder(this) .setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if(which == AlertDialog.BUTTON_POSITIVE) { deleteCategory(mDialogCategId); } } }) .setNegativeButton(R.string.cancel, null) .setTitle(R.string.delete + mDb.getCategoryName(mDialogCategId) + "?") .setMessage(R.string.trigger_loc_remove_location_text) .create(); return dialog; case DIALOG_RENAME: TrigTextInput ti = new TrigTextInput(this); ti.setPositiveButtonText(getString(R.string.done)); ti.setNegativeButtonText(getString(R.string.cancel)); String name = mDb.getCategoryName(mDialogCategId); ti.setTitle(getString(R.string.rename_msg, name)); if(mDialogText != null) { ti.setText(mDialogText); } else { ti.setText(name); } ti.setOnClickListener(new TrigTextInput.onClickListener() { @Override public void onClick(TrigTextInput ti, int which) { if(which == TrigTextInput.BUTTON_POSITIVE) { renameCategory(mDialogCategId, ti.getText()); } } }); ti.setOnTextChangedListener(new TrigTextInput.onTextChangedListener() { @Override public boolean onTextChanged(TrigTextInput ti, String text) { mDialogText = text; //If the text change to the same name, return true if(text.trim().equalsIgnoreCase(mDb.getCategoryName(mDialogCategId))) { return true; } return checkIfCategNameValid(text); } }); return ti.createDialog(); default: return null; } }
protected Dialog onCreateDialog(int id) { switch(id) { case DIALOG_DELETE: AlertDialog dialog = new AlertDialog.Builder(this) .setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if(which == AlertDialog.BUTTON_POSITIVE) { deleteCategory(mDialogCategId); } } }) .setNegativeButton(R.string.cancel, null) .setTitle(getString(R.string.delete_msg, mDb.getCategoryName(mDialogCategId) + "?")) .setMessage(R.string.trigger_loc_remove_location_text) .create(); return dialog; case DIALOG_RENAME: TrigTextInput ti = new TrigTextInput(this); ti.setPositiveButtonText(getString(R.string.done)); ti.setNegativeButtonText(getString(R.string.cancel)); String name = mDb.getCategoryName(mDialogCategId); ti.setTitle(getString(R.string.rename_msg, name)); if(mDialogText != null) { ti.setText(mDialogText); } else { ti.setText(name); } ti.setOnClickListener(new TrigTextInput.onClickListener() { @Override public void onClick(TrigTextInput ti, int which) { if(which == TrigTextInput.BUTTON_POSITIVE) { renameCategory(mDialogCategId, ti.getText()); } } }); ti.setOnTextChangedListener(new TrigTextInput.onTextChangedListener() { @Override public boolean onTextChanged(TrigTextInput ti, String text) { mDialogText = text; //If the text change to the same name, return true if(text.trim().equalsIgnoreCase(mDb.getCategoryName(mDialogCategId))) { return true; } return checkIfCategNameValid(text); } }); return ti.createDialog(); default: return null; } }
diff --git a/src/org/dazzlewire/Guilder/Guilder.java b/src/org/dazzlewire/Guilder/Guilder.java index ea74f61..d9746cb 100644 --- a/src/org/dazzlewire/Guilder/Guilder.java +++ b/src/org/dazzlewire/Guilder/Guilder.java @@ -1,631 +1,631 @@ package org.dazzlewire.Guilder; // Java imports import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.logging.Logger; // Bukkit imports import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.Listener; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.java.JavaPlugin; public class Guilder extends JavaPlugin implements Listener { // Declare variables public static Guilder plugin; public final Logger logger = Logger.getLogger("Minecraft"); private File configFile; private YamlConfiguration config; private GuildController guildController; PluginDescriptionFile pdf; boolean isOnline = false; String listOfGuildMembers = ""; /** * Online players */ Player[] onlinePlayers; /** * Called upon server start, restart or plugin enabeling * Hehe, this is working */ @Override public void onEnable() { // Load the config.yml loadConfiguration(); // Make a new guildController guildController = new GuildController(this); // Make sure that Bukkit will thow new event at our listeners this.getServer().getPluginManager().registerEvents(this, this); pdf = this.getDescription(); this.logger.info(pdf.getName() + " is now enabled. Running version " + pdf.getVersion()); //Currently online players onlinePlayers = Bukkit.getServer().getOnlinePlayers(); } /** * Called upon server stop og plugin disabeling */ @Override public void onDisable() { PluginDescriptionFile pdf = this.getDescription(); this.logger.info(pdf.getName() + " is now disabled. Running version " + pdf.getVersion()); } /** * Executed when a command is send by the user */ public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){ // Check if the command /g is used if(cmd.getName().equalsIgnoreCase("g")) { // Check if the sender is a player if(sender instanceof Player) { // Check if the player is sending a message (in the arguments) if(args.length > 0) { // Check if the player is in a guild if(guildController.isInGuild(sender.getName())) { // Make the arguments into a message String message = ""; for (int i = 0; i < args.length; i++) { message = message + " " + args[i]; } // Send the message to the guild guildController.getGuildOfPlayer(sender.getName()).sendMessage(message, sender.getName()); } else { // The player is not in a guild sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "You are not in a guild"); } } } } // Check if the user used "/guilder..." if(cmd.getName().equalsIgnoreCase("guilder")) { // Check if the sender is a player if(sender instanceof Player) { /** * The /guilder command * Will snow information about the Guilder mod. */ if(args.length == 0) { sender.sendMessage(ChatColor.GREEN + "[Guilder]" + ChatColor.WHITE + " will add guild functionality to your Bukkit servers."); sender.sendMessage("If you want a list of the commands used in the Guilder mod, you should type /guilder help"); } // Check if the user send at lease 1 argument else if(args.length > 0) { /** * The /guilder reload command * Reload the guild */ if(args[0].equalsIgnoreCase("reload")) { this.onEnable(); sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "has been reloaded"); return true; } /** * The /guilder guildlist command * Lists all the guilds in the plugin-folder */ if(args[0].equalsIgnoreCase("guildlist")) { // Desclare new variabels int pageNumber = 0; int linePerPage = 7; int pagesTotal = 1; // Make a new arraylist with commands ArrayList<Guild> guildList = guildController.getSortedGuildList(); // Calculate the number of pages total pagesTotal = (int) Math.ceil((double)guildList.size()/(double)linePerPage); // Test if the user want to see a specific page if(args.length == 2) { if(!args[1].equalsIgnoreCase("")) { pageNumber = Integer.parseInt(args[1])-1; // Check if the number is positive if(pageNumber < 0) { pageNumber = 0; } // Check if the users choise is a possibility if(pageNumber > pagesTotal) { pageNumber = 0; } } } // Check if there is enough guilds to fill out a single page, if not: Fix it by removing excess space while(guildList.size() % linePerPage > 0) { // Add empty string to arraylist guildList.add(new Guild(this, "", "")); } // Print the headline sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "Here is a list of guilds (Page " + (pageNumber+1) + " of " + pagesTotal + ")"); // Print the first page for (int i = (pageNumber * linePerPage); i < (pageNumber * linePerPage) + linePerPage; i++) { // Check if the array is empty if(!guildList.get(i).getGuildName().equals("")) { sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + guildList.get(i).getGuildName() + " [" + guildList.get(i).getGuildSize() + "]"); } } // Return true - the command is complete return true; } /** * The /guilder create * Will create a guild with the specified name */ else if(args[0].equalsIgnoreCase("create")) { // "/guilder create"-command if(args.length == 2) { // Check if the sender sends 2 arguments String specifiedGuildName = args[1]; // Check if the guild exists if(!guildController.guildExists(specifiedGuildName)) { // If the player is not in a guild if(!guildController.ownsGuild(sender.getName())) { // If the player owns a guild if(!guildController.isInGuild(sender.getName())) { // Create the guild guildController.createGuild(specifiedGuildName, sender.getName()); sender.sendMessage(ChatColor.GREEN + "[Guilder]" + ChatColor.WHITE + " Congratulations. \"" + specifiedGuildName + "\" has been formed"); return true; } else { // The player owns a guild sender.sendMessage(ChatColor.RED + "[Guilder]" + ChatColor.WHITE + " You are already in a guild."); return false; } } else { // If the player is in a guild sender.sendMessage(ChatColor.RED + "[Guilder]" + ChatColor.WHITE + " You already own a guild"); return false; } } else { // There is already a guild with that name sender.sendMessage(ChatColor.RED + "[Guilder]" + ChatColor.WHITE + " There is already a guild with the name \"" + args[1] + "\""); return false; } } else if(args.length > 2) { sender.sendMessage(ChatColor.RED + "[Guilder]" + ChatColor.WHITE + " Guildnames must only contain 1 word"); sender.sendMessage(ChatColor.RED + "[Guilder]" + ChatColor.WHITE + " /guilder create <guild-name>"); return false; } else if(args.length < 2) { sender.sendMessage(ChatColor.RED + "[Guilder]" + ChatColor.WHITE + " Provide a name for your guild"); sender.sendMessage(ChatColor.RED + "[Guilder]" + ChatColor.WHITE + " /guilder create <guild-name>"); return false; } } /** * The /guilder help command * Will display all the commands */ else if(args[0].equalsIgnoreCase("help")) { // Desclare new variabels int pageNumber = 0; int linePerPage = 7; int pagesTotal = 1; // Make a new arraylist with commands ArrayList<String> helpCommands = new ArrayList<String>(); // Add values to this arraylist helpCommands.add("/guilder"); helpCommands.add("/guilder create <guildname>"); helpCommands.add("/guilder help"); helpCommands.add("/guilder guildlist"); helpCommands.add("/guilder list"); helpCommands.add("/guilder online"); helpCommands.add("/guilder remove"); helpCommands.add("/guilder leave"); // Order the arraylist alphabetic Collections.sort(helpCommands); // Calculate the number of pages total pagesTotal = (int) Math.ceil((double)helpCommands.size()/(double)linePerPage); // Test if the user want to see a specific page if(args.length == 2) { if(!args[1].equalsIgnoreCase("")) { pageNumber = Integer.parseInt(args[1])-1; // Check if the number is positive if(pageNumber < 0) { pageNumber = 0; } // Check if the users choise is a possibility if(pageNumber > pagesTotal) { pageNumber = 0; } } } // Check if there is enough commands to fill out a single page, if not: Fix it by removing excess space while(helpCommands.size() % linePerPage > 0) { // Add empty string to arraylist helpCommands.add(""); } // Print the headline sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "Here is a list of commands for you (Page " + (pageNumber+1) + " of " + pagesTotal + ")"); // Print the first page for (int i = (pageNumber * linePerPage); i < (pageNumber * linePerPage) + linePerPage; i++) { // Check if the array is empty if(!helpCommands.get(i).equals("")) { sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + helpCommands.get(i)); } } // Return true - the command is complete return true; } /** * The /guilder invite command * Invites a player to your guild */ else if(args[0].equalsIgnoreCase("invite")) { if(args.length == 2) { //Checks if the sender is in a guild or is a guildmaster if(guildController.ownsGuild(sender.getName()) || guildController.isInGuild(sender.getName())) { //Checks if the reciever of the invite is not in a guild if(!guildController.isInGuild(args[1].toLowerCase())) { isOnline = false; onlinePlayers = Bukkit.getServer().getOnlinePlayers(); //Run through all online players for(int i = 0; i < onlinePlayers.length; i++) { //Check if the specific player is online if(onlinePlayers[i].getName().equalsIgnoreCase(args[1])) { guildController.setInvite(onlinePlayers[i].getName(), guildController.getGuildOfPlayer(sender.getName())); //Sends information to both sender and reciever sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "You have invited " + onlinePlayers[i].getName() + " to join your guild. He will have to accept your invite using /guilder acceptinvite."); onlinePlayers[i].sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "You have been invited to join " + guildController.getGuildOfPlayer(sender.getName()).getGuildName() + " by " + sender.getName() + ". Accept your invite using /guilder acceptinvite."); isOnline = true; } // Return when the loop is complete if(i == onlinePlayers.length) { return true; } } if(!isOnline) { sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + args[1].toLowerCase() + " is not online."); return false; } } else { sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "A player with that name is already in a guild"); return false; } } else { sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "You are a not in a guild"); return false; } } else if(args.length > 2) { //Check if the sender provide too many arguments sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "A player with that name does not exist"); sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "/guilder invite <player-name>"); return false; } else if(args.length == 1) { //Check if the sender do not provides enough arguments sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "You need to provide a player-name"); sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "/guilder invite <player-name>"); return false; } /** * The /guilder accept - command */ } else if(args[0].equalsIgnoreCase("acceptinvite")){ //Check if the player is invites to a guild if(guildController.getPendingPlayerGuild().containsKey(sender.getName())) { //Check if the player has been invited to a guild in the last 20 minutes if(System.currentTimeMillis() - guildController.getPendingPlayerTime().get(sender.getName()) <= 1200000) { //Adds the member to the specific guild guildController.getPendingPlayerGuild().get(sender.getName()).addMember(sender.getName()); sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "Congratulations you have joined " + guildController.getPendingPlayerGuild().get(sender.getName()).getGuildName() + "."); return true; } return false; } return false; } /** * The /guilder online command * Shows the players online in the commandsenders guild */ else if(args[0].equalsIgnoreCase("online")) { //Check if the sender is in a guild if(guildController.isInGuild(sender.getName())){ onlinePlayers = Bukkit.getOnlinePlayers(); listOfGuildMembers = ""; //Runs through all players in the guild of the sender for(int i = 0; i < guildController.getGuildOfPlayer(sender.getName()).getGuildSize(); i++){ for(int j = 0; j < onlinePlayers.length; j++){ if(onlinePlayers[j].getName().equalsIgnoreCase(guildController.getGuildOfPlayer(sender.getName()).getMemberArray()[i].toString())){ listOfGuildMembers = listOfGuildMembers + ", " + onlinePlayers[j].getName() ; } } // Break our of the command-statement when the loop is done if(i == guildController.getGuildOfPlayer(sender.getName()).getGuildSize()) { return true; } } sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "Here is a list of online players in your guild:"); sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + listOfGuildMembers.replaceFirst(", ", "")); } else { sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "You are not in a guild"); return false; } } /** * The /guilder list command * Lists all the commandsenders guildmates */ else if(args[0].equalsIgnoreCase("list")){ //Check if the sender is in a guild if(guildController.isInGuild(sender.getName())){ // Create an empty string listOfGuildMembers = ""; //Runs through all players in the guild of the sender for(int i = 0; i < guildController.getGuildOfPlayer(sender.getName()).getGuildSize(); i++){ listOfGuildMembers = listOfGuildMembers + ", " + guildController.getGuildOfPlayer(sender.getName()).getMemberArray()[i] ; } sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "Here is a list of all players in your guild:"); sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + listOfGuildMembers.replaceFirst(", ", "")); return true; } else { sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "You are not in a guild"); return false; } } /** * The /guilder leave command * Makes the commandsender leave his or hers guild */ else if(args[0].equalsIgnoreCase("leave")){ if(guildController.isInGuild(sender.getName())){ if(!guildController.ownsGuild(sender.getName())){ guildController.setLeave(sender.getName(), guildController.getGuildOfPlayer(sender.getName())); sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "Are you sure you want to leave " + guildController.getGuildOfPlayer(sender.getName()).getGuildName() + "? Type /guilder acceptleave to confirm your action."); return true; } else { sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "You cannot leave a guild that you own"); return false; } } else { sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "You are not in a guild"); return false; } } /** * The /guilder acceptleave command * Removes the player from his or hers guild, if there is a pending leaving-request */ else if(args[0].equalsIgnoreCase("acceptleave")){ //Check if the player has tried to leave a guild if(guildController.getLeavingPlayerGuild().containsKey(sender.getName())) { //Check if the player has asked to leave to a guild in the last 2 minutes if(System.currentTimeMillis() - guildController.getLeavingPlayerTime().get(sender.getName()) <= 120000) { //Removes the member to the specific guild guildController.getLeavingPlayerGuild().get(sender.getName()).removeMember(sender.getName()); sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "You have succesfully left " + guildController.getPendingPlayerGuild().get(sender.getName()).getGuildName() + "."); return true; // The player do not have a pending leave-request } else { sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "You do not have a pending leave-request. Type /guilder leave"); } // The player is not in a guild } else { sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "You are not in a guild"); } } /** * The /guilder remove command * Removes a player from the guildmasters guild */ else if(args[0].equalsIgnoreCase("remove")){ // Check if a player is specified if(!args[1].equals("")) { // Check if the commandsender is in a guild if(guildController.isInGuild(sender.getName())) { // Check if the commandsender is the guildmaster of the guild if(guildController.ownsGuild(sender.getName())) { // Check if the provided player is in the guild if(guildController.isInGuild(args[1])) { // Check if the provided player and the guildmaster is in the same guild if(guildController.getGuildOfPlayer(sender.getName()).equals(guildController.getGuildOfPlayer(args[1]))) { // Remove the player guildController.getGuildOfPlayer(sender.getName()).removeMember(args[1]); return true; } - // The pprovided player is not in a guild + // The provided player is not in the same guild as the guildmaster guild } else { - sender.sendMessage("5"); + sender.sendMessage(args[1]+" is not in your guild"); return false; } // The sender is not the guildmaster } else { - sender.sendMessage("1"); + sender.sendMessage("You are not a guildmaster"); return false; } // The sender is not in a guild } else { - sender.sendMessage("2"); + sender.sendMessage(args[1]+" is not in a guild"); return false; } // No player is specified } else { - sender.sendMessage("4"); + sender.sendMessage("You need to specify a targeted player. Use /guilder remove <player> to remove \"player\" from your guild"); return false; } } } } } // No right commands were found. Return false. return false; } /** * Add default values to the config file */ private void loadConfiguration() { configFile = new File("plugins" + File.separator + this.getDescription().getName() + File.separator + "config.yml"); //config file // Check if the config file exists if(!configFile.exists()) { // Create a new config file (new File("plugins" + File.separator + this.getDescription().getName())).mkdirs(); // Make directories config = YamlConfiguration.loadConfiguration(configFile); //get the yml-config from the guildSpecificFile // Add defaults to the config-file config.addDefault("Setting", "Result"); config.options().copyDefaults(true); try { config.save(configFile); // Save the file } catch (IOException e) { // Handle exception } } } }
false
true
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){ // Check if the command /g is used if(cmd.getName().equalsIgnoreCase("g")) { // Check if the sender is a player if(sender instanceof Player) { // Check if the player is sending a message (in the arguments) if(args.length > 0) { // Check if the player is in a guild if(guildController.isInGuild(sender.getName())) { // Make the arguments into a message String message = ""; for (int i = 0; i < args.length; i++) { message = message + " " + args[i]; } // Send the message to the guild guildController.getGuildOfPlayer(sender.getName()).sendMessage(message, sender.getName()); } else { // The player is not in a guild sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "You are not in a guild"); } } } } // Check if the user used "/guilder..." if(cmd.getName().equalsIgnoreCase("guilder")) { // Check if the sender is a player if(sender instanceof Player) { /** * The /guilder command * Will snow information about the Guilder mod. */ if(args.length == 0) { sender.sendMessage(ChatColor.GREEN + "[Guilder]" + ChatColor.WHITE + " will add guild functionality to your Bukkit servers."); sender.sendMessage("If you want a list of the commands used in the Guilder mod, you should type /guilder help"); } // Check if the user send at lease 1 argument else if(args.length > 0) { /** * The /guilder reload command * Reload the guild */ if(args[0].equalsIgnoreCase("reload")) { this.onEnable(); sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "has been reloaded"); return true; } /** * The /guilder guildlist command * Lists all the guilds in the plugin-folder */ if(args[0].equalsIgnoreCase("guildlist")) { // Desclare new variabels int pageNumber = 0; int linePerPage = 7; int pagesTotal = 1; // Make a new arraylist with commands ArrayList<Guild> guildList = guildController.getSortedGuildList(); // Calculate the number of pages total pagesTotal = (int) Math.ceil((double)guildList.size()/(double)linePerPage); // Test if the user want to see a specific page if(args.length == 2) { if(!args[1].equalsIgnoreCase("")) { pageNumber = Integer.parseInt(args[1])-1; // Check if the number is positive if(pageNumber < 0) { pageNumber = 0; } // Check if the users choise is a possibility if(pageNumber > pagesTotal) { pageNumber = 0; } } } // Check if there is enough guilds to fill out a single page, if not: Fix it by removing excess space while(guildList.size() % linePerPage > 0) { // Add empty string to arraylist guildList.add(new Guild(this, "", "")); } // Print the headline sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "Here is a list of guilds (Page " + (pageNumber+1) + " of " + pagesTotal + ")"); // Print the first page for (int i = (pageNumber * linePerPage); i < (pageNumber * linePerPage) + linePerPage; i++) { // Check if the array is empty if(!guildList.get(i).getGuildName().equals("")) { sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + guildList.get(i).getGuildName() + " [" + guildList.get(i).getGuildSize() + "]"); } } // Return true - the command is complete return true; } /** * The /guilder create * Will create a guild with the specified name */ else if(args[0].equalsIgnoreCase("create")) { // "/guilder create"-command if(args.length == 2) { // Check if the sender sends 2 arguments String specifiedGuildName = args[1]; // Check if the guild exists if(!guildController.guildExists(specifiedGuildName)) { // If the player is not in a guild if(!guildController.ownsGuild(sender.getName())) { // If the player owns a guild if(!guildController.isInGuild(sender.getName())) { // Create the guild guildController.createGuild(specifiedGuildName, sender.getName()); sender.sendMessage(ChatColor.GREEN + "[Guilder]" + ChatColor.WHITE + " Congratulations. \"" + specifiedGuildName + "\" has been formed"); return true; } else { // The player owns a guild sender.sendMessage(ChatColor.RED + "[Guilder]" + ChatColor.WHITE + " You are already in a guild."); return false; } } else { // If the player is in a guild sender.sendMessage(ChatColor.RED + "[Guilder]" + ChatColor.WHITE + " You already own a guild"); return false; } } else { // There is already a guild with that name sender.sendMessage(ChatColor.RED + "[Guilder]" + ChatColor.WHITE + " There is already a guild with the name \"" + args[1] + "\""); return false; } } else if(args.length > 2) { sender.sendMessage(ChatColor.RED + "[Guilder]" + ChatColor.WHITE + " Guildnames must only contain 1 word"); sender.sendMessage(ChatColor.RED + "[Guilder]" + ChatColor.WHITE + " /guilder create <guild-name>"); return false; } else if(args.length < 2) { sender.sendMessage(ChatColor.RED + "[Guilder]" + ChatColor.WHITE + " Provide a name for your guild"); sender.sendMessage(ChatColor.RED + "[Guilder]" + ChatColor.WHITE + " /guilder create <guild-name>"); return false; } } /** * The /guilder help command * Will display all the commands */ else if(args[0].equalsIgnoreCase("help")) { // Desclare new variabels int pageNumber = 0; int linePerPage = 7; int pagesTotal = 1; // Make a new arraylist with commands ArrayList<String> helpCommands = new ArrayList<String>(); // Add values to this arraylist helpCommands.add("/guilder"); helpCommands.add("/guilder create <guildname>"); helpCommands.add("/guilder help"); helpCommands.add("/guilder guildlist"); helpCommands.add("/guilder list"); helpCommands.add("/guilder online"); helpCommands.add("/guilder remove"); helpCommands.add("/guilder leave"); // Order the arraylist alphabetic Collections.sort(helpCommands); // Calculate the number of pages total pagesTotal = (int) Math.ceil((double)helpCommands.size()/(double)linePerPage); // Test if the user want to see a specific page if(args.length == 2) { if(!args[1].equalsIgnoreCase("")) { pageNumber = Integer.parseInt(args[1])-1; // Check if the number is positive if(pageNumber < 0) { pageNumber = 0; } // Check if the users choise is a possibility if(pageNumber > pagesTotal) { pageNumber = 0; } } } // Check if there is enough commands to fill out a single page, if not: Fix it by removing excess space while(helpCommands.size() % linePerPage > 0) { // Add empty string to arraylist helpCommands.add(""); } // Print the headline sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "Here is a list of commands for you (Page " + (pageNumber+1) + " of " + pagesTotal + ")"); // Print the first page for (int i = (pageNumber * linePerPage); i < (pageNumber * linePerPage) + linePerPage; i++) { // Check if the array is empty if(!helpCommands.get(i).equals("")) { sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + helpCommands.get(i)); } } // Return true - the command is complete return true; } /** * The /guilder invite command * Invites a player to your guild */ else if(args[0].equalsIgnoreCase("invite")) { if(args.length == 2) { //Checks if the sender is in a guild or is a guildmaster if(guildController.ownsGuild(sender.getName()) || guildController.isInGuild(sender.getName())) { //Checks if the reciever of the invite is not in a guild if(!guildController.isInGuild(args[1].toLowerCase())) { isOnline = false; onlinePlayers = Bukkit.getServer().getOnlinePlayers(); //Run through all online players for(int i = 0; i < onlinePlayers.length; i++) { //Check if the specific player is online if(onlinePlayers[i].getName().equalsIgnoreCase(args[1])) { guildController.setInvite(onlinePlayers[i].getName(), guildController.getGuildOfPlayer(sender.getName())); //Sends information to both sender and reciever sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "You have invited " + onlinePlayers[i].getName() + " to join your guild. He will have to accept your invite using /guilder acceptinvite."); onlinePlayers[i].sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "You have been invited to join " + guildController.getGuildOfPlayer(sender.getName()).getGuildName() + " by " + sender.getName() + ". Accept your invite using /guilder acceptinvite."); isOnline = true; } // Return when the loop is complete if(i == onlinePlayers.length) { return true; } } if(!isOnline) { sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + args[1].toLowerCase() + " is not online."); return false; } } else { sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "A player with that name is already in a guild"); return false; } } else { sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "You are a not in a guild"); return false; } } else if(args.length > 2) { //Check if the sender provide too many arguments sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "A player with that name does not exist"); sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "/guilder invite <player-name>"); return false; } else if(args.length == 1) { //Check if the sender do not provides enough arguments sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "You need to provide a player-name"); sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "/guilder invite <player-name>"); return false; } /** * The /guilder accept - command */ } else if(args[0].equalsIgnoreCase("acceptinvite")){ //Check if the player is invites to a guild if(guildController.getPendingPlayerGuild().containsKey(sender.getName())) { //Check if the player has been invited to a guild in the last 20 minutes if(System.currentTimeMillis() - guildController.getPendingPlayerTime().get(sender.getName()) <= 1200000) { //Adds the member to the specific guild guildController.getPendingPlayerGuild().get(sender.getName()).addMember(sender.getName()); sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "Congratulations you have joined " + guildController.getPendingPlayerGuild().get(sender.getName()).getGuildName() + "."); return true; } return false; } return false; } /** * The /guilder online command * Shows the players online in the commandsenders guild */ else if(args[0].equalsIgnoreCase("online")) { //Check if the sender is in a guild if(guildController.isInGuild(sender.getName())){ onlinePlayers = Bukkit.getOnlinePlayers(); listOfGuildMembers = ""; //Runs through all players in the guild of the sender for(int i = 0; i < guildController.getGuildOfPlayer(sender.getName()).getGuildSize(); i++){ for(int j = 0; j < onlinePlayers.length; j++){ if(onlinePlayers[j].getName().equalsIgnoreCase(guildController.getGuildOfPlayer(sender.getName()).getMemberArray()[i].toString())){ listOfGuildMembers = listOfGuildMembers + ", " + onlinePlayers[j].getName() ; } } // Break our of the command-statement when the loop is done if(i == guildController.getGuildOfPlayer(sender.getName()).getGuildSize()) { return true; } } sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "Here is a list of online players in your guild:"); sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + listOfGuildMembers.replaceFirst(", ", "")); } else { sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "You are not in a guild"); return false; } } /** * The /guilder list command * Lists all the commandsenders guildmates */ else if(args[0].equalsIgnoreCase("list")){ //Check if the sender is in a guild if(guildController.isInGuild(sender.getName())){ // Create an empty string listOfGuildMembers = ""; //Runs through all players in the guild of the sender for(int i = 0; i < guildController.getGuildOfPlayer(sender.getName()).getGuildSize(); i++){ listOfGuildMembers = listOfGuildMembers + ", " + guildController.getGuildOfPlayer(sender.getName()).getMemberArray()[i] ; } sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "Here is a list of all players in your guild:"); sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + listOfGuildMembers.replaceFirst(", ", "")); return true; } else { sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "You are not in a guild"); return false; } } /** * The /guilder leave command * Makes the commandsender leave his or hers guild */ else if(args[0].equalsIgnoreCase("leave")){ if(guildController.isInGuild(sender.getName())){ if(!guildController.ownsGuild(sender.getName())){ guildController.setLeave(sender.getName(), guildController.getGuildOfPlayer(sender.getName())); sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "Are you sure you want to leave " + guildController.getGuildOfPlayer(sender.getName()).getGuildName() + "? Type /guilder acceptleave to confirm your action."); return true; } else { sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "You cannot leave a guild that you own"); return false; } } else { sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "You are not in a guild"); return false; } } /** * The /guilder acceptleave command * Removes the player from his or hers guild, if there is a pending leaving-request */ else if(args[0].equalsIgnoreCase("acceptleave")){ //Check if the player has tried to leave a guild if(guildController.getLeavingPlayerGuild().containsKey(sender.getName())) { //Check if the player has asked to leave to a guild in the last 2 minutes if(System.currentTimeMillis() - guildController.getLeavingPlayerTime().get(sender.getName()) <= 120000) { //Removes the member to the specific guild guildController.getLeavingPlayerGuild().get(sender.getName()).removeMember(sender.getName()); sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "You have succesfully left " + guildController.getPendingPlayerGuild().get(sender.getName()).getGuildName() + "."); return true; // The player do not have a pending leave-request } else { sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "You do not have a pending leave-request. Type /guilder leave"); } // The player is not in a guild } else { sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "You are not in a guild"); } } /** * The /guilder remove command * Removes a player from the guildmasters guild */ else if(args[0].equalsIgnoreCase("remove")){ // Check if a player is specified if(!args[1].equals("")) { // Check if the commandsender is in a guild if(guildController.isInGuild(sender.getName())) { // Check if the commandsender is the guildmaster of the guild if(guildController.ownsGuild(sender.getName())) { // Check if the provided player is in the guild if(guildController.isInGuild(args[1])) { // Check if the provided player and the guildmaster is in the same guild if(guildController.getGuildOfPlayer(sender.getName()).equals(guildController.getGuildOfPlayer(args[1]))) { // Remove the player guildController.getGuildOfPlayer(sender.getName()).removeMember(args[1]); return true; } // The pprovided player is not in a guild } else { sender.sendMessage("5"); return false; } // The sender is not the guildmaster } else { sender.sendMessage("1"); return false; } // The sender is not in a guild } else { sender.sendMessage("2"); return false; } // No player is specified } else { sender.sendMessage("4"); return false; } } } } }
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){ // Check if the command /g is used if(cmd.getName().equalsIgnoreCase("g")) { // Check if the sender is a player if(sender instanceof Player) { // Check if the player is sending a message (in the arguments) if(args.length > 0) { // Check if the player is in a guild if(guildController.isInGuild(sender.getName())) { // Make the arguments into a message String message = ""; for (int i = 0; i < args.length; i++) { message = message + " " + args[i]; } // Send the message to the guild guildController.getGuildOfPlayer(sender.getName()).sendMessage(message, sender.getName()); } else { // The player is not in a guild sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "You are not in a guild"); } } } } // Check if the user used "/guilder..." if(cmd.getName().equalsIgnoreCase("guilder")) { // Check if the sender is a player if(sender instanceof Player) { /** * The /guilder command * Will snow information about the Guilder mod. */ if(args.length == 0) { sender.sendMessage(ChatColor.GREEN + "[Guilder]" + ChatColor.WHITE + " will add guild functionality to your Bukkit servers."); sender.sendMessage("If you want a list of the commands used in the Guilder mod, you should type /guilder help"); } // Check if the user send at lease 1 argument else if(args.length > 0) { /** * The /guilder reload command * Reload the guild */ if(args[0].equalsIgnoreCase("reload")) { this.onEnable(); sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "has been reloaded"); return true; } /** * The /guilder guildlist command * Lists all the guilds in the plugin-folder */ if(args[0].equalsIgnoreCase("guildlist")) { // Desclare new variabels int pageNumber = 0; int linePerPage = 7; int pagesTotal = 1; // Make a new arraylist with commands ArrayList<Guild> guildList = guildController.getSortedGuildList(); // Calculate the number of pages total pagesTotal = (int) Math.ceil((double)guildList.size()/(double)linePerPage); // Test if the user want to see a specific page if(args.length == 2) { if(!args[1].equalsIgnoreCase("")) { pageNumber = Integer.parseInt(args[1])-1; // Check if the number is positive if(pageNumber < 0) { pageNumber = 0; } // Check if the users choise is a possibility if(pageNumber > pagesTotal) { pageNumber = 0; } } } // Check if there is enough guilds to fill out a single page, if not: Fix it by removing excess space while(guildList.size() % linePerPage > 0) { // Add empty string to arraylist guildList.add(new Guild(this, "", "")); } // Print the headline sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "Here is a list of guilds (Page " + (pageNumber+1) + " of " + pagesTotal + ")"); // Print the first page for (int i = (pageNumber * linePerPage); i < (pageNumber * linePerPage) + linePerPage; i++) { // Check if the array is empty if(!guildList.get(i).getGuildName().equals("")) { sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + guildList.get(i).getGuildName() + " [" + guildList.get(i).getGuildSize() + "]"); } } // Return true - the command is complete return true; } /** * The /guilder create * Will create a guild with the specified name */ else if(args[0].equalsIgnoreCase("create")) { // "/guilder create"-command if(args.length == 2) { // Check if the sender sends 2 arguments String specifiedGuildName = args[1]; // Check if the guild exists if(!guildController.guildExists(specifiedGuildName)) { // If the player is not in a guild if(!guildController.ownsGuild(sender.getName())) { // If the player owns a guild if(!guildController.isInGuild(sender.getName())) { // Create the guild guildController.createGuild(specifiedGuildName, sender.getName()); sender.sendMessage(ChatColor.GREEN + "[Guilder]" + ChatColor.WHITE + " Congratulations. \"" + specifiedGuildName + "\" has been formed"); return true; } else { // The player owns a guild sender.sendMessage(ChatColor.RED + "[Guilder]" + ChatColor.WHITE + " You are already in a guild."); return false; } } else { // If the player is in a guild sender.sendMessage(ChatColor.RED + "[Guilder]" + ChatColor.WHITE + " You already own a guild"); return false; } } else { // There is already a guild with that name sender.sendMessage(ChatColor.RED + "[Guilder]" + ChatColor.WHITE + " There is already a guild with the name \"" + args[1] + "\""); return false; } } else if(args.length > 2) { sender.sendMessage(ChatColor.RED + "[Guilder]" + ChatColor.WHITE + " Guildnames must only contain 1 word"); sender.sendMessage(ChatColor.RED + "[Guilder]" + ChatColor.WHITE + " /guilder create <guild-name>"); return false; } else if(args.length < 2) { sender.sendMessage(ChatColor.RED + "[Guilder]" + ChatColor.WHITE + " Provide a name for your guild"); sender.sendMessage(ChatColor.RED + "[Guilder]" + ChatColor.WHITE + " /guilder create <guild-name>"); return false; } } /** * The /guilder help command * Will display all the commands */ else if(args[0].equalsIgnoreCase("help")) { // Desclare new variabels int pageNumber = 0; int linePerPage = 7; int pagesTotal = 1; // Make a new arraylist with commands ArrayList<String> helpCommands = new ArrayList<String>(); // Add values to this arraylist helpCommands.add("/guilder"); helpCommands.add("/guilder create <guildname>"); helpCommands.add("/guilder help"); helpCommands.add("/guilder guildlist"); helpCommands.add("/guilder list"); helpCommands.add("/guilder online"); helpCommands.add("/guilder remove"); helpCommands.add("/guilder leave"); // Order the arraylist alphabetic Collections.sort(helpCommands); // Calculate the number of pages total pagesTotal = (int) Math.ceil((double)helpCommands.size()/(double)linePerPage); // Test if the user want to see a specific page if(args.length == 2) { if(!args[1].equalsIgnoreCase("")) { pageNumber = Integer.parseInt(args[1])-1; // Check if the number is positive if(pageNumber < 0) { pageNumber = 0; } // Check if the users choise is a possibility if(pageNumber > pagesTotal) { pageNumber = 0; } } } // Check if there is enough commands to fill out a single page, if not: Fix it by removing excess space while(helpCommands.size() % linePerPage > 0) { // Add empty string to arraylist helpCommands.add(""); } // Print the headline sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "Here is a list of commands for you (Page " + (pageNumber+1) + " of " + pagesTotal + ")"); // Print the first page for (int i = (pageNumber * linePerPage); i < (pageNumber * linePerPage) + linePerPage; i++) { // Check if the array is empty if(!helpCommands.get(i).equals("")) { sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + helpCommands.get(i)); } } // Return true - the command is complete return true; } /** * The /guilder invite command * Invites a player to your guild */ else if(args[0].equalsIgnoreCase("invite")) { if(args.length == 2) { //Checks if the sender is in a guild or is a guildmaster if(guildController.ownsGuild(sender.getName()) || guildController.isInGuild(sender.getName())) { //Checks if the reciever of the invite is not in a guild if(!guildController.isInGuild(args[1].toLowerCase())) { isOnline = false; onlinePlayers = Bukkit.getServer().getOnlinePlayers(); //Run through all online players for(int i = 0; i < onlinePlayers.length; i++) { //Check if the specific player is online if(onlinePlayers[i].getName().equalsIgnoreCase(args[1])) { guildController.setInvite(onlinePlayers[i].getName(), guildController.getGuildOfPlayer(sender.getName())); //Sends information to both sender and reciever sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "You have invited " + onlinePlayers[i].getName() + " to join your guild. He will have to accept your invite using /guilder acceptinvite."); onlinePlayers[i].sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "You have been invited to join " + guildController.getGuildOfPlayer(sender.getName()).getGuildName() + " by " + sender.getName() + ". Accept your invite using /guilder acceptinvite."); isOnline = true; } // Return when the loop is complete if(i == onlinePlayers.length) { return true; } } if(!isOnline) { sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + args[1].toLowerCase() + " is not online."); return false; } } else { sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "A player with that name is already in a guild"); return false; } } else { sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "You are a not in a guild"); return false; } } else if(args.length > 2) { //Check if the sender provide too many arguments sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "A player with that name does not exist"); sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "/guilder invite <player-name>"); return false; } else if(args.length == 1) { //Check if the sender do not provides enough arguments sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "You need to provide a player-name"); sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "/guilder invite <player-name>"); return false; } /** * The /guilder accept - command */ } else if(args[0].equalsIgnoreCase("acceptinvite")){ //Check if the player is invites to a guild if(guildController.getPendingPlayerGuild().containsKey(sender.getName())) { //Check if the player has been invited to a guild in the last 20 minutes if(System.currentTimeMillis() - guildController.getPendingPlayerTime().get(sender.getName()) <= 1200000) { //Adds the member to the specific guild guildController.getPendingPlayerGuild().get(sender.getName()).addMember(sender.getName()); sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "Congratulations you have joined " + guildController.getPendingPlayerGuild().get(sender.getName()).getGuildName() + "."); return true; } return false; } return false; } /** * The /guilder online command * Shows the players online in the commandsenders guild */ else if(args[0].equalsIgnoreCase("online")) { //Check if the sender is in a guild if(guildController.isInGuild(sender.getName())){ onlinePlayers = Bukkit.getOnlinePlayers(); listOfGuildMembers = ""; //Runs through all players in the guild of the sender for(int i = 0; i < guildController.getGuildOfPlayer(sender.getName()).getGuildSize(); i++){ for(int j = 0; j < onlinePlayers.length; j++){ if(onlinePlayers[j].getName().equalsIgnoreCase(guildController.getGuildOfPlayer(sender.getName()).getMemberArray()[i].toString())){ listOfGuildMembers = listOfGuildMembers + ", " + onlinePlayers[j].getName() ; } } // Break our of the command-statement when the loop is done if(i == guildController.getGuildOfPlayer(sender.getName()).getGuildSize()) { return true; } } sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "Here is a list of online players in your guild:"); sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + listOfGuildMembers.replaceFirst(", ", "")); } else { sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "You are not in a guild"); return false; } } /** * The /guilder list command * Lists all the commandsenders guildmates */ else if(args[0].equalsIgnoreCase("list")){ //Check if the sender is in a guild if(guildController.isInGuild(sender.getName())){ // Create an empty string listOfGuildMembers = ""; //Runs through all players in the guild of the sender for(int i = 0; i < guildController.getGuildOfPlayer(sender.getName()).getGuildSize(); i++){ listOfGuildMembers = listOfGuildMembers + ", " + guildController.getGuildOfPlayer(sender.getName()).getMemberArray()[i] ; } sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "Here is a list of all players in your guild:"); sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + listOfGuildMembers.replaceFirst(", ", "")); return true; } else { sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "You are not in a guild"); return false; } } /** * The /guilder leave command * Makes the commandsender leave his or hers guild */ else if(args[0].equalsIgnoreCase("leave")){ if(guildController.isInGuild(sender.getName())){ if(!guildController.ownsGuild(sender.getName())){ guildController.setLeave(sender.getName(), guildController.getGuildOfPlayer(sender.getName())); sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "Are you sure you want to leave " + guildController.getGuildOfPlayer(sender.getName()).getGuildName() + "? Type /guilder acceptleave to confirm your action."); return true; } else { sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "You cannot leave a guild that you own"); return false; } } else { sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "You are not in a guild"); return false; } } /** * The /guilder acceptleave command * Removes the player from his or hers guild, if there is a pending leaving-request */ else if(args[0].equalsIgnoreCase("acceptleave")){ //Check if the player has tried to leave a guild if(guildController.getLeavingPlayerGuild().containsKey(sender.getName())) { //Check if the player has asked to leave to a guild in the last 2 minutes if(System.currentTimeMillis() - guildController.getLeavingPlayerTime().get(sender.getName()) <= 120000) { //Removes the member to the specific guild guildController.getLeavingPlayerGuild().get(sender.getName()).removeMember(sender.getName()); sender.sendMessage(ChatColor.GREEN + "[Guilder] " + ChatColor.WHITE + "You have succesfully left " + guildController.getPendingPlayerGuild().get(sender.getName()).getGuildName() + "."); return true; // The player do not have a pending leave-request } else { sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "You do not have a pending leave-request. Type /guilder leave"); } // The player is not in a guild } else { sender.sendMessage(ChatColor.RED + "[Guilder] " + ChatColor.WHITE + "You are not in a guild"); } } /** * The /guilder remove command * Removes a player from the guildmasters guild */ else if(args[0].equalsIgnoreCase("remove")){ // Check if a player is specified if(!args[1].equals("")) { // Check if the commandsender is in a guild if(guildController.isInGuild(sender.getName())) { // Check if the commandsender is the guildmaster of the guild if(guildController.ownsGuild(sender.getName())) { // Check if the provided player is in the guild if(guildController.isInGuild(args[1])) { // Check if the provided player and the guildmaster is in the same guild if(guildController.getGuildOfPlayer(sender.getName()).equals(guildController.getGuildOfPlayer(args[1]))) { // Remove the player guildController.getGuildOfPlayer(sender.getName()).removeMember(args[1]); return true; } // The provided player is not in the same guild as the guildmaster guild } else { sender.sendMessage(args[1]+" is not in your guild"); return false; } // The sender is not the guildmaster } else { sender.sendMessage("You are not a guildmaster"); return false; } // The sender is not in a guild } else { sender.sendMessage(args[1]+" is not in a guild"); return false; } // No player is specified } else { sender.sendMessage("You need to specify a targeted player. Use /guilder remove <player> to remove \"player\" from your guild"); return false; } } } } }
diff --git a/test/Strings.java b/test/Strings.java index 01082559..16ad24cd 100644 --- a/test/Strings.java +++ b/test/Strings.java @@ -1,29 +1,32 @@ package test; public class Strings { public static void main(String[] args) { String a = "alphabet"; String b = "belvedere"; String c = "AlPhAbEt"; String d = " \t alphabet \n \t "; int ia = 5; int ib = 6; System.out.println(a.contains("phab")); System.out.println(a.contains(b)); System.out.println(a.startsWith("alpha")); System.out.println(a.endsWith("bet")); System.out.println(a.toUpperCase()); System.out.println(a.toLowerCase()); System.out.println(a.equalsIgnoreCase(c)); System.out.println(a.lastIndexOf("a")); System.out.println(a.length()); System.out.println(a.substring(4,6)); System.out.println(a.toString()); + System.out.println(d); System.out.println(d.trim()); System.out.println(a.replace('a','z')); System.out.println(String.valueOf(1)); + // sans newlines + System.out.print(1); System.out.print(2); System.out.print(3); //System.out.println(String.valueOf(1.5)); //System.out.format("%s ", "asdf"); } }
false
true
public static void main(String[] args) { String a = "alphabet"; String b = "belvedere"; String c = "AlPhAbEt"; String d = " \t alphabet \n \t "; int ia = 5; int ib = 6; System.out.println(a.contains("phab")); System.out.println(a.contains(b)); System.out.println(a.startsWith("alpha")); System.out.println(a.endsWith("bet")); System.out.println(a.toUpperCase()); System.out.println(a.toLowerCase()); System.out.println(a.equalsIgnoreCase(c)); System.out.println(a.lastIndexOf("a")); System.out.println(a.length()); System.out.println(a.substring(4,6)); System.out.println(a.toString()); System.out.println(d.trim()); System.out.println(a.replace('a','z')); System.out.println(String.valueOf(1)); //System.out.println(String.valueOf(1.5)); //System.out.format("%s ", "asdf"); }
public static void main(String[] args) { String a = "alphabet"; String b = "belvedere"; String c = "AlPhAbEt"; String d = " \t alphabet \n \t "; int ia = 5; int ib = 6; System.out.println(a.contains("phab")); System.out.println(a.contains(b)); System.out.println(a.startsWith("alpha")); System.out.println(a.endsWith("bet")); System.out.println(a.toUpperCase()); System.out.println(a.toLowerCase()); System.out.println(a.equalsIgnoreCase(c)); System.out.println(a.lastIndexOf("a")); System.out.println(a.length()); System.out.println(a.substring(4,6)); System.out.println(a.toString()); System.out.println(d); System.out.println(d.trim()); System.out.println(a.replace('a','z')); System.out.println(String.valueOf(1)); // sans newlines System.out.print(1); System.out.print(2); System.out.print(3); //System.out.println(String.valueOf(1.5)); //System.out.format("%s ", "asdf"); }
diff --git a/runtime/ceylon/language/Ordinal$impl.java b/runtime/ceylon/language/Ordinal$impl.java index 9c8e0769..ed274247 100644 --- a/runtime/ceylon/language/Ordinal$impl.java +++ b/runtime/ceylon/language/Ordinal$impl.java @@ -1,5 +1,5 @@ package ceylon.language; public class Ordinal$impl<Other extends Ordinal<? extends Other>> { - public Ordinal$impl(Ordinal<Other> $this) {} + public Ordinal$impl(Ordinal<? extends Other> $this) {} }
true
true
public Ordinal$impl(Ordinal<Other> $this) {}
public Ordinal$impl(Ordinal<? extends Other> $this) {}
diff --git a/geoserver/web/src/main/java/org/geoserver/GeoserverInitStartupListener.java b/geoserver/web/src/main/java/org/geoserver/GeoserverInitStartupListener.java index 83687695f9..0159318e76 100644 --- a/geoserver/web/src/main/java/org/geoserver/GeoserverInitStartupListener.java +++ b/geoserver/web/src/main/java/org/geoserver/GeoserverInitStartupListener.java @@ -1,62 +1,63 @@ package org.geoserver; import java.util.logging.Logger; import javax.imageio.spi.ImageReaderSpi; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.geotools.factory.Hints; import org.geotools.resources.image.ImageUtilities; import org.geotools.util.logging.Logging; /** * Listens for GeoServer startup and tries to configure axis order, logging * redirection, and a few other things that really need to be set up before * anything else starts up */ public class GeoserverInitStartupListener implements ServletContextListener { private static final Logger LOGGER = Logging .getLogger("org.geoserver.logging"); public void contextDestroyed(ServletContextEvent sce) { } public void contextInitialized(ServletContextEvent sce) { // if the server admin did not set it up otherwise, force X/Y axis // ordering // This one is a good place because we need to initialize this property // before any other opeation can trigger the initialization of the CRS // subsystem if (System.getProperty("org.geotools.referencing.forceXY") == null) { - Hints.putSystemDefault(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, - Boolean.TRUE); +// Hints.putSystemDefault(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, +// Boolean.TRUE); + System.setProperty("org.geotools.referencing.forceXY", "true"); } if (Boolean.TRUE.equals(Hints .getSystemDefault(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER))) { Hints.putSystemDefault(Hints.FORCE_AXIS_ORDER_HONORING, "http"); } // HACK: java.util.prefs are awful. See // http://www.allaboutbalance.com/disableprefs. When the site comes // back up we should implement their better way of fixing the problem. System.setProperty("java.util.prefs.syncInterval", "5000000"); // HACK: under JDK 1.4.2 the native java image i/o stuff is failing // in all containers besides Tomcat. If running under jdk 1.4.2 we // disable the native codecs, unless the user forced the setting already if (System.getProperty("java.version").startsWith("1.4") && (System.getProperty("com.sun.media.imageio.disableCodecLib") == null)) { LOGGER.warning("Disabling mediaLib acceleration since this is a " + "java 1.4 VM.\n If you want to force its enabling, " // + "set -Dcom.sun.media.imageio.disableCodecLib=true " + "in your virtual machine"); System.setProperty("com.sun.media.imageio.disableCodecLib", "true"); } else { // in any case, the native png reader is worse than the pure java ones, so // let's disable it (the native png writer is on the other side faster)... ImageUtilities.allowNativeCodec("png", ImageReaderSpi.class, false); } } }
true
true
public void contextInitialized(ServletContextEvent sce) { // if the server admin did not set it up otherwise, force X/Y axis // ordering // This one is a good place because we need to initialize this property // before any other opeation can trigger the initialization of the CRS // subsystem if (System.getProperty("org.geotools.referencing.forceXY") == null) { Hints.putSystemDefault(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE); } if (Boolean.TRUE.equals(Hints .getSystemDefault(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER))) { Hints.putSystemDefault(Hints.FORCE_AXIS_ORDER_HONORING, "http"); } // HACK: java.util.prefs are awful. See // http://www.allaboutbalance.com/disableprefs. When the site comes // back up we should implement their better way of fixing the problem. System.setProperty("java.util.prefs.syncInterval", "5000000"); // HACK: under JDK 1.4.2 the native java image i/o stuff is failing // in all containers besides Tomcat. If running under jdk 1.4.2 we // disable the native codecs, unless the user forced the setting already if (System.getProperty("java.version").startsWith("1.4") && (System.getProperty("com.sun.media.imageio.disableCodecLib") == null)) { LOGGER.warning("Disabling mediaLib acceleration since this is a " + "java 1.4 VM.\n If you want to force its enabling, " // + "set -Dcom.sun.media.imageio.disableCodecLib=true " + "in your virtual machine"); System.setProperty("com.sun.media.imageio.disableCodecLib", "true"); } else { // in any case, the native png reader is worse than the pure java ones, so // let's disable it (the native png writer is on the other side faster)... ImageUtilities.allowNativeCodec("png", ImageReaderSpi.class, false); } }
public void contextInitialized(ServletContextEvent sce) { // if the server admin did not set it up otherwise, force X/Y axis // ordering // This one is a good place because we need to initialize this property // before any other opeation can trigger the initialization of the CRS // subsystem if (System.getProperty("org.geotools.referencing.forceXY") == null) { // Hints.putSystemDefault(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, // Boolean.TRUE); System.setProperty("org.geotools.referencing.forceXY", "true"); } if (Boolean.TRUE.equals(Hints .getSystemDefault(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER))) { Hints.putSystemDefault(Hints.FORCE_AXIS_ORDER_HONORING, "http"); } // HACK: java.util.prefs are awful. See // http://www.allaboutbalance.com/disableprefs. When the site comes // back up we should implement their better way of fixing the problem. System.setProperty("java.util.prefs.syncInterval", "5000000"); // HACK: under JDK 1.4.2 the native java image i/o stuff is failing // in all containers besides Tomcat. If running under jdk 1.4.2 we // disable the native codecs, unless the user forced the setting already if (System.getProperty("java.version").startsWith("1.4") && (System.getProperty("com.sun.media.imageio.disableCodecLib") == null)) { LOGGER.warning("Disabling mediaLib acceleration since this is a " + "java 1.4 VM.\n If you want to force its enabling, " // + "set -Dcom.sun.media.imageio.disableCodecLib=true " + "in your virtual machine"); System.setProperty("com.sun.media.imageio.disableCodecLib", "true"); } else { // in any case, the native png reader is worse than the pure java ones, so // let's disable it (the native png writer is on the other side faster)... ImageUtilities.allowNativeCodec("png", ImageReaderSpi.class, false); } }
diff --git a/src/com/btmura/android/reddit/content/ProfileThingLoader.java b/src/com/btmura/android/reddit/content/ProfileThingLoader.java index 61509aae..f4cc21d7 100644 --- a/src/com/btmura/android/reddit/content/ProfileThingLoader.java +++ b/src/com/btmura/android/reddit/content/ProfileThingLoader.java @@ -1,71 +1,71 @@ /* * Copyright (C) 2013 Brian Muramatsu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmura.android.reddit.content; import android.content.Context; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import com.btmura.android.reddit.BuildConfig; import com.btmura.android.reddit.database.CursorExtrasWrapper; import com.btmura.android.reddit.database.HideActions; import com.btmura.android.reddit.provider.ThingProvider; import com.btmura.android.reddit.util.Array; import com.btmura.android.reddit.widget.FilterAdapter; public class ProfileThingLoader extends AbstractThingLoader { private static final String TAG = "ProfileThingLoader"; private final String accountName; private final String profileUser; private final int filter; private final String more; public ProfileThingLoader(Context context, String accountName, String profileUser, int filter, String more) { super(context); this.accountName = accountName; this.profileUser = profileUser; this.filter = filter; this.more = more; - setUri(ThingProvider.THINGS_URI); + setUri(ThingProvider.THINGS_WITH_ACTIONS_URI); setProjection(PROJECTION); setSelection(getSelectionStatement()); } private String getSelectionStatement() { return filter == FilterAdapter.PROFILE_HIDDEN ? HideActions.SELECT_HIDDEN_BY_SESSION_ID : HideActions.SELECT_UNHIDDEN_BY_SESSION_ID; } @Override public Cursor loadInBackground() { if (BuildConfig.DEBUG) { Log.d(TAG, "loadInBackground"); } Bundle result = ThingProvider.getProfileSession(getContext(), accountName, profileUser, filter, more); long sessionId = result.getLong(ThingProvider.EXTRA_SESSION_ID); setSelectionArgs(Array.of(sessionId)); return new CursorExtrasWrapper(super.loadInBackground(), result); } }
true
true
public ProfileThingLoader(Context context, String accountName, String profileUser, int filter, String more) { super(context); this.accountName = accountName; this.profileUser = profileUser; this.filter = filter; this.more = more; setUri(ThingProvider.THINGS_URI); setProjection(PROJECTION); setSelection(getSelectionStatement()); }
public ProfileThingLoader(Context context, String accountName, String profileUser, int filter, String more) { super(context); this.accountName = accountName; this.profileUser = profileUser; this.filter = filter; this.more = more; setUri(ThingProvider.THINGS_WITH_ACTIONS_URI); setProjection(PROJECTION); setSelection(getSelectionStatement()); }
diff --git a/MyParser.java b/MyParser.java index 78aba42..b5c16a8 100755 --- a/MyParser.java +++ b/MyParser.java @@ -1,817 +1,817 @@ //--------------------------------------------------------------------- // //--------------------------------------------------------------------- import java_cup.runtime.*; import java.util.Vector; class MyParser extends parser { //---------------------------------------------------------------- // Instance variables //---------------------------------------------------------------- private Lexer m_lexer; private ErrorPrinter m_errors; private int m_nNumErrors; private String m_strLastLexeme; private boolean m_bSyntaxError = true; private int m_nSavedLineNum; private SymbolTable m_symtab; //---------------------------------------------------------------- // //---------------------------------------------------------------- public MyParser(Lexer lexer, ErrorPrinter errors) { m_lexer = lexer; m_symtab = new SymbolTable(); m_errors = errors; m_nNumErrors = 0; } //---------------------------------------------------------------- // //---------------------------------------------------------------- public boolean Ok() { return (m_nNumErrors == 0); } //---------------------------------------------------------------- // //---------------------------------------------------------------- public Symbol scan() { Token t = m_lexer.GetToken(); // We'll save the last token read for error messages. // Sometimes, the token is lost reading for the next // token which can be null. m_strLastLexeme = t.GetLexeme(); switch(t.GetCode()) { case sym.T_ID: case sym.T_ID_U: case sym.T_STR_LITERAL: case sym.T_FLOAT_LITERAL: case sym.T_INT_LITERAL: case sym.T_CHAR_LITERAL: return (new Symbol(t.GetCode(), t.GetLexeme())); default: return (new Symbol(t.GetCode())); } } //---------------------------------------------------------------- // //---------------------------------------------------------------- public void syntax_error(Symbol s) { } //---------------------------------------------------------------- // //---------------------------------------------------------------- public void report_fatal_error(Symbol s) { m_nNumErrors++; if(m_bSyntaxError) { m_nNumErrors++; // It is possible that the error was detected // at the end of a line - in which case, s will // be null. Instead, we saved the last token // read in to give a more meaningful error // message. m_errors.print(Formatter.toString(ErrorMsg.syntax_error, m_strLastLexeme)); } } //---------------------------------------------------------------- // //---------------------------------------------------------------- public void unrecovered_syntax_error(Symbol s) { report_fatal_error(s); } //---------------------------------------------------------------- // //---------------------------------------------------------------- public void DisableSyntaxError() { m_bSyntaxError = false; } public void EnableSyntaxError() { m_bSyntaxError = true; } //---------------------------------------------------------------- // //---------------------------------------------------------------- public String GetFile() { return (m_lexer.getEPFilename()); } public int GetLineNum() { return (m_lexer.getLineNumber()); } public void SaveLineNum() { m_nSavedLineNum = m_lexer.getLineNumber(); } public int GetSavedLineNum() { return (m_nSavedLineNum); } //---------------------------------------------------------------- // //---------------------------------------------------------------- void DoProgramStart() { // Opens the global scope. m_symtab.openScope(); } //---------------------------------------------------------------- // //---------------------------------------------------------------- void DoProgramEnd() { m_symtab.closeScope(); } //---------------------------------------------------------------- // //---------------------------------------------------------------- void DoVarDecl(Type type, Vector<String> lstIDs) { for(int i = 0; i < lstIDs.size(); i++) { String id = lstIDs.elementAt(i); // Check for var already existing in localScope if(m_symtab.accessLocal(id) != null) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.redeclared_id, id)); } VarSTO sto = new VarSTO(id, type); m_symtab.insert(sto); } } //---------------------------------------------------------------- // //---------------------------------------------------------------- void DoExternDecl(Vector<String> lstIDs) { for(int i = 0; i < lstIDs.size(); i++) { String id = lstIDs.elementAt(i); if(m_symtab.accessLocal(id) != null) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.redeclared_id, id)); } VarSTO sto = new VarSTO(id); m_symtab.insert(sto); } } //---------------------------------------------------------------- // //---------------------------------------------------------------- void DoConstDecl(Vector<String> lstIDs) { for(int i = 0; i < lstIDs.size(); i++) { String id = lstIDs.elementAt(i); if(m_symtab.accessLocal(id) != null) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.redeclared_id, id)); } ConstSTO sto = new ConstSTO(id); m_symtab.insert(sto); } } //---------------------------------------------------------------- // //---------------------------------------------------------------- void DoTypedefDecl(Vector<String> lstIDs) { for(int i = 0; i < lstIDs.size(); i++) { String id = lstIDs.elementAt(i); if(m_symtab.accessLocal(id) != null) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.redeclared_id, id)); } TypedefSTO sto = new TypedefSTO(id); m_symtab.insert(sto); } } //---------------------------------------------------------------- // //---------------------------------------------------------------- void DoStructdefDecl(String id) { if(m_symtab.accessLocal(id) != null) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.redeclared_id, id)); } TypedefSTO sto = new TypedefSTO(id); m_symtab.insert(sto); } //---------------------------------------------------------------- // //---------------------------------------------------------------- void DoFuncDecl_1(Type returnType, String id, Boolean retByRef) { // Check for func already existing in localScope if(m_symtab.accessLocal(id) != null) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.redeclared_id, id)); } FuncSTO sto = new FuncSTO(id, retByRef); // Set return type sto.setReturnType(returnType); m_symtab.insert(sto); m_symtab.openScope(); m_symtab.setFunc(sto); // Set the function's level sto.setLevel(m_symtab.getLevel()); } //---------------------------------------------------------------- // //---------------------------------------------------------------- void DoFuncDecl_2() { FuncSTO stoFunc; if((stoFunc = m_symtab.getFunc()) == null) { m_nNumErrors++; m_errors.print("internal: DoFuncDecl_2 says no proc!"); return; } // Check #6c - no return statement for non-void type function if(!stoFunc.getReturnType().isVoid()) { if(!stoFunc.getHasReturnStatement()) { m_nNumErrors++; m_errors.print(ErrorMsg.error6c_Return_missing); } } m_symtab.closeScope(); m_symtab.setFunc(null); } //---------------------------------------------------------------- // //---------------------------------------------------------------- void DoFormalParams(Vector<ParamSTO> params) { FuncSTO stoFunc; if((stoFunc = m_symtab.getFunc()) == null) { m_nNumErrors++; m_errors.print("internal: DoFormalParams says no proc!"); return; } // Insert parameters stoFunc.setParameters(params); // Add parameters to local scope for(STO thisParam: params) { /* Not sure if want this check if(m_symtab.accessLocal(id) != null) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.redeclared_id, id)); } */ m_symtab.insert(thisParam); } } //---------------------------------------------------------------- // //---------------------------------------------------------------- void DoBlockOpen() { // Open a scope. m_symtab.openScope(); } //---------------------------------------------------------------- // //---------------------------------------------------------------- void DoBlockClose() { m_symtab.closeScope(); } //---------------------------------------------------------------- // //---------------------------------------------------------------- STO DoAssignExpr(STO stoDes, STO stoValue) { // Check for previous errors in line and short circuit if(stoDes.isError()) { return stoDes; } if(stoValue.isError()) { return stoValue; } // Check #3a - illegal assignment - not modifiable L-value if(!stoDes.isModLValue()) { m_nNumErrors++; m_errors.print(ErrorMsg.error3a_Assign); return (new ErrorSTO("DoAssignExpr Error - not mod-L-Value")); } if(!stoValue.getType().isAssignable(stoDes.getType())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error3b_Assign, stoValue.getType().getName(), stoDes.getType().getName())); return (new ErrorSTO("DoAssignExpr Error - bad types")); } return stoDes; } //---------------------------------------------------------------- // //---------------------------------------------------------------- STO DoFuncCall(STO sto, Vector<ExprSTO> args) { if(!sto.isFunc()) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.not_function, sto.getName())); return (new ErrorSTO(sto.getName())); } // We know it's a function, do function call checks FuncSTO stoFunc =(FuncSTO)sto; // Check #5 // Check #5a - # args = # params if((stoFunc.getNumOfParams() != args.size())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error5n_Call, args.size(), stoFunc.getNumOfParams())); return (new ErrorSTO("DoFuncCall - # args")); } // Now we check each arg individually, accepting one error per arg boolean error_flag = false; for(int i = 0; i < args.size(); i++) { // For readability and shorter lines ParamSTO thisParam = stoFunc.getParameters().elementAt(i); - ExprSTO thisArg = args.elementAt(i); + STO thisArg = args.elementAt(i); // Check #5b - non-assignable arg for pass-by-value param if(!thisParam.isPassByReference()) { if(!thisArg.getType().isAssignable(thisParam.getType())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error5a_Call, thisArg.getType().getName(), thisParam.getName(), thisParam.getType().getName())); error_flag = true; } } // Check #5c - arg type not equivalent to pass-by-ref param type else if(thisParam.isPassByReference()) { if(!thisArg.getType().isEquivalent(thisParam.getType())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error5r_Call, thisArg.getType().getName(), thisParam.getName(), thisParam.getType().getName())); error_flag = true; } } // Check #5d - arg not modifiable l-value for pass by ref param else if(thisParam.isPassByReference()) { if(!thisArg.isModLValue()) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error5c_Call, thisArg.getName(), thisArg.getType().getName())); error_flag = true; } } } if(error_flag) { // Error occured in at least one arg, return error return (new ErrorSTO("DoFuncCall - Check 5")); } else { // Func call legal, return function return type return (new ExprSTO(stoFunc.getName() + " return type", stoFunc.getReturnType())); } } //---------------------------------------------------------------- // //---------------------------------------------------------------- STO DoDesignator2_Dot(STO sto, String strID) { // Good place to do the struct checks return sto; } //---------------------------------------------------------------- // //---------------------------------------------------------------- STO DoDesignator2_Array(STO sto) { // Good place to do the array checks return sto; } //---------------------------------------------------------------- // //---------------------------------------------------------------- STO DoDesignator3_GlobalID(String strID) { STO sto; if((sto = m_symtab.accessGlobal(strID)) == null) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error0g_Scope, strID)); sto = new ErrorSTO(strID); } return (sto); } //---------------------------------------------------------------- // //---------------------------------------------------------------- STO DoDesignator3_ID(String strID) { STO sto; if((sto = m_symtab.access(strID)) == null) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.undeclared_id, strID)); sto = new ErrorSTO(strID); } return (sto); } //---------------------------------------------------------------- // //---------------------------------------------------------------- STO DoQualIdent(String strID) { STO sto; if((sto = m_symtab.access(strID)) == null) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.undeclared_id, strID)); return (new ErrorSTO(strID)); } if(!sto.isTypedef()) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.not_type, sto.getName())); return (new ErrorSTO(sto.getName())); } return (sto); } //---------------------------------------------------------------- // DoBinaryOp //---------------------------------------------------------------- STO DoBinaryOp(BinaryOp op, STO operand1, STO operand2) { // Check for previous errors in line and short circuit if(operand1.isError()) { return operand1; } if(operand2.isError()) { return operand2; } // Use BinaryOp.checkOperands() to perform error checks STO resultSTO = op.checkOperands(operand1, operand2); // Process/Print errors if(resultSTO.isError()) { m_nNumErrors++; m_errors.print(resultSTO.getName()); } return resultSTO; } //---------------------------------------------------------------- // DoUnaryOp //---------------------------------------------------------------- STO DoUnaryOp(UnaryOp op, STO operand) { // Check for previous errors in line and short circuit if(operand.isError()) { return operand; } // Use UnaryOp.checkOperand() to perform error checks STO resultSTO = op.checkOperand(operand); // Process/Print errors if(resultSTO.isError()) { m_nNumErrors++; m_errors.print(resultSTO.getName()); } return resultSTO; } //---------------------------------------------------------------- // DoWhileExpr //---------------------------------------------------------------- STO DoWhileExpr(STO stoExpr) { // Check for previous errors in line and short circuit if(stoExpr.isError()) { return stoExpr; } // Check #4 - while expr - int or bool if((!stoExpr.getType().isInt()) &&(!stoExpr.getType().isBool())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error4_Test, stoExpr.getType().getName())); return (new ErrorSTO("DoWhile error")); } return stoExpr; } //---------------------------------------------------------------- // DoIfExpr //---------------------------------------------------------------- STO DoIfExpr(STO stoExpr) { // Check for previous errors in line and short circuit if(stoExpr.isError()) { return stoExpr; } // Check #4 - if expr - int or bool if((!stoExpr.getType().isInt()) &&(!stoExpr.getType().isBool())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error4_Test, stoExpr.getType().getName())); return (new ErrorSTO("DoIf error")); } return stoExpr; } //---------------------------------------------------------------- // DoReturnStmt_1 //---------------------------------------------------------------- STO DoReturnStmt_1() { FuncSTO stoFunc; if((stoFunc = m_symtab.getFunc()) == null) { m_nNumErrors++; m_errors.print("internal: DoReturnStmt_1 says no proc!"); return (new ErrorSTO("DoReturnStmt_1 Error")); } // Check #6a - no expr on non-void rtn if(!stoFunc.getReturnType().isVoid()) { m_nNumErrors++; m_errors.print(ErrorMsg.error6a_Return_expr); return (new ErrorSTO("DoReturnStmt_1 Error")); } // valid return statement, set func.hasReturnStatement if at right level if(stoFunc.getLevel() == m_symtab.getLevel()) { stoFunc.setHasReturnStatement(true); } return (new ExprSTO(stoFunc.getName() + " Return", new VoidType())); } //---------------------------------------------------------------- // DoReturnStmt_2 //---------------------------------------------------------------- STO DoReturnStmt_2(STO stoExpr) { FuncSTO stoFunc; // Check for previous errors in line and short circuit if(stoExpr.isError()) { return stoExpr; } if((stoFunc = m_symtab.getFunc()) == null) { m_nNumErrors++; m_errors.print("internal: DoReturnStmt_2 says no proc!"); return (new ErrorSTO("DoReturnStmt_2 Error")); } // Check #6b - 1st bullet - rtn by val - rtn expr type not assignable to return if(!stoFunc.getReturnByRef()) { if(!stoExpr.getType().isAssignable(stoFunc.getReturnType())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg. error6a_Return_type, stoExpr.getType().getName(), stoFunc.getReturnType().getName())); return (new ErrorSTO("DoReturnStmt_2 Error")); } } else { // Check #6b - 2nd bullet - rtn by ref - rtn expr type not equivalent to return type if(!stoExpr.getType().isEquivalent(stoFunc.getReturnType())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error6b_Return_equiv, stoExpr.getType().getName(), stoFunc.getReturnType().getName())); return (new ErrorSTO("DoReturnStmt_2 Error")); } // Check #6b - 3rd bullet - rtn by ref - rtn expr not modLValue if(!stoExpr.isModLValue()) { m_nNumErrors++; m_errors.print(ErrorMsg.error6b_Return_modlval); return (new ErrorSTO("DoReturnStmt_2 Error")); } } // valid return statement, set func.hasReturnStatement if at right level if(stoFunc.getLevel() == m_symtab.getLevel()) { stoFunc.setHasReturnStatement(true); } return stoExpr; } //---------------------------------------------------------------- // DoExitStmt //---------------------------------------------------------------- STO DoExitStmt(STO stoExpr) { // Check for previous errors in line and short circuit if(stoExpr.isError()) { return stoExpr; } // Check #7 - exit value assignable to int if(!stoExpr.getType().isAssignable(new IntType())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error7_Exit, stoExpr.getType().getName())); } return stoExpr; } }
true
true
STO DoFuncCall(STO sto, Vector<ExprSTO> args) { if(!sto.isFunc()) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.not_function, sto.getName())); return (new ErrorSTO(sto.getName())); } // We know it's a function, do function call checks FuncSTO stoFunc =(FuncSTO)sto; // Check #5 // Check #5a - # args = # params if((stoFunc.getNumOfParams() != args.size())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error5n_Call, args.size(), stoFunc.getNumOfParams())); return (new ErrorSTO("DoFuncCall - # args")); } // Now we check each arg individually, accepting one error per arg boolean error_flag = false; for(int i = 0; i < args.size(); i++) { // For readability and shorter lines ParamSTO thisParam = stoFunc.getParameters().elementAt(i); ExprSTO thisArg = args.elementAt(i); // Check #5b - non-assignable arg for pass-by-value param if(!thisParam.isPassByReference()) { if(!thisArg.getType().isAssignable(thisParam.getType())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error5a_Call, thisArg.getType().getName(), thisParam.getName(), thisParam.getType().getName())); error_flag = true; } } // Check #5c - arg type not equivalent to pass-by-ref param type else if(thisParam.isPassByReference()) { if(!thisArg.getType().isEquivalent(thisParam.getType())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error5r_Call, thisArg.getType().getName(), thisParam.getName(), thisParam.getType().getName())); error_flag = true; } } // Check #5d - arg not modifiable l-value for pass by ref param else if(thisParam.isPassByReference()) { if(!thisArg.isModLValue()) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error5c_Call, thisArg.getName(), thisArg.getType().getName())); error_flag = true; } } } if(error_flag) { // Error occured in at least one arg, return error return (new ErrorSTO("DoFuncCall - Check 5")); } else { // Func call legal, return function return type return (new ExprSTO(stoFunc.getName() + " return type", stoFunc.getReturnType())); } }
STO DoFuncCall(STO sto, Vector<ExprSTO> args) { if(!sto.isFunc()) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.not_function, sto.getName())); return (new ErrorSTO(sto.getName())); } // We know it's a function, do function call checks FuncSTO stoFunc =(FuncSTO)sto; // Check #5 // Check #5a - # args = # params if((stoFunc.getNumOfParams() != args.size())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error5n_Call, args.size(), stoFunc.getNumOfParams())); return (new ErrorSTO("DoFuncCall - # args")); } // Now we check each arg individually, accepting one error per arg boolean error_flag = false; for(int i = 0; i < args.size(); i++) { // For readability and shorter lines ParamSTO thisParam = stoFunc.getParameters().elementAt(i); STO thisArg = args.elementAt(i); // Check #5b - non-assignable arg for pass-by-value param if(!thisParam.isPassByReference()) { if(!thisArg.getType().isAssignable(thisParam.getType())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error5a_Call, thisArg.getType().getName(), thisParam.getName(), thisParam.getType().getName())); error_flag = true; } } // Check #5c - arg type not equivalent to pass-by-ref param type else if(thisParam.isPassByReference()) { if(!thisArg.getType().isEquivalent(thisParam.getType())) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error5r_Call, thisArg.getType().getName(), thisParam.getName(), thisParam.getType().getName())); error_flag = true; } } // Check #5d - arg not modifiable l-value for pass by ref param else if(thisParam.isPassByReference()) { if(!thisArg.isModLValue()) { m_nNumErrors++; m_errors.print(Formatter.toString(ErrorMsg.error5c_Call, thisArg.getName(), thisArg.getType().getName())); error_flag = true; } } } if(error_flag) { // Error occured in at least one arg, return error return (new ErrorSTO("DoFuncCall - Check 5")); } else { // Func call legal, return function return type return (new ExprSTO(stoFunc.getName() + " return type", stoFunc.getReturnType())); } }
diff --git a/Comecocos/src/Escenario.java b/Comecocos/src/Escenario.java index 2ae148e..764eced 100644 --- a/Comecocos/src/Escenario.java +++ b/Comecocos/src/Escenario.java @@ -1,78 +1,79 @@ import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.KeyStroke; public class Escenario extends JPanel implements Runnable,ActionListener{ private Laberinto l=Laberinto.ORIGINAL; private PacMan pacman=new PacMan(l,"/img/comecocos.png"); Thread t; boolean iniciado= false; Direccion direccion; public Escenario() { + direccion=pacman.getDireccion(); setPreferredSize(new Dimension(l.getImagen().getWidth(),l.getImagen().getHeight())); registerKeyboardAction(this, "iniciar", KeyStroke.getKeyStroke(KeyEvent.VK_I, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); registerKeyboardAction(this, "arriba", KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); registerKeyboardAction(this, "abajo", KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); registerKeyboardAction(this, "izquierda", KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); registerKeyboardAction(this, "derecha", KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); } @Override protected void paintComponent(Graphics g) { g.drawImage(l.getImagen(), 0, 0, this); int x = (int) pacman.getPosicion().x; int y = (int) pacman.getPosicion().y; int xs=35; int ys=70; g.drawImage(pacman.getImg(), x, y, x+35, y+35, xs, ys, xs+35, ys+35, this); } public void iniciar(){ t=new Thread(this); iniciado=true; t.start(); } @Override public void run() { while(iniciado){ pacman.mover(0.5,direccion); repaint(); try { Thread.sleep(5); } catch (InterruptedException e) { } } } @Override public void actionPerformed(ActionEvent e) { if(e.getActionCommand().equals("iniciar")) iniciar(); else if(e.getActionCommand().equals("arriba")) direccion=Direccion.ARRIBA; else if(e.getActionCommand().equals("abajo")) direccion=Direccion.ABAJO; else if(e.getActionCommand().equals("izquierda")) direccion=Direccion.IZDA; else if(e.getActionCommand().equals("derecha")) direccion=Direccion.DERECHA; } }
true
true
public Escenario() { setPreferredSize(new Dimension(l.getImagen().getWidth(),l.getImagen().getHeight())); registerKeyboardAction(this, "iniciar", KeyStroke.getKeyStroke(KeyEvent.VK_I, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); registerKeyboardAction(this, "arriba", KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); registerKeyboardAction(this, "abajo", KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); registerKeyboardAction(this, "izquierda", KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); registerKeyboardAction(this, "derecha", KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); }
public Escenario() { direccion=pacman.getDireccion(); setPreferredSize(new Dimension(l.getImagen().getWidth(),l.getImagen().getHeight())); registerKeyboardAction(this, "iniciar", KeyStroke.getKeyStroke(KeyEvent.VK_I, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); registerKeyboardAction(this, "arriba", KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); registerKeyboardAction(this, "abajo", KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); registerKeyboardAction(this, "izquierda", KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); registerKeyboardAction(this, "derecha", KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); }
diff --git a/bundles/org.eclipse.emf.emfstore.server/src/org/eclipse/emf/emfstore/internal/server/connection/xmlrpc/XmlRpcWebserverManager.java b/bundles/org.eclipse.emf.emfstore.server/src/org/eclipse/emf/emfstore/internal/server/connection/xmlrpc/XmlRpcWebserverManager.java index 5ed726b1e..2f149b3f9 100644 --- a/bundles/org.eclipse.emf.emfstore.server/src/org/eclipse/emf/emfstore/internal/server/connection/xmlrpc/XmlRpcWebserverManager.java +++ b/bundles/org.eclipse.emf.emfstore.server/src/org/eclipse/emf/emfstore/internal/server/connection/xmlrpc/XmlRpcWebserverManager.java @@ -1,182 +1,182 @@ /******************************************************************************* * Copyright (c) 2008-2011 Chair for Applied Software Engineering, * Technische Universitaet Muenchen. * 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: * wesendon ******************************************************************************/ package org.eclipse.emf.emfstore.internal.server.connection.xmlrpc; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLServerSocketFactory; import org.apache.xmlrpc.XmlRpcException; import org.apache.xmlrpc.server.PropertyHandlerMapping; import org.apache.xmlrpc.server.XmlRpcServer; import org.apache.xmlrpc.server.XmlRpcServerConfigImpl; import org.apache.xmlrpc.webserver.WebServer; import org.eclipse.emf.emfstore.internal.common.model.util.ModelUtil; import org.eclipse.emf.emfstore.internal.server.EMFStoreController; import org.eclipse.emf.emfstore.internal.server.ServerConfiguration; import org.eclipse.emf.emfstore.internal.server.connection.ServerKeyStoreManager; import org.eclipse.emf.emfstore.internal.server.connection.xmlrpc.util.EObjectTypeConverterFactory; import org.eclipse.emf.emfstore.internal.server.connection.xmlrpc.util.EObjectTypeFactory; import org.eclipse.emf.emfstore.internal.server.exceptions.FatalESException; import org.eclipse.emf.emfstore.internal.server.exceptions.ServerKeyStoreException; /** * Manages the webserver for XML RPC connections. * * @author wesendon */ public final class XmlRpcWebserverManager { /** * Initializes the singleton instance statically. */ private static class SingletonHolder { public static final XmlRpcWebserverManager INSTANCE = new XmlRpcWebserverManager(); } /** * Returns an instance of the webserver manager. * * @return instance of websever manager. */ public static XmlRpcWebserverManager getInstance() { return SingletonHolder.INSTANCE; } private WebServer webServer; private final int port; private XmlRpcWebserverManager() { int tmp = 8080; try { tmp = Integer.valueOf(ServerConfiguration.getProperties().getProperty(ServerConfiguration.XML_RPC_PORT)); } catch (final NumberFormatException e) { tmp = Integer.valueOf(ServerConfiguration.XML_RPC_PORT_DEFAULT); } port = tmp; } /** * Starts the server. * * @throws FatalESException in case of failure */ public void initServer() throws FatalESException { if (webServer != null) { return; } try { - webServer = new EMFStoreWebServer(port) { + webServer = new WebServer(port) { @Override protected ServerSocket createServerSocket(int pPort, int backlog, InetAddress addr) throws IOException { SSLServerSocketFactory serverSocketFactory = null; try { final SSLContext context = SSLContext.getInstance("TLS"); context.init(ServerKeyStoreManager.getInstance().getKeyManagerFactory().getKeyManagers(), null, null); serverSocketFactory = context.getServerSocketFactory(); } catch (final NoSuchAlgorithmException exception) { shutdown(serverSocketFactory, exception); } catch (final KeyManagementException exception) { shutdown(serverSocketFactory, exception); } catch (final ServerKeyStoreException exception) { shutdown(serverSocketFactory, exception); } return serverSocketFactory.createServerSocket(pPort, backlog, addr); } private void shutdown(SSLServerSocketFactory serverSocketFactory, Exception e) { if (serverSocketFactory == null) { ModelUtil.logException("Couldn't initialize server socket.", e); EMFStoreController.getInstance().shutdown(new FatalESException()); } } }; ModelUtil.logInfo("Started XML RPC Webserver on port: " + port); final XmlRpcServer xmlRpcServer = webServer.getXmlRpcServer(); xmlRpcServer.setTypeFactory(new EObjectTypeFactory(xmlRpcServer)); final EObjectTypeConverterFactory pFactory = new EObjectTypeConverterFactory(); xmlRpcServer.setTypeConverterFactory(pFactory); final PropertyHandlerMapping phm = new PropertyHandlerMapping(); phm.setVoidMethodEnabled(true); phm.setTypeConverterFactory(pFactory); xmlRpcServer.setHandlerMapping(phm); final XmlRpcServerConfigImpl serverConfig = (XmlRpcServerConfigImpl) xmlRpcServer.getConfig(); serverConfig.setEnabledForExtensions(true); serverConfig.setEnabledForExceptions(true); serverConfig.setContentLengthOptional(true); webServer.start(); } catch (final IOException e) { throw new FatalESException("Couldn't start webserver", e); } } /** * Adds a handler to the webserver. * * @param handlerName handler name * @param clazz class of server interface * @throws FatalESException in case of failure */ public void addHandler(String handlerName, Class<?> clazz) throws FatalESException { try { final PropertyHandlerMapping mapper = (PropertyHandlerMapping) webServer.getXmlRpcServer() .getHandlerMapping(); mapper.addHandler(handlerName, clazz); } catch (final XmlRpcException e) { throw new FatalESException("Couldn't add handler", e); } } /** * Removes a handler from the Webserver. * * @param handlerName the handler's name * @return true, if other handler still available */ public boolean removeHandler(String handlerName) { final PropertyHandlerMapping mapper = (PropertyHandlerMapping) webServer.getXmlRpcServer().getHandlerMapping(); mapper.removeHandler(handlerName); try { return mapper.getListMethods().length > 0; } catch (final XmlRpcException e) { return false; } } /** * Stops the server. * * @param force * should be set to {@code true}, if handler should be stopped forcefully */ public void stopServer(boolean force) { webServer.shutdown(); webServer = null; } }
true
true
public void initServer() throws FatalESException { if (webServer != null) { return; } try { webServer = new EMFStoreWebServer(port) { @Override protected ServerSocket createServerSocket(int pPort, int backlog, InetAddress addr) throws IOException { SSLServerSocketFactory serverSocketFactory = null; try { final SSLContext context = SSLContext.getInstance("TLS"); context.init(ServerKeyStoreManager.getInstance().getKeyManagerFactory().getKeyManagers(), null, null); serverSocketFactory = context.getServerSocketFactory(); } catch (final NoSuchAlgorithmException exception) { shutdown(serverSocketFactory, exception); } catch (final KeyManagementException exception) { shutdown(serverSocketFactory, exception); } catch (final ServerKeyStoreException exception) { shutdown(serverSocketFactory, exception); } return serverSocketFactory.createServerSocket(pPort, backlog, addr); } private void shutdown(SSLServerSocketFactory serverSocketFactory, Exception e) { if (serverSocketFactory == null) { ModelUtil.logException("Couldn't initialize server socket.", e); EMFStoreController.getInstance().shutdown(new FatalESException()); } } }; ModelUtil.logInfo("Started XML RPC Webserver on port: " + port); final XmlRpcServer xmlRpcServer = webServer.getXmlRpcServer(); xmlRpcServer.setTypeFactory(new EObjectTypeFactory(xmlRpcServer)); final EObjectTypeConverterFactory pFactory = new EObjectTypeConverterFactory(); xmlRpcServer.setTypeConverterFactory(pFactory); final PropertyHandlerMapping phm = new PropertyHandlerMapping(); phm.setVoidMethodEnabled(true); phm.setTypeConverterFactory(pFactory); xmlRpcServer.setHandlerMapping(phm); final XmlRpcServerConfigImpl serverConfig = (XmlRpcServerConfigImpl) xmlRpcServer.getConfig(); serverConfig.setEnabledForExtensions(true); serverConfig.setEnabledForExceptions(true); serverConfig.setContentLengthOptional(true); webServer.start(); } catch (final IOException e) { throw new FatalESException("Couldn't start webserver", e); } }
public void initServer() throws FatalESException { if (webServer != null) { return; } try { webServer = new WebServer(port) { @Override protected ServerSocket createServerSocket(int pPort, int backlog, InetAddress addr) throws IOException { SSLServerSocketFactory serverSocketFactory = null; try { final SSLContext context = SSLContext.getInstance("TLS"); context.init(ServerKeyStoreManager.getInstance().getKeyManagerFactory().getKeyManagers(), null, null); serverSocketFactory = context.getServerSocketFactory(); } catch (final NoSuchAlgorithmException exception) { shutdown(serverSocketFactory, exception); } catch (final KeyManagementException exception) { shutdown(serverSocketFactory, exception); } catch (final ServerKeyStoreException exception) { shutdown(serverSocketFactory, exception); } return serverSocketFactory.createServerSocket(pPort, backlog, addr); } private void shutdown(SSLServerSocketFactory serverSocketFactory, Exception e) { if (serverSocketFactory == null) { ModelUtil.logException("Couldn't initialize server socket.", e); EMFStoreController.getInstance().shutdown(new FatalESException()); } } }; ModelUtil.logInfo("Started XML RPC Webserver on port: " + port); final XmlRpcServer xmlRpcServer = webServer.getXmlRpcServer(); xmlRpcServer.setTypeFactory(new EObjectTypeFactory(xmlRpcServer)); final EObjectTypeConverterFactory pFactory = new EObjectTypeConverterFactory(); xmlRpcServer.setTypeConverterFactory(pFactory); final PropertyHandlerMapping phm = new PropertyHandlerMapping(); phm.setVoidMethodEnabled(true); phm.setTypeConverterFactory(pFactory); xmlRpcServer.setHandlerMapping(phm); final XmlRpcServerConfigImpl serverConfig = (XmlRpcServerConfigImpl) xmlRpcServer.getConfig(); serverConfig.setEnabledForExtensions(true); serverConfig.setEnabledForExceptions(true); serverConfig.setContentLengthOptional(true); webServer.start(); } catch (final IOException e) { throw new FatalESException("Couldn't start webserver", e); } }
diff --git a/org.eclipse.mylyn.gerrit.ui/src/org/eclipse/mylyn/internal/gerrit/ui/editor/PatchSetSection.java b/org.eclipse.mylyn.gerrit.ui/src/org/eclipse/mylyn/internal/gerrit/ui/editor/PatchSetSection.java index baa2d60c..3ca3d329 100644 --- a/org.eclipse.mylyn.gerrit.ui/src/org/eclipse/mylyn/internal/gerrit/ui/editor/PatchSetSection.java +++ b/org.eclipse.mylyn.gerrit.ui/src/org/eclipse/mylyn/internal/gerrit/ui/editor/PatchSetSection.java @@ -1,613 +1,615 @@ /******************************************************************************* * Copyright (c) 2010 Tasktop Technologies 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: * Tasktop Technologies - initial API and implementation * Sascha Scholz (SAP) - improvements * Sam Davis - improvements for bug 383592 *******************************************************************************/ package org.eclipse.mylyn.internal.gerrit.ui.editor; import java.io.IOException; import java.text.DateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.eclipse.compare.CompareConfiguration; import org.eclipse.compare.CompareUI; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.eclipse.egit.ui.internal.commit.CommitEditor; import org.eclipse.egit.ui.internal.fetch.FetchGerritChangeWizard; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.util.EContentAdapter; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider; import org.eclipse.jface.viewers.IOpenListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.OpenEvent; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.window.Window; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.mylyn.internal.gerrit.core.GerritCorePlugin; import org.eclipse.mylyn.internal.gerrit.core.GerritTaskSchema; import org.eclipse.mylyn.internal.gerrit.core.GerritUtil; import org.eclipse.mylyn.internal.gerrit.core.ReviewItemCache; import org.eclipse.mylyn.internal.gerrit.core.client.GerritChange; import org.eclipse.mylyn.internal.gerrit.core.client.GerritPatchSetContent; import org.eclipse.mylyn.internal.gerrit.core.client.compat.ChangeDetailX; import org.eclipse.mylyn.internal.gerrit.core.egit.GerritToGitMapping; import org.eclipse.mylyn.internal.gerrit.ui.GerritReviewBehavior; import org.eclipse.mylyn.internal.gerrit.ui.GerritUiPlugin; import org.eclipse.mylyn.internal.gerrit.ui.egit.EGitUiUtil; import org.eclipse.mylyn.internal.gerrit.ui.operations.AbandonDialog; import org.eclipse.mylyn.internal.gerrit.ui.operations.PublishDialog; import org.eclipse.mylyn.internal.gerrit.ui.operations.RestoreDialog; import org.eclipse.mylyn.internal.gerrit.ui.operations.SubmitDialog; import org.eclipse.mylyn.internal.reviews.ui.compare.FileItemCompareEditorInput; import org.eclipse.mylyn.internal.tasks.ui.editors.EditorUtil; import org.eclipse.mylyn.reviews.core.model.IFileItem; import org.eclipse.mylyn.reviews.core.model.IReviewItem; import org.eclipse.mylyn.reviews.core.model.IReviewItemSet; import org.eclipse.mylyn.reviews.internal.core.model.ReviewsPackage; import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPage; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Button; 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.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.forms.IFormColors; import org.eclipse.ui.forms.events.ExpansionAdapter; import org.eclipse.ui.forms.events.ExpansionEvent; import org.eclipse.ui.forms.events.HyperlinkAdapter; import org.eclipse.ui.forms.events.HyperlinkEvent; import org.eclipse.ui.forms.widgets.ExpandableComposite; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.Hyperlink; import org.eclipse.ui.forms.widgets.Section; import org.eclipse.ui.internal.IWorkbenchGraphicConstants; import org.eclipse.ui.internal.WorkbenchImages; import org.eclipse.ui.statushandlers.StatusManager; import com.google.gerrit.common.data.ChangeDetail; import com.google.gerrit.common.data.PatchSetDetail; import com.google.gerrit.common.data.PatchSetPublishDetail; import com.google.gerrit.reviewdb.ApprovalCategory; import com.google.gerrit.reviewdb.Patch; import com.google.gerrit.reviewdb.PatchSet; /** * @author Steffen Pingel * @author Sascha Scholz */ public class PatchSetSection extends AbstractGerritSection { private class CompareAction extends Action { private final PatchSet base; private final PatchSet target; private final ChangeDetail changeDetail; public CompareAction(ChangeDetail changeDetail, PatchSet base, PatchSet target) { this.changeDetail = changeDetail; this.base = base; this.target = target; } public void fill(Menu menu) { MenuItem item = new MenuItem(menu, SWT.NONE); item.setText(NLS.bind("Compare with Patch Set {0}", base.getPatchSetId())); item.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { run(); } }); } @Override public void run() { doCompareWith(changeDetail, base, target); } } private Composite composite; private final List<Job> jobs; private FormToolkit toolkit; // XXX drafts added after the publish detail was refreshed from server private int addedDrafts; private final ReviewItemCache cache; public PatchSetSection() { setPartName("Patch Sets"); this.jobs = new ArrayList<Job>(); this.cache = new ReviewItemCache(); } @Override public void dispose() { for (Job job : jobs) { job.cancel(); } super.dispose(); } public void updateTextClient(Section section, final PatchSetDetail patchSetDetail, boolean cachingInProgress) { String message; String time = DateFormat.getDateTimeInstance().format(patchSetDetail.getPatchSet().getCreatedOn()); int numComments = getNumComments(patchSetDetail); if (numComments > 0) { message = NLS.bind("{0}, {1} Comments", time, numComments); } else { message = NLS.bind("{0}", time); } if (cachingInProgress) { message += " [Caching contents...]"; } final Label textClientLabel = (Label) section.getTextClient(); textClientLabel.setText(" " + message); textClientLabel.getParent().layout(true, true); //textClientLabel.setVisible(cachingInProgress || !section.isExpanded()); } @Override public void initialize(AbstractTaskEditorPage taskEditorPage) { super.initialize(taskEditorPage); } private Composite createActions(final ChangeDetail changeDetail, final PatchSetDetail patchSetDetail, final PatchSetPublishDetail publishDetail, Composite composite) { Composite buttonComposite = new Composite(composite, SWT.NONE); RowLayout layout = new RowLayout(); layout.center = true; layout.spacing = 10; buttonComposite.setLayout(layout); boolean canPublish = getTaskData().getAttributeMapper().getBooleanValue( getTaskData().getRoot().getAttribute(GerritTaskSchema.getDefault().CAN_PUBLISH.getKey())); boolean canSubmit = false; if (changeDetail.getCurrentActions() != null) { canSubmit = changeDetail.getCurrentActions().contains(ApprovalCategory.SUBMIT); } else if (changeDetail instanceof ChangeDetailX) { // Gerrit 2.2 canSubmit = ((ChangeDetailX) changeDetail).canSubmit(); } if (canPublish) { Button publishButton = toolkit.createButton(buttonComposite, "Publish Comments...", SWT.PUSH); publishButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { doPublish(publishDetail); } }); } Button fetchButton = toolkit.createButton(buttonComposite, "Fetch...", SWT.PUSH); fetchButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { doFetch(changeDetail, patchSetDetail); } }); final Composite compareComposite = toolkit.createComposite(buttonComposite); GridLayoutFactory.fillDefaults().numColumns(2).spacing(0, 0).applyTo(compareComposite); Button compareButton = toolkit.createButton(compareComposite, "Compare With Base", SWT.PUSH); compareButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { doCompareWith(changeDetail, null, patchSetDetail.getPatchSet()); } }); if (changeDetail.getPatchSets().size() > 1) { Button compareWithButton = toolkit.createButton(compareComposite, "", SWT.PUSH); GridDataFactory.fillDefaults().grab(false, true).applyTo(compareWithButton); compareWithButton.setImage(WorkbenchImages.getImage(IWorkbenchGraphicConstants.IMG_LCL_BUTTON_MENU)); compareWithButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { showCompareMenu(compareComposite, changeDetail, patchSetDetail); } private void showCompareMenu(Composite compareComposite, ChangeDetail changeDetail, PatchSetDetail patchSetDetail) { Menu menu = new Menu(compareComposite); Point p = compareComposite.getLocation(); p.y = p.y + compareComposite.getSize().y; p = compareComposite.getParent().toDisplay(p); fillCompareWithMenu(changeDetail, patchSetDetail, menu); menu.setLocation(p); menu.setVisible(true); } }); } if (canSubmit) { Button submitButton = toolkit.createButton(buttonComposite, "Submit", SWT.PUSH); submitButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { doSubmit(patchSetDetail.getPatchSet()); } }); } if (changeDetail != null && changeDetail.isCurrentPatchSet(patchSetDetail)) { if (changeDetail.canAbandon()) { Button abondonButton = toolkit.createButton(buttonComposite, "Abandon...", SWT.PUSH); abondonButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { doAbandon(patchSetDetail.getPatchSet()); } }); } else if (changeDetail.canRestore()) { Button restoreButton = toolkit.createButton(buttonComposite, "Restore...", SWT.PUSH); restoreButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { doRestore(patchSetDetail.getPatchSet()); } }); } } return buttonComposite; } void fillCompareWithMenu(ChangeDetail changeDetail, PatchSetDetail patchSetDetail, Menu menu) { for (PatchSet patchSet : changeDetail.getPatchSets()) { if (patchSet.getPatchSetId() != patchSetDetail.getPatchSet().getPatchSetId()) { CompareAction action = new CompareAction(changeDetail, patchSet, patchSetDetail.getPatchSet()); action.fill(menu); } } } private void createSubSection(final ChangeDetail changeDetail, final PatchSetDetail patchSetDetail, final PatchSetPublishDetail publishDetail, Section section) { int style = ExpandableComposite.TWISTIE | ExpandableComposite.CLIENT_INDENT | ExpandableComposite.LEFT_TEXT_CLIENT_ALIGNMENT; if (changeDetail.isCurrentPatchSet(patchSetDetail)) { style |= ExpandableComposite.EXPANDED; } final Section subSection = toolkit.createSection(composite, style); GridDataFactory.fillDefaults().grab(true, false).applyTo(subSection); subSection.setText(NLS.bind("Patch Set {0}", patchSetDetail.getPatchSet().getId().get())); subSection.setTitleBarForeground(toolkit.getColors().getColor(IFormColors.TITLE)); addTextClient(toolkit, subSection, "", false); //$NON-NLS-1$ updateTextClient(subSection, patchSetDetail, false); if (subSection.isExpanded()) { createSubSectionContents(changeDetail, patchSetDetail, publishDetail, subSection); } subSection.addExpansionListener(new ExpansionAdapter() { @Override public void expansionStateChanged(ExpansionEvent e) { if (subSection.getClient() == null) { createSubSectionContents(changeDetail, patchSetDetail, publishDetail, subSection); } } }); } private int getNumComments(PatchSetDetail patchSetDetail) { int numComments = 0; for (Patch patch : patchSetDetail.getPatches()) { numComments += patch.getCommentCount(); } return numComments; } private void subSectionExpanded(final ChangeDetail changeDetail, final PatchSetDetail patchSetDetail, final Section composite, final Viewer viewer) { updateTextClient(composite, patchSetDetail, true); final GetPatchSetContentJob job = new GetPatchSetContentJob(getTaskEditorPage().getTaskRepository(), patchSetDetail); job.addJobChangeListener(new JobChangeAdapter() { @Override public void done(final IJobChangeEvent event) { Display.getDefault().asyncExec(new Runnable() { public void run() { if (getControl() != null && !getControl().isDisposed()) { if (event.getResult().isOK()) { GerritPatchSetContent content = job.getPatchSetContent(); if (content != null && content.getPatchScriptByPatchKey() != null) { viewer.setInput(GerritUtil.createInput(changeDetail, content, cache)); } } updateTextClient(composite, patchSetDetail, false); getTaskEditorPage().reflow(); } } }); } }); jobs.add(job); job.schedule(); } @Override protected Control createContent(FormToolkit toolkit, Composite parent) { this.toolkit = toolkit; composite = toolkit.createComposite(parent); GridLayoutFactory.fillDefaults().extendedMargins(0, 0, 0, 5).applyTo(composite); GerritChange change = GerritUtil.getChange(getTaskData()); if (change != null) { for (PatchSetDetail patchSetDetail : change.getPatchSetDetails()) { PatchSet.Id patchSetId = patchSetDetail.getPatchSet().getId(); PatchSetPublishDetail publishDetail = change.getPublishDetailByPatchSetId().get(patchSetId); createSubSection(change.getChangeDetail(), patchSetDetail, publishDetail, getSection()); } } return composite; } protected void doAbandon(PatchSet patchSet) { AbandonDialog dialog = new AbandonDialog(getShell(), getTask(), patchSet); openOperationDialog(dialog); } protected void doPublish(PatchSetPublishDetail publishDetail) { PublishDialog dialog = new PublishDialog(getShell(), getTask(), publishDetail, addedDrafts); openOperationDialog(dialog); } protected void doFetch(ChangeDetail changeDetail, PatchSetDetail patchSetDetail) { GerritToGitMapping mapping = getRepository(changeDetail); if (mapping != null) { String refName = patchSetDetail.getPatchSet().getRefName(); FetchGerritChangeWizard wizard = new FetchGerritChangeWizard(mapping.getRepository(), refName); WizardDialog wizardDialog = new WizardDialog(getShell(), wizard); wizardDialog.setHelpAvailable(false); wizardDialog.open(); } } private GerritToGitMapping getRepository(ChangeDetail changeDetail) { GerritToGitMapping mapper = new GerritToGitMapping(getTaskEditorPage().getTaskRepository(), getConfig(), getGerritProject(changeDetail)); try { if (mapper.find() != null) { return mapper; } else if (mapper.getGerritProject() != null) { boolean create = MessageDialog.openQuestion(getShell(), "Clone Git Repository", "The referenced Git repository was not found in the workspace. Clone Git repository?"); if (create) { int response = EGitUiUtil.openCloneRepositoryWizard(getShell(), getTaskEditorPage().getTaskRepository(), mapper.getGerritProject()); if (response == Window.OK && mapper.find() != null) { return mapper; } } } else { String message = NLS.bind("No Git repository found for fetching Gerrit change {0}", getTask().getTaskKey()); String reason = NLS.bind( "No remote config found that has fetch URL with host ''{0}'' and path matching ''{1}''", mapper.getGerritHost(), mapper.getGerritProjectName()); GerritCorePlugin.logError(message, null); ErrorDialog.openError(getShell(), "Gerrit Fetch Change Error", message, new Status(IStatus.ERROR, GerritUiPlugin.PLUGIN_ID, reason)); } } catch (IOException e) { Status status = new Status(IStatus.ERROR, GerritUiPlugin.PLUGIN_ID, "Error accessing Git repository", e); StatusManager.getManager().handle(status, StatusManager.BLOCK | StatusManager.SHOW | StatusManager.LOG); } return null; } protected void doCompareWithInSynchronizeView(ChangeDetail changeDetail, PatchSet base, PatchSet target) { GerritToGitMapping mapping = getRepository(changeDetail); if (mapping != null) { ComparePatchSetJob job = new ComparePatchSetJob(mapping.getRepository(), mapping.getRemote(), base, target); job.schedule(); } } protected void doCompareWith(ChangeDetail changeDetail, PatchSet base, PatchSet target) { OpenPatchSetJob job = new OpenPatchSetJob(getTaskEditorPage().getTaskRepository(), getTask(), changeDetail, base, target, cache); job.schedule(); } private String getGerritProject(ChangeDetail changeDetail) { return changeDetail.getChange().getProject().get(); } protected void doRestore(PatchSet patchSet) { RestoreDialog dialog = new RestoreDialog(getShell(), getTask(), patchSet); openOperationDialog(dialog); } protected void doSubmit(PatchSet patchSet) { SubmitDialog dialog = new SubmitDialog(getShell(), getTask(), patchSet); openOperationDialog(dialog); } @Override protected boolean shouldExpandOnCreate() { return true; } void createSubSectionContents(final ChangeDetail changeDetail, final PatchSetDetail patchSetDetail, PatchSetPublishDetail publishDetail, Section subSection) { Composite composite = toolkit.createComposite(subSection); GridLayoutFactory.fillDefaults().numColumns(2).applyTo(composite); subSection.setClient(composite); Label authorLabel = new Label(composite, SWT.NONE); authorLabel.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); authorLabel.setText("Author"); Text authorText = new Text(composite, SWT.READ_ONLY); authorText.setText(GerritUtil.getUserLabel(patchSetDetail.getInfo().getAuthor())); Label committerLabel = new Label(composite, SWT.NONE); committerLabel.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); committerLabel.setText("Committer"); Text committerText = new Text(composite, SWT.READ_ONLY); committerText.setText(GerritUtil.getUserLabel(patchSetDetail.getInfo().getCommitter())); Label commitLabel = new Label(composite, SWT.NONE); commitLabel.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); commitLabel.setText("Commit"); Hyperlink commitLink = new Hyperlink(composite, SWT.READ_ONLY); commitLink.setText(patchSetDetail.getPatchSet().getRevision().get()); commitLink.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent event) { GerritToGitMapping mapping = getRepository(changeDetail); if (mapping != null) { final FetchPatchSetJob job = new FetchPatchSetJob("Opening Commit Viewer", mapping.getRepository(), mapping.getRemote(), patchSetDetail.getPatchSet()); job.schedule(); job.addJobChangeListener(new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { CommitEditor.openQuiet(job.getCommit()); } }); } }); } } }); Label refLabel = new Label(composite, SWT.NONE); refLabel.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); refLabel.setText("Ref"); Text refText = new Text(composite, SWT.READ_ONLY); refText.setText(patchSetDetail.getPatchSet().getRefName()); final TableViewer viewer = new TableViewer(composite, SWT.SINGLE | SWT.BORDER | SWT.V_SCROLL | SWT.VIRTUAL); GridDataFactory.fillDefaults().span(2, 1).grab(true, true).hint(500, SWT.DEFAULT).applyTo(viewer.getControl()); viewer.setContentProvider(new IStructuredContentProvider() { private EContentAdapter modelAdapter; public void dispose() { // ignore } public Object[] getElements(Object inputElement) { return getReviewItems(inputElement).toArray(); } private List<IReviewItem> getReviewItems(Object inputElement) { if (inputElement instanceof IReviewItemSet) { return ((IReviewItemSet) inputElement).getItems(); } return Collections.emptyList(); } public void inputChanged(final Viewer viewer, Object oldInput, Object newInput) { if (modelAdapter != null) { for (IReviewItem item : getReviewItems(oldInput)) { ((EObject) item).eAdapters().remove(modelAdapter); } addedDrafts = 0; } if (newInput instanceof IReviewItemSet) { // monitors any new topics that are added modelAdapter = new EContentAdapter() { @Override public void notifyChanged(Notification notification) { super.notifyChanged(notification); if (notification.getFeatureID(IReviewItem.class) == ReviewsPackage.REVIEW_ITEM__TOPICS && notification.getEventType() == Notification.ADD) { viewer.refresh(); addedDrafts++; } } }; for (Object item : getReviewItems(newInput)) { ((EObject) item).eAdapters().add(modelAdapter); } } } }); viewer.setLabelProvider(new DelegatingStyledCellLabelProvider(new ReviewItemLabelProvider())); viewer.addOpenListener(new IOpenListener() { public void open(OpenEvent event) { IStructuredSelection selection = (IStructuredSelection) event.getSelection(); IFileItem item = (IFileItem) selection.getFirstElement(); - doOpen((IReviewItemSet) viewer.getInput(), item); + if (item != null) { + doOpen((IReviewItemSet) viewer.getInput(), item); + } } }); IReviewItemSet itemSet = GerritUtil.createInput(changeDetail, new GerritPatchSetContent(patchSetDetail), cache); viewer.setInput(itemSet); Composite actionComposite = createActions(changeDetail, patchSetDetail, publishDetail, composite); GridDataFactory.fillDefaults().span(2, 1).applyTo(actionComposite); subSectionExpanded(changeDetail, patchSetDetail, subSection, viewer); EditorUtil.addScrollListener(viewer.getTable()); getTaskEditorPage().reflow(); } private void doOpen(IReviewItemSet items, IFileItem item) { if (item.getBase() == null || item.getTarget() == null) { getTaskEditorPage().getEditor().setMessage("The selected file is not available, yet", IMessageProvider.WARNING); return; } GerritReviewBehavior behavior = new GerritReviewBehavior(getTask()); CompareConfiguration configuration = new CompareConfiguration(); CompareUI.openCompareEditor(new FileItemCompareEditorInput(configuration, item, behavior)); } }
true
true
void createSubSectionContents(final ChangeDetail changeDetail, final PatchSetDetail patchSetDetail, PatchSetPublishDetail publishDetail, Section subSection) { Composite composite = toolkit.createComposite(subSection); GridLayoutFactory.fillDefaults().numColumns(2).applyTo(composite); subSection.setClient(composite); Label authorLabel = new Label(composite, SWT.NONE); authorLabel.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); authorLabel.setText("Author"); Text authorText = new Text(composite, SWT.READ_ONLY); authorText.setText(GerritUtil.getUserLabel(patchSetDetail.getInfo().getAuthor())); Label committerLabel = new Label(composite, SWT.NONE); committerLabel.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); committerLabel.setText("Committer"); Text committerText = new Text(composite, SWT.READ_ONLY); committerText.setText(GerritUtil.getUserLabel(patchSetDetail.getInfo().getCommitter())); Label commitLabel = new Label(composite, SWT.NONE); commitLabel.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); commitLabel.setText("Commit"); Hyperlink commitLink = new Hyperlink(composite, SWT.READ_ONLY); commitLink.setText(patchSetDetail.getPatchSet().getRevision().get()); commitLink.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent event) { GerritToGitMapping mapping = getRepository(changeDetail); if (mapping != null) { final FetchPatchSetJob job = new FetchPatchSetJob("Opening Commit Viewer", mapping.getRepository(), mapping.getRemote(), patchSetDetail.getPatchSet()); job.schedule(); job.addJobChangeListener(new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { CommitEditor.openQuiet(job.getCommit()); } }); } }); } } }); Label refLabel = new Label(composite, SWT.NONE); refLabel.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); refLabel.setText("Ref"); Text refText = new Text(composite, SWT.READ_ONLY); refText.setText(patchSetDetail.getPatchSet().getRefName()); final TableViewer viewer = new TableViewer(composite, SWT.SINGLE | SWT.BORDER | SWT.V_SCROLL | SWT.VIRTUAL); GridDataFactory.fillDefaults().span(2, 1).grab(true, true).hint(500, SWT.DEFAULT).applyTo(viewer.getControl()); viewer.setContentProvider(new IStructuredContentProvider() { private EContentAdapter modelAdapter; public void dispose() { // ignore } public Object[] getElements(Object inputElement) { return getReviewItems(inputElement).toArray(); } private List<IReviewItem> getReviewItems(Object inputElement) { if (inputElement instanceof IReviewItemSet) { return ((IReviewItemSet) inputElement).getItems(); } return Collections.emptyList(); } public void inputChanged(final Viewer viewer, Object oldInput, Object newInput) { if (modelAdapter != null) { for (IReviewItem item : getReviewItems(oldInput)) { ((EObject) item).eAdapters().remove(modelAdapter); } addedDrafts = 0; } if (newInput instanceof IReviewItemSet) { // monitors any new topics that are added modelAdapter = new EContentAdapter() { @Override public void notifyChanged(Notification notification) { super.notifyChanged(notification); if (notification.getFeatureID(IReviewItem.class) == ReviewsPackage.REVIEW_ITEM__TOPICS && notification.getEventType() == Notification.ADD) { viewer.refresh(); addedDrafts++; } } }; for (Object item : getReviewItems(newInput)) { ((EObject) item).eAdapters().add(modelAdapter); } } } }); viewer.setLabelProvider(new DelegatingStyledCellLabelProvider(new ReviewItemLabelProvider())); viewer.addOpenListener(new IOpenListener() { public void open(OpenEvent event) { IStructuredSelection selection = (IStructuredSelection) event.getSelection(); IFileItem item = (IFileItem) selection.getFirstElement(); doOpen((IReviewItemSet) viewer.getInput(), item); } }); IReviewItemSet itemSet = GerritUtil.createInput(changeDetail, new GerritPatchSetContent(patchSetDetail), cache); viewer.setInput(itemSet); Composite actionComposite = createActions(changeDetail, patchSetDetail, publishDetail, composite); GridDataFactory.fillDefaults().span(2, 1).applyTo(actionComposite); subSectionExpanded(changeDetail, patchSetDetail, subSection, viewer); EditorUtil.addScrollListener(viewer.getTable()); getTaskEditorPage().reflow(); }
void createSubSectionContents(final ChangeDetail changeDetail, final PatchSetDetail patchSetDetail, PatchSetPublishDetail publishDetail, Section subSection) { Composite composite = toolkit.createComposite(subSection); GridLayoutFactory.fillDefaults().numColumns(2).applyTo(composite); subSection.setClient(composite); Label authorLabel = new Label(composite, SWT.NONE); authorLabel.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); authorLabel.setText("Author"); Text authorText = new Text(composite, SWT.READ_ONLY); authorText.setText(GerritUtil.getUserLabel(patchSetDetail.getInfo().getAuthor())); Label committerLabel = new Label(composite, SWT.NONE); committerLabel.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); committerLabel.setText("Committer"); Text committerText = new Text(composite, SWT.READ_ONLY); committerText.setText(GerritUtil.getUserLabel(patchSetDetail.getInfo().getCommitter())); Label commitLabel = new Label(composite, SWT.NONE); commitLabel.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); commitLabel.setText("Commit"); Hyperlink commitLink = new Hyperlink(composite, SWT.READ_ONLY); commitLink.setText(patchSetDetail.getPatchSet().getRevision().get()); commitLink.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent event) { GerritToGitMapping mapping = getRepository(changeDetail); if (mapping != null) { final FetchPatchSetJob job = new FetchPatchSetJob("Opening Commit Viewer", mapping.getRepository(), mapping.getRemote(), patchSetDetail.getPatchSet()); job.schedule(); job.addJobChangeListener(new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { CommitEditor.openQuiet(job.getCommit()); } }); } }); } } }); Label refLabel = new Label(composite, SWT.NONE); refLabel.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); refLabel.setText("Ref"); Text refText = new Text(composite, SWT.READ_ONLY); refText.setText(patchSetDetail.getPatchSet().getRefName()); final TableViewer viewer = new TableViewer(composite, SWT.SINGLE | SWT.BORDER | SWT.V_SCROLL | SWT.VIRTUAL); GridDataFactory.fillDefaults().span(2, 1).grab(true, true).hint(500, SWT.DEFAULT).applyTo(viewer.getControl()); viewer.setContentProvider(new IStructuredContentProvider() { private EContentAdapter modelAdapter; public void dispose() { // ignore } public Object[] getElements(Object inputElement) { return getReviewItems(inputElement).toArray(); } private List<IReviewItem> getReviewItems(Object inputElement) { if (inputElement instanceof IReviewItemSet) { return ((IReviewItemSet) inputElement).getItems(); } return Collections.emptyList(); } public void inputChanged(final Viewer viewer, Object oldInput, Object newInput) { if (modelAdapter != null) { for (IReviewItem item : getReviewItems(oldInput)) { ((EObject) item).eAdapters().remove(modelAdapter); } addedDrafts = 0; } if (newInput instanceof IReviewItemSet) { // monitors any new topics that are added modelAdapter = new EContentAdapter() { @Override public void notifyChanged(Notification notification) { super.notifyChanged(notification); if (notification.getFeatureID(IReviewItem.class) == ReviewsPackage.REVIEW_ITEM__TOPICS && notification.getEventType() == Notification.ADD) { viewer.refresh(); addedDrafts++; } } }; for (Object item : getReviewItems(newInput)) { ((EObject) item).eAdapters().add(modelAdapter); } } } }); viewer.setLabelProvider(new DelegatingStyledCellLabelProvider(new ReviewItemLabelProvider())); viewer.addOpenListener(new IOpenListener() { public void open(OpenEvent event) { IStructuredSelection selection = (IStructuredSelection) event.getSelection(); IFileItem item = (IFileItem) selection.getFirstElement(); if (item != null) { doOpen((IReviewItemSet) viewer.getInput(), item); } } }); IReviewItemSet itemSet = GerritUtil.createInput(changeDetail, new GerritPatchSetContent(patchSetDetail), cache); viewer.setInput(itemSet); Composite actionComposite = createActions(changeDetail, patchSetDetail, publishDetail, composite); GridDataFactory.fillDefaults().span(2, 1).applyTo(actionComposite); subSectionExpanded(changeDetail, patchSetDetail, subSection, viewer); EditorUtil.addScrollListener(viewer.getTable()); getTaskEditorPage().reflow(); }
diff --git a/de.gebit.integrity.dsl/src/de/gebit/integrity/parameter/conversion/conversions/integrity/nestedobjects/AbstractNestedObjectToString.java b/de.gebit.integrity.dsl/src/de/gebit/integrity/parameter/conversion/conversions/integrity/nestedobjects/AbstractNestedObjectToString.java index fdf00db4..384e4081 100644 --- a/de.gebit.integrity.dsl/src/de/gebit/integrity/parameter/conversion/conversions/integrity/nestedobjects/AbstractNestedObjectToString.java +++ b/de.gebit.integrity.dsl/src/de/gebit/integrity/parameter/conversion/conversions/integrity/nestedobjects/AbstractNestedObjectToString.java @@ -1,125 +1,128 @@ /******************************************************************************* * Copyright (c) 2013 Rene Schneider, GEBIT Solutions 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 de.gebit.integrity.parameter.conversion.conversions.integrity.nestedobjects; import java.lang.reflect.Array; import java.util.Hashtable; import java.util.Map; import de.gebit.integrity.dsl.KeyValuePair; import de.gebit.integrity.dsl.NestedObject; import de.gebit.integrity.operations.UnexecutableException; import de.gebit.integrity.parameter.conversion.Conversion; import de.gebit.integrity.parameter.conversion.ConversionFailedException; import de.gebit.integrity.parameter.conversion.UnresolvableVariableHandling; import de.gebit.integrity.string.FormatTokenElement; import de.gebit.integrity.string.FormatTokenElement.FormatTokenType; import de.gebit.integrity.string.FormattedString; /** * A default Integrity conversion. * * @author Rene Schneider - initial API and implementation * * @param <T> * the target type * */ public abstract class AbstractNestedObjectToString<T> extends Conversion<NestedObject, T> { /** * This static map stores the nesting depth information for string formatting. It is a map in order to be multi- * threading-safe, in case someone starts multiple test runner instances in one VM and runs them in parallel. */ private static Map<Thread, Integer> nestedObjectDepthMap = new Hashtable<Thread, Integer>(); /** * Converts the provided {@link NestedObject} to a {@link FormattedString}. * * @param aSource * the source value * @param anUnresolvableVariableHandlingPolicy * how unresolvable variables shall be treated * @return the resulting string * @throws ConversionFailedException */ protected FormattedString convertToFormattedString(NestedObject aSource, UnresolvableVariableHandling anUnresolvableVariableHandlingPolicy) throws ConversionFailedException { FormattedString tempBuffer = new FormattedString("{"); tempBuffer.add(new FormatTokenElement(FormatTokenType.NEWLINE)); Integer tempDepth = nestedObjectDepthMap.get(Thread.currentThread()); if (tempDepth == null) { tempDepth = 1; } else { tempDepth++; } nestedObjectDepthMap.put(Thread.currentThread(), tempDepth); try { boolean tempFirst = true; for (KeyValuePair tempAttribute : aSource.getAttributes()) { Object tempConvertedValue; try { tempConvertedValue = convertValueRecursive(FormattedString[].class, null, tempAttribute.getValue(), anUnresolvableVariableHandlingPolicy); } catch (ClassNotFoundException exc) { throw new ConversionFailedException(NestedObject.class, Map.class, null, exc); } catch (UnexecutableException exc) { - throw new ConversionFailedException(NestedObject.class, Map.class, null, exc); + // #5: NPE in dry run phase if operations are used in nested objects + // This exception is expected to happen during dry run if variable values are determined by calls + // and thus not yet known - but that's not really a problem, it just needs to be caught + tempConvertedValue = null; } catch (InstantiationException exc) { throw new ConversionFailedException(NestedObject.class, Map.class, null, exc); } if (!tempFirst) { tempBuffer.add(new FormatTokenElement(FormatTokenType.NEWLINE, ", ")); } FormattedString tempConvertedValueStringBuffer = new FormattedString(); if (tempConvertedValue == null) { tempConvertedValueStringBuffer.add("null"); } else { int tempArrayLength = Array.getLength(tempConvertedValue); for (int i = 0; i < tempArrayLength; i++) { if (i > 0) { tempConvertedValueStringBuffer.add(", "); } Object tempSingleArrayValue = Array.get(tempConvertedValue, i); if (tempSingleArrayValue instanceof FormattedString) { tempConvertedValueStringBuffer.add((FormattedString) tempSingleArrayValue); } else { tempConvertedValueStringBuffer.add(tempSingleArrayValue != null ? tempSingleArrayValue .toString() : "null"); } } } tempBuffer.addMultiple(new FormatTokenElement(FormatTokenType.TAB), tempDepth); tempBuffer.add(tempAttribute.getIdentifier() + " = "); tempBuffer.add(tempConvertedValueStringBuffer); tempFirst = false; } } finally { tempDepth--; tempBuffer.add(new FormatTokenElement(FormatTokenType.NEWLINE)); tempBuffer.addMultiple(new FormatTokenElement(FormatTokenType.TAB), tempDepth); tempBuffer.add("}"); if (tempDepth == 0) { nestedObjectDepthMap.remove(Thread.currentThread()); } else { nestedObjectDepthMap.put(Thread.currentThread(), tempDepth); } } return tempBuffer; } }
true
true
protected FormattedString convertToFormattedString(NestedObject aSource, UnresolvableVariableHandling anUnresolvableVariableHandlingPolicy) throws ConversionFailedException { FormattedString tempBuffer = new FormattedString("{"); tempBuffer.add(new FormatTokenElement(FormatTokenType.NEWLINE)); Integer tempDepth = nestedObjectDepthMap.get(Thread.currentThread()); if (tempDepth == null) { tempDepth = 1; } else { tempDepth++; } nestedObjectDepthMap.put(Thread.currentThread(), tempDepth); try { boolean tempFirst = true; for (KeyValuePair tempAttribute : aSource.getAttributes()) { Object tempConvertedValue; try { tempConvertedValue = convertValueRecursive(FormattedString[].class, null, tempAttribute.getValue(), anUnresolvableVariableHandlingPolicy); } catch (ClassNotFoundException exc) { throw new ConversionFailedException(NestedObject.class, Map.class, null, exc); } catch (UnexecutableException exc) { throw new ConversionFailedException(NestedObject.class, Map.class, null, exc); } catch (InstantiationException exc) { throw new ConversionFailedException(NestedObject.class, Map.class, null, exc); } if (!tempFirst) { tempBuffer.add(new FormatTokenElement(FormatTokenType.NEWLINE, ", ")); } FormattedString tempConvertedValueStringBuffer = new FormattedString(); if (tempConvertedValue == null) { tempConvertedValueStringBuffer.add("null"); } else { int tempArrayLength = Array.getLength(tempConvertedValue); for (int i = 0; i < tempArrayLength; i++) { if (i > 0) { tempConvertedValueStringBuffer.add(", "); } Object tempSingleArrayValue = Array.get(tempConvertedValue, i); if (tempSingleArrayValue instanceof FormattedString) { tempConvertedValueStringBuffer.add((FormattedString) tempSingleArrayValue); } else { tempConvertedValueStringBuffer.add(tempSingleArrayValue != null ? tempSingleArrayValue .toString() : "null"); } } } tempBuffer.addMultiple(new FormatTokenElement(FormatTokenType.TAB), tempDepth); tempBuffer.add(tempAttribute.getIdentifier() + " = "); tempBuffer.add(tempConvertedValueStringBuffer); tempFirst = false; } } finally { tempDepth--; tempBuffer.add(new FormatTokenElement(FormatTokenType.NEWLINE)); tempBuffer.addMultiple(new FormatTokenElement(FormatTokenType.TAB), tempDepth); tempBuffer.add("}"); if (tempDepth == 0) { nestedObjectDepthMap.remove(Thread.currentThread()); } else { nestedObjectDepthMap.put(Thread.currentThread(), tempDepth); } } return tempBuffer; }
protected FormattedString convertToFormattedString(NestedObject aSource, UnresolvableVariableHandling anUnresolvableVariableHandlingPolicy) throws ConversionFailedException { FormattedString tempBuffer = new FormattedString("{"); tempBuffer.add(new FormatTokenElement(FormatTokenType.NEWLINE)); Integer tempDepth = nestedObjectDepthMap.get(Thread.currentThread()); if (tempDepth == null) { tempDepth = 1; } else { tempDepth++; } nestedObjectDepthMap.put(Thread.currentThread(), tempDepth); try { boolean tempFirst = true; for (KeyValuePair tempAttribute : aSource.getAttributes()) { Object tempConvertedValue; try { tempConvertedValue = convertValueRecursive(FormattedString[].class, null, tempAttribute.getValue(), anUnresolvableVariableHandlingPolicy); } catch (ClassNotFoundException exc) { throw new ConversionFailedException(NestedObject.class, Map.class, null, exc); } catch (UnexecutableException exc) { // #5: NPE in dry run phase if operations are used in nested objects // This exception is expected to happen during dry run if variable values are determined by calls // and thus not yet known - but that's not really a problem, it just needs to be caught tempConvertedValue = null; } catch (InstantiationException exc) { throw new ConversionFailedException(NestedObject.class, Map.class, null, exc); } if (!tempFirst) { tempBuffer.add(new FormatTokenElement(FormatTokenType.NEWLINE, ", ")); } FormattedString tempConvertedValueStringBuffer = new FormattedString(); if (tempConvertedValue == null) { tempConvertedValueStringBuffer.add("null"); } else { int tempArrayLength = Array.getLength(tempConvertedValue); for (int i = 0; i < tempArrayLength; i++) { if (i > 0) { tempConvertedValueStringBuffer.add(", "); } Object tempSingleArrayValue = Array.get(tempConvertedValue, i); if (tempSingleArrayValue instanceof FormattedString) { tempConvertedValueStringBuffer.add((FormattedString) tempSingleArrayValue); } else { tempConvertedValueStringBuffer.add(tempSingleArrayValue != null ? tempSingleArrayValue .toString() : "null"); } } } tempBuffer.addMultiple(new FormatTokenElement(FormatTokenType.TAB), tempDepth); tempBuffer.add(tempAttribute.getIdentifier() + " = "); tempBuffer.add(tempConvertedValueStringBuffer); tempFirst = false; } } finally { tempDepth--; tempBuffer.add(new FormatTokenElement(FormatTokenType.NEWLINE)); tempBuffer.addMultiple(new FormatTokenElement(FormatTokenType.TAB), tempDepth); tempBuffer.add("}"); if (tempDepth == 0) { nestedObjectDepthMap.remove(Thread.currentThread()); } else { nestedObjectDepthMap.put(Thread.currentThread(), tempDepth); } } return tempBuffer; }
diff --git a/src/examples/wikisearch/ingest/src/main/java/org/apache/accumulo/examples/wikisearch/ingest/WikipediaInputFormat.java b/src/examples/wikisearch/ingest/src/main/java/org/apache/accumulo/examples/wikisearch/ingest/WikipediaInputFormat.java index 4c6a3b8e0..e8b8b5224 100644 --- a/src/examples/wikisearch/ingest/src/main/java/org/apache/accumulo/examples/wikisearch/ingest/WikipediaInputFormat.java +++ b/src/examples/wikisearch/ingest/src/main/java/org/apache/accumulo/examples/wikisearch/ingest/WikipediaInputFormat.java @@ -1,129 +1,129 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.accumulo.examples.wikisearch.ingest; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.accumulo.examples.wikisearch.reader.AggregatingRecordReader; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; public class WikipediaInputFormat extends TextInputFormat { public static class WikipediaInputSplit extends InputSplit implements Writable { public WikipediaInputSplit(){} public WikipediaInputSplit(FileSplit fileSplit, int partition) { this.fileSplit = fileSplit; this.partition = partition; } private FileSplit fileSplit = null; private int partition = -1; public int getPartition() { return partition; } public FileSplit getFileSplit() { return fileSplit; } @Override public long getLength() throws IOException, InterruptedException { return fileSplit.getLength(); } @Override public String[] getLocations() throws IOException, InterruptedException { return fileSplit.getLocations(); } @Override public void readFields(DataInput in) throws IOException { Path file = new Path(in.readUTF()); long start = in.readLong(); long length = in.readLong(); int numHosts = in.readInt(); String[] hosts = new String[numHosts]; for(int i = 0; i < numHosts; i++) hosts[i] = in.readUTF(); fileSplit = new FileSplit(file, start, length, hosts); partition = in.readInt(); } @Override public void write(DataOutput out) throws IOException { out.writeUTF(fileSplit.getPath().toString()); out.writeLong(fileSplit.getStart()); out.writeLong(fileSplit.getLength()); String [] hosts = fileSplit.getLocations(); out.writeInt(hosts.length); for(String host:hosts) out.writeUTF(host); fileSplit.write(out); out.writeInt(partition); } } @Override public List<InputSplit> getSplits(JobContext job) throws IOException { List<InputSplit> superSplits = super.getSplits(job); - List<WikipediaInputSplit> splits = new ArrayList<WikipediaInputSplit>(); + List<InputSplit> splits = new ArrayList<InputSplit>(); int numGroups = WikipediaConfiguration.getNumGroups(job.getConfiguration()); for(InputSplit split:superSplits) { FileSplit fileSplit = (FileSplit)split; for(int group = 0; group < numGroups; group++) { splits.add(new WikipediaInputSplit(fileSplit,group)); } } - return super.getSplits(job); + return splits; } @Override public RecordReader<LongWritable,Text> createRecordReader(InputSplit split, TaskAttemptContext context) { return new AggregatingRecordReader(); } @Override protected boolean isSplitable(JobContext context, Path file) { return false; } }
false
true
public List<InputSplit> getSplits(JobContext job) throws IOException { List<InputSplit> superSplits = super.getSplits(job); List<WikipediaInputSplit> splits = new ArrayList<WikipediaInputSplit>(); int numGroups = WikipediaConfiguration.getNumGroups(job.getConfiguration()); for(InputSplit split:superSplits) { FileSplit fileSplit = (FileSplit)split; for(int group = 0; group < numGroups; group++) { splits.add(new WikipediaInputSplit(fileSplit,group)); } } return super.getSplits(job); }
public List<InputSplit> getSplits(JobContext job) throws IOException { List<InputSplit> superSplits = super.getSplits(job); List<InputSplit> splits = new ArrayList<InputSplit>(); int numGroups = WikipediaConfiguration.getNumGroups(job.getConfiguration()); for(InputSplit split:superSplits) { FileSplit fileSplit = (FileSplit)split; for(int group = 0; group < numGroups; group++) { splits.add(new WikipediaInputSplit(fileSplit,group)); } } return splits; }
diff --git a/src/com/android/timezonepicker/TimeZoneFilterTypeAdapter.java b/src/com/android/timezonepicker/TimeZoneFilterTypeAdapter.java index 65bd530..ffc699b 100644 --- a/src/com/android/timezonepicker/TimeZoneFilterTypeAdapter.java +++ b/src/com/android/timezonepicker/TimeZoneFilterTypeAdapter.java @@ -1,392 +1,405 @@ /* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.timezonepicker; import android.content.Context; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Filter; import android.widget.Filterable; import android.widget.TextView; import java.util.ArrayList; public class TimeZoneFilterTypeAdapter extends BaseAdapter implements Filterable, OnClickListener { public static final String TAG = "TimeZoneFilterTypeAdapter"; public static final int FILTER_TYPE_EMPTY = -1; public static final int FILTER_TYPE_NONE = 0; public static final int FILTER_TYPE_COUNTRY = 1; public static final int FILTER_TYPE_STATE = 2; public static final int FILTER_TYPE_GMT = 3; public interface OnSetFilterListener { void onSetFilter(int filterType, String str, int time); } static class ViewHolder { int filterType; String str; int time; TextView strTextView; static void setupViewHolder(View v) { ViewHolder vh = new ViewHolder(); vh.strTextView = (TextView) v.findViewById(R.id.value); v.setTag(vh); } } class FilterTypeResult { int type; String constraint; public int time; public FilterTypeResult(int type, String constraint, int time) { this.type = type; this.constraint = constraint; this.time = time; } @Override public String toString() { return constraint; } } private ArrayList<FilterTypeResult> mLiveResults = new ArrayList<FilterTypeResult>(); private int mLiveResultsCount = 0; private ArrayFilter mFilter; private LayoutInflater mInflater; private TimeZoneData mTimeZoneData; private OnSetFilterListener mListener; public TimeZoneFilterTypeAdapter(Context context, TimeZoneData tzd, OnSetFilterListener l) { mTimeZoneData = tzd; mListener = l; mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return mLiveResultsCount; } @Override public FilterTypeResult getItem(int position) { return mLiveResults.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v; if (convertView != null) { v = convertView; } else { v = mInflater.inflate(R.layout.time_zone_filter_item, null); ViewHolder.setupViewHolder(v); } ViewHolder vh = (ViewHolder) v.getTag(); if (position >= mLiveResults.size()) { Log.e(TAG, "getView: " + position + " of " + mLiveResults.size()); } FilterTypeResult filter = mLiveResults.get(position); vh.filterType = filter.type; vh.str = filter.constraint; vh.time = filter.time; vh.strTextView.setText(filter.constraint); return v; } OnClickListener mDummyListener = new OnClickListener() { @Override public void onClick(View v) { } }; // Implements OnClickListener // This onClickListener is actually called from the AutoCompleteTextView's // onItemClickListener. Trying to update the text in AutoCompleteTextView // is causing an infinite loop. @Override public void onClick(View v) { if (mListener != null && v != null) { ViewHolder vh = (ViewHolder) v.getTag(); mListener.onSetFilter(vh.filterType, vh.str, vh.time); } notifyDataSetInvalidated(); } // Implements Filterable @Override public Filter getFilter() { if (mFilter == null) { mFilter = new ArrayFilter(); } return mFilter; } private class ArrayFilter extends Filter { @Override protected FilterResults performFiltering(CharSequence prefix) { Log.e(TAG, "performFiltering >>>> [" + prefix + "]"); FilterResults results = new FilterResults(); String prefixString = null; if (prefix != null) { prefixString = prefix.toString().trim().toLowerCase(); } if (TextUtils.isEmpty(prefixString)) { results.values = null; results.count = 0; return results; } // TODO Perf - we can loop through the filtered list if the new // search string starts with the old search string ArrayList<FilterTypeResult> filtered = new ArrayList<FilterTypeResult>(); // //////////////////////////////////////// // Search by local time and GMT offset // //////////////////////////////////////// boolean gmtOnly = false; int startParsePosition = 0; if (prefixString.charAt(0) == '+' || prefixString.charAt(0) == '-') { gmtOnly = true; } if (prefixString.startsWith("gmt")) { startParsePosition = 3; gmtOnly = true; } int num = parseNum(prefixString, startParsePosition); if (num != Integer.MIN_VALUE) { boolean positiveOnly = prefixString.length() > startParsePosition && prefixString.charAt(startParsePosition) == '+'; handleSearchByGmt(filtered, num, positiveOnly); } // //////////////////////////////////////// // Search by country // //////////////////////////////////////// for (String country : mTimeZoneData.mTimeZonesByCountry.keySet()) { // TODO Perf - cache toLowerCase()? if (!TextUtils.isEmpty(country)) { final String lowerCaseCountry = country.toLowerCase(); + boolean isMatch = false; if (lowerCaseCountry.startsWith(prefixString) || (lowerCaseCountry.charAt(0) == prefixString.charAt(0) && isStartingInitialsFor(prefixString, lowerCaseCountry))) { + isMatch = true; + } else if (lowerCaseCountry.contains(" ")){ + // We should also search other words in the country name, so that + // searches like "Korea" yield "South Korea". + for (String word : lowerCaseCountry.split(" ")) { + if (word.startsWith(prefixString)) { + isMatch = true; + break; + } + } + } + if (isMatch) { filtered.add(new FilterTypeResult(FILTER_TYPE_COUNTRY, country, 0)); } } } // //////////////////////////////////////// // TODO Search by state // //////////////////////////////////////// Log.e(TAG, "performFiltering <<<< " + filtered.size() + "[" + prefix + "]"); results.values = filtered; results.count = filtered.size(); return results; } /** * Returns true if the prefixString is an initial for string. Note that * this method will return true even if prefixString does not cover all * the words. Words are separated by non-letters which includes spaces * and symbols). * * For example: * isStartingInitialsFor("UA", "United Arb Emirates") would return true * isStartingInitialsFor("US", "U.S. Virgin Island") would return true * @param prefixString * @param string * @return */ private boolean isStartingInitialsFor(String prefixString, String string) { final int initialLen = prefixString.length(); final int strLen = string.length(); int initialIdx = 0; boolean wasWordBreak = true; for (int i = 0; i < strLen; i++) { if (!Character.isLetter(string.charAt(i))) { wasWordBreak = true; continue; } if (wasWordBreak) { if (prefixString.charAt(initialIdx++) != string.charAt(i)) { return false; } if (initialIdx == initialLen) { return true; } wasWordBreak = false; } } return false; } private void handleSearchByGmt(ArrayList<FilterTypeResult> filtered, int num, boolean positiveOnly) { FilterTypeResult r; if (num >= 0) { if (num == 1) { for (int i = 19; i >= 10; i--) { if (mTimeZoneData.hasTimeZonesInHrOffset(i)) { r = new FilterTypeResult(FILTER_TYPE_GMT, "GMT+" + i, i); filtered.add(r); } } } if (mTimeZoneData.hasTimeZonesInHrOffset(num)) { r = new FilterTypeResult(FILTER_TYPE_GMT, "GMT+" + num, num); filtered.add(r); } num *= -1; } if (!positiveOnly && num != 0) { if (mTimeZoneData.hasTimeZonesInHrOffset(num)) { r = new FilterTypeResult(FILTER_TYPE_GMT, "GMT" + num, num); filtered.add(r); } if (num == -1) { for (int i = -10; i >= -19; i--) { if (mTimeZoneData.hasTimeZonesInHrOffset(i)) { r = new FilterTypeResult(FILTER_TYPE_GMT, "GMT" + i, i); filtered.add(r); } } } } } /** * Acceptable strings are in the following format: [+-]?[0-9]?[0-9] * * @param str * @param startIndex * @return Integer.MIN_VALUE as invalid */ public int parseNum(String str, int startIndex) { int idx = startIndex; int num = Integer.MIN_VALUE; int negativeMultiplier = 1; // First char - check for + and - char ch = str.charAt(idx++); switch (ch) { case '-': negativeMultiplier = -1; // fall through case '+': if (idx >= str.length()) { // No more digits return Integer.MIN_VALUE; } ch = str.charAt(idx++); break; } if (!Character.isDigit(ch)) { // No digit return Integer.MIN_VALUE; } // Got first digit num = Character.digit(ch, 10); // Check next char if (idx < str.length()) { ch = str.charAt(idx++); if (Character.isDigit(ch)) { // Got second digit num = 10 * num + Character.digit(ch, 10); } else { return Integer.MIN_VALUE; } } if (idx != str.length()) { // Invalid return Integer.MIN_VALUE; } Log.e(TAG, "Parsing " + str + " -> " + negativeMultiplier * num); return negativeMultiplier * num; } @SuppressWarnings("unchecked") @Override protected void publishResults(CharSequence constraint, FilterResults results) { if (results.values == null || results.count == 0) { if (mListener != null) { int filterType; if (TextUtils.isEmpty(constraint)) { filterType = FILTER_TYPE_NONE; } else { filterType = FILTER_TYPE_EMPTY; } mListener.onSetFilter(filterType, null, 0); } Log.e(TAG, "publishResults: " + results.count + " of null [" + constraint); } else { mLiveResults = (ArrayList<FilterTypeResult>) results.values; Log.e(TAG, "publishResults: " + results.count + " of " + mLiveResults.size() + " [" + constraint); } mLiveResultsCount = results.count; if (results.count > 0) { notifyDataSetChanged(); } else { notifyDataSetInvalidated(); } } } }
false
true
protected FilterResults performFiltering(CharSequence prefix) { Log.e(TAG, "performFiltering >>>> [" + prefix + "]"); FilterResults results = new FilterResults(); String prefixString = null; if (prefix != null) { prefixString = prefix.toString().trim().toLowerCase(); } if (TextUtils.isEmpty(prefixString)) { results.values = null; results.count = 0; return results; } // TODO Perf - we can loop through the filtered list if the new // search string starts with the old search string ArrayList<FilterTypeResult> filtered = new ArrayList<FilterTypeResult>(); // //////////////////////////////////////// // Search by local time and GMT offset // //////////////////////////////////////// boolean gmtOnly = false; int startParsePosition = 0; if (prefixString.charAt(0) == '+' || prefixString.charAt(0) == '-') { gmtOnly = true; } if (prefixString.startsWith("gmt")) { startParsePosition = 3; gmtOnly = true; } int num = parseNum(prefixString, startParsePosition); if (num != Integer.MIN_VALUE) { boolean positiveOnly = prefixString.length() > startParsePosition && prefixString.charAt(startParsePosition) == '+'; handleSearchByGmt(filtered, num, positiveOnly); } // //////////////////////////////////////// // Search by country // //////////////////////////////////////// for (String country : mTimeZoneData.mTimeZonesByCountry.keySet()) { // TODO Perf - cache toLowerCase()? if (!TextUtils.isEmpty(country)) { final String lowerCaseCountry = country.toLowerCase(); if (lowerCaseCountry.startsWith(prefixString) || (lowerCaseCountry.charAt(0) == prefixString.charAt(0) && isStartingInitialsFor(prefixString, lowerCaseCountry))) { filtered.add(new FilterTypeResult(FILTER_TYPE_COUNTRY, country, 0)); } } } // //////////////////////////////////////// // TODO Search by state // //////////////////////////////////////// Log.e(TAG, "performFiltering <<<< " + filtered.size() + "[" + prefix + "]"); results.values = filtered; results.count = filtered.size(); return results; }
protected FilterResults performFiltering(CharSequence prefix) { Log.e(TAG, "performFiltering >>>> [" + prefix + "]"); FilterResults results = new FilterResults(); String prefixString = null; if (prefix != null) { prefixString = prefix.toString().trim().toLowerCase(); } if (TextUtils.isEmpty(prefixString)) { results.values = null; results.count = 0; return results; } // TODO Perf - we can loop through the filtered list if the new // search string starts with the old search string ArrayList<FilterTypeResult> filtered = new ArrayList<FilterTypeResult>(); // //////////////////////////////////////// // Search by local time and GMT offset // //////////////////////////////////////// boolean gmtOnly = false; int startParsePosition = 0; if (prefixString.charAt(0) == '+' || prefixString.charAt(0) == '-') { gmtOnly = true; } if (prefixString.startsWith("gmt")) { startParsePosition = 3; gmtOnly = true; } int num = parseNum(prefixString, startParsePosition); if (num != Integer.MIN_VALUE) { boolean positiveOnly = prefixString.length() > startParsePosition && prefixString.charAt(startParsePosition) == '+'; handleSearchByGmt(filtered, num, positiveOnly); } // //////////////////////////////////////// // Search by country // //////////////////////////////////////// for (String country : mTimeZoneData.mTimeZonesByCountry.keySet()) { // TODO Perf - cache toLowerCase()? if (!TextUtils.isEmpty(country)) { final String lowerCaseCountry = country.toLowerCase(); boolean isMatch = false; if (lowerCaseCountry.startsWith(prefixString) || (lowerCaseCountry.charAt(0) == prefixString.charAt(0) && isStartingInitialsFor(prefixString, lowerCaseCountry))) { isMatch = true; } else if (lowerCaseCountry.contains(" ")){ // We should also search other words in the country name, so that // searches like "Korea" yield "South Korea". for (String word : lowerCaseCountry.split(" ")) { if (word.startsWith(prefixString)) { isMatch = true; break; } } } if (isMatch) { filtered.add(new FilterTypeResult(FILTER_TYPE_COUNTRY, country, 0)); } } } // //////////////////////////////////////// // TODO Search by state // //////////////////////////////////////// Log.e(TAG, "performFiltering <<<< " + filtered.size() + "[" + prefix + "]"); results.values = filtered; results.count = filtered.size(); return results; }
diff --git a/src/test/java/org/chaoticbits/collabcloud/vc/svn/SVNRepoMaker.java b/src/test/java/org/chaoticbits/collabcloud/vc/svn/SVNRepoMaker.java index 030da57..90881e4 100755 --- a/src/test/java/org/chaoticbits/collabcloud/vc/svn/SVNRepoMaker.java +++ b/src/test/java/org/chaoticbits/collabcloud/vc/svn/SVNRepoMaker.java @@ -1,186 +1,186 @@ package org.chaoticbits.collabcloud.vc.svn; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.List; import java.util.Scanner; import org.apache.log4j.PropertyConfigurator; import org.chaoticbits.collabcloud.codeprocessor.java.RecurseJavaFiles; import org.tmatesoft.svn.core.SVNCommitInfo; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.auth.BasicAuthenticationManager; import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager; import org.tmatesoft.svn.core.internal.io.fs.FSRepositoryFactory; import org.tmatesoft.svn.core.io.ISVNEditor; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.io.SVNRepositoryFactory; import org.tmatesoft.svn.core.io.diff.SVNDeltaGenerator; /** * This class is for buildling an SVN repo for testing purposes. It's mostly hard-coded for this reason. * @author andy * */ public class SVNRepoMaker { private static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(SVNRepoMaker.class); private static ISVNAuthenticationManager andyProgrammer = new BasicAuthenticationManager("Andy Programmer <[email protected]>", ""); private static ISVNAuthenticationManager andyMeneely = new BasicAuthenticationManager("Andy Meneely <[email protected]>", ""); private static ISVNAuthenticationManager kellyDoctor = new BasicAuthenticationManager("Kelly Doctor <[email protected]>", ""); public static void main(String[] args) throws Exception { PropertyConfigurator.configure("log4j.properties"); log.info("Set up FSRepositoryFactory..."); FSRepositoryFactory.setup(); log.info("Create the local repo..."); SVNURL svnurl = SVNRepositoryFactory.createLocalRepository(new File("testsvn/repo"), true, true); SVNRepository repo = SVNRepositoryFactory.create(svnurl); addTrunk(repo); importProject(repo); andyPChange(repo); kellyDoctorChange(repo); andyPChangeGreedy(repo); andyMChangeGreedy(repo); log.info("Done."); } private static void addTrunk(SVNRepository repo) throws SVNException { log.info("Add trunk..."); repo.setAuthenticationManager(andyProgrammer); ISVNEditor editor = repo.getCommitEditor("adding trunk", null /* locks */, true /* keepLocks */, null /* mediator */); editor.openRoot(-1); editor.addDir("trunk", null, -1); editor.closeDir(); SVNCommitInfo commitInfo = editor.closeEdit(); log.info("Finished commit: " + commitInfo.toString()); } private static void importProject(SVNRepository repo) throws Exception { log.info("Import the project..."); repo.setAuthenticationManager(andyMeneely); ISVNEditor editor = repo.getCommitEditor("import project", null /* locks */, true /* keepLocks */, null /* mediator */); editor.openRoot(-1); List<File> files = new RecurseJavaFiles(true).loadRecursive(new File("testsvn/mancala")); for (File file : files) { String svnpath = ""; svnpath = "trunk/" + file.getPath().replaceFirst("testsvn\\\\", "").replaceAll("\\\\", "/"); log.debug("Adding svnpath: " + svnpath); if (file.isDirectory()) { editor.addDir(svnpath, null, -1); editor.closeDir(); } else { editor.addFile(svnpath, null, -1); editor.applyTextDelta(svnpath, null); Scanner scanner = new Scanner(file); StringBuffer sb = new StringBuffer(); - while (scanner.hasNext()) - sb.append(scanner.next()); + while (scanner.hasNextLine()) + sb.append(scanner.nextLine() + "\r\n"); scanner.close(); String checksum = new SVNDeltaGenerator().sendDelta(svnpath, new ByteArrayInputStream(sb.toString().getBytes()), editor, true); editor.closeFile(svnpath, checksum); } } SVNCommitInfo commitInfo = editor.closeEdit(); log.info("Finished commit: " + commitInfo.toString()); } private static void andyPChange(SVNRepository repo) throws Exception { log.info("Making Andy Programmer's change..."); repo.setAuthenticationManager(andyProgrammer); ISVNEditor editor = repo.getCommitEditor("Small change to a file", null /* locks */, true /* keepLocks */, null /* mediator */); Scanner scanner = new Scanner(new File("testsvn/mancala/player/TimedNegaScoutPlayer.java")); StringBuffer sb = new StringBuffer(); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.contains("public int getPlay(Board state) {")) line = "public int getPlay(Board state) {//Making a modification for the sake of testing"; sb.append(line + "\r\n"); } editor.openRoot(-1); editor.openDir("trunk/mancala/player", 2); editor.openFile("trunk/mancala/player/TimedNegaScoutPlayer.java", 2); editor.applyTextDelta("trunk/mancala/player/TimedNegaScoutPlayer.java", null); String checksum = new SVNDeltaGenerator().sendDelta("trunk/mancala/player/TimedNegaScoutPlayer.java", new ByteArrayInputStream(sb .toString().getBytes()), editor, true); editor.closeFile("trunk/mancala/player/TimedNegaScoutPlayer.java", checksum); SVNCommitInfo commitInfo = editor.closeEdit(); log.info("Finished commit: " + commitInfo.toString()); } private static void kellyDoctorChange(SVNRepository repo) throws Exception { log.info("Making Kelly Doctor's change..."); repo.setAuthenticationManager(kellyDoctor); ISVNEditor editor = repo.getCommitEditor("Another small change to a file", null /* locks */, true /* keepLocks */, null /* mediator */); Scanner scanner = new Scanner(new File("testsvn/mancala/player/TimedNegaScoutPlayer.java")); StringBuffer sb = new StringBuffer(); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.contains("public int getPlay(Board state) {")) line = "public int getPlay(Board state) {//Making another modification for the sake of testing"; sb.append(line + "\r\n"); } editor.openRoot(-1); editor.openDir("trunk/mancala/player", 3); editor.openFile("trunk/mancala/player/TimedNegaScoutPlayer.java", 3); editor.applyTextDelta("trunk/mancala/player/TimedNegaScoutPlayer.java", null); String checksum = new SVNDeltaGenerator().sendDelta("trunk/mancala/player/TimedNegaScoutPlayer.java", new ByteArrayInputStream(sb .toString().getBytes()), editor, true); editor.closeFile("trunk/mancala/player/TimedNegaScoutPlayer.java", checksum); SVNCommitInfo commitInfo = editor.closeEdit(); log.info("Finished commit: " + commitInfo.toString()); } private static void andyPChangeGreedy(SVNRepository repo) throws Exception { log.info("Making Andy Programmer's change to GreedyPlayer..."); repo.setAuthenticationManager(andyProgrammer); ISVNEditor editor = repo.getCommitEditor("Another small change to a file", null /* locks */, true /* keepLocks */, null /* mediator */); Scanner scanner = new Scanner(new File("testsvn/mancala/player/GreedyPlayer.java")); StringBuffer sb = new StringBuffer(); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.contains("for (int play = 0; play < Board.SLOT_WIDTH; play++) {")) line = "for (int play = 0; play < Board.SLOT_WIDTH; play++) {//Making a modification for the sake of testing"; sb.append(line + "\r\n"); } editor.openRoot(-1); editor.openDir("trunk/mancala/player", -1); editor.openFile("trunk/mancala/player/GreedyPlayer.java", -1); editor.applyTextDelta("trunk/mancala/player/GreedyPlayer.java", null); String checksum = new SVNDeltaGenerator().sendDelta("trunk/mancala/player/GreedyPlayer.java", new ByteArrayInputStream(sb.toString() .getBytes()), editor, true); editor.closeFile("trunk/mancala/player/GreedyPlayer.java", checksum); SVNCommitInfo commitInfo = editor.closeEdit(); log.info("Finished commit: " + commitInfo.toString()); } private static void andyMChangeGreedy(SVNRepository repo) throws Exception { log.info("Making Andy Programmer's change to GreedyPlayer..."); repo.setAuthenticationManager(andyMeneely); ISVNEditor editor = repo.getCommitEditor("Yet another small change to a file", null /* locks */, true /* keepLocks */, null /* mediator */); Scanner scanner = new Scanner(new File("testsvn/mancala/player/GreedyPlayer.java")); StringBuffer sb = new StringBuffer(); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.contains("for (int play = 0; play < Board.SLOT_WIDTH; play++) {")) line = "for (int play = 0; play < Board.SLOT_WIDTH; play++) {//Making another modification for the sake of testing"; sb.append(line + "\r\n"); } editor.openRoot(-1); editor.openDir("trunk/mancala/player", -1); editor.openFile("trunk/mancala/player/GreedyPlayer.java", -1); editor.applyTextDelta("trunk/mancala/player/GreedyPlayer.java", null); String checksum = new SVNDeltaGenerator().sendDelta("trunk/mancala/player/GreedyPlayer.java", new ByteArrayInputStream(sb.toString() .getBytes()), editor, true); editor.closeFile("trunk/mancala/player/GreedyPlayer.java", checksum); SVNCommitInfo commitInfo = editor.closeEdit(); log.info("Finished commit: " + commitInfo.toString()); } }
true
true
private static void importProject(SVNRepository repo) throws Exception { log.info("Import the project..."); repo.setAuthenticationManager(andyMeneely); ISVNEditor editor = repo.getCommitEditor("import project", null /* locks */, true /* keepLocks */, null /* mediator */); editor.openRoot(-1); List<File> files = new RecurseJavaFiles(true).loadRecursive(new File("testsvn/mancala")); for (File file : files) { String svnpath = ""; svnpath = "trunk/" + file.getPath().replaceFirst("testsvn\\\\", "").replaceAll("\\\\", "/"); log.debug("Adding svnpath: " + svnpath); if (file.isDirectory()) { editor.addDir(svnpath, null, -1); editor.closeDir(); } else { editor.addFile(svnpath, null, -1); editor.applyTextDelta(svnpath, null); Scanner scanner = new Scanner(file); StringBuffer sb = new StringBuffer(); while (scanner.hasNext()) sb.append(scanner.next()); scanner.close(); String checksum = new SVNDeltaGenerator().sendDelta(svnpath, new ByteArrayInputStream(sb.toString().getBytes()), editor, true); editor.closeFile(svnpath, checksum); } } SVNCommitInfo commitInfo = editor.closeEdit(); log.info("Finished commit: " + commitInfo.toString()); }
private static void importProject(SVNRepository repo) throws Exception { log.info("Import the project..."); repo.setAuthenticationManager(andyMeneely); ISVNEditor editor = repo.getCommitEditor("import project", null /* locks */, true /* keepLocks */, null /* mediator */); editor.openRoot(-1); List<File> files = new RecurseJavaFiles(true).loadRecursive(new File("testsvn/mancala")); for (File file : files) { String svnpath = ""; svnpath = "trunk/" + file.getPath().replaceFirst("testsvn\\\\", "").replaceAll("\\\\", "/"); log.debug("Adding svnpath: " + svnpath); if (file.isDirectory()) { editor.addDir(svnpath, null, -1); editor.closeDir(); } else { editor.addFile(svnpath, null, -1); editor.applyTextDelta(svnpath, null); Scanner scanner = new Scanner(file); StringBuffer sb = new StringBuffer(); while (scanner.hasNextLine()) sb.append(scanner.nextLine() + "\r\n"); scanner.close(); String checksum = new SVNDeltaGenerator().sendDelta(svnpath, new ByteArrayInputStream(sb.toString().getBytes()), editor, true); editor.closeFile(svnpath, checksum); } } SVNCommitInfo commitInfo = editor.closeEdit(); log.info("Finished commit: " + commitInfo.toString()); }
diff --git a/software/ncimbrowser/src/java/gov/nih/nci/evs/browser/utils/HTTPUtils.java b/software/ncimbrowser/src/java/gov/nih/nci/evs/browser/utils/HTTPUtils.java index 01baef26..3dab7cc4 100644 --- a/software/ncimbrowser/src/java/gov/nih/nci/evs/browser/utils/HTTPUtils.java +++ b/software/ncimbrowser/src/java/gov/nih/nci/evs/browser/utils/HTTPUtils.java @@ -1,249 +1,250 @@ package gov.nih.nci.evs.browser.utils; import java.io.*; import java.net.*; import java.util.*; import java.util.regex.*; import javax.faces.context.*; import javax.servlet.http.*; /** * <!-- LICENSE_TEXT_START --> * Copyright 2008,2009 NGIT. This software was developed in conjunction * with the National Cancer Institute, and so to the extent government * employees are co-authors, any rights in such works shall be subject * to Title 17 of the United States Code, section 105. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the disclaimer of Article 3, * below. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * 2. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by NGIT and the National * Cancer Institute." If no such end-user documentation is to be * included, this acknowledgment shall appear in the software itself, * wherever such third-party acknowledgments normally appear. * 3. The names "The National Cancer Institute", "NCI" and "NGIT" must * not be used to endorse or promote products derived from this software. * 4. This license does not authorize the incorporation of this software * into any third party proprietary programs. This license does not * authorize the recipient to use any trademarks owned by either NCI * or NGIT * 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED * WARRANTIES, (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE * DISCLAIMED. IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, * NGIT, OR THEIR AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * <!-- LICENSE_TEXT_END --> */ /** * HTTP Utility methods * * @author garciawa2 * */ public class HTTPUtils { private final static String REFERER = "referer"; /** * Remove potentially bad XSS syntax * * @param value * @return */ public static String cleanXSS(String value) { if (value == null || value.length() < 1) return value; try { value = URLDecoder.decode(value, "UTF-8"); } catch (UnsupportedEncodingException e) { // Do nothing, just use the input } catch (IllegalArgumentException e) { // Do nothing, just use the input // Note: The following exception was triggered: // java.lang.IllegalArgumentException: URLDecoder: Illegal hex // characters in escape (%) pattern - For input string: "^&". } // Remove XSS attacks value = replaceAll(value, "<\\s*script\\s*>.*</\\s*script\\s*>", ""); + value = value.replaceAll(".*<\\s*iframe.*>", ""); value = value.replaceAll("<", "&lt;").replaceAll(">", "&gt;"); value = value.replaceAll("\\(", "&#40;").replaceAll("\\)", "&#41;"); value = value.replaceAll("'", "&#39;"); value = value.replaceAll("eval\\((.*)\\)", ""); value = replaceAll(value, "[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\""); value = value.replaceAll("\"", "&quot;"); return value; } /** * @param string * @param regex * @param replaceWith * @return */ public static String replaceAll(String string, String regex, String replaceWith) { Pattern myPattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); string = myPattern.matcher(string).replaceAll(replaceWith); return string; } /** * @param name * @param classPath * @return */ @SuppressWarnings("unchecked") public static Object getBean(String name, String classPath) { try { Map<String, Object> map = FacesContext.getCurrentInstance().getExternalContext() .getSessionMap(); Object bean = map.get(name); if (bean == null) { Class klass = Class.forName(classPath); bean = klass.newInstance(); map.put(name, bean); } return bean; } catch (Exception e) { return null; } } /** * @return */ public static HttpServletRequest getRequest() { return (HttpServletRequest) FacesContext.getCurrentInstance() .getExternalContext().getRequest(); } /** * @param request * @param attributeName * @param defaultValue * @return */ public static String getAttribute(HttpServletRequest request, String attributeName, String defaultValue) { String value = (String) request.getAttribute(attributeName); return getValue(value, defaultValue); } /** * @param request * @param attributeName * @param defaultValue * @return */ public static String getSessionAttribute(HttpServletRequest request, String attributeName, String defaultValue) { String value = (String) request.getSession().getAttribute(attributeName); return getValue(value, defaultValue); } /** * @param value * @param defaultValue * @return */ public static String getValue(String value, String defaultValue) { if (value == null || value.trim().length() <= 0 || value.equals("null")) return defaultValue; return value; } /** * @param request * @return */ public static String getRefererParmEncode(HttpServletRequest request) { String iref = request.getHeader(REFERER); String referer = "N/A"; if (iref != null) try { referer = URLEncoder.encode(iref, "UTF-8"); } catch (UnsupportedEncodingException e) { // return N/A if encoding is not supported. } return cleanXSS(referer); } /** * @param request * @return */ public static String getRefererParmDecode(HttpServletRequest request) { String refurl = "N/A"; try { String iref = request.getParameter(REFERER); if (iref != null) refurl = URLDecoder.decode(request.getParameter(REFERER), "UTF-8"); } catch (UnsupportedEncodingException e) { // return N/A if encoding is not supported. } return cleanXSS(refurl); } /** * @param request */ public static void clearRefererParm(HttpServletRequest request) { request.setAttribute(REFERER, null); } /** * @param t * @return */ public static String convertJSPString(String t) { // Convert problem characters to JavaScript Escaped values if (t == null) { return ""; } if (t.compareTo("") == 0) { return ""; } String sigleQuoteChar = "'"; String doubleQuoteChar = "\""; String dq = "&quot;"; t = t.replaceAll(sigleQuoteChar, "\\" + sigleQuoteChar); t = t.replaceAll(doubleQuoteChar, "\\" + dq); t = t.replaceAll("\r", "\\r"); // replace CR with \r; t = t.replaceAll("\n", "\\n"); // replace LF with \n; return t; } }
true
true
public static String cleanXSS(String value) { if (value == null || value.length() < 1) return value; try { value = URLDecoder.decode(value, "UTF-8"); } catch (UnsupportedEncodingException e) { // Do nothing, just use the input } catch (IllegalArgumentException e) { // Do nothing, just use the input // Note: The following exception was triggered: // java.lang.IllegalArgumentException: URLDecoder: Illegal hex // characters in escape (%) pattern - For input string: "^&". } // Remove XSS attacks value = replaceAll(value, "<\\s*script\\s*>.*</\\s*script\\s*>", ""); value = value.replaceAll("<", "&lt;").replaceAll(">", "&gt;"); value = value.replaceAll("\\(", "&#40;").replaceAll("\\)", "&#41;"); value = value.replaceAll("'", "&#39;"); value = value.replaceAll("eval\\((.*)\\)", ""); value = replaceAll(value, "[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\""); value = value.replaceAll("\"", "&quot;"); return value; }
public static String cleanXSS(String value) { if (value == null || value.length() < 1) return value; try { value = URLDecoder.decode(value, "UTF-8"); } catch (UnsupportedEncodingException e) { // Do nothing, just use the input } catch (IllegalArgumentException e) { // Do nothing, just use the input // Note: The following exception was triggered: // java.lang.IllegalArgumentException: URLDecoder: Illegal hex // characters in escape (%) pattern - For input string: "^&". } // Remove XSS attacks value = replaceAll(value, "<\\s*script\\s*>.*</\\s*script\\s*>", ""); value = value.replaceAll(".*<\\s*iframe.*>", ""); value = value.replaceAll("<", "&lt;").replaceAll(">", "&gt;"); value = value.replaceAll("\\(", "&#40;").replaceAll("\\)", "&#41;"); value = value.replaceAll("'", "&#39;"); value = value.replaceAll("eval\\((.*)\\)", ""); value = replaceAll(value, "[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\""); value = value.replaceAll("\"", "&quot;"); return value; }
diff --git a/src/test/java/uk/ac/ebi/fgpt/sampletab/TestFileUtils.java b/src/test/java/uk/ac/ebi/fgpt/sampletab/TestFileUtils.java index 61986a06..f9c39ba9 100644 --- a/src/test/java/uk/ac/ebi/fgpt/sampletab/TestFileUtils.java +++ b/src/test/java/uk/ac/ebi/fgpt/sampletab/TestFileUtils.java @@ -1,77 +1,77 @@ package uk.ac.ebi.fgpt.sampletab; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.ebi.fgpt.sampletab.utils.FileUtils; import junit.framework.TestCase; public class TestFileUtils extends TestCase { private Logger log = LoggerFactory.getLogger(getClass()); public void testFileFilterRegex() { //first create a bunch of likely files //First //A1.txt //A2.txt //Second //A1.txt //A2.txt File first = new File("First"); if (!first.exists()) first.mkdir(); File firstA1 = new File(first, "A1.txt"); File firstA2 = new File(first, "A2.txt"); File second = new File("Second"); if (!second.exists()) second.mkdir(); File secondA1 = new File(second, "A1.txt"); File secondA2 = new File(second, "A2.txt"); try { firstA1.createNewFile(); firstA2.createNewFile(); secondA1.createNewFile(); secondA2.createNewFile(); } catch (IOException e) { log.error("unable to create files for testing"); e.printStackTrace(); fail(); } //now check the results are what we expect List<File> FA1A2 = new ArrayList<File>(); - FA1A2.add(new File("First/A1.txt")); - FA1A2.add(new File("First/A2.txt")); - assertEquals(FA1A2, FileUtils.getMatchesRegex("First/.*\\.txt")); + FA1A2.add(new File("First/A1.txt").getAbsoluteFile()); + FA1A2.add(new File("First/A2.txt").getAbsoluteFile()); + //assertEquals(FA1A2, FileUtils.getMatchesRegex("First/.*\\.txt")); assertEquals(FA1A2, FileUtils.getMatchesGlob("First/*.txt")); List<File> FA1 = new ArrayList<File>(); - FA1.add(new File("First/A1.txt")); + FA1.add(new File("First/A1.txt").getAbsoluteFile()); assertEquals(FA1, FileUtils.getMatchesRegex("First/A1.txt")); assertEquals(FA1, FileUtils.getMatchesGlob("First/A1.txt")); List<File> FA1SA1 = new ArrayList<File>(); - FA1SA1.add(new File("First/A1.txt")); - FA1SA1.add(new File("Second/A1.txt")); + FA1SA1.add(new File("First/A1.txt").getAbsoluteFile()); + FA1SA1.add(new File("Second/A1.txt").getAbsoluteFile()); assertEquals(FA1SA1, FileUtils.getMatchesGlob("*/A1.txt")); List<File> FA1A2SA1A2 = new ArrayList<File>(); - FA1A2SA1A2.add(new File("First/A1.txt")); - FA1A2SA1A2.add(new File("First/A2.txt")); - FA1A2SA1A2.add(new File("Second/A1.txt")); - FA1A2SA1A2.add(new File("Second/A2.txt")); + FA1A2SA1A2.add(new File("First/A1.txt").getAbsoluteFile()); + FA1A2SA1A2.add(new File("First/A2.txt").getAbsoluteFile()); + FA1A2SA1A2.add(new File("Second/A1.txt").getAbsoluteFile()); + FA1A2SA1A2.add(new File("Second/A2.txt").getAbsoluteFile()); assertEquals(FA1A2SA1A2, FileUtils.getMatchesGlob("*/A*.txt")); } }
false
true
public void testFileFilterRegex() { //first create a bunch of likely files //First //A1.txt //A2.txt //Second //A1.txt //A2.txt File first = new File("First"); if (!first.exists()) first.mkdir(); File firstA1 = new File(first, "A1.txt"); File firstA2 = new File(first, "A2.txt"); File second = new File("Second"); if (!second.exists()) second.mkdir(); File secondA1 = new File(second, "A1.txt"); File secondA2 = new File(second, "A2.txt"); try { firstA1.createNewFile(); firstA2.createNewFile(); secondA1.createNewFile(); secondA2.createNewFile(); } catch (IOException e) { log.error("unable to create files for testing"); e.printStackTrace(); fail(); } //now check the results are what we expect List<File> FA1A2 = new ArrayList<File>(); FA1A2.add(new File("First/A1.txt")); FA1A2.add(new File("First/A2.txt")); assertEquals(FA1A2, FileUtils.getMatchesRegex("First/.*\\.txt")); assertEquals(FA1A2, FileUtils.getMatchesGlob("First/*.txt")); List<File> FA1 = new ArrayList<File>(); FA1.add(new File("First/A1.txt")); assertEquals(FA1, FileUtils.getMatchesRegex("First/A1.txt")); assertEquals(FA1, FileUtils.getMatchesGlob("First/A1.txt")); List<File> FA1SA1 = new ArrayList<File>(); FA1SA1.add(new File("First/A1.txt")); FA1SA1.add(new File("Second/A1.txt")); assertEquals(FA1SA1, FileUtils.getMatchesGlob("*/A1.txt")); List<File> FA1A2SA1A2 = new ArrayList<File>(); FA1A2SA1A2.add(new File("First/A1.txt")); FA1A2SA1A2.add(new File("First/A2.txt")); FA1A2SA1A2.add(new File("Second/A1.txt")); FA1A2SA1A2.add(new File("Second/A2.txt")); assertEquals(FA1A2SA1A2, FileUtils.getMatchesGlob("*/A*.txt")); }
public void testFileFilterRegex() { //first create a bunch of likely files //First //A1.txt //A2.txt //Second //A1.txt //A2.txt File first = new File("First"); if (!first.exists()) first.mkdir(); File firstA1 = new File(first, "A1.txt"); File firstA2 = new File(first, "A2.txt"); File second = new File("Second"); if (!second.exists()) second.mkdir(); File secondA1 = new File(second, "A1.txt"); File secondA2 = new File(second, "A2.txt"); try { firstA1.createNewFile(); firstA2.createNewFile(); secondA1.createNewFile(); secondA2.createNewFile(); } catch (IOException e) { log.error("unable to create files for testing"); e.printStackTrace(); fail(); } //now check the results are what we expect List<File> FA1A2 = new ArrayList<File>(); FA1A2.add(new File("First/A1.txt").getAbsoluteFile()); FA1A2.add(new File("First/A2.txt").getAbsoluteFile()); //assertEquals(FA1A2, FileUtils.getMatchesRegex("First/.*\\.txt")); assertEquals(FA1A2, FileUtils.getMatchesGlob("First/*.txt")); List<File> FA1 = new ArrayList<File>(); FA1.add(new File("First/A1.txt").getAbsoluteFile()); assertEquals(FA1, FileUtils.getMatchesRegex("First/A1.txt")); assertEquals(FA1, FileUtils.getMatchesGlob("First/A1.txt")); List<File> FA1SA1 = new ArrayList<File>(); FA1SA1.add(new File("First/A1.txt").getAbsoluteFile()); FA1SA1.add(new File("Second/A1.txt").getAbsoluteFile()); assertEquals(FA1SA1, FileUtils.getMatchesGlob("*/A1.txt")); List<File> FA1A2SA1A2 = new ArrayList<File>(); FA1A2SA1A2.add(new File("First/A1.txt").getAbsoluteFile()); FA1A2SA1A2.add(new File("First/A2.txt").getAbsoluteFile()); FA1A2SA1A2.add(new File("Second/A1.txt").getAbsoluteFile()); FA1A2SA1A2.add(new File("Second/A2.txt").getAbsoluteFile()); assertEquals(FA1A2SA1A2, FileUtils.getMatchesGlob("*/A*.txt")); }
diff --git a/src/wjhk/jupload2/upload/DefaultFileUploadThread.java b/src/wjhk/jupload2/upload/DefaultFileUploadThread.java index 8ad7b84..8cf5124 100644 --- a/src/wjhk/jupload2/upload/DefaultFileUploadThread.java +++ b/src/wjhk/jupload2/upload/DefaultFileUploadThread.java @@ -1,570 +1,570 @@ // // $Id: DefaultFileUploadThread.java 287 2007-06-17 09:07:04 +0000 (dim., 17 // juin 2007) felfert $ // // jupload - A file upload applet. // Copyright 2007 The JUpload Team // // Created: ? // Creator: William JinHua Kwong // Last modified: $Date$ // // This program is free software; you can redistribute it and/or modify it under // the terms of the GNU General Public License as published by the Free Software // Foundation; either version 2 of the License, or (at your option) any later // version. This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more // details. You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, Inc., // 675 Mass Ave, Cambridge, MA 02139, USA. package wjhk.jupload2.upload; import java.io.OutputStream; import java.util.regex.Pattern; import wjhk.jupload2.exception.JUploadException; import wjhk.jupload2.exception.JUploadExceptionUploadFailed; import wjhk.jupload2.exception.JUploadIOException; import wjhk.jupload2.filedata.FileData; import wjhk.jupload2.policies.UploadPolicy; /** * This class is based on the {@link FileUploadThread} class. It's an abstract * class that contains the default implementation for the * {@link FileUploadThread} interface. <BR> * It contains the following abstract methods, which must be implemented in the * children classes. These methods are called in this order: <DIR> * <LI>For each upload request (for instance, upload of 3 files with * nbFilesPerRequest to 2, makes 2 request: 2 files, then the last one): <DIR> * <LI><I>try</I> * <LI>{@link #startRequest}: start of the UploadRequest. * <LI>Then, for each file to upload (according to the nbFilesPerRequest and * maxChunkSize applet parameters) <DIR> * <LI>beforeFile(int) is called before writting the bytes for this file (or * this chunk) * <LI>afterFile(int) is called after writting the bytes for this file (or this * chunk) </DIR> * <LI>finishRequest() </DIR> </LI> * <I>finally</I>cleanRequest() * <LI>Call of cleanAll(), to clean up any used resources, common to the whole * upload. </DIR> */ public abstract class DefaultFileUploadThread extends Thread implements FileUploadThread { // //////////////////////////////////////////////////////////////////////////////////// // /////////////////////// VARIABLES /////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////// /** * The array that contains the current packet to upload. * * @see FileUploadManagerThread#getNextPacket() */ UploadFileData[] filesToUpload = null; /** * The upload manager. The thread that prepares files, and is responsible to * manage the upload process. * * @see FileUploadManagerThread */ FileUploadManagerThread fileUploadManagerThread = null; /** * The upload policy contains all parameters needed to define the way files * should be uploaded, including the URL. */ protected UploadPolicy uploadPolicy = null; /** * The value of the applet parameter maxChunkSize, or its default value. */ private long maxChunkSize; // //////////////////////////////////////////////////////////////////////////////////// // /////////////////////// PRIVATE ATTRIBUTES // /////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////// /** * The full response message from the server, if any. For instance, in HTTP * mode, this contains both the headers and the body. */ protected String responseMsg = ""; /** * The response message from the application. For instance, in HTTP mode, * this contains the body response.<BR> * Note: for easier management on the various server configurations, all end * or line characters (CR, LF or CRLF) are changed to uniform CRLF. */ protected String responseBody = ""; /** * Creates a new instance. * * @param uploadPolicy The upload policy to be applied. * @param fileUploadManagerThread The thread that is managing the upload. */ public DefaultFileUploadThread(UploadPolicy uploadPolicy, FileUploadManagerThread fileUploadManagerThread) { // Thread parameters. super("FileUploadThread"); // Specific stuff. this.uploadPolicy = uploadPolicy; this.fileUploadManagerThread = fileUploadManagerThread; // Let's read up to date upload parameters. this.maxChunkSize = this.uploadPolicy.getMaxChunkSize(); this.uploadPolicy.displayDebug("DefaultFileUploadThread created", 30); } /** * This method is called before the upload. It calls the * {@link FileData#beforeUpload()} method for all files to upload, and * prepares the progressBar bar (if any), with total number of bytes to * upload. * * final private void beforeUpload() throws JUploadException { for (int i = * 0; i < this.filesToUpload.length && * !this.fileUploadManager.isUploadStopped(); i++) { * this.filesToUpload[i].beforeUpload(); } } * * /** This methods upload overhead for the file number indexFile in the * filesDataParam given to the constructor. For instance, in HTTP, the * upload contains a head and a tail for each files. * * @param indexFile The index of the file in the filesDataParam array, whose * addtional length is asked. * @return The additional number of bytes for this file. */ abstract long getAdditionnalBytesForUpload(int indexFile) throws JUploadIOException; /** * This method is called before starting of each request. It can be used to * prepare any work, before starting the request. For instance, in HTTP, the * tail must be properly calculated, as the last one must be different from * the others.<BR> * The files to prepare are stored in the {@link #filesToUpload} array. */ abstract void beforeRequest() throws JUploadException; /** * This method is called for each upload request to the server. The number * of request to the server depends on: <DIR> * <LI>The total number of files to upload. * <LI>The value of the nbFilesPerRequest applet parameter. * <LI>The value of the maxChunkSize applet parameter. </DIR> The main * objective of this method is to open the connection to the server, where * the files to upload will be written. It should also send any header * necessary for this upload request. The {@link #getOutputStream()} methods * is then called to know where the uploaded files should be written. <BR> * Note: it's up to the class containing this method to internally manage * the connection. * * @param contentLength The total number of bytes for the files (or the * chunk) to upload in this query. * @param bChunkEnabled True if this upload is part of a file (can occurs * only if the maxChunkSize applet parameter is set). False * otherwise. * @param chunkPart The chunk number. Should be ignored if bChunkEnabled is * false. * @param bLastChunk True if in chunk mode, and this upload is the last one. * Should be ignored if bChunkEnabled is false. */ abstract void startRequest(long contentLength, boolean bChunkEnabled, int chunkPart, boolean bLastChunk) throws JUploadException; /** * This method is called at the end of each request. * * @return The response status code from the server (200 == OK) * @see #startRequest(long, boolean, int, boolean) */ abstract int finishRequest() throws JUploadException; /** * This method is called before sending the bytes corresponding to the file * whose index is given in argument. If the file is splitted in chunks (see * the maxChunkSize applet parameter), this method is called before each * chunk for this file. * * @param index The index of the file that will be sent just after */ abstract void beforeFile(int index) throws JUploadException; /** * Idem as {@link #beforeFile(int)}, but is called after each file (and * each chunks for each file). * * @param index The index of the file that was just sent. */ abstract void afterFile(int index) throws JUploadException; /** * Clean any used resource of the last executed request. In HTTP mode, the * output stream, input stream and the socket should be cleaned here. */ abstract void cleanRequest() throws JUploadException; /** * Clean any used resource, like a 'permanent' connection. This method is * called after the end of the last request (see on the top of this page for * details). */ abstract void cleanAll() throws JUploadException; /** * Get the output stream where the files should be written for upload. * * @return The target output stream for upload. */ abstract OutputStream getOutputStream() throws JUploadException; /** * Return the the body for the server response. That is: the server response * without the http header. This is the functional response from the server * application, that has been as the HTTP reply body, for instance: all * 'echo' PHP commands. <BR> * * @return The last application response (HTTP body, in HTTP upload) */ public String getResponseBody() { return this.responseBody; } /** * Get the server Output. * * @return The status message from the first line of the response (e.g. "200 * OK"). */ public String getResponseMsg() { return this.responseMsg; } /** * Unused Store the String that contains the server response body. * * @param body The response body that has been read. */ void setResponseBody(String body) { this.responseBody = normalizeCRLF(body); } /** * Add a String that has been read from the server response. * * @param msg The status message from the first line of the response (e.g. * "200 OK"). */ void setResponseMsg(String msg) { this.responseMsg = normalizeCRLF(msg); } // //////////////////////////////////////////////////////////////////////////////////// // /////////////////////// PRIVATE FUNCTIONS // //////////////////////////////////////////////////////////////////////////////////// /** * This method loops on the {@link FileUploadManagerThread#getNextPacket()} * method, until a set of files is ready. Then, it calls the doUpload() * method, to send these files to the server. */ @Override final public void run() { this.uploadPolicy.displayDebug("Start of the FileUploadThread", 5); try { // We'll stop the upload if an error occurs. So the try/catch is // outside the while. // FIXME isUploadFinished will be true, when this thread stops! while (!this.fileUploadManagerThread.isUploadStopped() && !this.fileUploadManagerThread.isUploadFinished()) { // If a packet is ready, we take it into account. Otherwise, we // wait for a new packet. this.filesToUpload = this.fileUploadManagerThread .getNextPacket(); if (this.filesToUpload != null) { this.uploadPolicy.displayDebug("Before do upload", 5); // Let's go to work. doUpload(); this.uploadPolicy.displayDebug("After do upload", 5); } else { try { // We wait a little. If a file is prepared in the // meantime, this thread is notified. The wait duration, // is just to be sure to go and see if there is still // some work from time to time. sleep(200); } catch (InterruptedException e) { // Nothing to do. We'll just take a look at the loop // condition. } } } } catch (JUploadException e) { this.fileUploadManagerThread.setUploadException(e); } this.uploadPolicy.displayDebug("End of the FileUploadThread", 5); }// run /** * Actual execution file(s) upload. It's called by the run methods, once for * all files, or file by file, depending on the UploadPolicy. The list of * files to upload is stored in the {@link #filesToUpload} array.<BR> * This method is called by the run() method. The prerequisite about the * filesToUpload array are: <DIR> * <LI>If the sum of contentLength for the files in the array is more than * the maxChunkSize, then nbFilesToUploadParam is one. * <LI>The number of elements in filesToUpload is less (or equal) than the * nbMaxFilesPerUpload. </DIR> * * @throws JUploadException */ final private void doUpload() throws JUploadException { boolean bChunkEnabled = false; long totalContentLength = 0; long totalFileLength = 0; // We are about to start a new upload. this.fileUploadManagerThread.setUploadStatus(0, FileUploadManagerThread.UPLOAD_STATUS_UPLOADING); // Prepare upload, for all files to be uploaded. beforeRequest(); for (int i = 0; i < this.filesToUpload.length && !this.fileUploadManagerThread.isUploadStopped(); i++) { // Total length, for HTTP upload. totalContentLength += this.filesToUpload[i].getUploadLength(); totalContentLength += getAdditionnalBytesForUpload(i); // Total file length: used to manage the progress bar (we don't // follow the bytes uploaded within headers and forms). totalFileLength += this.filesToUpload[i].getUploadLength(); this.uploadPolicy.displayDebug("file " + (this.fileUploadManagerThread.getNbUploadedFiles() + i) + ": content=" + this.filesToUpload[i].getUploadLength() + " bytes, getAdditionnalBytesForUpload=" + getAdditionnalBytesForUpload(i) + " bytes", 50); }// for // Ok, now we check that the totalContentLength is less than the chunk // size. if (totalFileLength >= this.maxChunkSize) { // hum, hum, we have to download file by file, with chunk enabled. // This a prerequisite of this method. if (this.filesToUpload.length > 1) { this.fileUploadManagerThread .setUploadException(new JUploadException( "totalContentLength >= chunkSize: this.filesToUpload.length should be 1 (doUpload)")); } bChunkEnabled = true; } // Now, we can actually do the job. This is delegate into smaller // method, for easier understanding. if (bChunkEnabled) { doChunkedUpload(totalContentLength, totalFileLength); } else { doNonChunkedUpload(totalContentLength, totalFileLength); } this.fileUploadManagerThread .currentRequestIsFinished(this.filesToUpload); // We are finished with this packet. Let's display it. this.fileUploadManagerThread.setUploadStatus(this.filesToUpload.length, FileUploadManagerThread.UPLOAD_STATUS_UPLOADED); } /** * Execution of an upload, in chunk mode. This method expects that the * {@link #filesToUpload} array contains only one line. * * @throws JUploadException When any error occurs, or when there is more * than one file in {@link #filesToUpload}. */ final private void doChunkedUpload(final long totalContentLength, final long totalFileLength) throws JUploadException { boolean bLastChunk = false; int chunkPart = 0; long contentLength = 0; long thisChunkSize = 0; // No more than one file, when in chunk mode. if (this.filesToUpload.length > 1) { throw new JUploadException( - "totalContentLength >= chunkSize: this.filesToUpload.length should be more than 1 (doUpload)"); + "totalContentLength >= chunkSize: this.filesToUpload.length should not be more than 1 (doUpload)"); } // This while enables the chunk management: // In chunk mode, it loops until the last chunk is uploaded. This works // only because, in chunk mode, // files are uploaded one y one (the for loop within the while loops // through ... 1 unique file). // In normal mode, it does nothing, as the bLastChunk is set to true in // the first test, within the while. while (!bLastChunk && this.fileUploadManagerThread.getUploadException() == null && !this.fileUploadManagerThread.isUploadStopped()) { // Let's manage chunk: // Files are uploaded one by one. This is checked just above. chunkPart += 1; bLastChunk = (contentLength > this.filesToUpload[0] .getRemainingLength()); // Is this the last chunk ? if (bLastChunk) { thisChunkSize = this.filesToUpload[0].getRemainingLength(); } else { thisChunkSize = this.maxChunkSize; } contentLength = thisChunkSize + getAdditionnalBytesForUpload(0); // Ok, we've prepare the job for chunk upload. Let's do it! startRequest(contentLength, true, chunkPart, bLastChunk); // Let's add any file-specific header. beforeFile(0); // Actual upload of the file: this.filesToUpload[0].uploadFile(getOutputStream(), thisChunkSize); // If we are not in chunk mode, or if it was the last chunk, // upload should be finished. if (bLastChunk && this.filesToUpload[0].getRemainingLength() > 0) { throw new JUploadExceptionUploadFailed( "Files has not be entirely uploaded. The remaining size is " + this.filesToUpload[0].getRemainingLength() + " bytes. File size was: " + this.filesToUpload[0].getUploadLength() + " bytes."); } // Let's add any file-specific header. afterFile(0); // Let's finish the request, and wait for the server Output, if // any (not applicable in FTP) int status = finishRequest(); // We now ask to the uploadPolicy, if it was a success. // If not, the isUploadSuccessful should raise an exception. this.uploadPolicy.checkUploadSuccess(status, getResponseMsg(), getResponseBody()); cleanRequest(); } // Let's tell our manager that we've done the job! this.fileUploadManagerThread .anotherFileHasBeenSent(this.filesToUpload[0]); }// doChunkedUpload /** * Execution of an upload, in standard mode. This method uploads all files * in the {@link #filesToUpload} array. * * @throws JUploadException When any error occurs, or when there is more * than one file in {@link #filesToUpload}. */ final private void doNonChunkedUpload(final long totalContentLength, final long totalFileLength) throws JUploadException { // First step is to prepare all files. startRequest(totalContentLength, false, 0, true); // Then, upload each file. for (int i = 0; i < this.filesToUpload.length && !this.fileUploadManagerThread.isUploadStopped(); i++) { // We are about to start a new upload. this.fileUploadManagerThread.setUploadStatus(i, FileUploadManagerThread.UPLOAD_STATUS_UPLOADING); // Let's add any file-specific header. beforeFile(i); // Actual upload of the file: this.filesToUpload[i].uploadFile(getOutputStream(), this.filesToUpload[i].getUploadLength()); // Let's add any file-specific header. afterFile(i); // Let's tell our manager that we've done the job! // Ok, maybe the server will refuse it, but we won't say that now! this.fileUploadManagerThread .anotherFileHasBeenSent(this.filesToUpload[i]); } // We are finished with this one. Let's display it. this.fileUploadManagerThread .setUploadStatus( this.filesToUpload.length, FileUploadManagerThread.UPLOAD_STATUS_UPLOADED_WAITING_FOR_RESPONSE); // Let's finish the request, and wait for the server Output, if // any (not applicable in FTP) int status = finishRequest(); // We now ask to the uploadPolicy, if it was a success. // If not, the isUploadSuccessful should raise an exception. this.uploadPolicy.checkUploadSuccess(status, getResponseMsg(), getResponseBody()); cleanRequest(); }// doNonChunkedUpload /** @see FileUploadThread#close() */ public void close() { try { cleanAll(); } catch (JUploadException e) { this.uploadPolicy.displayErr(e); } } /** * Replace single \r and \n by uniform end of line characters (CRLF). This * makes it easier, to search for string within the body. * * @param s The original string * @return The string with single \r and \n modified changed to CRLF (\r\n). */ public final String normalizeCRLF(String s) { Pattern p = Pattern.compile("\\r\\n|\\r|\\n", Pattern.MULTILINE); String[] lines = p.split(s); // Worst case: the s string contains only \n or \r characters: we then // need to triple the string length. Let's say double is enough. StringBuffer sb = new StringBuffer(s.length() * 2); for (int i = 0; i < lines.length; i += 1) { sb.append(lines[i]).append("\r\n"); } return sb.toString(); } /** * Replace \r and \n by correctly displayed end of line characters. Used to * display debug output. It also replace any single \r or \n by \r\n, to * make it easier, to search for string within the body. * * @param s The original string * @return The string with \r and \n modified, to be correctly displayed. */ public final String quoteCRLF(String s) { return s.replaceAll("\r\n", "\\\\r\\\\n\n"); } }
true
true
final private void doChunkedUpload(final long totalContentLength, final long totalFileLength) throws JUploadException { boolean bLastChunk = false; int chunkPart = 0; long contentLength = 0; long thisChunkSize = 0; // No more than one file, when in chunk mode. if (this.filesToUpload.length > 1) { throw new JUploadException( "totalContentLength >= chunkSize: this.filesToUpload.length should be more than 1 (doUpload)"); } // This while enables the chunk management: // In chunk mode, it loops until the last chunk is uploaded. This works // only because, in chunk mode, // files are uploaded one y one (the for loop within the while loops // through ... 1 unique file). // In normal mode, it does nothing, as the bLastChunk is set to true in // the first test, within the while. while (!bLastChunk && this.fileUploadManagerThread.getUploadException() == null && !this.fileUploadManagerThread.isUploadStopped()) { // Let's manage chunk: // Files are uploaded one by one. This is checked just above. chunkPart += 1; bLastChunk = (contentLength > this.filesToUpload[0] .getRemainingLength()); // Is this the last chunk ? if (bLastChunk) { thisChunkSize = this.filesToUpload[0].getRemainingLength(); } else { thisChunkSize = this.maxChunkSize; } contentLength = thisChunkSize + getAdditionnalBytesForUpload(0); // Ok, we've prepare the job for chunk upload. Let's do it! startRequest(contentLength, true, chunkPart, bLastChunk); // Let's add any file-specific header. beforeFile(0); // Actual upload of the file: this.filesToUpload[0].uploadFile(getOutputStream(), thisChunkSize); // If we are not in chunk mode, or if it was the last chunk, // upload should be finished. if (bLastChunk && this.filesToUpload[0].getRemainingLength() > 0) { throw new JUploadExceptionUploadFailed( "Files has not be entirely uploaded. The remaining size is " + this.filesToUpload[0].getRemainingLength() + " bytes. File size was: " + this.filesToUpload[0].getUploadLength() + " bytes."); } // Let's add any file-specific header. afterFile(0); // Let's finish the request, and wait for the server Output, if // any (not applicable in FTP) int status = finishRequest(); // We now ask to the uploadPolicy, if it was a success. // If not, the isUploadSuccessful should raise an exception. this.uploadPolicy.checkUploadSuccess(status, getResponseMsg(), getResponseBody()); cleanRequest(); } // Let's tell our manager that we've done the job! this.fileUploadManagerThread .anotherFileHasBeenSent(this.filesToUpload[0]); }// doChunkedUpload
final private void doChunkedUpload(final long totalContentLength, final long totalFileLength) throws JUploadException { boolean bLastChunk = false; int chunkPart = 0; long contentLength = 0; long thisChunkSize = 0; // No more than one file, when in chunk mode. if (this.filesToUpload.length > 1) { throw new JUploadException( "totalContentLength >= chunkSize: this.filesToUpload.length should not be more than 1 (doUpload)"); } // This while enables the chunk management: // In chunk mode, it loops until the last chunk is uploaded. This works // only because, in chunk mode, // files are uploaded one y one (the for loop within the while loops // through ... 1 unique file). // In normal mode, it does nothing, as the bLastChunk is set to true in // the first test, within the while. while (!bLastChunk && this.fileUploadManagerThread.getUploadException() == null && !this.fileUploadManagerThread.isUploadStopped()) { // Let's manage chunk: // Files are uploaded one by one. This is checked just above. chunkPart += 1; bLastChunk = (contentLength > this.filesToUpload[0] .getRemainingLength()); // Is this the last chunk ? if (bLastChunk) { thisChunkSize = this.filesToUpload[0].getRemainingLength(); } else { thisChunkSize = this.maxChunkSize; } contentLength = thisChunkSize + getAdditionnalBytesForUpload(0); // Ok, we've prepare the job for chunk upload. Let's do it! startRequest(contentLength, true, chunkPart, bLastChunk); // Let's add any file-specific header. beforeFile(0); // Actual upload of the file: this.filesToUpload[0].uploadFile(getOutputStream(), thisChunkSize); // If we are not in chunk mode, or if it was the last chunk, // upload should be finished. if (bLastChunk && this.filesToUpload[0].getRemainingLength() > 0) { throw new JUploadExceptionUploadFailed( "Files has not be entirely uploaded. The remaining size is " + this.filesToUpload[0].getRemainingLength() + " bytes. File size was: " + this.filesToUpload[0].getUploadLength() + " bytes."); } // Let's add any file-specific header. afterFile(0); // Let's finish the request, and wait for the server Output, if // any (not applicable in FTP) int status = finishRequest(); // We now ask to the uploadPolicy, if it was a success. // If not, the isUploadSuccessful should raise an exception. this.uploadPolicy.checkUploadSuccess(status, getResponseMsg(), getResponseBody()); cleanRequest(); } // Let's tell our manager that we've done the job! this.fileUploadManagerThread .anotherFileHasBeenSent(this.filesToUpload[0]); }// doChunkedUpload
diff --git a/src/at/ac/tuwien/lsdc/mape/Planner.java b/src/at/ac/tuwien/lsdc/mape/Planner.java index 406c1fe..8f07119 100644 --- a/src/at/ac/tuwien/lsdc/mape/Planner.java +++ b/src/at/ac/tuwien/lsdc/mape/Planner.java @@ -1,8 +1,8 @@ package at.ac.tuwien.lsdc.mape; import at.ac.tuwien.lsdc.actions.Action; public abstract class Planner { - public Action selectAction(App app); + public abstract Action selectAction(Problem problem); }
true
true
public Action selectAction(App app);
public abstract Action selectAction(Problem problem);
diff --git a/src/powercrystals/minefactoryreloaded/tile/machine/TileEntityRedNote.java b/src/powercrystals/minefactoryreloaded/tile/machine/TileEntityRedNote.java index 2770a82c..003dffa7 100644 --- a/src/powercrystals/minefactoryreloaded/tile/machine/TileEntityRedNote.java +++ b/src/powercrystals/minefactoryreloaded/tile/machine/TileEntityRedNote.java @@ -1,35 +1,35 @@ package powercrystals.minefactoryreloaded.tile.machine; import powercrystals.minefactoryreloaded.tile.base.TileEntityFactory; public class TileEntityRedNote extends TileEntityFactory { private static final String[] _noteNames = new String[] { "harp", "bd", "snare", "hat", "bassattack" }; private boolean _playedLastChange = true; @Override public void onRedNetChanged(int value) { - if(value < 0 || value > 125) + if(value < 0 || value > 119) { return; } if(_playedLastChange) { _playedLastChange = false; return; } else { _playedLastChange = true; } int instrument = value / 25; int note = value % 25; float f = (float)Math.pow(2.0D, (note - 12) / 12.0D); worldObj.playSoundEffect(xCoord + 0.5D, yCoord + 0.5D, zCoord + 0.5D, "note." + _noteNames[instrument], 3.0F, f); } }
true
true
public void onRedNetChanged(int value) { if(value < 0 || value > 125) { return; } if(_playedLastChange) { _playedLastChange = false; return; } else { _playedLastChange = true; } int instrument = value / 25; int note = value % 25; float f = (float)Math.pow(2.0D, (note - 12) / 12.0D); worldObj.playSoundEffect(xCoord + 0.5D, yCoord + 0.5D, zCoord + 0.5D, "note." + _noteNames[instrument], 3.0F, f); }
public void onRedNetChanged(int value) { if(value < 0 || value > 119) { return; } if(_playedLastChange) { _playedLastChange = false; return; } else { _playedLastChange = true; } int instrument = value / 25; int note = value % 25; float f = (float)Math.pow(2.0D, (note - 12) / 12.0D); worldObj.playSoundEffect(xCoord + 0.5D, yCoord + 0.5D, zCoord + 0.5D, "note." + _noteNames[instrument], 3.0F, f); }
diff --git a/LaTeXDraw/src/net/sf/latexdraw/glib/views/Java2D/impl/LViewsFactory.java b/LaTeXDraw/src/net/sf/latexdraw/glib/views/Java2D/impl/LViewsFactory.java index 613dcdf8..55a5a986 100644 --- a/LaTeXDraw/src/net/sf/latexdraw/glib/views/Java2D/impl/LViewsFactory.java +++ b/LaTeXDraw/src/net/sf/latexdraw/glib/views/Java2D/impl/LViewsFactory.java @@ -1,89 +1,89 @@ package net.sf.latexdraw.glib.views.Java2D.impl; import net.sf.latexdraw.glib.models.interfaces.*; import net.sf.latexdraw.glib.views.CreateViewCmd; import net.sf.latexdraw.glib.views.Java2D.interfaces.IViewShape; import net.sf.latexdraw.glib.views.Java2D.interfaces.IViewsFactory; /** * The factory that creates views from given models.<br> *<br> * This file is part of LaTeXDraw<br> * Copyright (c) 2005-2012 Arnaud BLOUIN<br> *<br> * LaTeXDraw is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version.<br> *<br> * LaTeXDraw is distributed 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.<br> *<br> * 03/10/08<br> * @author Arnaud BLOUIN * @since 3.0 * @version 3.0 */ public class LViewsFactory implements IViewsFactory { /** The chain of responsibility used to reduce the complexity of the factory. */ private CreateView2DCmd createCmd; /** * Creates the factory. */ public LViewsFactory() { super(); initCommands(); } @Override public IViewShape createView(final IShape shape) { return shape==null ? null : createCmd.execute(shape); } /** * Initialises the chain of responsibility. */ private void initCommands() { CreateView2DCmd cmd = new CreateView2DCmd(null, IPicture.class) { @Override public IViewShape create(final IShape shape) { return new LPictureView((IPicture)shape); } }; cmd = new CreateView2DCmd(cmd, IFreehand.class) { @Override public IViewShape create(final IShape shape) { return new LFreeHandView((IFreehand)shape); } }; cmd = new CreateView2DCmd(cmd, IDot.class) { @Override public IViewShape create(final IShape shape) { return new LDotView((IDot)shape); } }; cmd = new CreateView2DCmd(cmd, IGrid.class) { @Override public IViewShape create(final IShape shape) { return new LGridView((IGrid)shape); } }; cmd = new CreateView2DCmd(cmd, IAxes.class) { @Override public IViewShape create(final IShape shape) { return new LAxesView((IAxes)shape); } }; cmd = new CreateView2DCmd(cmd, IBezierCurve.class){ @Override public IViewShape create(final IShape shape) { return new LBezierCurveView((IBezierCurve)shape); } }; cmd = new CreateView2DCmd(cmd, IPolygon.class) { @Override public IViewShape create(final IShape shape) { return new LPolygonView<IPolygon>((IPolygon)shape); } }; // All the commands of the chain of responsibility are chained together. cmd = new CreateView2DCmd(cmd, IPolyline.class) { @Override public IViewShape create(final IShape shape) { return new LPolylineView((IPolyline)shape); } }; cmd = new CreateView2DCmd(cmd, IRhombus.class) { @Override public IViewShape create(final IShape shape) { return new LRhombusView((IRhombus)shape); } }; cmd = new CreateView2DCmd(cmd, ITriangle.class) { @Override public IViewShape create(final IShape shape) { return new LTriangleView((ITriangle)shape); } }; - cmd = new CreateView2DCmd(cmd, IGroup.class) { @Override public IViewShape create(final IShape shape) { return new LGroupView((IGroup)shape); } }; cmd = new CreateView2DCmd(cmd, IEllipse.class) { @Override public IViewShape create(final IShape shape) { return new LEllipseView<IEllipse>((IEllipse)shape); } }; cmd = new CreateView2DCmd(cmd, IArc.class) { @Override public IViewShape create(final IShape shape) { return new LArcView<ICircleArc>((IArc)shape); } }; cmd = new CreateView2DCmd(cmd, ICircleArc.class) { @Override public IViewShape create(final IShape shape) { return new LCircleArcView((ICircleArc)shape); } }; cmd = new CreateView2DCmd(cmd, ICircle.class) { @Override public IViewShape create(final IShape shape) { return new LCircleView((ICircle)shape); } }; cmd = new CreateView2DCmd(cmd, IText.class) { @Override public IViewShape create(final IShape shape) { return new LTextView((IText)shape); } }; cmd = new CreateView2DCmd(cmd, IRectangle.class) { @Override public IViewShape create(final IShape shape) { return new LRectangleView<ISquare>((IRectangle)shape); } }; + cmd = new CreateView2DCmd(cmd, ISquare.class) { @Override public IViewShape create(final IShape shape) { return new LSquareView((ISquare)shape); } }; // The last created command is the first element of the chain. - createCmd = new CreateView2DCmd(cmd, ISquare.class) { @Override public IViewShape create(final IShape shape) { return new LSquareView((ISquare)shape); } }; + createCmd = new CreateView2DCmd(cmd, IGroup.class) { @Override public IViewShape create(final IShape shape) { return new LGroupView((IGroup)shape); } }; } /** * This class is a mix of the design patterns Command and Chain of responsibility. * The goal is to find the command which can create the view of the given shape. */ private abstract class CreateView2DCmd extends CreateViewCmd<IShape, IViewShape, CreateView2DCmd> { /** * Creates the command. * @param next The next command in the chain of responsibility. Can be null. * @param classShape The type of the shape supported by the command. * @since 3.0 */ public CreateView2DCmd(final CreateView2DCmd next, final Class<? extends IShape> classShape) { super(next, classShape); } } }
false
true
private void initCommands() { CreateView2DCmd cmd = new CreateView2DCmd(null, IPicture.class) { @Override public IViewShape create(final IShape shape) { return new LPictureView((IPicture)shape); } }; cmd = new CreateView2DCmd(cmd, IFreehand.class) { @Override public IViewShape create(final IShape shape) { return new LFreeHandView((IFreehand)shape); } }; cmd = new CreateView2DCmd(cmd, IDot.class) { @Override public IViewShape create(final IShape shape) { return new LDotView((IDot)shape); } }; cmd = new CreateView2DCmd(cmd, IGrid.class) { @Override public IViewShape create(final IShape shape) { return new LGridView((IGrid)shape); } }; cmd = new CreateView2DCmd(cmd, IAxes.class) { @Override public IViewShape create(final IShape shape) { return new LAxesView((IAxes)shape); } }; cmd = new CreateView2DCmd(cmd, IBezierCurve.class){ @Override public IViewShape create(final IShape shape) { return new LBezierCurveView((IBezierCurve)shape); } }; cmd = new CreateView2DCmd(cmd, IPolygon.class) { @Override public IViewShape create(final IShape shape) { return new LPolygonView<IPolygon>((IPolygon)shape); } }; // All the commands of the chain of responsibility are chained together. cmd = new CreateView2DCmd(cmd, IPolyline.class) { @Override public IViewShape create(final IShape shape) { return new LPolylineView((IPolyline)shape); } }; cmd = new CreateView2DCmd(cmd, IRhombus.class) { @Override public IViewShape create(final IShape shape) { return new LRhombusView((IRhombus)shape); } }; cmd = new CreateView2DCmd(cmd, ITriangle.class) { @Override public IViewShape create(final IShape shape) { return new LTriangleView((ITriangle)shape); } }; cmd = new CreateView2DCmd(cmd, IGroup.class) { @Override public IViewShape create(final IShape shape) { return new LGroupView((IGroup)shape); } }; cmd = new CreateView2DCmd(cmd, IEllipse.class) { @Override public IViewShape create(final IShape shape) { return new LEllipseView<IEllipse>((IEllipse)shape); } }; cmd = new CreateView2DCmd(cmd, IArc.class) { @Override public IViewShape create(final IShape shape) { return new LArcView<ICircleArc>((IArc)shape); } }; cmd = new CreateView2DCmd(cmd, ICircleArc.class) { @Override public IViewShape create(final IShape shape) { return new LCircleArcView((ICircleArc)shape); } }; cmd = new CreateView2DCmd(cmd, ICircle.class) { @Override public IViewShape create(final IShape shape) { return new LCircleView((ICircle)shape); } }; cmd = new CreateView2DCmd(cmd, IText.class) { @Override public IViewShape create(final IShape shape) { return new LTextView((IText)shape); } }; cmd = new CreateView2DCmd(cmd, IRectangle.class) { @Override public IViewShape create(final IShape shape) { return new LRectangleView<ISquare>((IRectangle)shape); } }; // The last created command is the first element of the chain. createCmd = new CreateView2DCmd(cmd, ISquare.class) { @Override public IViewShape create(final IShape shape) { return new LSquareView((ISquare)shape); } }; }
private void initCommands() { CreateView2DCmd cmd = new CreateView2DCmd(null, IPicture.class) { @Override public IViewShape create(final IShape shape) { return new LPictureView((IPicture)shape); } }; cmd = new CreateView2DCmd(cmd, IFreehand.class) { @Override public IViewShape create(final IShape shape) { return new LFreeHandView((IFreehand)shape); } }; cmd = new CreateView2DCmd(cmd, IDot.class) { @Override public IViewShape create(final IShape shape) { return new LDotView((IDot)shape); } }; cmd = new CreateView2DCmd(cmd, IGrid.class) { @Override public IViewShape create(final IShape shape) { return new LGridView((IGrid)shape); } }; cmd = new CreateView2DCmd(cmd, IAxes.class) { @Override public IViewShape create(final IShape shape) { return new LAxesView((IAxes)shape); } }; cmd = new CreateView2DCmd(cmd, IBezierCurve.class){ @Override public IViewShape create(final IShape shape) { return new LBezierCurveView((IBezierCurve)shape); } }; cmd = new CreateView2DCmd(cmd, IPolygon.class) { @Override public IViewShape create(final IShape shape) { return new LPolygonView<IPolygon>((IPolygon)shape); } }; // All the commands of the chain of responsibility are chained together. cmd = new CreateView2DCmd(cmd, IPolyline.class) { @Override public IViewShape create(final IShape shape) { return new LPolylineView((IPolyline)shape); } }; cmd = new CreateView2DCmd(cmd, IRhombus.class) { @Override public IViewShape create(final IShape shape) { return new LRhombusView((IRhombus)shape); } }; cmd = new CreateView2DCmd(cmd, ITriangle.class) { @Override public IViewShape create(final IShape shape) { return new LTriangleView((ITriangle)shape); } }; cmd = new CreateView2DCmd(cmd, IEllipse.class) { @Override public IViewShape create(final IShape shape) { return new LEllipseView<IEllipse>((IEllipse)shape); } }; cmd = new CreateView2DCmd(cmd, IArc.class) { @Override public IViewShape create(final IShape shape) { return new LArcView<ICircleArc>((IArc)shape); } }; cmd = new CreateView2DCmd(cmd, ICircleArc.class) { @Override public IViewShape create(final IShape shape) { return new LCircleArcView((ICircleArc)shape); } }; cmd = new CreateView2DCmd(cmd, ICircle.class) { @Override public IViewShape create(final IShape shape) { return new LCircleView((ICircle)shape); } }; cmd = new CreateView2DCmd(cmd, IText.class) { @Override public IViewShape create(final IShape shape) { return new LTextView((IText)shape); } }; cmd = new CreateView2DCmd(cmd, IRectangle.class) { @Override public IViewShape create(final IShape shape) { return new LRectangleView<ISquare>((IRectangle)shape); } }; cmd = new CreateView2DCmd(cmd, ISquare.class) { @Override public IViewShape create(final IShape shape) { return new LSquareView((ISquare)shape); } }; // The last created command is the first element of the chain. createCmd = new CreateView2DCmd(cmd, IGroup.class) { @Override public IViewShape create(final IShape shape) { return new LGroupView((IGroup)shape); } }; }
diff --git a/applications/rainbow/src/main/java/net/sf/okapi/applications/rainbow/batchconfig/BatchConfiguration.java b/applications/rainbow/src/main/java/net/sf/okapi/applications/rainbow/batchconfig/BatchConfiguration.java index 95732b7cf..f33fdd392 100644 --- a/applications/rainbow/src/main/java/net/sf/okapi/applications/rainbow/batchconfig/BatchConfiguration.java +++ b/applications/rainbow/src/main/java/net/sf/okapi/applications/rainbow/batchconfig/BatchConfiguration.java @@ -1,415 +1,414 @@ /*=========================================================================== Copyright (C) 2011 by the Okapi Framework contributors ----------------------------------------------------------------------------- This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA See also the full LGPL text here: http://www.gnu.org/copyleft/lesser.html ===========================================================================*/ package net.sf.okapi.applications.rainbow.batchconfig; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.RandomAccessFile; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import net.sf.okapi.applications.rainbow.Input; import net.sf.okapi.applications.rainbow.pipeline.PipelineStorage; import net.sf.okapi.applications.rainbow.pipeline.StepInfo; import net.sf.okapi.common.IParameters; import net.sf.okapi.common.ReferenceParameter; import net.sf.okapi.common.Util; import net.sf.okapi.common.exceptions.OkapiFileNotFoundException; import net.sf.okapi.common.exceptions.OkapiIOException; import net.sf.okapi.common.filters.FilterConfiguration; import net.sf.okapi.common.filters.IFilterConfigurationMapper; import net.sf.okapi.common.pipeline.IPipeline; import net.sf.okapi.common.pipeline.IPipelineStep; public class BatchConfiguration { private static final int MAXBUFFERSIZE = 1024*8; private static final int MAXBLOCKLEN = 65000; private static final String SIGNATURE = "batchConf"; private static final int VERSION = 1; public void exportConfiguration (String configPath, IPipeline pipeline, IFilterConfigurationMapper fcMapper, List<Input> inputFiles) { DataOutputStream dos = null; try { // Prepare the output dos = new DataOutputStream(new FileOutputStream(configPath)); dos.writeUTF(SIGNATURE); dos.writeInt(VERSION); //=== Section 1: the dereferenced files of the pipeline's parameters // int = id (-1 mark the end) // String = extension // String = content // Go through each step of the pipeline for ( IPipelineStep step : pipeline.getSteps() ) { // Get the parameters for that step IParameters params = step.getParameters(); if ( params == null ) continue; // Get all methods for the parameters object Method[] methods = params.getClass().getMethods(); // Look for references int id = 0; for ( Method m : methods ) { if ( Modifier.isPublic(m.getModifiers() ) && m.isAnnotationPresent(ReferenceParameter.class)) { String refPath = (String)m.invoke(params); harvestReferencedFile(dos, ++id, refPath); } } } // Last ID=-1 to mark no more references dos.writeInt(-1); //=== Section 2: The pipeline itself // OK to use null, because the available steps are not used for writing PipelineStorage store = new PipelineStorage(null); store.write(pipeline); writeLongString(dos, store.getStringOutput()); //=== Section 3: The filter configurations // Get the number of custom configurations Iterator<FilterConfiguration> iter = fcMapper.getAllConfigurations(); int count = 0; while ( iter.hasNext() ) { if ( iter.next().custom ) count++; } dos.writeInt(count); // Write each filter configuration iter = fcMapper.getAllConfigurations(); while ( iter.hasNext() ) { FilterConfiguration fc = iter.next(); if ( fc.custom ) { dos.writeUTF(fc.configId); IParameters params = fcMapper.getCustomParameters(fc); dos.writeUTF(params.toString()); } } //=== Section 4: Mapping extensions -> filter configuration id if ( inputFiles != null ) { // Gather the extensions (if duplicate: first one is used) HashMap<String, String> extMap = new HashMap<String, String>(); // From the input files first for ( Input input : inputFiles ) { String ext = Util.getExtension(input.relativePath); if ( !Util.isEmpty(ext) && !extMap.containsKey(ext) && !Util.isEmpty(input.filterConfigId)) { extMap.put(ext, input.filterConfigId); } } // Then complement with the default iter = fcMapper.getAllConfigurations(); while ( iter.hasNext() ) { FilterConfiguration fc = iter.next(); String ext = fc.extensions; if ( Util.isEmpty(ext) ) continue; int n = ext.indexOf(';'); if ( n > 0 ) ext = ext.substring(0, n); if ( !extMap.containsKey(ext) ) { extMap.put(ext, fc.configId); } } // Write out the mapping dos.writeInt(extMap.size()); for ( String ext : extMap.keySet() ) { dos.writeUTF(ext); dos.writeUTF(extMap.get(ext)); } } else { dos.writeInt(0); // None } } catch ( IllegalArgumentException e ) { throw new OkapiIOException("Error when calling getter method.", e); } catch ( IllegalAccessException e ) { throw new OkapiIOException("Error when calling getter method.", e); } catch ( InvocationTargetException e ) { throw new OkapiIOException("Error when calling getter method.", e); } catch ( FileNotFoundException e ) { throw new OkapiFileNotFoundException(e); } catch ( IOException e ) { throw new OkapiIOException(e); } finally { // Close the output file if ( dos != null ) { try { dos.close(); } catch ( IOException e ) { throw new OkapiIOException(e); } } } } public void installConfiguration (String configPath, String outputDir, Map<String, StepInfo> availableSteps) { RandomAccessFile raf = null; PrintWriter pw = null; try { raf = new RandomAccessFile(configPath, "r"); String tmp = raf.readUTF(); // signature if ( !SIGNATURE.equals(tmp) ) { throw new OkapiIOException("Invalid file format."); } int version = raf.readInt(); // Version info if ( version != VERSION ) { throw new OkapiIOException("Invalid version."); } Util.createDirectories(outputDir+File.separator); //=== Section 1: references data // Build a lookup table to the references HashMap<Integer, Long> refMap = new HashMap<Integer, Long>(); int id = raf.readInt(); // First ID or end of section marker long pos = raf.getFilePointer(); while ( id != -1 ) { raf.readUTF(); // Skip filename // Add the entry in the lookup table refMap.put(id, pos); // Skip over the data to move to the next reference long size = raf.readLong(); if ( size > 0 ) { raf.seek(raf.getFilePointer()+size); } // Then get the information for next entry id = raf.readInt(); // ID pos = raf.getFilePointer(); // Position - if ( id > 0 ) raf.readUTF(); // Skip filename } //=== Section 2 : the pipeline itself tmp = readLongString(raf); long startFilterConfigs = raf.getFilePointer(); // Read the pipeline and instantiate the steps PipelineStorage store = new PipelineStorage(availableSteps, (CharSequence)tmp); IPipeline pipeline = store.read(); byte[] buffer = new byte[MAXBUFFERSIZE]; // Go through each step of the pipeline for ( IPipelineStep step : pipeline.getSteps() ) { // Get the parameters for that step IParameters params = step.getParameters(); if ( params == null ) continue; // Get all methods for the parameters object Method[] methods = params.getClass().getMethods(); // Look for references id = 0; for ( Method m : methods ) { if ( Modifier.isPublic(m.getModifiers() ) && m.isAnnotationPresent(ReferenceParameter.class)) { // Update the references to point to the new location // Read the reference content pos = refMap.get(++id); raf.seek(pos); String filename = raf.readUTF(); long size = raf.readLong(); // Read the size // Save the data to a file if ( !Util.isEmpty(filename) ) { String path = outputDir + File.separator + filename; FileOutputStream fos = new FileOutputStream(path); int toRead = (int)Math.min(size, MAXBUFFERSIZE); int bytesRead = raf.read(buffer, 0, toRead); while ( bytesRead > 0 ) { fos.write(buffer, 0, bytesRead); size -= bytesRead; if ( size <= 0 ) break; toRead = (int)Math.min(size, MAXBUFFERSIZE); bytesRead = raf.read(buffer, 0, toRead); } fos.close(); // Update the reference in the parameters to point to the saved file // Test changing the value String setMethodName = "set"+m.getName().substring(3); Method setMethod = params.getClass().getMethod(setMethodName, String.class); setMethod.invoke(params, path); } } } } // Write out the pipeline file String path = outputDir + File.separator + "pipeline.pln"; pw = new PrintWriter(path, "UTF-8"); store.write(pipeline); pw.write(store.getStringOutput()); pw.close(); //=== Section 3 : the filter configurations raf.seek(startFilterConfigs); // Get the number of filter configurations int count = raf.readInt(); // Read each one for ( int i=0; i<count; i++ ) { String configId = raf.readUTF(); String data = raf.readUTF(); // And create the parameters file path = outputDir + File.separator + configId + ".fprm"; pw = new PrintWriter(path, "UTF-8"); pw.write(data); pw.close(); } //=== Section 4: the extensions -> filter configuration id mapping // Get the number of mappings path = outputDir + File.separator + "extensions-mapping.txt"; pw = new PrintWriter(path, "UTF-8"); String lb = System.getProperty("line.separator"); count = raf.readInt(); for ( int i=0; i<count; i++ ) { String ext = raf.readUTF(); String configId = raf.readUTF(); pw.write(ext + "\t" + configId + lb); } pw.close(); } catch ( Throwable e ) { throw new OkapiIOException("Error when installing the batch configuration.\n"+e.getMessage(), e); } finally { if ( pw != null ) { pw.close(); } if ( raf != null ) { try { raf.close(); } catch ( IOException e ) { throw new OkapiIOException(e); } } } } private void harvestReferencedFile (DataOutputStream dos, int id, String refPath) throws IOException { FileInputStream fis = null; try { dos.writeInt(id); String filename = Util.getFilename(refPath, true); dos.writeUTF(filename); // Deal with empty references if ( Util.isEmpty(refPath) ) { dos.writeLong(0); return; } // Else: copy the content of the referenced file // Write the size of the file File file = new File(refPath); long size = file.length(); dos.writeLong(size); // Write the content if ( size > 0 ) { fis = new FileInputStream(refPath); int bufferSize = Math.min(fis.available(), MAXBUFFERSIZE); byte[] buffer = new byte[bufferSize]; int bytesRead = fis.read(buffer, 0, bufferSize); while ( bytesRead > 0 ) { dos.write(buffer, 0, bufferSize); bufferSize = Math.min(fis.available(), MAXBUFFERSIZE); bytesRead = fis.read(buffer, 0, bufferSize); } } } finally { if ( fis != null ) { fis.close(); } } } private void writeLongString (DataOutputStream dos, String data) throws IOException { int r = (data.length() % MAXBLOCKLEN); int n = (data.length() / MAXBLOCKLEN); int count = n + ((r > 0) ? 1 : 0); dos.writeInt(count); // Number of blocks int pos = 0; // Write the full blocks for ( int i=0; i<n; i++ ) { dos.writeUTF(data.substring(pos, pos+MAXBLOCKLEN)); pos += MAXBLOCKLEN; } // Write the remaining text if ( r > 0 ) { dos.writeUTF(data.substring(pos)); } } private String readLongString (RandomAccessFile raf) throws IOException { StringBuilder tmp = new StringBuilder(); int count = raf.readInt(); for ( int i=0; i<count; i++ ) { tmp.append(raf.readUTF()); } return tmp.toString(); } }
true
true
public void installConfiguration (String configPath, String outputDir, Map<String, StepInfo> availableSteps) { RandomAccessFile raf = null; PrintWriter pw = null; try { raf = new RandomAccessFile(configPath, "r"); String tmp = raf.readUTF(); // signature if ( !SIGNATURE.equals(tmp) ) { throw new OkapiIOException("Invalid file format."); } int version = raf.readInt(); // Version info if ( version != VERSION ) { throw new OkapiIOException("Invalid version."); } Util.createDirectories(outputDir+File.separator); //=== Section 1: references data // Build a lookup table to the references HashMap<Integer, Long> refMap = new HashMap<Integer, Long>(); int id = raf.readInt(); // First ID or end of section marker long pos = raf.getFilePointer(); while ( id != -1 ) { raf.readUTF(); // Skip filename // Add the entry in the lookup table refMap.put(id, pos); // Skip over the data to move to the next reference long size = raf.readLong(); if ( size > 0 ) { raf.seek(raf.getFilePointer()+size); } // Then get the information for next entry id = raf.readInt(); // ID pos = raf.getFilePointer(); // Position if ( id > 0 ) raf.readUTF(); // Skip filename } //=== Section 2 : the pipeline itself tmp = readLongString(raf); long startFilterConfigs = raf.getFilePointer(); // Read the pipeline and instantiate the steps PipelineStorage store = new PipelineStorage(availableSteps, (CharSequence)tmp); IPipeline pipeline = store.read(); byte[] buffer = new byte[MAXBUFFERSIZE]; // Go through each step of the pipeline for ( IPipelineStep step : pipeline.getSteps() ) { // Get the parameters for that step IParameters params = step.getParameters(); if ( params == null ) continue; // Get all methods for the parameters object Method[] methods = params.getClass().getMethods(); // Look for references id = 0; for ( Method m : methods ) { if ( Modifier.isPublic(m.getModifiers() ) && m.isAnnotationPresent(ReferenceParameter.class)) { // Update the references to point to the new location // Read the reference content pos = refMap.get(++id); raf.seek(pos); String filename = raf.readUTF(); long size = raf.readLong(); // Read the size // Save the data to a file if ( !Util.isEmpty(filename) ) { String path = outputDir + File.separator + filename; FileOutputStream fos = new FileOutputStream(path); int toRead = (int)Math.min(size, MAXBUFFERSIZE); int bytesRead = raf.read(buffer, 0, toRead); while ( bytesRead > 0 ) { fos.write(buffer, 0, bytesRead); size -= bytesRead; if ( size <= 0 ) break; toRead = (int)Math.min(size, MAXBUFFERSIZE); bytesRead = raf.read(buffer, 0, toRead); } fos.close(); // Update the reference in the parameters to point to the saved file // Test changing the value String setMethodName = "set"+m.getName().substring(3); Method setMethod = params.getClass().getMethod(setMethodName, String.class); setMethod.invoke(params, path); } } } } // Write out the pipeline file String path = outputDir + File.separator + "pipeline.pln"; pw = new PrintWriter(path, "UTF-8"); store.write(pipeline); pw.write(store.getStringOutput()); pw.close(); //=== Section 3 : the filter configurations raf.seek(startFilterConfigs); // Get the number of filter configurations int count = raf.readInt(); // Read each one for ( int i=0; i<count; i++ ) { String configId = raf.readUTF(); String data = raf.readUTF(); // And create the parameters file path = outputDir + File.separator + configId + ".fprm"; pw = new PrintWriter(path, "UTF-8"); pw.write(data); pw.close(); } //=== Section 4: the extensions -> filter configuration id mapping // Get the number of mappings path = outputDir + File.separator + "extensions-mapping.txt"; pw = new PrintWriter(path, "UTF-8"); String lb = System.getProperty("line.separator"); count = raf.readInt(); for ( int i=0; i<count; i++ ) { String ext = raf.readUTF(); String configId = raf.readUTF(); pw.write(ext + "\t" + configId + lb); } pw.close(); } catch ( Throwable e ) { throw new OkapiIOException("Error when installing the batch configuration.\n"+e.getMessage(), e); } finally { if ( pw != null ) { pw.close(); } if ( raf != null ) { try { raf.close(); } catch ( IOException e ) { throw new OkapiIOException(e); } } } }
public void installConfiguration (String configPath, String outputDir, Map<String, StepInfo> availableSteps) { RandomAccessFile raf = null; PrintWriter pw = null; try { raf = new RandomAccessFile(configPath, "r"); String tmp = raf.readUTF(); // signature if ( !SIGNATURE.equals(tmp) ) { throw new OkapiIOException("Invalid file format."); } int version = raf.readInt(); // Version info if ( version != VERSION ) { throw new OkapiIOException("Invalid version."); } Util.createDirectories(outputDir+File.separator); //=== Section 1: references data // Build a lookup table to the references HashMap<Integer, Long> refMap = new HashMap<Integer, Long>(); int id = raf.readInt(); // First ID or end of section marker long pos = raf.getFilePointer(); while ( id != -1 ) { raf.readUTF(); // Skip filename // Add the entry in the lookup table refMap.put(id, pos); // Skip over the data to move to the next reference long size = raf.readLong(); if ( size > 0 ) { raf.seek(raf.getFilePointer()+size); } // Then get the information for next entry id = raf.readInt(); // ID pos = raf.getFilePointer(); // Position } //=== Section 2 : the pipeline itself tmp = readLongString(raf); long startFilterConfigs = raf.getFilePointer(); // Read the pipeline and instantiate the steps PipelineStorage store = new PipelineStorage(availableSteps, (CharSequence)tmp); IPipeline pipeline = store.read(); byte[] buffer = new byte[MAXBUFFERSIZE]; // Go through each step of the pipeline for ( IPipelineStep step : pipeline.getSteps() ) { // Get the parameters for that step IParameters params = step.getParameters(); if ( params == null ) continue; // Get all methods for the parameters object Method[] methods = params.getClass().getMethods(); // Look for references id = 0; for ( Method m : methods ) { if ( Modifier.isPublic(m.getModifiers() ) && m.isAnnotationPresent(ReferenceParameter.class)) { // Update the references to point to the new location // Read the reference content pos = refMap.get(++id); raf.seek(pos); String filename = raf.readUTF(); long size = raf.readLong(); // Read the size // Save the data to a file if ( !Util.isEmpty(filename) ) { String path = outputDir + File.separator + filename; FileOutputStream fos = new FileOutputStream(path); int toRead = (int)Math.min(size, MAXBUFFERSIZE); int bytesRead = raf.read(buffer, 0, toRead); while ( bytesRead > 0 ) { fos.write(buffer, 0, bytesRead); size -= bytesRead; if ( size <= 0 ) break; toRead = (int)Math.min(size, MAXBUFFERSIZE); bytesRead = raf.read(buffer, 0, toRead); } fos.close(); // Update the reference in the parameters to point to the saved file // Test changing the value String setMethodName = "set"+m.getName().substring(3); Method setMethod = params.getClass().getMethod(setMethodName, String.class); setMethod.invoke(params, path); } } } } // Write out the pipeline file String path = outputDir + File.separator + "pipeline.pln"; pw = new PrintWriter(path, "UTF-8"); store.write(pipeline); pw.write(store.getStringOutput()); pw.close(); //=== Section 3 : the filter configurations raf.seek(startFilterConfigs); // Get the number of filter configurations int count = raf.readInt(); // Read each one for ( int i=0; i<count; i++ ) { String configId = raf.readUTF(); String data = raf.readUTF(); // And create the parameters file path = outputDir + File.separator + configId + ".fprm"; pw = new PrintWriter(path, "UTF-8"); pw.write(data); pw.close(); } //=== Section 4: the extensions -> filter configuration id mapping // Get the number of mappings path = outputDir + File.separator + "extensions-mapping.txt"; pw = new PrintWriter(path, "UTF-8"); String lb = System.getProperty("line.separator"); count = raf.readInt(); for ( int i=0; i<count; i++ ) { String ext = raf.readUTF(); String configId = raf.readUTF(); pw.write(ext + "\t" + configId + lb); } pw.close(); } catch ( Throwable e ) { throw new OkapiIOException("Error when installing the batch configuration.\n"+e.getMessage(), e); } finally { if ( pw != null ) { pw.close(); } if ( raf != null ) { try { raf.close(); } catch ( IOException e ) { throw new OkapiIOException(e); } } } }
diff --git a/AE-go_GameServer/data/scripts/system/handlers/quest/ascension/_1006Ascension.java b/AE-go_GameServer/data/scripts/system/handlers/quest/ascension/_1006Ascension.java index 0de72929..4d779c4c 100644 --- a/AE-go_GameServer/data/scripts/system/handlers/quest/ascension/_1006Ascension.java +++ b/AE-go_GameServer/data/scripts/system/handlers/quest/ascension/_1006Ascension.java @@ -1,411 +1,406 @@ /* * This file is part of aion-unique <aion-unique.org>. * * aion-unique 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 * (at your option) any later version. * * aion-unique 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 aion-unique. If not, see <http://www.gnu.org/licenses/>. */ package quest.ascension; import java.util.ArrayList; import java.util.List; import com.aionemu.gameserver.ai.events.Event; import com.aionemu.gameserver.dataholders.SpawnsData; import com.aionemu.gameserver.model.PlayerClass; import com.aionemu.gameserver.model.gameobjects.Item; import com.aionemu.gameserver.model.gameobjects.Monster; import com.aionemu.gameserver.model.gameobjects.Npc; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.model.gameobjects.stats.StatEnum; import com.aionemu.gameserver.network.aion.serverpackets.SM_DIALOG_WINDOW; import com.aionemu.gameserver.network.aion.serverpackets.SM_EMOTION; import com.aionemu.gameserver.network.aion.serverpackets.SM_ITEM_USAGE_ANIMATION; import com.aionemu.gameserver.network.aion.serverpackets.SM_PLAY_MOVIE; import com.aionemu.gameserver.questEngine.QuestEngine; import com.aionemu.gameserver.questEngine.handlers.QuestHandler; import com.aionemu.gameserver.questEngine.model.QuestEnv; import com.aionemu.gameserver.questEngine.model.QuestState; import com.aionemu.gameserver.questEngine.model.QuestStatus; import com.aionemu.gameserver.utils.PacketSendUtility; import com.aionemu.gameserver.utils.ThreadPoolManager; import com.aionemu.gameserver.world.World; import com.aionemu.gameserver.world.zone.ZoneManager; import com.aionemu.gameserver.world.zone.ZoneName; import com.google.inject.Inject; /** * @author MrPoke * */ public class _1006Ascension extends QuestHandler { private final static int questId = 1006; private int activePlayerId = 0; private List<Npc> mobs = new ArrayList<Npc>(); private final SpawnsData spawnsData; @Inject public _1006Ascension(SpawnsData spawnsData) { super(questId); this.spawnsData = spawnsData; QuestEngine.getInstance().addQuestLvlUp(questId); QuestEngine.getInstance().setNpcQuestData(790001).addOnTalkEvent(questId); QuestEngine.getInstance().setQuestItemIds(182200007).add(questId); QuestEngine.getInstance().setNpcQuestData(730008).addOnTalkEvent(questId); QuestEngine.getInstance().setNpcQuestData(205000).addOnTalkEvent(questId); QuestEngine.getInstance().setNpcQuestData(211042).addOnKillEvent(questId); QuestEngine.getInstance().setNpcQuestData(211043).addOnAttackEvent(questId); QuestEngine.getInstance().setQuestMovieEndIds(151).add(questId); } @Override public boolean onKillEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); if(qs == null || qs.getStatus() != QuestStatus.START) return false; int var = qs.getQuestVars().getQuestVarById(0); int targetId = 0; if(env.getVisibleObject() instanceof Npc) targetId = ((Npc) env.getVisibleObject()).getNpcId(); if(targetId == 211042) { if(var >= 51 && var <= 53) { qs.getQuestVars().setQuestVar(qs.getQuestVars().getQuestVars() + 1); updateQuestStatus(player, qs); if(mobs.contains((Monster)env.getVisibleObject())) mobs.remove((Monster)env.getVisibleObject()); return true; } else if(var == 54) { qs.getQuestVars().setQuestVar(4); updateQuestStatus(player, qs); Monster mob = (Monster) QuestEngine.getInstance().addNewSpawn(310010000, 211043, (float) 226.7, (float) 251.5, (float) 205.5, (byte) 0, false); //TODO: Tempt decrease P attack. mob.getGameStats().setStat(StatEnum.PHYSICAL_ATTACK, mob.getGameStats().getCurrentStat(StatEnum.PHYSICAL_ATTACK)/3 ); mob.getAggroList().addDamageHate(player, 1000, 0); mob.getAi().handleEvent(Event.ATTACKED); mobs.add(mob); return true; } } return false; } @Override public boolean onDialogEvent(QuestEnv env) { final Player player = env.getPlayer(); final QuestState qs = player.getQuestStateList().getQuestState(questId); if(qs == null) return false; int var = qs.getQuestVars().getQuestVars(); int targetId = 0; if(env.getVisibleObject() instanceof Npc) targetId = ((Npc) env.getVisibleObject()).getNpcId(); if(qs.getStatus() == QuestStatus.START) { if(targetId == 790001) { switch(env.getDialogId()) { case 25: if(var == 0) return sendQuestDialog(player, env.getVisibleObject().getObjectId(), 1011); else if(var == 3) return sendQuestDialog(player, env.getVisibleObject().getObjectId(), 1693); else if(var == 5) return sendQuestDialog(player, env.getVisibleObject().getObjectId(), 2034); case 10000: if(var == 0) { if(player.getInventory().getItemCountByItemId(182200007) == 0) QuestEngine.getInstance().addItem(player, 182200007, 1); qs.getQuestVars().setQuestVarById(0, var + 1); updateQuestStatus(player, qs); PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(env.getVisibleObject() .getObjectId(), 10)); return true; } case 10002: if(var == 3) { player.getInventory().removeFromBagByItemId(182200009, 1); qs.getQuestVars().setQuestVar(99); updateQuestStatus(player, qs); PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(env.getVisibleObject() .getObjectId(), 0)); player.getController().teleportTo(310010000, 52, 174, 229, 0); return true; } case 10003: if(var == 5) { PlayerClass playerClass = player.getCommonData().getPlayerClass(); if(playerClass == PlayerClass.WARRIOR) return sendQuestDialog(player, env.getVisibleObject().getObjectId(), 2375); else if(playerClass == PlayerClass.SCOUT) return sendQuestDialog(player, env.getVisibleObject().getObjectId(), 2716); else if(playerClass == PlayerClass.MAGE) return sendQuestDialog(player, env.getVisibleObject().getObjectId(), 3057); else if(playerClass == PlayerClass.PRIEST) return sendQuestDialog(player, env.getVisibleObject().getObjectId(), 3398); } case 10004: if(var == 5) - { - player.getCommonData().setPlayerClass(PlayerClass.GLADIATOR); - player.getCommonData().upgradePlayer(); - qs.setStatus(QuestStatus.REWARD); - updateQuestStatus(player, qs); - } + return setPlayerClass(env, qs, PlayerClass.GLADIATOR); case 10005: if(var == 5) return setPlayerClass(env, qs, PlayerClass.TEMPLAR); case 10006: if(var == 5) return setPlayerClass(env, qs, PlayerClass.ASSASSIN); case 10007: if(var == 5) return setPlayerClass(env, qs, PlayerClass.RANGER); case 10008: if(var == 5) return setPlayerClass(env, qs, PlayerClass.SORCERER); case 10009: if(var == 5) return setPlayerClass(env, qs, PlayerClass.SPIRIT_MASTER); case 10010: if(var == 5) return setPlayerClass(env, qs, PlayerClass.CLERIC); case 10011: if(var == 5) return setPlayerClass(env, qs, PlayerClass.CHANTER); } } else if(targetId == 730008) { switch(env.getDialogId()) { case 25: if(var == 2) { if(player.getInventory().getItemCountByItemId(182200008) != 0) return sendQuestDialog(player, env.getVisibleObject().getObjectId(), 1352); else return sendQuestDialog(player, env.getVisibleObject().getObjectId(), 1354); } case 1353: if(var == 2) { PacketSendUtility.sendPacket(player, new SM_PLAY_MOVIE(0, 14)); player.getInventory().removeFromBagByItemId(182200008, 1); QuestEngine.getInstance().addItem(player, 182200009, 1); } return false; case 10001: if(var == 2) { qs.getQuestVars().setQuestVarById(0, var + 1); updateQuestStatus(player, qs); PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(env.getVisibleObject() .getObjectId(), 10)); return true; } } } else if(targetId == 205000) { switch(env.getDialogId()) { case 25: if(var == 99) { if(activePlayerId != 0 && activePlayerId != player.getObjectId()) { World world = player.getActiveRegion().getWorld(); Player activePlayer = world.findPlayer(activePlayerId); if(!(activePlayer == null || !activePlayer.isOnline() || activePlayer.getWorldId() != 310010000)) return false; } activePlayerId = player.getObjectId(); for(Npc mob : mobs) { mob.getAi().stop(); spawnsData.removeSpawn(mob.getSpawn()); } mobs.clear(); PacketSendUtility.sendPacket(player, new SM_EMOTION(player, 6, 1001, 0)); qs.getQuestVars().setQuestVar(50); updateQuestStatus(player, qs); ThreadPoolManager.getInstance().schedule(new Runnable(){ @Override public void run() { qs.getQuestVars().setQuestVar(51); updateQuestStatus(player, qs); mobs.add((Monster) QuestEngine.getInstance().addNewSpawn(310010000, 211042, (float) 224.073, (float) 239.1, (float) 206.7, (byte) 0, false)); mobs.add((Monster) QuestEngine.getInstance().addNewSpawn(310010000, 211042, (float) 233.5, (float) 241.04, (float) 206.365, (byte) 0, false)); mobs.add((Monster) QuestEngine.getInstance().addNewSpawn(310010000, 211042, (float) 229.6, (float) 265.7, (float) 205.7, (byte) 0, false)); mobs.add((Monster) QuestEngine.getInstance().addNewSpawn(310010000, 211042, (float) 222.8, (float) 262.5, (float) 205.7, (byte) 0, false)); for(Npc mob : mobs) { //TODO: Tempt decrease P attack. mob.getGameStats().setStat(StatEnum.PHYSICAL_ATTACK, mob.getGameStats().getCurrentStat(StatEnum.PHYSICAL_ATTACK)/3 ); ((Monster) mob).getAggroList().addDamageHate(player, 1000, 0); mob.getAi().handleEvent(Event.ATTACKED); } } }, 43000); return true; } return false; default: return false; } } } else if(qs.getStatus() == QuestStatus.REWARD) { if(targetId == 790001) { return defaultQuestEndDialog(env); } } return false; } @Override public boolean onLvlUpEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); if(qs != null) { if(qs.getStatus() != QuestStatus.START) return false; int var = qs.getQuestVars().getQuestVars(); if(var == 4 || (var >= 50 && var <= 55)) { if(activePlayerId == player.getObjectId() && player.getWorldId() == 310010000) return false; else { if(player.getWorldId() == 310010000) { player.getController().teleportTo(210010000, 243.34f, 1639.5f, 100.4f, 0); } qs.getQuestVars().setQuestVar(3); updateQuestStatus(player, qs); } } } if(player.getCommonData().getLevel() < 9) return false; env.setQuestId(questId); QuestEngine.getInstance().getQuest(env).startQuest(QuestStatus.START); return true; } @Override public boolean onAttackEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); if(qs == null || qs.getStatus() != QuestStatus.START || qs.getQuestVars().getQuestVars() != 4) return false; int targetId = 0; if(env.getVisibleObject() instanceof Npc) targetId = ((Npc) env.getVisibleObject()).getNpcId(); if(targetId != 211043) return false; Monster monster = (Monster) env.getVisibleObject(); if(monster.getLifeStats().getCurrentHp() < monster.getLifeStats().getMaxHp() / 2) { PacketSendUtility.sendPacket(player, new SM_PLAY_MOVIE(0, 151)); monster.getAi().stop(); spawnsData.removeSpawn(monster.getSpawn()); } return false; } @Override public boolean onItemUseEvent(QuestEnv env, Item item) { final Player player = env.getPlayer(); final int id = item.getItemTemplate().getItemId(); final int itemObjId = item.getObjectId(); if(id != 182200007) return false; if(!ZoneManager.getInstance().isInsideZone(player, ZoneName.ITEMUSE_Q1006)) return false; final QuestState qs = player.getQuestStateList().getQuestState(questId); if(qs == null) return false; PacketSendUtility.broadcastPacket(player, new SM_ITEM_USAGE_ANIMATION(player.getObjectId(), itemObjId, id, 3000, 0, 0), true); ThreadPoolManager.getInstance().schedule(new Runnable(){ @Override public void run() { PacketSendUtility.broadcastPacket(player, new SM_ITEM_USAGE_ANIMATION(player.getObjectId(), itemObjId, id, 0, 1, 0), true); player.getInventory().removeFromBagByObjectId(itemObjId, 1); QuestEngine.getInstance().addItem(player, 182200008, 1); qs.getQuestVars().setQuestVarById(0, 2); updateQuestStatus(player, qs); } }, 3000); return true; } @Override public boolean onMovieEndEvent(QuestEnv env, int movieId) { if(movieId != 151) return false; Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); if(qs == null || qs.getStatus() != QuestStatus.START || qs.getQuestVars().getQuestVars() != 4) return false; mobs.add((Npc) QuestEngine.getInstance().addNewSpawn(310010000, 790001, (float) 220.6, (float) 247.8, (float) 206.0, (byte) 0, false)); qs.getQuestVars().setQuestVar(5); updateQuestStatus(player, qs); return true; } private boolean setPlayerClass(QuestEnv env, QuestState qs, PlayerClass playerClass) { Player player = env.getPlayer(); player.getCommonData().setPlayerClass(playerClass); player.getCommonData().upgradePlayer(); qs.setStatus(QuestStatus.REWARD); updateQuestStatus(player, qs); sendQuestDialog(player, env.getVisibleObject().getObjectId(), 5); return true; } }
true
true
public boolean onDialogEvent(QuestEnv env) { final Player player = env.getPlayer(); final QuestState qs = player.getQuestStateList().getQuestState(questId); if(qs == null) return false; int var = qs.getQuestVars().getQuestVars(); int targetId = 0; if(env.getVisibleObject() instanceof Npc) targetId = ((Npc) env.getVisibleObject()).getNpcId(); if(qs.getStatus() == QuestStatus.START) { if(targetId == 790001) { switch(env.getDialogId()) { case 25: if(var == 0) return sendQuestDialog(player, env.getVisibleObject().getObjectId(), 1011); else if(var == 3) return sendQuestDialog(player, env.getVisibleObject().getObjectId(), 1693); else if(var == 5) return sendQuestDialog(player, env.getVisibleObject().getObjectId(), 2034); case 10000: if(var == 0) { if(player.getInventory().getItemCountByItemId(182200007) == 0) QuestEngine.getInstance().addItem(player, 182200007, 1); qs.getQuestVars().setQuestVarById(0, var + 1); updateQuestStatus(player, qs); PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(env.getVisibleObject() .getObjectId(), 10)); return true; } case 10002: if(var == 3) { player.getInventory().removeFromBagByItemId(182200009, 1); qs.getQuestVars().setQuestVar(99); updateQuestStatus(player, qs); PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(env.getVisibleObject() .getObjectId(), 0)); player.getController().teleportTo(310010000, 52, 174, 229, 0); return true; } case 10003: if(var == 5) { PlayerClass playerClass = player.getCommonData().getPlayerClass(); if(playerClass == PlayerClass.WARRIOR) return sendQuestDialog(player, env.getVisibleObject().getObjectId(), 2375); else if(playerClass == PlayerClass.SCOUT) return sendQuestDialog(player, env.getVisibleObject().getObjectId(), 2716); else if(playerClass == PlayerClass.MAGE) return sendQuestDialog(player, env.getVisibleObject().getObjectId(), 3057); else if(playerClass == PlayerClass.PRIEST) return sendQuestDialog(player, env.getVisibleObject().getObjectId(), 3398); } case 10004: if(var == 5) { player.getCommonData().setPlayerClass(PlayerClass.GLADIATOR); player.getCommonData().upgradePlayer(); qs.setStatus(QuestStatus.REWARD); updateQuestStatus(player, qs); } case 10005: if(var == 5) return setPlayerClass(env, qs, PlayerClass.TEMPLAR); case 10006: if(var == 5) return setPlayerClass(env, qs, PlayerClass.ASSASSIN); case 10007: if(var == 5) return setPlayerClass(env, qs, PlayerClass.RANGER); case 10008: if(var == 5) return setPlayerClass(env, qs, PlayerClass.SORCERER); case 10009: if(var == 5) return setPlayerClass(env, qs, PlayerClass.SPIRIT_MASTER); case 10010: if(var == 5) return setPlayerClass(env, qs, PlayerClass.CLERIC); case 10011: if(var == 5) return setPlayerClass(env, qs, PlayerClass.CHANTER); } } else if(targetId == 730008) { switch(env.getDialogId()) { case 25: if(var == 2) { if(player.getInventory().getItemCountByItemId(182200008) != 0) return sendQuestDialog(player, env.getVisibleObject().getObjectId(), 1352); else return sendQuestDialog(player, env.getVisibleObject().getObjectId(), 1354); } case 1353: if(var == 2) { PacketSendUtility.sendPacket(player, new SM_PLAY_MOVIE(0, 14)); player.getInventory().removeFromBagByItemId(182200008, 1); QuestEngine.getInstance().addItem(player, 182200009, 1); } return false; case 10001: if(var == 2) { qs.getQuestVars().setQuestVarById(0, var + 1); updateQuestStatus(player, qs); PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(env.getVisibleObject() .getObjectId(), 10)); return true; } } } else if(targetId == 205000) { switch(env.getDialogId()) { case 25: if(var == 99) { if(activePlayerId != 0 && activePlayerId != player.getObjectId()) { World world = player.getActiveRegion().getWorld(); Player activePlayer = world.findPlayer(activePlayerId); if(!(activePlayer == null || !activePlayer.isOnline() || activePlayer.getWorldId() != 310010000)) return false; } activePlayerId = player.getObjectId(); for(Npc mob : mobs) { mob.getAi().stop(); spawnsData.removeSpawn(mob.getSpawn()); } mobs.clear(); PacketSendUtility.sendPacket(player, new SM_EMOTION(player, 6, 1001, 0)); qs.getQuestVars().setQuestVar(50); updateQuestStatus(player, qs); ThreadPoolManager.getInstance().schedule(new Runnable(){ @Override public void run() { qs.getQuestVars().setQuestVar(51); updateQuestStatus(player, qs); mobs.add((Monster) QuestEngine.getInstance().addNewSpawn(310010000, 211042, (float) 224.073, (float) 239.1, (float) 206.7, (byte) 0, false)); mobs.add((Monster) QuestEngine.getInstance().addNewSpawn(310010000, 211042, (float) 233.5, (float) 241.04, (float) 206.365, (byte) 0, false)); mobs.add((Monster) QuestEngine.getInstance().addNewSpawn(310010000, 211042, (float) 229.6, (float) 265.7, (float) 205.7, (byte) 0, false)); mobs.add((Monster) QuestEngine.getInstance().addNewSpawn(310010000, 211042, (float) 222.8, (float) 262.5, (float) 205.7, (byte) 0, false)); for(Npc mob : mobs) { //TODO: Tempt decrease P attack. mob.getGameStats().setStat(StatEnum.PHYSICAL_ATTACK, mob.getGameStats().getCurrentStat(StatEnum.PHYSICAL_ATTACK)/3 ); ((Monster) mob).getAggroList().addDamageHate(player, 1000, 0); mob.getAi().handleEvent(Event.ATTACKED); } } }, 43000); return true; } return false; default: return false; } } } else if(qs.getStatus() == QuestStatus.REWARD) { if(targetId == 790001) { return defaultQuestEndDialog(env); } } return false; }
public boolean onDialogEvent(QuestEnv env) { final Player player = env.getPlayer(); final QuestState qs = player.getQuestStateList().getQuestState(questId); if(qs == null) return false; int var = qs.getQuestVars().getQuestVars(); int targetId = 0; if(env.getVisibleObject() instanceof Npc) targetId = ((Npc) env.getVisibleObject()).getNpcId(); if(qs.getStatus() == QuestStatus.START) { if(targetId == 790001) { switch(env.getDialogId()) { case 25: if(var == 0) return sendQuestDialog(player, env.getVisibleObject().getObjectId(), 1011); else if(var == 3) return sendQuestDialog(player, env.getVisibleObject().getObjectId(), 1693); else if(var == 5) return sendQuestDialog(player, env.getVisibleObject().getObjectId(), 2034); case 10000: if(var == 0) { if(player.getInventory().getItemCountByItemId(182200007) == 0) QuestEngine.getInstance().addItem(player, 182200007, 1); qs.getQuestVars().setQuestVarById(0, var + 1); updateQuestStatus(player, qs); PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(env.getVisibleObject() .getObjectId(), 10)); return true; } case 10002: if(var == 3) { player.getInventory().removeFromBagByItemId(182200009, 1); qs.getQuestVars().setQuestVar(99); updateQuestStatus(player, qs); PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(env.getVisibleObject() .getObjectId(), 0)); player.getController().teleportTo(310010000, 52, 174, 229, 0); return true; } case 10003: if(var == 5) { PlayerClass playerClass = player.getCommonData().getPlayerClass(); if(playerClass == PlayerClass.WARRIOR) return sendQuestDialog(player, env.getVisibleObject().getObjectId(), 2375); else if(playerClass == PlayerClass.SCOUT) return sendQuestDialog(player, env.getVisibleObject().getObjectId(), 2716); else if(playerClass == PlayerClass.MAGE) return sendQuestDialog(player, env.getVisibleObject().getObjectId(), 3057); else if(playerClass == PlayerClass.PRIEST) return sendQuestDialog(player, env.getVisibleObject().getObjectId(), 3398); } case 10004: if(var == 5) return setPlayerClass(env, qs, PlayerClass.GLADIATOR); case 10005: if(var == 5) return setPlayerClass(env, qs, PlayerClass.TEMPLAR); case 10006: if(var == 5) return setPlayerClass(env, qs, PlayerClass.ASSASSIN); case 10007: if(var == 5) return setPlayerClass(env, qs, PlayerClass.RANGER); case 10008: if(var == 5) return setPlayerClass(env, qs, PlayerClass.SORCERER); case 10009: if(var == 5) return setPlayerClass(env, qs, PlayerClass.SPIRIT_MASTER); case 10010: if(var == 5) return setPlayerClass(env, qs, PlayerClass.CLERIC); case 10011: if(var == 5) return setPlayerClass(env, qs, PlayerClass.CHANTER); } } else if(targetId == 730008) { switch(env.getDialogId()) { case 25: if(var == 2) { if(player.getInventory().getItemCountByItemId(182200008) != 0) return sendQuestDialog(player, env.getVisibleObject().getObjectId(), 1352); else return sendQuestDialog(player, env.getVisibleObject().getObjectId(), 1354); } case 1353: if(var == 2) { PacketSendUtility.sendPacket(player, new SM_PLAY_MOVIE(0, 14)); player.getInventory().removeFromBagByItemId(182200008, 1); QuestEngine.getInstance().addItem(player, 182200009, 1); } return false; case 10001: if(var == 2) { qs.getQuestVars().setQuestVarById(0, var + 1); updateQuestStatus(player, qs); PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(env.getVisibleObject() .getObjectId(), 10)); return true; } } } else if(targetId == 205000) { switch(env.getDialogId()) { case 25: if(var == 99) { if(activePlayerId != 0 && activePlayerId != player.getObjectId()) { World world = player.getActiveRegion().getWorld(); Player activePlayer = world.findPlayer(activePlayerId); if(!(activePlayer == null || !activePlayer.isOnline() || activePlayer.getWorldId() != 310010000)) return false; } activePlayerId = player.getObjectId(); for(Npc mob : mobs) { mob.getAi().stop(); spawnsData.removeSpawn(mob.getSpawn()); } mobs.clear(); PacketSendUtility.sendPacket(player, new SM_EMOTION(player, 6, 1001, 0)); qs.getQuestVars().setQuestVar(50); updateQuestStatus(player, qs); ThreadPoolManager.getInstance().schedule(new Runnable(){ @Override public void run() { qs.getQuestVars().setQuestVar(51); updateQuestStatus(player, qs); mobs.add((Monster) QuestEngine.getInstance().addNewSpawn(310010000, 211042, (float) 224.073, (float) 239.1, (float) 206.7, (byte) 0, false)); mobs.add((Monster) QuestEngine.getInstance().addNewSpawn(310010000, 211042, (float) 233.5, (float) 241.04, (float) 206.365, (byte) 0, false)); mobs.add((Monster) QuestEngine.getInstance().addNewSpawn(310010000, 211042, (float) 229.6, (float) 265.7, (float) 205.7, (byte) 0, false)); mobs.add((Monster) QuestEngine.getInstance().addNewSpawn(310010000, 211042, (float) 222.8, (float) 262.5, (float) 205.7, (byte) 0, false)); for(Npc mob : mobs) { //TODO: Tempt decrease P attack. mob.getGameStats().setStat(StatEnum.PHYSICAL_ATTACK, mob.getGameStats().getCurrentStat(StatEnum.PHYSICAL_ATTACK)/3 ); ((Monster) mob).getAggroList().addDamageHate(player, 1000, 0); mob.getAi().handleEvent(Event.ATTACKED); } } }, 43000); return true; } return false; default: return false; } } } else if(qs.getStatus() == QuestStatus.REWARD) { if(targetId == 790001) { return defaultQuestEndDialog(env); } } return false; }
diff --git a/src/main/java/org/jason/mapmaker/server/service/FeatureServiceImpl.java b/src/main/java/org/jason/mapmaker/server/service/FeatureServiceImpl.java index 3c76b91..3402fba 100644 --- a/src/main/java/org/jason/mapmaker/server/service/FeatureServiceImpl.java +++ b/src/main/java/org/jason/mapmaker/server/service/FeatureServiceImpl.java @@ -1,279 +1,279 @@ /** * Copyright 2011 Jason Ferguson. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.jason.mapmaker.server.service; import com.vividsolutions.jts.geom.*; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.math.NumberUtils; import org.geotools.factory.CommonFactoryFinder; import org.geotools.geometry.jts.JTSFactoryFinder; import org.jason.mapmaker.server.repository.FeatureRepository; import org.jason.mapmaker.server.util.ZipUtil; import org.jason.mapmaker.shared.exceptions.RepositoryException; import org.jason.mapmaker.shared.exceptions.ServiceException; import org.jason.mapmaker.shared.model.BorderPoint; import org.jason.mapmaker.shared.model.Feature; import org.jason.mapmaker.shared.model.FeaturesMetadata; import org.jason.mapmaker.shared.model.Location; import org.jason.mapmaker.shared.util.FeatureUtil; import org.jason.mapmaker.shared.util.GeographyUtils; import org.opengis.filter.FilterFactory2; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.apache.commons.lang.StringUtils.split; /** * Implementation of FeaturesService interface * * @since 0.3 * @author Jason Ferguson */ @Service("featureService") public class FeatureServiceImpl implements FeatureService { private static Logger log = LoggerFactory.getLogger(FeatureServiceImpl.class); private FeaturesMetadataService featuresMetadataService; private FeatureRepository featureRepository; @Autowired public void setFeaturesMetadataService(FeaturesMetadataService featuresMetadataService) { this.featuresMetadataService = featuresMetadataService; } @Autowired public void setFeatureRepository(FeatureRepository featureRepository) { this.featureRepository = featureRepository; } @Override public void persist(Feature object) throws ServiceException { try { featureRepository.save(object); } catch (Exception e) { log.debug("persist() threw RepositoryException: ", e); throw new ServiceException(e); } } @Override public void remove(Feature object) throws ServiceException { try { featureRepository.delete(object); } catch (Exception e) { log.debug("remove() threw RepositoryException: ", e); throw new ServiceException(e); } } @Override public void saveList(List<Feature> featureList) throws ServiceException { try { featureRepository.saveList(featureList); } catch (Exception ex) { log.debug("saveList() threw ServiceException", ex); throw new ServiceException(ex); } } @Override public List<String> getFeatureClasses() { return featureRepository.getFeatureClasses(); } @Override public List<Feature> getFeatures(Location location, String featureClassName) { // get everything of the given feature class within the general bounding box of the location List<Feature> initialList = featureRepository.getFeaturesByBoxAndFeatureClassName(location.getBoundingBox(), featureClassName); // create a polygon of the border points int numBorderPoints = location.getBorderPointList().size(); Coordinate[] coordinates = new Coordinate[numBorderPoints + 1]; for (int i = 0; i < numBorderPoints; i++) { BorderPoint bp = location.getBorderPointList().get(i); coordinates[i] = new Coordinate(bp.getLng(), bp.getLat()); } // close the polygon coordinates[numBorderPoints] = coordinates[0]; GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null); // create the linear ring of the outer border. However, the outer border is the only border, so pass null // for the second argument of createPolygon() LinearRing lr = geometryFactory.createLinearRing(coordinates); Polygon polygon = geometryFactory.createPolygon(lr, null); // check if point is in Polygon, if not throw it out of the feature list List<Feature> filteredList = new ArrayList<Feature>(); for (Feature f : initialList) { // we can only check if a given Geometry is inside a polygon, so create a Point from the coordinates Point point = geometryFactory.createPoint(new Coordinate(f.getLng(), f.getLat())); if (polygon.contains(point)) { filteredList.add(f); } } return filteredList; } @Override public Map<String, Long> getFeatureCounts() { return featureRepository.getFeatureCounts(); } public void deleteByFeaturesMetadata(FeaturesMetadata fm) throws ServiceException { String validatedGeoId = StringUtils.left(fm.getStateGeoId(), 2); try { featureRepository.deleteByStateGeoId(validatedGeoId); } catch (RepositoryException e) { throw new ServiceException(e); } fm.setCurrentStatus(GeographyUtils.Status.NOT_IMPORTED); featuresMetadataService.update(fm); } @Override public void importFromFeaturesMetadata(FeaturesMetadata fm) throws ServiceException { String url = generateUrl(fm.getStateGeoId(), fm.getUsgsDate()); importFromUrl(url, fm); fm.setCurrentStatus(GeographyUtils.Status.IMPORTED); featuresMetadataService.update(fm); } @Override public String generateUrl(String geoId, String dateUpdated) { String abbreviation = GeographyUtils.getAbbreviationForState(GeographyUtils.getStateForGeoId(geoId)); String result = "http://geonames.usgs.gov/docs/stategaz/" + abbreviation + "_Features_" + dateUpdated + ".zip"; return result; } @Override public void importFromUrl(String url, FeaturesMetadata fm) throws ServiceException { - URL u = null; + URL u; try { u = new URL(url); } catch (MalformedURLException ex) { log.debug("Exception thrown:", ex.getMessage()); throw new ServiceException(ex); } List<File> fileList; try { fileList = ZipUtil.decompress(u); } catch (Exception e) { log.debug("Exception thrown:", e.getMessage()); throw new ServiceException(e); } if (fileList == null || fileList.size() == 0) { log.debug("File list is null or zero!"); throw new ServiceException("File List contains no files!"); } File file = fileList.get(0); // get the txt file handler try { BufferedReader reader = new BufferedReader(new FileReader(file)); reader.readLine(); // ignore header line String line = reader.readLine(); List<Feature> featureList = new ArrayList<Feature>(); // arraylist may not be the best choice since I don't know how many features I'm importing int counter = 1; while (line != null) { String[] splitLine = split(line, "|"); // static import of StringUtils because I don't like regex's if (!NumberUtils.isNumber(splitLine[0]) || !NumberUtils.isNumber(splitLine[9]) || !NumberUtils.isNumber(splitLine[10])) { System.out.println("Feature ID#" + splitLine[0] + " fails isNumeric() test. Skipping."); line = reader.readLine(); continue; // "silently" die } // only import the manmade features if (FeatureUtil.isManmadeFeature(splitLine[2])) { // setting this to variables and using the non-default Feature constructor means this is // easier to debug. Yay. int id = Integer.parseInt(splitLine[0]); String featureName = StringUtils.left(splitLine[1], 99); String featureClass = StringUtils.left(splitLine[2], 99); double lat = Double.parseDouble(splitLine[9]); double lng = Double.parseDouble(splitLine[10]); Feature feature = new Feature(id, featureName, featureClass, lat, lng, fm); feature.setFeatureSource("usgs"); featureList.add(feature); counter++; } if (counter % 100000 == 0) { System.out.println("Processed " + counter + " items"); try { saveList(featureList); featureList.clear(); } catch (ServiceException e) { log.debug("Exception thrown: ", e.getMessage()); break; } } line = reader.readLine(); } saveList(featureList); reader.close(); } catch (IOException e) { log.debug("Exception thrown:", e); throw new ServiceException(e); } file.delete(); } @Override public void update(Feature obj) { featureRepository.update(obj); } @Override public void deleteAll() { featureRepository.deleteAll(); } }
true
true
public void importFromUrl(String url, FeaturesMetadata fm) throws ServiceException { URL u = null; try { u = new URL(url); } catch (MalformedURLException ex) { log.debug("Exception thrown:", ex.getMessage()); throw new ServiceException(ex); } List<File> fileList; try { fileList = ZipUtil.decompress(u); } catch (Exception e) { log.debug("Exception thrown:", e.getMessage()); throw new ServiceException(e); } if (fileList == null || fileList.size() == 0) { log.debug("File list is null or zero!"); throw new ServiceException("File List contains no files!"); } File file = fileList.get(0); // get the txt file handler try { BufferedReader reader = new BufferedReader(new FileReader(file)); reader.readLine(); // ignore header line String line = reader.readLine(); List<Feature> featureList = new ArrayList<Feature>(); // arraylist may not be the best choice since I don't know how many features I'm importing int counter = 1; while (line != null) { String[] splitLine = split(line, "|"); // static import of StringUtils because I don't like regex's if (!NumberUtils.isNumber(splitLine[0]) || !NumberUtils.isNumber(splitLine[9]) || !NumberUtils.isNumber(splitLine[10])) { System.out.println("Feature ID#" + splitLine[0] + " fails isNumeric() test. Skipping."); line = reader.readLine(); continue; // "silently" die } // only import the manmade features if (FeatureUtil.isManmadeFeature(splitLine[2])) { // setting this to variables and using the non-default Feature constructor means this is // easier to debug. Yay. int id = Integer.parseInt(splitLine[0]); String featureName = StringUtils.left(splitLine[1], 99); String featureClass = StringUtils.left(splitLine[2], 99); double lat = Double.parseDouble(splitLine[9]); double lng = Double.parseDouble(splitLine[10]); Feature feature = new Feature(id, featureName, featureClass, lat, lng, fm); feature.setFeatureSource("usgs"); featureList.add(feature); counter++; } if (counter % 100000 == 0) { System.out.println("Processed " + counter + " items"); try { saveList(featureList); featureList.clear(); } catch (ServiceException e) { log.debug("Exception thrown: ", e.getMessage()); break; } } line = reader.readLine(); } saveList(featureList); reader.close(); } catch (IOException e) { log.debug("Exception thrown:", e); throw new ServiceException(e); } file.delete(); }
public void importFromUrl(String url, FeaturesMetadata fm) throws ServiceException { URL u; try { u = new URL(url); } catch (MalformedURLException ex) { log.debug("Exception thrown:", ex.getMessage()); throw new ServiceException(ex); } List<File> fileList; try { fileList = ZipUtil.decompress(u); } catch (Exception e) { log.debug("Exception thrown:", e.getMessage()); throw new ServiceException(e); } if (fileList == null || fileList.size() == 0) { log.debug("File list is null or zero!"); throw new ServiceException("File List contains no files!"); } File file = fileList.get(0); // get the txt file handler try { BufferedReader reader = new BufferedReader(new FileReader(file)); reader.readLine(); // ignore header line String line = reader.readLine(); List<Feature> featureList = new ArrayList<Feature>(); // arraylist may not be the best choice since I don't know how many features I'm importing int counter = 1; while (line != null) { String[] splitLine = split(line, "|"); // static import of StringUtils because I don't like regex's if (!NumberUtils.isNumber(splitLine[0]) || !NumberUtils.isNumber(splitLine[9]) || !NumberUtils.isNumber(splitLine[10])) { System.out.println("Feature ID#" + splitLine[0] + " fails isNumeric() test. Skipping."); line = reader.readLine(); continue; // "silently" die } // only import the manmade features if (FeatureUtil.isManmadeFeature(splitLine[2])) { // setting this to variables and using the non-default Feature constructor means this is // easier to debug. Yay. int id = Integer.parseInt(splitLine[0]); String featureName = StringUtils.left(splitLine[1], 99); String featureClass = StringUtils.left(splitLine[2], 99); double lat = Double.parseDouble(splitLine[9]); double lng = Double.parseDouble(splitLine[10]); Feature feature = new Feature(id, featureName, featureClass, lat, lng, fm); feature.setFeatureSource("usgs"); featureList.add(feature); counter++; } if (counter % 100000 == 0) { System.out.println("Processed " + counter + " items"); try { saveList(featureList); featureList.clear(); } catch (ServiceException e) { log.debug("Exception thrown: ", e.getMessage()); break; } } line = reader.readLine(); } saveList(featureList); reader.close(); } catch (IOException e) { log.debug("Exception thrown:", e); throw new ServiceException(e); } file.delete(); }
diff --git a/com/mewin/WGRegionEffects/Util.java b/com/mewin/WGRegionEffects/Util.java index cb22ebb..a8fa1ee 100644 --- a/com/mewin/WGRegionEffects/Util.java +++ b/com/mewin/WGRegionEffects/Util.java @@ -1,114 +1,114 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.mewin.WGRegionEffects; import com.mewin.WGRegionEffects.flags.PotionEffectDesc; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; import com.sk89q.worldguard.protection.managers.RegionManager; import com.sk89q.worldguard.protection.regions.ProtectedRegion; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.bukkit.Location; import org.bukkit.potion.PotionEffectType; /** * * @author mewin<[email protected]> */ public class Util { public static List<PotionEffectDesc> getEffectsForLocation(WorldGuardPlugin wgp, Location loc) { Map<PotionEffectType, Entry<ProtectedRegion, PotionEffectDesc>> allEffects = new HashMap<PotionEffectType, Entry<ProtectedRegion, PotionEffectDesc>>(); Map<PotionEffectType, List<ProtectedRegion>> ignoredRegions = new HashMap<PotionEffectType, List<ProtectedRegion>>(); RegionManager rm = wgp.getRegionManager(loc.getWorld()); if (rm == null) { return new ArrayList<PotionEffectDesc>(); } for (ProtectedRegion region : rm.getApplicableRegions(loc)) { Set<PotionEffectDesc> regionEffects = (Set<PotionEffectDesc>) region.getFlag(WGRegionEffectsPlugin.EFFECT_FLAG); if (regionEffects == null) { continue; } for (PotionEffectDesc effect : regionEffects) { ProtectedRegion parent = region.getParent(); List<ProtectedRegion> iRegions; if (ignoredRegions.containsKey(effect.getType())) { iRegions = ignoredRegions.get(effect.getType()); } else { iRegions = new ArrayList<ProtectedRegion>(); } if (iRegions.contains(region)) { continue; } while (parent != null) { iRegions.add(parent); parent = parent.getParent(); } ignoredRegions.put(effect.getType(), iRegions); if (!allEffects.containsKey(effect.getType()) || iRegions.contains(allEffects.get(effect.getType()).getKey()) || allEffects.get(effect.getType()).getKey().getPriority() < region.getPriority() || (allEffects.get(effect.getType()).getKey().getPriority() == region.getPriority() && Math.abs(allEffects.get(effect.getType()).getValue().getAmplifier() + 1) < Math.abs(effect.getAmplifier() + 1))) { allEffects.put(effect.getType(), new SimpleEntry<ProtectedRegion, PotionEffectDesc>(region, effect)); } } } ArrayList<PotionEffectDesc> effects = new ArrayList<PotionEffectDesc>(); ProtectedRegion global = rm.getRegion("__global__"); if (global != null) { Set<PotionEffectDesc> gEffects = (Set<PotionEffectDesc>) global.getFlag(WGRegionEffectsPlugin.EFFECT_FLAG); if (gEffects != null) { for (PotionEffectDesc effect : gEffects) { if (!allEffects.containsKey(effect.getType())) { allEffects.put(effect.getType(), new SimpleEntry<ProtectedRegion, PotionEffectDesc>(global, effect)); } } } + } - for (Entry<ProtectedRegion, PotionEffectDesc> entry : allEffects.values()) - { - effects.add(entry.getValue()); - } + for (Entry<ProtectedRegion, PotionEffectDesc> entry : allEffects.values()) + { + effects.add(entry.getValue()); } return effects; } }
false
true
public static List<PotionEffectDesc> getEffectsForLocation(WorldGuardPlugin wgp, Location loc) { Map<PotionEffectType, Entry<ProtectedRegion, PotionEffectDesc>> allEffects = new HashMap<PotionEffectType, Entry<ProtectedRegion, PotionEffectDesc>>(); Map<PotionEffectType, List<ProtectedRegion>> ignoredRegions = new HashMap<PotionEffectType, List<ProtectedRegion>>(); RegionManager rm = wgp.getRegionManager(loc.getWorld()); if (rm == null) { return new ArrayList<PotionEffectDesc>(); } for (ProtectedRegion region : rm.getApplicableRegions(loc)) { Set<PotionEffectDesc> regionEffects = (Set<PotionEffectDesc>) region.getFlag(WGRegionEffectsPlugin.EFFECT_FLAG); if (regionEffects == null) { continue; } for (PotionEffectDesc effect : regionEffects) { ProtectedRegion parent = region.getParent(); List<ProtectedRegion> iRegions; if (ignoredRegions.containsKey(effect.getType())) { iRegions = ignoredRegions.get(effect.getType()); } else { iRegions = new ArrayList<ProtectedRegion>(); } if (iRegions.contains(region)) { continue; } while (parent != null) { iRegions.add(parent); parent = parent.getParent(); } ignoredRegions.put(effect.getType(), iRegions); if (!allEffects.containsKey(effect.getType()) || iRegions.contains(allEffects.get(effect.getType()).getKey()) || allEffects.get(effect.getType()).getKey().getPriority() < region.getPriority() || (allEffects.get(effect.getType()).getKey().getPriority() == region.getPriority() && Math.abs(allEffects.get(effect.getType()).getValue().getAmplifier() + 1) < Math.abs(effect.getAmplifier() + 1))) { allEffects.put(effect.getType(), new SimpleEntry<ProtectedRegion, PotionEffectDesc>(region, effect)); } } } ArrayList<PotionEffectDesc> effects = new ArrayList<PotionEffectDesc>(); ProtectedRegion global = rm.getRegion("__global__"); if (global != null) { Set<PotionEffectDesc> gEffects = (Set<PotionEffectDesc>) global.getFlag(WGRegionEffectsPlugin.EFFECT_FLAG); if (gEffects != null) { for (PotionEffectDesc effect : gEffects) { if (!allEffects.containsKey(effect.getType())) { allEffects.put(effect.getType(), new SimpleEntry<ProtectedRegion, PotionEffectDesc>(global, effect)); } } } for (Entry<ProtectedRegion, PotionEffectDesc> entry : allEffects.values()) { effects.add(entry.getValue()); } } return effects; }
public static List<PotionEffectDesc> getEffectsForLocation(WorldGuardPlugin wgp, Location loc) { Map<PotionEffectType, Entry<ProtectedRegion, PotionEffectDesc>> allEffects = new HashMap<PotionEffectType, Entry<ProtectedRegion, PotionEffectDesc>>(); Map<PotionEffectType, List<ProtectedRegion>> ignoredRegions = new HashMap<PotionEffectType, List<ProtectedRegion>>(); RegionManager rm = wgp.getRegionManager(loc.getWorld()); if (rm == null) { return new ArrayList<PotionEffectDesc>(); } for (ProtectedRegion region : rm.getApplicableRegions(loc)) { Set<PotionEffectDesc> regionEffects = (Set<PotionEffectDesc>) region.getFlag(WGRegionEffectsPlugin.EFFECT_FLAG); if (regionEffects == null) { continue; } for (PotionEffectDesc effect : regionEffects) { ProtectedRegion parent = region.getParent(); List<ProtectedRegion> iRegions; if (ignoredRegions.containsKey(effect.getType())) { iRegions = ignoredRegions.get(effect.getType()); } else { iRegions = new ArrayList<ProtectedRegion>(); } if (iRegions.contains(region)) { continue; } while (parent != null) { iRegions.add(parent); parent = parent.getParent(); } ignoredRegions.put(effect.getType(), iRegions); if (!allEffects.containsKey(effect.getType()) || iRegions.contains(allEffects.get(effect.getType()).getKey()) || allEffects.get(effect.getType()).getKey().getPriority() < region.getPriority() || (allEffects.get(effect.getType()).getKey().getPriority() == region.getPriority() && Math.abs(allEffects.get(effect.getType()).getValue().getAmplifier() + 1) < Math.abs(effect.getAmplifier() + 1))) { allEffects.put(effect.getType(), new SimpleEntry<ProtectedRegion, PotionEffectDesc>(region, effect)); } } } ArrayList<PotionEffectDesc> effects = new ArrayList<PotionEffectDesc>(); ProtectedRegion global = rm.getRegion("__global__"); if (global != null) { Set<PotionEffectDesc> gEffects = (Set<PotionEffectDesc>) global.getFlag(WGRegionEffectsPlugin.EFFECT_FLAG); if (gEffects != null) { for (PotionEffectDesc effect : gEffects) { if (!allEffects.containsKey(effect.getType())) { allEffects.put(effect.getType(), new SimpleEntry<ProtectedRegion, PotionEffectDesc>(global, effect)); } } } } for (Entry<ProtectedRegion, PotionEffectDesc> entry : allEffects.values()) { effects.add(entry.getValue()); } return effects; }
diff --git a/preflight/src/main/java/org/apache/padaf/preflight/helpers/StreamValidationHelper.java b/preflight/src/main/java/org/apache/padaf/preflight/helpers/StreamValidationHelper.java index d32304ca..de67f798 100644 --- a/preflight/src/main/java/org/apache/padaf/preflight/helpers/StreamValidationHelper.java +++ b/preflight/src/main/java/org/apache/padaf/preflight/helpers/StreamValidationHelper.java @@ -1,368 +1,369 @@ /***************************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ****************************************************************************/ package org.apache.padaf.preflight.helpers; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.IOUtils; import org.apache.padaf.preflight.DocumentHandler; import org.apache.padaf.preflight.ValidationConstants; import org.apache.padaf.preflight.ValidationException; import org.apache.padaf.preflight.ValidationResult; import org.apache.padaf.preflight.ValidatorConfig; import org.apache.padaf.preflight.ValidationResult.ValidationError; import org.apache.padaf.preflight.utils.COSUtils; import org.apache.padaf.preflight.utils.FilterHelper; import org.apache.pdfbox.cos.COSArray; import org.apache.pdfbox.cos.COSBase; import org.apache.pdfbox.cos.COSDocument; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.cos.COSObject; import org.apache.pdfbox.cos.COSStream; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.persistence.util.COSObjectKey; /** * @author eric * */ public class StreamValidationHelper extends AbstractValidationHelper { public StreamValidationHelper(ValidatorConfig cfg) throws ValidationException { super(cfg); } /* * (non-Javadoc) * * @see * net.awl.edoc.pdfa.validation.helpers.AbstractValidationHelper#innerValidate * (net.awl.edoc.pdfa.validation.DocumentHandler) */ @Override public List<ValidationError> innerValidate(DocumentHandler handler) throws ValidationException { List<ValidationError> result = new ArrayList<ValidationError>(0); PDDocument pdfDoc = handler.getDocument(); COSDocument cDoc = pdfDoc.getDocument(); List<?> lCOSObj = cDoc.getObjects(); for (Object o : lCOSObj) { COSObject cObj = (COSObject) o; // If this object represents a Stream, the Dictionary must contain the // Length key COSBase cBase = cObj.getObject(); if (cBase instanceof COSStream) { // it is a stream result.addAll(validateStreamObject(handler, cObj)); } } return result; } public List<ValidationError> validateStreamObject(DocumentHandler handler, COSObject cObj) throws ValidationException { List<ValidationError> result = new ArrayList<ValidationError>(0); COSStream streamObj = (COSStream) cObj.getObject(); // ---- Check dictionary entries // ---- Only the Length entry is mandatory // ---- In a PDF/A file, F, FFilter and FDecodeParms are forbidden checkDictionaryEntries(streamObj, result); // ---- check stream length checkStreamLength(handler, cObj, result); // ---- Check the Filter value(s) checkFilters(streamObj, handler, result); return result; } /** * This method checks if one of declared Filter is LZWdecode. If LZW is found, * the result list is updated with an error code. * * @param stream * @param handler * @param result */ protected void checkFilters(COSStream stream, DocumentHandler handler, List<ValidationError> result) { COSDocument cDoc = handler.getDocument().getDocument(); COSBase bFilter = stream.getItem(COSName .getPDFName(STREAM_DICTIONARY_KEY_FILTER)); if (bFilter != null) { if (COSUtils.isArray(bFilter, cDoc)) { COSArray afName = (COSArray) bFilter; for (int i = 0; i < afName.size(); ++i) { if (!FilterHelper.isAuthorizedFilter(afName.getString(i), result)) { return; } } } else if (bFilter instanceof COSName) { String fName = ((COSName) bFilter).getName(); if (!FilterHelper.isAuthorizedFilter(fName, result)) { return; } } else { // ---- The filter type is invalid result.add(new ValidationError(ERROR_SYNTAX_STREAM_INVALID_FILTER, "Filter should be a Name or an Array")); } } // else Filter entry is optional } private boolean readUntilStream(InputStream ra) throws IOException { boolean search = true; // String stream = ""; boolean maybe = false; int lastChar = -1; do { int c = ra.read(); switch (c) { case 's': // stream = "s"; maybe = true; lastChar = c; break; case 't': // if (maybe && stream.endsWith("s")) { if (maybe && lastChar == 's') { // stream = stream + "t"; lastChar = c; } else { maybe = false; lastChar = -1; } break; case 'r': // if (maybe && stream.endsWith("t")) { if (maybe && lastChar == 't') { // stream = stream + "r"; lastChar = c; } else { maybe = false; lastChar = -1; } break; case 'e': // if (maybe && stream.endsWith("r")) { if (maybe && lastChar == 'r') { lastChar = c; // stream = stream + "e"; } else { maybe = false; } break; case 'a': // if (maybe && stream.endsWith("e")) { if (maybe && lastChar == 'e') { lastChar = c; // stream = stream + "a"; } else { maybe = false; } break; case 'm': // if (maybe && stream.endsWith("a")) { if (maybe && lastChar == 'a') { return true; } else { maybe = false; } break; case -1: search = false; break; default: maybe = false; break; } } while (search); return false; } protected void checkStreamLength(DocumentHandler handler, COSObject cObj, List<ValidationError> result) throws ValidationException { COSStream streamObj = (COSStream) cObj.getObject(); int length = streamObj.getInt(COSName .getPDFName(STREAM_DICTIONARY_KEY_LENGHT)); InputStream ra = null; try { ra = handler.getSource().getInputStream(); Integer offset = (Integer) handler.getDocument().getDocument() .getXrefTable().get(new COSObjectKey(cObj)); // ---- go to the beginning of the object long skipped = 0; if (offset != null) { while (skipped != offset) { long curSkip = ra.skip(offset - skipped); if (curSkip < 0) { throw new ValidationException( "Unable to skip bytes in the PDFFile to check stream length"); } skipped += curSkip; } // ---- go to the stream key word if (readUntilStream(ra)) { int c = ra.read(); if (c == '\r') { ra.read(); } // else c is '\n' no more character to read // ---- Here is the true beginning of the Stream Content. // ---- Read the given length of bytes and check the 10 next bytes // ---- to see if there are endstream. byte[] buffer = new byte[1024]; int nbBytesToRead = length; do { int cr = 0; if (nbBytesToRead > 1024) { cr = ra.read(buffer, 0, 1024); } else { cr = ra.read(buffer, 0, nbBytesToRead); } if (cr == -1) { result.add(new ValidationResult.ValidationError( ValidationConstants.ERROR_SYNTAX_STREAM_LENGTH_INVALID, "Stream length is invalide")); return; } else { nbBytesToRead = nbBytesToRead - cr; } } while (nbBytesToRead > 0); int len = "endstream".length() + 2; byte[] buffer2 = new byte[len]; for (int i = 0; i < len; ++i) { buffer2[i] = (byte) ra.read(); } // ---- check the content of 10 last characters String endStream = new String(buffer2); if (buffer2[0] == '\r' && buffer2[1] == '\n') { if (!endStream.contains("endstream")) { result.add(new ValidationResult.ValidationError( ValidationConstants.ERROR_SYNTAX_STREAM_LENGTH_INVALID, "Stream length is invalide")); } } else if (buffer2[0] == '\r' && buffer2[1] == 'e') { if (!endStream.contains("endstream")) { result.add(new ValidationResult.ValidationError( ValidationConstants.ERROR_SYNTAX_STREAM_LENGTH_INVALID, "Stream length is invalide")); } } else if (buffer2[0] == '\n' && buffer2[1] == 'e') { if (!endStream.contains("endstream")) { result.add(new ValidationResult.ValidationError( ValidationConstants.ERROR_SYNTAX_STREAM_LENGTH_INVALID, "Stream length is invalide")); } } else { result.add(new ValidationResult.ValidationError( ValidationConstants.ERROR_SYNTAX_STREAM_LENGTH_INVALID, "Stream length is invalide")); } } else { result.add(new ValidationResult.ValidationError( ValidationConstants.ERROR_SYNTAX_STREAM_LENGTH_INVALID, "Stream length is invalide")); } } else { /* * * Offset is null. The stream isn't used, check is useless. * + * TODO : Is it the truth? */ } } catch (IOException e) { throw new ValidationException( "Unable to read a stream to validate it due to : " + e.getMessage(), e); } finally { if ( ra != null) { IOUtils.closeQuietly(ra); } } } /** * Check dictionary entries. Only the Length entry is mandatory. In a PDF/A * file, F, FFilter and FDecodeParms are forbidden * * @param streamObj * @param result */ protected void checkDictionaryEntries(COSStream streamObj, List<ValidationError> result) { boolean len = false; boolean f = false; boolean ffilter = false; boolean fdecParams = false; for (Object key : streamObj.keyList()) { if (!(key instanceof COSName)) { result.add(new ValidationResult.ValidationError( ValidationConstants.ERROR_SYNTAX_DICTIONARY_KEY_INVALID, "Invalid key in The Stream dictionary")); return; } COSName cosName = (COSName) key; if (cosName.getName().equals(STREAM_DICTIONARY_KEY_LENGHT)) { len = true; } if (cosName.getName().equals(STREAM_DICTIONARY_KEY_F)) { f = true; } if (cosName.getName().equals(STREAM_DICTIONARY_KEY_FFILTER)) { ffilter = true; } if (cosName.getName().equals(STREAM_DICTIONARY_KEY_FDECODEPARAMS)) { fdecParams = true; } } if (!len) { result.add(new ValidationResult.ValidationError( ValidationConstants.ERROR_SYNTAX_STREAM_LENGTH_MISSING, "Stream length is missing")); } if (f || ffilter || fdecParams) { result .add(new ValidationResult.ValidationError( ValidationConstants.ERROR_SYNTAX_STREAM_FX_KEYS, "F, FFilter or FDecodeParms keys are present in the stream dictionary")); } } }
true
true
protected void checkStreamLength(DocumentHandler handler, COSObject cObj, List<ValidationError> result) throws ValidationException { COSStream streamObj = (COSStream) cObj.getObject(); int length = streamObj.getInt(COSName .getPDFName(STREAM_DICTIONARY_KEY_LENGHT)); InputStream ra = null; try { ra = handler.getSource().getInputStream(); Integer offset = (Integer) handler.getDocument().getDocument() .getXrefTable().get(new COSObjectKey(cObj)); // ---- go to the beginning of the object long skipped = 0; if (offset != null) { while (skipped != offset) { long curSkip = ra.skip(offset - skipped); if (curSkip < 0) { throw new ValidationException( "Unable to skip bytes in the PDFFile to check stream length"); } skipped += curSkip; } // ---- go to the stream key word if (readUntilStream(ra)) { int c = ra.read(); if (c == '\r') { ra.read(); } // else c is '\n' no more character to read // ---- Here is the true beginning of the Stream Content. // ---- Read the given length of bytes and check the 10 next bytes // ---- to see if there are endstream. byte[] buffer = new byte[1024]; int nbBytesToRead = length; do { int cr = 0; if (nbBytesToRead > 1024) { cr = ra.read(buffer, 0, 1024); } else { cr = ra.read(buffer, 0, nbBytesToRead); } if (cr == -1) { result.add(new ValidationResult.ValidationError( ValidationConstants.ERROR_SYNTAX_STREAM_LENGTH_INVALID, "Stream length is invalide")); return; } else { nbBytesToRead = nbBytesToRead - cr; } } while (nbBytesToRead > 0); int len = "endstream".length() + 2; byte[] buffer2 = new byte[len]; for (int i = 0; i < len; ++i) { buffer2[i] = (byte) ra.read(); } // ---- check the content of 10 last characters String endStream = new String(buffer2); if (buffer2[0] == '\r' && buffer2[1] == '\n') { if (!endStream.contains("endstream")) { result.add(new ValidationResult.ValidationError( ValidationConstants.ERROR_SYNTAX_STREAM_LENGTH_INVALID, "Stream length is invalide")); } } else if (buffer2[0] == '\r' && buffer2[1] == 'e') { if (!endStream.contains("endstream")) { result.add(new ValidationResult.ValidationError( ValidationConstants.ERROR_SYNTAX_STREAM_LENGTH_INVALID, "Stream length is invalide")); } } else if (buffer2[0] == '\n' && buffer2[1] == 'e') { if (!endStream.contains("endstream")) { result.add(new ValidationResult.ValidationError( ValidationConstants.ERROR_SYNTAX_STREAM_LENGTH_INVALID, "Stream length is invalide")); } } else { result.add(new ValidationResult.ValidationError( ValidationConstants.ERROR_SYNTAX_STREAM_LENGTH_INVALID, "Stream length is invalide")); } } else { result.add(new ValidationResult.ValidationError( ValidationConstants.ERROR_SYNTAX_STREAM_LENGTH_INVALID, "Stream length is invalide")); } } else { /* * * Offset is null. The stream isn't used, check is useless. * */ } } catch (IOException e) { throw new ValidationException( "Unable to read a stream to validate it due to : " + e.getMessage(), e); } finally { if ( ra != null) { IOUtils.closeQuietly(ra); } } }
protected void checkStreamLength(DocumentHandler handler, COSObject cObj, List<ValidationError> result) throws ValidationException { COSStream streamObj = (COSStream) cObj.getObject(); int length = streamObj.getInt(COSName .getPDFName(STREAM_DICTIONARY_KEY_LENGHT)); InputStream ra = null; try { ra = handler.getSource().getInputStream(); Integer offset = (Integer) handler.getDocument().getDocument() .getXrefTable().get(new COSObjectKey(cObj)); // ---- go to the beginning of the object long skipped = 0; if (offset != null) { while (skipped != offset) { long curSkip = ra.skip(offset - skipped); if (curSkip < 0) { throw new ValidationException( "Unable to skip bytes in the PDFFile to check stream length"); } skipped += curSkip; } // ---- go to the stream key word if (readUntilStream(ra)) { int c = ra.read(); if (c == '\r') { ra.read(); } // else c is '\n' no more character to read // ---- Here is the true beginning of the Stream Content. // ---- Read the given length of bytes and check the 10 next bytes // ---- to see if there are endstream. byte[] buffer = new byte[1024]; int nbBytesToRead = length; do { int cr = 0; if (nbBytesToRead > 1024) { cr = ra.read(buffer, 0, 1024); } else { cr = ra.read(buffer, 0, nbBytesToRead); } if (cr == -1) { result.add(new ValidationResult.ValidationError( ValidationConstants.ERROR_SYNTAX_STREAM_LENGTH_INVALID, "Stream length is invalide")); return; } else { nbBytesToRead = nbBytesToRead - cr; } } while (nbBytesToRead > 0); int len = "endstream".length() + 2; byte[] buffer2 = new byte[len]; for (int i = 0; i < len; ++i) { buffer2[i] = (byte) ra.read(); } // ---- check the content of 10 last characters String endStream = new String(buffer2); if (buffer2[0] == '\r' && buffer2[1] == '\n') { if (!endStream.contains("endstream")) { result.add(new ValidationResult.ValidationError( ValidationConstants.ERROR_SYNTAX_STREAM_LENGTH_INVALID, "Stream length is invalide")); } } else if (buffer2[0] == '\r' && buffer2[1] == 'e') { if (!endStream.contains("endstream")) { result.add(new ValidationResult.ValidationError( ValidationConstants.ERROR_SYNTAX_STREAM_LENGTH_INVALID, "Stream length is invalide")); } } else if (buffer2[0] == '\n' && buffer2[1] == 'e') { if (!endStream.contains("endstream")) { result.add(new ValidationResult.ValidationError( ValidationConstants.ERROR_SYNTAX_STREAM_LENGTH_INVALID, "Stream length is invalide")); } } else { result.add(new ValidationResult.ValidationError( ValidationConstants.ERROR_SYNTAX_STREAM_LENGTH_INVALID, "Stream length is invalide")); } } else { result.add(new ValidationResult.ValidationError( ValidationConstants.ERROR_SYNTAX_STREAM_LENGTH_INVALID, "Stream length is invalide")); } } else { /* * * Offset is null. The stream isn't used, check is useless. * * TODO : Is it the truth? */ } } catch (IOException e) { throw new ValidationException( "Unable to read a stream to validate it due to : " + e.getMessage(), e); } finally { if ( ra != null) { IOUtils.closeQuietly(ra); } } }
diff --git a/src/smartpool/web/form/CreateCarpoolFormValidator.java b/src/smartpool/web/form/CreateCarpoolFormValidator.java index e8a532f..f6a4e5a 100644 --- a/src/smartpool/web/form/CreateCarpoolFormValidator.java +++ b/src/smartpool/web/form/CreateCarpoolFormValidator.java @@ -1,55 +1,55 @@ package smartpool.web.form; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import smartpool.common.Constants; public class CreateCarpoolFormValidator implements Validator { public CreateCarpoolFormValidator() { } @Override public boolean supports(Class<?> clazz) { return JoinRequestForm.class.equals(clazz); } @Override public void validate(Object target, Errors errors) { CreateCarpoolForm form = (CreateCarpoolForm) target; - if(form.from == null || form.from.equals("")) errors.rejectValue("from", Constants.FIELD_REQUIRED); - if(form.to == null || form.to.equals("")) errors.rejectValue("to", Constants.FIELD_REQUIRED); + if(form.from == null || form.from.trim().isEmpty() || form.from.equals("")) errors.rejectValue("from", Constants.FIELD_REQUIRED); + if(form.to == null || form.to.trim().isEmpty() || form.to.equals("")) errors.rejectValue("to", Constants.FIELD_REQUIRED); if(form.cabType == null || form.cabType.equals("")) errors.rejectValue("cabType", Constants.FIELD_REQUIRED); if(form.pickupPoint == null || form.pickupPoint.equals("")) errors.rejectValue("pickupPoint", Constants.FIELD_REQUIRED); if(form.pickupTime == null || form.pickupTime.equals("")) errors.rejectValue("pickupTime", Constants.FIELD_REQUIRED); else checkForInvalidTime(errors, form.pickupTime, "pickupTime"); if(form.officeArrivalTime == null || form.officeArrivalTime.equals("")) errors.rejectValue("officeArrivalTime", Constants.FIELD_REQUIRED); else checkForInvalidTime(errors, form.officeArrivalTime, "officeArrivalTime"); if(form.officeDepartureTime == null || form.officeDepartureTime.equals("")) errors.rejectValue("officeDepartureTime", Constants.FIELD_REQUIRED); else checkForInvalidTime(errors,form.officeDepartureTime,"officeDepartureTime"); try{ if(form.proposedStartDate == null || form.proposedStartDate.equals("")) errors.rejectValue("proposedStartDate", Constants.FIELD_REQUIRED); else if(form.proposedStartDate != null) Constants.DATE_FORMATTER.parseLocalDate(form.proposedStartDate); }catch (IllegalArgumentException e){ errors.rejectValue("proposedStartDate",Constants.FIELD_INVALID); } try{ if(form.capacity != null) Integer.parseInt(form.capacity); }catch (NumberFormatException e){ errors.rejectValue("capacity",Constants.FIELD_INVALID); } } private void checkForInvalidTime(Errors errors, String fieldValue, String fieldName) { try{ if(fieldValue != null) Constants.TIME_FORMATTER.parseLocalTime(fieldValue); }catch (IllegalArgumentException e){ errors.rejectValue(fieldName,Constants.FIELD_INVALID); } } }
true
true
public void validate(Object target, Errors errors) { CreateCarpoolForm form = (CreateCarpoolForm) target; if(form.from == null || form.from.equals("")) errors.rejectValue("from", Constants.FIELD_REQUIRED); if(form.to == null || form.to.equals("")) errors.rejectValue("to", Constants.FIELD_REQUIRED); if(form.cabType == null || form.cabType.equals("")) errors.rejectValue("cabType", Constants.FIELD_REQUIRED); if(form.pickupPoint == null || form.pickupPoint.equals("")) errors.rejectValue("pickupPoint", Constants.FIELD_REQUIRED); if(form.pickupTime == null || form.pickupTime.equals("")) errors.rejectValue("pickupTime", Constants.FIELD_REQUIRED); else checkForInvalidTime(errors, form.pickupTime, "pickupTime"); if(form.officeArrivalTime == null || form.officeArrivalTime.equals("")) errors.rejectValue("officeArrivalTime", Constants.FIELD_REQUIRED); else checkForInvalidTime(errors, form.officeArrivalTime, "officeArrivalTime"); if(form.officeDepartureTime == null || form.officeDepartureTime.equals("")) errors.rejectValue("officeDepartureTime", Constants.FIELD_REQUIRED); else checkForInvalidTime(errors,form.officeDepartureTime,"officeDepartureTime"); try{ if(form.proposedStartDate == null || form.proposedStartDate.equals("")) errors.rejectValue("proposedStartDate", Constants.FIELD_REQUIRED); else if(form.proposedStartDate != null) Constants.DATE_FORMATTER.parseLocalDate(form.proposedStartDate); }catch (IllegalArgumentException e){ errors.rejectValue("proposedStartDate",Constants.FIELD_INVALID); } try{ if(form.capacity != null) Integer.parseInt(form.capacity); }catch (NumberFormatException e){ errors.rejectValue("capacity",Constants.FIELD_INVALID); } }
public void validate(Object target, Errors errors) { CreateCarpoolForm form = (CreateCarpoolForm) target; if(form.from == null || form.from.trim().isEmpty() || form.from.equals("")) errors.rejectValue("from", Constants.FIELD_REQUIRED); if(form.to == null || form.to.trim().isEmpty() || form.to.equals("")) errors.rejectValue("to", Constants.FIELD_REQUIRED); if(form.cabType == null || form.cabType.equals("")) errors.rejectValue("cabType", Constants.FIELD_REQUIRED); if(form.pickupPoint == null || form.pickupPoint.equals("")) errors.rejectValue("pickupPoint", Constants.FIELD_REQUIRED); if(form.pickupTime == null || form.pickupTime.equals("")) errors.rejectValue("pickupTime", Constants.FIELD_REQUIRED); else checkForInvalidTime(errors, form.pickupTime, "pickupTime"); if(form.officeArrivalTime == null || form.officeArrivalTime.equals("")) errors.rejectValue("officeArrivalTime", Constants.FIELD_REQUIRED); else checkForInvalidTime(errors, form.officeArrivalTime, "officeArrivalTime"); if(form.officeDepartureTime == null || form.officeDepartureTime.equals("")) errors.rejectValue("officeDepartureTime", Constants.FIELD_REQUIRED); else checkForInvalidTime(errors,form.officeDepartureTime,"officeDepartureTime"); try{ if(form.proposedStartDate == null || form.proposedStartDate.equals("")) errors.rejectValue("proposedStartDate", Constants.FIELD_REQUIRED); else if(form.proposedStartDate != null) Constants.DATE_FORMATTER.parseLocalDate(form.proposedStartDate); }catch (IllegalArgumentException e){ errors.rejectValue("proposedStartDate",Constants.FIELD_INVALID); } try{ if(form.capacity != null) Integer.parseInt(form.capacity); }catch (NumberFormatException e){ errors.rejectValue("capacity",Constants.FIELD_INVALID); } }
diff --git a/src/main/java/net/epsilony/tb/analysis/DifferentiableFunctionUtils.java b/src/main/java/net/epsilony/tb/analysis/DifferentiableFunctionUtils.java index 5c7566f..6790b1a 100644 --- a/src/main/java/net/epsilony/tb/analysis/DifferentiableFunctionUtils.java +++ b/src/main/java/net/epsilony/tb/analysis/DifferentiableFunctionUtils.java @@ -1,119 +1,119 @@ /* (c) Copyright by Man YUAN */ package net.epsilony.tb.analysis; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; /** * * @author <a href="mailto:[email protected]">Man YUAN</a> */ public class DifferentiableFunctionUtils { public static DifferentiableFunction max( Collection<? extends DifferentiableFunction> functions) { return new Max(new ArrayList<>(functions)); } public static DifferentiableFunction min( Collection<? extends DifferentiableFunction> functions) { return new Min(new ArrayList<>(functions)); } public static class Max extends AbstractMinMax { public Max(List<DifferentiableFunction> functions) { super(functions); } @Override public double[] value(double[] input, double[] output) { if (null == output) { output = new double[1]; } double max = Double.NEGATIVE_INFINITY; for (DifferentiableFunction func : functions) { func.value(input, output); if (output[0] > max) { max = output[0]; } } output[0] = max; return output; } } public static class Min extends AbstractMinMax { public Min(List<DifferentiableFunction> functions) { super(functions); } @Override public double[] value(double[] input, double[] output) { if (null == output) { output = new double[1]; } double min = Double.POSITIVE_INFINITY; for (DifferentiableFunction func : functions) { func.value(input, output); if (output[0] < min) { min = output[0]; } } output[0] = min; return output; } } private static abstract class AbstractMinMax implements DifferentiableFunction { public AbstractMinMax(List<DifferentiableFunction> functions) { this.functions = functions; if (null == functions || functions.isEmpty()) { throw new IllegalArgumentException(); } Iterator<DifferentiableFunction> it = functions.iterator(); DifferentiableFunction first = it.next(); inputDimension = first.getInputDimension(); outputDimension = first.getOutputDimension(); while (it.hasNext()) { DifferentiableFunction func = it.next(); - if (inputDimension != func.getInputDimension() || outputDimension != func.getInputDimension()) { + if (inputDimension != func.getInputDimension() || outputDimension != func.getOutputDimension()) { throw new IllegalArgumentException(); } } } protected List<DifferentiableFunction> functions; protected int inputDimension; protected int outputDimension; @Override public int getDiffOrder() { return 0; } @Override public int getInputDimension() { return inputDimension; } @Override public int getOutputDimension() { return outputDimension; } @Override public void setDiffOrder(int diffOrder) { if (diffOrder != 0) { throw new IllegalArgumentException("only support 0, not " + diffOrder); } } @Override public abstract double[] value(double[] input, double[] output); } }
true
true
public AbstractMinMax(List<DifferentiableFunction> functions) { this.functions = functions; if (null == functions || functions.isEmpty()) { throw new IllegalArgumentException(); } Iterator<DifferentiableFunction> it = functions.iterator(); DifferentiableFunction first = it.next(); inputDimension = first.getInputDimension(); outputDimension = first.getOutputDimension(); while (it.hasNext()) { DifferentiableFunction func = it.next(); if (inputDimension != func.getInputDimension() || outputDimension != func.getInputDimension()) { throw new IllegalArgumentException(); } } }
public AbstractMinMax(List<DifferentiableFunction> functions) { this.functions = functions; if (null == functions || functions.isEmpty()) { throw new IllegalArgumentException(); } Iterator<DifferentiableFunction> it = functions.iterator(); DifferentiableFunction first = it.next(); inputDimension = first.getInputDimension(); outputDimension = first.getOutputDimension(); while (it.hasNext()) { DifferentiableFunction func = it.next(); if (inputDimension != func.getInputDimension() || outputDimension != func.getOutputDimension()) { throw new IllegalArgumentException(); } } }
diff --git a/src/main/java/ohtu/radioaine/controller/BatchController.java b/src/main/java/ohtu/radioaine/controller/BatchController.java index 04bfff6..2a271ec 100644 --- a/src/main/java/ohtu/radioaine/controller/BatchController.java +++ b/src/main/java/ohtu/radioaine/controller/BatchController.java @@ -1,219 +1,220 @@ /* * Contains following controllers for batch page: * - batch/{id}: fetches batch by id from db, gives it in model to view 'batchView' * - batch: fetches all batches from db, gives them in model to view 'batch' * - addBatch: */ /** * */ package ohtu.radioaine.controller; import javax.validation.Valid; import ohtu.radioaine.domain.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import ohtu.radioaine.service.BatchService; import ohtu.radioaine.service.EventService; import ohtu.radioaine.service.SubstanceService; import ohtu.radioaine.tools.EventHandler; import ohtu.radioaine.tools.EventHandler3; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMethod; import ohtu.radioaine.tools.Time; import org.springframework.web.bind.annotation.*; /** * Controllers for batch creation and viewing * * @author rmjheino */ @Controller public class BatchController { @Autowired private BatchService batchService; @Autowired private SubstanceService substanceService; @Autowired private EventService eventService; @RequestMapping(value = "batch/{id}", method = RequestMethod.GET) public String getBatchById(@PathVariable Integer id, Model model) { model.addAttribute("batch", batchService.read(id)); return "batchView"; } @RequestMapping(value = "doCheck/{id}+{sid}", method = RequestMethod.POST) public String qualityCheck(@PathVariable Integer id, @PathVariable Integer sid, @RequestParam Integer qualityCheck) { Batch temp = batchService.read(id); temp.setQualityCheck(qualityCheck); batchService.createOrUpdate(temp); return "redirect:/substance/"+sid; } @RequestMapping(value = "batch", method = RequestMethod.GET) public String batchList(Model model) { model.addAttribute("batches", batchService.list()); return "batchView"; } @RequestMapping(value = "addBatch", method = RequestMethod.GET) public String addbatchView(Model model) { model.addAttribute("batch", new BatchFormObject()); model.addAttribute("substances", substanceService.list()); return "addBatchView"; } @RequestMapping(value = "batch", method = RequestMethod.POST) public String addBatch(@Valid @ModelAttribute("batch") BatchFormObject bfm, BindingResult result) { if (result.hasErrors()) { return "addBatchView"; } Batch batch = createBatch(bfm); Batch temp = batchService.read(batch.getBatchNumber(), bfm.getSubstance()); if (temp == null) { batch = batchService.createOrUpdate(batch); Event event = EventHandler.newBatchEvent(batch); eventService.createOrUpdate(event); } else { batch = updateBatchSaato(temp.getId(), bfm); } return "redirect:/batch/" + batch.getId(); } //Batchin pΓ€ivittΓ€miseen kesken @RequestMapping(value = "updateBatch/{id}") public String batchUpdateRequest(Model model, @PathVariable Integer id) { model.addAttribute("substances", substanceService.list()); model.addAttribute("batch", batchService.read(id)); return "batchUpdateView"; } //Batchin pΓ€ivittΓ€miseen keskenlog @RequestMapping(value = "updateBatch/{id}", method = RequestMethod.POST) public String batchUpdate(@Valid @ModelAttribute("batch") BatchFormObject bfm, BindingResult result, Model model, @PathVariable Integer id) { if (result.hasErrors()) { return "redirect:/updateBatch/" + id; } updateBatch(id, bfm); return "redirect:/batch/" + id; } private Batch updateBatch(Integer id, BatchFormObject bfo) { int temp = 0; for(int i=0; i < bfo.getStorageLocations().length; i++) { temp += bfo.getStorageLocations()[i][1]; } bfo.setAmount(temp); Batch batch = batchService.read(id); + int oldAmount = batch.getAmount(); batch.setStorageLocations(bfo.getStorageLocations()); batch.setAmount(bfo.getAmount()); batch.setSubstanceVolume(bfo.getSubstanceVolume()); batch.setBatchNumber(bfo.getBatchNumber()); batch.setNote(bfo.getNote()); Substance substance = batch.getSubstance(); if(batch.getSubstance().getId() != bfo.getSubstance()){ Substance newSubstance = (Substance) substanceService.read(bfo.getSubstance()); - substance.setTotalAmount(substance.getTotalAmount() - batch.getAmount()); + substance.setTotalAmount(substance.getTotalAmount() - oldAmount); newSubstance.setTotalAmount(newSubstance.getTotalAmount() + batch.getAmount()); batch.setSubstance(newSubstance); substanceService.createOrUpdate(newSubstance); } else{ int amountChange = amountChange(batch, bfo); substance.setTotalAmount(substance.getTotalAmount() + amountChange); } batch = batchService.createOrUpdate(batch); substanceService.createOrUpdate(substance); // Event3 event = EventHandler3.updateBatchEvent(batch, bfo.getUserName()); // eventService.createOrUpdate(event); Event event = EventHandler.updateBatchEvent(batch); eventService.createOrUpdate(event); return batch; } private int amountChange(Batch batch, BatchFormObject bfm) { int tempAmount; if (batch.getAmount() > bfm.getAmount()) { tempAmount = -(batch.getAmount() - bfm.getAmount()); } else if (batch.getAmount() < bfm.getAmount()) { tempAmount = (bfm.getAmount() - batch.getAmount()); } else { tempAmount = 0; } return tempAmount; } @RequestMapping(value = "batchDelete/{id}", method = RequestMethod.POST) public String deleteBatch(@RequestParam String name, @RequestParam Integer amount, @PathVariable Integer id) { Batch batch = batchService.read(id); Substance substance = batch.getSubstance(); int total = batch.getAmount() - amount; if (total >= 0 && name.length() >= 1) { substance.setTotalAmount(substance.getTotalAmount() - amount); substanceService.createOrUpdate(substance); batch.setAmount(total); batchService.createOrUpdate(batch); } return "redirect:/batch/" + id; } /** * * @param bfo * @return */ private Batch createBatch(BatchFormObject bfo) { Batch batch = new Batch(); batch.setBatchNumber(bfo.getBatchNumber()); batch.setNote(bfo.getNote()); batch.setArrivalDate(Time.parseDate(bfo.getArrivalDate())); batch.setExpDate((Time.parseDate(bfo.getExpDate()))); //Counts and sets the correct amount of the batch from storageLocations int temp = 0; for(int i=0; i < bfo.getStorageLocations().length; i++) temp += bfo.getStorageLocations()[i][1]; bfo.setAmount(temp); batch.setAmount(bfo.getAmount()); batch.setSubstanceVolume(bfo.getSubstanceVolume()); batch.setStorageLocations(bfo.getStorageLocations()); Substance substance = (Substance) substanceService.read(bfo.getSubstance()); substance.setTotalAmount(substance.getTotalAmount() + bfo.getAmount()); substanceService.createOrUpdate(substance); batch.setSubstance(substance); batch.setManufacturer(substance.getManufacturer()); batch.setSupplier(substance.getSupplier()); return batch; } private Batch updateBatchSaato(int id, BatchFormObject bfm) { Batch batch = batchService.read(id); batch.setAmount(batch.getAmount()+bfm.getAmount()); batch.setNote(batch.getNote()+"\n"+bfm.getNote()); Event event = EventHandler.addToBatchEvent(batch); eventService.createOrUpdate(event); return batchService.createOrUpdate(batch); } }
false
true
private Batch updateBatch(Integer id, BatchFormObject bfo) { int temp = 0; for(int i=0; i < bfo.getStorageLocations().length; i++) { temp += bfo.getStorageLocations()[i][1]; } bfo.setAmount(temp); Batch batch = batchService.read(id); batch.setStorageLocations(bfo.getStorageLocations()); batch.setAmount(bfo.getAmount()); batch.setSubstanceVolume(bfo.getSubstanceVolume()); batch.setBatchNumber(bfo.getBatchNumber()); batch.setNote(bfo.getNote()); Substance substance = batch.getSubstance(); if(batch.getSubstance().getId() != bfo.getSubstance()){ Substance newSubstance = (Substance) substanceService.read(bfo.getSubstance()); substance.setTotalAmount(substance.getTotalAmount() - batch.getAmount()); newSubstance.setTotalAmount(newSubstance.getTotalAmount() + batch.getAmount()); batch.setSubstance(newSubstance); substanceService.createOrUpdate(newSubstance); } else{ int amountChange = amountChange(batch, bfo); substance.setTotalAmount(substance.getTotalAmount() + amountChange); } batch = batchService.createOrUpdate(batch); substanceService.createOrUpdate(substance); // Event3 event = EventHandler3.updateBatchEvent(batch, bfo.getUserName()); // eventService.createOrUpdate(event); Event event = EventHandler.updateBatchEvent(batch); eventService.createOrUpdate(event); return batch; }
private Batch updateBatch(Integer id, BatchFormObject bfo) { int temp = 0; for(int i=0; i < bfo.getStorageLocations().length; i++) { temp += bfo.getStorageLocations()[i][1]; } bfo.setAmount(temp); Batch batch = batchService.read(id); int oldAmount = batch.getAmount(); batch.setStorageLocations(bfo.getStorageLocations()); batch.setAmount(bfo.getAmount()); batch.setSubstanceVolume(bfo.getSubstanceVolume()); batch.setBatchNumber(bfo.getBatchNumber()); batch.setNote(bfo.getNote()); Substance substance = batch.getSubstance(); if(batch.getSubstance().getId() != bfo.getSubstance()){ Substance newSubstance = (Substance) substanceService.read(bfo.getSubstance()); substance.setTotalAmount(substance.getTotalAmount() - oldAmount); newSubstance.setTotalAmount(newSubstance.getTotalAmount() + batch.getAmount()); batch.setSubstance(newSubstance); substanceService.createOrUpdate(newSubstance); } else{ int amountChange = amountChange(batch, bfo); substance.setTotalAmount(substance.getTotalAmount() + amountChange); } batch = batchService.createOrUpdate(batch); substanceService.createOrUpdate(substance); // Event3 event = EventHandler3.updateBatchEvent(batch, bfo.getUserName()); // eventService.createOrUpdate(event); Event event = EventHandler.updateBatchEvent(batch); eventService.createOrUpdate(event); return batch; }
diff --git a/src/java/fedora/server/security/AttributeFinderModule.java b/src/java/fedora/server/security/AttributeFinderModule.java index 4468acbe1..0d7e914ef 100755 --- a/src/java/fedora/server/security/AttributeFinderModule.java +++ b/src/java/fedora/server/security/AttributeFinderModule.java @@ -1,357 +1,360 @@ package fedora.server.security; import java.util.Hashtable; import java.util.Iterator; import java.net.URI; import java.net.URISyntaxException; import java.util.HashSet; import java.util.Set; import javax.servlet.ServletContext; import com.sun.xacml.EvaluationCtx; import com.sun.xacml.attr.AttributeValue; import com.sun.xacml.attr.BagAttribute; import com.sun.xacml.attr.IntegerAttribute; import com.sun.xacml.attr.StringAttribute; import com.sun.xacml.attr.DateTimeAttribute; import com.sun.xacml.attr.DateAttribute; import com.sun.xacml.attr.TimeAttribute; import com.sun.xacml.cond.EvaluationResult; import com.sun.xacml.ctx.Status; /** * @author [email protected] */ /*package*/ abstract class AttributeFinderModule extends com.sun.xacml.finder.AttributeFinderModule { private ServletContext servletContext = null; protected void setServletContext(ServletContext servletContext) { if (this.servletContext == null) { this.servletContext = servletContext; } } protected AttributeFinderModule() { URI temp; try { temp = new URI(StringAttribute.identifier); } catch (URISyntaxException e1) { temp = null; // TODO Auto-generated catch block e1.printStackTrace(); } STRING_ATTRIBUTE_URI = temp; } private Boolean instantiatedOk = null; protected final void setInstantiatedOk(boolean value) { log("setInstantiatedOk() " + value); if (instantiatedOk == null) { instantiatedOk = new Boolean(value); } } public boolean isDesignatorSupported() { log("isDesignatorSupported() will return " + iAm() + " " + ((instantiatedOk != null) && instantiatedOk.booleanValue())); return (instantiatedOk != null) && instantiatedOk.booleanValue(); } private final boolean parmsOk( URI attributeType, URI attributeId, int designatorType) { log("in parmsOk " + iAm()); if (! getSupportedDesignatorTypes().contains(new Integer(designatorType))) { log("AttributeFinder:parmsOk" + iAm() + " exit on " + "target not supported"); return false; } if (attributeType == null) { log("AttributeFinder:parmsOk" + iAm() + " exit on " + "null attributeType"); return false; } if (attributeId == null) { log("AttributeFinder:parmsOk" + iAm() + " exit on " + "null attributeId"); return false; } log("AttributeFinder:parmsOk" + iAm() + " looking for " + attributeId.toString()); showRegisteredAttributes(); if (hasAttribute(attributeId.toString())) { if (! (getAttributeType(attributeId.toString()).equals(attributeType.toString()))) { log("AttributeFinder:parmsOk" + iAm() + " exit on " + "attributeType incorrect for attributeId"); return false; } } else { if (! (StringAttribute.identifier).equals(attributeType.toString())) { log("AttributeFinder:parmsOk" + iAm() + " exit on " + "attributeType incorrect for attributeId"); return false; } } log("exiting parmsOk normally " + iAm()); return true; } protected String iAm() { return this.getClass().getName(); } protected final Object getAttributeFromEvaluationResult(EvaluationResult attribute /*URI type, URI id, URI category, EvaluationCtx context*/) { if (attribute.indeterminate()) { log("AttributeFinder:getAttributeFromEvaluationCtx" + iAm() + " exit on " + "couldn't get resource attribute from xacml request " + "indeterminate"); return null; } if ((attribute.getStatus() != null) && ! Status.STATUS_OK.equals(attribute.getStatus())) { log("AttributeFinder:getAttributeFromEvaluationCtx" + iAm() + " exit on " + "couldn't get resource attribute from xacml request " + "bad status"); return null; } // (resourceAttribute.getStatus() == null) == everything is ok AttributeValue attributeValue = attribute.getAttributeValue(); if (! (attributeValue instanceof BagAttribute)) { log("AttributeFinder:getAttributeFromEvaluationCtx" + iAm() + " exit on " + "couldn't get resource attribute from xacml request " + "no bag"); return null; } BagAttribute bag = (BagAttribute) attributeValue; if (1 != bag.size()) { log("AttributeFinder:getAttributeFromEvaluationCtx" + iAm() + " exit on " + "couldn't get resource attribute from xacml request " + "wrong bag n=" + bag.size()); return null; } Iterator it = bag.iterator(); Object element = it.next(); if (element == null) { log("AttributeFinder:getAttributeFromEvaluationCtx" + iAm() + " exit on " + "couldn't get resource attribute from xacml request " + "null returned"); return null; } if (it.hasNext()) { log("AttributeFinder:getAttributeFromEvaluationCtx" + iAm() + " exit on " + "couldn't get resource attribute from xacml request " + "too many returned"); log(element.toString()); while(it.hasNext()) { log((it.next()).toString()); } return null; } log("AttributeFinder:getAttributeFromEvaluationCtx " + iAm() + " returning " + element.toString()); return element; } protected final HashSet attributesDenied = new HashSet(); private final Hashtable attributeIdUris = new Hashtable(); private final Hashtable attributeTypes = new Hashtable(); private final Hashtable attributeTypeUris = new Hashtable(); protected final void registerAttribute(String id, String type) throws URISyntaxException { log("registering attribute " + iAm() + " " + id); attributeIdUris.put(id, new URI(id)); attributeTypeUris.put(id, new URI(type)); attributeTypes.put(id, type); } protected final URI getAttributeIdUri(String id) { return (URI) attributeIdUris.get(id); } protected final boolean hasAttribute(String id) { return attributeIdUris.containsKey(id); } private final void showRegisteredAttributes() { Iterator it = attributeIdUris.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); log("another registered attribute = " + iAm() + " " + key); } } protected final String getAttributeType(String id) { return (String) attributeTypes.get(id); } protected final URI getAttributeTypeUri(String id) { return (URI) attributeTypeUris.get(id); } private static final Set NULLSET = new HashSet(); private final Set supportedDesignatorTypes = new HashSet(); protected final void registerSupportedDesignatorType(int designatorType) { log("registerSupportedDesignatorType() " + iAm()); supportedDesignatorTypes.add(new Integer(designatorType)); } public Set getSupportedDesignatorTypes() { if ((instantiatedOk != null) && instantiatedOk.booleanValue()) { log("getSupportedDesignatorTypes() will return "+ iAm() +" set of elements, n=" + supportedDesignatorTypes.size()); return supportedDesignatorTypes; } log("getSupportedDesignatorTypes() will return " + iAm() + "NULLSET"); return NULLSET; } protected abstract boolean canHandleAdhoc(); private final boolean willService(URI attributeId) { String temp = attributeId.toString(); if (hasAttribute(temp)) { log("willService() " + iAm() + " accept this known serviced attribute " + attributeId.toString()); return true; } if (! canHandleAdhoc()) { log("willService() " + iAm() + " deny any adhoc attribute " + attributeId.toString()); return false; } if (attributesDenied.contains(temp)) { log("willService() " + iAm() + " deny this known adhoc attribute " + attributeId.toString()); return false; } log("willService() " + iAm() + " allow this unknown adhoc attribute " + attributeId.toString()); return true; } public EvaluationResult findAttribute( URI attributeType, URI attributeId, URI issuer, URI category, EvaluationCtx context, int designatorType) { log("AttributeFinder:findAttribute " + iAm()); log("attributeType=[" + attributeType + "], attributeId=[" + attributeId + "]" + iAm()); if (! parmsOk(attributeType, attributeId, designatorType)) { log("AttributeFinder:findAttribute" + " exit on " + "parms not ok" + iAm()); if (attributeType == null) { try { attributeType = new URI(StringAttribute.identifier); } catch (URISyntaxException e) { //we tried } } return new EvaluationResult(BagAttribute.createEmptyBag(attributeType)); } if (! willService(attributeId)) { log("AttributeFinder:willService() " + iAm() + " returns false" + iAm()); return new EvaluationResult(BagAttribute.createEmptyBag(attributeType)); } if (category != null) { log("++++++++++ AttributeFinder:findAttribute " + iAm() + " category=" + category.toString()); } log("++++++++++ AttributeFinder:findAttribute " + iAm() + " designatorType=" + designatorType); log("about to get temp " + iAm()); Object temp = getAttributeLocally(designatorType, attributeId.toASCIIString(), category, context); log(iAm() + " got temp=" + temp); if (temp == null) { log("AttributeFinder:findAttribute" + " exit on " + "attribute value not found" + iAm()); return new EvaluationResult(BagAttribute.createEmptyBag(attributeType)); } Set set = new HashSet(); if (temp instanceof String) { log("AttributeFinder:findAttribute" + " will return a " + "String " + iAm()); if (attributeType.toString().equals(StringAttribute.identifier)) { set.add(new StringAttribute((String)temp)); } else if (attributeType.toString().equals(DateTimeAttribute.identifier)) { DateTimeAttribute tempDateTimeAttribute; try { tempDateTimeAttribute = DateTimeAttribute.getInstance((String)temp); set.add(tempDateTimeAttribute); } catch (Throwable t) { } } else if (attributeType.toString().equals(DateAttribute.identifier)) { DateAttribute tempDateAttribute; try { tempDateAttribute = DateAttribute.getInstance((String)temp); set.add(tempDateAttribute); } catch (Throwable t) { } } else if (attributeType.toString().equals(TimeAttribute.identifier)) { TimeAttribute tempTimeAttribute; try { tempTimeAttribute = TimeAttribute.getInstance((String)temp); set.add(tempTimeAttribute); } catch (Throwable t) { } } else if (attributeType.toString().equals(IntegerAttribute.identifier)) { IntegerAttribute tempIntegerAttribute; try { tempIntegerAttribute = IntegerAttribute.getInstance((String)temp); set.add(tempIntegerAttribute); } catch (Throwable t) { } } //xacml fixup //was set.add(new StringAttribute((String)temp)); } else if (temp instanceof String[]) { log("AttributeFinder:findAttribute" + " will return a " + "String[] " + iAm()); for (int i = 0; i < ((String[])temp).length; i++) { + if (((String[])temp)[i] == null) { + continue; + } if (attributeType.toString().equals(StringAttribute.identifier)) { set.add(new StringAttribute(((String[])temp)[i])); } else if (attributeType.toString().equals(DateTimeAttribute.identifier)) { log("USING AS DATETIME:" + ((String[])temp)[i]); DateTimeAttribute tempDateTimeAttribute; try { tempDateTimeAttribute = DateTimeAttribute.getInstance(((String[])temp)[i]); set.add(tempDateTimeAttribute); } catch (Throwable t) { } } else if (attributeType.toString().equals(DateAttribute.identifier)) { log("USING AS DATE:" + ((String[])temp)[i]); DateAttribute tempDateAttribute; try { tempDateAttribute = DateAttribute.getInstance(((String[])temp)[i]); set.add(tempDateAttribute); } catch (Throwable t) { } } else if (attributeType.toString().equals(TimeAttribute.identifier)) { log("USING AS TIME:" + ((String[])temp)[i]); TimeAttribute tempTimeAttribute; try { tempTimeAttribute = TimeAttribute.getInstance(((String[])temp)[i]); set.add(tempTimeAttribute); } catch (Throwable t) { } } else if (attributeType.toString().equals(IntegerAttribute.identifier)) { log("USING AS INTEGER:" + ((String[])temp)[i]); IntegerAttribute tempIntegerAttribute; try { tempIntegerAttribute = IntegerAttribute.getInstance(((String[])temp)[i]); set.add(tempIntegerAttribute); } catch (Throwable t) { } } //xacml fixup //was set.add(new StringAttribute(((String[])temp)[i])); } } return new EvaluationResult(new BagAttribute(attributeType, set)); } protected final URI STRING_ATTRIBUTE_URI; abstract protected Object getAttributeLocally(int designatorType, String attributeId, URI resourceCategory, EvaluationCtx context); public static boolean log = false; protected final void log(String msg) { if (! log) return; msg = this.getClass().getName() + ": " + msg; if (servletContext != null) { servletContext.log(msg); } else { System.err.println(msg); } } }
true
true
public EvaluationResult findAttribute( URI attributeType, URI attributeId, URI issuer, URI category, EvaluationCtx context, int designatorType) { log("AttributeFinder:findAttribute " + iAm()); log("attributeType=[" + attributeType + "], attributeId=[" + attributeId + "]" + iAm()); if (! parmsOk(attributeType, attributeId, designatorType)) { log("AttributeFinder:findAttribute" + " exit on " + "parms not ok" + iAm()); if (attributeType == null) { try { attributeType = new URI(StringAttribute.identifier); } catch (URISyntaxException e) { //we tried } } return new EvaluationResult(BagAttribute.createEmptyBag(attributeType)); } if (! willService(attributeId)) { log("AttributeFinder:willService() " + iAm() + " returns false" + iAm()); return new EvaluationResult(BagAttribute.createEmptyBag(attributeType)); } if (category != null) { log("++++++++++ AttributeFinder:findAttribute " + iAm() + " category=" + category.toString()); } log("++++++++++ AttributeFinder:findAttribute " + iAm() + " designatorType=" + designatorType); log("about to get temp " + iAm()); Object temp = getAttributeLocally(designatorType, attributeId.toASCIIString(), category, context); log(iAm() + " got temp=" + temp); if (temp == null) { log("AttributeFinder:findAttribute" + " exit on " + "attribute value not found" + iAm()); return new EvaluationResult(BagAttribute.createEmptyBag(attributeType)); } Set set = new HashSet(); if (temp instanceof String) { log("AttributeFinder:findAttribute" + " will return a " + "String " + iAm()); if (attributeType.toString().equals(StringAttribute.identifier)) { set.add(new StringAttribute((String)temp)); } else if (attributeType.toString().equals(DateTimeAttribute.identifier)) { DateTimeAttribute tempDateTimeAttribute; try { tempDateTimeAttribute = DateTimeAttribute.getInstance((String)temp); set.add(tempDateTimeAttribute); } catch (Throwable t) { } } else if (attributeType.toString().equals(DateAttribute.identifier)) { DateAttribute tempDateAttribute; try { tempDateAttribute = DateAttribute.getInstance((String)temp); set.add(tempDateAttribute); } catch (Throwable t) { } } else if (attributeType.toString().equals(TimeAttribute.identifier)) { TimeAttribute tempTimeAttribute; try { tempTimeAttribute = TimeAttribute.getInstance((String)temp); set.add(tempTimeAttribute); } catch (Throwable t) { } } else if (attributeType.toString().equals(IntegerAttribute.identifier)) { IntegerAttribute tempIntegerAttribute; try { tempIntegerAttribute = IntegerAttribute.getInstance((String)temp); set.add(tempIntegerAttribute); } catch (Throwable t) { } } //xacml fixup //was set.add(new StringAttribute((String)temp)); } else if (temp instanceof String[]) { log("AttributeFinder:findAttribute" + " will return a " + "String[] " + iAm()); for (int i = 0; i < ((String[])temp).length; i++) { if (attributeType.toString().equals(StringAttribute.identifier)) { set.add(new StringAttribute(((String[])temp)[i])); } else if (attributeType.toString().equals(DateTimeAttribute.identifier)) { log("USING AS DATETIME:" + ((String[])temp)[i]); DateTimeAttribute tempDateTimeAttribute; try { tempDateTimeAttribute = DateTimeAttribute.getInstance(((String[])temp)[i]); set.add(tempDateTimeAttribute); } catch (Throwable t) { } } else if (attributeType.toString().equals(DateAttribute.identifier)) { log("USING AS DATE:" + ((String[])temp)[i]); DateAttribute tempDateAttribute; try { tempDateAttribute = DateAttribute.getInstance(((String[])temp)[i]); set.add(tempDateAttribute); } catch (Throwable t) { } } else if (attributeType.toString().equals(TimeAttribute.identifier)) { log("USING AS TIME:" + ((String[])temp)[i]); TimeAttribute tempTimeAttribute; try { tempTimeAttribute = TimeAttribute.getInstance(((String[])temp)[i]); set.add(tempTimeAttribute); } catch (Throwable t) { } } else if (attributeType.toString().equals(IntegerAttribute.identifier)) { log("USING AS INTEGER:" + ((String[])temp)[i]); IntegerAttribute tempIntegerAttribute; try { tempIntegerAttribute = IntegerAttribute.getInstance(((String[])temp)[i]); set.add(tempIntegerAttribute); } catch (Throwable t) { } } //xacml fixup //was set.add(new StringAttribute(((String[])temp)[i])); } } return new EvaluationResult(new BagAttribute(attributeType, set)); }
public EvaluationResult findAttribute( URI attributeType, URI attributeId, URI issuer, URI category, EvaluationCtx context, int designatorType) { log("AttributeFinder:findAttribute " + iAm()); log("attributeType=[" + attributeType + "], attributeId=[" + attributeId + "]" + iAm()); if (! parmsOk(attributeType, attributeId, designatorType)) { log("AttributeFinder:findAttribute" + " exit on " + "parms not ok" + iAm()); if (attributeType == null) { try { attributeType = new URI(StringAttribute.identifier); } catch (URISyntaxException e) { //we tried } } return new EvaluationResult(BagAttribute.createEmptyBag(attributeType)); } if (! willService(attributeId)) { log("AttributeFinder:willService() " + iAm() + " returns false" + iAm()); return new EvaluationResult(BagAttribute.createEmptyBag(attributeType)); } if (category != null) { log("++++++++++ AttributeFinder:findAttribute " + iAm() + " category=" + category.toString()); } log("++++++++++ AttributeFinder:findAttribute " + iAm() + " designatorType=" + designatorType); log("about to get temp " + iAm()); Object temp = getAttributeLocally(designatorType, attributeId.toASCIIString(), category, context); log(iAm() + " got temp=" + temp); if (temp == null) { log("AttributeFinder:findAttribute" + " exit on " + "attribute value not found" + iAm()); return new EvaluationResult(BagAttribute.createEmptyBag(attributeType)); } Set set = new HashSet(); if (temp instanceof String) { log("AttributeFinder:findAttribute" + " will return a " + "String " + iAm()); if (attributeType.toString().equals(StringAttribute.identifier)) { set.add(new StringAttribute((String)temp)); } else if (attributeType.toString().equals(DateTimeAttribute.identifier)) { DateTimeAttribute tempDateTimeAttribute; try { tempDateTimeAttribute = DateTimeAttribute.getInstance((String)temp); set.add(tempDateTimeAttribute); } catch (Throwable t) { } } else if (attributeType.toString().equals(DateAttribute.identifier)) { DateAttribute tempDateAttribute; try { tempDateAttribute = DateAttribute.getInstance((String)temp); set.add(tempDateAttribute); } catch (Throwable t) { } } else if (attributeType.toString().equals(TimeAttribute.identifier)) { TimeAttribute tempTimeAttribute; try { tempTimeAttribute = TimeAttribute.getInstance((String)temp); set.add(tempTimeAttribute); } catch (Throwable t) { } } else if (attributeType.toString().equals(IntegerAttribute.identifier)) { IntegerAttribute tempIntegerAttribute; try { tempIntegerAttribute = IntegerAttribute.getInstance((String)temp); set.add(tempIntegerAttribute); } catch (Throwable t) { } } //xacml fixup //was set.add(new StringAttribute((String)temp)); } else if (temp instanceof String[]) { log("AttributeFinder:findAttribute" + " will return a " + "String[] " + iAm()); for (int i = 0; i < ((String[])temp).length; i++) { if (((String[])temp)[i] == null) { continue; } if (attributeType.toString().equals(StringAttribute.identifier)) { set.add(new StringAttribute(((String[])temp)[i])); } else if (attributeType.toString().equals(DateTimeAttribute.identifier)) { log("USING AS DATETIME:" + ((String[])temp)[i]); DateTimeAttribute tempDateTimeAttribute; try { tempDateTimeAttribute = DateTimeAttribute.getInstance(((String[])temp)[i]); set.add(tempDateTimeAttribute); } catch (Throwable t) { } } else if (attributeType.toString().equals(DateAttribute.identifier)) { log("USING AS DATE:" + ((String[])temp)[i]); DateAttribute tempDateAttribute; try { tempDateAttribute = DateAttribute.getInstance(((String[])temp)[i]); set.add(tempDateAttribute); } catch (Throwable t) { } } else if (attributeType.toString().equals(TimeAttribute.identifier)) { log("USING AS TIME:" + ((String[])temp)[i]); TimeAttribute tempTimeAttribute; try { tempTimeAttribute = TimeAttribute.getInstance(((String[])temp)[i]); set.add(tempTimeAttribute); } catch (Throwable t) { } } else if (attributeType.toString().equals(IntegerAttribute.identifier)) { log("USING AS INTEGER:" + ((String[])temp)[i]); IntegerAttribute tempIntegerAttribute; try { tempIntegerAttribute = IntegerAttribute.getInstance(((String[])temp)[i]); set.add(tempIntegerAttribute); } catch (Throwable t) { } } //xacml fixup //was set.add(new StringAttribute(((String[])temp)[i])); } } return new EvaluationResult(new BagAttribute(attributeType, set)); }
diff --git a/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileRandomAccessContent.java b/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileRandomAccessContent.java index 78461e4f..2d51be4d 100644 --- a/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileRandomAccessContent.java +++ b/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileRandomAccessContent.java @@ -1,612 +1,616 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.vfs2.provider.ram; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import org.apache.commons.vfs2.RandomAccessContent; import org.apache.commons.vfs2.util.RandomAccessMode; /** * RAM File Random Access Content. * @author <a href="http://commons.apache.org/vfs/team-list.html">Commons VFS team</a> */ public class RamFileRandomAccessContent implements RandomAccessContent { /** * File Pointer */ protected int filePointer = 0; /** * Buffer */ private byte[] buf; /** * buffer */ private final byte[] buffer8 = new byte[8]; /** * buffer */ private final byte[] buffer4 = new byte[4]; /** * buffer */ private final byte[] buffer2 = new byte[2]; /** * buffer */ private final byte[] buffer1 = new byte[1]; /** * Mode */ private final RandomAccessMode mode; /** * File */ private final RamFileObject file; private final InputStream rafis; /** * @param file The file to access. * @param mode The access mode. */ public RamFileRandomAccessContent(RamFileObject file, RandomAccessMode mode) { super(); this.buf = file.getData().getBuffer(); this.file = file; this.mode = mode; rafis = new InputStream() { @Override public int read() throws IOException { try { return readByte(); } catch (EOFException e) { return -1; } } @Override public long skip(long n) throws IOException { seek(getFilePointer() + n); return n; } @Override public void close() throws IOException { } @Override public int read(byte[] b) throws IOException { return read(b, 0, b.length); } @Override public int read(byte[] b, int off, int len) throws IOException { - int retLen = Math.min(len, getLeftBytes()); - RamFileRandomAccessContent.this.readFully(b, off, retLen); + int retLen = -1; + final int left = getLeftBytes(); + if (left > 0) { + retLen = Math.min(len, left); + RamFileRandomAccessContent.this.readFully(b, off, retLen); + } return retLen; } @Override public int available() throws IOException { return getLeftBytes(); } }; } /* * (non-Javadoc) * * @see org.apache.commons.vfs2.RandomAccessContent#getFilePointer() */ public long getFilePointer() throws IOException { return this.filePointer; } /* * (non-Javadoc) * * @see org.apache.commons.vfs2.RandomAccessContent#seek(long) */ public void seek(long pos) throws IOException { if (pos < 0) { throw new IOException("Attempt to position before the start of the file"); } this.filePointer = (int) pos; } /* * (non-Javadoc) * * @see org.apache.commons.vfs2.RandomAccessContent#length() */ public long length() throws IOException { return buf.length; } /* * (non-Javadoc) * * @see org.apache.commons.vfs2.RandomAccessContent#close() */ public void close() throws IOException { } /* * (non-Javadoc) * * @see java.io.DataInput#readByte() */ public byte readByte() throws IOException { return (byte) this.readUnsignedByte(); } /* * (non-Javadoc) * * @see java.io.DataInput#readChar() */ public char readChar() throws IOException { int ch1 = this.readUnsignedByte(); int ch2 = this.readUnsignedByte(); return (char) ((ch1 << 8) + (ch2 << 0)); } /* * (non-Javadoc) * * @see java.io.DataInput#readDouble() */ public double readDouble() throws IOException { return Double.longBitsToDouble(this.readLong()); } /* * (non-Javadoc) * * @see java.io.DataInput#readFloat() */ public float readFloat() throws IOException { return Float.intBitsToFloat(this.readInt()); } /* * (non-Javadoc) * * @see java.io.DataInput#readInt() */ public int readInt() throws IOException { return (readUnsignedByte() << 24) | (readUnsignedByte() << 16) | (readUnsignedByte() << 8) | readUnsignedByte(); } /* * (non-Javadoc) * * @see java.io.DataInput#readUnsignedByte() */ public int readUnsignedByte() throws IOException { if (filePointer < buf.length) { return buf[filePointer++] & 0xFF; } else { throw new EOFException(); } } /* * (non-Javadoc) * * @see java.io.DataInput#readUnsignedShort() */ public int readUnsignedShort() throws IOException { this.readFully(buffer2); return toUnsignedShort(buffer2); } /* * (non-Javadoc) * * @see java.io.DataInput#readLong() */ public long readLong() throws IOException { this.readFully(buffer8); return toLong(buffer8); } /* * (non-Javadoc) * * @see java.io.DataInput#readShort() */ public short readShort() throws IOException { this.readFully(buffer2); return toShort(buffer2); } /* * (non-Javadoc) * * @see java.io.DataInput#readBoolean() */ public boolean readBoolean() throws IOException { return (this.readUnsignedByte() != 0); } /* * (non-Javadoc) * * @see java.io.DataInput#skipBytes(int) */ public int skipBytes(int n) throws IOException { if (n < 0) { throw new IndexOutOfBoundsException( "The skip number can't be negative"); } long newPos = filePointer + n; if (newPos > buf.length) { throw new IndexOutOfBoundsException("Tyring to skip too much bytes"); } seek(newPos); return n; } /* * (non-Javadoc) * * @see java.io.DataInput#readFully(byte[]) */ public void readFully(byte[] b) throws IOException { this.readFully(b, 0, b.length); } /* * (non-Javadoc) * * @see java.io.DataInput#readFully(byte[], int, int) */ public void readFully(byte[] b, int off, int len) throws IOException { if (len < 0) { throw new IndexOutOfBoundsException("Length is lower than 0"); } if (len > this.getLeftBytes()) { throw new IndexOutOfBoundsException("Read length (" + len + ") is higher than buffer left bytes (" + this.getLeftBytes() + ") "); } System.arraycopy(buf, filePointer, b, off, len); filePointer += len; } private int getLeftBytes() { return buf.length - filePointer; } /* * (non-Javadoc) * * @see java.io.DataInput#readUTF() */ public String readUTF() throws IOException { return DataInputStream.readUTF(this); } /* * (non-Javadoc) * * @see java.io.DataOutput#write(byte[], int, int) */ public void write(byte[] b, int off, int len) throws IOException { if (this.getLeftBytes() < len) { int newSize = this.buf.length + len - this.getLeftBytes(); this.file.resize(newSize); this.buf = this.file.getData().getBuffer(); } System.arraycopy(b, off, this.buf, filePointer, len); this.filePointer += len; } /* * (non-Javadoc) * * @see java.io.DataOutput#write(byte[]) */ public void write(byte[] b) throws IOException { this.write(b, 0, b.length); } /* * (non-Javadoc) * * @see java.io.DataOutput#writeByte(int) */ public void writeByte(int i) throws IOException { this.write(i); } /** * Build a long from first 8 bytes of the array. * * @param b The byte[] to convert. * @return A long. */ public static long toLong(byte[] b) { return ((((long) b[7]) & 0xFF) + ((((long) b[6]) & 0xFF) << 8) + ((((long) b[5]) & 0xFF) << 16) + ((((long) b[4]) & 0xFF) << 24) + ((((long) b[3]) & 0xFF) << 32) + ((((long) b[2]) & 0xFF) << 40) + ((((long) b[1]) & 0xFF) << 48) + ((((long) b[0]) & 0xFF) << 56)); } /** * Build a 8-byte array from a long. No check is performed on the array * length. * * @param n The number to convert. * @param b The array to fill. * @return A byte[]. */ public static byte[] toBytes(long n, byte[] b) { b[7] = (byte) (n); n >>>= 8; b[6] = (byte) (n); n >>>= 8; b[5] = (byte) (n); n >>>= 8; b[4] = (byte) (n); n >>>= 8; b[3] = (byte) (n); n >>>= 8; b[2] = (byte) (n); n >>>= 8; b[1] = (byte) (n); n >>>= 8; b[0] = (byte) (n); return b; } /** * Build a short from first 2 bytes of the array. * @param b The byte[] to convert. * @return A short. */ public static short toShort(byte[] b) { return (short) toUnsignedShort(b); } /** * Build a short from first 2 bytes of the array. * * @param b The byte[] to convert. * @return A short. */ public static int toUnsignedShort(byte[] b) { return ((b[1] & 0xFF) + ((b[0] & 0xFF) << 8)); } /* * (non-Javadoc) * * @see java.io.DataOutput#write(int) */ public void write(int b) throws IOException { buffer1[0] = (byte) b; this.write(buffer1); } /* * (non-Javadoc) * * @see java.io.DataOutput#writeBoolean(boolean) */ public void writeBoolean(boolean v) throws IOException { this.write(v ? 1 : 0); } /* * (non-Javadoc) * * @see java.io.DataOutput#writeBytes(java.lang.String) */ public void writeBytes(String s) throws IOException { write(s.getBytes()); } /* * (non-Javadoc) * * @see java.io.DataOutput#writeChar(int) */ public void writeChar(int v) throws IOException { buffer2[0] = (byte) ((v >>> 8) & 0xFF); buffer2[1] = (byte) ((v >>> 0) & 0xFF); write(buffer2); } /* * (non-Javadoc) * * @see java.io.DataOutput#writeChars(java.lang.String) */ public void writeChars(String s) throws IOException { int len = s.length(); for (int i = 0; i < len; i++) { writeChar(s.charAt(i)); } } /* * (non-Javadoc) * * @see java.io.DataOutput#writeDouble(double) */ public void writeDouble(double v) throws IOException { writeLong(Double.doubleToLongBits(v)); } /* * (non-Javadoc) * * @see java.io.DataOutput#writeFloat(float) */ public void writeFloat(float v) throws IOException { writeInt(Float.floatToIntBits(v)); } /* * (non-Javadoc) * * @see java.io.DataOutput#writeInt(int) */ public void writeInt(int v) throws IOException { buffer4[0] = (byte) ((v >>> 24) & 0xFF); buffer4[1] = (byte) ((v >>> 16) & 0xFF); buffer4[2] = (byte) ((v >>> 8) & 0xFF); buffer4[3] = (byte) (v & 0xFF); write(buffer4); } /* * (non-Javadoc) * * @see java.io.DataOutput#writeLong(long) */ public void writeLong(long v) throws IOException { write(toBytes(v, buffer8)); } /* * (non-Javadoc) * * @see java.io.DataOutput#writeShort(int) */ public void writeShort(int v) throws IOException { buffer2[0] = (byte) ((v >>> 8) & 0xFF); buffer2[1] = (byte) (v & 0xFF); write(buffer2); } /* * (non-Javadoc) * * @see java.io.DataOutput#writeUTF(java.lang.String) */ public void writeUTF(String str) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(str.length()); DataOutputStream dataOut = new DataOutputStream(out); dataOut.writeUTF(str); dataOut.flush(); dataOut.close(); byte[] b = out.toByteArray(); write(b); } /* * (non-Javadoc) * * @see java.io.DataInput#readLine() */ public String readLine() throws IOException { throw new UnsupportedOperationException("deprecated"); } public InputStream getInputStream() throws IOException { return rafis; } }
true
true
public RamFileRandomAccessContent(RamFileObject file, RandomAccessMode mode) { super(); this.buf = file.getData().getBuffer(); this.file = file; this.mode = mode; rafis = new InputStream() { @Override public int read() throws IOException { try { return readByte(); } catch (EOFException e) { return -1; } } @Override public long skip(long n) throws IOException { seek(getFilePointer() + n); return n; } @Override public void close() throws IOException { } @Override public int read(byte[] b) throws IOException { return read(b, 0, b.length); } @Override public int read(byte[] b, int off, int len) throws IOException { int retLen = Math.min(len, getLeftBytes()); RamFileRandomAccessContent.this.readFully(b, off, retLen); return retLen; } @Override public int available() throws IOException { return getLeftBytes(); } }; }
public RamFileRandomAccessContent(RamFileObject file, RandomAccessMode mode) { super(); this.buf = file.getData().getBuffer(); this.file = file; this.mode = mode; rafis = new InputStream() { @Override public int read() throws IOException { try { return readByte(); } catch (EOFException e) { return -1; } } @Override public long skip(long n) throws IOException { seek(getFilePointer() + n); return n; } @Override public void close() throws IOException { } @Override public int read(byte[] b) throws IOException { return read(b, 0, b.length); } @Override public int read(byte[] b, int off, int len) throws IOException { int retLen = -1; final int left = getLeftBytes(); if (left > 0) { retLen = Math.min(len, left); RamFileRandomAccessContent.this.readFully(b, off, retLen); } return retLen; } @Override public int available() throws IOException { return getLeftBytes(); } }; }
diff --git a/src/com/menny/android/anysoftkeyboard/Dictionary/DictionaryFactory.java b/src/com/menny/android/anysoftkeyboard/Dictionary/DictionaryFactory.java index 571061cc..2089fc22 100644 --- a/src/com/menny/android/anysoftkeyboard/Dictionary/DictionaryFactory.java +++ b/src/com/menny/android/anysoftkeyboard/Dictionary/DictionaryFactory.java @@ -1,176 +1,177 @@ package com.menny.android.anysoftkeyboard.Dictionary; import java.util.HashMap; import java.util.Map.Entry; import android.util.Log; import com.menny.android.anysoftkeyboard.AnyKeyboardContextProvider; import com.menny.android.anysoftkeyboard.Dictionary.Dictionary.Language; public class DictionaryFactory { private static UserDictionaryBase msUserDictionary = null; private static final HashMap<Dictionary.Language, Dictionary> msDictionaries; static { msDictionaries = new HashMap<Dictionary.Language, Dictionary>(); } public synchronized static UserDictionaryBase createUserDictionary(AnyKeyboardContextProvider context) { if (msUserDictionary == null) { try { msUserDictionary = new AndroidUserDictionary(context); msUserDictionary.loadDictionary(); } catch(Exception ex) { Log.w("AnySoftKeyboard", "Failed to load 'AndroidUserDictionary' (could be that the platform does not support it). Will use fall-back dictionary. Error:"+ex.getMessage()); try { msUserDictionary = new FallbackUserDictionary(context); msUserDictionary.loadDictionary(); } catch (Exception e) { Log.e("AnySoftKeyboard", "Failed to load failback user dictionary!"); e.printStackTrace(); } } } return msUserDictionary; } public synchronized static Dictionary getDictionary(final Dictionary.Language language, AnyKeyboardContextProvider context) { if (msDictionaries.containsKey(language)) return msDictionaries.get(language); Dictionary dict = null; //showing lengthy operation toast //context.showToastMessage(R.string.toast_lengthy_words_long_operation, false); try { switch(language) { case English: dict = new SQLiteSimpleDictionary(context, "en", "en"); break; case Hebrew: dict = new SQLiteSimpleDictionary(context, "he", "he"); break; case French: dict = new SQLiteSimpleDictionary(context, "fr", "fr"); break; case German: dict = new SQLiteSimpleDictionary(context, "de", "de"); break; case Spanish: dict = new SQLiteSimpleDictionary(context, "es", "es"); break; case Swedish: dict = new SQLiteSimpleDictionary(context, "sv", "sv"); break; case Russian: dict = new SQLiteSimpleDictionary(context, "ru", "ru"); break; case Finnish: dict = new SQLiteSimpleDictionary(context, "fi", "fi"); break; case Dutch: dict = new SQLiteSimpleDictionary(context, "nl", "nl"); break; case Slovene: dict = new SQLiteSimpleDictionary(context, "sl", "sl"); + break; default: return null; } final Dictionary dictToLoad = dict; Thread loader = new Thread() { public void run() { try { dictToLoad.loadDictionary(); } catch (Exception e) { Log.e("AnySoftKeyboard", "Failed load dictionary for "+language+"! Will reset the map. Error:"+e.getMessage()); e.printStackTrace(); removeDictionary(language); } } }; loader.start(); msDictionaries.put(language, dict); } catch(Exception ex) { Log.e("AnySoftKeyboard", "Failed to load main dictionary for: "+language); ex.printStackTrace(); } return dict; } public synchronized static void removeDictionary(Language language) { if (msDictionaries.containsKey(language)) { Dictionary dict = msDictionaries.get(language); dict.close(); msDictionaries.remove(language); } } public synchronized static void close() { if (msUserDictionary != null) msUserDictionary.close(); for(Dictionary dict : msDictionaries.values()) dict.close(); msUserDictionary = null; msDictionaries.clear(); } public static void releaseAllDictionaries() { close(); } public synchronized static void releaseDictionary(Language language) { if (msDictionaries.containsKey(language)) { Dictionary dict = msDictionaries.get(language); dict.close(); msDictionaries.remove(language); } } public synchronized static void onLowMemory(Language currentlyUsedDictionary) { //I'll clear all dictionaries but the required. Dictionary dictToKeep = null; for(Entry<Language, Dictionary> dict : msDictionaries.entrySet()) { if (dict.getKey().equals(currentlyUsedDictionary)) { dictToKeep = dict.getValue(); } else { Log.i("AnySoftKeyboard", "DictionaryFacotry::onLowMemory: Removing "+dict.getKey()); dict.getValue().close(); } } msDictionaries.clear(); if (dictToKeep != null) { msDictionaries.put(currentlyUsedDictionary, dictToKeep); } } }
true
true
public synchronized static Dictionary getDictionary(final Dictionary.Language language, AnyKeyboardContextProvider context) { if (msDictionaries.containsKey(language)) return msDictionaries.get(language); Dictionary dict = null; //showing lengthy operation toast //context.showToastMessage(R.string.toast_lengthy_words_long_operation, false); try { switch(language) { case English: dict = new SQLiteSimpleDictionary(context, "en", "en"); break; case Hebrew: dict = new SQLiteSimpleDictionary(context, "he", "he"); break; case French: dict = new SQLiteSimpleDictionary(context, "fr", "fr"); break; case German: dict = new SQLiteSimpleDictionary(context, "de", "de"); break; case Spanish: dict = new SQLiteSimpleDictionary(context, "es", "es"); break; case Swedish: dict = new SQLiteSimpleDictionary(context, "sv", "sv"); break; case Russian: dict = new SQLiteSimpleDictionary(context, "ru", "ru"); break; case Finnish: dict = new SQLiteSimpleDictionary(context, "fi", "fi"); break; case Dutch: dict = new SQLiteSimpleDictionary(context, "nl", "nl"); break; case Slovene: dict = new SQLiteSimpleDictionary(context, "sl", "sl"); default: return null; } final Dictionary dictToLoad = dict; Thread loader = new Thread() { public void run() { try { dictToLoad.loadDictionary(); } catch (Exception e) { Log.e("AnySoftKeyboard", "Failed load dictionary for "+language+"! Will reset the map. Error:"+e.getMessage()); e.printStackTrace(); removeDictionary(language); } } }; loader.start(); msDictionaries.put(language, dict); } catch(Exception ex) { Log.e("AnySoftKeyboard", "Failed to load main dictionary for: "+language); ex.printStackTrace(); } return dict; }
public synchronized static Dictionary getDictionary(final Dictionary.Language language, AnyKeyboardContextProvider context) { if (msDictionaries.containsKey(language)) return msDictionaries.get(language); Dictionary dict = null; //showing lengthy operation toast //context.showToastMessage(R.string.toast_lengthy_words_long_operation, false); try { switch(language) { case English: dict = new SQLiteSimpleDictionary(context, "en", "en"); break; case Hebrew: dict = new SQLiteSimpleDictionary(context, "he", "he"); break; case French: dict = new SQLiteSimpleDictionary(context, "fr", "fr"); break; case German: dict = new SQLiteSimpleDictionary(context, "de", "de"); break; case Spanish: dict = new SQLiteSimpleDictionary(context, "es", "es"); break; case Swedish: dict = new SQLiteSimpleDictionary(context, "sv", "sv"); break; case Russian: dict = new SQLiteSimpleDictionary(context, "ru", "ru"); break; case Finnish: dict = new SQLiteSimpleDictionary(context, "fi", "fi"); break; case Dutch: dict = new SQLiteSimpleDictionary(context, "nl", "nl"); break; case Slovene: dict = new SQLiteSimpleDictionary(context, "sl", "sl"); break; default: return null; } final Dictionary dictToLoad = dict; Thread loader = new Thread() { public void run() { try { dictToLoad.loadDictionary(); } catch (Exception e) { Log.e("AnySoftKeyboard", "Failed load dictionary for "+language+"! Will reset the map. Error:"+e.getMessage()); e.printStackTrace(); removeDictionary(language); } } }; loader.start(); msDictionaries.put(language, dict); } catch(Exception ex) { Log.e("AnySoftKeyboard", "Failed to load main dictionary for: "+language); ex.printStackTrace(); } return dict; }
diff --git a/src/eu/bryants/anthony/plinth/compiler/passes/llvm/CodeGenerator.java b/src/eu/bryants/anthony/plinth/compiler/passes/llvm/CodeGenerator.java index d7b0fe2..a3d5459 100644 --- a/src/eu/bryants/anthony/plinth/compiler/passes/llvm/CodeGenerator.java +++ b/src/eu/bryants/anthony/plinth/compiler/passes/llvm/CodeGenerator.java @@ -1,2751 +1,2751 @@ package eu.bryants.anthony.plinth.compiler.passes.llvm; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.util.HashMap; import java.util.Map; import java.util.Set; import nativelib.c.C; import nativelib.llvm.LLVM; import nativelib.llvm.LLVM.LLVMBasicBlockRef; import nativelib.llvm.LLVM.LLVMBuilderRef; import nativelib.llvm.LLVM.LLVMModuleRef; import nativelib.llvm.LLVM.LLVMTypeRef; import nativelib.llvm.LLVM.LLVMValueRef; import eu.bryants.anthony.plinth.ast.ClassDefinition; import eu.bryants.anthony.plinth.ast.CompoundDefinition; import eu.bryants.anthony.plinth.ast.TypeDefinition; import eu.bryants.anthony.plinth.ast.expression.ArithmeticExpression; import eu.bryants.anthony.plinth.ast.expression.ArithmeticExpression.ArithmeticOperator; import eu.bryants.anthony.plinth.ast.expression.ArrayAccessExpression; import eu.bryants.anthony.plinth.ast.expression.ArrayCreationExpression; import eu.bryants.anthony.plinth.ast.expression.BitwiseNotExpression; import eu.bryants.anthony.plinth.ast.expression.BooleanLiteralExpression; import eu.bryants.anthony.plinth.ast.expression.BooleanNotExpression; import eu.bryants.anthony.plinth.ast.expression.BracketedExpression; import eu.bryants.anthony.plinth.ast.expression.CastExpression; import eu.bryants.anthony.plinth.ast.expression.ClassCreationExpression; import eu.bryants.anthony.plinth.ast.expression.EqualityExpression; import eu.bryants.anthony.plinth.ast.expression.EqualityExpression.EqualityOperator; import eu.bryants.anthony.plinth.ast.expression.Expression; import eu.bryants.anthony.plinth.ast.expression.FieldAccessExpression; import eu.bryants.anthony.plinth.ast.expression.FloatingLiteralExpression; import eu.bryants.anthony.plinth.ast.expression.FunctionCallExpression; import eu.bryants.anthony.plinth.ast.expression.InlineIfExpression; import eu.bryants.anthony.plinth.ast.expression.IntegerLiteralExpression; import eu.bryants.anthony.plinth.ast.expression.LogicalExpression; import eu.bryants.anthony.plinth.ast.expression.LogicalExpression.LogicalOperator; import eu.bryants.anthony.plinth.ast.expression.MinusExpression; import eu.bryants.anthony.plinth.ast.expression.NullCoalescingExpression; import eu.bryants.anthony.plinth.ast.expression.NullLiteralExpression; import eu.bryants.anthony.plinth.ast.expression.RelationalExpression; import eu.bryants.anthony.plinth.ast.expression.RelationalExpression.RelationalOperator; import eu.bryants.anthony.plinth.ast.expression.ShiftExpression; import eu.bryants.anthony.plinth.ast.expression.StringLiteralExpression; import eu.bryants.anthony.plinth.ast.expression.ThisExpression; import eu.bryants.anthony.plinth.ast.expression.TupleExpression; import eu.bryants.anthony.plinth.ast.expression.TupleIndexExpression; import eu.bryants.anthony.plinth.ast.expression.VariableExpression; import eu.bryants.anthony.plinth.ast.member.ArrayLengthMember; import eu.bryants.anthony.plinth.ast.member.BuiltinMethod; import eu.bryants.anthony.plinth.ast.member.Constructor; import eu.bryants.anthony.plinth.ast.member.Field; import eu.bryants.anthony.plinth.ast.member.Initialiser; import eu.bryants.anthony.plinth.ast.member.Member; import eu.bryants.anthony.plinth.ast.member.Method; import eu.bryants.anthony.plinth.ast.metadata.FieldInitialiser; import eu.bryants.anthony.plinth.ast.metadata.GlobalVariable; import eu.bryants.anthony.plinth.ast.metadata.MemberVariable; import eu.bryants.anthony.plinth.ast.metadata.Variable; import eu.bryants.anthony.plinth.ast.misc.ArrayElementAssignee; import eu.bryants.anthony.plinth.ast.misc.Assignee; import eu.bryants.anthony.plinth.ast.misc.BlankAssignee; import eu.bryants.anthony.plinth.ast.misc.FieldAssignee; import eu.bryants.anthony.plinth.ast.misc.Parameter; import eu.bryants.anthony.plinth.ast.misc.VariableAssignee; import eu.bryants.anthony.plinth.ast.statement.AssignStatement; import eu.bryants.anthony.plinth.ast.statement.Block; import eu.bryants.anthony.plinth.ast.statement.BreakStatement; import eu.bryants.anthony.plinth.ast.statement.BreakableStatement; import eu.bryants.anthony.plinth.ast.statement.ContinueStatement; import eu.bryants.anthony.plinth.ast.statement.DelegateConstructorStatement; import eu.bryants.anthony.plinth.ast.statement.ExpressionStatement; import eu.bryants.anthony.plinth.ast.statement.ForStatement; import eu.bryants.anthony.plinth.ast.statement.IfStatement; import eu.bryants.anthony.plinth.ast.statement.PrefixIncDecStatement; import eu.bryants.anthony.plinth.ast.statement.ReturnStatement; import eu.bryants.anthony.plinth.ast.statement.ShorthandAssignStatement; import eu.bryants.anthony.plinth.ast.statement.ShorthandAssignStatement.ShorthandAssignmentOperator; import eu.bryants.anthony.plinth.ast.statement.Statement; import eu.bryants.anthony.plinth.ast.statement.WhileStatement; import eu.bryants.anthony.plinth.ast.type.ArrayType; import eu.bryants.anthony.plinth.ast.type.FunctionType; import eu.bryants.anthony.plinth.ast.type.NamedType; import eu.bryants.anthony.plinth.ast.type.NullType; import eu.bryants.anthony.plinth.ast.type.PrimitiveType; import eu.bryants.anthony.plinth.ast.type.PrimitiveType.PrimitiveTypeType; import eu.bryants.anthony.plinth.ast.type.TupleType; import eu.bryants.anthony.plinth.ast.type.Type; import eu.bryants.anthony.plinth.ast.type.VoidType; import eu.bryants.anthony.plinth.compiler.passes.Resolver; import eu.bryants.anthony.plinth.compiler.passes.SpecialTypeHandler; import eu.bryants.anthony.plinth.compiler.passes.TypeChecker; /* * Created on 5 Apr 2012 */ /** * @author Anthony Bryant */ public class CodeGenerator { private TypeDefinition typeDefinition; private LLVMModuleRef module; private LLVMBuilderRef builder; private LLVMValueRef callocFunction; private Map<GlobalVariable, LLVMValueRef> globalVariables = new HashMap<GlobalVariable, LLVMValueRef>(); private TypeHelper typeHelper; private BuiltinCodeGenerator builtinGenerator; public CodeGenerator(TypeDefinition typeDefinition) { this.typeDefinition = typeDefinition; } public void generateModule() { if (module != null || builder != null) { throw new IllegalStateException("Cannot generate the module again, it has already been generated by this CodeGenerator"); } module = LLVM.LLVMModuleCreateWithName(typeDefinition.getQualifiedName().toString()); builder = LLVM.LLVMCreateBuilder(); typeHelper = new TypeHelper(builder); builtinGenerator = new BuiltinCodeGenerator(builder, module, this, typeHelper); // add all of the global (static) variables addGlobalVariables(); // add all of the LLVM functions, including initialisers, constructors, and methods addFunctions(); addInitialiserBody(true); // add the static initialisers setGlobalConstructor(getInitialiserFunction(true)); addInitialiserBody(false); // add the non-static initialisers addConstructorBodies(); addMethodBodies(); MetadataGenerator.generateMetadata(typeDefinition, module); } public LLVMModuleRef getModule() { if (module == null) { throw new IllegalStateException("The module has not yet been created; please call generateModule() before getModule()"); } return module; } private void addGlobalVariables() { for (Field field : typeDefinition.getFields()) { if (field.isStatic()) { GlobalVariable globalVariable = field.getGlobalVariable(); LLVMValueRef value = LLVM.LLVMAddGlobal(module, typeHelper.findStandardType(field.getType()), globalVariable.getMangledName()); LLVM.LLVMSetInitializer(value, LLVM.LLVMConstNull(typeHelper.findStandardType(field.getType()))); globalVariables.put(globalVariable, value); } } } private LLVMValueRef getGlobal(GlobalVariable globalVariable) { LLVMValueRef value = globalVariables.get(globalVariable); if (value != null) { return value; } // lazily initialise globals which do not yet exist Type type = globalVariable.getType(); LLVMValueRef newValue = LLVM.LLVMAddGlobal(module, typeHelper.findStandardType(type), globalVariable.getMangledName()); LLVM.LLVMSetInitializer(newValue, LLVM.LLVMConstNull(typeHelper.findStandardType(type))); globalVariables.put(globalVariable, newValue); return newValue; } private void addFunctions() { // add calloc() as an external function LLVMTypeRef callocReturnType = LLVM.LLVMPointerType(LLVM.LLVMInt8Type(), 0); LLVMTypeRef[] callocParamTypes = new LLVMTypeRef[] {LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount())}; callocFunction = LLVM.LLVMAddFunction(module, "calloc", LLVM.LLVMFunctionType(callocReturnType, C.toNativePointerArray(callocParamTypes, false, true), callocParamTypes.length, false)); // create the static and non-static initialiser functions getInitialiserFunction(true); getInitialiserFunction(false); // create the constructor and method functions for (Constructor constructor : typeDefinition.getConstructors()) { getConstructorFunction(constructor); } for (Method method : typeDefinition.getAllMethods()) { getMethodFunction(method); } } /** * Gets the (static or non-static) initialiser function for the TypeDefinition we are building. * @param isStatic - true for the static initialiser, false for the non-static initialiser * @return the function declaration for the specified Initialiser */ private LLVMValueRef getInitialiserFunction(boolean isStatic) { String mangledName = Initialiser.getMangledName(typeDefinition, isStatic); LLVMValueRef existingFunc = LLVM.LLVMGetNamedFunction(module, mangledName); if (existingFunc != null) { return existingFunc; } LLVMTypeRef[] types = null; if (isStatic) { types = new LLVMTypeRef[0]; } else { types = new LLVMTypeRef[1]; types[0] = typeHelper.findTemporaryType(new NamedType(false, false, typeDefinition)); } LLVMTypeRef returnType = LLVM.LLVMVoidType(); LLVMTypeRef functionType = LLVM.LLVMFunctionType(returnType, C.toNativePointerArray(types, false, true), types.length, false); LLVMValueRef llvmFunc = LLVM.LLVMAddFunction(module, mangledName, functionType); LLVM.LLVMSetFunctionCallConv(llvmFunc, LLVM.LLVMCallConv.LLVMCCallConv); if (!isStatic) { LLVM.LLVMSetValueName(LLVM.LLVMGetParam(llvmFunc, 0), "this"); } return llvmFunc; } /** * Gets the function definition for the specified Constructor. If necessary, it is added first. * @param constructor - the Constructor to find the declaration of (or to declare) * @return the function declaration for the specified Constructor */ LLVMValueRef getConstructorFunction(Constructor constructor) { String mangledName = constructor.getMangledName(); LLVMValueRef existingFunc = LLVM.LLVMGetNamedFunction(module, mangledName); if (existingFunc != null) { return existingFunc; } TypeDefinition typeDefinition = constructor.getContainingTypeDefinition(); Parameter[] parameters = constructor.getParameters(); LLVMTypeRef[] types = null; // constructors need an extra 'uninitialised this' parameter at the start, which is the newly allocated data to initialise // the 'this' parameter always has a temporary type representation types = new LLVMTypeRef[1 + parameters.length]; types[0] = typeHelper.findTemporaryType(new NamedType(false, false, typeDefinition)); for (int i = 0; i < parameters.length; i++) { types[1 + i] = typeHelper.findStandardType(parameters[i].getType()); } LLVMTypeRef resultType = LLVM.LLVMVoidType(); LLVMTypeRef functionType = LLVM.LLVMFunctionType(resultType, C.toNativePointerArray(types, false, true), types.length, false); LLVMValueRef llvmFunc = LLVM.LLVMAddFunction(module, mangledName, functionType); LLVM.LLVMSetFunctionCallConv(llvmFunc, LLVM.LLVMCallConv.LLVMCCallConv); LLVM.LLVMSetValueName(LLVM.LLVMGetParam(llvmFunc, 0), "this"); for (int i = 0; i < parameters.length; i++) { LLVMValueRef parameter = LLVM.LLVMGetParam(llvmFunc, 1 + i); LLVM.LLVMSetValueName(parameter, parameters[i].getName()); } return llvmFunc; } /** * Gets the function definition for the specified Method. If necessary, it is added first. * @param method - the Method to find the declaration of (or to declare) * @return the function declaration for the specified Method */ LLVMValueRef getMethodFunction(Method method) { String mangledName = method.getMangledName(); LLVMValueRef existingFunc = LLVM.LLVMGetNamedFunction(module, mangledName); if (existingFunc != null) { return existingFunc; } if (method instanceof BuiltinMethod) { return builtinGenerator.generateMethod((BuiltinMethod) method); } TypeDefinition typeDefinition = method.getContainingTypeDefinition(); Parameter[] parameters = method.getParameters(); LLVMTypeRef[] types = new LLVMTypeRef[1 + parameters.length]; // add the 'this' type to the function - 'this' always has a temporary type representation if (method.isStatic()) { // for static methods, we add an unused opaque*, so that the static method can be easily converted to a function type types[0] = typeHelper.getOpaquePointer(); } else if (typeDefinition instanceof ClassDefinition) { types[0] = typeHelper.findTemporaryType(new NamedType(false, method.isImmutable(), typeDefinition)); } else if (typeDefinition instanceof CompoundDefinition) { types[0] = typeHelper.findTemporaryType(new NamedType(false, method.isImmutable(), typeDefinition)); } for (int i = 0; i < parameters.length; ++i) { types[i + 1] = typeHelper.findStandardType(parameters[i].getType()); } LLVMTypeRef resultType = typeHelper.findStandardType(method.getReturnType()); LLVMTypeRef functionType = LLVM.LLVMFunctionType(resultType, C.toNativePointerArray(types, false, true), types.length, false); LLVMValueRef llvmFunc = LLVM.LLVMAddFunction(module, mangledName, functionType); LLVM.LLVMSetFunctionCallConv(llvmFunc, LLVM.LLVMCallConv.LLVMCCallConv); int paramCount = LLVM.LLVMCountParams(llvmFunc); if (paramCount != types.length) { throw new IllegalStateException("LLVM returned wrong number of parameters"); } LLVM.LLVMSetValueName(LLVM.LLVMGetParam(llvmFunc, 0), method.isStatic() ? "unused" : "this"); for (int i = 0; i < parameters.length; ++i) { LLVMValueRef parameter = LLVM.LLVMGetParam(llvmFunc, i + 1); LLVM.LLVMSetValueName(parameter, parameters[i].getName()); } // add the native function if the programmer specified one // but only if we are in the type definition which defines this Method if (method.getNativeName() != null && method.getContainingTypeDefinition() == this.typeDefinition) { if (method.getBlock() == null) { addNativeDowncallFunction(method, llvmFunc); } else { addNativeUpcallFunction(method, llvmFunc); } } return llvmFunc; } /** * Adds a native function which calls the specified non-native function. * This consists simply of a new function with the method's native name, which calls the non-native function and returns its result. * @param method - the method that this native upcall function is for * @param nonNativeFunction - the non-native function to call */ private void addNativeUpcallFunction(Method method, LLVMValueRef nonNativeFunction) { LLVMTypeRef resultType = typeHelper.findStandardType(method.getReturnType()); Parameter[] parameters = method.getParameters(); // if the method is non-static, add the pointer argument int offset = method.isStatic() ? 0 : 1; LLVMTypeRef[] parameterTypes = new LLVMTypeRef[offset + parameters.length]; if (!method.isStatic()) { if (typeDefinition instanceof ClassDefinition) { parameterTypes[0] = typeHelper.findTemporaryType(new NamedType(false, method.isImmutable(), method.getContainingTypeDefinition())); } else if (typeDefinition instanceof CompoundDefinition) { parameterTypes[0] = typeHelper.findTemporaryType(new NamedType(false, method.isImmutable(), method.getContainingTypeDefinition())); } } for (int i = 0; i < parameters.length; ++i) { parameterTypes[offset + i] = typeHelper.findStandardType(parameters[i].getType()); } LLVMTypeRef functionType = LLVM.LLVMFunctionType(resultType, C.toNativePointerArray(parameterTypes, false, true), parameterTypes.length, false); LLVMValueRef nativeFunction = LLVM.LLVMAddFunction(module, method.getNativeName(), functionType); LLVM.LLVMSetFunctionCallConv(nativeFunction, LLVM.LLVMCallConv.LLVMCCallConv); // if the method is static, add a null first argument to the list of arguments to pass to the non-native function LLVMValueRef[] arguments = new LLVMValueRef[1 + parameters.length]; if (method.isStatic()) { arguments[0] = LLVM.LLVMConstNull(typeHelper.getOpaquePointer()); } for (int i = 0; i < parameterTypes.length; ++i) { arguments[i + (method.isStatic() ? 1 : 0)] = LLVM.LLVMGetParam(nativeFunction, i); } LLVMBasicBlockRef block = LLVM.LLVMAppendBasicBlock(nativeFunction, "entry"); LLVM.LLVMPositionBuilderAtEnd(builder, block); LLVMValueRef result = LLVM.LLVMBuildCall(builder, nonNativeFunction, C.toNativePointerArray(arguments, false, true), arguments.length, ""); if (method.getReturnType() instanceof VoidType) { LLVM.LLVMBuildRetVoid(builder); } else { LLVM.LLVMBuildRet(builder, result); } } /** * Adds a native function, and calls it from the specified non-native function. * This consists simply of a new function declaration with the method's native name, * and a call to it from the specified non-native function which returns its result. * @param method - the method that this native downcall function is for * @param nonNativeFunction - the non-native function to make the downcall */ private void addNativeDowncallFunction(Method method, LLVMValueRef nonNativeFunction) { LLVMTypeRef resultType = typeHelper.findStandardType(method.getReturnType()); Parameter[] parameters = method.getParameters(); // if the method is non-static, add the pointer argument int offset = method.isStatic() ? 0 : 1; LLVMTypeRef[] parameterTypes = new LLVMTypeRef[offset + parameters.length]; if (!method.isStatic()) { if (typeDefinition instanceof ClassDefinition) { parameterTypes[0] = typeHelper.findTemporaryType(new NamedType(false, method.isImmutable(), method.getContainingTypeDefinition())); } else if (typeDefinition instanceof CompoundDefinition) { parameterTypes[0] = typeHelper.findTemporaryType(new NamedType(false, method.isImmutable(), method.getContainingTypeDefinition())); } } for (int i = 0; i < parameters.length; ++i) { parameterTypes[offset + i] = typeHelper.findStandardType(parameters[i].getType()); } LLVMTypeRef functionType = LLVM.LLVMFunctionType(resultType, C.toNativePointerArray(parameterTypes, false, true), parameterTypes.length, false); LLVMValueRef nativeFunction = LLVM.LLVMAddFunction(module, method.getNativeName(), functionType); LLVM.LLVMSetFunctionCallConv(nativeFunction, LLVM.LLVMCallConv.LLVMCCallConv); LLVMValueRef[] arguments = new LLVMValueRef[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; ++i) { arguments[i] = LLVM.LLVMGetParam(nonNativeFunction, i + (method.isStatic() ? 1 : 0)); } LLVMBasicBlockRef block = LLVM.LLVMAppendBasicBlock(nonNativeFunction, "entry"); LLVM.LLVMPositionBuilderAtEnd(builder, block); LLVMValueRef result = LLVM.LLVMBuildCall(builder, nativeFunction, C.toNativePointerArray(arguments, false, true), arguments.length, ""); if (method.getReturnType() instanceof VoidType) { LLVM.LLVMBuildRetVoid(builder); } else { LLVM.LLVMBuildRet(builder, result); } } private void addInitialiserBody(boolean isStatic) { LLVMValueRef initialiserFunc = getInitialiserFunction(isStatic); LLVMValueRef thisValue = isStatic ? null : LLVM.LLVMGetParam(initialiserFunc, 0); LLVMBasicBlockRef entryBlock = LLVM.LLVMAppendBasicBlock(initialiserFunc, "entry"); LLVM.LLVMPositionBuilderAtEnd(builder, entryBlock); // build all of the static/non-static initialisers in one LLVM function for (Initialiser initialiser : typeDefinition.getInitialisers()) { if (initialiser.isStatic() != isStatic) { continue; } if (initialiser instanceof FieldInitialiser) { Field field = ((FieldInitialiser) initialiser).getField(); LLVMValueRef result = buildExpression(field.getInitialiserExpression(), initialiserFunc, thisValue, new HashMap<Variable, LLVM.LLVMValueRef>()); LLVMValueRef assigneePointer = null; if (field.isStatic()) { assigneePointer = getGlobal(field.getGlobalVariable()); } else { LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), field.getMemberIndex(), false)}; assigneePointer = LLVM.LLVMBuildGEP(builder, thisValue, C.toNativePointerArray(indices, false, true), indices.length, ""); } LLVMValueRef convertedValue = typeHelper.convertTemporaryToStandard(result, field.getInitialiserExpression().getType(), field.getType(), initialiserFunc); LLVM.LLVMBuildStore(builder, convertedValue, assigneePointer); } else { // build allocas for all of the variables, at the start of the entry block Set<Variable> allVariables = Resolver.getAllNestedVariables(initialiser.getBlock()); Map<Variable, LLVMValueRef> variables = new HashMap<Variable, LLVM.LLVMValueRef>(); LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMPositionBuilderAtStart(builder, entryBlock); for (Variable v : allVariables) { LLVMValueRef allocaInst = LLVM.LLVMBuildAlloca(builder, typeHelper.findTemporaryType(v.getType()), v.getName()); variables.put(v, allocaInst); } LLVM.LLVMPositionBuilderAtEnd(builder, currentBlock); buildStatement(initialiser.getBlock(), VoidType.VOID_TYPE, initialiserFunc, thisValue, variables, new HashMap<BreakableStatement, LLVM.LLVMBasicBlockRef>(), new HashMap<BreakableStatement, LLVM.LLVMBasicBlockRef>(), new Runnable() { @Override public void run() { throw new IllegalStateException("Cannot return from an initialiser"); } }); } } LLVM.LLVMBuildRetVoid(builder); } private void setGlobalConstructor(LLVMValueRef initialiserFunc) { // build up the type of the global variable LLVMTypeRef[] paramTypes = new LLVMTypeRef[0]; LLVMTypeRef functionType = LLVM.LLVMFunctionType(LLVM.LLVMVoidType(), C.toNativePointerArray(paramTypes, false, true), paramTypes.length, false); LLVMTypeRef functionPointerType = LLVM.LLVMPointerType(functionType, 0); LLVMTypeRef[] structSubTypes = new LLVMTypeRef[] {LLVM.LLVMInt32Type(), functionPointerType}; LLVMTypeRef structType = LLVM.LLVMStructType(C.toNativePointerArray(structSubTypes, false, true), structSubTypes.length, false); LLVMTypeRef arrayType = LLVM.LLVMArrayType(structType, 1); // build the constant expression for global variable's initialiser LLVMValueRef[] constantValues = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMInt32Type(), 0, false), initialiserFunc}; LLVMValueRef element = LLVM.LLVMConstStruct(C.toNativePointerArray(constantValues, false, true), constantValues.length, false); LLVMValueRef[] arrayElements = new LLVMValueRef[] {element}; LLVMValueRef array = LLVM.LLVMConstArray(structType, C.toNativePointerArray(arrayElements, false, true), arrayElements.length); // create the 'llvm.global_ctors' global variable, which lists which functions are run before main() LLVMValueRef global = LLVM.LLVMAddGlobal(module, arrayType, "llvm.global_ctors"); LLVM.LLVMSetLinkage(global, LLVM.LLVMLinkage.LLVMAppendingLinkage); LLVM.LLVMSetInitializer(global, array); } private void addConstructorBodies() { for (Constructor constructor : typeDefinition.getConstructors()) { final LLVMValueRef llvmFunction = getConstructorFunction(constructor); LLVMBasicBlockRef block = LLVM.LLVMAppendBasicBlock(llvmFunction, "entry"); LLVM.LLVMPositionBuilderAtEnd(builder, block); // create LLVMValueRefs for all of the variables, including paramters Set<Variable> allVariables = Resolver.getAllNestedVariables(constructor.getBlock()); Map<Variable, LLVMValueRef> variables = new HashMap<Variable, LLVM.LLVMValueRef>(); for (Variable v : allVariables) { LLVMValueRef allocaInst = LLVM.LLVMBuildAlloca(builder, typeHelper.findTemporaryType(v.getType()), v.getName()); variables.put(v, allocaInst); } // the first constructor parameter is always the newly allocated 'this' pointer final LLVMValueRef thisValue = LLVM.LLVMGetParam(llvmFunction, 0); // store the parameter values to the LLVMValueRefs for (Parameter p : constructor.getParameters()) { LLVMValueRef llvmParameter = LLVM.LLVMGetParam(llvmFunction, 1 + p.getIndex()); LLVMValueRef convertedParameter = typeHelper.convertStandardToTemporary(llvmParameter, p.getType(), llvmFunction); LLVM.LLVMBuildStore(builder, convertedParameter, variables.get(p.getVariable())); } if (!constructor.getCallsDelegateConstructor()) { // call the non-static initialiser function, which runs all non-static initialisers and sets the initial values for all of the fields // if this constructor calls a delegate constructor then it will be called later on in the block LLVMValueRef initialiserFunction = getInitialiserFunction(false); LLVMValueRef[] initialiserArgs = new LLVMValueRef[] {thisValue}; LLVM.LLVMBuildCall(builder, initialiserFunction, C.toNativePointerArray(initialiserArgs, false, true), initialiserArgs.length, ""); } buildStatement(constructor.getBlock(), VoidType.VOID_TYPE, llvmFunction, thisValue, variables, new HashMap<BreakableStatement, LLVM.LLVMBasicBlockRef>(), new HashMap<BreakableStatement, LLVM.LLVMBasicBlockRef>(), new Runnable() { @Override public void run() { // this will be run whenever a return void is found // so return the result of the constructor, which is always void LLVM.LLVMBuildRetVoid(builder); } }); // return if control reaches the end of the function if (!constructor.getBlock().stopsExecution()) { LLVM.LLVMBuildRetVoid(builder); } } } private void addMethodBodies() { for (Method method : typeDefinition.getAllMethods()) { if (method.getBlock() == null) { continue; } LLVMValueRef llvmFunction = getMethodFunction(method); LLVMBasicBlockRef block = LLVM.LLVMAppendBasicBlock(llvmFunction, "entry"); LLVM.LLVMPositionBuilderAtEnd(builder, block); // create LLVMValueRefs for all of the variables, including parameters Map<Variable, LLVMValueRef> variables = new HashMap<Variable, LLVM.LLVMValueRef>(); for (Variable v : Resolver.getAllNestedVariables(method.getBlock())) { LLVMValueRef allocaInst = LLVM.LLVMBuildAlloca(builder, typeHelper.findTemporaryType(v.getType()), v.getName()); variables.put(v, allocaInst); } // store the parameter values to the LLVMValueRefs for (Parameter p : method.getParameters()) { // find the LLVM parameter, the +1 on the index is to account for the 'this' pointer (or the unused opaque* for static methods) LLVMValueRef llvmParameter = LLVM.LLVMGetParam(llvmFunction, p.getIndex() + 1); LLVMValueRef convertedParameter = typeHelper.convertStandardToTemporary(llvmParameter, p.getType(), llvmFunction); LLVM.LLVMBuildStore(builder, convertedParameter, variables.get(p.getVariable())); } LLVMValueRef thisValue = method.isStatic() ? null : LLVM.LLVMGetParam(llvmFunction, 0); buildStatement(method.getBlock(), method.getReturnType(), llvmFunction, thisValue, variables, new HashMap<BreakableStatement, LLVM.LLVMBasicBlockRef>(), new HashMap<BreakableStatement, LLVM.LLVMBasicBlockRef>(), new Runnable() { @Override public void run() { // this will be run whenever a return void is found // so return void LLVM.LLVMBuildRetVoid(builder); } }); // add a "ret void" if control reaches the end of the function if (!method.getBlock().stopsExecution()) { LLVM.LLVMBuildRetVoid(builder); } } } /** * Generates a main method for the "static uint main([]string)" method in the TypeDefinition we are generating. */ public void generateMainMethod() { Type argsType = new ArrayType(false, false, SpecialTypeHandler.STRING_TYPE, null); Method mainMethod = null; for (Method method : typeDefinition.getAllMethods()) { if (method.isStatic() && method.getName().equals(SpecialTypeHandler.MAIN_METHOD_NAME) && method.getReturnType().isEquivalent(new PrimitiveType(false, PrimitiveTypeType.UINT, null))) { Parameter[] parameters = method.getParameters(); if (parameters.length == 1 && parameters[0].getType().isEquivalent(argsType)) { mainMethod = method; break; } } } if (mainMethod == null) { throw new IllegalArgumentException("Could not find main method in " + typeDefinition.getQualifiedName()); } LLVMValueRef languageMainFunction = getMethodFunction(mainMethod); // define strlen (which we will need for finding the length of each of the arguments) LLVMTypeRef[] strlenParameters = new LLVMTypeRef[] {LLVM.LLVMPointerType(LLVM.LLVMInt8Type(), 0)}; LLVMTypeRef strlenFunctionType = LLVM.LLVMFunctionType(LLVM.LLVMInt32Type(), C.toNativePointerArray(strlenParameters, false, true), strlenParameters.length, false); LLVMValueRef strlenFunction = LLVM.LLVMAddFunction(module, "strlen", strlenFunctionType); // define main LLVMTypeRef argvType = LLVM.LLVMPointerType(LLVM.LLVMPointerType(LLVM.LLVMInt8Type(), 0), 0); LLVMTypeRef[] paramTypes = new LLVMTypeRef[] {LLVM.LLVMInt32Type(), argvType}; LLVMTypeRef returnType = LLVM.LLVMInt32Type(); LLVMTypeRef functionType = LLVM.LLVMFunctionType(returnType, C.toNativePointerArray(paramTypes, false, true), paramTypes.length, false); LLVMValueRef mainFunction = LLVM.LLVMAddFunction(module, "main", functionType); LLVMBasicBlockRef entryBlock = LLVM.LLVMAppendBasicBlock(mainFunction, "entry"); LLVMBasicBlockRef argvLoopBlock = LLVM.LLVMAppendBasicBlock(mainFunction, "argvCopyLoop"); LLVMBasicBlockRef stringLoopBlock = LLVM.LLVMAppendBasicBlock(mainFunction, "stringCopyLoop"); LLVMBasicBlockRef argvLoopEndBlock = LLVM.LLVMAppendBasicBlock(mainFunction, "argvCopyLoopEnd"); LLVMBasicBlockRef finalBlock = LLVM.LLVMAppendBasicBlock(mainFunction, "startProgram"); LLVM.LLVMPositionBuilderAtEnd(builder, entryBlock); LLVMValueRef argc = LLVM.LLVMGetParam(mainFunction, 0); LLVM.LLVMSetValueName(argc, "argc"); LLVMValueRef argv = LLVM.LLVMGetParam(mainFunction, 1); LLVM.LLVMSetValueName(argv, "argv"); // create the final args array LLVMTypeRef llvmArrayType = typeHelper.findTemporaryType(new ArrayType(false, false, SpecialTypeHandler.STRING_TYPE, null)); LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), // go into the pointer to the {i32, [0 x <string>]} LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false), // go into the structure to get the [0 x <string>] argc}; // go argc elements along the array, to get the byte directly after the whole structure, which is also our size LLVMValueRef llvmArraySize = LLVM.LLVMBuildGEP(builder, LLVM.LLVMConstNull(llvmArrayType), C.toNativePointerArray(indices, false, true), indices.length, ""); LLVMValueRef llvmSize = LLVM.LLVMBuildPtrToInt(builder, llvmArraySize, LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), ""); LLVMValueRef[] callocArgs = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMInt32Type(), 1, false), llvmSize}; LLVMValueRef stringArray = LLVM.LLVMBuildCall(builder, callocFunction, C.toNativePointerArray(callocArgs, false, true), callocArgs.length, ""); stringArray = LLVM.LLVMBuildBitCast(builder, stringArray, llvmArrayType, ""); LLVMValueRef[] sizePointerIndices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false)}; LLVMValueRef sizePointer = LLVM.LLVMBuildGEP(builder, stringArray, C.toNativePointerArray(sizePointerIndices, false, true), sizePointerIndices.length, ""); LLVM.LLVMBuildStore(builder, argc, sizePointer); // branch to the argv-copying loop LLVMValueRef initialArgvLoopCheck = LLVM.LLVMBuildICmp(builder, LLVM.LLVMIntPredicate.LLVMIntNE, argc, LLVM.LLVMConstInt(LLVM.LLVMInt32Type(), 0, false), ""); LLVM.LLVMBuildCondBr(builder, initialArgvLoopCheck, argvLoopBlock, finalBlock); LLVM.LLVMPositionBuilderAtEnd(builder, argvLoopBlock); LLVMValueRef argvIndex = LLVM.LLVMBuildPhi(builder, LLVM.LLVMInt32Type(), ""); LLVMValueRef[] charArrayIndices = new LLVMValueRef[] {argvIndex}; LLVMValueRef charArrayPointer = LLVM.LLVMBuildGEP(builder, argv, C.toNativePointerArray(charArrayIndices, false, true), charArrayIndices.length, ""); LLVMValueRef charArray = LLVM.LLVMBuildLoad(builder, charArrayPointer, ""); // call strlen(argv[argvIndex]) LLVMValueRef[] strlenArgs = new LLVMValueRef[] {charArray}; LLVMValueRef argLength = LLVM.LLVMBuildCall(builder, strlenFunction, C.toNativePointerArray(strlenArgs, false, true), strlenArgs.length, ""); // allocate the []ubyte to contain this argument LLVMTypeRef ubyteArrayType = typeHelper.findTemporaryType(new ArrayType(false, true, new PrimitiveType(false, PrimitiveTypeType.UBYTE, null), null)); LLVMValueRef[] ubyteArraySizeIndices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), // go into the pointer to the {i32, [0 x i8]} LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false), // go into the structure to get the [0 x i8] argLength}; // go argLength elements along the array, to get the byte directly after the whole structure, which is also our size LLVMValueRef llvmUbyteArraySize = LLVM.LLVMBuildGEP(builder, LLVM.LLVMConstNull(ubyteArrayType), C.toNativePointerArray(ubyteArraySizeIndices, false, true), ubyteArraySizeIndices.length, ""); LLVMValueRef llvmUbyteSize = LLVM.LLVMBuildPtrToInt(builder, llvmUbyteArraySize, LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), ""); LLVMValueRef[] ubyteCallocArgs = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMInt32Type(), 1, false), llvmUbyteSize}; LLVMValueRef bytes = LLVM.LLVMBuildCall(builder, callocFunction, C.toNativePointerArray(ubyteCallocArgs, false, true), ubyteCallocArgs.length, ""); bytes = LLVM.LLVMBuildBitCast(builder, bytes, ubyteArrayType, ""); LLVMValueRef[] bytesSizePointerIndices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false)}; LLVMValueRef bytesSizePointer = LLVM.LLVMBuildGEP(builder, bytes, C.toNativePointerArray(bytesSizePointerIndices, false, true), bytesSizePointerIndices.length, ""); LLVM.LLVMBuildStore(builder, argLength, bytesSizePointer); // branch to the character copying loop LLVMValueRef initialBytesLoopCheck = LLVM.LLVMBuildICmp(builder, LLVM.LLVMIntPredicate.LLVMIntNE, argLength, LLVM.LLVMConstInt(LLVM.LLVMInt32Type(), 0, false), ""); LLVM.LLVMBuildCondBr(builder, initialBytesLoopCheck, stringLoopBlock, argvLoopEndBlock); LLVM.LLVMPositionBuilderAtEnd(builder, stringLoopBlock); // copy the character LLVMValueRef characterIndex = LLVM.LLVMBuildPhi(builder, LLVM.LLVMInt32Type(), ""); LLVMValueRef[] inPointerIndices = new LLVMValueRef[] {characterIndex}; LLVMValueRef inPointer = LLVM.LLVMBuildGEP(builder, charArray, C.toNativePointerArray(inPointerIndices, false, true), inPointerIndices.length, ""); LLVMValueRef character = LLVM.LLVMBuildLoad(builder, inPointer, ""); LLVMValueRef[] outPointerIndices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false), characterIndex}; LLVMValueRef outPointer = LLVM.LLVMBuildGEP(builder, bytes, C.toNativePointerArray(outPointerIndices, false, true), outPointerIndices.length, ""); LLVM.LLVMBuildStore(builder, character, outPointer); // update the character index, and branch LLVMValueRef incCharacterIndex = LLVM.LLVMBuildAdd(builder, characterIndex, LLVM.LLVMConstInt(LLVM.LLVMInt32Type(), 1, false), ""); LLVMValueRef bytesLoopCheck = LLVM.LLVMBuildICmp(builder, LLVM.LLVMIntPredicate.LLVMIntNE, incCharacterIndex, argLength, ""); LLVM.LLVMBuildCondBr(builder, bytesLoopCheck, stringLoopBlock, argvLoopEndBlock); // add the incomings for the character index LLVMValueRef[] bytesLoopPhiValues = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMInt32Type(), 0, false), incCharacterIndex}; LLVMBasicBlockRef[] bytesLoopPhiBlocks = new LLVMBasicBlockRef[] {argvLoopBlock, stringLoopBlock}; LLVM.LLVMAddIncoming(characterIndex, C.toNativePointerArray(bytesLoopPhiValues, false, true), C.toNativePointerArray(bytesLoopPhiBlocks, false, true), bytesLoopPhiValues.length); // build the end of the string creation loop LLVM.LLVMPositionBuilderAtEnd(builder, argvLoopEndBlock); LLVMValueRef[] stringArrayIndices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false), argvIndex}; LLVMValueRef stringArrayElementPointer = LLVM.LLVMBuildGEP(builder, stringArray, C.toNativePointerArray(stringArrayIndices, false, true), stringArrayIndices.length, ""); typeHelper.initialiseCompoundType((CompoundDefinition) SpecialTypeHandler.STRING_TYPE.getResolvedTypeDefinition(), stringArrayElementPointer); LLVMValueRef[] stringCreationArgs = new LLVMValueRef[] {stringArrayElementPointer, bytes}; LLVM.LLVMBuildCall(builder, getConstructorFunction(SpecialTypeHandler.stringArrayConstructor), C.toNativePointerArray(stringCreationArgs, false, true), stringCreationArgs.length, ""); // update the argv index, and branch LLVMValueRef incArgvIndex = LLVM.LLVMBuildAdd(builder, argvIndex, LLVM.LLVMConstInt(LLVM.LLVMInt32Type(), 1, false), ""); LLVMValueRef argvLoopCheck = LLVM.LLVMBuildICmp(builder, LLVM.LLVMIntPredicate.LLVMIntNE, incArgvIndex, argc, ""); LLVM.LLVMBuildCondBr(builder, argvLoopCheck, argvLoopBlock, finalBlock); // add the incomings for the argv index LLVMValueRef[] argvLoopPhiValues = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMInt32Type(), 0, false), incArgvIndex}; LLVMBasicBlockRef[] argvLoopPhiBlocks = new LLVMBasicBlockRef[] {entryBlock, argvLoopEndBlock}; LLVM.LLVMAddIncoming(argvIndex, C.toNativePointerArray(argvLoopPhiValues, false, true), C.toNativePointerArray(argvLoopPhiBlocks, false, true), argvLoopPhiValues.length); // build the actual function call LLVM.LLVMPositionBuilderAtEnd(builder, finalBlock); LLVMValueRef[] arguments = new LLVMValueRef[] {LLVM.LLVMConstNull(typeHelper.getOpaquePointer()), stringArray}; LLVMValueRef returnCode = LLVM.LLVMBuildCall(builder, languageMainFunction, C.toNativePointerArray(arguments, false, true), arguments.length, ""); LLVM.LLVMBuildRet(builder, returnCode); } private void buildStatement(Statement statement, Type returnType, LLVMValueRef llvmFunction, LLVMValueRef thisValue, Map<Variable, LLVMValueRef> variables, Map<BreakableStatement, LLVMBasicBlockRef> breakBlocks, Map<BreakableStatement, LLVMBasicBlockRef> continueBlocks, Runnable returnVoidCallback) { if (statement instanceof AssignStatement) { AssignStatement assignStatement = (AssignStatement) statement; Assignee[] assignees = assignStatement.getAssignees(); LLVMValueRef[] llvmAssigneePointers = new LLVMValueRef[assignees.length]; boolean[] standardTypeRepresentations = new boolean[assignees.length]; for (int i = 0; i < assignees.length; i++) { if (assignees[i] instanceof VariableAssignee) { Variable resolvedVariable = ((VariableAssignee) assignees[i]).getResolvedVariable(); if (resolvedVariable instanceof MemberVariable) { Field field = ((MemberVariable) resolvedVariable).getField(); LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), field.getMemberIndex(), false)}; llvmAssigneePointers[i] = LLVM.LLVMBuildGEP(builder, thisValue, C.toNativePointerArray(indices, false, true), indices.length, ""); standardTypeRepresentations[i] = true; } else if (resolvedVariable instanceof GlobalVariable) { llvmAssigneePointers[i] = getGlobal((GlobalVariable) resolvedVariable); standardTypeRepresentations[i] = true; } else { llvmAssigneePointers[i] = variables.get(resolvedVariable); standardTypeRepresentations[i] = false; } } else if (assignees[i] instanceof ArrayElementAssignee) { ArrayElementAssignee arrayElementAssignee = (ArrayElementAssignee) assignees[i]; LLVMValueRef array = buildExpression(arrayElementAssignee.getArrayExpression(), llvmFunction, thisValue, variables); LLVMValueRef dimension = buildExpression(arrayElementAssignee.getDimensionExpression(), llvmFunction, thisValue, variables); LLVMValueRef convertedDimension = typeHelper.convertTemporaryToStandard(dimension, arrayElementAssignee.getDimensionExpression().getType(), ArrayLengthMember.ARRAY_LENGTH_TYPE, llvmFunction); LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false), convertedDimension}; llvmAssigneePointers[i] = LLVM.LLVMBuildGEP(builder, array, C.toNativePointerArray(indices, false, true), indices.length, ""); standardTypeRepresentations[i] = true; } else if (assignees[i] instanceof FieldAssignee) { FieldAssignee fieldAssignee = (FieldAssignee) assignees[i]; FieldAccessExpression fieldAccessExpression = fieldAssignee.getFieldAccessExpression(); if (fieldAccessExpression.getResolvedMember() instanceof Field) { Field field = (Field) fieldAccessExpression.getResolvedMember(); if (field.isStatic()) { llvmAssigneePointers[i] = getGlobal(field.getGlobalVariable()); standardTypeRepresentations[i] = true; } else { LLVMValueRef expressionValue = buildExpression(fieldAccessExpression.getBaseExpression(), llvmFunction, thisValue, variables); LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), field.getMemberIndex(), false)}; llvmAssigneePointers[i] = LLVM.LLVMBuildGEP(builder, expressionValue, C.toNativePointerArray(indices, false, true), indices.length, ""); standardTypeRepresentations[i] = true; } } else { throw new IllegalArgumentException("Unknown member assigned to in a FieldAssignee: " + fieldAccessExpression.getResolvedMember()); } } else if (assignees[i] instanceof BlankAssignee) { // this assignee doesn't actually get assigned to llvmAssigneePointers[i] = null; standardTypeRepresentations[i] = false; } else { throw new IllegalStateException("Unknown Assignee type: " + assignees[i]); } } if (assignStatement.getExpression() != null) { LLVMValueRef value = buildExpression(assignStatement.getExpression(), llvmFunction, thisValue, variables); if (llvmAssigneePointers.length == 1) { if (llvmAssigneePointers[0] != null) { LLVMValueRef convertedValue; if (standardTypeRepresentations[0]) { convertedValue = typeHelper.convertTemporaryToStandard(value, assignStatement.getExpression().getType(), assignees[0].getResolvedType(), llvmFunction); } else { convertedValue = typeHelper.convertTemporary(value, assignStatement.getExpression().getType(), assignees[0].getResolvedType()); } LLVM.LLVMBuildStore(builder, convertedValue, llvmAssigneePointers[0]); } } else { if (assignStatement.getResolvedType().isNullable()) { throw new IllegalStateException("An assign statement's type cannot be nullable if it is about to be split into multiple assignees"); } Type[] expressionSubTypes = ((TupleType) assignStatement.getExpression().getType()).getSubTypes(); for (int i = 0; i < llvmAssigneePointers.length; i++) { if (llvmAssigneePointers[i] != null) { LLVMValueRef extracted = LLVM.LLVMBuildExtractValue(builder, value, i, ""); LLVMValueRef convertedValue; if (standardTypeRepresentations[i]) { convertedValue = typeHelper.convertTemporaryToStandard(extracted, expressionSubTypes[i], assignees[i].getResolvedType(), llvmFunction); } else { convertedValue = typeHelper.convertTemporary(extracted, expressionSubTypes[i], assignees[i].getResolvedType()); } LLVM.LLVMBuildStore(builder, convertedValue, llvmAssigneePointers[i]); } } } } } else if (statement instanceof Block) { for (Statement s : ((Block) statement).getStatements()) { buildStatement(s, returnType, llvmFunction, thisValue, variables, breakBlocks, continueBlocks, returnVoidCallback); } } else if (statement instanceof BreakStatement) { LLVMBasicBlockRef block = breakBlocks.get(((BreakStatement) statement).getResolvedBreakable()); if (block == null) { throw new IllegalStateException("Break statement leads to a null block during code generation: " + statement); } LLVM.LLVMBuildBr(builder, block); } else if (statement instanceof ContinueStatement) { LLVMBasicBlockRef block = continueBlocks.get(((ContinueStatement) statement).getResolvedBreakable()); if (block == null) { throw new IllegalStateException("Continue statement leads to a null block during code generation: " + statement); } LLVM.LLVMBuildBr(builder, block); } else if (statement instanceof DelegateConstructorStatement) { DelegateConstructorStatement delegateConstructorStatement = (DelegateConstructorStatement) statement; Constructor delegatedConstructor = delegateConstructorStatement.getResolvedConstructor(); Parameter[] parameters = delegatedConstructor.getParameters(); Expression[] arguments = delegateConstructorStatement.getArguments(); LLVMValueRef llvmConstructor = getConstructorFunction(delegatedConstructor); LLVMValueRef[] llvmArguments = new LLVMValueRef[1 + parameters.length]; llvmArguments[0] = thisValue; for (int i = 0; i < parameters.length; ++i) { LLVMValueRef argument = buildExpression(arguments[i], llvmFunction, thisValue, variables); llvmArguments[1 + i] = typeHelper.convertTemporaryToStandard(argument, arguments[i].getType(), parameters[i].getType(), llvmFunction); } LLVM.LLVMBuildCall(builder, llvmConstructor, C.toNativePointerArray(llvmArguments, false, true), llvmArguments.length, ""); } else if (statement instanceof ExpressionStatement) { buildExpression(((ExpressionStatement) statement).getExpression(), llvmFunction, thisValue, variables); } else if (statement instanceof ForStatement) { ForStatement forStatement = (ForStatement) statement; Statement init = forStatement.getInitStatement(); if (init != null) { buildStatement(init, returnType, llvmFunction, thisValue, variables, breakBlocks, continueBlocks, returnVoidCallback); } Expression conditional = forStatement.getConditional(); Statement update = forStatement.getUpdateStatement(); LLVMBasicBlockRef loopCheck = conditional == null ? null : LLVM.LLVMAppendBasicBlock(llvmFunction, "forLoopCheck"); LLVMBasicBlockRef loopBody = LLVM.LLVMAppendBasicBlock(llvmFunction, "forLoopBody"); LLVMBasicBlockRef loopUpdate = update == null ? null : LLVM.LLVMAppendBasicBlock(llvmFunction, "forLoopUpdate"); // only generate a continuation block if there is a way to get out of the loop LLVMBasicBlockRef continuationBlock = forStatement.stopsExecution() ? null : LLVM.LLVMAppendBasicBlock(llvmFunction, "afterForLoop"); if (conditional == null) { LLVM.LLVMBuildBr(builder, loopBody); } else { LLVM.LLVMBuildBr(builder, loopCheck); LLVM.LLVMPositionBuilderAtEnd(builder, loopCheck); LLVMValueRef conditionResult = buildExpression(conditional, llvmFunction, thisValue, variables); conditionResult = typeHelper.convertTemporaryToStandard(conditionResult, conditional.getType(), new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null), llvmFunction); LLVM.LLVMBuildCondBr(builder, conditionResult, loopBody, continuationBlock); } LLVM.LLVMPositionBuilderAtEnd(builder, loopBody); if (continuationBlock != null) { breakBlocks.put(forStatement, continuationBlock); } continueBlocks.put(forStatement, loopUpdate == null ? (loopCheck == null ? loopBody : loopCheck) : loopUpdate); buildStatement(forStatement.getBlock(), returnType, llvmFunction, thisValue, variables, breakBlocks, continueBlocks, returnVoidCallback); if (!forStatement.getBlock().stopsExecution()) { LLVM.LLVMBuildBr(builder, loopUpdate == null ? (loopCheck == null ? loopBody : loopCheck) : loopUpdate); } if (update != null) { LLVM.LLVMPositionBuilderAtEnd(builder, loopUpdate); buildStatement(update, returnType, llvmFunction, thisValue, variables, breakBlocks, continueBlocks, returnVoidCallback); if (update.stopsExecution()) { throw new IllegalStateException("For loop update stops execution before the branch to the loop check: " + update); } LLVM.LLVMBuildBr(builder, loopCheck == null ? loopBody : loopCheck); } if (continuationBlock != null) { LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); } } else if (statement instanceof IfStatement) { IfStatement ifStatement = (IfStatement) statement; LLVMValueRef conditional = buildExpression(ifStatement.getExpression(), llvmFunction, thisValue, variables); conditional = typeHelper.convertTemporaryToStandard(conditional, ifStatement.getExpression().getType(), new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null), llvmFunction); LLVMBasicBlockRef thenClause = LLVM.LLVMAppendBasicBlock(llvmFunction, "then"); LLVMBasicBlockRef elseClause = null; if (ifStatement.getElseClause() != null) { elseClause = LLVM.LLVMAppendBasicBlock(llvmFunction, "else"); } LLVMBasicBlockRef continuation = null; if (!ifStatement.stopsExecution()) { continuation = LLVM.LLVMAppendBasicBlock(llvmFunction, "continuation"); } // build the branch instruction if (elseClause == null) { // if we have no else clause, then a continuation must have been created, since the if statement cannot stop execution LLVM.LLVMBuildCondBr(builder, conditional, thenClause, continuation); } else { LLVM.LLVMBuildCondBr(builder, conditional, thenClause, elseClause); // build the else clause LLVM.LLVMPositionBuilderAtEnd(builder, elseClause); buildStatement(ifStatement.getElseClause(), returnType, llvmFunction, thisValue, variables, breakBlocks, continueBlocks, returnVoidCallback); if (!ifStatement.getElseClause().stopsExecution()) { LLVM.LLVMBuildBr(builder, continuation); } } // build the then clause LLVM.LLVMPositionBuilderAtEnd(builder, thenClause); buildStatement(ifStatement.getThenClause(), returnType, llvmFunction, thisValue, variables, breakBlocks, continueBlocks, returnVoidCallback); if (!ifStatement.getThenClause().stopsExecution()) { LLVM.LLVMBuildBr(builder, continuation); } if (continuation != null) { LLVM.LLVMPositionBuilderAtEnd(builder, continuation); } } else if (statement instanceof PrefixIncDecStatement) { PrefixIncDecStatement prefixIncDecStatement = (PrefixIncDecStatement) statement; Assignee assignee = prefixIncDecStatement.getAssignee(); LLVMValueRef pointer; boolean standardTypeRepresentation = false; if (assignee instanceof VariableAssignee) { Variable resolvedVariable = ((VariableAssignee) assignee).getResolvedVariable(); if (resolvedVariable instanceof MemberVariable) { Field field = ((MemberVariable) resolvedVariable).getField(); LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), field.getMemberIndex(), false)}; pointer = LLVM.LLVMBuildGEP(builder, thisValue, C.toNativePointerArray(indices, false, true), indices.length, ""); standardTypeRepresentation = true; } else if (resolvedVariable instanceof GlobalVariable) { pointer = getGlobal((GlobalVariable) resolvedVariable); standardTypeRepresentation = true; } else { pointer = variables.get(resolvedVariable); standardTypeRepresentation = false; } } else if (assignee instanceof ArrayElementAssignee) { ArrayElementAssignee arrayElementAssignee = (ArrayElementAssignee) assignee; LLVMValueRef array = buildExpression(arrayElementAssignee.getArrayExpression(), llvmFunction, thisValue, variables); LLVMValueRef dimension = buildExpression(arrayElementAssignee.getDimensionExpression(), llvmFunction, thisValue, variables); LLVMValueRef convertedDimension = typeHelper.convertTemporaryToStandard(dimension, arrayElementAssignee.getDimensionExpression().getType(), ArrayLengthMember.ARRAY_LENGTH_TYPE, llvmFunction); LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false), convertedDimension}; pointer = LLVM.LLVMBuildGEP(builder, array, C.toNativePointerArray(indices, false, true), indices.length, ""); standardTypeRepresentation = true; } else if (assignee instanceof FieldAssignee) { FieldAssignee fieldAssignee = (FieldAssignee) assignee; FieldAccessExpression fieldAccessExpression = fieldAssignee.getFieldAccessExpression(); if (fieldAccessExpression.getResolvedMember() instanceof Field) { Field field = (Field) fieldAccessExpression.getResolvedMember(); if (field.isStatic()) { pointer = getGlobal(field.getGlobalVariable()); standardTypeRepresentation = true; } else { LLVMValueRef expressionValue = buildExpression(fieldAccessExpression.getBaseExpression(), llvmFunction, thisValue, variables); LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), field.getMemberIndex(), false)}; pointer = LLVM.LLVMBuildGEP(builder, expressionValue, C.toNativePointerArray(indices, false, true), indices.length, ""); standardTypeRepresentation = true; } } else { throw new IllegalArgumentException("Unknown member assigned to in a FieldAssignee: " + fieldAccessExpression.getResolvedMember()); } } else { // ignore blank assignees, they shouldn't be able to get through variable resolution throw new IllegalStateException("Unknown Assignee type: " + assignee); } LLVMValueRef loaded = LLVM.LLVMBuildLoad(builder, pointer, ""); PrimitiveType type = (PrimitiveType) assignee.getResolvedType(); LLVMValueRef result; if (type.getPrimitiveTypeType().isFloating()) { LLVMValueRef one = LLVM.LLVMConstReal(typeHelper.findTemporaryType(type), 1); if (prefixIncDecStatement.isIncrement()) { result = LLVM.LLVMBuildFAdd(builder, loaded, one, ""); } else { result = LLVM.LLVMBuildFSub(builder, loaded, one, ""); } } else { LLVMValueRef one = LLVM.LLVMConstInt(typeHelper.findTemporaryType(type), 1, false); if (prefixIncDecStatement.isIncrement()) { result = LLVM.LLVMBuildAdd(builder, loaded, one, ""); } else { result = LLVM.LLVMBuildSub(builder, loaded, one, ""); } } if (standardTypeRepresentation) { result = typeHelper.convertTemporaryToStandard(result, type, llvmFunction); } LLVM.LLVMBuildStore(builder, result, pointer); } else if (statement instanceof ReturnStatement) { Expression returnedExpression = ((ReturnStatement) statement).getExpression(); if (returnedExpression == null) { returnVoidCallback.run(); } else { LLVMValueRef value = buildExpression(returnedExpression, llvmFunction, thisValue, variables); LLVMValueRef convertedValue = typeHelper.convertTemporaryToStandard(value, returnedExpression.getType(), returnType, llvmFunction); LLVM.LLVMBuildRet(builder, convertedValue); } } else if (statement instanceof ShorthandAssignStatement) { ShorthandAssignStatement shorthandAssignStatement = (ShorthandAssignStatement) statement; Assignee[] assignees = shorthandAssignStatement.getAssignees(); LLVMValueRef[] llvmAssigneePointers = new LLVMValueRef[assignees.length]; boolean[] standardTypeRepresentations = new boolean[assignees.length]; for (int i = 0; i < assignees.length; ++i) { if (assignees[i] instanceof VariableAssignee) { Variable resolvedVariable = ((VariableAssignee) assignees[i]).getResolvedVariable(); if (resolvedVariable instanceof MemberVariable) { Field field = ((MemberVariable) resolvedVariable).getField(); LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), field.getMemberIndex(), false)}; llvmAssigneePointers[i] = LLVM.LLVMBuildGEP(builder, thisValue, C.toNativePointerArray(indices, false, true), indices.length, ""); standardTypeRepresentations[i] = true; } else if (resolvedVariable instanceof GlobalVariable) { llvmAssigneePointers[i] = getGlobal((GlobalVariable) resolvedVariable); standardTypeRepresentations[i] = true; } else { llvmAssigneePointers[i] = variables.get(resolvedVariable); standardTypeRepresentations[i] = false; } } else if (assignees[i] instanceof ArrayElementAssignee) { ArrayElementAssignee arrayElementAssignee = (ArrayElementAssignee) assignees[i]; LLVMValueRef array = buildExpression(arrayElementAssignee.getArrayExpression(), llvmFunction, thisValue, variables); LLVMValueRef dimension = buildExpression(arrayElementAssignee.getDimensionExpression(), llvmFunction, thisValue, variables); LLVMValueRef convertedDimension = typeHelper.convertTemporaryToStandard(dimension, arrayElementAssignee.getDimensionExpression().getType(), ArrayLengthMember.ARRAY_LENGTH_TYPE, llvmFunction); LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false), convertedDimension}; llvmAssigneePointers[i] = LLVM.LLVMBuildGEP(builder, array, C.toNativePointerArray(indices, false, true), indices.length, ""); standardTypeRepresentations[i] = true; } else if (assignees[i] instanceof FieldAssignee) { FieldAssignee fieldAssignee = (FieldAssignee) assignees[i]; FieldAccessExpression fieldAccessExpression = fieldAssignee.getFieldAccessExpression(); if (fieldAccessExpression.getResolvedMember() instanceof Field) { Field field = (Field) fieldAccessExpression.getResolvedMember(); if (field.isStatic()) { llvmAssigneePointers[i] = getGlobal(field.getGlobalVariable()); standardTypeRepresentations[i] = true; } else { LLVMValueRef expressionValue = buildExpression(fieldAccessExpression.getBaseExpression(), llvmFunction, thisValue, variables); LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), field.getMemberIndex(), false)}; llvmAssigneePointers[i] = LLVM.LLVMBuildGEP(builder, expressionValue, C.toNativePointerArray(indices, false, true), indices.length, ""); standardTypeRepresentations[i] = true; } } else { throw new IllegalArgumentException("Unknown member assigned to in a FieldAssignee: " + fieldAccessExpression.getResolvedMember()); } } else if (assignees[i] instanceof BlankAssignee) { // this assignee doesn't actually get assigned to llvmAssigneePointers[i] = null; standardTypeRepresentations[i] = false; } else { throw new IllegalStateException("Unknown Assignee type: " + assignees[i]); } } LLVMValueRef result = buildExpression(shorthandAssignStatement.getExpression(), llvmFunction, thisValue, variables); Type resultType = shorthandAssignStatement.getExpression().getType(); LLVMValueRef[] resultValues = new LLVMValueRef[assignees.length]; Type[] resultValueTypes = new Type[assignees.length]; if (resultType instanceof TupleType && !resultType.isNullable() && ((TupleType) resultType).getSubTypes().length == assignees.length) { Type[] subTypes = ((TupleType) resultType).getSubTypes(); for (int i = 0; i < assignees.length; ++i) { if (assignees[i] instanceof BlankAssignee) { continue; } resultValues[i] = LLVM.LLVMBuildExtractValue(builder, result, i, ""); resultValueTypes[i] = subTypes[i]; } } else { for (int i = 0; i < assignees.length; ++i) { resultValues[i] = result; resultValueTypes[i] = resultType; } } for (int i = 0; i < assignees.length; ++i) { if (llvmAssigneePointers[i] == null) { // this is a blank assignee, so don't try to do anything for it continue; } Type type = assignees[i].getResolvedType(); LLVMValueRef leftValue = LLVM.LLVMBuildLoad(builder, llvmAssigneePointers[i], ""); if (standardTypeRepresentations[i]) { leftValue = typeHelper.convertStandardToTemporary(leftValue, type, llvmFunction); } LLVMValueRef rightValue = typeHelper.convertTemporary(resultValues[i], resultValueTypes[i], type); LLVMValueRef assigneeResult; if (shorthandAssignStatement.getOperator() == ShorthandAssignmentOperator.ADD && type.isEquivalent(SpecialTypeHandler.STRING_TYPE)) { // concatenate the strings // build an alloca in the entry block for the result of the concatenation LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMPositionBuilderAtStart(builder, LLVM.LLVMGetEntryBasicBlock(llvmFunction)); // find the type to alloca, which is the standard representation of a non-nullable version of this type // when we alloca this type, it becomes equivalent to the temporary type representation of this compound type (with any nullability) LLVMTypeRef allocaBaseType = typeHelper.findStandardType(new NamedType(false, false, SpecialTypeHandler.stringConcatenationConstructor.getContainingTypeDefinition())); LLVMValueRef alloca = LLVM.LLVMBuildAlloca(builder, allocaBaseType, ""); LLVM.LLVMPositionBuilderAtEnd(builder, currentBlock); typeHelper.initialiseCompoundType((CompoundDefinition) SpecialTypeHandler.stringConcatenationConstructor.getContainingTypeDefinition(), alloca); // call the string(string, string) constructor LLVMValueRef[] arguments = new LLVMValueRef[] {alloca, typeHelper.convertTemporaryToStandard(leftValue, resultType, llvmFunction), typeHelper.convertTemporaryToStandard(rightValue, resultType, llvmFunction)}; LLVMValueRef concatenationConstructor = getConstructorFunction(SpecialTypeHandler.stringConcatenationConstructor); LLVM.LLVMBuildCall(builder, concatenationConstructor, C.toNativePointerArray(arguments, false, true), arguments.length, ""); assigneeResult = alloca; } else if (type instanceof PrimitiveType) { PrimitiveTypeType primitiveType = ((PrimitiveType) type).getPrimitiveTypeType(); boolean floating = primitiveType.isFloating(); boolean signed = primitiveType.isSigned(); switch (shorthandAssignStatement.getOperator()) { case AND: assigneeResult = LLVM.LLVMBuildAnd(builder, leftValue, rightValue, ""); break; case OR: assigneeResult = LLVM.LLVMBuildOr(builder, leftValue, rightValue, ""); break; case XOR: assigneeResult = LLVM.LLVMBuildXor(builder, leftValue, rightValue, ""); break; case ADD: assigneeResult = floating ? LLVM.LLVMBuildFAdd(builder, leftValue, rightValue, "") : LLVM.LLVMBuildAdd(builder, leftValue, rightValue, ""); break; case SUBTRACT: assigneeResult = floating ? LLVM.LLVMBuildFSub(builder, leftValue, rightValue, "") : LLVM.LLVMBuildSub(builder, leftValue, rightValue, ""); break; case MULTIPLY: assigneeResult = floating ? LLVM.LLVMBuildFMul(builder, leftValue, rightValue, "") : LLVM.LLVMBuildMul(builder, leftValue, rightValue, ""); break; case DIVIDE: assigneeResult = floating ? LLVM.LLVMBuildFDiv(builder, leftValue, rightValue, "") : signed ? LLVM.LLVMBuildSDiv(builder, leftValue, rightValue, "") : LLVM.LLVMBuildUDiv(builder, leftValue, rightValue, ""); break; case REMAINDER: assigneeResult = floating ? LLVM.LLVMBuildFRem(builder, leftValue, rightValue, "") : signed ? LLVM.LLVMBuildSRem(builder, leftValue, rightValue, "") : LLVM.LLVMBuildURem(builder, leftValue, rightValue, ""); break; case MODULO: if (floating) { LLVMValueRef rem = LLVM.LLVMBuildFRem(builder, leftValue, rightValue, ""); LLVMValueRef add = LLVM.LLVMBuildFAdd(builder, rem, rightValue, ""); assigneeResult = LLVM.LLVMBuildFRem(builder, add, rightValue, ""); } else if (signed) { LLVMValueRef rem = LLVM.LLVMBuildSRem(builder, leftValue, rightValue, ""); LLVMValueRef add = LLVM.LLVMBuildAdd(builder, rem, rightValue, ""); assigneeResult = LLVM.LLVMBuildSRem(builder, add, rightValue, ""); } else { // unsigned modulo is the same as unsigned remainder assigneeResult = LLVM.LLVMBuildURem(builder, leftValue, rightValue, ""); } break; case LEFT_SHIFT: assigneeResult = LLVM.LLVMBuildShl(builder, leftValue, rightValue, ""); break; case RIGHT_SHIFT: assigneeResult = signed ? LLVM.LLVMBuildAShr(builder, leftValue, rightValue, "") : LLVM.LLVMBuildLShr(builder, leftValue, rightValue, ""); break; default: throw new IllegalStateException("Unknown shorthand assignment operator: " + shorthandAssignStatement.getOperator()); } } else { throw new IllegalStateException("Unknown shorthand assignment operation: " + shorthandAssignStatement); } if (standardTypeRepresentations[i]) { assigneeResult = typeHelper.convertTemporaryToStandard(assigneeResult, type, llvmFunction); } LLVM.LLVMBuildStore(builder, assigneeResult, llvmAssigneePointers[i]); } } else if (statement instanceof WhileStatement) { WhileStatement whileStatement = (WhileStatement) statement; LLVMBasicBlockRef loopCheck = LLVM.LLVMAppendBasicBlock(llvmFunction, "whileLoopCheck"); LLVM.LLVMBuildBr(builder, loopCheck); LLVM.LLVMPositionBuilderAtEnd(builder, loopCheck); LLVMValueRef conditional = buildExpression(whileStatement.getExpression(), llvmFunction, thisValue, variables); conditional = typeHelper.convertTemporaryToStandard(conditional, whileStatement.getExpression().getType(), new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null), llvmFunction); LLVMBasicBlockRef loopBodyBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "whileLoopBody"); LLVMBasicBlockRef afterLoopBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "afterWhileLoop"); LLVM.LLVMBuildCondBr(builder, conditional, loopBodyBlock, afterLoopBlock); LLVM.LLVMPositionBuilderAtEnd(builder, loopBodyBlock); // add the while statement's afterLoop block to the breakBlocks map before it's statement is built breakBlocks.put(whileStatement, afterLoopBlock); continueBlocks.put(whileStatement, loopCheck); buildStatement(whileStatement.getStatement(), returnType, llvmFunction, thisValue, variables, breakBlocks, continueBlocks, returnVoidCallback); if (!whileStatement.getStatement().stopsExecution()) { LLVM.LLVMBuildBr(builder, loopCheck); } LLVM.LLVMPositionBuilderAtEnd(builder, afterLoopBlock); } } private int getPredicate(EqualityOperator operator, boolean floating) { if (floating) { switch (operator) { case EQUAL: return LLVM.LLVMRealPredicate.LLVMRealOEQ; case NOT_EQUAL: return LLVM.LLVMRealPredicate.LLVMRealONE; } } else { switch (operator) { case EQUAL: return LLVM.LLVMIntPredicate.LLVMIntEQ; case NOT_EQUAL: return LLVM.LLVMIntPredicate.LLVMIntNE; } } throw new IllegalArgumentException("Unknown predicate '" + operator + "'"); } private int getPredicate(RelationalOperator operator, boolean floating, boolean signed) { if (floating) { switch (operator) { case LESS_THAN: return LLVM.LLVMRealPredicate.LLVMRealOLT; case LESS_THAN_EQUAL: return LLVM.LLVMRealPredicate.LLVMRealOLE; case MORE_THAN: return LLVM.LLVMRealPredicate.LLVMRealOGT; case MORE_THAN_EQUAL: return LLVM.LLVMRealPredicate.LLVMRealOGE; } } else { switch (operator) { case LESS_THAN: return signed ? LLVM.LLVMIntPredicate.LLVMIntSLT : LLVM.LLVMIntPredicate.LLVMIntULT; case LESS_THAN_EQUAL: return signed ? LLVM.LLVMIntPredicate.LLVMIntSLE : LLVM.LLVMIntPredicate.LLVMIntULE; case MORE_THAN: return signed ? LLVM.LLVMIntPredicate.LLVMIntSGT : LLVM.LLVMIntPredicate.LLVMIntUGT; case MORE_THAN_EQUAL: return signed ? LLVM.LLVMIntPredicate.LLVMIntSGE : LLVM.LLVMIntPredicate.LLVMIntUGE; } } throw new IllegalArgumentException("Unknown predicate '" + operator + "'"); } private LLVMValueRef buildArrayCreation(LLVMValueRef llvmFunction, LLVMValueRef[] llvmLengths, ArrayType type) { LLVMTypeRef llvmArrayType = typeHelper.findTemporaryType(type); LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), // go into the pointer to the {i32, [0 x <type>]} LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false), // go into the structure to get the [0 x <type>] llvmLengths[0]}; // go length elements along the array, to get the byte directly after the whole structure, which is also our size LLVMValueRef llvmArraySize = LLVM.LLVMBuildGEP(builder, LLVM.LLVMConstNull(llvmArrayType), C.toNativePointerArray(indices, false, true), indices.length, ""); LLVMValueRef llvmSize = LLVM.LLVMBuildPtrToInt(builder, llvmArraySize, LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), ""); // call calloc to allocate the memory and initialise it to a string of zeros LLVMValueRef[] arguments = new LLVMValueRef[] {llvmSize, LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false)}; LLVMValueRef memoryPointer = LLVM.LLVMBuildCall(builder, callocFunction, C.toNativePointerArray(arguments, false, true), arguments.length, ""); LLVMValueRef allocatedPointer = LLVM.LLVMBuildBitCast(builder, memoryPointer, llvmArrayType, ""); LLVMValueRef[] sizeIndices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false)}; LLVMValueRef sizeElementPointer = LLVM.LLVMBuildGEP(builder, allocatedPointer, C.toNativePointerArray(sizeIndices, false, true), sizeIndices.length, ""); LLVM.LLVMBuildStore(builder, llvmLengths[0], sizeElementPointer); if (llvmLengths.length > 1) { // build a loop to create all of the elements of this array by recursively calling buildArrayCreation() ArrayType subType = (ArrayType) type.getBaseType(); LLVMBasicBlockRef startBlock = LLVM.LLVMGetInsertBlock(builder); LLVMBasicBlockRef loopCheckBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "arrayCreationCheck"); LLVMBasicBlockRef loopBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "arrayCreation"); LLVMBasicBlockRef exitBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "arrayCreationEnd"); LLVM.LLVMBuildBr(builder, loopCheckBlock); LLVM.LLVMPositionBuilderAtEnd(builder, loopCheckBlock); LLVMValueRef phiNode = LLVM.LLVMBuildPhi(builder, LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), "arrayCounter"); LLVMValueRef breakBoolean = LLVM.LLVMBuildICmp(builder, LLVM.LLVMIntPredicate.LLVMIntULT, phiNode, llvmLengths[0], ""); LLVM.LLVMBuildCondBr(builder, breakBoolean, loopBlock, exitBlock); LLVM.LLVMPositionBuilderAtEnd(builder, loopBlock); // recurse to create this element of the array LLVMValueRef[] subLengths = new LLVMValueRef[llvmLengths.length - 1]; System.arraycopy(llvmLengths, 1, subLengths, 0, subLengths.length); LLVMValueRef subArray = buildArrayCreation(llvmFunction, subLengths, subType); // find the indices for the current location in the array LLVMValueRef[] assignmentIndices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false), phiNode}; LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, allocatedPointer, C.toNativePointerArray(assignmentIndices, false, true), assignmentIndices.length, ""); LLVM.LLVMBuildStore(builder, subArray, elementPointer); // add the incoming values to the phi node LLVMValueRef nextCounterValue = LLVM.LLVMBuildAdd(builder, phiNode, LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false), ""); LLVMValueRef[] incomingValues = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), nextCounterValue}; LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {startBlock, LLVM.LLVMGetInsertBlock(builder)}; LLVM.LLVMAddIncoming(phiNode, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), 2); LLVM.LLVMBuildBr(builder, loopCheckBlock); LLVM.LLVMPositionBuilderAtEnd(builder, exitBlock); } return allocatedPointer; } /** * Builds the LLVM statements for a null check on the specified value. * @param value - the LLVMValueRef to compare to null, in a temporary native representation * @param type - the type of the specified LLVMValueRef * @return an LLVMValueRef for an i1, which will be 1 if the value is non-null, and 0 if the value is null */ private LLVMValueRef buildNullCheck(LLVMValueRef value, Type type) { if (!type.isNullable()) { throw new IllegalArgumentException("A null check can only work on a nullable type"); } if (type instanceof ArrayType) { return LLVM.LLVMBuildICmp(builder, LLVM.LLVMIntPredicate.LLVMIntNE, value, LLVM.LLVMConstNull(typeHelper.findTemporaryType(type)), ""); } if (type instanceof FunctionType) { LLVMValueRef functionPointer = LLVM.LLVMBuildExtractValue(builder, value, 1, ""); LLVMTypeRef llvmFunctionPointerType = typeHelper.findRawFunctionPointerType((FunctionType) type); return LLVM.LLVMBuildICmp(builder, LLVM.LLVMIntPredicate.LLVMIntNE, functionPointer, LLVM.LLVMConstNull(llvmFunctionPointerType), ""); } if (type instanceof NamedType) { TypeDefinition typeDefinition = ((NamedType) type).getResolvedTypeDefinition(); if (typeDefinition instanceof ClassDefinition) { return LLVM.LLVMBuildIsNotNull(builder, value, ""); } else if (typeDefinition instanceof CompoundDefinition) { // a compound type with a temporary native representation is a pointer which may or may not be null return LLVM.LLVMBuildIsNotNull(builder, value, ""); } } if (type instanceof NullType) { return LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 0, false); } if (type instanceof PrimitiveType) { return LLVM.LLVMBuildExtractValue(builder, value, 0, ""); } if (type instanceof TupleType) { return LLVM.LLVMBuildExtractValue(builder, value, 0, ""); } throw new IllegalArgumentException("Cannot build a null check for the unrecognised type: " + type); } /** * Builds the LLVM statements for an equality check between the specified two values, which are both of the specified type. * The equality check either checks whether the values are equal, or not equal, depending on the EqualityOperator provided. * @param left - the left LLVMValueRef in the comparison, in a temporary native representation * @param right - the right LLVMValueRef in the comparison, in a temporary native representation * @param type - the Type of both of the values - both of the values should be converted to this type before this function is called * @param operator - the EqualityOperator which determines which way to compare the values (e.g. EQUAL results in a 1 iff the values are equal) * @param llvmFunction - the LLVM Function that we are building this check in, this must be provided so that we can append basic blocks * @return an LLVMValueRef for an i1, which will be 1 if the check returns true, or 0 if the check returns false */ private LLVMValueRef buildEqualityCheck(LLVMValueRef left, LLVMValueRef right, Type type, EqualityOperator operator, LLVMValueRef llvmFunction) { if (type instanceof ArrayType) { return LLVM.LLVMBuildICmp(builder, getPredicate(operator, false), left, right, ""); } if (type instanceof FunctionType) { LLVMValueRef leftOpaque = LLVM.LLVMBuildExtractValue(builder, left, 0, ""); LLVMValueRef rightOpaque = LLVM.LLVMBuildExtractValue(builder, right, 0, ""); LLVMValueRef opaqueComparison = LLVM.LLVMBuildICmp(builder, getPredicate(operator, false), leftOpaque, rightOpaque, ""); LLVMValueRef leftFunction = LLVM.LLVMBuildExtractValue(builder, left, 1, ""); LLVMValueRef rightFunction = LLVM.LLVMBuildExtractValue(builder, right, 1, ""); LLVMValueRef functionComparison = LLVM.LLVMBuildICmp(builder, getPredicate(operator, false), leftFunction, rightFunction, ""); if (operator == EqualityOperator.EQUAL) { return LLVM.LLVMBuildAnd(builder, opaqueComparison, functionComparison, ""); } if (operator == EqualityOperator.NOT_EQUAL) { return LLVM.LLVMBuildOr(builder, opaqueComparison, functionComparison, ""); } throw new IllegalArgumentException("Cannot build an equality check without a valid EqualityOperator"); } if (type instanceof NamedType) { TypeDefinition typeDefinition = ((NamedType) type).getResolvedTypeDefinition(); if (typeDefinition instanceof ClassDefinition) { return LLVM.LLVMBuildICmp(builder, getPredicate(operator, false), left, right, ""); } if (typeDefinition instanceof CompoundDefinition) { // we don't want to compare anything if one of the compound definitions is null, so we need to branch and only compare them if they are both not-null LLVMValueRef nullityComparison = null; LLVMBasicBlockRef startBlock = null; LLVMBasicBlockRef finalBlock = null; if (type.isNullable()) { LLVMValueRef leftNullity = LLVM.LLVMBuildIsNotNull(builder, left, ""); LLVMValueRef rightNullity = LLVM.LLVMBuildIsNotNull(builder, right, ""); nullityComparison = LLVM.LLVMBuildICmp(builder, getPredicate(operator, false), leftNullity, rightNullity, ""); LLVMValueRef bothNotNull = LLVM.LLVMBuildAnd(builder, leftNullity, rightNullity, ""); startBlock = LLVM.LLVMGetInsertBlock(builder); LLVMBasicBlockRef comparisonBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "equality_comparevalues"); finalBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "equality_final"); LLVM.LLVMBuildCondBr(builder, bothNotNull, comparisonBlock, finalBlock); LLVM.LLVMPositionBuilderAtEnd(builder, comparisonBlock); } // compare each of the fields from the left and right values Field[] nonStaticFields = typeDefinition.getNonStaticFields(); LLVMValueRef[] compareResults = new LLVMValueRef[nonStaticFields.length]; for (int i = 0; i < nonStaticFields.length; ++i) { Type fieldType = nonStaticFields[i].getType(); LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), i, false)}; LLVMValueRef leftField = LLVM.LLVMBuildGEP(builder, left, C.toNativePointerArray(indices, false, true), indices.length, ""); LLVMValueRef rightField = LLVM.LLVMBuildGEP(builder, right, C.toNativePointerArray(indices, false, true), indices.length, ""); LLVMValueRef leftValue = LLVM.LLVMBuildLoad(builder, leftField, ""); LLVMValueRef rightValue = LLVM.LLVMBuildLoad(builder, rightField, ""); leftValue = typeHelper.convertStandardToTemporary(leftValue, fieldType, llvmFunction); rightValue = typeHelper.convertStandardToTemporary(rightValue, fieldType, llvmFunction); compareResults[i] = buildEqualityCheck(leftValue, rightValue, fieldType, operator, llvmFunction); } // AND or OR the list together, using a binary tree int multiple = 1; while (multiple < nonStaticFields.length) { for (int i = 0; i < nonStaticFields.length; i += 2 * multiple) { LLVMValueRef first = compareResults[i]; if (i + multiple >= nonStaticFields.length) { continue; } LLVMValueRef second = compareResults[i + multiple]; LLVMValueRef result = null; if (operator == EqualityOperator.EQUAL) { result = LLVM.LLVMBuildAnd(builder, first, second, ""); } else if (operator == EqualityOperator.NOT_EQUAL) { result = LLVM.LLVMBuildOr(builder, first, second, ""); } compareResults[i] = result; } multiple *= 2; } LLVMValueRef normalComparison = compareResults[0]; if (type.isNullable()) { LLVMBasicBlockRef endComparisonBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, finalBlock); LLVM.LLVMPositionBuilderAtEnd(builder, finalBlock); LLVMValueRef phiNode = LLVM.LLVMBuildPhi(builder, LLVM.LLVMInt1Type(), ""); LLVMValueRef[] incomingValues = new LLVMValueRef[] {nullityComparison, normalComparison}; LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {startBlock, endComparisonBlock}; LLVM.LLVMAddIncoming(phiNode, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), incomingValues.length); return phiNode; } return normalComparison; } } if (type instanceof PrimitiveType) { PrimitiveTypeType primitiveTypeType = ((PrimitiveType) type).getPrimitiveTypeType(); LLVMValueRef leftValue = left; LLVMValueRef rightValue = right; if (type.isNullable()) { leftValue = LLVM.LLVMBuildExtractValue(builder, left, 1, ""); rightValue = LLVM.LLVMBuildExtractValue(builder, right, 1, ""); } LLVMValueRef valueEqualityResult; if (primitiveTypeType.isFloating()) { valueEqualityResult = LLVM.LLVMBuildFCmp(builder, getPredicate(operator, true), leftValue, rightValue, ""); } else { valueEqualityResult = LLVM.LLVMBuildICmp(builder, getPredicate(operator, false), leftValue, rightValue, ""); } if (type.isNullable()) { LLVMValueRef leftNullity = LLVM.LLVMBuildExtractValue(builder, left, 0, ""); LLVMValueRef rightNullity = LLVM.LLVMBuildExtractValue(builder, right, 0, ""); LLVMValueRef bothNotNull = LLVM.LLVMBuildAnd(builder, leftNullity, rightNullity, ""); LLVMValueRef notNullAndValueResult = LLVM.LLVMBuildAnd(builder, bothNotNull, valueEqualityResult, ""); LLVMValueRef nullityComparison; if (operator == EqualityOperator.EQUAL) { nullityComparison = LLVM.LLVMBuildNot(builder, LLVM.LLVMBuildOr(builder, leftNullity, rightNullity, ""), ""); } else { nullityComparison = LLVM.LLVMBuildXor(builder, leftNullity, rightNullity, ""); } return LLVM.LLVMBuildOr(builder, notNullAndValueResult, nullityComparison, ""); } return valueEqualityResult; } if (type instanceof TupleType) { // we don't want to compare anything if one of the tuples is null, so we need to branch and only compare them if they are both not-null LLVMValueRef nullityComparison = null; LLVMBasicBlockRef startBlock = null; LLVMBasicBlockRef finalBlock = null; LLVMValueRef leftNotNull = left; LLVMValueRef rightNotNull = right; if (type.isNullable()) { LLVMValueRef leftNullity = LLVM.LLVMBuildExtractValue(builder, left, 0, ""); LLVMValueRef rightNullity = LLVM.LLVMBuildExtractValue(builder, right, 0, ""); nullityComparison = LLVM.LLVMBuildICmp(builder, getPredicate(operator, false), leftNullity, rightNullity, ""); LLVMValueRef bothNotNull = LLVM.LLVMBuildAnd(builder, leftNullity, rightNullity, ""); startBlock = LLVM.LLVMGetInsertBlock(builder); LLVMBasicBlockRef comparisonBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "equality_comparevalues"); finalBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "equality_final"); LLVM.LLVMBuildCondBr(builder, bothNotNull, comparisonBlock, finalBlock); LLVM.LLVMPositionBuilderAtEnd(builder, comparisonBlock); leftNotNull = LLVM.LLVMBuildExtractValue(builder, left, 1, ""); rightNotNull = LLVM.LLVMBuildExtractValue(builder, right, 1, ""); } // compare each of the fields from the left and right values Type[] subTypes = ((TupleType) type).getSubTypes(); LLVMValueRef[] compareResults = new LLVMValueRef[subTypes.length]; for (int i = 0; i < subTypes.length; ++i) { Type subType = subTypes[i]; LLVMValueRef leftValue = LLVM.LLVMBuildExtractValue(builder, leftNotNull, i, ""); LLVMValueRef rightValue = LLVM.LLVMBuildExtractValue(builder, rightNotNull, i, ""); compareResults[i] = buildEqualityCheck(leftValue, rightValue, subType, operator, llvmFunction); } // AND or OR the list together, using a binary tree int multiple = 1; while (multiple < subTypes.length) { for (int i = 0; i < subTypes.length; i += 2 * multiple) { LLVMValueRef first = compareResults[i]; if (i + multiple >= subTypes.length) { continue; } LLVMValueRef second = compareResults[i + multiple]; LLVMValueRef result = null; if (operator == EqualityOperator.EQUAL) { result = LLVM.LLVMBuildAnd(builder, first, second, ""); } else if (operator == EqualityOperator.NOT_EQUAL) { result = LLVM.LLVMBuildOr(builder, first, second, ""); } compareResults[i] = result; } multiple *= 2; } LLVMValueRef normalComparison = compareResults[0]; if (type.isNullable()) { LLVMBasicBlockRef endComparisonBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, finalBlock); LLVM.LLVMPositionBuilderAtEnd(builder, finalBlock); LLVMValueRef phiNode = LLVM.LLVMBuildPhi(builder, LLVM.LLVMInt1Type(), ""); LLVMValueRef[] incomingValues = new LLVMValueRef[] {nullityComparison, normalComparison}; LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {startBlock, endComparisonBlock}; LLVM.LLVMAddIncoming(phiNode, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), incomingValues.length); return phiNode; } return normalComparison; } throw new IllegalArgumentException("Cannot compare two values of type '" + type + "' for equality"); } private LLVMValueRef buildExpression(Expression expression, LLVMValueRef llvmFunction, LLVMValueRef thisValue, Map<Variable, LLVMValueRef> variables) { if (expression instanceof ArithmeticExpression) { ArithmeticExpression arithmeticExpression = (ArithmeticExpression) expression; LLVMValueRef left = buildExpression(arithmeticExpression.getLeftSubExpression(), llvmFunction, thisValue, variables); LLVMValueRef right = buildExpression(arithmeticExpression.getRightSubExpression(), llvmFunction, thisValue, variables); Type leftType = arithmeticExpression.getLeftSubExpression().getType(); Type rightType = arithmeticExpression.getRightSubExpression().getType(); Type resultType = arithmeticExpression.getType(); // cast if necessary left = typeHelper.convertTemporary(left, leftType, resultType); right = typeHelper.convertTemporary(right, rightType, resultType); if (arithmeticExpression.getOperator() == ArithmeticOperator.ADD && resultType.isEquivalent(SpecialTypeHandler.STRING_TYPE)) { // concatenate the strings // build an alloca in the entry block for the result of the concatenation LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMPositionBuilderAtStart(builder, LLVM.LLVMGetEntryBasicBlock(llvmFunction)); // find the type to alloca, which is the standard representation of a non-nullable version of this type // when we alloca this type, it becomes equivalent to the temporary type representation of this compound type (with any nullability) LLVMTypeRef allocaBaseType = typeHelper.findStandardType(new NamedType(false, false, SpecialTypeHandler.stringConcatenationConstructor.getContainingTypeDefinition())); LLVMValueRef alloca = LLVM.LLVMBuildAlloca(builder, allocaBaseType, ""); LLVM.LLVMPositionBuilderAtEnd(builder, currentBlock); typeHelper.initialiseCompoundType((CompoundDefinition) SpecialTypeHandler.stringConcatenationConstructor.getContainingTypeDefinition(), alloca); LLVMValueRef[] arguments = new LLVMValueRef[] {alloca, typeHelper.convertTemporaryToStandard(left, resultType, llvmFunction), typeHelper.convertTemporaryToStandard(right, resultType, llvmFunction)}; LLVMValueRef concatenationConstructor = getConstructorFunction(SpecialTypeHandler.stringConcatenationConstructor); LLVM.LLVMBuildCall(builder, concatenationConstructor, C.toNativePointerArray(arguments, false, true), arguments.length, ""); return typeHelper.convertTemporary(alloca, new NamedType(false, false, SpecialTypeHandler.stringConcatenationConstructor.getContainingTypeDefinition()), resultType); } boolean floating = ((PrimitiveType) resultType).getPrimitiveTypeType().isFloating(); boolean signed = ((PrimitiveType) resultType).getPrimitiveTypeType().isSigned(); switch (arithmeticExpression.getOperator()) { case ADD: return floating ? LLVM.LLVMBuildFAdd(builder, left, right, "") : LLVM.LLVMBuildAdd(builder, left, right, ""); case SUBTRACT: return floating ? LLVM.LLVMBuildFSub(builder, left, right, "") : LLVM.LLVMBuildSub(builder, left, right, ""); case MULTIPLY: return floating ? LLVM.LLVMBuildFMul(builder, left, right, "") : LLVM.LLVMBuildMul(builder, left, right, ""); case DIVIDE: return floating ? LLVM.LLVMBuildFDiv(builder, left, right, "") : signed ? LLVM.LLVMBuildSDiv(builder, left, right, "") : LLVM.LLVMBuildUDiv(builder, left, right, ""); case REMAINDER: return floating ? LLVM.LLVMBuildFRem(builder, left, right, "") : signed ? LLVM.LLVMBuildSRem(builder, left, right, "") : LLVM.LLVMBuildURem(builder, left, right, ""); case MODULO: if (floating) { LLVMValueRef rem = LLVM.LLVMBuildFRem(builder, left, right, ""); LLVMValueRef add = LLVM.LLVMBuildFAdd(builder, rem, right, ""); return LLVM.LLVMBuildFRem(builder, add, right, ""); } if (signed) { LLVMValueRef rem = LLVM.LLVMBuildSRem(builder, left, right, ""); LLVMValueRef add = LLVM.LLVMBuildAdd(builder, rem, right, ""); return LLVM.LLVMBuildSRem(builder, add, right, ""); } // unsigned modulo is the same as unsigned remainder return LLVM.LLVMBuildURem(builder, left, right, ""); } throw new IllegalArgumentException("Unknown arithmetic operator: " + arithmeticExpression.getOperator()); } if (expression instanceof ArrayAccessExpression) { ArrayAccessExpression arrayAccessExpression = (ArrayAccessExpression) expression; LLVMValueRef arrayValue = buildExpression(arrayAccessExpression.getArrayExpression(), llvmFunction, thisValue, variables); LLVMValueRef dimensionValue = buildExpression(arrayAccessExpression.getDimensionExpression(), llvmFunction, thisValue, variables); LLVMValueRef convertedDimensionValue = typeHelper.convertTemporaryToStandard(dimensionValue, arrayAccessExpression.getDimensionExpression().getType(), ArrayLengthMember.ARRAY_LENGTH_TYPE, llvmFunction); LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false), convertedDimensionValue}; LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, arrayValue, C.toNativePointerArray(indices, false, true), indices.length, ""); ArrayType arrayType = (ArrayType) arrayAccessExpression.getArrayExpression().getType(); return typeHelper.convertStandardPointerToTemporary(elementPointer, arrayType.getBaseType(), arrayAccessExpression.getType(), llvmFunction); } if (expression instanceof ArrayCreationExpression) { ArrayCreationExpression arrayCreationExpression = (ArrayCreationExpression) expression; ArrayType type = arrayCreationExpression.getDeclaredType(); Expression[] dimensionExpressions = arrayCreationExpression.getDimensionExpressions(); if (dimensionExpressions == null) { Expression[] valueExpressions = arrayCreationExpression.getValueExpressions(); LLVMValueRef llvmLength = LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), valueExpressions.length, false); LLVMValueRef array = buildArrayCreation(llvmFunction, new LLVMValueRef[] {llvmLength}, type); for (int i = 0; i < valueExpressions.length; i++) { LLVMValueRef expressionValue = buildExpression(valueExpressions[i], llvmFunction, thisValue, variables); LLVMValueRef convertedValue = typeHelper.convertTemporaryToStandard(expressionValue, valueExpressions[i].getType(), type.getBaseType(), llvmFunction); LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), i, false)}; LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, array, C.toNativePointerArray(indices, false, true), indices.length, ""); LLVM.LLVMBuildStore(builder, convertedValue, elementPointer); } return typeHelper.convertTemporary(array, type, arrayCreationExpression.getType()); } LLVMValueRef[] llvmLengths = new LLVMValueRef[dimensionExpressions.length]; for (int i = 0; i < llvmLengths.length; i++) { LLVMValueRef expressionValue = buildExpression(dimensionExpressions[i], llvmFunction, thisValue, variables); llvmLengths[i] = typeHelper.convertTemporaryToStandard(expressionValue, dimensionExpressions[i].getType(), ArrayLengthMember.ARRAY_LENGTH_TYPE, llvmFunction); } LLVMValueRef array = buildArrayCreation(llvmFunction, llvmLengths, type); return typeHelper.convertTemporary(array, type, arrayCreationExpression.getType()); } if (expression instanceof BitwiseNotExpression) { LLVMValueRef value = buildExpression(((BitwiseNotExpression) expression).getExpression(), llvmFunction, thisValue, variables); value = typeHelper.convertTemporary(value, ((BitwiseNotExpression) expression).getExpression().getType(), expression.getType()); return LLVM.LLVMBuildNot(builder, value, ""); } if (expression instanceof BooleanLiteralExpression) { LLVMValueRef value = LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), ((BooleanLiteralExpression) expression).getValue() ? 1 : 0, false); return typeHelper.convertStandardToTemporary(value, new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null), expression.getType(), llvmFunction); } if (expression instanceof BooleanNotExpression) { LLVMValueRef value = buildExpression(((BooleanNotExpression) expression).getExpression(), llvmFunction, thisValue, variables); LLVMValueRef result = LLVM.LLVMBuildNot(builder, value, ""); return typeHelper.convertTemporary(result, ((BooleanNotExpression) expression).getExpression().getType(), expression.getType()); } if (expression instanceof BracketedExpression) { BracketedExpression bracketedExpression = (BracketedExpression) expression; LLVMValueRef value = buildExpression(bracketedExpression.getExpression(), llvmFunction, thisValue, variables); return typeHelper.convertTemporary(value, bracketedExpression.getExpression().getType(), expression.getType()); } if (expression instanceof CastExpression) { CastExpression castExpression = (CastExpression) expression; LLVMValueRef value = buildExpression(castExpression.getExpression(), llvmFunction, thisValue, variables); return typeHelper.convertTemporary(value, castExpression.getExpression().getType(), castExpression.getType()); } if (expression instanceof ClassCreationExpression) { ClassCreationExpression classCreationExpression = (ClassCreationExpression) expression; Expression[] arguments = classCreationExpression.getArguments(); Constructor constructor = classCreationExpression.getResolvedConstructor(); Parameter[] parameters = constructor.getParameters(); LLVMValueRef[] llvmArguments = new LLVMValueRef[1 + arguments.length]; for (int i = 0; i < arguments.length; ++i) { LLVMValueRef argument = buildExpression(arguments[i], llvmFunction, thisValue, variables); llvmArguments[i + 1] = typeHelper.convertTemporaryToStandard(argument, arguments[i].getType(), parameters[i].getType(), llvmFunction); } Type type = classCreationExpression.getType(); LLVMTypeRef nativeType = typeHelper.findTemporaryType(type); LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false)}; LLVMValueRef llvmStructSize = LLVM.LLVMBuildGEP(builder, LLVM.LLVMConstNull(nativeType), C.toNativePointerArray(indices, false, true), indices.length, ""); LLVMValueRef llvmSize = LLVM.LLVMBuildPtrToInt(builder, llvmStructSize, LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), ""); LLVMValueRef[] callocArguments = new LLVMValueRef[] {llvmSize, LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false)}; LLVMValueRef memory = LLVM.LLVMBuildCall(builder, callocFunction, C.toNativePointerArray(callocArguments, false, true), callocArguments.length, ""); LLVMValueRef pointer = LLVM.LLVMBuildBitCast(builder, memory, nativeType, ""); llvmArguments[0] = pointer; // get the constructor and call it LLVMValueRef llvmFunc = getConstructorFunction(constructor); - LLVMValueRef result = LLVM.LLVMBuildCall(builder, llvmFunc, C.toNativePointerArray(llvmArguments, false, true), llvmArguments.length, ""); - return result; + LLVM.LLVMBuildCall(builder, llvmFunc, C.toNativePointerArray(llvmArguments, false, true), llvmArguments.length, ""); + return pointer; } if (expression instanceof EqualityExpression) { EqualityExpression equalityExpression = (EqualityExpression) expression; EqualityOperator operator = equalityExpression.getOperator(); // if the type checker has annotated this as a null check, just perform it without building both sub-expressions Expression nullCheckExpression = equalityExpression.getNullCheckExpression(); if (nullCheckExpression != null) { LLVMValueRef value = buildExpression(nullCheckExpression, llvmFunction, thisValue, variables); LLVMValueRef convertedValue = typeHelper.convertTemporary(value, nullCheckExpression.getType(), equalityExpression.getComparisonType()); LLVMValueRef nullity = buildNullCheck(convertedValue, equalityExpression.getComparisonType()); switch (operator) { case EQUAL: return LLVM.LLVMBuildNot(builder, nullity, ""); case NOT_EQUAL: return nullity; default: throw new IllegalArgumentException("Cannot build an EqualityExpression with no EqualityOperator"); } } LLVMValueRef left = buildExpression(equalityExpression.getLeftSubExpression(), llvmFunction, thisValue, variables); LLVMValueRef right = buildExpression(equalityExpression.getRightSubExpression(), llvmFunction, thisValue, variables); Type leftType = equalityExpression.getLeftSubExpression().getType(); Type rightType = equalityExpression.getRightSubExpression().getType(); Type comparisonType = equalityExpression.getComparisonType(); // if comparisonType is null, then the types are integers which cannot be assigned to each other either way around, because one is signed and the other is unsigned // so we must extend each of them to a larger bitCount which they can both fit into, and compare them there if (comparisonType == null) { if (!(leftType instanceof PrimitiveType) || !(rightType instanceof PrimitiveType)) { throw new IllegalStateException("A comparison type must be provided if either the left or right type is not a PrimitiveType: " + equalityExpression); } LLVMValueRef leftIsNotNull = LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 1, false); LLVMValueRef rightIsNotNull = LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 1, false); LLVMValueRef leftValue = left; LLVMValueRef rightValue = right; if (leftType.isNullable()) { leftIsNotNull = LLVM.LLVMBuildExtractValue(builder, left, 0, ""); leftValue = LLVM.LLVMBuildExtractValue(builder, left, 1, ""); } if (rightType.isNullable()) { rightIsNotNull = LLVM.LLVMBuildExtractValue(builder, right, 0, ""); rightValue = LLVM.LLVMBuildExtractValue(builder, right, 1, ""); } PrimitiveTypeType leftTypeType = ((PrimitiveType) leftType).getPrimitiveTypeType(); PrimitiveTypeType rightTypeType = ((PrimitiveType) rightType).getPrimitiveTypeType(); if (!leftTypeType.isFloating() && !rightTypeType.isFloating() && leftTypeType.isSigned() != rightTypeType.isSigned()) { // compare the signed and non-signed integers as (bitCount + 1) bit numbers, since they will not fit in bitCount bits int bitCount = Math.max(leftTypeType.getBitCount(), rightTypeType.getBitCount()) + 1; LLVMTypeRef llvmComparisonType = LLVM.LLVMIntType(bitCount); if (leftTypeType.isSigned()) { leftValue = LLVM.LLVMBuildSExt(builder, leftValue, llvmComparisonType, ""); rightValue = LLVM.LLVMBuildZExt(builder, rightValue, llvmComparisonType, ""); } else { leftValue = LLVM.LLVMBuildZExt(builder, leftValue, llvmComparisonType, ""); rightValue = LLVM.LLVMBuildSExt(builder, rightValue, llvmComparisonType, ""); } LLVMValueRef comparisonResult = LLVM.LLVMBuildICmp(builder, getPredicate(equalityExpression.getOperator(), false), leftValue, rightValue, ""); if (leftType.isNullable() || rightType.isNullable()) { LLVMValueRef nullityComparison = LLVM.LLVMBuildICmp(builder, getPredicate(equalityExpression.getOperator(), false), leftIsNotNull, rightIsNotNull, ""); if (equalityExpression.getOperator() == EqualityOperator.EQUAL) { comparisonResult = LLVM.LLVMBuildAnd(builder, nullityComparison, comparisonResult, ""); } else { comparisonResult = LLVM.LLVMBuildOr(builder, nullityComparison, comparisonResult, ""); } } return typeHelper.convertTemporary(comparisonResult, new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null), equalityExpression.getType()); } throw new IllegalArgumentException("Unknown result type, unable to generate comparison expression: " + equalityExpression); } // perform a standard equality check, using buildEqualityCheck() left = typeHelper.convertTemporary(left, leftType, comparisonType); right = typeHelper.convertTemporary(right, rightType, comparisonType); return buildEqualityCheck(left, right, comparisonType, operator, llvmFunction); } if (expression instanceof FieldAccessExpression) { FieldAccessExpression fieldAccessExpression = (FieldAccessExpression) expression; Member member = fieldAccessExpression.getResolvedMember(); Expression baseExpression = fieldAccessExpression.getBaseExpression(); if (baseExpression != null) { LLVMValueRef baseValue = buildExpression(baseExpression, llvmFunction, thisValue, variables); LLVMValueRef notNullValue = baseValue; LLVMBasicBlockRef startBlock = null; LLVMBasicBlockRef continuationBlock = null; if (fieldAccessExpression.isNullTraversing()) { LLVMValueRef nullCheckResult = buildNullCheck(baseValue, baseExpression.getType()); LLVMBasicBlockRef accessBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "nullTraversalAccess"); continuationBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "nullTraversalContinuation"); startBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildCondBr(builder, nullCheckResult, accessBlock, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, accessBlock); notNullValue = typeHelper.convertTemporary(baseValue, baseExpression.getType(), TypeChecker.findTypeWithNullability(baseExpression.getType(), false)); } LLVMValueRef result; if (member instanceof ArrayLengthMember) { LLVMValueRef array = notNullValue; LLVMValueRef[] sizeIndices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false)}; LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, array, C.toNativePointerArray(sizeIndices, false, true), sizeIndices.length, ""); result = LLVM.LLVMBuildLoad(builder, elementPointer, ""); result = typeHelper.convertStandardToTemporary(result, ArrayLengthMember.ARRAY_LENGTH_TYPE, fieldAccessExpression.getType(), llvmFunction); } else if (member instanceof Field) { Field field = (Field) member; if (field.isStatic()) { throw new IllegalStateException("A FieldAccessExpression for a static field should not have a base expression"); } LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), field.getMemberIndex(), false)}; LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, notNullValue, C.toNativePointerArray(indices, false, true), indices.length, ""); result = typeHelper.convertStandardPointerToTemporary(elementPointer, field.getType(), fieldAccessExpression.getType(), llvmFunction); } else if (member instanceof Method) { Method method = (Method) member; Parameter[] parameters = method.getParameters(); Type[] parameterTypes = new Type[parameters.length]; for (int i = 0; i < parameters.length; ++i) { parameterTypes[i] = parameters[i].getType(); } FunctionType functionType = new FunctionType(false, method.isImmutable(), method.getReturnType(), parameterTypes, null); if (method.isStatic()) { throw new IllegalStateException("A FieldAccessExpression for a static method should not have a base expression"); } LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder); LLVMValueRef function = getMethodFunction(method); LLVM.LLVMPositionBuilderAtEnd(builder, currentBlock); function = LLVM.LLVMBuildBitCast(builder, function, typeHelper.findRawFunctionPointerType(functionType), ""); LLVMValueRef firstArgument = LLVM.LLVMBuildBitCast(builder, notNullValue, typeHelper.getOpaquePointer(), ""); result = LLVM.LLVMGetUndef(typeHelper.findStandardType(functionType)); result = LLVM.LLVMBuildInsertValue(builder, result, firstArgument, 0, ""); result = LLVM.LLVMBuildInsertValue(builder, result, function, 1, ""); result = typeHelper.convertStandardToTemporary(result, functionType, fieldAccessExpression.getType(), llvmFunction); } else { throw new IllegalArgumentException("Unknown member type for a FieldAccessExpression: " + member); } if (fieldAccessExpression.isNullTraversing()) { LLVMBasicBlockRef accessBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); LLVMValueRef phiNode = LLVM.LLVMBuildPhi(builder, typeHelper.findTemporaryType(fieldAccessExpression.getType()), ""); LLVMValueRef nullAlternative = LLVM.LLVMConstNull(typeHelper.findTemporaryType(fieldAccessExpression.getType())); LLVMValueRef[] phiValues = new LLVMValueRef[] {result, nullAlternative}; LLVMBasicBlockRef[] phiBlocks = new LLVMBasicBlockRef[] {accessBlock, startBlock}; LLVM.LLVMAddIncoming(phiNode, C.toNativePointerArray(phiValues, false, true), C.toNativePointerArray(phiBlocks, false, true), phiValues.length); return phiNode; } return result; } // we don't have a base expression, so handle the static field accesses if (member instanceof Field) { Field field = (Field) member; if (!field.isStatic()) { throw new IllegalStateException("A FieldAccessExpression for a non-static field should have a base expression"); } LLVMValueRef global = getGlobal(field.getGlobalVariable()); return typeHelper.convertStandardPointerToTemporary(global, field.getType(), fieldAccessExpression.getType(), llvmFunction); } if (member instanceof Method) { Method method = (Method) member; if (!method.isStatic()) { throw new IllegalStateException("A FieldAccessExpression for a non-static method should have a base expression"); } Parameter[] parameters = method.getParameters(); Type[] parameterTypes = new Type[parameters.length]; for (int i = 0; i < parameters.length; ++i) { parameterTypes[i] = parameters[i].getType(); } FunctionType functionType = new FunctionType(false, method.isImmutable(), method.getReturnType(), parameterTypes, null); LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder); LLVMValueRef function = getMethodFunction(method); LLVM.LLVMPositionBuilderAtEnd(builder, currentBlock); function = LLVM.LLVMBuildBitCast(builder, function, typeHelper.findRawFunctionPointerType(functionType), ""); LLVMValueRef firstArgument = LLVM.LLVMConstNull(typeHelper.getOpaquePointer()); LLVMValueRef result = LLVM.LLVMGetUndef(typeHelper.findStandardType(functionType)); result = LLVM.LLVMBuildInsertValue(builder, result, firstArgument, 0, ""); result = LLVM.LLVMBuildInsertValue(builder, result, function, 1, ""); return typeHelper.convertStandardToTemporary(result, functionType, fieldAccessExpression.getType(), llvmFunction); } throw new IllegalArgumentException("Unknown member type for a FieldAccessExpression: " + member); } if (expression instanceof FloatingLiteralExpression) { double value = Double.parseDouble(((FloatingLiteralExpression) expression).getLiteral().toString()); LLVMValueRef llvmValue = LLVM.LLVMConstReal(typeHelper.findStandardType(TypeChecker.findTypeWithNullability(expression.getType(), false)), value); return typeHelper.convertStandardToTemporary(llvmValue, TypeChecker.findTypeWithNullability(expression.getType(), false), expression.getType(), llvmFunction); } if (expression instanceof FunctionCallExpression) { FunctionCallExpression functionExpression = (FunctionCallExpression) expression; Constructor resolvedConstructor = functionExpression.getResolvedConstructor(); Method resolvedMethod = functionExpression.getResolvedMethod(); Expression resolvedBaseExpression = functionExpression.getResolvedBaseExpression(); Type[] parameterTypes; Type returnType; LLVMValueRef llvmResolvedFunction; if (resolvedConstructor != null) { Parameter[] params = resolvedConstructor.getParameters(); parameterTypes = new Type[params.length]; for (int i = 0; i < params.length; ++i) { parameterTypes[i] = params[i].getType(); } returnType = new NamedType(false, false, resolvedConstructor.getContainingTypeDefinition()); llvmResolvedFunction = getConstructorFunction(resolvedConstructor); } else if (resolvedMethod != null) { Parameter[] params = resolvedMethod.getParameters(); parameterTypes = new Type[params.length]; for (int i = 0; i < params.length; ++i) { parameterTypes[i] = params[i].getType(); } returnType = resolvedMethod.getReturnType(); LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder); llvmResolvedFunction = getMethodFunction(resolvedMethod); LLVM.LLVMPositionBuilderAtEnd(builder, currentBlock); } else if (resolvedBaseExpression != null) { FunctionType baseType = (FunctionType) resolvedBaseExpression.getType(); parameterTypes = baseType.getParameterTypes(); returnType = baseType.getReturnType(); llvmResolvedFunction = null; } else { throw new IllegalArgumentException("Unresolved function call expression: " + functionExpression); } LLVMValueRef callee = null; if (resolvedBaseExpression != null) { callee = buildExpression(resolvedBaseExpression, llvmFunction, thisValue, variables); } // if this is a null traversing function call, apply it properly boolean nullTraversal = resolvedBaseExpression != null && resolvedMethod != null && functionExpression.getResolvedNullTraversal(); LLVMValueRef notNullCallee = callee; LLVMBasicBlockRef startBlock = null; LLVMBasicBlockRef continuationBlock = null; if (nullTraversal) { LLVMValueRef nullCheckResult = buildNullCheck(callee, resolvedBaseExpression.getType()); LLVMBasicBlockRef callBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "nullTraversalCall"); continuationBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "nullTraversalCallContinuation"); startBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildCondBr(builder, nullCheckResult, callBlock, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, callBlock); notNullCallee = typeHelper.convertTemporary(callee, resolvedBaseExpression.getType(), TypeChecker.findTypeWithNullability(resolvedBaseExpression.getType(), false)); } Expression[] arguments = functionExpression.getArguments(); LLVMValueRef[] values = new LLVMValueRef[arguments.length]; for (int i = 0; i < arguments.length; i++) { LLVMValueRef arg = buildExpression(arguments[i], llvmFunction, thisValue, variables); values[i] = typeHelper.convertTemporaryToStandard(arg, arguments[i].getType(), parameterTypes[i], llvmFunction); } LLVMValueRef result; boolean resultIsTemporary = false; // true iff result has a temporary type representation if (resolvedConstructor != null) { // build an alloca in the entry block for the result of the constructor call LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMPositionBuilderAtStart(builder, LLVM.LLVMGetEntryBasicBlock(llvmFunction)); // find the type to alloca, which is the standard representation of a non-nullable type // when we alloca this type, it becomes equivalent to the temporary type representation of this compound type (with any nullability) LLVMTypeRef allocaBaseType = typeHelper.findStandardType(returnType); LLVMValueRef alloca = LLVM.LLVMBuildAlloca(builder, allocaBaseType, ""); LLVM.LLVMPositionBuilderAtEnd(builder, currentBlock); typeHelper.initialiseCompoundType((CompoundDefinition) ((NamedType) returnType).getResolvedTypeDefinition(), alloca); LLVMValueRef[] realArguments = new LLVMValueRef[1 + values.length]; realArguments[0] = alloca; System.arraycopy(values, 0, realArguments, 1, values.length); LLVM.LLVMBuildCall(builder, llvmResolvedFunction, C.toNativePointerArray(realArguments, false, true), realArguments.length, ""); result = alloca; resultIsTemporary = true; } else if (resolvedMethod != null) { LLVMValueRef[] realArguments = new LLVMValueRef[values.length + 1]; if (resolvedMethod.isStatic()) { realArguments[0] = LLVM.LLVMConstNull(typeHelper.getOpaquePointer()); } else { realArguments[0] = notNullCallee != null ? notNullCallee : thisValue; } System.arraycopy(values, 0, realArguments, 1, values.length); result = LLVM.LLVMBuildCall(builder, llvmResolvedFunction, C.toNativePointerArray(realArguments, false, true), realArguments.length, ""); } else if (resolvedBaseExpression != null) { // callee here is actually a tuple of an opaque pointer and a function type, where the first argument to the function is the opaque pointer LLVMValueRef firstArgument = LLVM.LLVMBuildExtractValue(builder, callee, 0, ""); LLVMValueRef calleeFunction = LLVM.LLVMBuildExtractValue(builder, callee, 1, ""); LLVMValueRef[] realArguments = new LLVMValueRef[values.length + 1]; realArguments[0] = firstArgument; System.arraycopy(values, 0, realArguments, 1, values.length); result = LLVM.LLVMBuildCall(builder, calleeFunction, C.toNativePointerArray(realArguments, false, true), realArguments.length, ""); } else { throw new IllegalArgumentException("Unresolved function call expression: " + functionExpression); } if (nullTraversal) { if (returnType instanceof VoidType) { LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); return null; } if (resultIsTemporary) { result = typeHelper.convertTemporary(result, returnType, functionExpression.getType()); } else { result = typeHelper.convertStandardToTemporary(result, returnType, functionExpression.getType(), llvmFunction); } LLVMBasicBlockRef callBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); LLVMValueRef phiNode = LLVM.LLVMBuildPhi(builder, typeHelper.findTemporaryType(functionExpression.getType()), ""); LLVMValueRef nullAlternative = LLVM.LLVMConstNull(typeHelper.findTemporaryType(functionExpression.getType())); LLVMValueRef[] phiValues = new LLVMValueRef[] {result, nullAlternative}; LLVMBasicBlockRef[] phiBlocks = new LLVMBasicBlockRef[] {callBlock, startBlock}; LLVM.LLVMAddIncoming(phiNode, C.toNativePointerArray(phiValues, false, true), C.toNativePointerArray(phiBlocks, false, true), phiValues.length); return phiNode; } if (returnType instanceof VoidType) { return result; } if (resultIsTemporary) { return typeHelper.convertTemporary(result, returnType, functionExpression.getType()); } return typeHelper.convertStandardToTemporary(result, returnType, functionExpression.getType(), llvmFunction); } if (expression instanceof InlineIfExpression) { InlineIfExpression inlineIf = (InlineIfExpression) expression; LLVMValueRef conditionValue = buildExpression(inlineIf.getCondition(), llvmFunction, thisValue, variables); conditionValue = typeHelper.convertTemporaryToStandard(conditionValue, inlineIf.getCondition().getType(), new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null), llvmFunction); LLVMBasicBlockRef thenBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "inlineIfThen"); LLVMBasicBlockRef elseBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "inlineIfElse"); LLVMBasicBlockRef continuationBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "afterInlineIf"); LLVM.LLVMBuildCondBr(builder, conditionValue, thenBlock, elseBlock); LLVM.LLVMPositionBuilderAtEnd(builder, thenBlock); LLVMValueRef thenValue = buildExpression(inlineIf.getThenExpression(), llvmFunction, thisValue, variables); LLVMValueRef convertedThenValue = typeHelper.convertTemporary(thenValue, inlineIf.getThenExpression().getType(), inlineIf.getType()); LLVMBasicBlockRef thenBranchBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, elseBlock); LLVMValueRef elseValue = buildExpression(inlineIf.getElseExpression(), llvmFunction, thisValue, variables); LLVMValueRef convertedElseValue = typeHelper.convertTemporary(elseValue, inlineIf.getElseExpression().getType(), inlineIf.getType()); LLVMBasicBlockRef elseBranchBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); LLVMValueRef result = LLVM.LLVMBuildPhi(builder, typeHelper.findTemporaryType(inlineIf.getType()), ""); LLVMValueRef[] incomingValues = new LLVMValueRef[] {convertedThenValue, convertedElseValue}; LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {thenBranchBlock, elseBranchBlock}; LLVM.LLVMAddIncoming(result, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), 2); return result; } if (expression instanceof IntegerLiteralExpression) { BigInteger bigintValue = ((IntegerLiteralExpression) expression).getLiteral().getValue(); byte[] bytes = bigintValue.toByteArray(); // convert the big-endian byte[] from the BigInteger into a little-endian long[] for LLVM long[] longs = new long[(bytes.length + 7) / 8]; for (int i = 0; i < bytes.length; ++i) { int longIndex = (bytes.length - 1 - i) / 8; int longBitPos = ((bytes.length - 1 - i) % 8) * 8; longs[longIndex] |= (((long) bytes[i]) & 0xff) << longBitPos; } LLVMValueRef value = LLVM.LLVMConstIntOfArbitraryPrecision(typeHelper.findStandardType(TypeChecker.findTypeWithNullability(expression.getType(), false)), longs.length, longs); return typeHelper.convertStandardToTemporary(value, TypeChecker.findTypeWithNullability(expression.getType(), false), expression.getType(), llvmFunction); } if (expression instanceof LogicalExpression) { LogicalExpression logicalExpression = (LogicalExpression) expression; LLVMValueRef left = buildExpression(logicalExpression.getLeftSubExpression(), llvmFunction, thisValue, variables); PrimitiveType leftType = (PrimitiveType) logicalExpression.getLeftSubExpression().getType(); PrimitiveType rightType = (PrimitiveType) logicalExpression.getRightSubExpression().getType(); // cast if necessary PrimitiveType resultType = (PrimitiveType) logicalExpression.getType(); left = typeHelper.convertTemporary(left, leftType, resultType); LogicalOperator operator = logicalExpression.getOperator(); if (operator != LogicalOperator.SHORT_CIRCUIT_AND && operator != LogicalOperator.SHORT_CIRCUIT_OR) { LLVMValueRef right = buildExpression(logicalExpression.getRightSubExpression(), llvmFunction, thisValue, variables); right = typeHelper.convertTemporary(right, rightType, resultType); switch (operator) { case AND: return LLVM.LLVMBuildAnd(builder, left, right, ""); case OR: return LLVM.LLVMBuildOr(builder, left, right, ""); case XOR: return LLVM.LLVMBuildXor(builder, left, right, ""); default: throw new IllegalStateException("Unexpected non-short-circuit operator: " + logicalExpression.getOperator()); } } LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder); LLVMBasicBlockRef rightCheckBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "shortCircuitCheck"); LLVMBasicBlockRef continuationBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "shortCircuitContinue"); // the only difference between short circuit AND and OR is whether they jump to the check block when the left hand side is true or false LLVMBasicBlockRef trueDest = operator == LogicalOperator.SHORT_CIRCUIT_AND ? rightCheckBlock : continuationBlock; LLVMBasicBlockRef falseDest = operator == LogicalOperator.SHORT_CIRCUIT_AND ? continuationBlock : rightCheckBlock; LLVM.LLVMBuildCondBr(builder, left, trueDest, falseDest); LLVM.LLVMPositionBuilderAtEnd(builder, rightCheckBlock); LLVMValueRef right = buildExpression(logicalExpression.getRightSubExpression(), llvmFunction, thisValue, variables); right = typeHelper.convertTemporary(right, rightType, resultType); LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); // create a phi node for the result, and return it LLVMValueRef phi = LLVM.LLVMBuildPhi(builder, typeHelper.findTemporaryType(resultType), ""); LLVMValueRef[] incomingValues = new LLVMValueRef[] {left, right}; LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {currentBlock, rightCheckBlock}; LLVM.LLVMAddIncoming(phi, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), 2); return phi; } if (expression instanceof MinusExpression) { MinusExpression minusExpression = (MinusExpression) expression; LLVMValueRef value = buildExpression(minusExpression.getExpression(), llvmFunction, thisValue, variables); value = typeHelper.convertTemporary(value, minusExpression.getExpression().getType(), TypeChecker.findTypeWithNullability(minusExpression.getType(), false)); PrimitiveTypeType primitiveTypeType = ((PrimitiveType) minusExpression.getType()).getPrimitiveTypeType(); LLVMValueRef result; if (primitiveTypeType.isFloating()) { result = LLVM.LLVMBuildFNeg(builder, value, ""); } else { result = LLVM.LLVMBuildNeg(builder, value, ""); } return typeHelper.convertTemporary(result, TypeChecker.findTypeWithNullability(minusExpression.getType(), false), minusExpression.getType()); } if (expression instanceof NullCoalescingExpression) { NullCoalescingExpression nullCoalescingExpression = (NullCoalescingExpression) expression; LLVMValueRef nullableValue = buildExpression(nullCoalescingExpression.getNullableExpression(), llvmFunction, thisValue, variables); nullableValue = typeHelper.convertTemporary(nullableValue, nullCoalescingExpression.getNullableExpression().getType(), TypeChecker.findTypeWithNullability(nullCoalescingExpression.getType(), true)); LLVMValueRef checkResult = buildNullCheck(nullableValue, TypeChecker.findTypeWithNullability(nullCoalescingExpression.getType(), true)); LLVMBasicBlockRef conversionBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "nullCoalescingConversion"); LLVMBasicBlockRef alternativeBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "nullCoalescingAlternative"); LLVMBasicBlockRef continuationBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "nullCoalescingContinuation"); LLVM.LLVMBuildCondBr(builder, checkResult, conversionBlock, alternativeBlock); // create a block to convert the nullable value into a non-nullable value LLVM.LLVMPositionBuilderAtEnd(builder, conversionBlock); LLVMValueRef convertedNullableValue = typeHelper.convertTemporary(nullableValue, TypeChecker.findTypeWithNullability(nullCoalescingExpression.getType(), true), nullCoalescingExpression.getType()); LLVMBasicBlockRef endConversionBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, alternativeBlock); LLVMValueRef alternativeValue = buildExpression(nullCoalescingExpression.getAlternativeExpression(), llvmFunction, thisValue, variables); alternativeValue = typeHelper.convertTemporary(alternativeValue, nullCoalescingExpression.getAlternativeExpression().getType(), nullCoalescingExpression.getType()); LLVMBasicBlockRef endAlternativeBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); // create a phi node for the result, and return it LLVMTypeRef resultType = typeHelper.findTemporaryType(nullCoalescingExpression.getType()); LLVMValueRef result = LLVM.LLVMBuildPhi(builder, resultType, ""); LLVMValueRef[] incomingValues = new LLVMValueRef[] {convertedNullableValue, alternativeValue}; LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {endConversionBlock, endAlternativeBlock}; LLVM.LLVMAddIncoming(result, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), incomingValues.length); return result; } if (expression instanceof NullLiteralExpression) { Type type = expression.getType(); return LLVM.LLVMConstNull(typeHelper.findTemporaryType(type)); } if (expression instanceof RelationalExpression) { RelationalExpression relationalExpression = (RelationalExpression) expression; LLVMValueRef left = buildExpression(relationalExpression.getLeftSubExpression(), llvmFunction, thisValue, variables); LLVMValueRef right = buildExpression(relationalExpression.getRightSubExpression(), llvmFunction, thisValue, variables); PrimitiveType leftType = (PrimitiveType) relationalExpression.getLeftSubExpression().getType(); PrimitiveType rightType = (PrimitiveType) relationalExpression.getRightSubExpression().getType(); // cast if necessary PrimitiveType resultType = relationalExpression.getComparisonType(); if (resultType == null) { PrimitiveTypeType leftTypeType = leftType.getPrimitiveTypeType(); PrimitiveTypeType rightTypeType = rightType.getPrimitiveTypeType(); if (!leftTypeType.isFloating() && !rightTypeType.isFloating() && leftTypeType.isSigned() != rightTypeType.isSigned() && !leftType.isNullable() && !rightType.isNullable()) { // compare the signed and non-signed integers as (bitCount + 1) bit numbers, since they will not fit in bitCount bits int bitCount = Math.max(leftTypeType.getBitCount(), rightTypeType.getBitCount()) + 1; LLVMTypeRef comparisonType = LLVM.LLVMIntType(bitCount); if (leftTypeType.isSigned()) { left = LLVM.LLVMBuildSExt(builder, left, comparisonType, ""); right = LLVM.LLVMBuildZExt(builder, right, comparisonType, ""); } else { left = LLVM.LLVMBuildZExt(builder, left, comparisonType, ""); right = LLVM.LLVMBuildSExt(builder, right, comparisonType, ""); } return LLVM.LLVMBuildICmp(builder, getPredicate(relationalExpression.getOperator(), false, true), left, right, ""); } throw new IllegalArgumentException("Unknown result type, unable to generate comparison expression: " + expression); } left = typeHelper.convertTemporary(left, leftType, resultType); right = typeHelper.convertTemporary(right, rightType, resultType); LLVMValueRef result; if (resultType.getPrimitiveTypeType().isFloating()) { result = LLVM.LLVMBuildFCmp(builder, getPredicate(relationalExpression.getOperator(), true, true), left, right, ""); } else { result = LLVM.LLVMBuildICmp(builder, getPredicate(relationalExpression.getOperator(), false, resultType.getPrimitiveTypeType().isSigned()), left, right, ""); } return typeHelper.convertTemporary(result, new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null), relationalExpression.getType()); } if (expression instanceof ShiftExpression) { ShiftExpression shiftExpression = (ShiftExpression) expression; LLVMValueRef leftValue = buildExpression(shiftExpression.getLeftExpression(), llvmFunction, thisValue, variables); LLVMValueRef rightValue = buildExpression(shiftExpression.getRightExpression(), llvmFunction, thisValue, variables); LLVMValueRef convertedLeft = typeHelper.convertTemporary(leftValue, shiftExpression.getLeftExpression().getType(), shiftExpression.getType()); LLVMValueRef convertedRight = typeHelper.convertTemporary(rightValue, shiftExpression.getRightExpression().getType(), shiftExpression.getType()); switch (shiftExpression.getOperator()) { case RIGHT_SHIFT: if (((PrimitiveType) shiftExpression.getType()).getPrimitiveTypeType().isSigned()) { return LLVM.LLVMBuildAShr(builder, convertedLeft, convertedRight, ""); } return LLVM.LLVMBuildLShr(builder, convertedLeft, convertedRight, ""); case LEFT_SHIFT: return LLVM.LLVMBuildShl(builder, convertedLeft, convertedRight, ""); } throw new IllegalArgumentException("Unknown shift operator: " + shiftExpression.getOperator()); } if (expression instanceof StringLiteralExpression) { StringLiteralExpression stringLiteralExpression = (StringLiteralExpression) expression; String value = stringLiteralExpression.getLiteral().getLiteralValue(); byte[] bytes; try { bytes = value.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("UTF-8 encoding not supported!", e); } // build the []ubyte up from the string value, and store it as a global variable LLVMValueRef lengthValue = LLVM.LLVMConstInt(typeHelper.findStandardType(ArrayLengthMember.ARRAY_LENGTH_TYPE), bytes.length, false); LLVMValueRef constString = LLVM.LLVMConstString(bytes, bytes.length, true); LLVMValueRef[] arrayValues = new LLVMValueRef[] {lengthValue, constString}; LLVMValueRef byteArrayStruct = LLVM.LLVMConstStruct(C.toNativePointerArray(arrayValues, false, true), arrayValues.length, false); LLVMTypeRef stringType = LLVM.LLVMArrayType(LLVM.LLVMInt8Type(), bytes.length); LLVMTypeRef[] structSubTypes = new LLVMTypeRef[] {typeHelper.findStandardType(ArrayLengthMember.ARRAY_LENGTH_TYPE), stringType}; LLVMTypeRef structType = LLVM.LLVMStructType(C.toNativePointerArray(structSubTypes, false, true), structSubTypes.length, false); LLVMValueRef globalVariable = LLVM.LLVMAddGlobal(module, structType, "str"); LLVM.LLVMSetInitializer(globalVariable, byteArrayStruct); LLVM.LLVMSetLinkage(globalVariable, LLVM.LLVMLinkage.LLVMPrivateLinkage); LLVM.LLVMSetGlobalConstant(globalVariable, true); // extract the string([]ubyte) constructor from the type of this expression Type arrayType = new ArrayType(false, true, new PrimitiveType(false, PrimitiveTypeType.UBYTE, null), null); LLVMValueRef constructorFunction = getConstructorFunction(SpecialTypeHandler.stringArrayConstructor); LLVMValueRef bitcastedArray = LLVM.LLVMBuildBitCast(builder, globalVariable, typeHelper.findStandardType(arrayType), ""); // build an alloca in the entry block for the string value LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMPositionBuilderAtStart(builder, LLVM.LLVMGetEntryBasicBlock(llvmFunction)); // find the type to alloca, which is the standard representation of a non-nullable version of this type // when we alloca this type, it becomes equivalent to the temporary type representation of this compound type (with any nullability) LLVMTypeRef allocaBaseType = typeHelper.findStandardType(new NamedType(false, false, SpecialTypeHandler.stringArrayConstructor.getContainingTypeDefinition())); LLVMValueRef alloca = LLVM.LLVMBuildAlloca(builder, allocaBaseType, ""); LLVM.LLVMPositionBuilderAtEnd(builder, currentBlock); typeHelper.initialiseCompoundType((CompoundDefinition) SpecialTypeHandler.stringArrayConstructor.getContainingTypeDefinition(), alloca); LLVMValueRef[] arguments = new LLVMValueRef[] {alloca, bitcastedArray}; LLVM.LLVMBuildCall(builder, constructorFunction, C.toNativePointerArray(arguments, false, true), arguments.length, ""); return typeHelper.convertTemporary(alloca, new NamedType(false, false, SpecialTypeHandler.stringArrayConstructor.getContainingTypeDefinition()), expression.getType()); } if (expression instanceof ThisExpression) { // the 'this' value always has a temporary representation return thisValue; } if (expression instanceof TupleExpression) { TupleExpression tupleExpression = (TupleExpression) expression; Type[] tupleTypes = ((TupleType) tupleExpression.getType()).getSubTypes(); Expression[] subExpressions = tupleExpression.getSubExpressions(); Type nonNullableTupleType = TypeChecker.findTypeWithNullability(tupleExpression.getType(), false); LLVMValueRef currentValue = LLVM.LLVMGetUndef(typeHelper.findTemporaryType(nonNullableTupleType)); for (int i = 0; i < subExpressions.length; i++) { LLVMValueRef value = buildExpression(subExpressions[i], llvmFunction, thisValue, variables); Type type = tupleTypes[i]; value = typeHelper.convertTemporary(value, subExpressions[i].getType(), type); currentValue = LLVM.LLVMBuildInsertValue(builder, currentValue, value, i, ""); } return typeHelper.convertTemporary(currentValue, nonNullableTupleType, tupleExpression.getType()); } if (expression instanceof TupleIndexExpression) { TupleIndexExpression tupleIndexExpression = (TupleIndexExpression) expression; TupleType tupleType = (TupleType) tupleIndexExpression.getExpression().getType(); LLVMValueRef result = buildExpression(tupleIndexExpression.getExpression(), llvmFunction, thisValue, variables); // convert the 1-based indexing to 0-based before extracting the value int index = tupleIndexExpression.getIndexLiteral().getValue().intValue() - 1; LLVMValueRef value = LLVM.LLVMBuildExtractValue(builder, result, index, ""); return typeHelper.convertTemporary(value, tupleType.getSubTypes()[index], tupleIndexExpression.getType()); } if (expression instanceof VariableExpression) { VariableExpression variableExpression = (VariableExpression) expression; Variable variable = variableExpression.getResolvedVariable(); if (variable != null) { if (variable instanceof MemberVariable) { Field field = ((MemberVariable) variable).getField(); LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), field.getMemberIndex(), false)}; LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, thisValue, C.toNativePointerArray(indices, false, true), indices.length, ""); return typeHelper.convertStandardPointerToTemporary(elementPointer, variable.getType(), variableExpression.getType(), llvmFunction); } if (variable instanceof GlobalVariable) { LLVMValueRef global = getGlobal((GlobalVariable) variable); return typeHelper.convertStandardPointerToTemporary(global, variable.getType(), variableExpression.getType(), llvmFunction); } LLVMValueRef value = variables.get(variable); if (value == null) { throw new IllegalStateException("Missing LLVMValueRef in variable Map: " + variableExpression.getName()); } return LLVM.LLVMBuildLoad(builder, value, ""); } Method method = variableExpression.getResolvedMethod(); if (method != null) { Parameter[] parameters = method.getParameters(); Type[] parameterTypes = new Type[parameters.length]; for (int i = 0; i < parameters.length; ++i) { parameterTypes[i] = parameters[i].getType(); } FunctionType functionType = new FunctionType(false, method.isImmutable(), method.getReturnType(), parameterTypes, null); LLVMValueRef function = getMethodFunction(method); function = LLVM.LLVMBuildBitCast(builder, function, typeHelper.findRawFunctionPointerType(functionType), ""); LLVMValueRef firstArgument; if (method.isStatic()) { firstArgument = LLVM.LLVMConstNull(typeHelper.getOpaquePointer()); } else { firstArgument = LLVM.LLVMBuildBitCast(builder, thisValue, typeHelper.getOpaquePointer(), ""); } LLVMValueRef result = LLVM.LLVMGetUndef(typeHelper.findStandardType(functionType)); result = LLVM.LLVMBuildInsertValue(builder, result, firstArgument, 0, ""); result = LLVM.LLVMBuildInsertValue(builder, result, function, 1, ""); return typeHelper.convertStandardToTemporary(result, functionType, variableExpression.getType(), llvmFunction); } } throw new IllegalArgumentException("Unknown Expression type: " + expression); } }
true
true
private LLVMValueRef buildExpression(Expression expression, LLVMValueRef llvmFunction, LLVMValueRef thisValue, Map<Variable, LLVMValueRef> variables) { if (expression instanceof ArithmeticExpression) { ArithmeticExpression arithmeticExpression = (ArithmeticExpression) expression; LLVMValueRef left = buildExpression(arithmeticExpression.getLeftSubExpression(), llvmFunction, thisValue, variables); LLVMValueRef right = buildExpression(arithmeticExpression.getRightSubExpression(), llvmFunction, thisValue, variables); Type leftType = arithmeticExpression.getLeftSubExpression().getType(); Type rightType = arithmeticExpression.getRightSubExpression().getType(); Type resultType = arithmeticExpression.getType(); // cast if necessary left = typeHelper.convertTemporary(left, leftType, resultType); right = typeHelper.convertTemporary(right, rightType, resultType); if (arithmeticExpression.getOperator() == ArithmeticOperator.ADD && resultType.isEquivalent(SpecialTypeHandler.STRING_TYPE)) { // concatenate the strings // build an alloca in the entry block for the result of the concatenation LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMPositionBuilderAtStart(builder, LLVM.LLVMGetEntryBasicBlock(llvmFunction)); // find the type to alloca, which is the standard representation of a non-nullable version of this type // when we alloca this type, it becomes equivalent to the temporary type representation of this compound type (with any nullability) LLVMTypeRef allocaBaseType = typeHelper.findStandardType(new NamedType(false, false, SpecialTypeHandler.stringConcatenationConstructor.getContainingTypeDefinition())); LLVMValueRef alloca = LLVM.LLVMBuildAlloca(builder, allocaBaseType, ""); LLVM.LLVMPositionBuilderAtEnd(builder, currentBlock); typeHelper.initialiseCompoundType((CompoundDefinition) SpecialTypeHandler.stringConcatenationConstructor.getContainingTypeDefinition(), alloca); LLVMValueRef[] arguments = new LLVMValueRef[] {alloca, typeHelper.convertTemporaryToStandard(left, resultType, llvmFunction), typeHelper.convertTemporaryToStandard(right, resultType, llvmFunction)}; LLVMValueRef concatenationConstructor = getConstructorFunction(SpecialTypeHandler.stringConcatenationConstructor); LLVM.LLVMBuildCall(builder, concatenationConstructor, C.toNativePointerArray(arguments, false, true), arguments.length, ""); return typeHelper.convertTemporary(alloca, new NamedType(false, false, SpecialTypeHandler.stringConcatenationConstructor.getContainingTypeDefinition()), resultType); } boolean floating = ((PrimitiveType) resultType).getPrimitiveTypeType().isFloating(); boolean signed = ((PrimitiveType) resultType).getPrimitiveTypeType().isSigned(); switch (arithmeticExpression.getOperator()) { case ADD: return floating ? LLVM.LLVMBuildFAdd(builder, left, right, "") : LLVM.LLVMBuildAdd(builder, left, right, ""); case SUBTRACT: return floating ? LLVM.LLVMBuildFSub(builder, left, right, "") : LLVM.LLVMBuildSub(builder, left, right, ""); case MULTIPLY: return floating ? LLVM.LLVMBuildFMul(builder, left, right, "") : LLVM.LLVMBuildMul(builder, left, right, ""); case DIVIDE: return floating ? LLVM.LLVMBuildFDiv(builder, left, right, "") : signed ? LLVM.LLVMBuildSDiv(builder, left, right, "") : LLVM.LLVMBuildUDiv(builder, left, right, ""); case REMAINDER: return floating ? LLVM.LLVMBuildFRem(builder, left, right, "") : signed ? LLVM.LLVMBuildSRem(builder, left, right, "") : LLVM.LLVMBuildURem(builder, left, right, ""); case MODULO: if (floating) { LLVMValueRef rem = LLVM.LLVMBuildFRem(builder, left, right, ""); LLVMValueRef add = LLVM.LLVMBuildFAdd(builder, rem, right, ""); return LLVM.LLVMBuildFRem(builder, add, right, ""); } if (signed) { LLVMValueRef rem = LLVM.LLVMBuildSRem(builder, left, right, ""); LLVMValueRef add = LLVM.LLVMBuildAdd(builder, rem, right, ""); return LLVM.LLVMBuildSRem(builder, add, right, ""); } // unsigned modulo is the same as unsigned remainder return LLVM.LLVMBuildURem(builder, left, right, ""); } throw new IllegalArgumentException("Unknown arithmetic operator: " + arithmeticExpression.getOperator()); } if (expression instanceof ArrayAccessExpression) { ArrayAccessExpression arrayAccessExpression = (ArrayAccessExpression) expression; LLVMValueRef arrayValue = buildExpression(arrayAccessExpression.getArrayExpression(), llvmFunction, thisValue, variables); LLVMValueRef dimensionValue = buildExpression(arrayAccessExpression.getDimensionExpression(), llvmFunction, thisValue, variables); LLVMValueRef convertedDimensionValue = typeHelper.convertTemporaryToStandard(dimensionValue, arrayAccessExpression.getDimensionExpression().getType(), ArrayLengthMember.ARRAY_LENGTH_TYPE, llvmFunction); LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false), convertedDimensionValue}; LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, arrayValue, C.toNativePointerArray(indices, false, true), indices.length, ""); ArrayType arrayType = (ArrayType) arrayAccessExpression.getArrayExpression().getType(); return typeHelper.convertStandardPointerToTemporary(elementPointer, arrayType.getBaseType(), arrayAccessExpression.getType(), llvmFunction); } if (expression instanceof ArrayCreationExpression) { ArrayCreationExpression arrayCreationExpression = (ArrayCreationExpression) expression; ArrayType type = arrayCreationExpression.getDeclaredType(); Expression[] dimensionExpressions = arrayCreationExpression.getDimensionExpressions(); if (dimensionExpressions == null) { Expression[] valueExpressions = arrayCreationExpression.getValueExpressions(); LLVMValueRef llvmLength = LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), valueExpressions.length, false); LLVMValueRef array = buildArrayCreation(llvmFunction, new LLVMValueRef[] {llvmLength}, type); for (int i = 0; i < valueExpressions.length; i++) { LLVMValueRef expressionValue = buildExpression(valueExpressions[i], llvmFunction, thisValue, variables); LLVMValueRef convertedValue = typeHelper.convertTemporaryToStandard(expressionValue, valueExpressions[i].getType(), type.getBaseType(), llvmFunction); LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), i, false)}; LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, array, C.toNativePointerArray(indices, false, true), indices.length, ""); LLVM.LLVMBuildStore(builder, convertedValue, elementPointer); } return typeHelper.convertTemporary(array, type, arrayCreationExpression.getType()); } LLVMValueRef[] llvmLengths = new LLVMValueRef[dimensionExpressions.length]; for (int i = 0; i < llvmLengths.length; i++) { LLVMValueRef expressionValue = buildExpression(dimensionExpressions[i], llvmFunction, thisValue, variables); llvmLengths[i] = typeHelper.convertTemporaryToStandard(expressionValue, dimensionExpressions[i].getType(), ArrayLengthMember.ARRAY_LENGTH_TYPE, llvmFunction); } LLVMValueRef array = buildArrayCreation(llvmFunction, llvmLengths, type); return typeHelper.convertTemporary(array, type, arrayCreationExpression.getType()); } if (expression instanceof BitwiseNotExpression) { LLVMValueRef value = buildExpression(((BitwiseNotExpression) expression).getExpression(), llvmFunction, thisValue, variables); value = typeHelper.convertTemporary(value, ((BitwiseNotExpression) expression).getExpression().getType(), expression.getType()); return LLVM.LLVMBuildNot(builder, value, ""); } if (expression instanceof BooleanLiteralExpression) { LLVMValueRef value = LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), ((BooleanLiteralExpression) expression).getValue() ? 1 : 0, false); return typeHelper.convertStandardToTemporary(value, new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null), expression.getType(), llvmFunction); } if (expression instanceof BooleanNotExpression) { LLVMValueRef value = buildExpression(((BooleanNotExpression) expression).getExpression(), llvmFunction, thisValue, variables); LLVMValueRef result = LLVM.LLVMBuildNot(builder, value, ""); return typeHelper.convertTemporary(result, ((BooleanNotExpression) expression).getExpression().getType(), expression.getType()); } if (expression instanceof BracketedExpression) { BracketedExpression bracketedExpression = (BracketedExpression) expression; LLVMValueRef value = buildExpression(bracketedExpression.getExpression(), llvmFunction, thisValue, variables); return typeHelper.convertTemporary(value, bracketedExpression.getExpression().getType(), expression.getType()); } if (expression instanceof CastExpression) { CastExpression castExpression = (CastExpression) expression; LLVMValueRef value = buildExpression(castExpression.getExpression(), llvmFunction, thisValue, variables); return typeHelper.convertTemporary(value, castExpression.getExpression().getType(), castExpression.getType()); } if (expression instanceof ClassCreationExpression) { ClassCreationExpression classCreationExpression = (ClassCreationExpression) expression; Expression[] arguments = classCreationExpression.getArguments(); Constructor constructor = classCreationExpression.getResolvedConstructor(); Parameter[] parameters = constructor.getParameters(); LLVMValueRef[] llvmArguments = new LLVMValueRef[1 + arguments.length]; for (int i = 0; i < arguments.length; ++i) { LLVMValueRef argument = buildExpression(arguments[i], llvmFunction, thisValue, variables); llvmArguments[i + 1] = typeHelper.convertTemporaryToStandard(argument, arguments[i].getType(), parameters[i].getType(), llvmFunction); } Type type = classCreationExpression.getType(); LLVMTypeRef nativeType = typeHelper.findTemporaryType(type); LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false)}; LLVMValueRef llvmStructSize = LLVM.LLVMBuildGEP(builder, LLVM.LLVMConstNull(nativeType), C.toNativePointerArray(indices, false, true), indices.length, ""); LLVMValueRef llvmSize = LLVM.LLVMBuildPtrToInt(builder, llvmStructSize, LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), ""); LLVMValueRef[] callocArguments = new LLVMValueRef[] {llvmSize, LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false)}; LLVMValueRef memory = LLVM.LLVMBuildCall(builder, callocFunction, C.toNativePointerArray(callocArguments, false, true), callocArguments.length, ""); LLVMValueRef pointer = LLVM.LLVMBuildBitCast(builder, memory, nativeType, ""); llvmArguments[0] = pointer; // get the constructor and call it LLVMValueRef llvmFunc = getConstructorFunction(constructor); LLVMValueRef result = LLVM.LLVMBuildCall(builder, llvmFunc, C.toNativePointerArray(llvmArguments, false, true), llvmArguments.length, ""); return result; } if (expression instanceof EqualityExpression) { EqualityExpression equalityExpression = (EqualityExpression) expression; EqualityOperator operator = equalityExpression.getOperator(); // if the type checker has annotated this as a null check, just perform it without building both sub-expressions Expression nullCheckExpression = equalityExpression.getNullCheckExpression(); if (nullCheckExpression != null) { LLVMValueRef value = buildExpression(nullCheckExpression, llvmFunction, thisValue, variables); LLVMValueRef convertedValue = typeHelper.convertTemporary(value, nullCheckExpression.getType(), equalityExpression.getComparisonType()); LLVMValueRef nullity = buildNullCheck(convertedValue, equalityExpression.getComparisonType()); switch (operator) { case EQUAL: return LLVM.LLVMBuildNot(builder, nullity, ""); case NOT_EQUAL: return nullity; default: throw new IllegalArgumentException("Cannot build an EqualityExpression with no EqualityOperator"); } } LLVMValueRef left = buildExpression(equalityExpression.getLeftSubExpression(), llvmFunction, thisValue, variables); LLVMValueRef right = buildExpression(equalityExpression.getRightSubExpression(), llvmFunction, thisValue, variables); Type leftType = equalityExpression.getLeftSubExpression().getType(); Type rightType = equalityExpression.getRightSubExpression().getType(); Type comparisonType = equalityExpression.getComparisonType(); // if comparisonType is null, then the types are integers which cannot be assigned to each other either way around, because one is signed and the other is unsigned // so we must extend each of them to a larger bitCount which they can both fit into, and compare them there if (comparisonType == null) { if (!(leftType instanceof PrimitiveType) || !(rightType instanceof PrimitiveType)) { throw new IllegalStateException("A comparison type must be provided if either the left or right type is not a PrimitiveType: " + equalityExpression); } LLVMValueRef leftIsNotNull = LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 1, false); LLVMValueRef rightIsNotNull = LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 1, false); LLVMValueRef leftValue = left; LLVMValueRef rightValue = right; if (leftType.isNullable()) { leftIsNotNull = LLVM.LLVMBuildExtractValue(builder, left, 0, ""); leftValue = LLVM.LLVMBuildExtractValue(builder, left, 1, ""); } if (rightType.isNullable()) { rightIsNotNull = LLVM.LLVMBuildExtractValue(builder, right, 0, ""); rightValue = LLVM.LLVMBuildExtractValue(builder, right, 1, ""); } PrimitiveTypeType leftTypeType = ((PrimitiveType) leftType).getPrimitiveTypeType(); PrimitiveTypeType rightTypeType = ((PrimitiveType) rightType).getPrimitiveTypeType(); if (!leftTypeType.isFloating() && !rightTypeType.isFloating() && leftTypeType.isSigned() != rightTypeType.isSigned()) { // compare the signed and non-signed integers as (bitCount + 1) bit numbers, since they will not fit in bitCount bits int bitCount = Math.max(leftTypeType.getBitCount(), rightTypeType.getBitCount()) + 1; LLVMTypeRef llvmComparisonType = LLVM.LLVMIntType(bitCount); if (leftTypeType.isSigned()) { leftValue = LLVM.LLVMBuildSExt(builder, leftValue, llvmComparisonType, ""); rightValue = LLVM.LLVMBuildZExt(builder, rightValue, llvmComparisonType, ""); } else { leftValue = LLVM.LLVMBuildZExt(builder, leftValue, llvmComparisonType, ""); rightValue = LLVM.LLVMBuildSExt(builder, rightValue, llvmComparisonType, ""); } LLVMValueRef comparisonResult = LLVM.LLVMBuildICmp(builder, getPredicate(equalityExpression.getOperator(), false), leftValue, rightValue, ""); if (leftType.isNullable() || rightType.isNullable()) { LLVMValueRef nullityComparison = LLVM.LLVMBuildICmp(builder, getPredicate(equalityExpression.getOperator(), false), leftIsNotNull, rightIsNotNull, ""); if (equalityExpression.getOperator() == EqualityOperator.EQUAL) { comparisonResult = LLVM.LLVMBuildAnd(builder, nullityComparison, comparisonResult, ""); } else { comparisonResult = LLVM.LLVMBuildOr(builder, nullityComparison, comparisonResult, ""); } } return typeHelper.convertTemporary(comparisonResult, new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null), equalityExpression.getType()); } throw new IllegalArgumentException("Unknown result type, unable to generate comparison expression: " + equalityExpression); } // perform a standard equality check, using buildEqualityCheck() left = typeHelper.convertTemporary(left, leftType, comparisonType); right = typeHelper.convertTemporary(right, rightType, comparisonType); return buildEqualityCheck(left, right, comparisonType, operator, llvmFunction); } if (expression instanceof FieldAccessExpression) { FieldAccessExpression fieldAccessExpression = (FieldAccessExpression) expression; Member member = fieldAccessExpression.getResolvedMember(); Expression baseExpression = fieldAccessExpression.getBaseExpression(); if (baseExpression != null) { LLVMValueRef baseValue = buildExpression(baseExpression, llvmFunction, thisValue, variables); LLVMValueRef notNullValue = baseValue; LLVMBasicBlockRef startBlock = null; LLVMBasicBlockRef continuationBlock = null; if (fieldAccessExpression.isNullTraversing()) { LLVMValueRef nullCheckResult = buildNullCheck(baseValue, baseExpression.getType()); LLVMBasicBlockRef accessBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "nullTraversalAccess"); continuationBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "nullTraversalContinuation"); startBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildCondBr(builder, nullCheckResult, accessBlock, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, accessBlock); notNullValue = typeHelper.convertTemporary(baseValue, baseExpression.getType(), TypeChecker.findTypeWithNullability(baseExpression.getType(), false)); } LLVMValueRef result; if (member instanceof ArrayLengthMember) { LLVMValueRef array = notNullValue; LLVMValueRef[] sizeIndices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false)}; LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, array, C.toNativePointerArray(sizeIndices, false, true), sizeIndices.length, ""); result = LLVM.LLVMBuildLoad(builder, elementPointer, ""); result = typeHelper.convertStandardToTemporary(result, ArrayLengthMember.ARRAY_LENGTH_TYPE, fieldAccessExpression.getType(), llvmFunction); } else if (member instanceof Field) { Field field = (Field) member; if (field.isStatic()) { throw new IllegalStateException("A FieldAccessExpression for a static field should not have a base expression"); } LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), field.getMemberIndex(), false)}; LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, notNullValue, C.toNativePointerArray(indices, false, true), indices.length, ""); result = typeHelper.convertStandardPointerToTemporary(elementPointer, field.getType(), fieldAccessExpression.getType(), llvmFunction); } else if (member instanceof Method) { Method method = (Method) member; Parameter[] parameters = method.getParameters(); Type[] parameterTypes = new Type[parameters.length]; for (int i = 0; i < parameters.length; ++i) { parameterTypes[i] = parameters[i].getType(); } FunctionType functionType = new FunctionType(false, method.isImmutable(), method.getReturnType(), parameterTypes, null); if (method.isStatic()) { throw new IllegalStateException("A FieldAccessExpression for a static method should not have a base expression"); } LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder); LLVMValueRef function = getMethodFunction(method); LLVM.LLVMPositionBuilderAtEnd(builder, currentBlock); function = LLVM.LLVMBuildBitCast(builder, function, typeHelper.findRawFunctionPointerType(functionType), ""); LLVMValueRef firstArgument = LLVM.LLVMBuildBitCast(builder, notNullValue, typeHelper.getOpaquePointer(), ""); result = LLVM.LLVMGetUndef(typeHelper.findStandardType(functionType)); result = LLVM.LLVMBuildInsertValue(builder, result, firstArgument, 0, ""); result = LLVM.LLVMBuildInsertValue(builder, result, function, 1, ""); result = typeHelper.convertStandardToTemporary(result, functionType, fieldAccessExpression.getType(), llvmFunction); } else { throw new IllegalArgumentException("Unknown member type for a FieldAccessExpression: " + member); } if (fieldAccessExpression.isNullTraversing()) { LLVMBasicBlockRef accessBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); LLVMValueRef phiNode = LLVM.LLVMBuildPhi(builder, typeHelper.findTemporaryType(fieldAccessExpression.getType()), ""); LLVMValueRef nullAlternative = LLVM.LLVMConstNull(typeHelper.findTemporaryType(fieldAccessExpression.getType())); LLVMValueRef[] phiValues = new LLVMValueRef[] {result, nullAlternative}; LLVMBasicBlockRef[] phiBlocks = new LLVMBasicBlockRef[] {accessBlock, startBlock}; LLVM.LLVMAddIncoming(phiNode, C.toNativePointerArray(phiValues, false, true), C.toNativePointerArray(phiBlocks, false, true), phiValues.length); return phiNode; } return result; } // we don't have a base expression, so handle the static field accesses if (member instanceof Field) { Field field = (Field) member; if (!field.isStatic()) { throw new IllegalStateException("A FieldAccessExpression for a non-static field should have a base expression"); } LLVMValueRef global = getGlobal(field.getGlobalVariable()); return typeHelper.convertStandardPointerToTemporary(global, field.getType(), fieldAccessExpression.getType(), llvmFunction); } if (member instanceof Method) { Method method = (Method) member; if (!method.isStatic()) { throw new IllegalStateException("A FieldAccessExpression for a non-static method should have a base expression"); } Parameter[] parameters = method.getParameters(); Type[] parameterTypes = new Type[parameters.length]; for (int i = 0; i < parameters.length; ++i) { parameterTypes[i] = parameters[i].getType(); } FunctionType functionType = new FunctionType(false, method.isImmutable(), method.getReturnType(), parameterTypes, null); LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder); LLVMValueRef function = getMethodFunction(method); LLVM.LLVMPositionBuilderAtEnd(builder, currentBlock); function = LLVM.LLVMBuildBitCast(builder, function, typeHelper.findRawFunctionPointerType(functionType), ""); LLVMValueRef firstArgument = LLVM.LLVMConstNull(typeHelper.getOpaquePointer()); LLVMValueRef result = LLVM.LLVMGetUndef(typeHelper.findStandardType(functionType)); result = LLVM.LLVMBuildInsertValue(builder, result, firstArgument, 0, ""); result = LLVM.LLVMBuildInsertValue(builder, result, function, 1, ""); return typeHelper.convertStandardToTemporary(result, functionType, fieldAccessExpression.getType(), llvmFunction); } throw new IllegalArgumentException("Unknown member type for a FieldAccessExpression: " + member); } if (expression instanceof FloatingLiteralExpression) { double value = Double.parseDouble(((FloatingLiteralExpression) expression).getLiteral().toString()); LLVMValueRef llvmValue = LLVM.LLVMConstReal(typeHelper.findStandardType(TypeChecker.findTypeWithNullability(expression.getType(), false)), value); return typeHelper.convertStandardToTemporary(llvmValue, TypeChecker.findTypeWithNullability(expression.getType(), false), expression.getType(), llvmFunction); } if (expression instanceof FunctionCallExpression) { FunctionCallExpression functionExpression = (FunctionCallExpression) expression; Constructor resolvedConstructor = functionExpression.getResolvedConstructor(); Method resolvedMethod = functionExpression.getResolvedMethod(); Expression resolvedBaseExpression = functionExpression.getResolvedBaseExpression(); Type[] parameterTypes; Type returnType; LLVMValueRef llvmResolvedFunction; if (resolvedConstructor != null) { Parameter[] params = resolvedConstructor.getParameters(); parameterTypes = new Type[params.length]; for (int i = 0; i < params.length; ++i) { parameterTypes[i] = params[i].getType(); } returnType = new NamedType(false, false, resolvedConstructor.getContainingTypeDefinition()); llvmResolvedFunction = getConstructorFunction(resolvedConstructor); } else if (resolvedMethod != null) { Parameter[] params = resolvedMethod.getParameters(); parameterTypes = new Type[params.length]; for (int i = 0; i < params.length; ++i) { parameterTypes[i] = params[i].getType(); } returnType = resolvedMethod.getReturnType(); LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder); llvmResolvedFunction = getMethodFunction(resolvedMethod); LLVM.LLVMPositionBuilderAtEnd(builder, currentBlock); } else if (resolvedBaseExpression != null) { FunctionType baseType = (FunctionType) resolvedBaseExpression.getType(); parameterTypes = baseType.getParameterTypes(); returnType = baseType.getReturnType(); llvmResolvedFunction = null; } else { throw new IllegalArgumentException("Unresolved function call expression: " + functionExpression); } LLVMValueRef callee = null; if (resolvedBaseExpression != null) { callee = buildExpression(resolvedBaseExpression, llvmFunction, thisValue, variables); } // if this is a null traversing function call, apply it properly boolean nullTraversal = resolvedBaseExpression != null && resolvedMethod != null && functionExpression.getResolvedNullTraversal(); LLVMValueRef notNullCallee = callee; LLVMBasicBlockRef startBlock = null; LLVMBasicBlockRef continuationBlock = null; if (nullTraversal) { LLVMValueRef nullCheckResult = buildNullCheck(callee, resolvedBaseExpression.getType()); LLVMBasicBlockRef callBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "nullTraversalCall"); continuationBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "nullTraversalCallContinuation"); startBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildCondBr(builder, nullCheckResult, callBlock, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, callBlock); notNullCallee = typeHelper.convertTemporary(callee, resolvedBaseExpression.getType(), TypeChecker.findTypeWithNullability(resolvedBaseExpression.getType(), false)); } Expression[] arguments = functionExpression.getArguments(); LLVMValueRef[] values = new LLVMValueRef[arguments.length]; for (int i = 0; i < arguments.length; i++) { LLVMValueRef arg = buildExpression(arguments[i], llvmFunction, thisValue, variables); values[i] = typeHelper.convertTemporaryToStandard(arg, arguments[i].getType(), parameterTypes[i], llvmFunction); } LLVMValueRef result; boolean resultIsTemporary = false; // true iff result has a temporary type representation if (resolvedConstructor != null) { // build an alloca in the entry block for the result of the constructor call LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMPositionBuilderAtStart(builder, LLVM.LLVMGetEntryBasicBlock(llvmFunction)); // find the type to alloca, which is the standard representation of a non-nullable type // when we alloca this type, it becomes equivalent to the temporary type representation of this compound type (with any nullability) LLVMTypeRef allocaBaseType = typeHelper.findStandardType(returnType); LLVMValueRef alloca = LLVM.LLVMBuildAlloca(builder, allocaBaseType, ""); LLVM.LLVMPositionBuilderAtEnd(builder, currentBlock); typeHelper.initialiseCompoundType((CompoundDefinition) ((NamedType) returnType).getResolvedTypeDefinition(), alloca); LLVMValueRef[] realArguments = new LLVMValueRef[1 + values.length]; realArguments[0] = alloca; System.arraycopy(values, 0, realArguments, 1, values.length); LLVM.LLVMBuildCall(builder, llvmResolvedFunction, C.toNativePointerArray(realArguments, false, true), realArguments.length, ""); result = alloca; resultIsTemporary = true; } else if (resolvedMethod != null) { LLVMValueRef[] realArguments = new LLVMValueRef[values.length + 1]; if (resolvedMethod.isStatic()) { realArguments[0] = LLVM.LLVMConstNull(typeHelper.getOpaquePointer()); } else { realArguments[0] = notNullCallee != null ? notNullCallee : thisValue; } System.arraycopy(values, 0, realArguments, 1, values.length); result = LLVM.LLVMBuildCall(builder, llvmResolvedFunction, C.toNativePointerArray(realArguments, false, true), realArguments.length, ""); } else if (resolvedBaseExpression != null) { // callee here is actually a tuple of an opaque pointer and a function type, where the first argument to the function is the opaque pointer LLVMValueRef firstArgument = LLVM.LLVMBuildExtractValue(builder, callee, 0, ""); LLVMValueRef calleeFunction = LLVM.LLVMBuildExtractValue(builder, callee, 1, ""); LLVMValueRef[] realArguments = new LLVMValueRef[values.length + 1]; realArguments[0] = firstArgument; System.arraycopy(values, 0, realArguments, 1, values.length); result = LLVM.LLVMBuildCall(builder, calleeFunction, C.toNativePointerArray(realArguments, false, true), realArguments.length, ""); } else { throw new IllegalArgumentException("Unresolved function call expression: " + functionExpression); } if (nullTraversal) { if (returnType instanceof VoidType) { LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); return null; } if (resultIsTemporary) { result = typeHelper.convertTemporary(result, returnType, functionExpression.getType()); } else { result = typeHelper.convertStandardToTemporary(result, returnType, functionExpression.getType(), llvmFunction); } LLVMBasicBlockRef callBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); LLVMValueRef phiNode = LLVM.LLVMBuildPhi(builder, typeHelper.findTemporaryType(functionExpression.getType()), ""); LLVMValueRef nullAlternative = LLVM.LLVMConstNull(typeHelper.findTemporaryType(functionExpression.getType())); LLVMValueRef[] phiValues = new LLVMValueRef[] {result, nullAlternative}; LLVMBasicBlockRef[] phiBlocks = new LLVMBasicBlockRef[] {callBlock, startBlock}; LLVM.LLVMAddIncoming(phiNode, C.toNativePointerArray(phiValues, false, true), C.toNativePointerArray(phiBlocks, false, true), phiValues.length); return phiNode; } if (returnType instanceof VoidType) { return result; } if (resultIsTemporary) { return typeHelper.convertTemporary(result, returnType, functionExpression.getType()); } return typeHelper.convertStandardToTemporary(result, returnType, functionExpression.getType(), llvmFunction); } if (expression instanceof InlineIfExpression) { InlineIfExpression inlineIf = (InlineIfExpression) expression; LLVMValueRef conditionValue = buildExpression(inlineIf.getCondition(), llvmFunction, thisValue, variables); conditionValue = typeHelper.convertTemporaryToStandard(conditionValue, inlineIf.getCondition().getType(), new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null), llvmFunction); LLVMBasicBlockRef thenBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "inlineIfThen"); LLVMBasicBlockRef elseBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "inlineIfElse"); LLVMBasicBlockRef continuationBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "afterInlineIf"); LLVM.LLVMBuildCondBr(builder, conditionValue, thenBlock, elseBlock); LLVM.LLVMPositionBuilderAtEnd(builder, thenBlock); LLVMValueRef thenValue = buildExpression(inlineIf.getThenExpression(), llvmFunction, thisValue, variables); LLVMValueRef convertedThenValue = typeHelper.convertTemporary(thenValue, inlineIf.getThenExpression().getType(), inlineIf.getType()); LLVMBasicBlockRef thenBranchBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, elseBlock); LLVMValueRef elseValue = buildExpression(inlineIf.getElseExpression(), llvmFunction, thisValue, variables); LLVMValueRef convertedElseValue = typeHelper.convertTemporary(elseValue, inlineIf.getElseExpression().getType(), inlineIf.getType()); LLVMBasicBlockRef elseBranchBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); LLVMValueRef result = LLVM.LLVMBuildPhi(builder, typeHelper.findTemporaryType(inlineIf.getType()), ""); LLVMValueRef[] incomingValues = new LLVMValueRef[] {convertedThenValue, convertedElseValue}; LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {thenBranchBlock, elseBranchBlock}; LLVM.LLVMAddIncoming(result, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), 2); return result; } if (expression instanceof IntegerLiteralExpression) { BigInteger bigintValue = ((IntegerLiteralExpression) expression).getLiteral().getValue(); byte[] bytes = bigintValue.toByteArray(); // convert the big-endian byte[] from the BigInteger into a little-endian long[] for LLVM long[] longs = new long[(bytes.length + 7) / 8]; for (int i = 0; i < bytes.length; ++i) { int longIndex = (bytes.length - 1 - i) / 8; int longBitPos = ((bytes.length - 1 - i) % 8) * 8; longs[longIndex] |= (((long) bytes[i]) & 0xff) << longBitPos; } LLVMValueRef value = LLVM.LLVMConstIntOfArbitraryPrecision(typeHelper.findStandardType(TypeChecker.findTypeWithNullability(expression.getType(), false)), longs.length, longs); return typeHelper.convertStandardToTemporary(value, TypeChecker.findTypeWithNullability(expression.getType(), false), expression.getType(), llvmFunction); } if (expression instanceof LogicalExpression) { LogicalExpression logicalExpression = (LogicalExpression) expression; LLVMValueRef left = buildExpression(logicalExpression.getLeftSubExpression(), llvmFunction, thisValue, variables); PrimitiveType leftType = (PrimitiveType) logicalExpression.getLeftSubExpression().getType(); PrimitiveType rightType = (PrimitiveType) logicalExpression.getRightSubExpression().getType(); // cast if necessary PrimitiveType resultType = (PrimitiveType) logicalExpression.getType(); left = typeHelper.convertTemporary(left, leftType, resultType); LogicalOperator operator = logicalExpression.getOperator(); if (operator != LogicalOperator.SHORT_CIRCUIT_AND && operator != LogicalOperator.SHORT_CIRCUIT_OR) { LLVMValueRef right = buildExpression(logicalExpression.getRightSubExpression(), llvmFunction, thisValue, variables); right = typeHelper.convertTemporary(right, rightType, resultType); switch (operator) { case AND: return LLVM.LLVMBuildAnd(builder, left, right, ""); case OR: return LLVM.LLVMBuildOr(builder, left, right, ""); case XOR: return LLVM.LLVMBuildXor(builder, left, right, ""); default: throw new IllegalStateException("Unexpected non-short-circuit operator: " + logicalExpression.getOperator()); } } LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder); LLVMBasicBlockRef rightCheckBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "shortCircuitCheck"); LLVMBasicBlockRef continuationBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "shortCircuitContinue"); // the only difference between short circuit AND and OR is whether they jump to the check block when the left hand side is true or false LLVMBasicBlockRef trueDest = operator == LogicalOperator.SHORT_CIRCUIT_AND ? rightCheckBlock : continuationBlock; LLVMBasicBlockRef falseDest = operator == LogicalOperator.SHORT_CIRCUIT_AND ? continuationBlock : rightCheckBlock; LLVM.LLVMBuildCondBr(builder, left, trueDest, falseDest); LLVM.LLVMPositionBuilderAtEnd(builder, rightCheckBlock); LLVMValueRef right = buildExpression(logicalExpression.getRightSubExpression(), llvmFunction, thisValue, variables); right = typeHelper.convertTemporary(right, rightType, resultType); LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); // create a phi node for the result, and return it LLVMValueRef phi = LLVM.LLVMBuildPhi(builder, typeHelper.findTemporaryType(resultType), ""); LLVMValueRef[] incomingValues = new LLVMValueRef[] {left, right}; LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {currentBlock, rightCheckBlock}; LLVM.LLVMAddIncoming(phi, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), 2); return phi; } if (expression instanceof MinusExpression) { MinusExpression minusExpression = (MinusExpression) expression; LLVMValueRef value = buildExpression(minusExpression.getExpression(), llvmFunction, thisValue, variables); value = typeHelper.convertTemporary(value, minusExpression.getExpression().getType(), TypeChecker.findTypeWithNullability(minusExpression.getType(), false)); PrimitiveTypeType primitiveTypeType = ((PrimitiveType) minusExpression.getType()).getPrimitiveTypeType(); LLVMValueRef result; if (primitiveTypeType.isFloating()) { result = LLVM.LLVMBuildFNeg(builder, value, ""); } else { result = LLVM.LLVMBuildNeg(builder, value, ""); } return typeHelper.convertTemporary(result, TypeChecker.findTypeWithNullability(minusExpression.getType(), false), minusExpression.getType()); } if (expression instanceof NullCoalescingExpression) { NullCoalescingExpression nullCoalescingExpression = (NullCoalescingExpression) expression; LLVMValueRef nullableValue = buildExpression(nullCoalescingExpression.getNullableExpression(), llvmFunction, thisValue, variables); nullableValue = typeHelper.convertTemporary(nullableValue, nullCoalescingExpression.getNullableExpression().getType(), TypeChecker.findTypeWithNullability(nullCoalescingExpression.getType(), true)); LLVMValueRef checkResult = buildNullCheck(nullableValue, TypeChecker.findTypeWithNullability(nullCoalescingExpression.getType(), true)); LLVMBasicBlockRef conversionBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "nullCoalescingConversion"); LLVMBasicBlockRef alternativeBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "nullCoalescingAlternative"); LLVMBasicBlockRef continuationBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "nullCoalescingContinuation"); LLVM.LLVMBuildCondBr(builder, checkResult, conversionBlock, alternativeBlock); // create a block to convert the nullable value into a non-nullable value LLVM.LLVMPositionBuilderAtEnd(builder, conversionBlock); LLVMValueRef convertedNullableValue = typeHelper.convertTemporary(nullableValue, TypeChecker.findTypeWithNullability(nullCoalescingExpression.getType(), true), nullCoalescingExpression.getType()); LLVMBasicBlockRef endConversionBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, alternativeBlock); LLVMValueRef alternativeValue = buildExpression(nullCoalescingExpression.getAlternativeExpression(), llvmFunction, thisValue, variables); alternativeValue = typeHelper.convertTemporary(alternativeValue, nullCoalescingExpression.getAlternativeExpression().getType(), nullCoalescingExpression.getType()); LLVMBasicBlockRef endAlternativeBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); // create a phi node for the result, and return it LLVMTypeRef resultType = typeHelper.findTemporaryType(nullCoalescingExpression.getType()); LLVMValueRef result = LLVM.LLVMBuildPhi(builder, resultType, ""); LLVMValueRef[] incomingValues = new LLVMValueRef[] {convertedNullableValue, alternativeValue}; LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {endConversionBlock, endAlternativeBlock}; LLVM.LLVMAddIncoming(result, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), incomingValues.length); return result; } if (expression instanceof NullLiteralExpression) { Type type = expression.getType(); return LLVM.LLVMConstNull(typeHelper.findTemporaryType(type)); } if (expression instanceof RelationalExpression) { RelationalExpression relationalExpression = (RelationalExpression) expression; LLVMValueRef left = buildExpression(relationalExpression.getLeftSubExpression(), llvmFunction, thisValue, variables); LLVMValueRef right = buildExpression(relationalExpression.getRightSubExpression(), llvmFunction, thisValue, variables); PrimitiveType leftType = (PrimitiveType) relationalExpression.getLeftSubExpression().getType(); PrimitiveType rightType = (PrimitiveType) relationalExpression.getRightSubExpression().getType(); // cast if necessary PrimitiveType resultType = relationalExpression.getComparisonType(); if (resultType == null) { PrimitiveTypeType leftTypeType = leftType.getPrimitiveTypeType(); PrimitiveTypeType rightTypeType = rightType.getPrimitiveTypeType(); if (!leftTypeType.isFloating() && !rightTypeType.isFloating() && leftTypeType.isSigned() != rightTypeType.isSigned() && !leftType.isNullable() && !rightType.isNullable()) { // compare the signed and non-signed integers as (bitCount + 1) bit numbers, since they will not fit in bitCount bits int bitCount = Math.max(leftTypeType.getBitCount(), rightTypeType.getBitCount()) + 1; LLVMTypeRef comparisonType = LLVM.LLVMIntType(bitCount); if (leftTypeType.isSigned()) { left = LLVM.LLVMBuildSExt(builder, left, comparisonType, ""); right = LLVM.LLVMBuildZExt(builder, right, comparisonType, ""); } else { left = LLVM.LLVMBuildZExt(builder, left, comparisonType, ""); right = LLVM.LLVMBuildSExt(builder, right, comparisonType, ""); } return LLVM.LLVMBuildICmp(builder, getPredicate(relationalExpression.getOperator(), false, true), left, right, ""); } throw new IllegalArgumentException("Unknown result type, unable to generate comparison expression: " + expression); } left = typeHelper.convertTemporary(left, leftType, resultType); right = typeHelper.convertTemporary(right, rightType, resultType); LLVMValueRef result; if (resultType.getPrimitiveTypeType().isFloating()) { result = LLVM.LLVMBuildFCmp(builder, getPredicate(relationalExpression.getOperator(), true, true), left, right, ""); } else { result = LLVM.LLVMBuildICmp(builder, getPredicate(relationalExpression.getOperator(), false, resultType.getPrimitiveTypeType().isSigned()), left, right, ""); } return typeHelper.convertTemporary(result, new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null), relationalExpression.getType()); } if (expression instanceof ShiftExpression) { ShiftExpression shiftExpression = (ShiftExpression) expression; LLVMValueRef leftValue = buildExpression(shiftExpression.getLeftExpression(), llvmFunction, thisValue, variables); LLVMValueRef rightValue = buildExpression(shiftExpression.getRightExpression(), llvmFunction, thisValue, variables); LLVMValueRef convertedLeft = typeHelper.convertTemporary(leftValue, shiftExpression.getLeftExpression().getType(), shiftExpression.getType()); LLVMValueRef convertedRight = typeHelper.convertTemporary(rightValue, shiftExpression.getRightExpression().getType(), shiftExpression.getType()); switch (shiftExpression.getOperator()) { case RIGHT_SHIFT: if (((PrimitiveType) shiftExpression.getType()).getPrimitiveTypeType().isSigned()) { return LLVM.LLVMBuildAShr(builder, convertedLeft, convertedRight, ""); } return LLVM.LLVMBuildLShr(builder, convertedLeft, convertedRight, ""); case LEFT_SHIFT: return LLVM.LLVMBuildShl(builder, convertedLeft, convertedRight, ""); } throw new IllegalArgumentException("Unknown shift operator: " + shiftExpression.getOperator()); } if (expression instanceof StringLiteralExpression) { StringLiteralExpression stringLiteralExpression = (StringLiteralExpression) expression; String value = stringLiteralExpression.getLiteral().getLiteralValue(); byte[] bytes; try { bytes = value.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("UTF-8 encoding not supported!", e); } // build the []ubyte up from the string value, and store it as a global variable LLVMValueRef lengthValue = LLVM.LLVMConstInt(typeHelper.findStandardType(ArrayLengthMember.ARRAY_LENGTH_TYPE), bytes.length, false); LLVMValueRef constString = LLVM.LLVMConstString(bytes, bytes.length, true); LLVMValueRef[] arrayValues = new LLVMValueRef[] {lengthValue, constString}; LLVMValueRef byteArrayStruct = LLVM.LLVMConstStruct(C.toNativePointerArray(arrayValues, false, true), arrayValues.length, false); LLVMTypeRef stringType = LLVM.LLVMArrayType(LLVM.LLVMInt8Type(), bytes.length); LLVMTypeRef[] structSubTypes = new LLVMTypeRef[] {typeHelper.findStandardType(ArrayLengthMember.ARRAY_LENGTH_TYPE), stringType}; LLVMTypeRef structType = LLVM.LLVMStructType(C.toNativePointerArray(structSubTypes, false, true), structSubTypes.length, false); LLVMValueRef globalVariable = LLVM.LLVMAddGlobal(module, structType, "str"); LLVM.LLVMSetInitializer(globalVariable, byteArrayStruct); LLVM.LLVMSetLinkage(globalVariable, LLVM.LLVMLinkage.LLVMPrivateLinkage); LLVM.LLVMSetGlobalConstant(globalVariable, true); // extract the string([]ubyte) constructor from the type of this expression Type arrayType = new ArrayType(false, true, new PrimitiveType(false, PrimitiveTypeType.UBYTE, null), null); LLVMValueRef constructorFunction = getConstructorFunction(SpecialTypeHandler.stringArrayConstructor); LLVMValueRef bitcastedArray = LLVM.LLVMBuildBitCast(builder, globalVariable, typeHelper.findStandardType(arrayType), ""); // build an alloca in the entry block for the string value LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMPositionBuilderAtStart(builder, LLVM.LLVMGetEntryBasicBlock(llvmFunction)); // find the type to alloca, which is the standard representation of a non-nullable version of this type // when we alloca this type, it becomes equivalent to the temporary type representation of this compound type (with any nullability) LLVMTypeRef allocaBaseType = typeHelper.findStandardType(new NamedType(false, false, SpecialTypeHandler.stringArrayConstructor.getContainingTypeDefinition())); LLVMValueRef alloca = LLVM.LLVMBuildAlloca(builder, allocaBaseType, ""); LLVM.LLVMPositionBuilderAtEnd(builder, currentBlock); typeHelper.initialiseCompoundType((CompoundDefinition) SpecialTypeHandler.stringArrayConstructor.getContainingTypeDefinition(), alloca); LLVMValueRef[] arguments = new LLVMValueRef[] {alloca, bitcastedArray}; LLVM.LLVMBuildCall(builder, constructorFunction, C.toNativePointerArray(arguments, false, true), arguments.length, ""); return typeHelper.convertTemporary(alloca, new NamedType(false, false, SpecialTypeHandler.stringArrayConstructor.getContainingTypeDefinition()), expression.getType()); } if (expression instanceof ThisExpression) { // the 'this' value always has a temporary representation return thisValue; } if (expression instanceof TupleExpression) { TupleExpression tupleExpression = (TupleExpression) expression; Type[] tupleTypes = ((TupleType) tupleExpression.getType()).getSubTypes(); Expression[] subExpressions = tupleExpression.getSubExpressions(); Type nonNullableTupleType = TypeChecker.findTypeWithNullability(tupleExpression.getType(), false); LLVMValueRef currentValue = LLVM.LLVMGetUndef(typeHelper.findTemporaryType(nonNullableTupleType)); for (int i = 0; i < subExpressions.length; i++) { LLVMValueRef value = buildExpression(subExpressions[i], llvmFunction, thisValue, variables); Type type = tupleTypes[i]; value = typeHelper.convertTemporary(value, subExpressions[i].getType(), type); currentValue = LLVM.LLVMBuildInsertValue(builder, currentValue, value, i, ""); } return typeHelper.convertTemporary(currentValue, nonNullableTupleType, tupleExpression.getType()); } if (expression instanceof TupleIndexExpression) { TupleIndexExpression tupleIndexExpression = (TupleIndexExpression) expression; TupleType tupleType = (TupleType) tupleIndexExpression.getExpression().getType(); LLVMValueRef result = buildExpression(tupleIndexExpression.getExpression(), llvmFunction, thisValue, variables); // convert the 1-based indexing to 0-based before extracting the value int index = tupleIndexExpression.getIndexLiteral().getValue().intValue() - 1; LLVMValueRef value = LLVM.LLVMBuildExtractValue(builder, result, index, ""); return typeHelper.convertTemporary(value, tupleType.getSubTypes()[index], tupleIndexExpression.getType()); } if (expression instanceof VariableExpression) { VariableExpression variableExpression = (VariableExpression) expression; Variable variable = variableExpression.getResolvedVariable(); if (variable != null) { if (variable instanceof MemberVariable) { Field field = ((MemberVariable) variable).getField(); LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), field.getMemberIndex(), false)}; LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, thisValue, C.toNativePointerArray(indices, false, true), indices.length, ""); return typeHelper.convertStandardPointerToTemporary(elementPointer, variable.getType(), variableExpression.getType(), llvmFunction); } if (variable instanceof GlobalVariable) { LLVMValueRef global = getGlobal((GlobalVariable) variable); return typeHelper.convertStandardPointerToTemporary(global, variable.getType(), variableExpression.getType(), llvmFunction); } LLVMValueRef value = variables.get(variable); if (value == null) { throw new IllegalStateException("Missing LLVMValueRef in variable Map: " + variableExpression.getName()); } return LLVM.LLVMBuildLoad(builder, value, ""); } Method method = variableExpression.getResolvedMethod(); if (method != null) { Parameter[] parameters = method.getParameters(); Type[] parameterTypes = new Type[parameters.length]; for (int i = 0; i < parameters.length; ++i) { parameterTypes[i] = parameters[i].getType(); } FunctionType functionType = new FunctionType(false, method.isImmutable(), method.getReturnType(), parameterTypes, null); LLVMValueRef function = getMethodFunction(method); function = LLVM.LLVMBuildBitCast(builder, function, typeHelper.findRawFunctionPointerType(functionType), ""); LLVMValueRef firstArgument; if (method.isStatic()) { firstArgument = LLVM.LLVMConstNull(typeHelper.getOpaquePointer()); } else { firstArgument = LLVM.LLVMBuildBitCast(builder, thisValue, typeHelper.getOpaquePointer(), ""); } LLVMValueRef result = LLVM.LLVMGetUndef(typeHelper.findStandardType(functionType)); result = LLVM.LLVMBuildInsertValue(builder, result, firstArgument, 0, ""); result = LLVM.LLVMBuildInsertValue(builder, result, function, 1, ""); return typeHelper.convertStandardToTemporary(result, functionType, variableExpression.getType(), llvmFunction); } } throw new IllegalArgumentException("Unknown Expression type: " + expression); }
private LLVMValueRef buildExpression(Expression expression, LLVMValueRef llvmFunction, LLVMValueRef thisValue, Map<Variable, LLVMValueRef> variables) { if (expression instanceof ArithmeticExpression) { ArithmeticExpression arithmeticExpression = (ArithmeticExpression) expression; LLVMValueRef left = buildExpression(arithmeticExpression.getLeftSubExpression(), llvmFunction, thisValue, variables); LLVMValueRef right = buildExpression(arithmeticExpression.getRightSubExpression(), llvmFunction, thisValue, variables); Type leftType = arithmeticExpression.getLeftSubExpression().getType(); Type rightType = arithmeticExpression.getRightSubExpression().getType(); Type resultType = arithmeticExpression.getType(); // cast if necessary left = typeHelper.convertTemporary(left, leftType, resultType); right = typeHelper.convertTemporary(right, rightType, resultType); if (arithmeticExpression.getOperator() == ArithmeticOperator.ADD && resultType.isEquivalent(SpecialTypeHandler.STRING_TYPE)) { // concatenate the strings // build an alloca in the entry block for the result of the concatenation LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMPositionBuilderAtStart(builder, LLVM.LLVMGetEntryBasicBlock(llvmFunction)); // find the type to alloca, which is the standard representation of a non-nullable version of this type // when we alloca this type, it becomes equivalent to the temporary type representation of this compound type (with any nullability) LLVMTypeRef allocaBaseType = typeHelper.findStandardType(new NamedType(false, false, SpecialTypeHandler.stringConcatenationConstructor.getContainingTypeDefinition())); LLVMValueRef alloca = LLVM.LLVMBuildAlloca(builder, allocaBaseType, ""); LLVM.LLVMPositionBuilderAtEnd(builder, currentBlock); typeHelper.initialiseCompoundType((CompoundDefinition) SpecialTypeHandler.stringConcatenationConstructor.getContainingTypeDefinition(), alloca); LLVMValueRef[] arguments = new LLVMValueRef[] {alloca, typeHelper.convertTemporaryToStandard(left, resultType, llvmFunction), typeHelper.convertTemporaryToStandard(right, resultType, llvmFunction)}; LLVMValueRef concatenationConstructor = getConstructorFunction(SpecialTypeHandler.stringConcatenationConstructor); LLVM.LLVMBuildCall(builder, concatenationConstructor, C.toNativePointerArray(arguments, false, true), arguments.length, ""); return typeHelper.convertTemporary(alloca, new NamedType(false, false, SpecialTypeHandler.stringConcatenationConstructor.getContainingTypeDefinition()), resultType); } boolean floating = ((PrimitiveType) resultType).getPrimitiveTypeType().isFloating(); boolean signed = ((PrimitiveType) resultType).getPrimitiveTypeType().isSigned(); switch (arithmeticExpression.getOperator()) { case ADD: return floating ? LLVM.LLVMBuildFAdd(builder, left, right, "") : LLVM.LLVMBuildAdd(builder, left, right, ""); case SUBTRACT: return floating ? LLVM.LLVMBuildFSub(builder, left, right, "") : LLVM.LLVMBuildSub(builder, left, right, ""); case MULTIPLY: return floating ? LLVM.LLVMBuildFMul(builder, left, right, "") : LLVM.LLVMBuildMul(builder, left, right, ""); case DIVIDE: return floating ? LLVM.LLVMBuildFDiv(builder, left, right, "") : signed ? LLVM.LLVMBuildSDiv(builder, left, right, "") : LLVM.LLVMBuildUDiv(builder, left, right, ""); case REMAINDER: return floating ? LLVM.LLVMBuildFRem(builder, left, right, "") : signed ? LLVM.LLVMBuildSRem(builder, left, right, "") : LLVM.LLVMBuildURem(builder, left, right, ""); case MODULO: if (floating) { LLVMValueRef rem = LLVM.LLVMBuildFRem(builder, left, right, ""); LLVMValueRef add = LLVM.LLVMBuildFAdd(builder, rem, right, ""); return LLVM.LLVMBuildFRem(builder, add, right, ""); } if (signed) { LLVMValueRef rem = LLVM.LLVMBuildSRem(builder, left, right, ""); LLVMValueRef add = LLVM.LLVMBuildAdd(builder, rem, right, ""); return LLVM.LLVMBuildSRem(builder, add, right, ""); } // unsigned modulo is the same as unsigned remainder return LLVM.LLVMBuildURem(builder, left, right, ""); } throw new IllegalArgumentException("Unknown arithmetic operator: " + arithmeticExpression.getOperator()); } if (expression instanceof ArrayAccessExpression) { ArrayAccessExpression arrayAccessExpression = (ArrayAccessExpression) expression; LLVMValueRef arrayValue = buildExpression(arrayAccessExpression.getArrayExpression(), llvmFunction, thisValue, variables); LLVMValueRef dimensionValue = buildExpression(arrayAccessExpression.getDimensionExpression(), llvmFunction, thisValue, variables); LLVMValueRef convertedDimensionValue = typeHelper.convertTemporaryToStandard(dimensionValue, arrayAccessExpression.getDimensionExpression().getType(), ArrayLengthMember.ARRAY_LENGTH_TYPE, llvmFunction); LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false), convertedDimensionValue}; LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, arrayValue, C.toNativePointerArray(indices, false, true), indices.length, ""); ArrayType arrayType = (ArrayType) arrayAccessExpression.getArrayExpression().getType(); return typeHelper.convertStandardPointerToTemporary(elementPointer, arrayType.getBaseType(), arrayAccessExpression.getType(), llvmFunction); } if (expression instanceof ArrayCreationExpression) { ArrayCreationExpression arrayCreationExpression = (ArrayCreationExpression) expression; ArrayType type = arrayCreationExpression.getDeclaredType(); Expression[] dimensionExpressions = arrayCreationExpression.getDimensionExpressions(); if (dimensionExpressions == null) { Expression[] valueExpressions = arrayCreationExpression.getValueExpressions(); LLVMValueRef llvmLength = LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), valueExpressions.length, false); LLVMValueRef array = buildArrayCreation(llvmFunction, new LLVMValueRef[] {llvmLength}, type); for (int i = 0; i < valueExpressions.length; i++) { LLVMValueRef expressionValue = buildExpression(valueExpressions[i], llvmFunction, thisValue, variables); LLVMValueRef convertedValue = typeHelper.convertTemporaryToStandard(expressionValue, valueExpressions[i].getType(), type.getBaseType(), llvmFunction); LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), i, false)}; LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, array, C.toNativePointerArray(indices, false, true), indices.length, ""); LLVM.LLVMBuildStore(builder, convertedValue, elementPointer); } return typeHelper.convertTemporary(array, type, arrayCreationExpression.getType()); } LLVMValueRef[] llvmLengths = new LLVMValueRef[dimensionExpressions.length]; for (int i = 0; i < llvmLengths.length; i++) { LLVMValueRef expressionValue = buildExpression(dimensionExpressions[i], llvmFunction, thisValue, variables); llvmLengths[i] = typeHelper.convertTemporaryToStandard(expressionValue, dimensionExpressions[i].getType(), ArrayLengthMember.ARRAY_LENGTH_TYPE, llvmFunction); } LLVMValueRef array = buildArrayCreation(llvmFunction, llvmLengths, type); return typeHelper.convertTemporary(array, type, arrayCreationExpression.getType()); } if (expression instanceof BitwiseNotExpression) { LLVMValueRef value = buildExpression(((BitwiseNotExpression) expression).getExpression(), llvmFunction, thisValue, variables); value = typeHelper.convertTemporary(value, ((BitwiseNotExpression) expression).getExpression().getType(), expression.getType()); return LLVM.LLVMBuildNot(builder, value, ""); } if (expression instanceof BooleanLiteralExpression) { LLVMValueRef value = LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), ((BooleanLiteralExpression) expression).getValue() ? 1 : 0, false); return typeHelper.convertStandardToTemporary(value, new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null), expression.getType(), llvmFunction); } if (expression instanceof BooleanNotExpression) { LLVMValueRef value = buildExpression(((BooleanNotExpression) expression).getExpression(), llvmFunction, thisValue, variables); LLVMValueRef result = LLVM.LLVMBuildNot(builder, value, ""); return typeHelper.convertTemporary(result, ((BooleanNotExpression) expression).getExpression().getType(), expression.getType()); } if (expression instanceof BracketedExpression) { BracketedExpression bracketedExpression = (BracketedExpression) expression; LLVMValueRef value = buildExpression(bracketedExpression.getExpression(), llvmFunction, thisValue, variables); return typeHelper.convertTemporary(value, bracketedExpression.getExpression().getType(), expression.getType()); } if (expression instanceof CastExpression) { CastExpression castExpression = (CastExpression) expression; LLVMValueRef value = buildExpression(castExpression.getExpression(), llvmFunction, thisValue, variables); return typeHelper.convertTemporary(value, castExpression.getExpression().getType(), castExpression.getType()); } if (expression instanceof ClassCreationExpression) { ClassCreationExpression classCreationExpression = (ClassCreationExpression) expression; Expression[] arguments = classCreationExpression.getArguments(); Constructor constructor = classCreationExpression.getResolvedConstructor(); Parameter[] parameters = constructor.getParameters(); LLVMValueRef[] llvmArguments = new LLVMValueRef[1 + arguments.length]; for (int i = 0; i < arguments.length; ++i) { LLVMValueRef argument = buildExpression(arguments[i], llvmFunction, thisValue, variables); llvmArguments[i + 1] = typeHelper.convertTemporaryToStandard(argument, arguments[i].getType(), parameters[i].getType(), llvmFunction); } Type type = classCreationExpression.getType(); LLVMTypeRef nativeType = typeHelper.findTemporaryType(type); LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false)}; LLVMValueRef llvmStructSize = LLVM.LLVMBuildGEP(builder, LLVM.LLVMConstNull(nativeType), C.toNativePointerArray(indices, false, true), indices.length, ""); LLVMValueRef llvmSize = LLVM.LLVMBuildPtrToInt(builder, llvmStructSize, LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), ""); LLVMValueRef[] callocArguments = new LLVMValueRef[] {llvmSize, LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false)}; LLVMValueRef memory = LLVM.LLVMBuildCall(builder, callocFunction, C.toNativePointerArray(callocArguments, false, true), callocArguments.length, ""); LLVMValueRef pointer = LLVM.LLVMBuildBitCast(builder, memory, nativeType, ""); llvmArguments[0] = pointer; // get the constructor and call it LLVMValueRef llvmFunc = getConstructorFunction(constructor); LLVM.LLVMBuildCall(builder, llvmFunc, C.toNativePointerArray(llvmArguments, false, true), llvmArguments.length, ""); return pointer; } if (expression instanceof EqualityExpression) { EqualityExpression equalityExpression = (EqualityExpression) expression; EqualityOperator operator = equalityExpression.getOperator(); // if the type checker has annotated this as a null check, just perform it without building both sub-expressions Expression nullCheckExpression = equalityExpression.getNullCheckExpression(); if (nullCheckExpression != null) { LLVMValueRef value = buildExpression(nullCheckExpression, llvmFunction, thisValue, variables); LLVMValueRef convertedValue = typeHelper.convertTemporary(value, nullCheckExpression.getType(), equalityExpression.getComparisonType()); LLVMValueRef nullity = buildNullCheck(convertedValue, equalityExpression.getComparisonType()); switch (operator) { case EQUAL: return LLVM.LLVMBuildNot(builder, nullity, ""); case NOT_EQUAL: return nullity; default: throw new IllegalArgumentException("Cannot build an EqualityExpression with no EqualityOperator"); } } LLVMValueRef left = buildExpression(equalityExpression.getLeftSubExpression(), llvmFunction, thisValue, variables); LLVMValueRef right = buildExpression(equalityExpression.getRightSubExpression(), llvmFunction, thisValue, variables); Type leftType = equalityExpression.getLeftSubExpression().getType(); Type rightType = equalityExpression.getRightSubExpression().getType(); Type comparisonType = equalityExpression.getComparisonType(); // if comparisonType is null, then the types are integers which cannot be assigned to each other either way around, because one is signed and the other is unsigned // so we must extend each of them to a larger bitCount which they can both fit into, and compare them there if (comparisonType == null) { if (!(leftType instanceof PrimitiveType) || !(rightType instanceof PrimitiveType)) { throw new IllegalStateException("A comparison type must be provided if either the left or right type is not a PrimitiveType: " + equalityExpression); } LLVMValueRef leftIsNotNull = LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 1, false); LLVMValueRef rightIsNotNull = LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 1, false); LLVMValueRef leftValue = left; LLVMValueRef rightValue = right; if (leftType.isNullable()) { leftIsNotNull = LLVM.LLVMBuildExtractValue(builder, left, 0, ""); leftValue = LLVM.LLVMBuildExtractValue(builder, left, 1, ""); } if (rightType.isNullable()) { rightIsNotNull = LLVM.LLVMBuildExtractValue(builder, right, 0, ""); rightValue = LLVM.LLVMBuildExtractValue(builder, right, 1, ""); } PrimitiveTypeType leftTypeType = ((PrimitiveType) leftType).getPrimitiveTypeType(); PrimitiveTypeType rightTypeType = ((PrimitiveType) rightType).getPrimitiveTypeType(); if (!leftTypeType.isFloating() && !rightTypeType.isFloating() && leftTypeType.isSigned() != rightTypeType.isSigned()) { // compare the signed and non-signed integers as (bitCount + 1) bit numbers, since they will not fit in bitCount bits int bitCount = Math.max(leftTypeType.getBitCount(), rightTypeType.getBitCount()) + 1; LLVMTypeRef llvmComparisonType = LLVM.LLVMIntType(bitCount); if (leftTypeType.isSigned()) { leftValue = LLVM.LLVMBuildSExt(builder, leftValue, llvmComparisonType, ""); rightValue = LLVM.LLVMBuildZExt(builder, rightValue, llvmComparisonType, ""); } else { leftValue = LLVM.LLVMBuildZExt(builder, leftValue, llvmComparisonType, ""); rightValue = LLVM.LLVMBuildSExt(builder, rightValue, llvmComparisonType, ""); } LLVMValueRef comparisonResult = LLVM.LLVMBuildICmp(builder, getPredicate(equalityExpression.getOperator(), false), leftValue, rightValue, ""); if (leftType.isNullable() || rightType.isNullable()) { LLVMValueRef nullityComparison = LLVM.LLVMBuildICmp(builder, getPredicate(equalityExpression.getOperator(), false), leftIsNotNull, rightIsNotNull, ""); if (equalityExpression.getOperator() == EqualityOperator.EQUAL) { comparisonResult = LLVM.LLVMBuildAnd(builder, nullityComparison, comparisonResult, ""); } else { comparisonResult = LLVM.LLVMBuildOr(builder, nullityComparison, comparisonResult, ""); } } return typeHelper.convertTemporary(comparisonResult, new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null), equalityExpression.getType()); } throw new IllegalArgumentException("Unknown result type, unable to generate comparison expression: " + equalityExpression); } // perform a standard equality check, using buildEqualityCheck() left = typeHelper.convertTemporary(left, leftType, comparisonType); right = typeHelper.convertTemporary(right, rightType, comparisonType); return buildEqualityCheck(left, right, comparisonType, operator, llvmFunction); } if (expression instanceof FieldAccessExpression) { FieldAccessExpression fieldAccessExpression = (FieldAccessExpression) expression; Member member = fieldAccessExpression.getResolvedMember(); Expression baseExpression = fieldAccessExpression.getBaseExpression(); if (baseExpression != null) { LLVMValueRef baseValue = buildExpression(baseExpression, llvmFunction, thisValue, variables); LLVMValueRef notNullValue = baseValue; LLVMBasicBlockRef startBlock = null; LLVMBasicBlockRef continuationBlock = null; if (fieldAccessExpression.isNullTraversing()) { LLVMValueRef nullCheckResult = buildNullCheck(baseValue, baseExpression.getType()); LLVMBasicBlockRef accessBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "nullTraversalAccess"); continuationBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "nullTraversalContinuation"); startBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildCondBr(builder, nullCheckResult, accessBlock, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, accessBlock); notNullValue = typeHelper.convertTemporary(baseValue, baseExpression.getType(), TypeChecker.findTypeWithNullability(baseExpression.getType(), false)); } LLVMValueRef result; if (member instanceof ArrayLengthMember) { LLVMValueRef array = notNullValue; LLVMValueRef[] sizeIndices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false)}; LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, array, C.toNativePointerArray(sizeIndices, false, true), sizeIndices.length, ""); result = LLVM.LLVMBuildLoad(builder, elementPointer, ""); result = typeHelper.convertStandardToTemporary(result, ArrayLengthMember.ARRAY_LENGTH_TYPE, fieldAccessExpression.getType(), llvmFunction); } else if (member instanceof Field) { Field field = (Field) member; if (field.isStatic()) { throw new IllegalStateException("A FieldAccessExpression for a static field should not have a base expression"); } LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), field.getMemberIndex(), false)}; LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, notNullValue, C.toNativePointerArray(indices, false, true), indices.length, ""); result = typeHelper.convertStandardPointerToTemporary(elementPointer, field.getType(), fieldAccessExpression.getType(), llvmFunction); } else if (member instanceof Method) { Method method = (Method) member; Parameter[] parameters = method.getParameters(); Type[] parameterTypes = new Type[parameters.length]; for (int i = 0; i < parameters.length; ++i) { parameterTypes[i] = parameters[i].getType(); } FunctionType functionType = new FunctionType(false, method.isImmutable(), method.getReturnType(), parameterTypes, null); if (method.isStatic()) { throw new IllegalStateException("A FieldAccessExpression for a static method should not have a base expression"); } LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder); LLVMValueRef function = getMethodFunction(method); LLVM.LLVMPositionBuilderAtEnd(builder, currentBlock); function = LLVM.LLVMBuildBitCast(builder, function, typeHelper.findRawFunctionPointerType(functionType), ""); LLVMValueRef firstArgument = LLVM.LLVMBuildBitCast(builder, notNullValue, typeHelper.getOpaquePointer(), ""); result = LLVM.LLVMGetUndef(typeHelper.findStandardType(functionType)); result = LLVM.LLVMBuildInsertValue(builder, result, firstArgument, 0, ""); result = LLVM.LLVMBuildInsertValue(builder, result, function, 1, ""); result = typeHelper.convertStandardToTemporary(result, functionType, fieldAccessExpression.getType(), llvmFunction); } else { throw new IllegalArgumentException("Unknown member type for a FieldAccessExpression: " + member); } if (fieldAccessExpression.isNullTraversing()) { LLVMBasicBlockRef accessBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); LLVMValueRef phiNode = LLVM.LLVMBuildPhi(builder, typeHelper.findTemporaryType(fieldAccessExpression.getType()), ""); LLVMValueRef nullAlternative = LLVM.LLVMConstNull(typeHelper.findTemporaryType(fieldAccessExpression.getType())); LLVMValueRef[] phiValues = new LLVMValueRef[] {result, nullAlternative}; LLVMBasicBlockRef[] phiBlocks = new LLVMBasicBlockRef[] {accessBlock, startBlock}; LLVM.LLVMAddIncoming(phiNode, C.toNativePointerArray(phiValues, false, true), C.toNativePointerArray(phiBlocks, false, true), phiValues.length); return phiNode; } return result; } // we don't have a base expression, so handle the static field accesses if (member instanceof Field) { Field field = (Field) member; if (!field.isStatic()) { throw new IllegalStateException("A FieldAccessExpression for a non-static field should have a base expression"); } LLVMValueRef global = getGlobal(field.getGlobalVariable()); return typeHelper.convertStandardPointerToTemporary(global, field.getType(), fieldAccessExpression.getType(), llvmFunction); } if (member instanceof Method) { Method method = (Method) member; if (!method.isStatic()) { throw new IllegalStateException("A FieldAccessExpression for a non-static method should have a base expression"); } Parameter[] parameters = method.getParameters(); Type[] parameterTypes = new Type[parameters.length]; for (int i = 0; i < parameters.length; ++i) { parameterTypes[i] = parameters[i].getType(); } FunctionType functionType = new FunctionType(false, method.isImmutable(), method.getReturnType(), parameterTypes, null); LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder); LLVMValueRef function = getMethodFunction(method); LLVM.LLVMPositionBuilderAtEnd(builder, currentBlock); function = LLVM.LLVMBuildBitCast(builder, function, typeHelper.findRawFunctionPointerType(functionType), ""); LLVMValueRef firstArgument = LLVM.LLVMConstNull(typeHelper.getOpaquePointer()); LLVMValueRef result = LLVM.LLVMGetUndef(typeHelper.findStandardType(functionType)); result = LLVM.LLVMBuildInsertValue(builder, result, firstArgument, 0, ""); result = LLVM.LLVMBuildInsertValue(builder, result, function, 1, ""); return typeHelper.convertStandardToTemporary(result, functionType, fieldAccessExpression.getType(), llvmFunction); } throw new IllegalArgumentException("Unknown member type for a FieldAccessExpression: " + member); } if (expression instanceof FloatingLiteralExpression) { double value = Double.parseDouble(((FloatingLiteralExpression) expression).getLiteral().toString()); LLVMValueRef llvmValue = LLVM.LLVMConstReal(typeHelper.findStandardType(TypeChecker.findTypeWithNullability(expression.getType(), false)), value); return typeHelper.convertStandardToTemporary(llvmValue, TypeChecker.findTypeWithNullability(expression.getType(), false), expression.getType(), llvmFunction); } if (expression instanceof FunctionCallExpression) { FunctionCallExpression functionExpression = (FunctionCallExpression) expression; Constructor resolvedConstructor = functionExpression.getResolvedConstructor(); Method resolvedMethod = functionExpression.getResolvedMethod(); Expression resolvedBaseExpression = functionExpression.getResolvedBaseExpression(); Type[] parameterTypes; Type returnType; LLVMValueRef llvmResolvedFunction; if (resolvedConstructor != null) { Parameter[] params = resolvedConstructor.getParameters(); parameterTypes = new Type[params.length]; for (int i = 0; i < params.length; ++i) { parameterTypes[i] = params[i].getType(); } returnType = new NamedType(false, false, resolvedConstructor.getContainingTypeDefinition()); llvmResolvedFunction = getConstructorFunction(resolvedConstructor); } else if (resolvedMethod != null) { Parameter[] params = resolvedMethod.getParameters(); parameterTypes = new Type[params.length]; for (int i = 0; i < params.length; ++i) { parameterTypes[i] = params[i].getType(); } returnType = resolvedMethod.getReturnType(); LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder); llvmResolvedFunction = getMethodFunction(resolvedMethod); LLVM.LLVMPositionBuilderAtEnd(builder, currentBlock); } else if (resolvedBaseExpression != null) { FunctionType baseType = (FunctionType) resolvedBaseExpression.getType(); parameterTypes = baseType.getParameterTypes(); returnType = baseType.getReturnType(); llvmResolvedFunction = null; } else { throw new IllegalArgumentException("Unresolved function call expression: " + functionExpression); } LLVMValueRef callee = null; if (resolvedBaseExpression != null) { callee = buildExpression(resolvedBaseExpression, llvmFunction, thisValue, variables); } // if this is a null traversing function call, apply it properly boolean nullTraversal = resolvedBaseExpression != null && resolvedMethod != null && functionExpression.getResolvedNullTraversal(); LLVMValueRef notNullCallee = callee; LLVMBasicBlockRef startBlock = null; LLVMBasicBlockRef continuationBlock = null; if (nullTraversal) { LLVMValueRef nullCheckResult = buildNullCheck(callee, resolvedBaseExpression.getType()); LLVMBasicBlockRef callBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "nullTraversalCall"); continuationBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "nullTraversalCallContinuation"); startBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildCondBr(builder, nullCheckResult, callBlock, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, callBlock); notNullCallee = typeHelper.convertTemporary(callee, resolvedBaseExpression.getType(), TypeChecker.findTypeWithNullability(resolvedBaseExpression.getType(), false)); } Expression[] arguments = functionExpression.getArguments(); LLVMValueRef[] values = new LLVMValueRef[arguments.length]; for (int i = 0; i < arguments.length; i++) { LLVMValueRef arg = buildExpression(arguments[i], llvmFunction, thisValue, variables); values[i] = typeHelper.convertTemporaryToStandard(arg, arguments[i].getType(), parameterTypes[i], llvmFunction); } LLVMValueRef result; boolean resultIsTemporary = false; // true iff result has a temporary type representation if (resolvedConstructor != null) { // build an alloca in the entry block for the result of the constructor call LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMPositionBuilderAtStart(builder, LLVM.LLVMGetEntryBasicBlock(llvmFunction)); // find the type to alloca, which is the standard representation of a non-nullable type // when we alloca this type, it becomes equivalent to the temporary type representation of this compound type (with any nullability) LLVMTypeRef allocaBaseType = typeHelper.findStandardType(returnType); LLVMValueRef alloca = LLVM.LLVMBuildAlloca(builder, allocaBaseType, ""); LLVM.LLVMPositionBuilderAtEnd(builder, currentBlock); typeHelper.initialiseCompoundType((CompoundDefinition) ((NamedType) returnType).getResolvedTypeDefinition(), alloca); LLVMValueRef[] realArguments = new LLVMValueRef[1 + values.length]; realArguments[0] = alloca; System.arraycopy(values, 0, realArguments, 1, values.length); LLVM.LLVMBuildCall(builder, llvmResolvedFunction, C.toNativePointerArray(realArguments, false, true), realArguments.length, ""); result = alloca; resultIsTemporary = true; } else if (resolvedMethod != null) { LLVMValueRef[] realArguments = new LLVMValueRef[values.length + 1]; if (resolvedMethod.isStatic()) { realArguments[0] = LLVM.LLVMConstNull(typeHelper.getOpaquePointer()); } else { realArguments[0] = notNullCallee != null ? notNullCallee : thisValue; } System.arraycopy(values, 0, realArguments, 1, values.length); result = LLVM.LLVMBuildCall(builder, llvmResolvedFunction, C.toNativePointerArray(realArguments, false, true), realArguments.length, ""); } else if (resolvedBaseExpression != null) { // callee here is actually a tuple of an opaque pointer and a function type, where the first argument to the function is the opaque pointer LLVMValueRef firstArgument = LLVM.LLVMBuildExtractValue(builder, callee, 0, ""); LLVMValueRef calleeFunction = LLVM.LLVMBuildExtractValue(builder, callee, 1, ""); LLVMValueRef[] realArguments = new LLVMValueRef[values.length + 1]; realArguments[0] = firstArgument; System.arraycopy(values, 0, realArguments, 1, values.length); result = LLVM.LLVMBuildCall(builder, calleeFunction, C.toNativePointerArray(realArguments, false, true), realArguments.length, ""); } else { throw new IllegalArgumentException("Unresolved function call expression: " + functionExpression); } if (nullTraversal) { if (returnType instanceof VoidType) { LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); return null; } if (resultIsTemporary) { result = typeHelper.convertTemporary(result, returnType, functionExpression.getType()); } else { result = typeHelper.convertStandardToTemporary(result, returnType, functionExpression.getType(), llvmFunction); } LLVMBasicBlockRef callBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); LLVMValueRef phiNode = LLVM.LLVMBuildPhi(builder, typeHelper.findTemporaryType(functionExpression.getType()), ""); LLVMValueRef nullAlternative = LLVM.LLVMConstNull(typeHelper.findTemporaryType(functionExpression.getType())); LLVMValueRef[] phiValues = new LLVMValueRef[] {result, nullAlternative}; LLVMBasicBlockRef[] phiBlocks = new LLVMBasicBlockRef[] {callBlock, startBlock}; LLVM.LLVMAddIncoming(phiNode, C.toNativePointerArray(phiValues, false, true), C.toNativePointerArray(phiBlocks, false, true), phiValues.length); return phiNode; } if (returnType instanceof VoidType) { return result; } if (resultIsTemporary) { return typeHelper.convertTemporary(result, returnType, functionExpression.getType()); } return typeHelper.convertStandardToTemporary(result, returnType, functionExpression.getType(), llvmFunction); } if (expression instanceof InlineIfExpression) { InlineIfExpression inlineIf = (InlineIfExpression) expression; LLVMValueRef conditionValue = buildExpression(inlineIf.getCondition(), llvmFunction, thisValue, variables); conditionValue = typeHelper.convertTemporaryToStandard(conditionValue, inlineIf.getCondition().getType(), new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null), llvmFunction); LLVMBasicBlockRef thenBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "inlineIfThen"); LLVMBasicBlockRef elseBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "inlineIfElse"); LLVMBasicBlockRef continuationBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "afterInlineIf"); LLVM.LLVMBuildCondBr(builder, conditionValue, thenBlock, elseBlock); LLVM.LLVMPositionBuilderAtEnd(builder, thenBlock); LLVMValueRef thenValue = buildExpression(inlineIf.getThenExpression(), llvmFunction, thisValue, variables); LLVMValueRef convertedThenValue = typeHelper.convertTemporary(thenValue, inlineIf.getThenExpression().getType(), inlineIf.getType()); LLVMBasicBlockRef thenBranchBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, elseBlock); LLVMValueRef elseValue = buildExpression(inlineIf.getElseExpression(), llvmFunction, thisValue, variables); LLVMValueRef convertedElseValue = typeHelper.convertTemporary(elseValue, inlineIf.getElseExpression().getType(), inlineIf.getType()); LLVMBasicBlockRef elseBranchBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); LLVMValueRef result = LLVM.LLVMBuildPhi(builder, typeHelper.findTemporaryType(inlineIf.getType()), ""); LLVMValueRef[] incomingValues = new LLVMValueRef[] {convertedThenValue, convertedElseValue}; LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {thenBranchBlock, elseBranchBlock}; LLVM.LLVMAddIncoming(result, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), 2); return result; } if (expression instanceof IntegerLiteralExpression) { BigInteger bigintValue = ((IntegerLiteralExpression) expression).getLiteral().getValue(); byte[] bytes = bigintValue.toByteArray(); // convert the big-endian byte[] from the BigInteger into a little-endian long[] for LLVM long[] longs = new long[(bytes.length + 7) / 8]; for (int i = 0; i < bytes.length; ++i) { int longIndex = (bytes.length - 1 - i) / 8; int longBitPos = ((bytes.length - 1 - i) % 8) * 8; longs[longIndex] |= (((long) bytes[i]) & 0xff) << longBitPos; } LLVMValueRef value = LLVM.LLVMConstIntOfArbitraryPrecision(typeHelper.findStandardType(TypeChecker.findTypeWithNullability(expression.getType(), false)), longs.length, longs); return typeHelper.convertStandardToTemporary(value, TypeChecker.findTypeWithNullability(expression.getType(), false), expression.getType(), llvmFunction); } if (expression instanceof LogicalExpression) { LogicalExpression logicalExpression = (LogicalExpression) expression; LLVMValueRef left = buildExpression(logicalExpression.getLeftSubExpression(), llvmFunction, thisValue, variables); PrimitiveType leftType = (PrimitiveType) logicalExpression.getLeftSubExpression().getType(); PrimitiveType rightType = (PrimitiveType) logicalExpression.getRightSubExpression().getType(); // cast if necessary PrimitiveType resultType = (PrimitiveType) logicalExpression.getType(); left = typeHelper.convertTemporary(left, leftType, resultType); LogicalOperator operator = logicalExpression.getOperator(); if (operator != LogicalOperator.SHORT_CIRCUIT_AND && operator != LogicalOperator.SHORT_CIRCUIT_OR) { LLVMValueRef right = buildExpression(logicalExpression.getRightSubExpression(), llvmFunction, thisValue, variables); right = typeHelper.convertTemporary(right, rightType, resultType); switch (operator) { case AND: return LLVM.LLVMBuildAnd(builder, left, right, ""); case OR: return LLVM.LLVMBuildOr(builder, left, right, ""); case XOR: return LLVM.LLVMBuildXor(builder, left, right, ""); default: throw new IllegalStateException("Unexpected non-short-circuit operator: " + logicalExpression.getOperator()); } } LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder); LLVMBasicBlockRef rightCheckBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "shortCircuitCheck"); LLVMBasicBlockRef continuationBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "shortCircuitContinue"); // the only difference between short circuit AND and OR is whether they jump to the check block when the left hand side is true or false LLVMBasicBlockRef trueDest = operator == LogicalOperator.SHORT_CIRCUIT_AND ? rightCheckBlock : continuationBlock; LLVMBasicBlockRef falseDest = operator == LogicalOperator.SHORT_CIRCUIT_AND ? continuationBlock : rightCheckBlock; LLVM.LLVMBuildCondBr(builder, left, trueDest, falseDest); LLVM.LLVMPositionBuilderAtEnd(builder, rightCheckBlock); LLVMValueRef right = buildExpression(logicalExpression.getRightSubExpression(), llvmFunction, thisValue, variables); right = typeHelper.convertTemporary(right, rightType, resultType); LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); // create a phi node for the result, and return it LLVMValueRef phi = LLVM.LLVMBuildPhi(builder, typeHelper.findTemporaryType(resultType), ""); LLVMValueRef[] incomingValues = new LLVMValueRef[] {left, right}; LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {currentBlock, rightCheckBlock}; LLVM.LLVMAddIncoming(phi, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), 2); return phi; } if (expression instanceof MinusExpression) { MinusExpression minusExpression = (MinusExpression) expression; LLVMValueRef value = buildExpression(minusExpression.getExpression(), llvmFunction, thisValue, variables); value = typeHelper.convertTemporary(value, minusExpression.getExpression().getType(), TypeChecker.findTypeWithNullability(minusExpression.getType(), false)); PrimitiveTypeType primitiveTypeType = ((PrimitiveType) minusExpression.getType()).getPrimitiveTypeType(); LLVMValueRef result; if (primitiveTypeType.isFloating()) { result = LLVM.LLVMBuildFNeg(builder, value, ""); } else { result = LLVM.LLVMBuildNeg(builder, value, ""); } return typeHelper.convertTemporary(result, TypeChecker.findTypeWithNullability(minusExpression.getType(), false), minusExpression.getType()); } if (expression instanceof NullCoalescingExpression) { NullCoalescingExpression nullCoalescingExpression = (NullCoalescingExpression) expression; LLVMValueRef nullableValue = buildExpression(nullCoalescingExpression.getNullableExpression(), llvmFunction, thisValue, variables); nullableValue = typeHelper.convertTemporary(nullableValue, nullCoalescingExpression.getNullableExpression().getType(), TypeChecker.findTypeWithNullability(nullCoalescingExpression.getType(), true)); LLVMValueRef checkResult = buildNullCheck(nullableValue, TypeChecker.findTypeWithNullability(nullCoalescingExpression.getType(), true)); LLVMBasicBlockRef conversionBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "nullCoalescingConversion"); LLVMBasicBlockRef alternativeBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "nullCoalescingAlternative"); LLVMBasicBlockRef continuationBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "nullCoalescingContinuation"); LLVM.LLVMBuildCondBr(builder, checkResult, conversionBlock, alternativeBlock); // create a block to convert the nullable value into a non-nullable value LLVM.LLVMPositionBuilderAtEnd(builder, conversionBlock); LLVMValueRef convertedNullableValue = typeHelper.convertTemporary(nullableValue, TypeChecker.findTypeWithNullability(nullCoalescingExpression.getType(), true), nullCoalescingExpression.getType()); LLVMBasicBlockRef endConversionBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, alternativeBlock); LLVMValueRef alternativeValue = buildExpression(nullCoalescingExpression.getAlternativeExpression(), llvmFunction, thisValue, variables); alternativeValue = typeHelper.convertTemporary(alternativeValue, nullCoalescingExpression.getAlternativeExpression().getType(), nullCoalescingExpression.getType()); LLVMBasicBlockRef endAlternativeBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); // create a phi node for the result, and return it LLVMTypeRef resultType = typeHelper.findTemporaryType(nullCoalescingExpression.getType()); LLVMValueRef result = LLVM.LLVMBuildPhi(builder, resultType, ""); LLVMValueRef[] incomingValues = new LLVMValueRef[] {convertedNullableValue, alternativeValue}; LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {endConversionBlock, endAlternativeBlock}; LLVM.LLVMAddIncoming(result, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), incomingValues.length); return result; } if (expression instanceof NullLiteralExpression) { Type type = expression.getType(); return LLVM.LLVMConstNull(typeHelper.findTemporaryType(type)); } if (expression instanceof RelationalExpression) { RelationalExpression relationalExpression = (RelationalExpression) expression; LLVMValueRef left = buildExpression(relationalExpression.getLeftSubExpression(), llvmFunction, thisValue, variables); LLVMValueRef right = buildExpression(relationalExpression.getRightSubExpression(), llvmFunction, thisValue, variables); PrimitiveType leftType = (PrimitiveType) relationalExpression.getLeftSubExpression().getType(); PrimitiveType rightType = (PrimitiveType) relationalExpression.getRightSubExpression().getType(); // cast if necessary PrimitiveType resultType = relationalExpression.getComparisonType(); if (resultType == null) { PrimitiveTypeType leftTypeType = leftType.getPrimitiveTypeType(); PrimitiveTypeType rightTypeType = rightType.getPrimitiveTypeType(); if (!leftTypeType.isFloating() && !rightTypeType.isFloating() && leftTypeType.isSigned() != rightTypeType.isSigned() && !leftType.isNullable() && !rightType.isNullable()) { // compare the signed and non-signed integers as (bitCount + 1) bit numbers, since they will not fit in bitCount bits int bitCount = Math.max(leftTypeType.getBitCount(), rightTypeType.getBitCount()) + 1; LLVMTypeRef comparisonType = LLVM.LLVMIntType(bitCount); if (leftTypeType.isSigned()) { left = LLVM.LLVMBuildSExt(builder, left, comparisonType, ""); right = LLVM.LLVMBuildZExt(builder, right, comparisonType, ""); } else { left = LLVM.LLVMBuildZExt(builder, left, comparisonType, ""); right = LLVM.LLVMBuildSExt(builder, right, comparisonType, ""); } return LLVM.LLVMBuildICmp(builder, getPredicate(relationalExpression.getOperator(), false, true), left, right, ""); } throw new IllegalArgumentException("Unknown result type, unable to generate comparison expression: " + expression); } left = typeHelper.convertTemporary(left, leftType, resultType); right = typeHelper.convertTemporary(right, rightType, resultType); LLVMValueRef result; if (resultType.getPrimitiveTypeType().isFloating()) { result = LLVM.LLVMBuildFCmp(builder, getPredicate(relationalExpression.getOperator(), true, true), left, right, ""); } else { result = LLVM.LLVMBuildICmp(builder, getPredicate(relationalExpression.getOperator(), false, resultType.getPrimitiveTypeType().isSigned()), left, right, ""); } return typeHelper.convertTemporary(result, new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null), relationalExpression.getType()); } if (expression instanceof ShiftExpression) { ShiftExpression shiftExpression = (ShiftExpression) expression; LLVMValueRef leftValue = buildExpression(shiftExpression.getLeftExpression(), llvmFunction, thisValue, variables); LLVMValueRef rightValue = buildExpression(shiftExpression.getRightExpression(), llvmFunction, thisValue, variables); LLVMValueRef convertedLeft = typeHelper.convertTemporary(leftValue, shiftExpression.getLeftExpression().getType(), shiftExpression.getType()); LLVMValueRef convertedRight = typeHelper.convertTemporary(rightValue, shiftExpression.getRightExpression().getType(), shiftExpression.getType()); switch (shiftExpression.getOperator()) { case RIGHT_SHIFT: if (((PrimitiveType) shiftExpression.getType()).getPrimitiveTypeType().isSigned()) { return LLVM.LLVMBuildAShr(builder, convertedLeft, convertedRight, ""); } return LLVM.LLVMBuildLShr(builder, convertedLeft, convertedRight, ""); case LEFT_SHIFT: return LLVM.LLVMBuildShl(builder, convertedLeft, convertedRight, ""); } throw new IllegalArgumentException("Unknown shift operator: " + shiftExpression.getOperator()); } if (expression instanceof StringLiteralExpression) { StringLiteralExpression stringLiteralExpression = (StringLiteralExpression) expression; String value = stringLiteralExpression.getLiteral().getLiteralValue(); byte[] bytes; try { bytes = value.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("UTF-8 encoding not supported!", e); } // build the []ubyte up from the string value, and store it as a global variable LLVMValueRef lengthValue = LLVM.LLVMConstInt(typeHelper.findStandardType(ArrayLengthMember.ARRAY_LENGTH_TYPE), bytes.length, false); LLVMValueRef constString = LLVM.LLVMConstString(bytes, bytes.length, true); LLVMValueRef[] arrayValues = new LLVMValueRef[] {lengthValue, constString}; LLVMValueRef byteArrayStruct = LLVM.LLVMConstStruct(C.toNativePointerArray(arrayValues, false, true), arrayValues.length, false); LLVMTypeRef stringType = LLVM.LLVMArrayType(LLVM.LLVMInt8Type(), bytes.length); LLVMTypeRef[] structSubTypes = new LLVMTypeRef[] {typeHelper.findStandardType(ArrayLengthMember.ARRAY_LENGTH_TYPE), stringType}; LLVMTypeRef structType = LLVM.LLVMStructType(C.toNativePointerArray(structSubTypes, false, true), structSubTypes.length, false); LLVMValueRef globalVariable = LLVM.LLVMAddGlobal(module, structType, "str"); LLVM.LLVMSetInitializer(globalVariable, byteArrayStruct); LLVM.LLVMSetLinkage(globalVariable, LLVM.LLVMLinkage.LLVMPrivateLinkage); LLVM.LLVMSetGlobalConstant(globalVariable, true); // extract the string([]ubyte) constructor from the type of this expression Type arrayType = new ArrayType(false, true, new PrimitiveType(false, PrimitiveTypeType.UBYTE, null), null); LLVMValueRef constructorFunction = getConstructorFunction(SpecialTypeHandler.stringArrayConstructor); LLVMValueRef bitcastedArray = LLVM.LLVMBuildBitCast(builder, globalVariable, typeHelper.findStandardType(arrayType), ""); // build an alloca in the entry block for the string value LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMPositionBuilderAtStart(builder, LLVM.LLVMGetEntryBasicBlock(llvmFunction)); // find the type to alloca, which is the standard representation of a non-nullable version of this type // when we alloca this type, it becomes equivalent to the temporary type representation of this compound type (with any nullability) LLVMTypeRef allocaBaseType = typeHelper.findStandardType(new NamedType(false, false, SpecialTypeHandler.stringArrayConstructor.getContainingTypeDefinition())); LLVMValueRef alloca = LLVM.LLVMBuildAlloca(builder, allocaBaseType, ""); LLVM.LLVMPositionBuilderAtEnd(builder, currentBlock); typeHelper.initialiseCompoundType((CompoundDefinition) SpecialTypeHandler.stringArrayConstructor.getContainingTypeDefinition(), alloca); LLVMValueRef[] arguments = new LLVMValueRef[] {alloca, bitcastedArray}; LLVM.LLVMBuildCall(builder, constructorFunction, C.toNativePointerArray(arguments, false, true), arguments.length, ""); return typeHelper.convertTemporary(alloca, new NamedType(false, false, SpecialTypeHandler.stringArrayConstructor.getContainingTypeDefinition()), expression.getType()); } if (expression instanceof ThisExpression) { // the 'this' value always has a temporary representation return thisValue; } if (expression instanceof TupleExpression) { TupleExpression tupleExpression = (TupleExpression) expression; Type[] tupleTypes = ((TupleType) tupleExpression.getType()).getSubTypes(); Expression[] subExpressions = tupleExpression.getSubExpressions(); Type nonNullableTupleType = TypeChecker.findTypeWithNullability(tupleExpression.getType(), false); LLVMValueRef currentValue = LLVM.LLVMGetUndef(typeHelper.findTemporaryType(nonNullableTupleType)); for (int i = 0; i < subExpressions.length; i++) { LLVMValueRef value = buildExpression(subExpressions[i], llvmFunction, thisValue, variables); Type type = tupleTypes[i]; value = typeHelper.convertTemporary(value, subExpressions[i].getType(), type); currentValue = LLVM.LLVMBuildInsertValue(builder, currentValue, value, i, ""); } return typeHelper.convertTemporary(currentValue, nonNullableTupleType, tupleExpression.getType()); } if (expression instanceof TupleIndexExpression) { TupleIndexExpression tupleIndexExpression = (TupleIndexExpression) expression; TupleType tupleType = (TupleType) tupleIndexExpression.getExpression().getType(); LLVMValueRef result = buildExpression(tupleIndexExpression.getExpression(), llvmFunction, thisValue, variables); // convert the 1-based indexing to 0-based before extracting the value int index = tupleIndexExpression.getIndexLiteral().getValue().intValue() - 1; LLVMValueRef value = LLVM.LLVMBuildExtractValue(builder, result, index, ""); return typeHelper.convertTemporary(value, tupleType.getSubTypes()[index], tupleIndexExpression.getType()); } if (expression instanceof VariableExpression) { VariableExpression variableExpression = (VariableExpression) expression; Variable variable = variableExpression.getResolvedVariable(); if (variable != null) { if (variable instanceof MemberVariable) { Field field = ((MemberVariable) variable).getField(); LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), field.getMemberIndex(), false)}; LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, thisValue, C.toNativePointerArray(indices, false, true), indices.length, ""); return typeHelper.convertStandardPointerToTemporary(elementPointer, variable.getType(), variableExpression.getType(), llvmFunction); } if (variable instanceof GlobalVariable) { LLVMValueRef global = getGlobal((GlobalVariable) variable); return typeHelper.convertStandardPointerToTemporary(global, variable.getType(), variableExpression.getType(), llvmFunction); } LLVMValueRef value = variables.get(variable); if (value == null) { throw new IllegalStateException("Missing LLVMValueRef in variable Map: " + variableExpression.getName()); } return LLVM.LLVMBuildLoad(builder, value, ""); } Method method = variableExpression.getResolvedMethod(); if (method != null) { Parameter[] parameters = method.getParameters(); Type[] parameterTypes = new Type[parameters.length]; for (int i = 0; i < parameters.length; ++i) { parameterTypes[i] = parameters[i].getType(); } FunctionType functionType = new FunctionType(false, method.isImmutable(), method.getReturnType(), parameterTypes, null); LLVMValueRef function = getMethodFunction(method); function = LLVM.LLVMBuildBitCast(builder, function, typeHelper.findRawFunctionPointerType(functionType), ""); LLVMValueRef firstArgument; if (method.isStatic()) { firstArgument = LLVM.LLVMConstNull(typeHelper.getOpaquePointer()); } else { firstArgument = LLVM.LLVMBuildBitCast(builder, thisValue, typeHelper.getOpaquePointer(), ""); } LLVMValueRef result = LLVM.LLVMGetUndef(typeHelper.findStandardType(functionType)); result = LLVM.LLVMBuildInsertValue(builder, result, firstArgument, 0, ""); result = LLVM.LLVMBuildInsertValue(builder, result, function, 1, ""); return typeHelper.convertStandardToTemporary(result, functionType, variableExpression.getType(), llvmFunction); } } throw new IllegalArgumentException("Unknown Expression type: " + expression); }
diff --git a/src/com/orangeleap/tangerine/controller/importexport/CsvExportController.java b/src/com/orangeleap/tangerine/controller/importexport/CsvExportController.java index 8d55a295..3dac5c3b 100644 --- a/src/com/orangeleap/tangerine/controller/importexport/CsvExportController.java +++ b/src/com/orangeleap/tangerine/controller/importexport/CsvExportController.java @@ -1,116 +1,118 @@ package com.orangeleap.tangerine.controller.importexport; import java.io.PrintWriter; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.context.ApplicationContext; import org.springframework.validation.BindException; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.SimpleFormController; import au.com.bytecode.opencsv.CSVWriter; import com.orangeleap.tangerine.controller.importexport.exporters.EntityExporter; import com.orangeleap.tangerine.controller.importexport.exporters.EntityExporterFactory; public class CsvExportController extends SimpleFormController { protected final Log logger = LogFactory.getLog(getClass()); @Override protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception { super.initBinder(request, binder); binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("MM/dd/yyyy"), true)); // TODO: custom date format } @Override protected Object formBackingObject(HttpServletRequest request) throws ServletException { return new ExportRequest(); } private static final SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); private static Date FUTURE_DATE; private static Date PAST_DATE; static { try { FUTURE_DATE = sdf.parse("1/1/2100"); PAST_DATE = sdf.parse("1/1/1900"); } catch (Exception e) {} } private static final String LOW_ID = new String("0"); private static final String HIGH_ID = new String("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"); @Override protected ModelAndView processFormSubmission( HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { ExportRequest er = (ExportRequest)command; if (er.getFromDate() == null) er.setFromDate(PAST_DATE); if (er.getToDate() == null) er.setToDate(FUTURE_DATE); if (StringUtils.trimToNull(er.getFromId()) == null) er.setFromId(LOW_ID); if (StringUtils.trimToNull(er.getToId()) == null) er.setToId(HIGH_ID); if (!CsvImportController.importexportAllowed(request)) { return null; // For security only, unauthorized users will not have the menu option to even get here normally. } try { String exportData = getExport(er); response.setContentType("application/x-download"); String entity = er.getEntity(); if (entity.equals("person")) entity = "constituent"; response.setHeader("Content-Disposition", "attachment; filename=" + entity + "-export.csv"); response.setContentLength(exportData.length()); PrintWriter out = response.getWriter(); out.print(exportData); out.flush(); return null; } catch (Exception e) { + logger.debug(e); + e.printStackTrace(); ModelAndView mav = new ModelAndView("redirect:/importexport.htm"); mav.addObject("exportmessage", e.getMessage()); return mav; } } private String getExport(ExportRequest er) { StringWriter sw = new StringWriter(); CSVWriter writer = new CSVWriter(sw); ApplicationContext applicationContext = getApplicationContext(); EntityExporter ex = new EntityExporterFactory().getEntityExporter(er, applicationContext); if (ex == null) return ""; List<List<String>> data = ex.exportAll(); List<String[]> csvdata = new ArrayList<String[]>(); for (List<String> line:data) { String[] aline = line.toArray(new String[line.size()]); csvdata.add(aline); } writer.writeAll(csvdata); return sw.toString(); } }
true
true
protected ModelAndView processFormSubmission( HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { ExportRequest er = (ExportRequest)command; if (er.getFromDate() == null) er.setFromDate(PAST_DATE); if (er.getToDate() == null) er.setToDate(FUTURE_DATE); if (StringUtils.trimToNull(er.getFromId()) == null) er.setFromId(LOW_ID); if (StringUtils.trimToNull(er.getToId()) == null) er.setToId(HIGH_ID); if (!CsvImportController.importexportAllowed(request)) { return null; // For security only, unauthorized users will not have the menu option to even get here normally. } try { String exportData = getExport(er); response.setContentType("application/x-download"); String entity = er.getEntity(); if (entity.equals("person")) entity = "constituent"; response.setHeader("Content-Disposition", "attachment; filename=" + entity + "-export.csv"); response.setContentLength(exportData.length()); PrintWriter out = response.getWriter(); out.print(exportData); out.flush(); return null; } catch (Exception e) { ModelAndView mav = new ModelAndView("redirect:/importexport.htm"); mav.addObject("exportmessage", e.getMessage()); return mav; } }
protected ModelAndView processFormSubmission( HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { ExportRequest er = (ExportRequest)command; if (er.getFromDate() == null) er.setFromDate(PAST_DATE); if (er.getToDate() == null) er.setToDate(FUTURE_DATE); if (StringUtils.trimToNull(er.getFromId()) == null) er.setFromId(LOW_ID); if (StringUtils.trimToNull(er.getToId()) == null) er.setToId(HIGH_ID); if (!CsvImportController.importexportAllowed(request)) { return null; // For security only, unauthorized users will not have the menu option to even get here normally. } try { String exportData = getExport(er); response.setContentType("application/x-download"); String entity = er.getEntity(); if (entity.equals("person")) entity = "constituent"; response.setHeader("Content-Disposition", "attachment; filename=" + entity + "-export.csv"); response.setContentLength(exportData.length()); PrintWriter out = response.getWriter(); out.print(exportData); out.flush(); return null; } catch (Exception e) { logger.debug(e); e.printStackTrace(); ModelAndView mav = new ModelAndView("redirect:/importexport.htm"); mav.addObject("exportmessage", e.getMessage()); return mav; } }
diff --git a/TiramisouApp/src/com/amazon/hackday/trms/DisplayFeeYouShipActivity.java b/TiramisouApp/src/com/amazon/hackday/trms/DisplayFeeYouShipActivity.java index 15db70e..1ff1438 100644 --- a/TiramisouApp/src/com/amazon/hackday/trms/DisplayFeeYouShipActivity.java +++ b/TiramisouApp/src/com/amazon/hackday/trms/DisplayFeeYouShipActivity.java @@ -1,101 +1,101 @@ package com.amazon.hackday.trms; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; public class DisplayFeeYouShipActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.display_fee_you_ship); // start Over button - ImageView startover = (ImageView)findViewById(R.id.youshipstartOver); + ImageView startover = (ImageView)findViewById(R.id.youshipstartover); startover.setOnClickListener(startOverClickListener); // create Listings Button ImageView createListing = (ImageView)findViewById(R.id.youshipcreateListing); createListing.setOnClickListener(createListingClickListener); // calculate ImageView calculate = (ImageView)findViewById(R.id.youshipcalculate); calculate.setOnClickListener(calculateClickListener); // EditText EditText itemPrice = (EditText)findViewById(R.id.ysEditItemPrice); itemPrice.setOnFocusChangeListener(itemPriceFocusChangeListener); itemPrice.setText("200.00"); calculateFee(); } private void calculateFee() { EditText text = (EditText)findViewById(R.id.ysEditItemPrice); String value = text.getText().toString(); Double val = Double.parseDouble(value); EditText tShipCredit = (EditText)findViewById(R.id.ysEditShippingCredit); String shipcredit = tShipCredit.getText().toString(); Double shipCreditVal = Double.parseDouble(shipcredit); TextView referralText = (TextView) findViewById(R.id.ysEditReferralFee); Double rFee = 0.08 * (val + shipCreditVal); referralText.setText("($" + rFee.toString() + ")"); TextView netAmountText = (TextView) findViewById(R.id.ysEditNetAmount); Double netFee = val - rFee; netAmountText.setText("($" + netFee.toString() + ")"); } OnClickListener calculateClickListener = new OnClickListener() { public void onClick(View view) { calculateFee(); } }; OnClickListener startOverClickListener = new OnClickListener() { public void onClick(View view) { Context context = view.getContext(); Intent intent = new Intent(DisplayFeeYouShipActivity.this, FindAsinActivity.class); try { //Start next activity context.startActivity(intent); } catch (Exception e) { e.printStackTrace(); // TODO: handle exception } } }; OnFocusChangeListener itemPriceFocusChangeListener = new OnFocusChangeListener() { public void onFocusChange(View view, boolean arg1) { //calculateFee(); } }; OnClickListener createListingClickListener = new OnClickListener() { public void onClick(View view) { Context context = view.getContext(); Intent intent = new Intent(DisplayFeeYouShipActivity.this, CreateListingActivity.class); try { //Start next activity context.startActivity(intent); } catch (Exception e) { e.printStackTrace(); // TODO: handle exception } } }; }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.display_fee_you_ship); // start Over button ImageView startover = (ImageView)findViewById(R.id.youshipstartOver); startover.setOnClickListener(startOverClickListener); // create Listings Button ImageView createListing = (ImageView)findViewById(R.id.youshipcreateListing); createListing.setOnClickListener(createListingClickListener); // calculate ImageView calculate = (ImageView)findViewById(R.id.youshipcalculate); calculate.setOnClickListener(calculateClickListener); // EditText EditText itemPrice = (EditText)findViewById(R.id.ysEditItemPrice); itemPrice.setOnFocusChangeListener(itemPriceFocusChangeListener); itemPrice.setText("200.00"); calculateFee(); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.display_fee_you_ship); // start Over button ImageView startover = (ImageView)findViewById(R.id.youshipstartover); startover.setOnClickListener(startOverClickListener); // create Listings Button ImageView createListing = (ImageView)findViewById(R.id.youshipcreateListing); createListing.setOnClickListener(createListingClickListener); // calculate ImageView calculate = (ImageView)findViewById(R.id.youshipcalculate); calculate.setOnClickListener(calculateClickListener); // EditText EditText itemPrice = (EditText)findViewById(R.id.ysEditItemPrice); itemPrice.setOnFocusChangeListener(itemPriceFocusChangeListener); itemPrice.setText("200.00"); calculateFee(); }
diff --git a/kie-wb-common-widgets/kie-wb-common-ui/src/main/java/org/kie/workbench/common/widgets/client/widget/AttachmentFileWidget.java b/kie-wb-common-widgets/kie-wb-common-ui/src/main/java/org/kie/workbench/common/widgets/client/widget/AttachmentFileWidget.java index 6b13aa2cb8..53cdddf370 100644 --- a/kie-wb-common-widgets/kie-wb-common-ui/src/main/java/org/kie/workbench/common/widgets/client/widget/AttachmentFileWidget.java +++ b/kie-wb-common-widgets/kie-wb-common-ui/src/main/java/org/kie/workbench/common/widgets/client/widget/AttachmentFileWidget.java @@ -1,235 +1,235 @@ /* * Copyright 2010 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.workbench.common.widgets.client.widget; import com.github.gwtbootstrap.client.ui.Form; import com.google.gwt.dom.client.InputElement; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FormPanel; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.TextBox; import org.guvnor.common.services.shared.file.upload.FileManagerFields; import org.guvnor.common.services.shared.file.upload.FileOperation; import org.kie.workbench.common.widgets.client.resources.i18n.CommonConstants; import org.uberfire.backend.vfs.Path; import org.uberfire.client.common.FileUpload; /** * This wraps a file uploader utility */ public class AttachmentFileWidget extends Composite { private final Form form = new Form(); private FileUpload up; private final HorizontalPanel fields = new HorizontalPanel(); private final TextBox fieldFilePath = getHiddenField( FileManagerFields.FORM_FIELD_PATH, "" ); private final TextBox fieldFileName = getHiddenField( FileManagerFields.FORM_FIELD_NAME, "" ); private final TextBox fieldFileFullPath = getHiddenField( FileManagerFields.FORM_FIELD_FULL_PATH, "" ); private final TextBox fieldFileOperation = getHiddenField( FileManagerFields.FORM_FIELD_OPERATION, "" ); private Command successCallback; private Command errorCallback; private String[] validFileExtensions; private ClickHandler uploadButtonClickHanlder; public AttachmentFileWidget() { setup( false ); } public AttachmentFileWidget( final String[] validFileExtensions ) { setup( false ); setAccept( validFileExtensions ); } public AttachmentFileWidget( final boolean addFileUpload ) { setup( addFileUpload ); } public AttachmentFileWidget( final String[] validFileExtensions, final boolean addFileUpload ) { setup( addFileUpload ); setAccept( validFileExtensions ); } private void setup( boolean addFileUpload ) { up = new FileUpload( new org.uberfire.mvp.Command() { @Override public void execute() { uploadButtonClickHanlder.onClick( null ); } }, addFileUpload ); up.setName( FileManagerFields.UPLOAD_FIELD_NAME_ATTACH ); form.setEncoding( FormPanel.ENCODING_MULTIPART ); form.setMethod( FormPanel.METHOD_POST ); form.addSubmitHandler( new Form.SubmitHandler() { @Override public void onSubmit( final Form.SubmitEvent event ) { final String fileName = up.getFilename(); if ( fileName == null || "".equals( fileName ) ) { Window.alert( CommonConstants.INSTANCE.UploadSelectAFile() ); event.cancel(); executeCallback( errorCallback ); return; } if ( validFileExtensions != null && validFileExtensions.length != 0 ) { boolean isValid = false; for ( String extension : validFileExtensions ) { if ( fileName.endsWith( extension ) ) { isValid = true; break; } } if ( !isValid ) { Window.alert( CommonConstants.INSTANCE.UploadFileTypeNotSupported() ); event.cancel(); executeCallback( errorCallback ); return; } } } } ); form.addSubmitCompleteHandler( new Form.SubmitCompleteHandler() { @Override public void onSubmitComplete( final Form.SubmitCompleteEvent event ) { - reset(); if ( "OK".equalsIgnoreCase( event.getResults() ) ) { executeCallback( successCallback ); Window.alert( CommonConstants.INSTANCE.UploadSuccess() ); } else { executeCallback( errorCallback ); if ( event.getResults().contains( "org.uberfire.java.nio.file.FileAlreadyExistsException" ) ) { Window.alert( CommonConstants.INSTANCE.ExceptionFileAlreadyExists0( fieldFileName.getText() ) ); //ErrorPopup.showMessage( CommonConstants.INSTANCE.ExceptionFileAlreadyExists0( fieldFileName.getText() ) ); } else if ( event.getResults().contains( "DecisionTableParseException" ) ) { Window.alert( CommonConstants.INSTANCE.UploadGenericError() ); //ErrorPopup.showMessage( CommonConstants.INSTANCE.UploadGenericError() ); } else { Window.alert( CommonConstants.INSTANCE.ExceptionGeneric0( event.getResults() ) ); //ErrorPopup.showMessage( CommonConstants.INSTANCE.ExceptionGeneric0( event.getResults() ) ); } } + reset(); } } ); fields.add( up ); fields.add( fieldFilePath ); fields.add( fieldFileName ); fields.add( fieldFileFullPath ); fields.add( fieldFileOperation ); form.add( fields ); initWidget( form ); } private void executeCallback( final Command callback ) { if ( callback == null ) { return; } callback.execute(); } public void reset() { form.reset(); } public void submit( final Path context, final String fileName, final String targetUrl, final Command successCallback, final Command errorCallback ) { this.successCallback = successCallback; this.errorCallback = errorCallback; fieldFileName.setText( fileName ); fieldFilePath.setText( context.toURI() ); fieldFileOperation.setText( FileOperation.CREATE.toString() ); fieldFileFullPath.setText( "" ); form.setAction( targetUrl ); form.submit(); } public void submit( final Path path, final String targetUrl, final Command successCallback, final Command errorCallback ) { this.successCallback = successCallback; this.errorCallback = errorCallback; fieldFileOperation.setText( FileOperation.UPDATE.toString() ); fieldFileFullPath.setText( path.toURI() ); fieldFileName.setText( "" ); fieldFilePath.setText( "" ); form.setAction( targetUrl ); form.submit(); } private void setAccept( final String[] validFileExtensions ) { this.validFileExtensions = validFileExtensions; final InputElement element = up.getElement().cast(); element.setAccept( makeAcceptString( validFileExtensions ) ); } private String makeAcceptString( final String[] validFileExtensions ) { if ( validFileExtensions == null || validFileExtensions.length == 0 ) { return ""; } final StringBuilder sb = new StringBuilder(); for ( String fileExtension : validFileExtensions ) { sb.append( fileExtension ).append( "," ); } sb.substring( 0, sb.length() - 1 ); return sb.toString(); } private TextBox getHiddenField( final String name, final String value ) { final TextBox t = new TextBox(); t.setName( name ); t.setText( value ); t.setVisible( false ); return t; } public void addClickHandler( final ClickHandler clickHandler ) { this.uploadButtonClickHanlder = clickHandler; } public void setEnabled( boolean b ) { up.setEnabled( b ); } }
false
true
private void setup( boolean addFileUpload ) { up = new FileUpload( new org.uberfire.mvp.Command() { @Override public void execute() { uploadButtonClickHanlder.onClick( null ); } }, addFileUpload ); up.setName( FileManagerFields.UPLOAD_FIELD_NAME_ATTACH ); form.setEncoding( FormPanel.ENCODING_MULTIPART ); form.setMethod( FormPanel.METHOD_POST ); form.addSubmitHandler( new Form.SubmitHandler() { @Override public void onSubmit( final Form.SubmitEvent event ) { final String fileName = up.getFilename(); if ( fileName == null || "".equals( fileName ) ) { Window.alert( CommonConstants.INSTANCE.UploadSelectAFile() ); event.cancel(); executeCallback( errorCallback ); return; } if ( validFileExtensions != null && validFileExtensions.length != 0 ) { boolean isValid = false; for ( String extension : validFileExtensions ) { if ( fileName.endsWith( extension ) ) { isValid = true; break; } } if ( !isValid ) { Window.alert( CommonConstants.INSTANCE.UploadFileTypeNotSupported() ); event.cancel(); executeCallback( errorCallback ); return; } } } } ); form.addSubmitCompleteHandler( new Form.SubmitCompleteHandler() { @Override public void onSubmitComplete( final Form.SubmitCompleteEvent event ) { reset(); if ( "OK".equalsIgnoreCase( event.getResults() ) ) { executeCallback( successCallback ); Window.alert( CommonConstants.INSTANCE.UploadSuccess() ); } else { executeCallback( errorCallback ); if ( event.getResults().contains( "org.uberfire.java.nio.file.FileAlreadyExistsException" ) ) { Window.alert( CommonConstants.INSTANCE.ExceptionFileAlreadyExists0( fieldFileName.getText() ) ); //ErrorPopup.showMessage( CommonConstants.INSTANCE.ExceptionFileAlreadyExists0( fieldFileName.getText() ) ); } else if ( event.getResults().contains( "DecisionTableParseException" ) ) { Window.alert( CommonConstants.INSTANCE.UploadGenericError() ); //ErrorPopup.showMessage( CommonConstants.INSTANCE.UploadGenericError() ); } else { Window.alert( CommonConstants.INSTANCE.ExceptionGeneric0( event.getResults() ) ); //ErrorPopup.showMessage( CommonConstants.INSTANCE.ExceptionGeneric0( event.getResults() ) ); } } } } ); fields.add( up ); fields.add( fieldFilePath ); fields.add( fieldFileName ); fields.add( fieldFileFullPath ); fields.add( fieldFileOperation ); form.add( fields ); initWidget( form ); }
private void setup( boolean addFileUpload ) { up = new FileUpload( new org.uberfire.mvp.Command() { @Override public void execute() { uploadButtonClickHanlder.onClick( null ); } }, addFileUpload ); up.setName( FileManagerFields.UPLOAD_FIELD_NAME_ATTACH ); form.setEncoding( FormPanel.ENCODING_MULTIPART ); form.setMethod( FormPanel.METHOD_POST ); form.addSubmitHandler( new Form.SubmitHandler() { @Override public void onSubmit( final Form.SubmitEvent event ) { final String fileName = up.getFilename(); if ( fileName == null || "".equals( fileName ) ) { Window.alert( CommonConstants.INSTANCE.UploadSelectAFile() ); event.cancel(); executeCallback( errorCallback ); return; } if ( validFileExtensions != null && validFileExtensions.length != 0 ) { boolean isValid = false; for ( String extension : validFileExtensions ) { if ( fileName.endsWith( extension ) ) { isValid = true; break; } } if ( !isValid ) { Window.alert( CommonConstants.INSTANCE.UploadFileTypeNotSupported() ); event.cancel(); executeCallback( errorCallback ); return; } } } } ); form.addSubmitCompleteHandler( new Form.SubmitCompleteHandler() { @Override public void onSubmitComplete( final Form.SubmitCompleteEvent event ) { if ( "OK".equalsIgnoreCase( event.getResults() ) ) { executeCallback( successCallback ); Window.alert( CommonConstants.INSTANCE.UploadSuccess() ); } else { executeCallback( errorCallback ); if ( event.getResults().contains( "org.uberfire.java.nio.file.FileAlreadyExistsException" ) ) { Window.alert( CommonConstants.INSTANCE.ExceptionFileAlreadyExists0( fieldFileName.getText() ) ); //ErrorPopup.showMessage( CommonConstants.INSTANCE.ExceptionFileAlreadyExists0( fieldFileName.getText() ) ); } else if ( event.getResults().contains( "DecisionTableParseException" ) ) { Window.alert( CommonConstants.INSTANCE.UploadGenericError() ); //ErrorPopup.showMessage( CommonConstants.INSTANCE.UploadGenericError() ); } else { Window.alert( CommonConstants.INSTANCE.ExceptionGeneric0( event.getResults() ) ); //ErrorPopup.showMessage( CommonConstants.INSTANCE.ExceptionGeneric0( event.getResults() ) ); } } reset(); } } ); fields.add( up ); fields.add( fieldFilePath ); fields.add( fieldFileName ); fields.add( fieldFileFullPath ); fields.add( fieldFileOperation ); form.add( fields ); initWidget( form ); }
diff --git a/src/test/java/org/fusesource/camel/component/salesforce/SalesforceComponentTest.java b/src/test/java/org/fusesource/camel/component/salesforce/SalesforceComponentTest.java index b93210a..ed84c58 100644 --- a/src/test/java/org/fusesource/camel/component/salesforce/SalesforceComponentTest.java +++ b/src/test/java/org/fusesource/camel/component/salesforce/SalesforceComponentTest.java @@ -1,536 +1,540 @@ package org.fusesource.camel.component.salesforce; import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.CamelTestSupport; import org.codehaus.jackson.map.ObjectMapper; import org.fusesource.camel.component.salesforce.api.dto.*; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Properties; public class SalesforceComponentTest extends CamelTestSupport { private static final Logger LOG = LoggerFactory.getLogger(SalesforceComponentTest.class); private static final String TEST_LOGIN_PROPERTIES = "/test-login.properties"; private static final String TEST_LINE_ITEM_ID = "1"; private static final String NEW_LINE_ITEM_ID = "100"; private static final String API_VERSION = "25.0"; private static final String DEFAULT_FORMAT = "json"; private ObjectMapper objectMapper; private static String testId; @Override public boolean isCreateCamelContextPerClass() { // only create the context once for this class return true; } @Test public void testGetVersions() throws Exception { doTestGetVersion(""); doTestGetVersion("Xml"); } private void doTestGetVersion(String suffix) throws Exception { MockEndpoint mock = getMockEndpoint("mock:testGetVersions" + suffix); mock.expectedMinimumMessageCount(1); // test versions doesn't need a body sendBody("direct:testGetVersions" + suffix, null); mock.assertIsSatisfied(); // assert expected result Exchange ex = mock.getExchanges().get(0); List<Version> versions = null; Versions versions1 = ex.getIn().getBody(Versions.class); if (versions1 == null) { versions = ex.getIn().getBody(List.class); } else { versions = versions1.getVersions(); } assertNotNull(versions); LOG.trace("Versions: {}", versions); } @Test public void testGetResources() throws Exception { doTestGetResources(""); doTestGetResources("Xml"); } private void doTestGetResources(String suffix) throws Exception { MockEndpoint mock = getMockEndpoint("mock:testGetResources" + suffix); mock.expectedMinimumMessageCount(1); sendBody("direct:testGetResources" + suffix, null); mock.assertIsSatisfied(); // assert expected result Exchange ex = mock.getExchanges().get(0); RestResources resources = ex.getIn().getBody(RestResources.class); assertNotNull(resources); LOG.trace("Resources: {}", resources); } @Test public void testGetGlobalObjects() throws Exception { doTestGetGlobalObjects(""); doTestGetGlobalObjects("Xml"); } private void doTestGetGlobalObjects(String suffix) throws Exception { MockEndpoint mock = getMockEndpoint("mock:testGetGlobalObjects" + suffix); mock.expectedMinimumMessageCount(1); sendBody("direct:testGetGlobalObjects" + suffix, null); mock.assertIsSatisfied(); // assert expected result Exchange ex = mock.getExchanges().get(0); GlobalObjects globalObjects = ex.getIn().getBody(GlobalObjects.class); assertNotNull(globalObjects); LOG.trace("GlobalObjects: {}", globalObjects); } @Test public void testGetSObjectBasicInfo() throws Exception { doTestGetSObjectBasicInfo(""); doTestGetSObjectBasicInfo("Xml"); } private void doTestGetSObjectBasicInfo(String suffix) throws Exception { MockEndpoint mock = getMockEndpoint("mock:testGetSObjectBasicInfo" + suffix); mock.expectedMinimumMessageCount(1); sendBody("direct:testGetSObjectBasicInfo" + suffix, null); mock.assertIsSatisfied(); // assert expected result Exchange ex = mock.getExchanges().get(0); SObjectBasicInfo objectBasicInfo = ex.getIn().getBody(SObjectBasicInfo.class); assertNotNull(objectBasicInfo); LOG.trace("SObjectBasicInfo: {}", objectBasicInfo); } @Test public void testGetSObjectDescription() throws Exception { doTestGetSObjectDescription(""); doTestGetSObjectDescription("Xml"); } private void doTestGetSObjectDescription(String suffix) throws Exception { MockEndpoint mock = getMockEndpoint("mock:testGetSObjectDescription" + suffix); mock.expectedMinimumMessageCount(1); sendBody("direct:testGetSObjectDescription" + suffix, null); mock.assertIsSatisfied(); // assert expected result Exchange ex = mock.getExchanges().get(0); SObjectDescription sObjectDescription = ex.getIn().getBody(SObjectDescription.class); assertNotNull(sObjectDescription); LOG.trace("SObjectDescription: {}", sObjectDescription); } @Test public void testGetSObjectById() throws Exception { doTestGetSObjectById(""); doTestGetSObjectById("Xml"); } private void doTestGetSObjectById(String suffix) throws Exception { MockEndpoint mock = getMockEndpoint("mock:testGetSObjectById" + suffix); mock.expectedMinimumMessageCount(1); sendBody("direct:testGetSObjectById" + suffix, testId); mock.assertIsSatisfied(); // assert expected result Exchange ex = mock.getExchanges().get(0); Merchandise__c merchandise = ex.getIn().getBody(Merchandise__c.class); assertNotNull(merchandise); if (suffix.isEmpty()) { assertNull(merchandise.getTotal_Inventory__c()); assertNotNull(merchandise.getPrice__c()); } else { assertNotNull(merchandise.getTotal_Inventory__c()); assertNull(merchandise.getPrice__c()); } LOG.trace("SObjectById: {}", merchandise); } @Test public void testCreateUpdateDeleteById() throws Exception { doTestCreateUpdateDeleteById(""); doTestCreateUpdateDeleteById("Xml"); } private void doTestCreateUpdateDeleteById(String suffix) throws InterruptedException { MockEndpoint mock = getMockEndpoint("mock:testCreateSObject" + suffix); mock.expectedMinimumMessageCount(1); Merchandise__c merchandise__c = new Merchandise__c(); merchandise__c.setName("Wee Wee Wee Plane"); merchandise__c.setDescription__c("Microlite plane"); merchandise__c.setPrice__c(2000.0); merchandise__c.setTotal_Inventory__c(50.0); sendBody("direct:testCreateSObject" + suffix, merchandise__c); mock.assertIsSatisfied(); // assert expected result Exchange ex = mock.getExchanges().get(0); assertNull(ex.getException()); CreateSObjectResult result = ex.getIn().getBody(CreateSObjectResult.class); assertNotNull(result); assertTrue("CreateSObject success", result.getSuccess()); LOG.trace("CreateSObject: " + result); // test JSON update mock = getMockEndpoint("mock:testUpdateSObjectById" + suffix); mock.expectedMinimumMessageCount(1); merchandise__c = new Merchandise__c(); // make the plane cheaper merchandise__c.setPrice__c(1500.0); // change inventory to half merchandise__c.setTotal_Inventory__c(25.0); template().sendBodyAndHeader("direct:testUpdateSObjectById" + suffix, merchandise__c, SalesforceEndpointConfig.SOBJECT_ID, result.getId()); mock.assertIsSatisfied(); // assert expected result ex = mock.getExchanges().get(0); // empty body and no exception assertNull(ex.getException()); assertNull(ex.getOut().getBody()); LOG.trace("UpdateSObjectById successful"); // delete the newly created SObject mock = getMockEndpoint("mock:testDeleteSObjectById" + suffix); mock.expectedMinimumMessageCount(1); sendBody("direct:testDeleteSObjectById" + suffix, result.getId()); mock.assertIsSatisfied(); // assert expected result ex = mock.getExchanges().get(0); // empty body and no exception assertNull(ex.getException()); assertNull(ex.getOut().getBody()); LOG.trace("DeleteSObjectById successful"); } @Test public void testCreateUpdateDeleteByExternalId() throws Exception { doTestCreateUpdateDeleteByExternalId(""); doTestCreateUpdateDeleteByExternalId("Xml"); } private void doTestCreateUpdateDeleteByExternalId(String suffix) throws InterruptedException { MockEndpoint mock = getMockEndpoint("mock:testGetSObjectByExternalId" + suffix); mock.expectedMinimumMessageCount(1); // get line item with Name 1 sendBody("direct:testGetSObjectByExternalId" + suffix, TEST_LINE_ITEM_ID); mock.assertIsSatisfied(); // assert expected result Exchange ex = mock.getExchanges().get(0); assertNull(ex.getException()); Line_Item__c line_item__c = ex.getIn().getBody(Line_Item__c.class); assertNotNull(line_item__c); LOG.trace("GetSObjectByExternalId: {}", line_item__c); // test JSON update mock = getMockEndpoint("mock:testCreateOrUpdateSObjectByExternalId" + suffix); mock.expectedMinimumMessageCount(1); // change line_item__c to create a new Line Item // otherwise we will get an error from Salesforce line_item__c.clearBaseFields(); // set the unit price and sold line_item__c.setUnit_Price__c(1000.0); line_item__c.setUnits_Sold__c(50.0); // update line item with Name NEW_LINE_ITEM_ID template().sendBodyAndHeader("direct:testCreateOrUpdateSObjectByExternalId" + suffix, line_item__c, SalesforceEndpointConfig.SOBJECT_EXT_ID_VALUE, NEW_LINE_ITEM_ID); mock.assertIsSatisfied(); // assert expected result ex = mock.getExchanges().get(0); CreateSObjectResult result = ex.getIn().getBody(CreateSObjectResult.class); assertNotNull(result); assertTrue(result.getSuccess()); LOG.trace("CreateSObjectByExternalId: {}", result); // change line_item__c to update existing Line Item // otherwise we will get an error from Salesforce line_item__c.clearBaseFields(); // clear read only parent type fields line_item__c.setInvoice_Statement__c(null); line_item__c.setMerchandise__c(null); // change the units sold line_item__c.setUnits_Sold__c(25.0); // update line item with Name NEW_LINE_ITEM_ID template().sendBodyAndHeader("direct:testCreateOrUpdateSObjectByExternalId" + suffix, line_item__c, SalesforceEndpointConfig.SOBJECT_EXT_ID_VALUE, NEW_LINE_ITEM_ID); mock.assertIsSatisfied(); // assert expected result ex = mock.getExchanges().get(0); result = ex.getIn().getBody(CreateSObjectResult.class); assertNotNull(result); assertTrue(result.getSuccess()); LOG.trace("UpdateSObjectByExternalId: {}", result); // delete the SObject with Name=2 mock = getMockEndpoint("mock:testDeleteSObjectByExternalId" + suffix); mock.expectedMinimumMessageCount(1); sendBody("direct:testDeleteSObjectByExternalId" + suffix, NEW_LINE_ITEM_ID); mock.assertIsSatisfied(); // assert expected result ex = mock.getExchanges().get(0); // empty body and no exception assertNull(ex.getException()); assertNull(ex.getOut().getBody()); LOG.trace("DeleteSObjectByExternalId successful"); } @Test public void testExecuteQuery() throws Exception { doTestExecuteQuery(""); doTestExecuteQuery("Xml"); } private void doTestExecuteQuery(String suffix) throws InterruptedException { MockEndpoint mock = getMockEndpoint("mock:testExecuteQuery" + suffix); mock.expectedMinimumMessageCount(1); sendBody("direct:testExecuteQuery" + suffix, null); mock.assertIsSatisfied(); // assert expected result Exchange ex = mock.getExchanges().get(0); assertNull(ex.getException()); QueryRecordsLine_Item__c queryRecords = ex.getIn().getBody(QueryRecordsLine_Item__c.class); assertNotNull(queryRecords); LOG.trace("ExecuteQuery: {}", queryRecords); } @Test public void testExecuteSearch() throws Exception { doTestExecuteSearch(""); doTestExecuteSearch("Xml"); } private void doTestExecuteSearch(String suffix) throws InterruptedException { MockEndpoint mock = getMockEndpoint("mock:testExecuteSearch" + suffix); mock.expectedMinimumMessageCount(1); sendBody("direct:testExecuteSearch" + suffix, null); mock.assertIsSatisfied(); // assert expected result Exchange ex = mock.getExchanges().get(0); assertNull(ex.getException()); SearchResults queryRecords = ex.getIn().getBody(SearchResults.class); List<SearchResult> searchResults = null; if (queryRecords != null) { searchResults = queryRecords.getResults(); } else { searchResults = ex.getIn().getBody(List.class); } assertNotNull(searchResults); LOG.trace("ExecuteSearch: {}", searchResults); } @Override protected RouteBuilder createRouteBuilder() throws Exception { // create a json mapper objectMapper = new ObjectMapper(); // create the component SalesforceComponent component = new SalesforceComponent(); setLoginProperties(component); // default component level payload format component.setFormat(DEFAULT_FORMAT); // default api version component.setApiVersion(API_VERSION); + // set DTO package + component.setPackages(new String[] { + Merchandise__c.class.getPackage().getName() + }); // add it to context context().addComponent("force", component); // create test route return new RouteBuilder() { public void configure() { // testGetVersion from("direct:testGetVersions") .to("force://getVersions") .to("mock:testGetVersions"); // allow overriding format per endpoint from("direct:testGetVersionsXml") .to("force://getVersions?format=xml") .to("mock:testGetVersionsXml"); // testGetResources from("direct:testGetResources") .to("force://getResources") .to("mock:testGetResources"); from("direct:testGetResourcesXml") .to("force://getResources?format=xml") .to("mock:testGetResourcesXml"); // testGetGlobalObjects from("direct:testGetGlobalObjects") .to("force://getGlobalObjects") .to("mock:testGetGlobalObjects"); from("direct:testGetGlobalObjectsXml") .to("force://getGlobalObjects?format=xml") .to("mock:testGetGlobalObjectsXml"); // testGetSObjectBasicInfo from("direct:testGetSObjectBasicInfo") .to("force://getSObjectBasicInfo?sObjectName=Merchandise__c") .to("mock:testGetSObjectBasicInfo"); from("direct:testGetSObjectBasicInfoXml") .to("force://getSObjectBasicInfo?format=xml&sObjectName=Merchandise__c") .to("mock:testGetSObjectBasicInfoXml"); // testGetSObjectDescription from("direct:testGetSObjectDescription") .to("force://getSObjectDescription?sObjectName=Merchandise__c") .to("mock:testGetSObjectDescription"); from("direct:testGetSObjectDescriptionXml") .to("force://getSObjectDescription?format=xml&sObjectName=Merchandise__c") .to("mock:testGetSObjectDescriptionXml"); // testGetSObjectById from("direct:testGetSObjectById") - .to("force://getSObjectById?sObjectName=Merchandise__c&sObjectClass=org.fusesource.camel.component.salesforce.Merchandise__c&sObjectFields=Description__c,Price__c") + .to("force://getSObjectById?sObjectName=Merchandise__c&sObjectFields=Description__c,Price__c") .to("mock:testGetSObjectById"); from("direct:testGetSObjectByIdXml") - .to("force://getSObjectById?format=xml&sObjectName=Merchandise__c&sObjectClass=org.fusesource.camel.component.salesforce.Merchandise__c&sObjectFields=Description__c,Total_Inventory__c") + .to("force://getSObjectById?format=xml&sObjectName=Merchandise__c&sObjectFields=Description__c,Total_Inventory__c") .to("mock:testGetSObjectByIdXml"); // testCreateSObject from("direct:testCreateSObject") - .to("force://createSObject?sObjectName=Merchandise__c&sObjectClass=org.fusesource.camel.component.salesforce.Merchandise__c") + .to("force://createSObject?sObjectName=Merchandise__c") .to("mock:testCreateSObject"); from("direct:testCreateSObjectXml") - .to("force://createSObject?format=xml&sObjectName=Merchandise__c&sObjectClass=org.fusesource.camel.component.salesforce.Merchandise__c") + .to("force://createSObject?format=xml&sObjectName=Merchandise__c") .to("mock:testCreateSObjectXml"); // testUpdateSObjectById from("direct:testUpdateSObjectById") - .to("force://updateSObjectById?sObjectName=Merchandise__c&sObjectClass=org.fusesource.camel.component.salesforce.Merchandise__c") + .to("force://updateSObjectById?sObjectName=Merchandise__c") .to("mock:testUpdateSObjectById"); from("direct:testUpdateSObjectByIdXml") - .to("force://updateSObjectById?format=xml&sObjectName=Merchandise__c&sObjectClass=org.fusesource.camel.component.salesforce.Merchandise__c") + .to("force://updateSObjectById?format=xml&sObjectName=Merchandise__c") .to("mock:testUpdateSObjectByIdXml"); // testDeleteSObjectById from("direct:testDeleteSObjectById") .to("force://deleteSObjectById?sObjectName=Merchandise__c") .to("mock:testDeleteSObjectById"); from("direct:testDeleteSObjectByIdXml") .to("force://deleteSObjectById?format=xml&sObjectName=Merchandise__c") .to("mock:testDeleteSObjectByIdXml"); // testGetSObjectByExternalId from("direct:testGetSObjectByExternalId") - .to("force://getSObjectByExternalId?sObjectName=Line_Item__c&sObjectIdName=Name&sObjectClass=org.fusesource.camel.component.salesforce.Line_Item__c") + .to("force://getSObjectByExternalId?sObjectName=Line_Item__c&sObjectIdName=Name") .to("mock:testGetSObjectByExternalId"); from("direct:testGetSObjectByExternalIdXml") - .to("force://getSObjectByExternalId?format=xml&sObjectName=Line_Item__c&sObjectIdName=Name&sObjectClass=org.fusesource.camel.component.salesforce.Line_Item__c") + .to("force://getSObjectByExternalId?format=xml&sObjectName=Line_Item__c&sObjectIdName=Name") .to("mock:testGetSObjectByExternalIdXml"); // testCreateOrUpdateSObjectByExternalId from("direct:testCreateOrUpdateSObjectByExternalId") - .to("force://createOrUpdateSObjectByExternalId?sObjectName=Line_Item__c&sObjectIdName=Name&sObjectClass=org.fusesource.camel.component.salesforce.Line_Item__c") + .to("force://createOrUpdateSObjectByExternalId?sObjectName=Line_Item__c&sObjectIdName=Name") .to("mock:testCreateOrUpdateSObjectByExternalId"); from("direct:testCreateOrUpdateSObjectByExternalIdXml") - .to("force://createOrUpdateSObjectByExternalId?format=xml&sObjectName=Line_Item__c&sObjectIdName=Name&sObjectClass=org.fusesource.camel.component.salesforce.Line_Item__c") + .to("force://createOrUpdateSObjectByExternalId?format=xml&sObjectName=Line_Item__c&sObjectIdName=Name") .to("mock:testCreateOrUpdateSObjectByExternalIdXml"); // testDeleteSObjectByExternalId from("direct:testDeleteSObjectByExternalId") .to("force://deleteSObjectByExternalId?sObjectName=Line_Item__c&sObjectIdName=Name") .to("mock:testDeleteSObjectByExternalId"); from("direct:testDeleteSObjectByExternalIdXml") .to("force://deleteSObjectByExternalId?format=xml&sObjectName=Line_Item__c&sObjectIdName=Name") .to("mock:testDeleteSObjectByExternalIdXml"); // testExecuteQuery from("direct:testExecuteQuery") .to("force://executeQuery?sObjectQuery=SELECT name from Line_Item__c&sObjectClass=org.fusesource.camel.component.salesforce.QueryRecordsLine_Item__c") .to("mock:testExecuteQuery"); from("direct:testExecuteQueryXml") .to("force://executeQuery?format=xml&sObjectQuery=SELECT name from Line_Item__c&sObjectClass=org.fusesource.camel.component.salesforce.QueryRecordsLine_Item__c") .to("mock:testExecuteQueryXml"); // testExecuteSearch from("direct:testExecuteSearch") .to("force://executeSearch?sObjectSearch=FIND {Wee}") .to("mock:testExecuteSearch"); from("direct:testExecuteSearchXml") .to("force://executeSearch?format=xml&sObjectSearch=FIND {Wee}") .to("mock:testExecuteSearchXml"); } }; } private void setLoginProperties(SalesforceComponent component) throws IllegalAccessException, IOException { // load test-login properties Properties properties = new Properties(); InputStream stream = getClass().getResourceAsStream(TEST_LOGIN_PROPERTIES); if (null == stream) { throw new IllegalAccessException("Create a properties file named " + TEST_LOGIN_PROPERTIES + " with clientId, clientSecret, userName, password and a testId" + " for a Salesforce account with the Merchandise object from Salesforce Guides."); } properties.load(stream); component.setClientId(properties.getProperty("clientId")); component.setClientSecret(properties.getProperty("clientSecret")); component.setUserName(properties.getProperty("userName")); component.setPassword(properties.getProperty("password")); testId = properties.getProperty("testId"); assertNotNull("Null clientId", component.getClientId()); assertNotNull("Null clientSecret", component.getClientSecret()); assertNotNull("Null userName", component.getUserName()); assertNotNull("Null password", component.getPassword()); assertNotNull("Null testId", testId); } }
false
true
protected RouteBuilder createRouteBuilder() throws Exception { // create a json mapper objectMapper = new ObjectMapper(); // create the component SalesforceComponent component = new SalesforceComponent(); setLoginProperties(component); // default component level payload format component.setFormat(DEFAULT_FORMAT); // default api version component.setApiVersion(API_VERSION); // add it to context context().addComponent("force", component); // create test route return new RouteBuilder() { public void configure() { // testGetVersion from("direct:testGetVersions") .to("force://getVersions") .to("mock:testGetVersions"); // allow overriding format per endpoint from("direct:testGetVersionsXml") .to("force://getVersions?format=xml") .to("mock:testGetVersionsXml"); // testGetResources from("direct:testGetResources") .to("force://getResources") .to("mock:testGetResources"); from("direct:testGetResourcesXml") .to("force://getResources?format=xml") .to("mock:testGetResourcesXml"); // testGetGlobalObjects from("direct:testGetGlobalObjects") .to("force://getGlobalObjects") .to("mock:testGetGlobalObjects"); from("direct:testGetGlobalObjectsXml") .to("force://getGlobalObjects?format=xml") .to("mock:testGetGlobalObjectsXml"); // testGetSObjectBasicInfo from("direct:testGetSObjectBasicInfo") .to("force://getSObjectBasicInfo?sObjectName=Merchandise__c") .to("mock:testGetSObjectBasicInfo"); from("direct:testGetSObjectBasicInfoXml") .to("force://getSObjectBasicInfo?format=xml&sObjectName=Merchandise__c") .to("mock:testGetSObjectBasicInfoXml"); // testGetSObjectDescription from("direct:testGetSObjectDescription") .to("force://getSObjectDescription?sObjectName=Merchandise__c") .to("mock:testGetSObjectDescription"); from("direct:testGetSObjectDescriptionXml") .to("force://getSObjectDescription?format=xml&sObjectName=Merchandise__c") .to("mock:testGetSObjectDescriptionXml"); // testGetSObjectById from("direct:testGetSObjectById") .to("force://getSObjectById?sObjectName=Merchandise__c&sObjectClass=org.fusesource.camel.component.salesforce.Merchandise__c&sObjectFields=Description__c,Price__c") .to("mock:testGetSObjectById"); from("direct:testGetSObjectByIdXml") .to("force://getSObjectById?format=xml&sObjectName=Merchandise__c&sObjectClass=org.fusesource.camel.component.salesforce.Merchandise__c&sObjectFields=Description__c,Total_Inventory__c") .to("mock:testGetSObjectByIdXml"); // testCreateSObject from("direct:testCreateSObject") .to("force://createSObject?sObjectName=Merchandise__c&sObjectClass=org.fusesource.camel.component.salesforce.Merchandise__c") .to("mock:testCreateSObject"); from("direct:testCreateSObjectXml") .to("force://createSObject?format=xml&sObjectName=Merchandise__c&sObjectClass=org.fusesource.camel.component.salesforce.Merchandise__c") .to("mock:testCreateSObjectXml"); // testUpdateSObjectById from("direct:testUpdateSObjectById") .to("force://updateSObjectById?sObjectName=Merchandise__c&sObjectClass=org.fusesource.camel.component.salesforce.Merchandise__c") .to("mock:testUpdateSObjectById"); from("direct:testUpdateSObjectByIdXml") .to("force://updateSObjectById?format=xml&sObjectName=Merchandise__c&sObjectClass=org.fusesource.camel.component.salesforce.Merchandise__c") .to("mock:testUpdateSObjectByIdXml"); // testDeleteSObjectById from("direct:testDeleteSObjectById") .to("force://deleteSObjectById?sObjectName=Merchandise__c") .to("mock:testDeleteSObjectById"); from("direct:testDeleteSObjectByIdXml") .to("force://deleteSObjectById?format=xml&sObjectName=Merchandise__c") .to("mock:testDeleteSObjectByIdXml"); // testGetSObjectByExternalId from("direct:testGetSObjectByExternalId") .to("force://getSObjectByExternalId?sObjectName=Line_Item__c&sObjectIdName=Name&sObjectClass=org.fusesource.camel.component.salesforce.Line_Item__c") .to("mock:testGetSObjectByExternalId"); from("direct:testGetSObjectByExternalIdXml") .to("force://getSObjectByExternalId?format=xml&sObjectName=Line_Item__c&sObjectIdName=Name&sObjectClass=org.fusesource.camel.component.salesforce.Line_Item__c") .to("mock:testGetSObjectByExternalIdXml"); // testCreateOrUpdateSObjectByExternalId from("direct:testCreateOrUpdateSObjectByExternalId") .to("force://createOrUpdateSObjectByExternalId?sObjectName=Line_Item__c&sObjectIdName=Name&sObjectClass=org.fusesource.camel.component.salesforce.Line_Item__c") .to("mock:testCreateOrUpdateSObjectByExternalId"); from("direct:testCreateOrUpdateSObjectByExternalIdXml") .to("force://createOrUpdateSObjectByExternalId?format=xml&sObjectName=Line_Item__c&sObjectIdName=Name&sObjectClass=org.fusesource.camel.component.salesforce.Line_Item__c") .to("mock:testCreateOrUpdateSObjectByExternalIdXml"); // testDeleteSObjectByExternalId from("direct:testDeleteSObjectByExternalId") .to("force://deleteSObjectByExternalId?sObjectName=Line_Item__c&sObjectIdName=Name") .to("mock:testDeleteSObjectByExternalId"); from("direct:testDeleteSObjectByExternalIdXml") .to("force://deleteSObjectByExternalId?format=xml&sObjectName=Line_Item__c&sObjectIdName=Name") .to("mock:testDeleteSObjectByExternalIdXml"); // testExecuteQuery from("direct:testExecuteQuery") .to("force://executeQuery?sObjectQuery=SELECT name from Line_Item__c&sObjectClass=org.fusesource.camel.component.salesforce.QueryRecordsLine_Item__c") .to("mock:testExecuteQuery"); from("direct:testExecuteQueryXml") .to("force://executeQuery?format=xml&sObjectQuery=SELECT name from Line_Item__c&sObjectClass=org.fusesource.camel.component.salesforce.QueryRecordsLine_Item__c") .to("mock:testExecuteQueryXml"); // testExecuteSearch from("direct:testExecuteSearch") .to("force://executeSearch?sObjectSearch=FIND {Wee}") .to("mock:testExecuteSearch"); from("direct:testExecuteSearchXml") .to("force://executeSearch?format=xml&sObjectSearch=FIND {Wee}") .to("mock:testExecuteSearchXml"); } }; }
protected RouteBuilder createRouteBuilder() throws Exception { // create a json mapper objectMapper = new ObjectMapper(); // create the component SalesforceComponent component = new SalesforceComponent(); setLoginProperties(component); // default component level payload format component.setFormat(DEFAULT_FORMAT); // default api version component.setApiVersion(API_VERSION); // set DTO package component.setPackages(new String[] { Merchandise__c.class.getPackage().getName() }); // add it to context context().addComponent("force", component); // create test route return new RouteBuilder() { public void configure() { // testGetVersion from("direct:testGetVersions") .to("force://getVersions") .to("mock:testGetVersions"); // allow overriding format per endpoint from("direct:testGetVersionsXml") .to("force://getVersions?format=xml") .to("mock:testGetVersionsXml"); // testGetResources from("direct:testGetResources") .to("force://getResources") .to("mock:testGetResources"); from("direct:testGetResourcesXml") .to("force://getResources?format=xml") .to("mock:testGetResourcesXml"); // testGetGlobalObjects from("direct:testGetGlobalObjects") .to("force://getGlobalObjects") .to("mock:testGetGlobalObjects"); from("direct:testGetGlobalObjectsXml") .to("force://getGlobalObjects?format=xml") .to("mock:testGetGlobalObjectsXml"); // testGetSObjectBasicInfo from("direct:testGetSObjectBasicInfo") .to("force://getSObjectBasicInfo?sObjectName=Merchandise__c") .to("mock:testGetSObjectBasicInfo"); from("direct:testGetSObjectBasicInfoXml") .to("force://getSObjectBasicInfo?format=xml&sObjectName=Merchandise__c") .to("mock:testGetSObjectBasicInfoXml"); // testGetSObjectDescription from("direct:testGetSObjectDescription") .to("force://getSObjectDescription?sObjectName=Merchandise__c") .to("mock:testGetSObjectDescription"); from("direct:testGetSObjectDescriptionXml") .to("force://getSObjectDescription?format=xml&sObjectName=Merchandise__c") .to("mock:testGetSObjectDescriptionXml"); // testGetSObjectById from("direct:testGetSObjectById") .to("force://getSObjectById?sObjectName=Merchandise__c&sObjectFields=Description__c,Price__c") .to("mock:testGetSObjectById"); from("direct:testGetSObjectByIdXml") .to("force://getSObjectById?format=xml&sObjectName=Merchandise__c&sObjectFields=Description__c,Total_Inventory__c") .to("mock:testGetSObjectByIdXml"); // testCreateSObject from("direct:testCreateSObject") .to("force://createSObject?sObjectName=Merchandise__c") .to("mock:testCreateSObject"); from("direct:testCreateSObjectXml") .to("force://createSObject?format=xml&sObjectName=Merchandise__c") .to("mock:testCreateSObjectXml"); // testUpdateSObjectById from("direct:testUpdateSObjectById") .to("force://updateSObjectById?sObjectName=Merchandise__c") .to("mock:testUpdateSObjectById"); from("direct:testUpdateSObjectByIdXml") .to("force://updateSObjectById?format=xml&sObjectName=Merchandise__c") .to("mock:testUpdateSObjectByIdXml"); // testDeleteSObjectById from("direct:testDeleteSObjectById") .to("force://deleteSObjectById?sObjectName=Merchandise__c") .to("mock:testDeleteSObjectById"); from("direct:testDeleteSObjectByIdXml") .to("force://deleteSObjectById?format=xml&sObjectName=Merchandise__c") .to("mock:testDeleteSObjectByIdXml"); // testGetSObjectByExternalId from("direct:testGetSObjectByExternalId") .to("force://getSObjectByExternalId?sObjectName=Line_Item__c&sObjectIdName=Name") .to("mock:testGetSObjectByExternalId"); from("direct:testGetSObjectByExternalIdXml") .to("force://getSObjectByExternalId?format=xml&sObjectName=Line_Item__c&sObjectIdName=Name") .to("mock:testGetSObjectByExternalIdXml"); // testCreateOrUpdateSObjectByExternalId from("direct:testCreateOrUpdateSObjectByExternalId") .to("force://createOrUpdateSObjectByExternalId?sObjectName=Line_Item__c&sObjectIdName=Name") .to("mock:testCreateOrUpdateSObjectByExternalId"); from("direct:testCreateOrUpdateSObjectByExternalIdXml") .to("force://createOrUpdateSObjectByExternalId?format=xml&sObjectName=Line_Item__c&sObjectIdName=Name") .to("mock:testCreateOrUpdateSObjectByExternalIdXml"); // testDeleteSObjectByExternalId from("direct:testDeleteSObjectByExternalId") .to("force://deleteSObjectByExternalId?sObjectName=Line_Item__c&sObjectIdName=Name") .to("mock:testDeleteSObjectByExternalId"); from("direct:testDeleteSObjectByExternalIdXml") .to("force://deleteSObjectByExternalId?format=xml&sObjectName=Line_Item__c&sObjectIdName=Name") .to("mock:testDeleteSObjectByExternalIdXml"); // testExecuteQuery from("direct:testExecuteQuery") .to("force://executeQuery?sObjectQuery=SELECT name from Line_Item__c&sObjectClass=org.fusesource.camel.component.salesforce.QueryRecordsLine_Item__c") .to("mock:testExecuteQuery"); from("direct:testExecuteQueryXml") .to("force://executeQuery?format=xml&sObjectQuery=SELECT name from Line_Item__c&sObjectClass=org.fusesource.camel.component.salesforce.QueryRecordsLine_Item__c") .to("mock:testExecuteQueryXml"); // testExecuteSearch from("direct:testExecuteSearch") .to("force://executeSearch?sObjectSearch=FIND {Wee}") .to("mock:testExecuteSearch"); from("direct:testExecuteSearchXml") .to("force://executeSearch?format=xml&sObjectSearch=FIND {Wee}") .to("mock:testExecuteSearchXml"); } }; }
diff --git a/src/de/podfetcher/feed/RSSHandler.java b/src/de/podfetcher/feed/RSSHandler.java index 75671f29..80e7fab8 100644 --- a/src/de/podfetcher/feed/RSSHandler.java +++ b/src/de/podfetcher/feed/RSSHandler.java @@ -1,123 +1,123 @@ package de.podfetcher.feed; import java.util.ArrayList; import de.podfetcher.feed.FeedHandler; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * SAX-Parser for reading RSS-Feeds * * @author daniel * */ public class RSSHandler extends DefaultHandler { public ArrayList<FeedItem> items; public FeedItem currentItem; public StringBuilder strBuilder; public Feed feed; public String active_root_element; // channel or item or image public String active_sub_element; // Not channel or item public RSSHandler(Feed f) { super(); this.feed = f; } @Override public void characters(char[] ch, int start, int length) throws SAXException { if (active_sub_element != null) { strBuilder.append(ch, start, length); } } @Override public void endDocument() throws SAXException { feed.setItems(items); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equalsIgnoreCase(FeedHandler.ITEM)) { currentItem.setFeed(feed); items.add(currentItem); } else if (qName.equalsIgnoreCase(FeedHandler.TITLE)) { if (active_root_element.equalsIgnoreCase(FeedHandler.CHANNEL)) { feed.setTitle(strBuilder.toString()); - } else if(active_root_element.equalsIgnoreCase(FeedHandler.TITLE)) { + } else if(active_root_element.equalsIgnoreCase(FeedHandler.ITEM)) { currentItem.setTitle(strBuilder.toString()); } else if(active_root_element.equalsIgnoreCase(FeedHandler.IMAGE)) { feed.getImage().title = strBuilder.toString(); } } else if (qName.equalsIgnoreCase(FeedHandler.DESCR)) { if (active_root_element.equalsIgnoreCase(FeedHandler.CHANNEL)) { feed.setDescription(strBuilder.toString()); } else { currentItem.setDescription(strBuilder.toString()); } } else if (qName.equalsIgnoreCase(FeedHandler.LINK)) { if (active_root_element.equalsIgnoreCase(FeedHandler.CHANNEL)) { feed.setLink(strBuilder.toString()); - } else if(active_root_element.equalsIgnoreCase(FeedHandler.TITLE)){ + } else if(active_root_element.equalsIgnoreCase(FeedHandler.ITEM)){ currentItem.setLink(strBuilder.toString()); } } else if (qName.equalsIgnoreCase(FeedHandler.PUBDATE)) { if (active_root_element.equalsIgnoreCase(FeedHandler.ITEM)) { currentItem.setPubDate(strBuilder.toString()); } } else if (qName.equalsIgnoreCase(FeedHandler.URL)) { if(active_root_element.equalsIgnoreCase(FeedHandler.IMAGE)) { feed.getImage().download_url = strBuilder.toString(); } } else if(qName.equalsIgnoreCase(FeedHandler.IMAGE)) { active_root_element = FeedHandler.CHANNEL; } active_sub_element = null; strBuilder = new StringBuilder(); } @Override public void startDocument() throws SAXException { items = new ArrayList<FeedItem>(); strBuilder = new StringBuilder(); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase(FeedHandler.CHANNEL)) { if(feed == null) { feed = new Feed(); } active_root_element = qName; } else if (qName.equalsIgnoreCase(FeedHandler.ITEM)) { currentItem = new FeedItem(); active_root_element = qName; } else if (qName.equalsIgnoreCase(FeedHandler.TITLE)) { active_sub_element = qName; } else if (qName.equalsIgnoreCase(FeedHandler.DESCR)) { active_sub_element = qName; } else if (qName.equalsIgnoreCase(FeedHandler.LINK)) { active_sub_element = qName; } else if (qName.equalsIgnoreCase(FeedHandler.PUBDATE)) { active_sub_element = qName; } else if (qName.equalsIgnoreCase(FeedHandler.ENCLOSURE)) { currentItem.setMedia(new FeedMedia(currentItem, attributes.getValue(FeedHandler.ENC_URL), Long.parseLong(attributes.getValue(FeedHandler.ENC_LEN)), attributes.getValue(FeedHandler.ENC_TYPE))); } else if(qName.equalsIgnoreCase(FeedHandler.IMAGE)) { feed.setImage(new FeedImage()); active_root_element = qName; } else if(qName.equalsIgnoreCase(FeedHandler.URL)) { active_sub_element = qName; } } }
false
true
public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equalsIgnoreCase(FeedHandler.ITEM)) { currentItem.setFeed(feed); items.add(currentItem); } else if (qName.equalsIgnoreCase(FeedHandler.TITLE)) { if (active_root_element.equalsIgnoreCase(FeedHandler.CHANNEL)) { feed.setTitle(strBuilder.toString()); } else if(active_root_element.equalsIgnoreCase(FeedHandler.TITLE)) { currentItem.setTitle(strBuilder.toString()); } else if(active_root_element.equalsIgnoreCase(FeedHandler.IMAGE)) { feed.getImage().title = strBuilder.toString(); } } else if (qName.equalsIgnoreCase(FeedHandler.DESCR)) { if (active_root_element.equalsIgnoreCase(FeedHandler.CHANNEL)) { feed.setDescription(strBuilder.toString()); } else { currentItem.setDescription(strBuilder.toString()); } } else if (qName.equalsIgnoreCase(FeedHandler.LINK)) { if (active_root_element.equalsIgnoreCase(FeedHandler.CHANNEL)) { feed.setLink(strBuilder.toString()); } else if(active_root_element.equalsIgnoreCase(FeedHandler.TITLE)){ currentItem.setLink(strBuilder.toString()); } } else if (qName.equalsIgnoreCase(FeedHandler.PUBDATE)) { if (active_root_element.equalsIgnoreCase(FeedHandler.ITEM)) { currentItem.setPubDate(strBuilder.toString()); } } else if (qName.equalsIgnoreCase(FeedHandler.URL)) { if(active_root_element.equalsIgnoreCase(FeedHandler.IMAGE)) { feed.getImage().download_url = strBuilder.toString(); } } else if(qName.equalsIgnoreCase(FeedHandler.IMAGE)) { active_root_element = FeedHandler.CHANNEL; } active_sub_element = null; strBuilder = new StringBuilder(); }
public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equalsIgnoreCase(FeedHandler.ITEM)) { currentItem.setFeed(feed); items.add(currentItem); } else if (qName.equalsIgnoreCase(FeedHandler.TITLE)) { if (active_root_element.equalsIgnoreCase(FeedHandler.CHANNEL)) { feed.setTitle(strBuilder.toString()); } else if(active_root_element.equalsIgnoreCase(FeedHandler.ITEM)) { currentItem.setTitle(strBuilder.toString()); } else if(active_root_element.equalsIgnoreCase(FeedHandler.IMAGE)) { feed.getImage().title = strBuilder.toString(); } } else if (qName.equalsIgnoreCase(FeedHandler.DESCR)) { if (active_root_element.equalsIgnoreCase(FeedHandler.CHANNEL)) { feed.setDescription(strBuilder.toString()); } else { currentItem.setDescription(strBuilder.toString()); } } else if (qName.equalsIgnoreCase(FeedHandler.LINK)) { if (active_root_element.equalsIgnoreCase(FeedHandler.CHANNEL)) { feed.setLink(strBuilder.toString()); } else if(active_root_element.equalsIgnoreCase(FeedHandler.ITEM)){ currentItem.setLink(strBuilder.toString()); } } else if (qName.equalsIgnoreCase(FeedHandler.PUBDATE)) { if (active_root_element.equalsIgnoreCase(FeedHandler.ITEM)) { currentItem.setPubDate(strBuilder.toString()); } } else if (qName.equalsIgnoreCase(FeedHandler.URL)) { if(active_root_element.equalsIgnoreCase(FeedHandler.IMAGE)) { feed.getImage().download_url = strBuilder.toString(); } } else if(qName.equalsIgnoreCase(FeedHandler.IMAGE)) { active_root_element = FeedHandler.CHANNEL; } active_sub_element = null; strBuilder = new StringBuilder(); }
diff --git a/src/me/Kruithne/WolfHunt/WolfHunt.java b/src/me/Kruithne/WolfHunt/WolfHunt.java index 8899e39..bffc05d 100644 --- a/src/me/Kruithne/WolfHunt/WolfHunt.java +++ b/src/me/Kruithne/WolfHunt/WolfHunt.java @@ -1,43 +1,43 @@ package me.Kruithne.WolfHunt; import java.util.logging.Logger; import org.bukkit.Server; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.plugin.java.JavaPlugin; public class WolfHunt extends JavaPlugin { public Server server; public Logger log = Logger.getLogger("Minecraft"); public Configuration config = null; public CommandHandler commandHandler = null; public WolfHuntPlayerListener playerListener = null; public Tracking tracking = null; public VanishHandler vanisHandler = null; public Permissions permission = null; public VanishHandler vanishHandler = null; public Output output = null; public void onEnable() { this.server = this.getServer(); this.config = new Configuration(this); this.commandHandler = new CommandHandler(this); this.tracking = new Tracking(this.config); this.permission = new Permissions(this.config); - this.vanishHandler = new VanishHandler(this.server); + this.vanishHandler = new VanishHandler(this.server, this.config); this.output = new Output(this.log); this.playerListener = new WolfHuntPlayerListener(this.tracking, this.output, this.vanishHandler, this.permission, this.config); this.config.loadConfiguration(); - this.server.getPluginManager().registerEvents(this.commandHandler, this); + this.server.getPluginManager().registerEvents(this.playerListener, this); } public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] arguments) { return this.commandHandler.handleCommand(sender, command, arguments); } }
false
true
public void onEnable() { this.server = this.getServer(); this.config = new Configuration(this); this.commandHandler = new CommandHandler(this); this.tracking = new Tracking(this.config); this.permission = new Permissions(this.config); this.vanishHandler = new VanishHandler(this.server); this.output = new Output(this.log); this.playerListener = new WolfHuntPlayerListener(this.tracking, this.output, this.vanishHandler, this.permission, this.config); this.config.loadConfiguration(); this.server.getPluginManager().registerEvents(this.commandHandler, this); }
public void onEnable() { this.server = this.getServer(); this.config = new Configuration(this); this.commandHandler = new CommandHandler(this); this.tracking = new Tracking(this.config); this.permission = new Permissions(this.config); this.vanishHandler = new VanishHandler(this.server, this.config); this.output = new Output(this.log); this.playerListener = new WolfHuntPlayerListener(this.tracking, this.output, this.vanishHandler, this.permission, this.config); this.config.loadConfiguration(); this.server.getPluginManager().registerEvents(this.playerListener, this); }
diff --git a/src/com/github/desmaster/Devio/realm/storage/Inventory.java b/src/com/github/desmaster/Devio/realm/storage/Inventory.java index c73b3da..13a8dcb 100644 --- a/src/com/github/desmaster/Devio/realm/storage/Inventory.java +++ b/src/com/github/desmaster/Devio/realm/storage/Inventory.java @@ -1,182 +1,182 @@ package com.github.desmaster.Devio.realm.storage; import static org.lwjgl.opengl.GL11.GL_LINES; import static org.lwjgl.opengl.GL11.GL_QUADS; import static org.lwjgl.opengl.GL11.GL_TEXTURE_2D; import static org.lwjgl.opengl.GL11.glBegin; import static org.lwjgl.opengl.GL11.glColor4f; import static org.lwjgl.opengl.GL11.glDisable; import static org.lwjgl.opengl.GL11.glEnd; import static org.lwjgl.opengl.GL11.glLoadIdentity; import static org.lwjgl.opengl.GL11.glTranslatef; import static org.lwjgl.opengl.GL11.glVertex2f; import java.util.ArrayList; import java.util.List; import org.lwjgl.opengl.Display; import org.lwjgl.util.Rectangle; import com.github.desmaster.Devio.cons.Console; import com.github.desmaster.Devio.gfx.Screen; import com.github.desmaster.Devio.gfx.Text; import com.github.desmaster.Devio.gfx.userinterface.UserInterface; import com.github.desmaster.Devio.realm.item.Item; public class Inventory extends UserInterface { public List<Item> items = new ArrayList<Item>(); public static boolean active; public Inventory() { super("Inventory"); container = new Rectangle(50, 50, Display.getWidth() - 125, Display.getHeight() - 125); } public void add(int slot, Item item) { items.add(slot, item); } public boolean contains(Item item) { return items.contains(items); } public void tick() { if (Screen.getInput().inventory.clicked) { if (Screen.canOpenScreen(this)) active = !active; } if (active) { Screen.getPlayer().disableInput(); } else { if (!Console.isActive()) if (!Screen.getPlayer().isTicking()) Screen.getPlayer().enableInput(); } } public void render() { if (active) { shadeBackground(); renderInventoryContainer(); renderInventory(); } } public void shadeBackground() { glLoadIdentity(); glDisable(GL_TEXTURE_2D); glColor4f(0.025f, 0.025f, 0.025f, 0.8f); glTranslatef(0, 0, 0); glBegin(GL_QUADS); glVertex2f(0, 0); glVertex2f(0 + Display.getWidth(), 0); glVertex2f(0 + Display.getWidth(), 0 + Display.getHeight()); glVertex2f(0, 0 + Display.getHeight()); glEnd(); } public void renderInventoryContainer() { int x = container.getX(); int y = container.getY(); glLoadIdentity(); glDisable(GL_TEXTURE_2D); glColor4f(.4f, .2f, .08f, 1); glTranslatef(x, y, 0); glBegin(GL_QUADS); glVertex2f(x, y); glVertex2f(x + container.getWidth() - 50, y); glVertex2f(x + container.getWidth() - 50, y + container.getHeight() - 50); glVertex2f(x, y + container.getHeight() - 50); glEnd(); glLoadIdentity(); } public void renderInventory() { Text.drawString(name, container.getX() + 55, container.getY() + 65, 1, 1, 1, 1); glColor4f(1, 1, 1, 1); glBegin(GL_LINES); glVertex2f(container.getX() + 50, container.getY() + 70); glVertex2f(container.getX() + container.getWidth(), container.getY() + 70); glEnd(); renderSlotBackground(); renderSlots(); } public void renderSlotBackground() { glLoadIdentity(); int x = container.getX() + 25; int y = container.getY() + 20; glColor4f(0.67f, 0.35f, 0, 1); glTranslatef(x, y, 0); glBegin(GL_QUADS); glVertex2f(x, y); glVertex2f(x + container.getWidth() - 150, y); glVertex2f(x + container.getWidth() - 150, y + container.getHeight() - 115); glVertex2f(x, y + container.getHeight() - 115); glEnd(); } public void renderSlots() { glLoadIdentity(); int x = container.getX(); int y = container.getY() + 20; glColor4f(1, 1, 1, 1); glTranslatef(x, y, 0); glBegin(GL_LINES); glVertex2f(x, y); glVertex2f(x + container.getWidth() - 50, y); glEnd(); x += 50; glBegin(GL_LINES); glVertex2f(x, y); glVertex2f(x, y + container.getHeight() - 115); glEnd(); y += container.getHeight() - 115; glBegin(GL_LINES); glVertex2f(x, y); glVertex2f((x) + container.getWidth() - 150, y); glEnd(); x += container.getWidth() - 150; y -= container.getHeight() - 115; glBegin(GL_LINES); glVertex2f(x, y); glVertex2f(x, y + container.getHeight() - 115); glEnd(); int width = (container.getWidth()) / 32; int height = (container.getHeight()) / 32; glColor4f(1, 1, 1, 1); - for (int xx = 0; x < width; x++) { - for (int yy = 0; y < height; y++) { + for (int xx = 0; xx < width; xx++) { + for (int yy = 0; yy < height; yy++) { glBegin(GL_LINES); xx *= 32 / 2; yy *= 32 / 2; glVertex2f(xx, yy); glVertex2f(xx + 32, yy + 32); glEnd(); } } } public boolean contains(Item item, int count) { List<Item> items = new ArrayList<Item>(); for (int i = 0; i < count; i++) { items.add(item); } return items.containsAll(items); } public static boolean isActive() { return active; } public static void setActive(boolean bool) { active = bool; } }
true
true
public void renderSlots() { glLoadIdentity(); int x = container.getX(); int y = container.getY() + 20; glColor4f(1, 1, 1, 1); glTranslatef(x, y, 0); glBegin(GL_LINES); glVertex2f(x, y); glVertex2f(x + container.getWidth() - 50, y); glEnd(); x += 50; glBegin(GL_LINES); glVertex2f(x, y); glVertex2f(x, y + container.getHeight() - 115); glEnd(); y += container.getHeight() - 115; glBegin(GL_LINES); glVertex2f(x, y); glVertex2f((x) + container.getWidth() - 150, y); glEnd(); x += container.getWidth() - 150; y -= container.getHeight() - 115; glBegin(GL_LINES); glVertex2f(x, y); glVertex2f(x, y + container.getHeight() - 115); glEnd(); int width = (container.getWidth()) / 32; int height = (container.getHeight()) / 32; glColor4f(1, 1, 1, 1); for (int xx = 0; x < width; x++) { for (int yy = 0; y < height; y++) { glBegin(GL_LINES); xx *= 32 / 2; yy *= 32 / 2; glVertex2f(xx, yy); glVertex2f(xx + 32, yy + 32); glEnd(); } } }
public void renderSlots() { glLoadIdentity(); int x = container.getX(); int y = container.getY() + 20; glColor4f(1, 1, 1, 1); glTranslatef(x, y, 0); glBegin(GL_LINES); glVertex2f(x, y); glVertex2f(x + container.getWidth() - 50, y); glEnd(); x += 50; glBegin(GL_LINES); glVertex2f(x, y); glVertex2f(x, y + container.getHeight() - 115); glEnd(); y += container.getHeight() - 115; glBegin(GL_LINES); glVertex2f(x, y); glVertex2f((x) + container.getWidth() - 150, y); glEnd(); x += container.getWidth() - 150; y -= container.getHeight() - 115; glBegin(GL_LINES); glVertex2f(x, y); glVertex2f(x, y + container.getHeight() - 115); glEnd(); int width = (container.getWidth()) / 32; int height = (container.getHeight()) / 32; glColor4f(1, 1, 1, 1); for (int xx = 0; xx < width; xx++) { for (int yy = 0; yy < height; yy++) { glBegin(GL_LINES); xx *= 32 / 2; yy *= 32 / 2; glVertex2f(xx, yy); glVertex2f(xx + 32, yy + 32); glEnd(); } } }
diff --git a/core/src/main/java/org/icepush/PushGroupManagerFactory.java b/core/src/main/java/org/icepush/PushGroupManagerFactory.java index 478d768..8439783 100644 --- a/core/src/main/java/org/icepush/PushGroupManagerFactory.java +++ b/core/src/main/java/org/icepush/PushGroupManagerFactory.java @@ -1,128 +1,131 @@ /* * Copyright 2004-2012 ICEsoft Technologies Canada Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language * governing permissions and limitations under the License. * */ package org.icepush; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.HashSet; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletContext; import org.icepush.util.AnnotationScanner; public class PushGroupManagerFactory { private static final Logger LOGGER = Logger.getLogger(PushGroupManagerFactory.class.getName()); public static PushGroupManager newPushGroupManager(final ServletContext servletContext, final Configuration configuration) { - String _pushGroupManager = configuration.getAttribute("pushGroupManager", null); + String _pushGroupManager = (String)servletContext.getAttribute("org.icepush.PushGroupManager"); + if (_pushGroupManager == null) { + _pushGroupManager = configuration.getAttribute("pushGroupManager", null); + } if (_pushGroupManager == null || _pushGroupManager.trim().length() == 0) { LOGGER.log(Level.FINEST, "Using annotation scanner to find @ExtendedPushGroupManager."); Set<String> _annotationSet = new HashSet<String>(); _annotationSet.add("Lorg/icepush/ExtendedPushGroupManager;"); AnnotationScanner _annotationScanner = new AnnotationScanner(_annotationSet, servletContext); try { Class[] _classes = _annotationScanner.getClasses(); // throws IOException for (Class _class : _classes) { try { return (PushGroupManager) _class. // throws NoSuchMethodException, SecurityException getConstructor(ServletContext.class). // throws // IllegalAccessException, IllegalArgumentException, InstantiationException, // InvocationTargetException, ExceptionInInitializerError newInstance(servletContext); } catch (NoSuchMethodException exception) { LOGGER.log(Level.FINEST, "Can't get constructor!", exception); // Do nothing. } catch (SecurityException exception) { LOGGER.log(Level.FINEST, "Can't get constructor!", exception); // Do nothing. } catch (IllegalAccessException exception) { LOGGER.log(Level.FINEST, "Can't create instance!", exception); // Do nothing. } catch (IllegalArgumentException exception) { LOGGER.log(Level.FINEST, "Can't create instance!", exception); // Do nothing. } catch (InstantiationException exception) { LOGGER.log(Level.FINEST, "Can't create instance!", exception); // Do nothing. } catch (InvocationTargetException exception) { LOGGER.log(Level.FINEST, "Can't create instance!", exception); // Do nothing. } catch (ExceptionInInitializerError error) { LOGGER.log(Level.FINEST, "Can't create instance!", error); // Do nothing. } } } catch (IOException exception) { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log( Level.FINEST, "An I/O error occurred while trying to get the classes.", exception); } // Do nothing. } } else { LOGGER.log(Level.FINEST, "PushGroupManager: " + _pushGroupManager); try { return (PushGroupManager) // throws ClassNotFoundException, ExceptionInInitializerError Class.forName(_pushGroupManager). // throws NoSuchMethodException, SecurityException getConstructor(ServletContext.class). // throws // IllegalAccessException, IllegalArgumentException, InstantiationException, // InvocationTargetException, ExceptionInInitializerError newInstance(servletContext); } catch (ClassNotFoundException exception) { LOGGER.log(Level.FINEST, "Can't find class!", exception); // Do nothing. } catch (ExceptionInInitializerError error) { LOGGER.log(Level.FINEST, "Can't find class or can't create instance!", error); // Do nothing. } catch (NoSuchMethodException exception) { LOGGER.log(Level.FINEST, "Can't get constructor!", exception); // Do nothing. } catch (SecurityException exception) { LOGGER.log(Level.FINEST, "Can't get constructor!", exception); // Do nothing. } catch (IllegalAccessException exception) { LOGGER.log(Level.FINEST, "Can't create instance!", exception); // Do nothing. } catch (IllegalArgumentException exception) { LOGGER.log(Level.FINEST, "Can't create instance!", exception); // Do nothing. } catch (InstantiationException exception) { LOGGER.log(Level.FINEST, "Can't create instance!", exception); // Do nothing. } catch (InvocationTargetException exception) { LOGGER.log(Level.FINEST, "Can't create instance!", exception); // Do nothing. } } LOGGER.log(Level.FINEST, "Falling back to LocalPushGroupManager."); return new LocalPushGroupManager(servletContext); } }
true
true
public static PushGroupManager newPushGroupManager(final ServletContext servletContext, final Configuration configuration) { String _pushGroupManager = configuration.getAttribute("pushGroupManager", null); if (_pushGroupManager == null || _pushGroupManager.trim().length() == 0) { LOGGER.log(Level.FINEST, "Using annotation scanner to find @ExtendedPushGroupManager."); Set<String> _annotationSet = new HashSet<String>(); _annotationSet.add("Lorg/icepush/ExtendedPushGroupManager;"); AnnotationScanner _annotationScanner = new AnnotationScanner(_annotationSet, servletContext); try { Class[] _classes = _annotationScanner.getClasses(); // throws IOException for (Class _class : _classes) { try { return (PushGroupManager) _class. // throws NoSuchMethodException, SecurityException getConstructor(ServletContext.class). // throws // IllegalAccessException, IllegalArgumentException, InstantiationException, // InvocationTargetException, ExceptionInInitializerError newInstance(servletContext); } catch (NoSuchMethodException exception) { LOGGER.log(Level.FINEST, "Can't get constructor!", exception); // Do nothing. } catch (SecurityException exception) { LOGGER.log(Level.FINEST, "Can't get constructor!", exception); // Do nothing. } catch (IllegalAccessException exception) { LOGGER.log(Level.FINEST, "Can't create instance!", exception); // Do nothing. } catch (IllegalArgumentException exception) { LOGGER.log(Level.FINEST, "Can't create instance!", exception); // Do nothing. } catch (InstantiationException exception) { LOGGER.log(Level.FINEST, "Can't create instance!", exception); // Do nothing. } catch (InvocationTargetException exception) { LOGGER.log(Level.FINEST, "Can't create instance!", exception); // Do nothing. } catch (ExceptionInInitializerError error) { LOGGER.log(Level.FINEST, "Can't create instance!", error); // Do nothing. } } } catch (IOException exception) { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log( Level.FINEST, "An I/O error occurred while trying to get the classes.", exception); } // Do nothing. } } else { LOGGER.log(Level.FINEST, "PushGroupManager: " + _pushGroupManager); try { return (PushGroupManager) // throws ClassNotFoundException, ExceptionInInitializerError Class.forName(_pushGroupManager). // throws NoSuchMethodException, SecurityException getConstructor(ServletContext.class). // throws // IllegalAccessException, IllegalArgumentException, InstantiationException, // InvocationTargetException, ExceptionInInitializerError newInstance(servletContext); } catch (ClassNotFoundException exception) { LOGGER.log(Level.FINEST, "Can't find class!", exception); // Do nothing. } catch (ExceptionInInitializerError error) { LOGGER.log(Level.FINEST, "Can't find class or can't create instance!", error); // Do nothing. } catch (NoSuchMethodException exception) { LOGGER.log(Level.FINEST, "Can't get constructor!", exception); // Do nothing. } catch (SecurityException exception) { LOGGER.log(Level.FINEST, "Can't get constructor!", exception); // Do nothing. } catch (IllegalAccessException exception) { LOGGER.log(Level.FINEST, "Can't create instance!", exception); // Do nothing. } catch (IllegalArgumentException exception) { LOGGER.log(Level.FINEST, "Can't create instance!", exception); // Do nothing. } catch (InstantiationException exception) { LOGGER.log(Level.FINEST, "Can't create instance!", exception); // Do nothing. } catch (InvocationTargetException exception) { LOGGER.log(Level.FINEST, "Can't create instance!", exception); // Do nothing. } } LOGGER.log(Level.FINEST, "Falling back to LocalPushGroupManager."); return new LocalPushGroupManager(servletContext); }
public static PushGroupManager newPushGroupManager(final ServletContext servletContext, final Configuration configuration) { String _pushGroupManager = (String)servletContext.getAttribute("org.icepush.PushGroupManager"); if (_pushGroupManager == null) { _pushGroupManager = configuration.getAttribute("pushGroupManager", null); } if (_pushGroupManager == null || _pushGroupManager.trim().length() == 0) { LOGGER.log(Level.FINEST, "Using annotation scanner to find @ExtendedPushGroupManager."); Set<String> _annotationSet = new HashSet<String>(); _annotationSet.add("Lorg/icepush/ExtendedPushGroupManager;"); AnnotationScanner _annotationScanner = new AnnotationScanner(_annotationSet, servletContext); try { Class[] _classes = _annotationScanner.getClasses(); // throws IOException for (Class _class : _classes) { try { return (PushGroupManager) _class. // throws NoSuchMethodException, SecurityException getConstructor(ServletContext.class). // throws // IllegalAccessException, IllegalArgumentException, InstantiationException, // InvocationTargetException, ExceptionInInitializerError newInstance(servletContext); } catch (NoSuchMethodException exception) { LOGGER.log(Level.FINEST, "Can't get constructor!", exception); // Do nothing. } catch (SecurityException exception) { LOGGER.log(Level.FINEST, "Can't get constructor!", exception); // Do nothing. } catch (IllegalAccessException exception) { LOGGER.log(Level.FINEST, "Can't create instance!", exception); // Do nothing. } catch (IllegalArgumentException exception) { LOGGER.log(Level.FINEST, "Can't create instance!", exception); // Do nothing. } catch (InstantiationException exception) { LOGGER.log(Level.FINEST, "Can't create instance!", exception); // Do nothing. } catch (InvocationTargetException exception) { LOGGER.log(Level.FINEST, "Can't create instance!", exception); // Do nothing. } catch (ExceptionInInitializerError error) { LOGGER.log(Level.FINEST, "Can't create instance!", error); // Do nothing. } } } catch (IOException exception) { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log( Level.FINEST, "An I/O error occurred while trying to get the classes.", exception); } // Do nothing. } } else { LOGGER.log(Level.FINEST, "PushGroupManager: " + _pushGroupManager); try { return (PushGroupManager) // throws ClassNotFoundException, ExceptionInInitializerError Class.forName(_pushGroupManager). // throws NoSuchMethodException, SecurityException getConstructor(ServletContext.class). // throws // IllegalAccessException, IllegalArgumentException, InstantiationException, // InvocationTargetException, ExceptionInInitializerError newInstance(servletContext); } catch (ClassNotFoundException exception) { LOGGER.log(Level.FINEST, "Can't find class!", exception); // Do nothing. } catch (ExceptionInInitializerError error) { LOGGER.log(Level.FINEST, "Can't find class or can't create instance!", error); // Do nothing. } catch (NoSuchMethodException exception) { LOGGER.log(Level.FINEST, "Can't get constructor!", exception); // Do nothing. } catch (SecurityException exception) { LOGGER.log(Level.FINEST, "Can't get constructor!", exception); // Do nothing. } catch (IllegalAccessException exception) { LOGGER.log(Level.FINEST, "Can't create instance!", exception); // Do nothing. } catch (IllegalArgumentException exception) { LOGGER.log(Level.FINEST, "Can't create instance!", exception); // Do nothing. } catch (InstantiationException exception) { LOGGER.log(Level.FINEST, "Can't create instance!", exception); // Do nothing. } catch (InvocationTargetException exception) { LOGGER.log(Level.FINEST, "Can't create instance!", exception); // Do nothing. } } LOGGER.log(Level.FINEST, "Falling back to LocalPushGroupManager."); return new LocalPushGroupManager(servletContext); }
diff --git a/src/main/java/net/qldarch/ingest/transcript/TranscriptDescribeFactory.java b/src/main/java/net/qldarch/ingest/transcript/TranscriptDescribeFactory.java index dc6e8a5..ef6ca45 100644 --- a/src/main/java/net/qldarch/ingest/transcript/TranscriptDescribeFactory.java +++ b/src/main/java/net/qldarch/ingest/transcript/TranscriptDescribeFactory.java @@ -1,15 +1,15 @@ package net.qldarch.ingest.transcript; import net.qldarch.ingest.Configuration; import net.qldarch.ingest.IngestStage; import net.qldarch.ingest.IngestStageFactory; public class TranscriptDescribeFactory implements IngestStageFactory<TranscriptDescribe> { public String getStageName() { - return "deploy"; + return "describe"; } public TranscriptDescribe createIngestStage(Configuration configuration) { return new TranscriptDescribe(configuration); } }
true
true
public String getStageName() { return "deploy"; }
public String getStageName() { return "describe"; }
diff --git a/src/test/cli/cloudify/cloud/services/rackspace/RackspaceCloudService.java b/src/test/cli/cloudify/cloud/services/rackspace/RackspaceCloudService.java index ae3e4e9c..ab51980c 100644 --- a/src/test/cli/cloudify/cloud/services/rackspace/RackspaceCloudService.java +++ b/src/test/cli/cloudify/cloud/services/rackspace/RackspaceCloudService.java @@ -1,81 +1,81 @@ package test.cli.cloudify.cloud.services.rackspace; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.commons.io.FileUtils; import test.cli.cloudify.cloud.services.AbstractCloudService; import framework.tools.SGTestHelper; import framework.utils.IOUtils; import framework.utils.ScriptUtils; public class RackspaceCloudService extends AbstractCloudService { private String cloudName = "rsopenstack"; private String user = "gsrackspace"; private String apiKey = "1ee2495897b53409f4643926f1968c0c"; private String tenant = "658142"; public String getCloudName() { return cloudName; } public void setCloudName(String cloudName) { this.cloudName = cloudName; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getApiKey() { return apiKey; } public void setApiKey(String apiKey) { this.apiKey = apiKey; } public String getTenant() { return tenant; } public void setTenant(String tenant) { this.tenant = tenant; } @Override public void injectAuthenticationDetails() throws IOException { String cloudTestPath = (SGTestHelper.getSGTestRootDir() + "/apps/cloudify/cloud/" + cloudName).replace('\\', '/'); // cloud plugin should include recipe that includes secret key File cloudPluginDir = new File(ScriptUtils.getBuildPath() , "tools/cli/plugins/esc/" + cloudName + "/"); File originalCloudDslFile = new File(cloudPluginDir, cloudName + "-cloud.groovy"); File backupCloudDslFile = new File(cloudPluginDir, cloudName + "-cloud.backup"); // first make a backup of the original file FileUtils.copyFile(originalCloudDslFile, backupCloudDslFile); Map<String, String> propsToReplace = new HashMap<String,String>(); - propsToReplace.put("ENTER_USER", user); - propsToReplace.put("ENTER_API_KEY", apiKey); + propsToReplace.put("USER_NAME", user); + propsToReplace.put("API_KEY", apiKey); propsToReplace.put("cloudify_agent_", this.machinePrefix + "cloudify_agent"); propsToReplace.put("cloudify_manager", this.machinePrefix + "cloudify_manager"); propsToReplace.put("ENTER_TENANT", tenant); propsToReplace.put("numberOfManagementMachines 1", "numberOfManagementMachines " + numberOfManagementMachines); propsToReplace.put("\"openstack.wireLog\": \"false\"", "\"openstack.wireLog\": \"true\""); IOUtils.replaceTextInFile(originalCloudDslFile, propsToReplace); } }
true
true
public void injectAuthenticationDetails() throws IOException { String cloudTestPath = (SGTestHelper.getSGTestRootDir() + "/apps/cloudify/cloud/" + cloudName).replace('\\', '/'); // cloud plugin should include recipe that includes secret key File cloudPluginDir = new File(ScriptUtils.getBuildPath() , "tools/cli/plugins/esc/" + cloudName + "/"); File originalCloudDslFile = new File(cloudPluginDir, cloudName + "-cloud.groovy"); File backupCloudDslFile = new File(cloudPluginDir, cloudName + "-cloud.backup"); // first make a backup of the original file FileUtils.copyFile(originalCloudDslFile, backupCloudDslFile); Map<String, String> propsToReplace = new HashMap<String,String>(); propsToReplace.put("ENTER_USER", user); propsToReplace.put("ENTER_API_KEY", apiKey); propsToReplace.put("cloudify_agent_", this.machinePrefix + "cloudify_agent"); propsToReplace.put("cloudify_manager", this.machinePrefix + "cloudify_manager"); propsToReplace.put("ENTER_TENANT", tenant); propsToReplace.put("numberOfManagementMachines 1", "numberOfManagementMachines " + numberOfManagementMachines); propsToReplace.put("\"openstack.wireLog\": \"false\"", "\"openstack.wireLog\": \"true\""); IOUtils.replaceTextInFile(originalCloudDslFile, propsToReplace); }
public void injectAuthenticationDetails() throws IOException { String cloudTestPath = (SGTestHelper.getSGTestRootDir() + "/apps/cloudify/cloud/" + cloudName).replace('\\', '/'); // cloud plugin should include recipe that includes secret key File cloudPluginDir = new File(ScriptUtils.getBuildPath() , "tools/cli/plugins/esc/" + cloudName + "/"); File originalCloudDslFile = new File(cloudPluginDir, cloudName + "-cloud.groovy"); File backupCloudDslFile = new File(cloudPluginDir, cloudName + "-cloud.backup"); // first make a backup of the original file FileUtils.copyFile(originalCloudDslFile, backupCloudDslFile); Map<String, String> propsToReplace = new HashMap<String,String>(); propsToReplace.put("USER_NAME", user); propsToReplace.put("API_KEY", apiKey); propsToReplace.put("cloudify_agent_", this.machinePrefix + "cloudify_agent"); propsToReplace.put("cloudify_manager", this.machinePrefix + "cloudify_manager"); propsToReplace.put("ENTER_TENANT", tenant); propsToReplace.put("numberOfManagementMachines 1", "numberOfManagementMachines " + numberOfManagementMachines); propsToReplace.put("\"openstack.wireLog\": \"false\"", "\"openstack.wireLog\": \"true\""); IOUtils.replaceTextInFile(originalCloudDslFile, propsToReplace); }
diff --git a/iris-core/src/main/java/ru/iris/Launcher.java b/iris-core/src/main/java/ru/iris/Launcher.java index 2c9436a..cca80fe 100644 --- a/iris-core/src/main/java/ru/iris/Launcher.java +++ b/iris-core/src/main/java/ru/iris/Launcher.java @@ -1,86 +1,86 @@ package ru.iris; import org.h2.tools.Server; import org.jetbrains.annotations.NonNls; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.iris.common.Config; import ru.iris.common.I18N; import ru.iris.common.Messaging; import ru.iris.common.SQL; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; import java.io.IOException; import java.util.HashMap; /** * IRISv2 Project * Author: Nikolay A. Viguro * WWW: iris.ph-systems.ru * E-Mail: [email protected] * Date: 08.09.13 * Time: 22:52 * License: GPL v3 */ public class Launcher { public static HashMap<String, String> config; private static Logger log = LoggerFactory.getLogger(Launcher.class); public static SQL sql; public static MessageConsumer messageConsumer; public static MessageProducer messageProducer; public static Messaging msg; public static Session session; public static void main(String[] args) throws Exception { // Launch H2 TCP server Server.createTcpServer().start(); msg = new Messaging(); messageConsumer = msg.getConsumer (); messageProducer = msg.getProducer (); session = msg.getSession (); // Enable internationalization I18N i18n = new I18N(); log.info ("----------------------------------------"); log.info (i18n.message("irisv2.is.starting")); log.info ("----------------------------------------"); // Load configuration Config cfg = new Config (); config = cfg.getConfig (); sql = new SQL(); // Modules poll new StatusChecker(); // Lauch REST service - runModule("java -jar Rest.jar"); + runModule("java -jar iris-rest.jar"); // Launch capture sound module - runModule("java -jar Record.jar"); + runModule("java -jar iris-record.jar"); // Launch speak synth module - runModule("java -jar Speak.jar"); + runModule("java -jar iris-speak.jar"); // Launch module for work with devices - runModule("java -jar Devices.jar"); + runModule("java -jar iris-devices.jar"); // Launch schedule module - runModule("java -jar Scheduler.jar"); + runModule("java -jar iris-scheduler.jar"); // Launch events module - runModule("java -jar Events.jar"); + runModule("java -jar iris-events.jar"); } private static void runModule(@NonNls String cmd) throws IOException { ProcessBuilder builder = new ProcessBuilder(cmd.split("\\s+")).redirectOutput(ProcessBuilder.Redirect.INHERIT).redirectErrorStream(true); builder.start(); } }
false
true
public static void main(String[] args) throws Exception { // Launch H2 TCP server Server.createTcpServer().start(); msg = new Messaging(); messageConsumer = msg.getConsumer (); messageProducer = msg.getProducer (); session = msg.getSession (); // Enable internationalization I18N i18n = new I18N(); log.info ("----------------------------------------"); log.info (i18n.message("irisv2.is.starting")); log.info ("----------------------------------------"); // Load configuration Config cfg = new Config (); config = cfg.getConfig (); sql = new SQL(); // Modules poll new StatusChecker(); // Lauch REST service runModule("java -jar Rest.jar"); // Launch capture sound module runModule("java -jar Record.jar"); // Launch speak synth module runModule("java -jar Speak.jar"); // Launch module for work with devices runModule("java -jar Devices.jar"); // Launch schedule module runModule("java -jar Scheduler.jar"); // Launch events module runModule("java -jar Events.jar"); }
public static void main(String[] args) throws Exception { // Launch H2 TCP server Server.createTcpServer().start(); msg = new Messaging(); messageConsumer = msg.getConsumer (); messageProducer = msg.getProducer (); session = msg.getSession (); // Enable internationalization I18N i18n = new I18N(); log.info ("----------------------------------------"); log.info (i18n.message("irisv2.is.starting")); log.info ("----------------------------------------"); // Load configuration Config cfg = new Config (); config = cfg.getConfig (); sql = new SQL(); // Modules poll new StatusChecker(); // Lauch REST service runModule("java -jar iris-rest.jar"); // Launch capture sound module runModule("java -jar iris-record.jar"); // Launch speak synth module runModule("java -jar iris-speak.jar"); // Launch module for work with devices runModule("java -jar iris-devices.jar"); // Launch schedule module runModule("java -jar iris-scheduler.jar"); // Launch events module runModule("java -jar iris-events.jar"); }
diff --git a/river/src/main/java/org/jboss/marshalling/river/RiverMarshaller.java b/river/src/main/java/org/jboss/marshalling/river/RiverMarshaller.java index fbfd6ef..81f335d 100644 --- a/river/src/main/java/org/jboss/marshalling/river/RiverMarshaller.java +++ b/river/src/main/java/org/jboss/marshalling/river/RiverMarshaller.java @@ -1,1456 +1,1456 @@ /* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.river; import java.io.Externalizable; import java.io.IOException; import java.io.InvalidClassException; import java.io.InvalidObjectException; import java.io.NotSerializableException; import java.io.ObjectOutput; import java.lang.reflect.Field; import java.lang.reflect.Proxy; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.security.PrivilegedAction; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.TreeSet; import java.util.EnumMap; import java.util.EnumSet; import java.util.AbstractCollection; import java.util.AbstractList; import java.util.AbstractQueue; import java.util.AbstractSequentialList; import java.util.AbstractSet; import java.util.Vector; import java.util.Stack; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; import org.jboss.marshalling.AbstractMarshaller; import org.jboss.marshalling.ByteOutput; import org.jboss.marshalling.ClassExternalizerFactory; import org.jboss.marshalling.ClassTable; import org.jboss.marshalling.Externalizer; import org.jboss.marshalling.MarshallingConfiguration; import org.jboss.marshalling.ObjectResolver; import org.jboss.marshalling.ObjectTable; import org.jboss.marshalling.Pair; import org.jboss.marshalling.UTFUtils; import org.jboss.marshalling.TraceInformation; import org.jboss.marshalling.reflect.SerializableClass; import org.jboss.marshalling.reflect.SerializableClassRegistry; import org.jboss.marshalling.reflect.SerializableField; import org.jboss.marshalling.util.IdentityIntMap; import static org.jboss.marshalling.river.Protocol.*; /** * */ public class RiverMarshaller extends AbstractMarshaller { private final IdentityIntMap<Object> instanceCache; private final IdentityIntMap<Class<?>> classCache; private final IdentityHashMap<Class<?>, Externalizer> externalizers; private int instanceSeq; private int classSeq; private final SerializableClassRegistry registry; private RiverObjectOutputStream objectOutputStream; private ObjectOutput objectOutput; private BlockMarshaller blockMarshaller; protected RiverMarshaller(final RiverMarshallerFactory marshallerFactory, final SerializableClassRegistry registry, final MarshallingConfiguration configuration) throws IOException { super(marshallerFactory, configuration); final int configuredVersion = this.configuredVersion; if (configuredVersion < MIN_VERSION || configuredVersion > MAX_VERSION) { throw new IOException("Unsupported protocol version " + configuredVersion); } this.registry = registry; final float loadFactor = 0x0.5p0f; instanceCache = new IdentityIntMap<Object>((int) ((double)configuration.getInstanceCount() / (double)loadFactor), loadFactor); classCache = new IdentityIntMap<Class<?>>((int) ((double)configuration.getClassCount() / (double)loadFactor), loadFactor); externalizers = new IdentityHashMap<Class<?>, Externalizer>(configuration.getClassCount()); } protected void doWriteObject(final Object original, final boolean unshared) throws IOException { final ClassExternalizerFactory classExternalizerFactory = this.classExternalizerFactory; final ObjectResolver objectResolver = this.objectResolver; Object obj = original; Class<?> objClass; int id; boolean isArray, isEnum; SerializableClass info; boolean unreplaced = true; final int configuredVersion = this.configuredVersion; try { for (;;) { if (obj == null) { write(ID_NULL); return; } final int rid; if (! unshared && (rid = instanceCache.get(obj, -1)) != -1) { final int diff = rid - instanceSeq; if (diff >= -256) { write(ID_REPEAT_OBJECT_NEAR); write(diff); } else if (diff >= -65536) { write(ID_REPEAT_OBJECT_NEARISH); writeShort(diff); } else { write(ID_REPEAT_OBJECT_FAR); writeInt(rid); } return; } final ObjectTable.Writer objectTableWriter; if (! unshared && (objectTableWriter = objectTable.getObjectWriter(obj)) != null) { write(ID_PREDEFINED_OBJECT); if (configuredVersion == 1) { objectTableWriter.writeObject(getBlockMarshaller(), obj); writeEndBlock(); } else { objectTableWriter.writeObject(this, obj); } return; } objClass = obj.getClass(); id = getBasicClasses(configuredVersion).get(objClass, -1); // First, non-replaceable classes if (id == ID_CLASS_CLASS) { final Class<?> classObj = (Class<?>) obj; // If a class is one we have an entry for, we just write that byte directly. // These guys can't be written directly though, otherwise they'll get confused with the objects // of the corresponding type. final int cid = BASIC_CLASSES_V2.get(classObj, -1); switch (cid) { case -1: case ID_SINGLETON_MAP_OBJECT: case ID_SINGLETON_SET_OBJECT: case ID_SINGLETON_LIST_OBJECT: case ID_EMPTY_MAP_OBJECT: case ID_EMPTY_SET_OBJECT: case ID_EMPTY_LIST_OBJECT: { // If the class is one of the above special object types, then we write a // full NEW_OBJECT+CLASS_CLASS header followed by the class byte, or if there is none, write // the full class descriptor. write(ID_NEW_OBJECT); writeClassClass(classObj); return; } default: { write(cid); return; } } // not reached } isEnum = obj instanceof Enum; isArray = objClass.isArray(); // objects with id != -1 will never make use of the "info" param in *any* way info = isArray || isEnum || id != -1 ? null : registry.lookup(objClass); // replace once - objects with id != -1 will not have replacement methods but might be globally replaced if (unreplaced) { if (info != null) { // check for a user replacement if (info.hasWriteReplace()) { obj = info.callWriteReplace(obj); } } // Check for a global replacement obj = objectResolver.writeReplace(obj); if (obj != original) { unreplaced = false; continue; } else { break; } } else { break; } } if (isEnum) { // objClass cannot equal Enum.class because it is abstract final Enum<?> theEnum = (Enum<?>) obj; // enums are always shared write(ID_NEW_OBJECT); writeEnumClass(theEnum.getDeclaringClass()); writeString(theEnum.name()); instanceCache.put(obj, instanceSeq++); return; } // Now replaceable classes switch (id) { case ID_BYTE_CLASS: { write(ID_BYTE_OBJECT); writeByte(((Byte) obj).byteValue()); return; } case ID_BOOLEAN_CLASS: { write(((Boolean) obj).booleanValue() ? ID_BOOLEAN_OBJECT_TRUE : ID_BOOLEAN_OBJECT_FALSE); return; } case ID_CHARACTER_CLASS: { write(ID_CHARACTER_OBJECT); writeChar(((Character) obj).charValue()); return; } case ID_DOUBLE_CLASS: { write(ID_DOUBLE_OBJECT); writeDouble(((Double) obj).doubleValue()); return; } case ID_FLOAT_CLASS: { write(ID_FLOAT_OBJECT); writeFloat(((Float) obj).floatValue()); return; } case ID_INTEGER_CLASS: { write(ID_INTEGER_OBJECT); writeInt(((Integer) obj).intValue()); return; } case ID_LONG_CLASS: { write(ID_LONG_OBJECT); writeLong(((Long) obj).longValue()); return; } case ID_SHORT_CLASS: { write(ID_SHORT_OBJECT); writeShort(((Short) obj).shortValue()); return; } case ID_STRING_CLASS: { final String string = (String) obj; final int len = string.length(); if (len == 0) { write(ID_STRING_EMPTY); // don't cache empty strings return; } else if (len <= 0x100) { write(ID_STRING_SMALL); write(len); } else if (len <= 0x10000) { write(ID_STRING_MEDIUM); writeShort(len); } else { write(ID_STRING_LARGE); writeInt(len); } shallowFlush(); UTFUtils.writeUTFBytes(byteOutput, string); if (unshared) { instanceCache.put(obj, -1); instanceSeq++; } else { instanceCache.put(obj, instanceSeq++); } return; } case ID_BYTE_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final byte[] bytes = (byte[]) obj; final int len = bytes.length; if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_BYTE); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_BYTE); write(bytes, 0, len); } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_BYTE); write(bytes, 0, len); } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_BYTE); write(bytes, 0, len); } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_BOOLEAN_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final boolean[] booleans = (boolean[]) obj; final int len = booleans.length; if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_BOOLEAN); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_BOOLEAN); writeBooleanArray(booleans); } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_BOOLEAN); writeBooleanArray(booleans); } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_BOOLEAN); writeBooleanArray(booleans); } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_CHAR_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final char[] chars = (char[]) obj; final int len = chars.length; if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_CHAR); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_CHAR); for (int i = 0; i < len; i ++) { writeChar(chars[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_CHAR); for (int i = 0; i < len; i ++) { writeChar(chars[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_CHAR); for (int i = 0; i < len; i ++) { writeChar(chars[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_SHORT_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final short[] shorts = (short[]) obj; final int len = shorts.length; if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_SHORT); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_SHORT); for (int i = 0; i < len; i ++) { writeShort(shorts[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_SHORT); for (int i = 0; i < len; i ++) { writeShort(shorts[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_SHORT); for (int i = 0; i < len; i ++) { writeShort(shorts[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_INT_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final int[] ints = (int[]) obj; final int len = ints.length; if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_INT); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_INT); for (int i = 0; i < len; i ++) { writeInt(ints[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_INT); for (int i = 0; i < len; i ++) { writeInt(ints[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_INT); for (int i = 0; i < len; i ++) { writeInt(ints[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_LONG_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final long[] longs = (long[]) obj; final int len = longs.length; if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_LONG); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_LONG); for (int i = 0; i < len; i ++) { writeLong(longs[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_LONG); for (int i = 0; i < len; i ++) { writeLong(longs[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_LONG); for (int i = 0; i < len; i ++) { writeLong(longs[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_FLOAT_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final float[] floats = (float[]) obj; final int len = floats.length; if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_FLOAT); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_FLOAT); for (int i = 0; i < len; i ++) { writeFloat(floats[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_FLOAT); for (int i = 0; i < len; i ++) { writeFloat(floats[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_FLOAT); for (int i = 0; i < len; i ++) { writeFloat(floats[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_DOUBLE_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final double[] doubles = (double[]) obj; final int len = doubles.length; if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_DOUBLE); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_DOUBLE); for (int i = 0; i < len; i ++) { writeDouble(doubles[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_DOUBLE); for (int i = 0; i < len; i ++) { writeDouble(doubles[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_DOUBLE); for (int i = 0; i < len; i ++) { writeDouble(doubles[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_CC_HASH_SET: case ID_CC_LINKED_HASH_SET: case ID_CC_TREE_SET: case ID_CC_ARRAY_LIST: case ID_CC_LINKED_LIST: case ID_CC_VECTOR: case ID_CC_STACK: case ID_CC_ARRAY_DEQUE: { instanceCache.put(obj, instanceSeq++); final Collection<?> collection = (Collection<?>) obj; final int len = collection.size(); if (len == 0) { write(unshared ? ID_COLLECTION_EMPTY_UNSHARED : ID_COLLECTION_EMPTY); write(id); if (id == ID_CC_TREE_SET) { doWriteObject(((TreeSet)collection).comparator(), false); } } else if (len <= 256) { write(unshared ? ID_COLLECTION_SMALL_UNSHARED : ID_COLLECTION_SMALL); write(len); write(id); if (id == ID_CC_TREE_SET) { doWriteObject(((TreeSet)collection).comparator(), false); } for (Object o : collection) { doWriteObject(o, false); } } else if (len <= 65536) { write(unshared ? ID_COLLECTION_MEDIUM_UNSHARED : ID_COLLECTION_MEDIUM); writeShort(len); write(id); if (id == ID_CC_TREE_SET) { doWriteObject(((TreeSet)collection).comparator(), false); } for (Object o : collection) { doWriteObject(o, false); } } else { write(unshared ? ID_COLLECTION_LARGE_UNSHARED : ID_COLLECTION_LARGE); writeInt(len); write(id); if (id == ID_CC_TREE_SET) { doWriteObject(((TreeSet)collection).comparator(), false); } for (Object o : collection) { doWriteObject(o, false); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_CC_ENUM_SET_PROXY: { instanceCache.put(obj, instanceSeq++); final Enum[] elements = getEnumSetElements(obj); final int len = elements.length; if (len == 0) { write(unshared ? ID_COLLECTION_EMPTY_UNSHARED : ID_COLLECTION_EMPTY); write(id); writeClass(getEnumSetElementType(obj)); } else if (len <= 256) { write(unshared ? ID_COLLECTION_SMALL_UNSHARED : ID_COLLECTION_SMALL); write(len); write(id); writeClass(getEnumSetElementType(obj)); for (Object o : elements) { doWriteObject(o, false); } } else if (len <= 65536) { write(unshared ? ID_COLLECTION_MEDIUM_UNSHARED : ID_COLLECTION_MEDIUM); writeShort(len); write(id); writeClass(getEnumSetElementType(obj)); for (Object o : elements) { doWriteObject(o, false); } } else { write(unshared ? ID_COLLECTION_LARGE_UNSHARED : ID_COLLECTION_LARGE); writeInt(len); write(id); writeClass(getEnumSetElementType(obj)); for (Object o : elements) { doWriteObject(o, false); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_CC_HASH_MAP: case ID_CC_HASHTABLE: case ID_CC_IDENTITY_HASH_MAP: case ID_CC_LINKED_HASH_MAP: case ID_CC_TREE_MAP: case ID_CC_ENUM_MAP: { instanceCache.put(obj, instanceSeq++); final Map<?, ?> map = (Map<?, ?>) obj; final int len = map.size(); if (len == 0) { write(unshared ? ID_COLLECTION_EMPTY_UNSHARED : ID_COLLECTION_EMPTY); write(id); switch (id) { case ID_CC_TREE_MAP: doWriteObject(((TreeMap)map).comparator(), false); break; case ID_CC_ENUM_MAP: writeClass(getEnumMapKeyType(obj)); break; } } else if (len <= 256) { write(unshared ? ID_COLLECTION_SMALL_UNSHARED : ID_COLLECTION_SMALL); write(len); write(id); switch (id) { case ID_CC_TREE_MAP: doWriteObject(((TreeMap)map).comparator(), false); break; case ID_CC_ENUM_MAP: writeClass(getEnumMapKeyType(obj)); break; } for (Map.Entry<?, ?> entry : map.entrySet()) { doWriteObject(entry.getKey(), false); doWriteObject(entry.getValue(), false); } } else if (len <= 65536) { write(unshared ? ID_COLLECTION_MEDIUM_UNSHARED : ID_COLLECTION_MEDIUM); writeShort(len); write(id); switch (id) { case ID_CC_TREE_MAP: doWriteObject(((TreeMap)map).comparator(), false); break; case ID_CC_ENUM_MAP: writeClass(getEnumMapKeyType(obj)); break; } for (Map.Entry<?, ?> entry : map.entrySet()) { doWriteObject(entry.getKey(), false); doWriteObject(entry.getValue(), false); } } else { write(unshared ? ID_COLLECTION_LARGE_UNSHARED : ID_COLLECTION_LARGE); writeInt(len); write(id); switch (id) { case ID_CC_TREE_MAP: doWriteObject(((TreeMap)map).comparator(), false); break; case ID_CC_ENUM_MAP: writeClass(getEnumMapKeyType(obj)); break; } for (Map.Entry<?, ?> entry : map.entrySet()) { doWriteObject(entry.getKey(), false); doWriteObject(entry.getValue(), false); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_EMPTY_MAP_OBJECT: case ID_EMPTY_SET_OBJECT: case ID_EMPTY_LIST_OBJECT: case ID_REVERSE_ORDER_OBJECT: { write(id); return; } case ID_SINGLETON_MAP_OBJECT: { instanceCache.put(obj, instanceSeq++); write(id); final Map.Entry entry = (Map.Entry) ((Map) obj).entrySet().iterator().next(); doWriteObject(entry.getKey(), false); doWriteObject(entry.getValue(), false); if (unshared) { instanceCache.put(obj, -1); } return; } case ID_SINGLETON_LIST_OBJECT: case ID_SINGLETON_SET_OBJECT: { instanceCache.put(obj, instanceSeq++); write(id); doWriteObject(((Collection)obj).iterator().next(), false); if (unshared) { instanceCache.put(obj, -1); } return; } case ID_REVERSE_ORDER2_OBJECT: { instanceCache.put(obj, instanceSeq++); write(id); try { doWriteObject(Protocol.reverseOrder2Field.get(obj), false); } catch (IllegalAccessException e) { throw new InvalidObjectException("Cannot access standard field for reverse-order comparator"); } return; } case ID_CC_CONCURRENT_HASH_MAP: case ID_CC_COPY_ON_WRITE_ARRAY_LIST: case ID_CC_COPY_ON_WRITE_ARRAY_SET: { info = registry.lookup(objClass); break; } case ID_PAIR: { instanceCache.put(obj, instanceSeq++); write(id); Pair<?, ?> pair = (Pair<?, ?>) obj; doWriteObject(pair.getA(), unshared); doWriteObject(pair.getB(), unshared); if (unshared) { instanceCache.put(obj, -1); } return; } case ID_CC_NCOPIES: { List<?> list = (List<?>) obj; int size = list.size(); if (size == 0) { write(ID_EMPTY_LIST_OBJECT); return; } instanceCache.put(obj, instanceSeq++); if (size <= 256) { write(unshared ? ID_COLLECTION_SMALL_UNSHARED : ID_COLLECTION_SMALL); write(size); } else if (size <= 65536) { write(unshared ? ID_COLLECTION_MEDIUM_UNSHARED : ID_COLLECTION_MEDIUM); writeShort(size); } else { write(unshared ? ID_COLLECTION_LARGE_UNSHARED : ID_COLLECTION_LARGE); writeInt(size); } write(id); doWriteObject(list.iterator().next(), false); if (unshared) { instanceCache.put(obj, -1); } return; } case -1: break; default: throw new NotSerializableException(objClass.getName()); } if (isArray) { instanceCache.put(obj, instanceSeq++); final Object[] objects = (Object[]) obj; final int len = objects.length; if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); writeClass(objClass.getComponentType()); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); writeClass(objClass.getComponentType()); for (int i = 0; i < len; i++) { doWriteObject(objects[i], unshared); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); writeClass(objClass.getComponentType()); for (int i = 0; i < len; i++) { doWriteObject(objects[i], unshared); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); writeClass(objClass.getComponentType()); for (int i = 0; i < len; i++) { doWriteObject(objects[i], unshared); } } if (unshared) { instanceCache.put(obj, -1); } return; } // serialize proxies efficiently if (Proxy.isProxyClass(objClass)) { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); instanceCache.put(obj, instanceSeq++); writeProxyClass(objClass); doWriteObject(Proxy.getInvocationHandler(obj), false); if (unshared) { instanceCache.put(obj, -1); } return; } // it's a user type // user type #1: externalizer Externalizer externalizer; if (externalizers.containsKey(objClass)) { externalizer = externalizers.get(objClass); } else { externalizer = classExternalizerFactory.getExternalizer(objClass); externalizers.put(objClass, externalizer); } if (externalizer != null) { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); writeExternalizerClass(objClass, externalizer); instanceCache.put(obj, instanceSeq++); final ObjectOutput objectOutput; objectOutput = getObjectOutput(); externalizer.writeExternal(obj, objectOutput); writeEndBlock(); if (unshared) { instanceCache.put(obj, -1); } return; } // user type #2: externalizable if (obj instanceof Externalizable) { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); - instanceCache.put(obj, instanceSeq++); final Externalizable ext = (Externalizable) obj; final ObjectOutput objectOutput = getObjectOutput(); writeExternalizableClass(objClass); + instanceCache.put(obj, instanceSeq++); ext.writeExternal(objectOutput); writeEndBlock(); if (unshared) { instanceCache.put(obj, -1); } return; } // user type #3: serializable if (serializabilityChecker.isSerializable(objClass)) { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); writeSerializableClass(objClass); instanceCache.put(obj, instanceSeq++); doWriteSerializableObject(info, obj, objClass); if (unshared) { instanceCache.put(obj, -1); } return; } throw new NotSerializableException(objClass.getName()); } finally { if (! unreplaced && obj != original) { final int replId = instanceCache.get(obj, -1); if (replId != -1) { instanceCache.put(original, replId); } } } } private static IdentityIntMap<Class<?>> getBasicClasses(final int configuredVersion) { return configuredVersion == 2 ? BASIC_CLASSES_V2 : BASIC_CLASSES_V3; } private static Class<? extends Enum> getEnumMapKeyType(final Object obj) { return getAccessibleEnumFieldValue(ENUM_MAP_KEY_TYPE_FIELD, obj); } private static Class<? extends Enum> getEnumSetElementType(final Object obj) { return getAccessibleEnumFieldValue(ENUM_SET_ELEMENT_TYPE_FIELD, obj); } private static Enum[] getEnumSetElements(final Object obj) { try { return (Enum[]) ENUM_SET_VALUES_FIELD.get(obj); } catch (IllegalAccessException e) { // should not happen throw new IllegalStateException("Unexpected state", e); } } private static Class<? extends Enum> getAccessibleEnumFieldValue(final Field field, final Object obj) { try { return ((Class<?>) field.get(obj)).asSubclass(Enum.class); } catch (IllegalAccessException e) { // should not happen throw new IllegalStateException("Unexpected state", e); } } private void writeBooleanArray(final boolean[] booleans) throws IOException { final int len = booleans.length; final int bc = len & ~7; for (int i = 0; i < bc;) { write( (booleans[i++] ? 1 : 0) | (booleans[i++] ? 2 : 0) | (booleans[i++] ? 4 : 0) | (booleans[i++] ? 8 : 0) | (booleans[i++] ? 16 : 0) | (booleans[i++] ? 32 : 0) | (booleans[i++] ? 64 : 0) | (booleans[i++] ? 128 : 0) ); } if (bc < len) { int out = 0; int bit = 1; for (int i = bc; i < len; i++) { if (booleans[i]) out |= bit; bit <<= 1; } write(out); } } private void writeEndBlock() throws IOException { final BlockMarshaller blockMarshaller = this.blockMarshaller; if (blockMarshaller != null) { blockMarshaller.flush(); writeByte(ID_END_BLOCK_DATA); } } protected ObjectOutput getObjectOutput() { final ObjectOutput output = objectOutput; return output == null ? (objectOutput = getBlockMarshaller()) : output; } protected BlockMarshaller getBlockMarshaller() { final BlockMarshaller blockMarshaller = this.blockMarshaller; return blockMarshaller == null ? (this.blockMarshaller = new BlockMarshaller(this, bufferSize)) : blockMarshaller; } private RiverObjectOutputStream getObjectOutputStream() throws IOException { final RiverObjectOutputStream objectOutputStream = this.objectOutputStream; return objectOutputStream == null ? this.objectOutputStream = createObjectOutputStream() : objectOutputStream; } private final PrivilegedExceptionAction<RiverObjectOutputStream> createObjectOutputStreamAction = new PrivilegedExceptionAction<RiverObjectOutputStream>() { public RiverObjectOutputStream run() throws IOException { return new RiverObjectOutputStream(getBlockMarshaller(), RiverMarshaller.this); } }; private RiverObjectOutputStream createObjectOutputStream() throws IOException { try { return AccessController.doPrivileged(createObjectOutputStreamAction); } catch (PrivilegedActionException e) { throw (IOException) e.getCause(); } } protected void doWriteSerializableObject(final SerializableClass info, final Object obj, final Class<?> objClass) throws IOException { final Class<?> superclass = objClass.getSuperclass(); if (serializabilityChecker.isSerializable(superclass)) { doWriteSerializableObject(registry.lookup(superclass), obj, superclass); } if (info.hasWriteObject()) { final RiverObjectOutputStream objectOutputStream = getObjectOutputStream(); final SerializableClass oldInfo = objectOutputStream.swapClass(info); final Object oldObj = objectOutputStream.swapCurrent(obj); final RiverObjectOutputStream.State restoreState = objectOutputStream.start(); boolean ok = false; try { info.callWriteObject(obj, objectOutputStream); writeEndBlock(); objectOutputStream.finish(restoreState); objectOutputStream.swapCurrent(oldObj); objectOutputStream.swapClass(oldInfo); ok = true; } finally { if (! ok) { objectOutputStream.fullReset(); } } } else { doWriteFields(info, obj); } } protected void doWriteFields(final SerializableClass info, final Object obj) throws IOException { final SerializableField[] serializableFields = info.getFields(); for (SerializableField serializableField : serializableFields) { try { try { final Field field = serializableField.getField(); switch (serializableField.getKind()) { case BOOLEAN: { writeBoolean(field.getBoolean(obj)); break; } case BYTE: { writeByte(field.getByte(obj)); break; } case SHORT: { writeShort(field.getShort(obj)); break; } case INT: { writeInt(field.getInt(obj)); break; } case CHAR: { writeChar(field.getChar(obj)); break; } case LONG: { writeLong(field.getLong(obj)); break; } case DOUBLE: { writeDouble(field.getDouble(obj)); break; } case FLOAT: { writeFloat(field.getFloat(obj)); break; } case OBJECT: { doWriteObject(field.get(obj), serializableField.isUnshared()); break; } } } catch (IllegalAccessException e) { final InvalidObjectException ioe = new InvalidObjectException("Unexpected illegal access exception"); ioe.initCause(e); throw ioe; } } catch (IOException e) { TraceInformation.addFieldInformation(e, serializableField.getName()); throw e; } catch (RuntimeException e) { TraceInformation.addFieldInformation(e, serializableField.getName()); throw e; } } } protected void writeProxyClass(final Class<?> objClass) throws IOException { if (! writeKnownClass(objClass)) { writeNewProxyClass(objClass); } } protected void writeNewProxyClass(final Class<?> objClass) throws IOException { ClassTable.Writer classTableWriter = classTable.getClassWriter(objClass); if (classTableWriter != null) { write(ID_PREDEFINED_PROXY_CLASS); classCache.put(objClass, classSeq++); writeClassTableData(objClass, classTableWriter); } else { write(ID_PROXY_CLASS); final String[] names = classResolver.getProxyInterfaces(objClass); writeInt(names.length); for (String name : names) { writeString(name); } classCache.put(objClass, classSeq++); if (configuredVersion == 1) { final BlockMarshaller blockMarshaller = getBlockMarshaller(); classResolver.annotateProxyClass(blockMarshaller, objClass); writeEndBlock(); } else { classResolver.annotateProxyClass(this, objClass); } } } protected void writeEnumClass(final Class<? extends Enum> objClass) throws IOException { if (! writeKnownClass(objClass)) { writeNewEnumClass(objClass); } } protected void writeNewEnumClass(final Class<? extends Enum> objClass) throws IOException { ClassTable.Writer classTableWriter = classTable.getClassWriter(objClass); if (classTableWriter != null) { write(ID_PREDEFINED_ENUM_TYPE_CLASS); classCache.put(objClass, classSeq++); writeClassTableData(objClass, classTableWriter); } else { write(ID_ENUM_TYPE_CLASS); writeString(classResolver.getClassName(objClass)); classCache.put(objClass, classSeq++); classResolver.annotateClass(this, objClass); } } protected void writeClassClass(final Class<?> classObj) throws IOException { write(ID_CLASS_CLASS); writeClass(classObj); // not cached } protected void writeObjectArrayClass(final Class<?> objClass) throws IOException { write(ID_OBJECT_ARRAY_TYPE_CLASS); writeClass(objClass.getComponentType()); classCache.put(objClass, classSeq++); } protected void writeClass(final Class<?> objClass) throws IOException { if (! writeKnownClass(objClass)) { writeNewClass(objClass); } } private static final IdentityIntMap<Class<?>> BASIC_CLASSES_V2; private static final IdentityIntMap<Class<?>> BASIC_CLASSES_V3; private static final Field ENUM_SET_ELEMENT_TYPE_FIELD; private static final Field ENUM_SET_VALUES_FIELD; private static final Field ENUM_MAP_KEY_TYPE_FIELD; static { final IdentityIntMap<Class<?>> map = new IdentityIntMap<Class<?>>(0x0.6p0f); map.put(byte.class, ID_PRIM_BYTE); map.put(boolean.class, ID_PRIM_BOOLEAN); map.put(char.class, ID_PRIM_CHAR); map.put(double.class, ID_PRIM_DOUBLE); map.put(float.class, ID_PRIM_FLOAT); map.put(int.class, ID_PRIM_INT); map.put(long.class, ID_PRIM_LONG); map.put(short.class, ID_PRIM_SHORT); map.put(void.class, ID_VOID); map.put(Byte.class, ID_BYTE_CLASS); map.put(Boolean.class, ID_BOOLEAN_CLASS); map.put(Character.class, ID_CHARACTER_CLASS); map.put(Double.class, ID_DOUBLE_CLASS); map.put(Float.class, ID_FLOAT_CLASS); map.put(Integer.class, ID_INTEGER_CLASS); map.put(Long.class, ID_LONG_CLASS); map.put(Short.class, ID_SHORT_CLASS); map.put(Void.class, ID_VOID_CLASS); map.put(Object.class, ID_OBJECT_CLASS); map.put(Class.class, ID_CLASS_CLASS); map.put(String.class, ID_STRING_CLASS); map.put(Enum.class, ID_ENUM_CLASS); map.put(byte[].class, ID_BYTE_ARRAY_CLASS); map.put(boolean[].class, ID_BOOLEAN_ARRAY_CLASS); map.put(char[].class, ID_CHAR_ARRAY_CLASS); map.put(double[].class, ID_DOUBLE_ARRAY_CLASS); map.put(float[].class, ID_FLOAT_ARRAY_CLASS); map.put(int[].class, ID_INT_ARRAY_CLASS); map.put(long[].class, ID_LONG_ARRAY_CLASS); map.put(short[].class, ID_SHORT_ARRAY_CLASS); map.put(ArrayList.class, ID_CC_ARRAY_LIST); map.put(LinkedList.class, ID_CC_LINKED_LIST); map.put(HashSet.class, ID_CC_HASH_SET); map.put(LinkedHashSet.class, ID_CC_LINKED_HASH_SET); map.put(TreeSet.class, ID_CC_TREE_SET); map.put(IdentityHashMap.class, ID_CC_IDENTITY_HASH_MAP); map.put(HashMap.class, ID_CC_HASH_MAP); map.put(Hashtable.class, ID_CC_HASHTABLE); map.put(LinkedHashMap.class, ID_CC_LINKED_HASH_MAP); map.put(TreeMap.class, ID_CC_TREE_MAP); map.put(AbstractCollection.class, ID_ABSTRACT_COLLECTION); map.put(AbstractList.class, ID_ABSTRACT_LIST); map.put(AbstractQueue.class, ID_ABSTRACT_QUEUE); map.put(AbstractSequentialList.class, ID_ABSTRACT_SEQUENTIAL_LIST); map.put(AbstractSet.class, ID_ABSTRACT_SET); map.put(ConcurrentHashMap.class, ID_CC_CONCURRENT_HASH_MAP); map.put(CopyOnWriteArrayList.class, ID_CC_COPY_ON_WRITE_ARRAY_LIST); map.put(CopyOnWriteArraySet.class, ID_CC_COPY_ON_WRITE_ARRAY_SET); map.put(Vector.class, ID_CC_VECTOR); map.put(Stack.class, ID_CC_STACK); map.put(emptyListClass, ID_EMPTY_LIST_OBJECT); // special case map.put(singletonListClass, ID_SINGLETON_LIST_OBJECT); // special case map.put(emptySetClass, ID_EMPTY_SET_OBJECT); // special case map.put(singletonSetClass, ID_SINGLETON_SET_OBJECT); // special case map.put(emptyMapClass, ID_EMPTY_MAP_OBJECT); // special case map.put(singletonMapClass, ID_SINGLETON_MAP_OBJECT); // special case map.put(EnumMap.class, ID_CC_ENUM_MAP); map.put(EnumSet.class, ID_CC_ENUM_SET); map.put(enumSetProxyClass, ID_CC_ENUM_SET_PROXY); // special case BASIC_CLASSES_V2 = map.clone(); map.put(Pair.class, ID_PAIR); map.put(ArrayDeque.class, ID_CC_ARRAY_DEQUE); map.put(reverseOrderClass, ID_REVERSE_ORDER_OBJECT); // special case map.put(reverseOrder2Class, ID_REVERSE_ORDER2_OBJECT); // special case map.put(nCopiesClass, ID_CC_NCOPIES); BASIC_CLASSES_V3 = map; // this solution will work for any JDK which conforms to the serialization spec of Enum; unless they // do something tricky involving ObjectStreamField anyway... ENUM_SET_VALUES_FIELD = AccessController.doPrivileged(new PrivilegedAction<Field>() { public Field run() { try { final Field field = enumSetProxyClass.getDeclaredField("elements"); field.setAccessible(true); return field; } catch (NoSuchFieldException e) { throw new RuntimeException("Cannot locate the elements field on EnumSet's serialization proxy!"); } } }); ENUM_SET_ELEMENT_TYPE_FIELD = AccessController.doPrivileged(new PrivilegedAction<Field>() { public Field run() { try { final Field field = enumSetProxyClass.getDeclaredField("elementType"); field.setAccessible(true); return field; } catch (NoSuchFieldException e) { throw new RuntimeException("Cannot locate the elementType field on EnumSet's serialization proxy!"); } } }); ENUM_MAP_KEY_TYPE_FIELD = AccessController.doPrivileged(new PrivilegedAction<Field>() { public Field run() { try { final Field field = EnumMap.class.getDeclaredField("keyType"); field.setAccessible(true); return field; } catch (NoSuchFieldException e) { throw new RuntimeException("Cannot locate the keyType field on EnumMap!"); } } }); } protected void writeNewClass(final Class<?> objClass) throws IOException { if (objClass.isEnum()) { writeNewEnumClass(objClass.asSubclass(Enum.class)); } else if (Proxy.isProxyClass(objClass)) { writeNewProxyClass(objClass); } else if (objClass.isArray()) { writeObjectArrayClass(objClass); } else if (! objClass.isInterface() && serializabilityChecker.isSerializable(objClass)) { if (Externalizable.class.isAssignableFrom(objClass)) { writeNewExternalizableClass(objClass); } else { writeNewSerializableClass(objClass); } } else { ClassTable.Writer classTableWriter = classTable.getClassWriter(objClass); if (classTableWriter != null) { write(ID_PREDEFINED_PLAIN_CLASS); classCache.put(objClass, classSeq++); writeClassTableData(objClass, classTableWriter); } else { write(ID_PLAIN_CLASS); writeString(classResolver.getClassName(objClass)); classResolver.annotateClass(this, objClass); classCache.put(objClass, classSeq++); } } } private void writeClassTableData(final Class<?> objClass, final ClassTable.Writer classTableWriter) throws IOException { if (configuredVersion == 1) { classTableWriter.writeClass(getBlockMarshaller(), objClass); writeEndBlock(); } else { classTableWriter.writeClass(this, objClass); } } protected boolean writeKnownClass(final Class<?> objClass) throws IOException { final int configuredVersion = this.configuredVersion; int i = getBasicClasses(configuredVersion).get(objClass, -1); if (i != -1) { write(i); return true; } i = classCache.get(objClass, -1); if (i != -1) { final int diff = i - classSeq; if (diff >= -256) { write(ID_REPEAT_CLASS_NEAR); write(diff); } else if (diff >= -65536) { write(ID_REPEAT_CLASS_NEARISH); writeShort(diff); } else { write(ID_REPEAT_CLASS_FAR); writeInt(i); } return true; } return false; } protected void writeSerializableClass(final Class<?> objClass) throws IOException { if (! writeKnownClass(objClass)) { writeNewSerializableClass(objClass); } } protected void writeNewSerializableClass(final Class<?> objClass) throws IOException { ClassTable.Writer classTableWriter = classTable.getClassWriter(objClass); if (classTableWriter != null) { write(ID_PREDEFINED_SERIALIZABLE_CLASS); classCache.put(objClass, classSeq++); writeClassTableData(objClass, classTableWriter); } else { final SerializableClass info = registry.lookup(objClass); if (info.hasWriteObject()) { write(ID_WRITE_OBJECT_CLASS); } else { write(ID_SERIALIZABLE_CLASS); } writeString(classResolver.getClassName(objClass)); writeLong(info.getEffectiveSerialVersionUID()); classCache.put(objClass, classSeq++); classResolver.annotateClass(this, objClass); final SerializableField[] fields = info.getFields(); final int cnt = fields.length; writeInt(cnt); for (int i = 0; i < cnt; i++) { SerializableField field = fields[i]; writeUTF(field.getName()); try { writeClass(field.getType()); } catch (ClassNotFoundException e) { throw new InvalidClassException("Class of field was unloaded"); } writeBoolean(field.isUnshared()); } } writeClass(objClass.getSuperclass()); } protected void writeExternalizableClass(final Class<?> objClass) throws IOException { if (! writeKnownClass(objClass)) { writeNewExternalizableClass(objClass); } } protected void writeNewExternalizableClass(final Class<?> objClass) throws IOException { ClassTable.Writer classTableWriter = classTable.getClassWriter(objClass); if (classTableWriter != null) { write(ID_PREDEFINED_EXTERNALIZABLE_CLASS); classCache.put(objClass, classSeq++); writeClassTableData(objClass, classTableWriter); } else { write(ID_EXTERNALIZABLE_CLASS); writeString(classResolver.getClassName(objClass)); writeLong(registry.lookup(objClass).getEffectiveSerialVersionUID()); classCache.put(objClass, classSeq++); classResolver.annotateClass(this, objClass); } } protected void writeExternalizerClass(final Class<?> objClass, final Externalizer externalizer) throws IOException { if (! writeKnownClass(objClass)) { writeNewExternalizerClass(objClass, externalizer); } } protected void writeNewExternalizerClass(final Class<?> objClass, final Externalizer externalizer) throws IOException { ClassTable.Writer classTableWriter = classTable.getClassWriter(objClass); if (classTableWriter != null) { write(ID_PREDEFINED_EXTERNALIZER_CLASS); classCache.put(objClass, classSeq++); writeClassTableData(objClass, classTableWriter); } else { write(ID_EXTERNALIZER_CLASS); writeString(classResolver.getClassName(objClass)); classCache.put(objClass, classSeq++); classResolver.annotateClass(this, objClass); } writeObject(externalizer); } public void clearInstanceCache() throws IOException { instanceCache.clear(); instanceSeq = 0; if (byteOutput != null) { write(ID_CLEAR_INSTANCE_CACHE); } } public void clearClassCache() throws IOException { classCache.clear(); externalizers.clear(); classSeq = 0; instanceCache.clear(); instanceSeq = 0; if (byteOutput != null) { write(ID_CLEAR_CLASS_CACHE); } } public void start(final ByteOutput byteOutput) throws IOException { super.start(byteOutput); writeByte(configuredVersion); } private void writeString(String string) throws IOException { writeInt(string.length()); shallowFlush(); UTFUtils.writeUTFBytes(byteOutput, string); } // Replace writeUTF with a faster, non-scanning version public void writeUTF(final String string) throws IOException { writeInt(string.length()); shallowFlush(); UTFUtils.writeUTFBytes(byteOutput, string); } }
false
true
protected void doWriteObject(final Object original, final boolean unshared) throws IOException { final ClassExternalizerFactory classExternalizerFactory = this.classExternalizerFactory; final ObjectResolver objectResolver = this.objectResolver; Object obj = original; Class<?> objClass; int id; boolean isArray, isEnum; SerializableClass info; boolean unreplaced = true; final int configuredVersion = this.configuredVersion; try { for (;;) { if (obj == null) { write(ID_NULL); return; } final int rid; if (! unshared && (rid = instanceCache.get(obj, -1)) != -1) { final int diff = rid - instanceSeq; if (diff >= -256) { write(ID_REPEAT_OBJECT_NEAR); write(diff); } else if (diff >= -65536) { write(ID_REPEAT_OBJECT_NEARISH); writeShort(diff); } else { write(ID_REPEAT_OBJECT_FAR); writeInt(rid); } return; } final ObjectTable.Writer objectTableWriter; if (! unshared && (objectTableWriter = objectTable.getObjectWriter(obj)) != null) { write(ID_PREDEFINED_OBJECT); if (configuredVersion == 1) { objectTableWriter.writeObject(getBlockMarshaller(), obj); writeEndBlock(); } else { objectTableWriter.writeObject(this, obj); } return; } objClass = obj.getClass(); id = getBasicClasses(configuredVersion).get(objClass, -1); // First, non-replaceable classes if (id == ID_CLASS_CLASS) { final Class<?> classObj = (Class<?>) obj; // If a class is one we have an entry for, we just write that byte directly. // These guys can't be written directly though, otherwise they'll get confused with the objects // of the corresponding type. final int cid = BASIC_CLASSES_V2.get(classObj, -1); switch (cid) { case -1: case ID_SINGLETON_MAP_OBJECT: case ID_SINGLETON_SET_OBJECT: case ID_SINGLETON_LIST_OBJECT: case ID_EMPTY_MAP_OBJECT: case ID_EMPTY_SET_OBJECT: case ID_EMPTY_LIST_OBJECT: { // If the class is one of the above special object types, then we write a // full NEW_OBJECT+CLASS_CLASS header followed by the class byte, or if there is none, write // the full class descriptor. write(ID_NEW_OBJECT); writeClassClass(classObj); return; } default: { write(cid); return; } } // not reached } isEnum = obj instanceof Enum; isArray = objClass.isArray(); // objects with id != -1 will never make use of the "info" param in *any* way info = isArray || isEnum || id != -1 ? null : registry.lookup(objClass); // replace once - objects with id != -1 will not have replacement methods but might be globally replaced if (unreplaced) { if (info != null) { // check for a user replacement if (info.hasWriteReplace()) { obj = info.callWriteReplace(obj); } } // Check for a global replacement obj = objectResolver.writeReplace(obj); if (obj != original) { unreplaced = false; continue; } else { break; } } else { break; } } if (isEnum) { // objClass cannot equal Enum.class because it is abstract final Enum<?> theEnum = (Enum<?>) obj; // enums are always shared write(ID_NEW_OBJECT); writeEnumClass(theEnum.getDeclaringClass()); writeString(theEnum.name()); instanceCache.put(obj, instanceSeq++); return; } // Now replaceable classes switch (id) { case ID_BYTE_CLASS: { write(ID_BYTE_OBJECT); writeByte(((Byte) obj).byteValue()); return; } case ID_BOOLEAN_CLASS: { write(((Boolean) obj).booleanValue() ? ID_BOOLEAN_OBJECT_TRUE : ID_BOOLEAN_OBJECT_FALSE); return; } case ID_CHARACTER_CLASS: { write(ID_CHARACTER_OBJECT); writeChar(((Character) obj).charValue()); return; } case ID_DOUBLE_CLASS: { write(ID_DOUBLE_OBJECT); writeDouble(((Double) obj).doubleValue()); return; } case ID_FLOAT_CLASS: { write(ID_FLOAT_OBJECT); writeFloat(((Float) obj).floatValue()); return; } case ID_INTEGER_CLASS: { write(ID_INTEGER_OBJECT); writeInt(((Integer) obj).intValue()); return; } case ID_LONG_CLASS: { write(ID_LONG_OBJECT); writeLong(((Long) obj).longValue()); return; } case ID_SHORT_CLASS: { write(ID_SHORT_OBJECT); writeShort(((Short) obj).shortValue()); return; } case ID_STRING_CLASS: { final String string = (String) obj; final int len = string.length(); if (len == 0) { write(ID_STRING_EMPTY); // don't cache empty strings return; } else if (len <= 0x100) { write(ID_STRING_SMALL); write(len); } else if (len <= 0x10000) { write(ID_STRING_MEDIUM); writeShort(len); } else { write(ID_STRING_LARGE); writeInt(len); } shallowFlush(); UTFUtils.writeUTFBytes(byteOutput, string); if (unshared) { instanceCache.put(obj, -1); instanceSeq++; } else { instanceCache.put(obj, instanceSeq++); } return; } case ID_BYTE_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final byte[] bytes = (byte[]) obj; final int len = bytes.length; if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_BYTE); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_BYTE); write(bytes, 0, len); } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_BYTE); write(bytes, 0, len); } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_BYTE); write(bytes, 0, len); } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_BOOLEAN_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final boolean[] booleans = (boolean[]) obj; final int len = booleans.length; if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_BOOLEAN); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_BOOLEAN); writeBooleanArray(booleans); } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_BOOLEAN); writeBooleanArray(booleans); } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_BOOLEAN); writeBooleanArray(booleans); } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_CHAR_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final char[] chars = (char[]) obj; final int len = chars.length; if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_CHAR); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_CHAR); for (int i = 0; i < len; i ++) { writeChar(chars[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_CHAR); for (int i = 0; i < len; i ++) { writeChar(chars[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_CHAR); for (int i = 0; i < len; i ++) { writeChar(chars[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_SHORT_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final short[] shorts = (short[]) obj; final int len = shorts.length; if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_SHORT); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_SHORT); for (int i = 0; i < len; i ++) { writeShort(shorts[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_SHORT); for (int i = 0; i < len; i ++) { writeShort(shorts[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_SHORT); for (int i = 0; i < len; i ++) { writeShort(shorts[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_INT_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final int[] ints = (int[]) obj; final int len = ints.length; if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_INT); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_INT); for (int i = 0; i < len; i ++) { writeInt(ints[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_INT); for (int i = 0; i < len; i ++) { writeInt(ints[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_INT); for (int i = 0; i < len; i ++) { writeInt(ints[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_LONG_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final long[] longs = (long[]) obj; final int len = longs.length; if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_LONG); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_LONG); for (int i = 0; i < len; i ++) { writeLong(longs[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_LONG); for (int i = 0; i < len; i ++) { writeLong(longs[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_LONG); for (int i = 0; i < len; i ++) { writeLong(longs[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_FLOAT_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final float[] floats = (float[]) obj; final int len = floats.length; if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_FLOAT); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_FLOAT); for (int i = 0; i < len; i ++) { writeFloat(floats[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_FLOAT); for (int i = 0; i < len; i ++) { writeFloat(floats[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_FLOAT); for (int i = 0; i < len; i ++) { writeFloat(floats[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_DOUBLE_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final double[] doubles = (double[]) obj; final int len = doubles.length; if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_DOUBLE); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_DOUBLE); for (int i = 0; i < len; i ++) { writeDouble(doubles[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_DOUBLE); for (int i = 0; i < len; i ++) { writeDouble(doubles[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_DOUBLE); for (int i = 0; i < len; i ++) { writeDouble(doubles[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_CC_HASH_SET: case ID_CC_LINKED_HASH_SET: case ID_CC_TREE_SET: case ID_CC_ARRAY_LIST: case ID_CC_LINKED_LIST: case ID_CC_VECTOR: case ID_CC_STACK: case ID_CC_ARRAY_DEQUE: { instanceCache.put(obj, instanceSeq++); final Collection<?> collection = (Collection<?>) obj; final int len = collection.size(); if (len == 0) { write(unshared ? ID_COLLECTION_EMPTY_UNSHARED : ID_COLLECTION_EMPTY); write(id); if (id == ID_CC_TREE_SET) { doWriteObject(((TreeSet)collection).comparator(), false); } } else if (len <= 256) { write(unshared ? ID_COLLECTION_SMALL_UNSHARED : ID_COLLECTION_SMALL); write(len); write(id); if (id == ID_CC_TREE_SET) { doWriteObject(((TreeSet)collection).comparator(), false); } for (Object o : collection) { doWriteObject(o, false); } } else if (len <= 65536) { write(unshared ? ID_COLLECTION_MEDIUM_UNSHARED : ID_COLLECTION_MEDIUM); writeShort(len); write(id); if (id == ID_CC_TREE_SET) { doWriteObject(((TreeSet)collection).comparator(), false); } for (Object o : collection) { doWriteObject(o, false); } } else { write(unshared ? ID_COLLECTION_LARGE_UNSHARED : ID_COLLECTION_LARGE); writeInt(len); write(id); if (id == ID_CC_TREE_SET) { doWriteObject(((TreeSet)collection).comparator(), false); } for (Object o : collection) { doWriteObject(o, false); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_CC_ENUM_SET_PROXY: { instanceCache.put(obj, instanceSeq++); final Enum[] elements = getEnumSetElements(obj); final int len = elements.length; if (len == 0) { write(unshared ? ID_COLLECTION_EMPTY_UNSHARED : ID_COLLECTION_EMPTY); write(id); writeClass(getEnumSetElementType(obj)); } else if (len <= 256) { write(unshared ? ID_COLLECTION_SMALL_UNSHARED : ID_COLLECTION_SMALL); write(len); write(id); writeClass(getEnumSetElementType(obj)); for (Object o : elements) { doWriteObject(o, false); } } else if (len <= 65536) { write(unshared ? ID_COLLECTION_MEDIUM_UNSHARED : ID_COLLECTION_MEDIUM); writeShort(len); write(id); writeClass(getEnumSetElementType(obj)); for (Object o : elements) { doWriteObject(o, false); } } else { write(unshared ? ID_COLLECTION_LARGE_UNSHARED : ID_COLLECTION_LARGE); writeInt(len); write(id); writeClass(getEnumSetElementType(obj)); for (Object o : elements) { doWriteObject(o, false); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_CC_HASH_MAP: case ID_CC_HASHTABLE: case ID_CC_IDENTITY_HASH_MAP: case ID_CC_LINKED_HASH_MAP: case ID_CC_TREE_MAP: case ID_CC_ENUM_MAP: { instanceCache.put(obj, instanceSeq++); final Map<?, ?> map = (Map<?, ?>) obj; final int len = map.size(); if (len == 0) { write(unshared ? ID_COLLECTION_EMPTY_UNSHARED : ID_COLLECTION_EMPTY); write(id); switch (id) { case ID_CC_TREE_MAP: doWriteObject(((TreeMap)map).comparator(), false); break; case ID_CC_ENUM_MAP: writeClass(getEnumMapKeyType(obj)); break; } } else if (len <= 256) { write(unshared ? ID_COLLECTION_SMALL_UNSHARED : ID_COLLECTION_SMALL); write(len); write(id); switch (id) { case ID_CC_TREE_MAP: doWriteObject(((TreeMap)map).comparator(), false); break; case ID_CC_ENUM_MAP: writeClass(getEnumMapKeyType(obj)); break; } for (Map.Entry<?, ?> entry : map.entrySet()) { doWriteObject(entry.getKey(), false); doWriteObject(entry.getValue(), false); } } else if (len <= 65536) { write(unshared ? ID_COLLECTION_MEDIUM_UNSHARED : ID_COLLECTION_MEDIUM); writeShort(len); write(id); switch (id) { case ID_CC_TREE_MAP: doWriteObject(((TreeMap)map).comparator(), false); break; case ID_CC_ENUM_MAP: writeClass(getEnumMapKeyType(obj)); break; } for (Map.Entry<?, ?> entry : map.entrySet()) { doWriteObject(entry.getKey(), false); doWriteObject(entry.getValue(), false); } } else { write(unshared ? ID_COLLECTION_LARGE_UNSHARED : ID_COLLECTION_LARGE); writeInt(len); write(id); switch (id) { case ID_CC_TREE_MAP: doWriteObject(((TreeMap)map).comparator(), false); break; case ID_CC_ENUM_MAP: writeClass(getEnumMapKeyType(obj)); break; } for (Map.Entry<?, ?> entry : map.entrySet()) { doWriteObject(entry.getKey(), false); doWriteObject(entry.getValue(), false); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_EMPTY_MAP_OBJECT: case ID_EMPTY_SET_OBJECT: case ID_EMPTY_LIST_OBJECT: case ID_REVERSE_ORDER_OBJECT: { write(id); return; } case ID_SINGLETON_MAP_OBJECT: { instanceCache.put(obj, instanceSeq++); write(id); final Map.Entry entry = (Map.Entry) ((Map) obj).entrySet().iterator().next(); doWriteObject(entry.getKey(), false); doWriteObject(entry.getValue(), false); if (unshared) { instanceCache.put(obj, -1); } return; } case ID_SINGLETON_LIST_OBJECT: case ID_SINGLETON_SET_OBJECT: { instanceCache.put(obj, instanceSeq++); write(id); doWriteObject(((Collection)obj).iterator().next(), false); if (unshared) { instanceCache.put(obj, -1); } return; } case ID_REVERSE_ORDER2_OBJECT: { instanceCache.put(obj, instanceSeq++); write(id); try { doWriteObject(Protocol.reverseOrder2Field.get(obj), false); } catch (IllegalAccessException e) { throw new InvalidObjectException("Cannot access standard field for reverse-order comparator"); } return; } case ID_CC_CONCURRENT_HASH_MAP: case ID_CC_COPY_ON_WRITE_ARRAY_LIST: case ID_CC_COPY_ON_WRITE_ARRAY_SET: { info = registry.lookup(objClass); break; } case ID_PAIR: { instanceCache.put(obj, instanceSeq++); write(id); Pair<?, ?> pair = (Pair<?, ?>) obj; doWriteObject(pair.getA(), unshared); doWriteObject(pair.getB(), unshared); if (unshared) { instanceCache.put(obj, -1); } return; } case ID_CC_NCOPIES: { List<?> list = (List<?>) obj; int size = list.size(); if (size == 0) { write(ID_EMPTY_LIST_OBJECT); return; } instanceCache.put(obj, instanceSeq++); if (size <= 256) { write(unshared ? ID_COLLECTION_SMALL_UNSHARED : ID_COLLECTION_SMALL); write(size); } else if (size <= 65536) { write(unshared ? ID_COLLECTION_MEDIUM_UNSHARED : ID_COLLECTION_MEDIUM); writeShort(size); } else { write(unshared ? ID_COLLECTION_LARGE_UNSHARED : ID_COLLECTION_LARGE); writeInt(size); } write(id); doWriteObject(list.iterator().next(), false); if (unshared) { instanceCache.put(obj, -1); } return; } case -1: break; default: throw new NotSerializableException(objClass.getName()); } if (isArray) { instanceCache.put(obj, instanceSeq++); final Object[] objects = (Object[]) obj; final int len = objects.length; if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); writeClass(objClass.getComponentType()); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); writeClass(objClass.getComponentType()); for (int i = 0; i < len; i++) { doWriteObject(objects[i], unshared); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); writeClass(objClass.getComponentType()); for (int i = 0; i < len; i++) { doWriteObject(objects[i], unshared); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); writeClass(objClass.getComponentType()); for (int i = 0; i < len; i++) { doWriteObject(objects[i], unshared); } } if (unshared) { instanceCache.put(obj, -1); } return; } // serialize proxies efficiently if (Proxy.isProxyClass(objClass)) { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); instanceCache.put(obj, instanceSeq++); writeProxyClass(objClass); doWriteObject(Proxy.getInvocationHandler(obj), false); if (unshared) { instanceCache.put(obj, -1); } return; } // it's a user type // user type #1: externalizer Externalizer externalizer; if (externalizers.containsKey(objClass)) { externalizer = externalizers.get(objClass); } else { externalizer = classExternalizerFactory.getExternalizer(objClass); externalizers.put(objClass, externalizer); } if (externalizer != null) { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); writeExternalizerClass(objClass, externalizer); instanceCache.put(obj, instanceSeq++); final ObjectOutput objectOutput; objectOutput = getObjectOutput(); externalizer.writeExternal(obj, objectOutput); writeEndBlock(); if (unshared) { instanceCache.put(obj, -1); } return; } // user type #2: externalizable if (obj instanceof Externalizable) { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); instanceCache.put(obj, instanceSeq++); final Externalizable ext = (Externalizable) obj; final ObjectOutput objectOutput = getObjectOutput(); writeExternalizableClass(objClass); ext.writeExternal(objectOutput); writeEndBlock(); if (unshared) { instanceCache.put(obj, -1); } return; } // user type #3: serializable if (serializabilityChecker.isSerializable(objClass)) { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); writeSerializableClass(objClass); instanceCache.put(obj, instanceSeq++); doWriteSerializableObject(info, obj, objClass); if (unshared) { instanceCache.put(obj, -1); } return; } throw new NotSerializableException(objClass.getName()); } finally { if (! unreplaced && obj != original) { final int replId = instanceCache.get(obj, -1); if (replId != -1) { instanceCache.put(original, replId); } } } }
protected void doWriteObject(final Object original, final boolean unshared) throws IOException { final ClassExternalizerFactory classExternalizerFactory = this.classExternalizerFactory; final ObjectResolver objectResolver = this.objectResolver; Object obj = original; Class<?> objClass; int id; boolean isArray, isEnum; SerializableClass info; boolean unreplaced = true; final int configuredVersion = this.configuredVersion; try { for (;;) { if (obj == null) { write(ID_NULL); return; } final int rid; if (! unshared && (rid = instanceCache.get(obj, -1)) != -1) { final int diff = rid - instanceSeq; if (diff >= -256) { write(ID_REPEAT_OBJECT_NEAR); write(diff); } else if (diff >= -65536) { write(ID_REPEAT_OBJECT_NEARISH); writeShort(diff); } else { write(ID_REPEAT_OBJECT_FAR); writeInt(rid); } return; } final ObjectTable.Writer objectTableWriter; if (! unshared && (objectTableWriter = objectTable.getObjectWriter(obj)) != null) { write(ID_PREDEFINED_OBJECT); if (configuredVersion == 1) { objectTableWriter.writeObject(getBlockMarshaller(), obj); writeEndBlock(); } else { objectTableWriter.writeObject(this, obj); } return; } objClass = obj.getClass(); id = getBasicClasses(configuredVersion).get(objClass, -1); // First, non-replaceable classes if (id == ID_CLASS_CLASS) { final Class<?> classObj = (Class<?>) obj; // If a class is one we have an entry for, we just write that byte directly. // These guys can't be written directly though, otherwise they'll get confused with the objects // of the corresponding type. final int cid = BASIC_CLASSES_V2.get(classObj, -1); switch (cid) { case -1: case ID_SINGLETON_MAP_OBJECT: case ID_SINGLETON_SET_OBJECT: case ID_SINGLETON_LIST_OBJECT: case ID_EMPTY_MAP_OBJECT: case ID_EMPTY_SET_OBJECT: case ID_EMPTY_LIST_OBJECT: { // If the class is one of the above special object types, then we write a // full NEW_OBJECT+CLASS_CLASS header followed by the class byte, or if there is none, write // the full class descriptor. write(ID_NEW_OBJECT); writeClassClass(classObj); return; } default: { write(cid); return; } } // not reached } isEnum = obj instanceof Enum; isArray = objClass.isArray(); // objects with id != -1 will never make use of the "info" param in *any* way info = isArray || isEnum || id != -1 ? null : registry.lookup(objClass); // replace once - objects with id != -1 will not have replacement methods but might be globally replaced if (unreplaced) { if (info != null) { // check for a user replacement if (info.hasWriteReplace()) { obj = info.callWriteReplace(obj); } } // Check for a global replacement obj = objectResolver.writeReplace(obj); if (obj != original) { unreplaced = false; continue; } else { break; } } else { break; } } if (isEnum) { // objClass cannot equal Enum.class because it is abstract final Enum<?> theEnum = (Enum<?>) obj; // enums are always shared write(ID_NEW_OBJECT); writeEnumClass(theEnum.getDeclaringClass()); writeString(theEnum.name()); instanceCache.put(obj, instanceSeq++); return; } // Now replaceable classes switch (id) { case ID_BYTE_CLASS: { write(ID_BYTE_OBJECT); writeByte(((Byte) obj).byteValue()); return; } case ID_BOOLEAN_CLASS: { write(((Boolean) obj).booleanValue() ? ID_BOOLEAN_OBJECT_TRUE : ID_BOOLEAN_OBJECT_FALSE); return; } case ID_CHARACTER_CLASS: { write(ID_CHARACTER_OBJECT); writeChar(((Character) obj).charValue()); return; } case ID_DOUBLE_CLASS: { write(ID_DOUBLE_OBJECT); writeDouble(((Double) obj).doubleValue()); return; } case ID_FLOAT_CLASS: { write(ID_FLOAT_OBJECT); writeFloat(((Float) obj).floatValue()); return; } case ID_INTEGER_CLASS: { write(ID_INTEGER_OBJECT); writeInt(((Integer) obj).intValue()); return; } case ID_LONG_CLASS: { write(ID_LONG_OBJECT); writeLong(((Long) obj).longValue()); return; } case ID_SHORT_CLASS: { write(ID_SHORT_OBJECT); writeShort(((Short) obj).shortValue()); return; } case ID_STRING_CLASS: { final String string = (String) obj; final int len = string.length(); if (len == 0) { write(ID_STRING_EMPTY); // don't cache empty strings return; } else if (len <= 0x100) { write(ID_STRING_SMALL); write(len); } else if (len <= 0x10000) { write(ID_STRING_MEDIUM); writeShort(len); } else { write(ID_STRING_LARGE); writeInt(len); } shallowFlush(); UTFUtils.writeUTFBytes(byteOutput, string); if (unshared) { instanceCache.put(obj, -1); instanceSeq++; } else { instanceCache.put(obj, instanceSeq++); } return; } case ID_BYTE_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final byte[] bytes = (byte[]) obj; final int len = bytes.length; if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_BYTE); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_BYTE); write(bytes, 0, len); } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_BYTE); write(bytes, 0, len); } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_BYTE); write(bytes, 0, len); } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_BOOLEAN_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final boolean[] booleans = (boolean[]) obj; final int len = booleans.length; if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_BOOLEAN); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_BOOLEAN); writeBooleanArray(booleans); } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_BOOLEAN); writeBooleanArray(booleans); } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_BOOLEAN); writeBooleanArray(booleans); } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_CHAR_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final char[] chars = (char[]) obj; final int len = chars.length; if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_CHAR); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_CHAR); for (int i = 0; i < len; i ++) { writeChar(chars[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_CHAR); for (int i = 0; i < len; i ++) { writeChar(chars[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_CHAR); for (int i = 0; i < len; i ++) { writeChar(chars[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_SHORT_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final short[] shorts = (short[]) obj; final int len = shorts.length; if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_SHORT); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_SHORT); for (int i = 0; i < len; i ++) { writeShort(shorts[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_SHORT); for (int i = 0; i < len; i ++) { writeShort(shorts[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_SHORT); for (int i = 0; i < len; i ++) { writeShort(shorts[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_INT_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final int[] ints = (int[]) obj; final int len = ints.length; if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_INT); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_INT); for (int i = 0; i < len; i ++) { writeInt(ints[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_INT); for (int i = 0; i < len; i ++) { writeInt(ints[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_INT); for (int i = 0; i < len; i ++) { writeInt(ints[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_LONG_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final long[] longs = (long[]) obj; final int len = longs.length; if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_LONG); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_LONG); for (int i = 0; i < len; i ++) { writeLong(longs[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_LONG); for (int i = 0; i < len; i ++) { writeLong(longs[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_LONG); for (int i = 0; i < len; i ++) { writeLong(longs[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_FLOAT_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final float[] floats = (float[]) obj; final int len = floats.length; if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_FLOAT); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_FLOAT); for (int i = 0; i < len; i ++) { writeFloat(floats[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_FLOAT); for (int i = 0; i < len; i ++) { writeFloat(floats[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_FLOAT); for (int i = 0; i < len; i ++) { writeFloat(floats[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_DOUBLE_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final double[] doubles = (double[]) obj; final int len = doubles.length; if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_DOUBLE); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_DOUBLE); for (int i = 0; i < len; i ++) { writeDouble(doubles[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_DOUBLE); for (int i = 0; i < len; i ++) { writeDouble(doubles[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_DOUBLE); for (int i = 0; i < len; i ++) { writeDouble(doubles[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_CC_HASH_SET: case ID_CC_LINKED_HASH_SET: case ID_CC_TREE_SET: case ID_CC_ARRAY_LIST: case ID_CC_LINKED_LIST: case ID_CC_VECTOR: case ID_CC_STACK: case ID_CC_ARRAY_DEQUE: { instanceCache.put(obj, instanceSeq++); final Collection<?> collection = (Collection<?>) obj; final int len = collection.size(); if (len == 0) { write(unshared ? ID_COLLECTION_EMPTY_UNSHARED : ID_COLLECTION_EMPTY); write(id); if (id == ID_CC_TREE_SET) { doWriteObject(((TreeSet)collection).comparator(), false); } } else if (len <= 256) { write(unshared ? ID_COLLECTION_SMALL_UNSHARED : ID_COLLECTION_SMALL); write(len); write(id); if (id == ID_CC_TREE_SET) { doWriteObject(((TreeSet)collection).comparator(), false); } for (Object o : collection) { doWriteObject(o, false); } } else if (len <= 65536) { write(unshared ? ID_COLLECTION_MEDIUM_UNSHARED : ID_COLLECTION_MEDIUM); writeShort(len); write(id); if (id == ID_CC_TREE_SET) { doWriteObject(((TreeSet)collection).comparator(), false); } for (Object o : collection) { doWriteObject(o, false); } } else { write(unshared ? ID_COLLECTION_LARGE_UNSHARED : ID_COLLECTION_LARGE); writeInt(len); write(id); if (id == ID_CC_TREE_SET) { doWriteObject(((TreeSet)collection).comparator(), false); } for (Object o : collection) { doWriteObject(o, false); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_CC_ENUM_SET_PROXY: { instanceCache.put(obj, instanceSeq++); final Enum[] elements = getEnumSetElements(obj); final int len = elements.length; if (len == 0) { write(unshared ? ID_COLLECTION_EMPTY_UNSHARED : ID_COLLECTION_EMPTY); write(id); writeClass(getEnumSetElementType(obj)); } else if (len <= 256) { write(unshared ? ID_COLLECTION_SMALL_UNSHARED : ID_COLLECTION_SMALL); write(len); write(id); writeClass(getEnumSetElementType(obj)); for (Object o : elements) { doWriteObject(o, false); } } else if (len <= 65536) { write(unshared ? ID_COLLECTION_MEDIUM_UNSHARED : ID_COLLECTION_MEDIUM); writeShort(len); write(id); writeClass(getEnumSetElementType(obj)); for (Object o : elements) { doWriteObject(o, false); } } else { write(unshared ? ID_COLLECTION_LARGE_UNSHARED : ID_COLLECTION_LARGE); writeInt(len); write(id); writeClass(getEnumSetElementType(obj)); for (Object o : elements) { doWriteObject(o, false); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_CC_HASH_MAP: case ID_CC_HASHTABLE: case ID_CC_IDENTITY_HASH_MAP: case ID_CC_LINKED_HASH_MAP: case ID_CC_TREE_MAP: case ID_CC_ENUM_MAP: { instanceCache.put(obj, instanceSeq++); final Map<?, ?> map = (Map<?, ?>) obj; final int len = map.size(); if (len == 0) { write(unshared ? ID_COLLECTION_EMPTY_UNSHARED : ID_COLLECTION_EMPTY); write(id); switch (id) { case ID_CC_TREE_MAP: doWriteObject(((TreeMap)map).comparator(), false); break; case ID_CC_ENUM_MAP: writeClass(getEnumMapKeyType(obj)); break; } } else if (len <= 256) { write(unshared ? ID_COLLECTION_SMALL_UNSHARED : ID_COLLECTION_SMALL); write(len); write(id); switch (id) { case ID_CC_TREE_MAP: doWriteObject(((TreeMap)map).comparator(), false); break; case ID_CC_ENUM_MAP: writeClass(getEnumMapKeyType(obj)); break; } for (Map.Entry<?, ?> entry : map.entrySet()) { doWriteObject(entry.getKey(), false); doWriteObject(entry.getValue(), false); } } else if (len <= 65536) { write(unshared ? ID_COLLECTION_MEDIUM_UNSHARED : ID_COLLECTION_MEDIUM); writeShort(len); write(id); switch (id) { case ID_CC_TREE_MAP: doWriteObject(((TreeMap)map).comparator(), false); break; case ID_CC_ENUM_MAP: writeClass(getEnumMapKeyType(obj)); break; } for (Map.Entry<?, ?> entry : map.entrySet()) { doWriteObject(entry.getKey(), false); doWriteObject(entry.getValue(), false); } } else { write(unshared ? ID_COLLECTION_LARGE_UNSHARED : ID_COLLECTION_LARGE); writeInt(len); write(id); switch (id) { case ID_CC_TREE_MAP: doWriteObject(((TreeMap)map).comparator(), false); break; case ID_CC_ENUM_MAP: writeClass(getEnumMapKeyType(obj)); break; } for (Map.Entry<?, ?> entry : map.entrySet()) { doWriteObject(entry.getKey(), false); doWriteObject(entry.getValue(), false); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_EMPTY_MAP_OBJECT: case ID_EMPTY_SET_OBJECT: case ID_EMPTY_LIST_OBJECT: case ID_REVERSE_ORDER_OBJECT: { write(id); return; } case ID_SINGLETON_MAP_OBJECT: { instanceCache.put(obj, instanceSeq++); write(id); final Map.Entry entry = (Map.Entry) ((Map) obj).entrySet().iterator().next(); doWriteObject(entry.getKey(), false); doWriteObject(entry.getValue(), false); if (unshared) { instanceCache.put(obj, -1); } return; } case ID_SINGLETON_LIST_OBJECT: case ID_SINGLETON_SET_OBJECT: { instanceCache.put(obj, instanceSeq++); write(id); doWriteObject(((Collection)obj).iterator().next(), false); if (unshared) { instanceCache.put(obj, -1); } return; } case ID_REVERSE_ORDER2_OBJECT: { instanceCache.put(obj, instanceSeq++); write(id); try { doWriteObject(Protocol.reverseOrder2Field.get(obj), false); } catch (IllegalAccessException e) { throw new InvalidObjectException("Cannot access standard field for reverse-order comparator"); } return; } case ID_CC_CONCURRENT_HASH_MAP: case ID_CC_COPY_ON_WRITE_ARRAY_LIST: case ID_CC_COPY_ON_WRITE_ARRAY_SET: { info = registry.lookup(objClass); break; } case ID_PAIR: { instanceCache.put(obj, instanceSeq++); write(id); Pair<?, ?> pair = (Pair<?, ?>) obj; doWriteObject(pair.getA(), unshared); doWriteObject(pair.getB(), unshared); if (unshared) { instanceCache.put(obj, -1); } return; } case ID_CC_NCOPIES: { List<?> list = (List<?>) obj; int size = list.size(); if (size == 0) { write(ID_EMPTY_LIST_OBJECT); return; } instanceCache.put(obj, instanceSeq++); if (size <= 256) { write(unshared ? ID_COLLECTION_SMALL_UNSHARED : ID_COLLECTION_SMALL); write(size); } else if (size <= 65536) { write(unshared ? ID_COLLECTION_MEDIUM_UNSHARED : ID_COLLECTION_MEDIUM); writeShort(size); } else { write(unshared ? ID_COLLECTION_LARGE_UNSHARED : ID_COLLECTION_LARGE); writeInt(size); } write(id); doWriteObject(list.iterator().next(), false); if (unshared) { instanceCache.put(obj, -1); } return; } case -1: break; default: throw new NotSerializableException(objClass.getName()); } if (isArray) { instanceCache.put(obj, instanceSeq++); final Object[] objects = (Object[]) obj; final int len = objects.length; if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); writeClass(objClass.getComponentType()); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); writeClass(objClass.getComponentType()); for (int i = 0; i < len; i++) { doWriteObject(objects[i], unshared); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); writeClass(objClass.getComponentType()); for (int i = 0; i < len; i++) { doWriteObject(objects[i], unshared); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); writeClass(objClass.getComponentType()); for (int i = 0; i < len; i++) { doWriteObject(objects[i], unshared); } } if (unshared) { instanceCache.put(obj, -1); } return; } // serialize proxies efficiently if (Proxy.isProxyClass(objClass)) { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); instanceCache.put(obj, instanceSeq++); writeProxyClass(objClass); doWriteObject(Proxy.getInvocationHandler(obj), false); if (unshared) { instanceCache.put(obj, -1); } return; } // it's a user type // user type #1: externalizer Externalizer externalizer; if (externalizers.containsKey(objClass)) { externalizer = externalizers.get(objClass); } else { externalizer = classExternalizerFactory.getExternalizer(objClass); externalizers.put(objClass, externalizer); } if (externalizer != null) { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); writeExternalizerClass(objClass, externalizer); instanceCache.put(obj, instanceSeq++); final ObjectOutput objectOutput; objectOutput = getObjectOutput(); externalizer.writeExternal(obj, objectOutput); writeEndBlock(); if (unshared) { instanceCache.put(obj, -1); } return; } // user type #2: externalizable if (obj instanceof Externalizable) { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); final Externalizable ext = (Externalizable) obj; final ObjectOutput objectOutput = getObjectOutput(); writeExternalizableClass(objClass); instanceCache.put(obj, instanceSeq++); ext.writeExternal(objectOutput); writeEndBlock(); if (unshared) { instanceCache.put(obj, -1); } return; } // user type #3: serializable if (serializabilityChecker.isSerializable(objClass)) { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); writeSerializableClass(objClass); instanceCache.put(obj, instanceSeq++); doWriteSerializableObject(info, obj, objClass); if (unshared) { instanceCache.put(obj, -1); } return; } throw new NotSerializableException(objClass.getName()); } finally { if (! unreplaced && obj != original) { final int replId = instanceCache.get(obj, -1); if (replId != -1) { instanceCache.put(original, replId); } } } }
diff --git a/src/main/java/ch/entwine/weblounge/contentrepository/impl/endpoint/PreviewsEndpoint.java b/src/main/java/ch/entwine/weblounge/contentrepository/impl/endpoint/PreviewsEndpoint.java index 9be743876..2e70b4fab 100644 --- a/src/main/java/ch/entwine/weblounge/contentrepository/impl/endpoint/PreviewsEndpoint.java +++ b/src/main/java/ch/entwine/weblounge/contentrepository/impl/endpoint/PreviewsEndpoint.java @@ -1,411 +1,416 @@ /* * Weblounge: Web Content Management System * Copyright (c) 2003 - 2011 The Weblounge Team * http://entwinemedia.com/weblounge * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package ch.entwine.weblounge.contentrepository.impl.endpoint; import ch.entwine.weblounge.common.content.PreviewGenerator; import ch.entwine.weblounge.common.content.Resource; import ch.entwine.weblounge.common.content.ResourceContent; import ch.entwine.weblounge.common.content.ResourceURI; import ch.entwine.weblounge.common.content.image.ImageStyle; import ch.entwine.weblounge.common.content.repository.ContentRepository; import ch.entwine.weblounge.common.content.repository.ContentRepositoryException; import ch.entwine.weblounge.common.impl.content.ResourceUtils; import ch.entwine.weblounge.common.impl.content.image.ImageStyleUtils; import ch.entwine.weblounge.common.impl.language.LanguageUtils; import ch.entwine.weblounge.common.language.Language; import ch.entwine.weblounge.common.language.UnknownLanguageException; import ch.entwine.weblounge.common.site.ImageScalingMode; import ch.entwine.weblounge.common.site.Module; import ch.entwine.weblounge.common.site.Site; import ch.entwine.weblounge.contentrepository.ResourceSerializer; import ch.entwine.weblounge.contentrepository.ResourceSerializerFactory; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.osgi.service.component.ComponentContext; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.EntityTag; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.StreamingOutput; /** * This class implements the <code>REST</code> endpoint for resource previews. */ @Path("/") public class PreviewsEndpoint extends ContentRepositoryEndpoint { /** The endpoint documentation */ private String docs = null; /** The list of image styles */ private List<ImageStyle> styles = new ArrayList<ImageStyle>(); /** * OSGi callback on component deactivation. * * @param ctx * the component context */ void deactivate(ComponentContext ctx) { styles.clear(); } /** * Returns the resource with the given identifier and styled using the * requested image style or a <code>404</code> if the resource or the resource * content could not be found. * <p> * If the content is not available in the requested language, the original * language version is used. * * @param request * the request * @param resourceId * the resource identifier * @param languageId * the language identifier * @param styleId * the image style identifier * @return the image */ @GET @Path("/{resource}/locales/{language}/styles/{style}") public Response getPreview(@Context HttpServletRequest request, @PathParam("resource") String resourceId, @PathParam("language") String languageId, @PathParam("style") String styleId) { // Check the parameters if (resourceId == null) throw new WebApplicationException(Status.BAD_REQUEST); // Get the resource final Resource<?> resource = loadResource(request, resourceId, null); if (resource == null) throw new WebApplicationException(Status.NOT_FOUND); // Extract the language Language language = null; try { language = LanguageUtils.getLanguage(languageId); if (!resource.supportsLanguage(language)) { if (!resource.contents().isEmpty()) language = resource.getOriginalContent().getLanguage(); else throw new WebApplicationException(Status.NOT_FOUND); } } catch (UnknownLanguageException e) { throw new WebApplicationException(Status.BAD_REQUEST); } // Search the site for the image style Site site = getSite(request); ImageStyle style = null; for (Module m : site.getModules()) { style = m.getImageStyle(styleId); if (style != null) { break; } } // Search the global styles if (style == null) { for (ImageStyle s : styles) { if (s.getIdentifier().equals(styleId)) { style = s; break; } } } // The image style was not found if (style == null) throw new WebApplicationException(Status.BAD_REQUEST); // Is there an up-to-date, cached version on the client side? if (!ResourceUtils.isModified(resource, request)) { return Response.notModified().build(); } // Load the content ResourceContent resourceContent = resource.getContent(language); // Check the ETag String eTag = ResourceUtils.getETagValue(resource, language, style); if (!ResourceUtils.isMismatch(eTag, request)) { return Response.notModified(new EntityTag(eTag)).build(); } ResourceURI resourceURI = resource.getURI(); final ContentRepository contentRepository = getContentRepository(site, false); // When there is no scaling required, just return the original if (ImageScalingMode.None.equals(style.getScalingMode())) { return getResourceContent(request, resource, language); } // Find a serializer ResourceSerializer<?, ?> serializer = ResourceSerializerFactory.getSerializerByType(resourceURI.getType()); if (serializer == null) throw new WebApplicationException(Status.NOT_FOUND); // Does the serializer come with a preview generator? PreviewGenerator previewGenerator = serializer.getPreviewGenerator(); if (previewGenerator == null) throw new WebApplicationException(Status.NOT_FOUND); // Load the resource contents from the repository InputStream resourceInputStream = null; long contentLength = -1; // Create the target file name StringBuilder filename = new StringBuilder(); String basename = null; if (resourceContent != null) basename = FilenameUtils.getBaseName(resourceContent.getFilename()); else basename = resource.getIdentifier(); String suffix = previewGenerator.getSuffix(resource, language, style); filename.append(basename); filename.append("-").append(language.getIdentifier()); if (StringUtils.isNotBlank(suffix)) { filename.append(".").append(suffix); } // Load the input stream from the scaled image InputStream contentRepositoryIs = null; FileOutputStream fos = null; File scaledResourceFile = null; try { scaledResourceFile = ImageStyleUtils.createScaledFile(resource, filename.toString(), language, style); long lastModified = resource.getModificationDate().getTime(); if (!scaledResourceFile.isFile() || scaledResourceFile.lastModified() < lastModified) { contentRepositoryIs = contentRepository.getContent(resourceURI, language); fos = new FileOutputStream(scaledResourceFile); logger.debug("Creating scaled image '{}' at {}", resource, scaledResourceFile); previewGenerator.createPreview(resource, language, style, contentRepositoryIs, fos); scaledResourceFile.setLastModified(lastModified); } // The scaled resource should now exist resourceInputStream = new FileInputStream(scaledResourceFile); contentLength = scaledResourceFile.length(); } catch (ContentRepositoryException e) { logger.error("Error loading {} image '{}' from {}: {}", new Object[] { language, resource, contentRepository, e.getMessage() }); logger.error(e.getMessage(), e); IOUtils.closeQuietly(resourceInputStream); FileUtils.deleteQuietly(scaledResourceFile); throw new WebApplicationException(); } catch (IOException e) { logger.error("Error scaling image '{}': {}", resourceURI, e.getMessage()); IOUtils.closeQuietly(resourceInputStream); FileUtils.deleteQuietly(scaledResourceFile); throw new WebApplicationException(); + } catch (Throwable t) { + logger.error("Error scaling image '{}': {}", resourceURI, t.getMessage()); + IOUtils.closeQuietly(resourceInputStream); + FileUtils.deleteQuietly(scaledResourceFile); + throw new WebApplicationException(); } finally { IOUtils.closeQuietly(contentRepositoryIs); IOUtils.closeQuietly(fos); } // Create the response final InputStream is = resourceInputStream; ResponseBuilder response = Response.ok(new StreamingOutput() { public void write(OutputStream os) throws IOException, WebApplicationException { try { IOUtils.copy(is, os); os.flush(); } finally { IOUtils.closeQuietly(is); } } }); // Add mime type header String mimetype = previewGenerator.getContentType(resource, language, style); if (mimetype == null) mimetype = MediaType.APPLICATION_OCTET_STREAM; response.type(mimetype); // Add last modified header response.lastModified(resource.getModificationDate()); // Add ETag header response.tag(new EntityTag(eTag)); // Add filename header response.header("Content-Disposition", "inline; filename=" + filename); // Content length response.header("Content-Length", Long.toString(contentLength)); // Send the response return response.build(); } /** * Returns the list of image styles that are registered for a site. * * @param request * the request * @return the list of image styles */ @GET @Produces(MediaType.TEXT_XML) @Path("/styles") public Response getImagestyles(@Context HttpServletRequest request) { Site site = getSite(request); if (site == null) throw new WebApplicationException(Status.NOT_FOUND); StringBuffer buf = new StringBuffer("<styles>"); // Add styles of current site for (Module m : site.getModules()) { ImageStyle[] styles = m.getImageStyles(); for (ImageStyle style : styles) { buf.append(style.toXml()); } } // Add global styles for (ImageStyle style : styles) { buf.append(style.toXml()); } buf.append("</styles>"); ResponseBuilder response = Response.ok(buf.toString()); return response.build(); } /** * Returns the image styles or a <code>404</code>. * * @param request * the request * @param styleId * the image style identifier * @return the image */ @GET @Produces(MediaType.TEXT_XML) @Path("/styles/{style}") public Response getImagestyle(@Context HttpServletRequest request, @PathParam("style") String styleId) { Site site = getSite(request); // Search styles of current site for (Module m : site.getModules()) { ImageStyle style = m.getImageStyle(styleId); if (style != null) { ResponseBuilder response = Response.ok(style.toXml()); return response.build(); } } // Search global styles for (ImageStyle style : styles) { if (style.getIdentifier().equals(styleId)) { ResponseBuilder response = Response.ok(style.toXml()); return response.build(); } } // The image style was not found throw new WebApplicationException(Status.NOT_FOUND); } /** * Returns the endpoint documentation. * * @return the endpoint documentation */ @GET @Path("/docs") @Produces(MediaType.TEXT_HTML) public String getDocumentation(@Context HttpServletRequest request) { if (docs == null) { String docsPath = request.getRequestURI(); String docsPathExtension = request.getPathInfo(); String servicePath = request.getRequestURI().substring(0, docsPath.length() - docsPathExtension.length()); docs = PreviewsEndpointDocs.createDocumentation(servicePath); } return docs; } /** * Callback from OSGi declarative services on registration of a new image * style in the service registry. * * @param style * the image style */ void addImageStyle(ImageStyle style) { styles.add(style); } /** * Callback from OSGi declarative services on removal of an image style from * the service registry. * * @param style * the image style */ void removeImageStyle(ImageStyle style) { styles.remove(style); } /** * {@inheritDoc} * * @see java.lang.Object#toString() */ @Override public String toString() { return "Previews rest endpoint"; } }
true
true
public Response getPreview(@Context HttpServletRequest request, @PathParam("resource") String resourceId, @PathParam("language") String languageId, @PathParam("style") String styleId) { // Check the parameters if (resourceId == null) throw new WebApplicationException(Status.BAD_REQUEST); // Get the resource final Resource<?> resource = loadResource(request, resourceId, null); if (resource == null) throw new WebApplicationException(Status.NOT_FOUND); // Extract the language Language language = null; try { language = LanguageUtils.getLanguage(languageId); if (!resource.supportsLanguage(language)) { if (!resource.contents().isEmpty()) language = resource.getOriginalContent().getLanguage(); else throw new WebApplicationException(Status.NOT_FOUND); } } catch (UnknownLanguageException e) { throw new WebApplicationException(Status.BAD_REQUEST); } // Search the site for the image style Site site = getSite(request); ImageStyle style = null; for (Module m : site.getModules()) { style = m.getImageStyle(styleId); if (style != null) { break; } } // Search the global styles if (style == null) { for (ImageStyle s : styles) { if (s.getIdentifier().equals(styleId)) { style = s; break; } } } // The image style was not found if (style == null) throw new WebApplicationException(Status.BAD_REQUEST); // Is there an up-to-date, cached version on the client side? if (!ResourceUtils.isModified(resource, request)) { return Response.notModified().build(); } // Load the content ResourceContent resourceContent = resource.getContent(language); // Check the ETag String eTag = ResourceUtils.getETagValue(resource, language, style); if (!ResourceUtils.isMismatch(eTag, request)) { return Response.notModified(new EntityTag(eTag)).build(); } ResourceURI resourceURI = resource.getURI(); final ContentRepository contentRepository = getContentRepository(site, false); // When there is no scaling required, just return the original if (ImageScalingMode.None.equals(style.getScalingMode())) { return getResourceContent(request, resource, language); } // Find a serializer ResourceSerializer<?, ?> serializer = ResourceSerializerFactory.getSerializerByType(resourceURI.getType()); if (serializer == null) throw new WebApplicationException(Status.NOT_FOUND); // Does the serializer come with a preview generator? PreviewGenerator previewGenerator = serializer.getPreviewGenerator(); if (previewGenerator == null) throw new WebApplicationException(Status.NOT_FOUND); // Load the resource contents from the repository InputStream resourceInputStream = null; long contentLength = -1; // Create the target file name StringBuilder filename = new StringBuilder(); String basename = null; if (resourceContent != null) basename = FilenameUtils.getBaseName(resourceContent.getFilename()); else basename = resource.getIdentifier(); String suffix = previewGenerator.getSuffix(resource, language, style); filename.append(basename); filename.append("-").append(language.getIdentifier()); if (StringUtils.isNotBlank(suffix)) { filename.append(".").append(suffix); } // Load the input stream from the scaled image InputStream contentRepositoryIs = null; FileOutputStream fos = null; File scaledResourceFile = null; try { scaledResourceFile = ImageStyleUtils.createScaledFile(resource, filename.toString(), language, style); long lastModified = resource.getModificationDate().getTime(); if (!scaledResourceFile.isFile() || scaledResourceFile.lastModified() < lastModified) { contentRepositoryIs = contentRepository.getContent(resourceURI, language); fos = new FileOutputStream(scaledResourceFile); logger.debug("Creating scaled image '{}' at {}", resource, scaledResourceFile); previewGenerator.createPreview(resource, language, style, contentRepositoryIs, fos); scaledResourceFile.setLastModified(lastModified); } // The scaled resource should now exist resourceInputStream = new FileInputStream(scaledResourceFile); contentLength = scaledResourceFile.length(); } catch (ContentRepositoryException e) { logger.error("Error loading {} image '{}' from {}: {}", new Object[] { language, resource, contentRepository, e.getMessage() }); logger.error(e.getMessage(), e); IOUtils.closeQuietly(resourceInputStream); FileUtils.deleteQuietly(scaledResourceFile); throw new WebApplicationException(); } catch (IOException e) { logger.error("Error scaling image '{}': {}", resourceURI, e.getMessage()); IOUtils.closeQuietly(resourceInputStream); FileUtils.deleteQuietly(scaledResourceFile); throw new WebApplicationException(); } finally { IOUtils.closeQuietly(contentRepositoryIs); IOUtils.closeQuietly(fos); } // Create the response final InputStream is = resourceInputStream; ResponseBuilder response = Response.ok(new StreamingOutput() { public void write(OutputStream os) throws IOException, WebApplicationException { try { IOUtils.copy(is, os); os.flush(); } finally { IOUtils.closeQuietly(is); } } }); // Add mime type header String mimetype = previewGenerator.getContentType(resource, language, style); if (mimetype == null) mimetype = MediaType.APPLICATION_OCTET_STREAM; response.type(mimetype); // Add last modified header response.lastModified(resource.getModificationDate()); // Add ETag header response.tag(new EntityTag(eTag)); // Add filename header response.header("Content-Disposition", "inline; filename=" + filename); // Content length response.header("Content-Length", Long.toString(contentLength)); // Send the response return response.build(); }
public Response getPreview(@Context HttpServletRequest request, @PathParam("resource") String resourceId, @PathParam("language") String languageId, @PathParam("style") String styleId) { // Check the parameters if (resourceId == null) throw new WebApplicationException(Status.BAD_REQUEST); // Get the resource final Resource<?> resource = loadResource(request, resourceId, null); if (resource == null) throw new WebApplicationException(Status.NOT_FOUND); // Extract the language Language language = null; try { language = LanguageUtils.getLanguage(languageId); if (!resource.supportsLanguage(language)) { if (!resource.contents().isEmpty()) language = resource.getOriginalContent().getLanguage(); else throw new WebApplicationException(Status.NOT_FOUND); } } catch (UnknownLanguageException e) { throw new WebApplicationException(Status.BAD_REQUEST); } // Search the site for the image style Site site = getSite(request); ImageStyle style = null; for (Module m : site.getModules()) { style = m.getImageStyle(styleId); if (style != null) { break; } } // Search the global styles if (style == null) { for (ImageStyle s : styles) { if (s.getIdentifier().equals(styleId)) { style = s; break; } } } // The image style was not found if (style == null) throw new WebApplicationException(Status.BAD_REQUEST); // Is there an up-to-date, cached version on the client side? if (!ResourceUtils.isModified(resource, request)) { return Response.notModified().build(); } // Load the content ResourceContent resourceContent = resource.getContent(language); // Check the ETag String eTag = ResourceUtils.getETagValue(resource, language, style); if (!ResourceUtils.isMismatch(eTag, request)) { return Response.notModified(new EntityTag(eTag)).build(); } ResourceURI resourceURI = resource.getURI(); final ContentRepository contentRepository = getContentRepository(site, false); // When there is no scaling required, just return the original if (ImageScalingMode.None.equals(style.getScalingMode())) { return getResourceContent(request, resource, language); } // Find a serializer ResourceSerializer<?, ?> serializer = ResourceSerializerFactory.getSerializerByType(resourceURI.getType()); if (serializer == null) throw new WebApplicationException(Status.NOT_FOUND); // Does the serializer come with a preview generator? PreviewGenerator previewGenerator = serializer.getPreviewGenerator(); if (previewGenerator == null) throw new WebApplicationException(Status.NOT_FOUND); // Load the resource contents from the repository InputStream resourceInputStream = null; long contentLength = -1; // Create the target file name StringBuilder filename = new StringBuilder(); String basename = null; if (resourceContent != null) basename = FilenameUtils.getBaseName(resourceContent.getFilename()); else basename = resource.getIdentifier(); String suffix = previewGenerator.getSuffix(resource, language, style); filename.append(basename); filename.append("-").append(language.getIdentifier()); if (StringUtils.isNotBlank(suffix)) { filename.append(".").append(suffix); } // Load the input stream from the scaled image InputStream contentRepositoryIs = null; FileOutputStream fos = null; File scaledResourceFile = null; try { scaledResourceFile = ImageStyleUtils.createScaledFile(resource, filename.toString(), language, style); long lastModified = resource.getModificationDate().getTime(); if (!scaledResourceFile.isFile() || scaledResourceFile.lastModified() < lastModified) { contentRepositoryIs = contentRepository.getContent(resourceURI, language); fos = new FileOutputStream(scaledResourceFile); logger.debug("Creating scaled image '{}' at {}", resource, scaledResourceFile); previewGenerator.createPreview(resource, language, style, contentRepositoryIs, fos); scaledResourceFile.setLastModified(lastModified); } // The scaled resource should now exist resourceInputStream = new FileInputStream(scaledResourceFile); contentLength = scaledResourceFile.length(); } catch (ContentRepositoryException e) { logger.error("Error loading {} image '{}' from {}: {}", new Object[] { language, resource, contentRepository, e.getMessage() }); logger.error(e.getMessage(), e); IOUtils.closeQuietly(resourceInputStream); FileUtils.deleteQuietly(scaledResourceFile); throw new WebApplicationException(); } catch (IOException e) { logger.error("Error scaling image '{}': {}", resourceURI, e.getMessage()); IOUtils.closeQuietly(resourceInputStream); FileUtils.deleteQuietly(scaledResourceFile); throw new WebApplicationException(); } catch (Throwable t) { logger.error("Error scaling image '{}': {}", resourceURI, t.getMessage()); IOUtils.closeQuietly(resourceInputStream); FileUtils.deleteQuietly(scaledResourceFile); throw new WebApplicationException(); } finally { IOUtils.closeQuietly(contentRepositoryIs); IOUtils.closeQuietly(fos); } // Create the response final InputStream is = resourceInputStream; ResponseBuilder response = Response.ok(new StreamingOutput() { public void write(OutputStream os) throws IOException, WebApplicationException { try { IOUtils.copy(is, os); os.flush(); } finally { IOUtils.closeQuietly(is); } } }); // Add mime type header String mimetype = previewGenerator.getContentType(resource, language, style); if (mimetype == null) mimetype = MediaType.APPLICATION_OCTET_STREAM; response.type(mimetype); // Add last modified header response.lastModified(resource.getModificationDate()); // Add ETag header response.tag(new EntityTag(eTag)); // Add filename header response.header("Content-Disposition", "inline; filename=" + filename); // Content length response.header("Content-Length", Long.toString(contentLength)); // Send the response return response.build(); }
diff --git a/plugins/com.aptana.rdt.profiling/src/com/aptana/rdt/internal/profiling/StandardVMProfiler.java b/plugins/com.aptana.rdt.profiling/src/com/aptana/rdt/internal/profiling/StandardVMProfiler.java index 1a53f07..2424508 100644 --- a/plugins/com.aptana.rdt.profiling/src/com/aptana/rdt/internal/profiling/StandardVMProfiler.java +++ b/plugins/com.aptana.rdt.profiling/src/com/aptana/rdt/internal/profiling/StandardVMProfiler.java @@ -1,109 +1,109 @@ package com.aptana.rdt.internal.profiling; import java.io.File; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.model.IProcess; import org.rubypeople.rdt.internal.launching.LaunchingMessages; import org.rubypeople.rdt.internal.launching.StandardVMRunner; import org.rubypeople.rdt.launching.IRubyLaunchConfigurationConstants; import org.rubypeople.rdt.launching.VMRunnerConfiguration; import com.aptana.rdt.profiling.IProfileUIConstants; import com.aptana.rdt.profiling.ProfilingPlugin; public class StandardVMProfiler extends StandardVMRunner { @Override public void run(VMRunnerConfiguration config, ILaunch launch, IProgressMonitor monitor) throws CoreException { if (monitor == null) { monitor = new NullProgressMonitor(); } IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 1); subMonitor.beginTask(LaunchingMessages.StandardVMRunner_Launching_VM____1, 2); subMonitor.subTask(LaunchingMessages.StandardVMRunner_Constructing_command_line____2); - List<String> arguments= constructProgramString(config); + List<String> arguments= constructProgramString(config, monitor); // VM args are the first thing after the ruby program so that users can specify // options like '-client' & '-server' which are required to be the first option String[] allVMArgs = combineVmArgs(config, fVMInstance); addArguments(allVMArgs, arguments); String[] lp= config.getLoadPath(); if (lp.length > 0) { arguments.addAll(convertLoadPath(config, lp)); } addStreamSync(arguments); arguments.add(END_OF_OPTIONS_DELIMITER); injectFileToLaunch(arguments, launch); arguments.add(getFileToLaunch(config)); addArguments(config.getProgramArguments(), arguments); String[] cmdLine= new String[arguments.size()]; arguments.toArray(cmdLine); String[] envp = getEnvironment(config); subMonitor.worked(1); // check for cancellation if (monitor.isCanceled()) { return; } subMonitor.subTask(LaunchingMessages.StandardVMRunner_Starting_virtual_machine____3); Process p= null; File workingDir = getWorkingDir(config); if (envp != null && envp.length > 0) { p= exec(cmdLine, workingDir, envp); } else { p = exec(cmdLine, workingDir); } if (p == null) { return; } // check for cancellation if (monitor.isCanceled()) { p.destroy(); return; } IProcess process= newProcess(launch, p, renderProcessLabel(cmdLine), getDefaultProcessMap()); process.setAttribute(IProcess.ATTR_CMDLINE, renderCommandLine(cmdLine)); process.setAttribute(IRubyLaunchConfigurationConstants.ATTR_PROJECT_NAME, launch.getAttribute(IRubyLaunchConfigurationConstants.ATTR_PROJECT_NAME)); process.setAttribute(IRubyLaunchConfigurationConstants.ATTR_REQUIRES_REFRESH, launch.getAttribute(IRubyLaunchConfigurationConstants.ATTR_REQUIRES_REFRESH)); subMonitor.worked(1); subMonitor.done(); } private void injectFileToLaunch(List<String> arguments, ILaunch launch) { String file = ProfilingPlugin.getDefault().getStateLocation().append("profile_" + System.currentTimeMillis() + ".log").toFile().toString(); launch.setAttribute(IProfileUIConstants.ATTR_PROFILE_OUTPUT, file); // Inject the path to the ruby-prof script! File vmInstallLocation = fVMInstance.getInstallLocation(); String path = vmInstallLocation.getAbsolutePath(); if (!vmInstallLocation.getName().equals("bin")) { path += File.separator + "bin"; } path = path + File.separator + "ruby-prof"; arguments.add(path); arguments.add("-f"); arguments.add(file); arguments.add("-p"); arguments.add("graph"); arguments.add("--replace-progname"); arguments.add(END_OF_OPTIONS_DELIMITER); } }
true
true
public void run(VMRunnerConfiguration config, ILaunch launch, IProgressMonitor monitor) throws CoreException { if (monitor == null) { monitor = new NullProgressMonitor(); } IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 1); subMonitor.beginTask(LaunchingMessages.StandardVMRunner_Launching_VM____1, 2); subMonitor.subTask(LaunchingMessages.StandardVMRunner_Constructing_command_line____2); List<String> arguments= constructProgramString(config); // VM args are the first thing after the ruby program so that users can specify // options like '-client' & '-server' which are required to be the first option String[] allVMArgs = combineVmArgs(config, fVMInstance); addArguments(allVMArgs, arguments); String[] lp= config.getLoadPath(); if (lp.length > 0) { arguments.addAll(convertLoadPath(config, lp)); } addStreamSync(arguments); arguments.add(END_OF_OPTIONS_DELIMITER); injectFileToLaunch(arguments, launch); arguments.add(getFileToLaunch(config)); addArguments(config.getProgramArguments(), arguments); String[] cmdLine= new String[arguments.size()]; arguments.toArray(cmdLine); String[] envp = getEnvironment(config); subMonitor.worked(1); // check for cancellation if (monitor.isCanceled()) { return; } subMonitor.subTask(LaunchingMessages.StandardVMRunner_Starting_virtual_machine____3); Process p= null; File workingDir = getWorkingDir(config); if (envp != null && envp.length > 0) { p= exec(cmdLine, workingDir, envp); } else { p = exec(cmdLine, workingDir); } if (p == null) { return; } // check for cancellation if (monitor.isCanceled()) { p.destroy(); return; } IProcess process= newProcess(launch, p, renderProcessLabel(cmdLine), getDefaultProcessMap()); process.setAttribute(IProcess.ATTR_CMDLINE, renderCommandLine(cmdLine)); process.setAttribute(IRubyLaunchConfigurationConstants.ATTR_PROJECT_NAME, launch.getAttribute(IRubyLaunchConfigurationConstants.ATTR_PROJECT_NAME)); process.setAttribute(IRubyLaunchConfigurationConstants.ATTR_REQUIRES_REFRESH, launch.getAttribute(IRubyLaunchConfigurationConstants.ATTR_REQUIRES_REFRESH)); subMonitor.worked(1); subMonitor.done(); }
public void run(VMRunnerConfiguration config, ILaunch launch, IProgressMonitor monitor) throws CoreException { if (monitor == null) { monitor = new NullProgressMonitor(); } IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 1); subMonitor.beginTask(LaunchingMessages.StandardVMRunner_Launching_VM____1, 2); subMonitor.subTask(LaunchingMessages.StandardVMRunner_Constructing_command_line____2); List<String> arguments= constructProgramString(config, monitor); // VM args are the first thing after the ruby program so that users can specify // options like '-client' & '-server' which are required to be the first option String[] allVMArgs = combineVmArgs(config, fVMInstance); addArguments(allVMArgs, arguments); String[] lp= config.getLoadPath(); if (lp.length > 0) { arguments.addAll(convertLoadPath(config, lp)); } addStreamSync(arguments); arguments.add(END_OF_OPTIONS_DELIMITER); injectFileToLaunch(arguments, launch); arguments.add(getFileToLaunch(config)); addArguments(config.getProgramArguments(), arguments); String[] cmdLine= new String[arguments.size()]; arguments.toArray(cmdLine); String[] envp = getEnvironment(config); subMonitor.worked(1); // check for cancellation if (monitor.isCanceled()) { return; } subMonitor.subTask(LaunchingMessages.StandardVMRunner_Starting_virtual_machine____3); Process p= null; File workingDir = getWorkingDir(config); if (envp != null && envp.length > 0) { p= exec(cmdLine, workingDir, envp); } else { p = exec(cmdLine, workingDir); } if (p == null) { return; } // check for cancellation if (monitor.isCanceled()) { p.destroy(); return; } IProcess process= newProcess(launch, p, renderProcessLabel(cmdLine), getDefaultProcessMap()); process.setAttribute(IProcess.ATTR_CMDLINE, renderCommandLine(cmdLine)); process.setAttribute(IRubyLaunchConfigurationConstants.ATTR_PROJECT_NAME, launch.getAttribute(IRubyLaunchConfigurationConstants.ATTR_PROJECT_NAME)); process.setAttribute(IRubyLaunchConfigurationConstants.ATTR_REQUIRES_REFRESH, launch.getAttribute(IRubyLaunchConfigurationConstants.ATTR_REQUIRES_REFRESH)); subMonitor.worked(1); subMonitor.done(); }
diff --git a/tools/src/XJavac.java b/tools/src/XJavac.java index 75a59d01d..72d10d75d 100644 --- a/tools/src/XJavac.java +++ b/tools/src/XJavac.java @@ -1,150 +1,151 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xerces.util; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.util.JavaEnvUtils; import org.apache.tools.ant.taskdefs.Javac; import java.lang.StringBuffer; import java.util.Properties; import java.util.Locale; /** * The implementation of the javac compiler for JDK 1.4 and above * * The purpose of this task is to diagnose whether we're * running on a 1.4 or above JVM; if we are, to * set up the bootclasspath such that the build will * succeed; if we aren't, then invoke the Javac12 * task. * * @author Neil Graham, IBM */ public class XJavac extends Javac { /** * Run the compilation. * * @exception BuildException if the compilation has problems. */ public void execute() throws BuildException { if(isJDK14OrHigher()) { // maybe the right one; check vendor: // by checking system properties: Properties props = null; try { props = System.getProperties(); } catch (Exception e) { throw new BuildException("unable to determine java vendor because could not access system properties!"); } // this is supposed to be provided by all JVM's from time immemorial String vendor = ((String)props.get("java.vendor")).toUpperCase(Locale.ENGLISH); if (vendor.indexOf("IBM") >= 0) { // we're on an IBM 1.4 or higher; fiddle with the bootclasspath. setBootclasspath(createIBMJDKBootclasspath()); } // need to do special things for Sun too and also - // for Apple, HP, SableVM, Kaffe and Blackdown: a Linux port of Sun Java + // for Apple, HP, FreeBSD, SableVM, Kaffe and Blackdown: a Linux port of Sun Java else if( (vendor.indexOf("SUN") >= 0) || (vendor.indexOf("BLACKDOWN") >= 0) || (vendor.indexOf("APPLE") >= 0) || (vendor.indexOf("HEWLETT-PACKARD") >= 0) || (vendor.indexOf("KAFFE") >= 0) || - (vendor.indexOf("SABLE") >= 0)) { + (vendor.indexOf("SABLE") >= 0) || + (vendor.indexOf("FREEBSD") >= 0)) { // we're on an SUN 1.4 or higher; fiddle with the bootclasspath. // since we can't eviscerate XML-related info here, // we must use the classpath Path bcp = createBootclasspath(); Path clPath = getClasspath(); bcp.append(clPath); String currBCP = (String)props.get("sun.boot.class.path"); Path currBCPath = new Path(null); currBCPath.createPathElement().setPath(currBCP); bcp.append(currBCPath); setBootclasspath(bcp); } } // now just do the normal thing: super.execute(); } /** * Creates bootclasspath for IBM JDK 1.4 and above. */ private Path createIBMJDKBootclasspath() { Path bcp = createBootclasspath(); String javaHome = System.getProperty("java.home"); StringBuffer bcpMember = new StringBuffer(); bcpMember.append(javaHome).append("/lib/charsets.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/core.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/vm.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/java.util.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/rt.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/graphics.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/javaws.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/jaws.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/security.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/server.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/JawBridge.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/gskikm.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/ibmjceprovider.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/indicim.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/jaccess.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/ldapsec.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/oldcertpath.jar"); bcp.createPathElement().setPath(bcpMember.toString()); return bcp; } /** * Checks whether the JDK version is 1.4 or higher. If it's not * JDK 1.4 we check whether we're on a future JDK by checking * that we're not on JDKs 1.0, 1.1, 1.2 or 1.3. This check by * exclusion should future proof this task from new versions of * Ant which are aware of higher JDK versions. * * @return true if the JDK version is 1.4 or higher. */ private boolean isJDK14OrHigher() { final String version = JavaEnvUtils.getJavaVersion(); return version.equals(JavaEnvUtils.JAVA_1_4) || (!version.equals(JavaEnvUtils.JAVA_1_3) && !version.equals(JavaEnvUtils.JAVA_1_2) && !version.equals(JavaEnvUtils.JAVA_1_1) && !version.equals(JavaEnvUtils.JAVA_1_0)); } }
false
true
public void execute() throws BuildException { if(isJDK14OrHigher()) { // maybe the right one; check vendor: // by checking system properties: Properties props = null; try { props = System.getProperties(); } catch (Exception e) { throw new BuildException("unable to determine java vendor because could not access system properties!"); } // this is supposed to be provided by all JVM's from time immemorial String vendor = ((String)props.get("java.vendor")).toUpperCase(Locale.ENGLISH); if (vendor.indexOf("IBM") >= 0) { // we're on an IBM 1.4 or higher; fiddle with the bootclasspath. setBootclasspath(createIBMJDKBootclasspath()); } // need to do special things for Sun too and also // for Apple, HP, SableVM, Kaffe and Blackdown: a Linux port of Sun Java else if( (vendor.indexOf("SUN") >= 0) || (vendor.indexOf("BLACKDOWN") >= 0) || (vendor.indexOf("APPLE") >= 0) || (vendor.indexOf("HEWLETT-PACKARD") >= 0) || (vendor.indexOf("KAFFE") >= 0) || (vendor.indexOf("SABLE") >= 0)) { // we're on an SUN 1.4 or higher; fiddle with the bootclasspath. // since we can't eviscerate XML-related info here, // we must use the classpath Path bcp = createBootclasspath(); Path clPath = getClasspath(); bcp.append(clPath); String currBCP = (String)props.get("sun.boot.class.path"); Path currBCPath = new Path(null); currBCPath.createPathElement().setPath(currBCP); bcp.append(currBCPath); setBootclasspath(bcp); } } // now just do the normal thing: super.execute(); }
public void execute() throws BuildException { if(isJDK14OrHigher()) { // maybe the right one; check vendor: // by checking system properties: Properties props = null; try { props = System.getProperties(); } catch (Exception e) { throw new BuildException("unable to determine java vendor because could not access system properties!"); } // this is supposed to be provided by all JVM's from time immemorial String vendor = ((String)props.get("java.vendor")).toUpperCase(Locale.ENGLISH); if (vendor.indexOf("IBM") >= 0) { // we're on an IBM 1.4 or higher; fiddle with the bootclasspath. setBootclasspath(createIBMJDKBootclasspath()); } // need to do special things for Sun too and also // for Apple, HP, FreeBSD, SableVM, Kaffe and Blackdown: a Linux port of Sun Java else if( (vendor.indexOf("SUN") >= 0) || (vendor.indexOf("BLACKDOWN") >= 0) || (vendor.indexOf("APPLE") >= 0) || (vendor.indexOf("HEWLETT-PACKARD") >= 0) || (vendor.indexOf("KAFFE") >= 0) || (vendor.indexOf("SABLE") >= 0) || (vendor.indexOf("FREEBSD") >= 0)) { // we're on an SUN 1.4 or higher; fiddle with the bootclasspath. // since we can't eviscerate XML-related info here, // we must use the classpath Path bcp = createBootclasspath(); Path clPath = getClasspath(); bcp.append(clPath); String currBCP = (String)props.get("sun.boot.class.path"); Path currBCPath = new Path(null); currBCPath.createPathElement().setPath(currBCP); bcp.append(currBCPath); setBootclasspath(bcp); } } // now just do the normal thing: super.execute(); }
diff --git a/springnet-git/src/main/java/mantech/controller/EquipmentController.java b/springnet-git/src/main/java/mantech/controller/EquipmentController.java index 157fc9d..c15344e 100644 --- a/springnet-git/src/main/java/mantech/controller/EquipmentController.java +++ b/springnet-git/src/main/java/mantech/controller/EquipmentController.java @@ -1,117 +1,117 @@ /** * Written by Long Nguyen <[email protected]> * FREE FOR ALL BUT DOES NOT MEAN THERE IS NO PRICE. */ package mantech.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.SessionAttributes; import mantech.controller.helpers.TemplateKeys; import mantech.domain.Category; import mantech.domain.Equipment; import mantech.repository.CategoryRepository; import mantech.repository.EquipmentRepository; import mantech.service.EquipmentService; /** * @author Long Nguyen * @version $Id: Equipment.java,v 1.0 Sep 12, 2011 1:30:35 PM nguyenlong Exp $ */ @Controller @SessionAttributes("equipment") public class EquipmentController { @Autowired private EquipmentRepository equipmentRepo; @Autowired private EquipmentService equipmentService; @Autowired private CategoryRepository categoryRepo; @RequestMapping(value = "/equipment", params = "action=list", method = RequestMethod.GET) - public String list(@RequestParam(value="page", required=false, defaultValue="1") int page, + public String list(@RequestParam(value="id", required=false, defaultValue="1") int page, ModelMap model) { int pageCount; if (equipmentRepo.count().intValue() % 3 == 0) { pageCount = equipmentRepo.count().intValue() / 3; } else { pageCount = (equipmentRepo.count().intValue() / 3) + 1; } if (page < 1 || page > pageCount) { model.addAttribute("msg", "Nothing to show"); } else { List<Equipment> listEquipment = equipmentService.paginate(page); model.addAttribute("listEquipment", listEquipment); } model.addAttribute("pageCount", pageCount); return TemplateKeys.EQUIPMENT_LIST; } @RequestMapping(value = "/equipment", params = "action=add", method = RequestMethod.GET) public String insert(ModelMap model) { List<Category> category = categoryRepo.findAll(); model.addAttribute("category", category); return "/equipment/add"; } @RequestMapping(value = "/equipment/addSave", method = RequestMethod.POST) public String insertSave(@RequestParam(value="name") String name, @RequestParam(value="catId") int id, ModelMap model) { Category category = categoryRepo.get(id); Equipment equipment = new Equipment(); equipment.setName(name); equipment.setCategory(category); equipmentRepo.save(equipment); model.addAttribute("msg", "Added Equipment Successfully!"); return "msg"; } @RequestMapping(value = "/equipment", params = "action=edit", method = RequestMethod.GET) public String update(@RequestParam(value="id", required=false, defaultValue="0") int id, ModelMap model) { Equipment equipment = equipmentRepo.get(id); List<Category> listCategory = categoryRepo.findAll(); model.addAttribute("equipment", equipment); model.addAttribute("listCategory", listCategory); return TemplateKeys.EQUIPMENT_EDIT; } @RequestMapping(value = "/equipment/editSave", method = RequestMethod.POST) public String updateSave(@RequestParam(value="id") int id, @RequestParam(value="catId") int catId, @RequestParam(value="name") String name, ModelMap model) { Equipment equipment = equipmentRepo.get(id); Category newCate = categoryRepo.get(catId); if (newCate != null) { equipment.setName(name); equipment.setCategory(newCate); equipmentRepo.update(equipment); model.addAttribute("msg", "Update successfully"); } else { model.addAttribute("msg", "Update fail"); } return update(id, model); } }
true
true
public String list(@RequestParam(value="page", required=false, defaultValue="1") int page, ModelMap model) { int pageCount; if (equipmentRepo.count().intValue() % 3 == 0) { pageCount = equipmentRepo.count().intValue() / 3; } else { pageCount = (equipmentRepo.count().intValue() / 3) + 1; } if (page < 1 || page > pageCount) { model.addAttribute("msg", "Nothing to show"); } else { List<Equipment> listEquipment = equipmentService.paginate(page); model.addAttribute("listEquipment", listEquipment); } model.addAttribute("pageCount", pageCount); return TemplateKeys.EQUIPMENT_LIST; }
public String list(@RequestParam(value="id", required=false, defaultValue="1") int page, ModelMap model) { int pageCount; if (equipmentRepo.count().intValue() % 3 == 0) { pageCount = equipmentRepo.count().intValue() / 3; } else { pageCount = (equipmentRepo.count().intValue() / 3) + 1; } if (page < 1 || page > pageCount) { model.addAttribute("msg", "Nothing to show"); } else { List<Equipment> listEquipment = equipmentService.paginate(page); model.addAttribute("listEquipment", listEquipment); } model.addAttribute("pageCount", pageCount); return TemplateKeys.EQUIPMENT_LIST; }
diff --git a/twitter4j-core/src/main/java/twitter4j/internal/http/HttpResponseImpl.java b/twitter4j-core/src/main/java/twitter4j/internal/http/HttpResponseImpl.java index e805602c..0327237c 100644 --- a/twitter4j-core/src/main/java/twitter4j/internal/http/HttpResponseImpl.java +++ b/twitter4j-core/src/main/java/twitter4j/internal/http/HttpResponseImpl.java @@ -1,67 +1,81 @@ /* * Copyright 2007 Yusuke Yamamoto * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package twitter4j.internal.http; import java.io.IOException; import java.net.HttpURLConnection; import java.util.List; import java.util.Map; /** * @author Yusuke Yamamoto - yusuke at mac.com * @since Twitter4J 2.1.2 */ public class HttpResponseImpl extends HttpResponse { private HttpURLConnection con; HttpResponseImpl(HttpURLConnection con, HttpClientConfiguration conf) throws IOException { super(conf); this.con = con; - this.statusCode = con.getResponseCode(); + try { + this.statusCode = con.getResponseCode(); + } catch (IOException e) { + /* + * If the user has revoked the access token in use, then Twitter naughtily returns a 401 with no "WWW-Authenticate" header. + * + * This causes an IOException in the getResponseCode() method call. See https://dev.twitter.com/issues/1114 + * This call can, however, me made a second time without exception. + */ + if ("Received authentication challenge is null".equals(e.getMessage())) { + this.statusCode = con.getResponseCode(); + } else { + throw e; + } + } if (null == (is = con.getErrorStream())) { is = con.getInputStream(); } if (is != null && "gzip".equals(con.getContentEncoding())) { // the response is gzipped is = new StreamingGZIPInputStream(is); } } // for test purpose /*package*/ HttpResponseImpl(String content) { super(); this.responseAsString = content; } @Override public String getResponseHeader(String name) { return con.getHeaderField(name); } @Override public Map<String, List<String>> getResponseHeaderFields() { return con.getHeaderFields(); } /** * {@inheritDoc} */ @Override public void disconnect() { con.disconnect(); } }
true
true
HttpResponseImpl(HttpURLConnection con, HttpClientConfiguration conf) throws IOException { super(conf); this.con = con; this.statusCode = con.getResponseCode(); if (null == (is = con.getErrorStream())) { is = con.getInputStream(); } if (is != null && "gzip".equals(con.getContentEncoding())) { // the response is gzipped is = new StreamingGZIPInputStream(is); } }
HttpResponseImpl(HttpURLConnection con, HttpClientConfiguration conf) throws IOException { super(conf); this.con = con; try { this.statusCode = con.getResponseCode(); } catch (IOException e) { /* * If the user has revoked the access token in use, then Twitter naughtily returns a 401 with no "WWW-Authenticate" header. * * This causes an IOException in the getResponseCode() method call. See https://dev.twitter.com/issues/1114 * This call can, however, me made a second time without exception. */ if ("Received authentication challenge is null".equals(e.getMessage())) { this.statusCode = con.getResponseCode(); } else { throw e; } } if (null == (is = con.getErrorStream())) { is = con.getInputStream(); } if (is != null && "gzip".equals(con.getContentEncoding())) { // the response is gzipped is = new StreamingGZIPInputStream(is); } }
diff --git a/src/main/java/com/alta189/simplesave/h2/H2Database.java b/src/main/java/com/alta189/simplesave/h2/H2Database.java index 277e541..d2fa801 100644 --- a/src/main/java/com/alta189/simplesave/h2/H2Database.java +++ b/src/main/java/com/alta189/simplesave/h2/H2Database.java @@ -1,558 +1,558 @@ /* * This file is part of SimpleSave * * SimpleSave is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SimpleSave 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 program. If not, see <http://www.gnu.org/licenses/>. */ package com.alta189.simplesave.h2; import com.alta189.simplesave.Configuration; import com.alta189.simplesave.Database; import com.alta189.simplesave.DatabaseFactory; import com.alta189.simplesave.exceptions.ConnectionException; import com.alta189.simplesave.exceptions.TableRegistrationException; import com.alta189.simplesave.exceptions.UnknownTableException; import com.alta189.simplesave.internal.FieldRegistration; import com.alta189.simplesave.internal.IdRegistration; import com.alta189.simplesave.internal.PreparedStatementUtils; import com.alta189.simplesave.internal.ResultSetUtils; import com.alta189.simplesave.internal.TableFactory; import com.alta189.simplesave.internal.TableRegistration; import com.alta189.simplesave.internal.TableUtils; import com.alta189.simplesave.query.Comparator; import com.alta189.simplesave.query.OrderQuery.OrderPair; import com.alta189.simplesave.query.Query; import com.alta189.simplesave.query.QueryResult; import com.alta189.simplesave.query.SelectQuery; import com.alta189.simplesave.query.WhereEntry; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; public class H2Database extends Database { private static final String driver = "h2"; private String connectionURL; private Connection connection; static { DatabaseFactory.registerDatabase(H2Database.class); } public H2Database(Configuration config) { String h2db = config.getProperty(H2Configuration.H2_DATABASE); if (h2db == null || h2db.isEmpty()) { throw new IllegalArgumentException("Database is null or empty!"); } this.connectionURL = "jdbc:h2:file:" + h2db + ";MODE=MYSQL;IGNORECASE=TRUE;AUTO_SERVER=TRUE"; } public H2Database(String connectionURL) { this.connectionURL = connectionURL; } public static String getDriver() { return driver; } @Override public void connect() throws ConnectionException { if (!isConnected()) { super.connect(); try { Class.forName("org.h2.Driver"); } catch (ClassNotFoundException e) { throw new ConnectionException("Could not find the H2 JDBC Driver!", e); } try { connection = DriverManager.getConnection(connectionURL); createTables(); if (checkTableOnRegistration()) { for (TableRegistration t : getTableRegistrations()){ checkTableStructure(t); } } } catch (SQLException e) { throw new ConnectionException(e); } } } @Override public void close() throws ConnectionException { if (isConnected()) { try { connection.close(); } catch (SQLException e) { throw new ConnectionException(e); } super.close(); } } @Override public boolean isConnected() { try { return connection != null && !connection.isClosed() && connection.isValid(5000); } catch (SQLException e) { return false; } } @Override public <T> QueryResult<T> execute(Query<T> query) { if (!isConnected()) { try { connect(); } catch (ConnectionException e) { throw new RuntimeException(e); } } try { switch (query.getType()) { case SELECT: SelectQuery selectQuery = (SelectQuery) query; TableRegistration table = getTableRegistration(selectQuery.getTableClass()); PreparedStatement statement = null; StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("SELECT * from ") .append(table.getName()) .append(" "); if (!selectQuery.where().getEntries().isEmpty()) { queryBuilder.append("WHERE "); int count = 0; for (Object o : selectQuery.where().getEntries()) { count++; if (!(o instanceof WhereEntry)) { throw new InternalError("Something has gone very wrong!"); } WhereEntry entry = (WhereEntry) o; if (entry.getPrefix() != null && !entry.getPrefix().isEmpty()) { queryBuilder.append(entry.getPrefix()); } queryBuilder.append(entry.getField()); switch (entry.getComparator()) { case EQUAL: queryBuilder.append("=? "); break; case NOT_EQUAL: queryBuilder.append("<>? "); break; case GREATER_THAN: queryBuilder.append(">? "); break; case LESS_THAN: queryBuilder.append("<? "); break; case GREATER_THAN_OR_EQUAL: queryBuilder.append(">=? "); break; case LESS_THAN_OR_EQUAL: queryBuilder.append("<=? "); break; case CONTAINS: queryBuilder.append(" LIKE ? "); break; } if (entry.getSuffix() != null && !entry.getSuffix().isEmpty()) { queryBuilder.append(entry.getSuffix()); } if (count != selectQuery.where().getEntries().size()) { queryBuilder.append(entry.getOperator().name()) .append(" "); } } - if (selectQuery.limit().getLimit()!=null){ - queryBuilder.append("LIMIT "); - if (selectQuery.limit().getStartFrom()!=null) - queryBuilder.append(selectQuery.limit().getStartFrom()).append(", "); - queryBuilder.append(selectQuery.limit().getLimit()).append(" "); - } if (!selectQuery.order().getPairs().isEmpty()){ queryBuilder.append("ORDER BY "); int track = 0; for (Object pair : selectQuery.order().getPairs()){ track++; if (!(pair instanceof OrderPair)) throw new InternalError("Internal Error: Uncastable Object to OrderPair!"); OrderPair order = (OrderPair)pair; queryBuilder.append(order.column).append(" ").append(order.order.name()); if (track == selectQuery.order().getPairs().size()) queryBuilder.append(" "); else queryBuilder.append(", "); } } + if (selectQuery.limit().getLimit()!=null){ + queryBuilder.append("LIMIT "); + if (selectQuery.limit().getStartFrom()!=null) + queryBuilder.append(selectQuery.limit().getStartFrom()).append(", "); + queryBuilder.append(selectQuery.limit().getLimit()).append(" "); + } statement = connection.prepareStatement(queryBuilder.toString()); count = 0; for (Object o : selectQuery.where().getEntries()) { count++; if (!(o instanceof WhereEntry)) { throw new InternalError("Something has gone very wrong!"); } WhereEntry entry = (WhereEntry) o; if (entry.getComparator() == Comparator.CONTAINS) { statement.setString(count, "%" + entry.getComparison().getValue().toString() + "%"); } else { PreparedStatementUtils.setObject(statement, count, entry.getComparison().getValue()); } } } if (statement == null) { - if (selectQuery.limit().getLimit()!=null){ - queryBuilder.append("LIMIT "); - if (selectQuery.limit().getStartFrom()!=null) - queryBuilder.append(selectQuery.limit().getStartFrom()).append(", "); - queryBuilder.append(selectQuery.limit().getLimit()).append(" "); - } if (!selectQuery.order().getPairs().isEmpty()){ queryBuilder.append("ORDER BY "); int track = 0; for (Object pair : selectQuery.order().getPairs()){ track++; if (!(pair instanceof OrderPair)) throw new InternalError("Internal Error: Uncastable Object to OrderPair!"); OrderPair order = (OrderPair)pair; queryBuilder.append(order.column).append(" ").append(order.order.name()); if (track == selectQuery.order().getPairs().size()) queryBuilder.append(" "); else queryBuilder.append(", "); } } + if (selectQuery.limit().getLimit()!=null){ + queryBuilder.append("LIMIT "); + if (selectQuery.limit().getStartFrom()!=null) + queryBuilder.append(selectQuery.limit().getStartFrom()).append(", "); + queryBuilder.append(selectQuery.limit().getLimit()).append(" "); + } statement = connection.prepareStatement(queryBuilder.toString()); } ResultSet set = statement.executeQuery(); QueryResult<T> result = new QueryResult<T>(ResultSetUtils.buildResultList(table, (Class<T>) table.getTableClass(), set)); set.close(); return result; default: break; } } catch (SQLException e) { throw new RuntimeException(e); } return null; } @Override public void save(Class<?> tableClass, Object o) { if (!isConnected()) { try { connect(); } catch (ConnectionException e) { throw new RuntimeException(e); } } if (!tableClass.isAssignableFrom(o.getClass())) { throw new IllegalArgumentException("The provided table class and save objects classes were not compatible."); } TableRegistration table = getTableRegistration(tableClass); if (table == null) { throw new UnknownTableException("The table class '" + tableClass.getCanonicalName() + "' is not registered!"); } StringBuilder query = new StringBuilder(); long id = TableUtils.getIdValue(table, o); if (id == 0) { query.append("INSERT INTO ") .append(table.getName()) .append(" ("); StringBuilder valuesBuilder = new StringBuilder(); valuesBuilder.append("VALUES ( "); int count = 0; for (FieldRegistration fieldRegistration : table.getFields()) { count++; query.append(fieldRegistration.getName()); valuesBuilder.append("?"); if (count == table.getFields().size()) { query.append(") "); valuesBuilder.append(")"); } else { query.append(", "); valuesBuilder.append(", "); } } query.append(valuesBuilder.toString()); } else { query.append("UPDATE ") .append(table.getName()) .append(" SET "); int count = 0; for (FieldRegistration fieldRegistration : table.getFields()) { count++; query.append(fieldRegistration.getName()) .append("=?"); if (count != table.getFields().size()) { query.append(", "); } } query.append(" WHERE ") .append(table.getId().getName()) .append("=?"); } try { PreparedStatement statement; if (id == 0) statement = connection.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS); else statement = connection.prepareStatement(query.toString()); int i = 0; for (FieldRegistration fieldRegistration : table.getFields()) { i++; if (fieldRegistration.isSerializable()) { PreparedStatementUtils.setObject(statement, i, o); } else { if (fieldRegistration.getType().equals(int.class) || fieldRegistration.getType().equals(Integer.class)) { PreparedStatementUtils.setObject(statement, i, (Integer) TableUtils.getValue(fieldRegistration, o)); } else if (fieldRegistration.getType().equals(long.class) || fieldRegistration.getType().equals(Long.class)) { PreparedStatementUtils.setObject(statement, i, (Long) TableUtils.getValue(fieldRegistration, o)); } else if (fieldRegistration.getType().equals(double.class) || fieldRegistration.getType().equals(Double.class)) { PreparedStatementUtils.setObject(statement, i, (Double) TableUtils.getValue(fieldRegistration, o)); } else if (fieldRegistration.getType().equals(String.class)) { PreparedStatementUtils.setObject(statement, i, (String) TableUtils.getValue(fieldRegistration, o)); } else if (fieldRegistration.getType().equals(boolean.class) || fieldRegistration.getType().equals(Boolean.class)) { boolean value = (Boolean) TableUtils.getValue(fieldRegistration, o); if (value) { PreparedStatementUtils.setObject(statement, i, 1); } else { PreparedStatementUtils.setObject(statement, i, 0); } } else if (fieldRegistration.getType().equals(short.class) || fieldRegistration.getType().equals(Short.class)) { PreparedStatementUtils.setObject(statement, i, (Short) TableUtils.getValue(fieldRegistration, o)); } else if (fieldRegistration.getType().equals(float.class) || fieldRegistration.getType().equals(Float.class)) { PreparedStatementUtils.setObject(statement, i, (Float) TableUtils.getValue(fieldRegistration, o)); } else if (fieldRegistration.getType().equals(byte.class) || fieldRegistration.getType().equals(Byte.class)) { PreparedStatementUtils.setObject(statement, i, (Byte) TableUtils.getValue(fieldRegistration, o)); } else { PreparedStatementUtils.setObject(statement, i, (Object) TableUtils.getValue(fieldRegistration, o)); } } } if (id != 0) { i++; IdRegistration idRegistration = table.getId(); if (idRegistration.getType().equals(Integer.class) || idRegistration.getType().equals(int.class)) { PreparedStatementUtils.setObject(statement, i, (Integer) TableUtils.getValue(idRegistration, o)); } else if (idRegistration.getType().equals(Long.class) || idRegistration.getType().equals(long.class)) { PreparedStatementUtils.setObject(statement, i, (Long) TableUtils.getValue(idRegistration, o)); } } statement.executeUpdate(); if (id == 0) { ResultSet resultSet = statement.getGeneratedKeys(); if (resultSet != null && resultSet.next()) { try { Field field = table.getId().getField(); field.setAccessible(true); if (table.getId().getType().equals(int.class)) { field.setInt(o, resultSet.getInt(1)); } else if (table.getId().getType().equals(Integer.class)) { field.set(o, resultSet.getObject(1)); } else if (table.getId().getType().equals(long.class)) { field.setLong(o, resultSet.getLong(1)); } else if (table.getId().getType().equals(Long.class)) { field.set(o, resultSet.getObject(1)); } } catch (IllegalAccessException e) { e.printStackTrace(); } } } } catch (SQLException e) { throw new RuntimeException(e); } } @Override public void registerTable(Class<?> tableClass) throws TableRegistrationException { TableRegistration table = TableFactory.buildTable(tableClass); if (table == null) { throw new TableRegistrationException("The TableFactory returned a null table"); } for (TableRegistration t : getTables().values()) { if (t.getName().equalsIgnoreCase(table.getName())) throw new TableRegistrationException("This table matches another with the same name!"); } super.registerTable(tableClass); } @Override public void remove(Class<?> tableClass, Object o) { if (!isConnected()) { try { connect(); } catch (ConnectionException e) { throw new RuntimeException(e); } } if (!tableClass.isAssignableFrom(o.getClass())) { throw new IllegalArgumentException("The provided table class and save objects classes were not compatible."); } TableRegistration table = getTableRegistration(tableClass); if (table == null) { throw new UnknownTableException("The table class '" + tableClass.getCanonicalName() + "' is not registered!"); } StringBuilder query = new StringBuilder(); long id = TableUtils.getIdValue(table, o); if (id == 0) throw new IllegalArgumentException("Object was never inserted into database!"); query.append("DELETE FROM ") .append(table.getName()) .append(" WHERE ") .append(table.getId().getName()) .append("=?"); try { PreparedStatement statement = connection.prepareStatement(query.toString()); IdRegistration idRegistration = table.getId(); if (idRegistration.getType().equals(Integer.class) || idRegistration.getType().equals(int.class)) { PreparedStatementUtils.setObject(statement, 1, (Integer) TableUtils.getValue(idRegistration, o)); } else if (idRegistration.getType().equals(Long.class) || idRegistration.getType().equals(long.class)) { PreparedStatementUtils.setObject(statement, 1, (Long) TableUtils.getValue(idRegistration, o)); } statement.executeUpdate(); } catch (SQLException e) { throw new RuntimeException(e); } } @Override public void clear(Class<?> tableClass) { if (!isConnected()) { try { connect(); } catch (ConnectionException e) { throw new RuntimeException(e); } } TableRegistration table = getTableRegistration(tableClass); if (table == null) { throw new UnknownTableException("The table class '" + tableClass.getCanonicalName() + "' is not registered!"); } StringBuilder query = new StringBuilder(); query.append("DELETE FROM ").append(table.getName()); try { PreparedStatement statement = connection.prepareStatement(query.toString()); statement.executeUpdate(); } catch (SQLException e) { throw new RuntimeException(e); } } private void createTables() { for (TableRegistration table : getTables().values()) { StringBuilder query = new StringBuilder(); query.append("CREATE TABLE IF NOT EXISTS ") .append(table.getName()) .append(" (") .append(table.getId().getName()) .append(" ") .append(H2Util.getTypeFromClass(table.getId().getType())) .append(" NOT NULL AUTO_INCREMENT PRIMARY KEY, "); int count = 0; for (FieldRegistration field : table.getFields()) { count++; String type = null; if (field.isSerializable()) { type = H2Util.getTypeFromClass(String.class); } else { type = H2Util.getTypeFromClass(field.getType()); } query.append(field.getName()) .append(" ") .append(type); if (count != table.getFields().size()) { query.append(", "); } } query.append(") "); try { PreparedStatement statement = connection.prepareStatement(query.toString()); statement.executeUpdate(); } catch (SQLException e) { throw new RuntimeException(e); } } } public void checkTableStructure(TableRegistration table) { // TODO Update table structure StringBuilder query = new StringBuilder(); query.append("SELECT * FROM ") .append(table.getName()) .append(" LIMIT 1"); try { ResultSetMetaData meta = connection.prepareStatement(query.toString()).executeQuery().getMetaData(); Collection<FieldRegistration> fields = table.getFields(); // <field,alreadyexisting?> Map<String, String> redo = new LinkedHashMap<String, String>(); for (FieldRegistration f : fields) { boolean found = false; String deftype = H2Util.getTypeFromClass(f.getType()); for (int i = 1; i <= meta.getColumnCount(); i++) { if (f.getName().equalsIgnoreCase(meta.getColumnName(i))) { String type = meta.getColumnTypeName(i); if (!deftype.equals(type)) { redo.put(f.getName(), true + ";" + deftype); } found = true; break; } } if (!found) { redo.put(f.getName(), false + ";" + deftype); } } for (String s : redo.keySet()) { StringBuilder q = new StringBuilder(); q.append("ALTER TABLE ").append(table.getName()).append(" "); String[] results = redo.get(s).split(";"); if (results[0].equalsIgnoreCase("true")) { q.append("ALTER COLUMN ").append(s).append(" ").append(results[1]); } else { q.append("ADD COLUMN ").append(s).append(" ").append(results[1]); } connection.prepareStatement(q.toString()).executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } } }
false
true
public <T> QueryResult<T> execute(Query<T> query) { if (!isConnected()) { try { connect(); } catch (ConnectionException e) { throw new RuntimeException(e); } } try { switch (query.getType()) { case SELECT: SelectQuery selectQuery = (SelectQuery) query; TableRegistration table = getTableRegistration(selectQuery.getTableClass()); PreparedStatement statement = null; StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("SELECT * from ") .append(table.getName()) .append(" "); if (!selectQuery.where().getEntries().isEmpty()) { queryBuilder.append("WHERE "); int count = 0; for (Object o : selectQuery.where().getEntries()) { count++; if (!(o instanceof WhereEntry)) { throw new InternalError("Something has gone very wrong!"); } WhereEntry entry = (WhereEntry) o; if (entry.getPrefix() != null && !entry.getPrefix().isEmpty()) { queryBuilder.append(entry.getPrefix()); } queryBuilder.append(entry.getField()); switch (entry.getComparator()) { case EQUAL: queryBuilder.append("=? "); break; case NOT_EQUAL: queryBuilder.append("<>? "); break; case GREATER_THAN: queryBuilder.append(">? "); break; case LESS_THAN: queryBuilder.append("<? "); break; case GREATER_THAN_OR_EQUAL: queryBuilder.append(">=? "); break; case LESS_THAN_OR_EQUAL: queryBuilder.append("<=? "); break; case CONTAINS: queryBuilder.append(" LIKE ? "); break; } if (entry.getSuffix() != null && !entry.getSuffix().isEmpty()) { queryBuilder.append(entry.getSuffix()); } if (count != selectQuery.where().getEntries().size()) { queryBuilder.append(entry.getOperator().name()) .append(" "); } } if (selectQuery.limit().getLimit()!=null){ queryBuilder.append("LIMIT "); if (selectQuery.limit().getStartFrom()!=null) queryBuilder.append(selectQuery.limit().getStartFrom()).append(", "); queryBuilder.append(selectQuery.limit().getLimit()).append(" "); } if (!selectQuery.order().getPairs().isEmpty()){ queryBuilder.append("ORDER BY "); int track = 0; for (Object pair : selectQuery.order().getPairs()){ track++; if (!(pair instanceof OrderPair)) throw new InternalError("Internal Error: Uncastable Object to OrderPair!"); OrderPair order = (OrderPair)pair; queryBuilder.append(order.column).append(" ").append(order.order.name()); if (track == selectQuery.order().getPairs().size()) queryBuilder.append(" "); else queryBuilder.append(", "); } } statement = connection.prepareStatement(queryBuilder.toString()); count = 0; for (Object o : selectQuery.where().getEntries()) { count++; if (!(o instanceof WhereEntry)) { throw new InternalError("Something has gone very wrong!"); } WhereEntry entry = (WhereEntry) o; if (entry.getComparator() == Comparator.CONTAINS) { statement.setString(count, "%" + entry.getComparison().getValue().toString() + "%"); } else { PreparedStatementUtils.setObject(statement, count, entry.getComparison().getValue()); } } } if (statement == null) { if (selectQuery.limit().getLimit()!=null){ queryBuilder.append("LIMIT "); if (selectQuery.limit().getStartFrom()!=null) queryBuilder.append(selectQuery.limit().getStartFrom()).append(", "); queryBuilder.append(selectQuery.limit().getLimit()).append(" "); } if (!selectQuery.order().getPairs().isEmpty()){ queryBuilder.append("ORDER BY "); int track = 0; for (Object pair : selectQuery.order().getPairs()){ track++; if (!(pair instanceof OrderPair)) throw new InternalError("Internal Error: Uncastable Object to OrderPair!"); OrderPair order = (OrderPair)pair; queryBuilder.append(order.column).append(" ").append(order.order.name()); if (track == selectQuery.order().getPairs().size()) queryBuilder.append(" "); else queryBuilder.append(", "); } } statement = connection.prepareStatement(queryBuilder.toString()); } ResultSet set = statement.executeQuery(); QueryResult<T> result = new QueryResult<T>(ResultSetUtils.buildResultList(table, (Class<T>) table.getTableClass(), set)); set.close(); return result; default: break; } } catch (SQLException e) { throw new RuntimeException(e); } return null; }
public <T> QueryResult<T> execute(Query<T> query) { if (!isConnected()) { try { connect(); } catch (ConnectionException e) { throw new RuntimeException(e); } } try { switch (query.getType()) { case SELECT: SelectQuery selectQuery = (SelectQuery) query; TableRegistration table = getTableRegistration(selectQuery.getTableClass()); PreparedStatement statement = null; StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("SELECT * from ") .append(table.getName()) .append(" "); if (!selectQuery.where().getEntries().isEmpty()) { queryBuilder.append("WHERE "); int count = 0; for (Object o : selectQuery.where().getEntries()) { count++; if (!(o instanceof WhereEntry)) { throw new InternalError("Something has gone very wrong!"); } WhereEntry entry = (WhereEntry) o; if (entry.getPrefix() != null && !entry.getPrefix().isEmpty()) { queryBuilder.append(entry.getPrefix()); } queryBuilder.append(entry.getField()); switch (entry.getComparator()) { case EQUAL: queryBuilder.append("=? "); break; case NOT_EQUAL: queryBuilder.append("<>? "); break; case GREATER_THAN: queryBuilder.append(">? "); break; case LESS_THAN: queryBuilder.append("<? "); break; case GREATER_THAN_OR_EQUAL: queryBuilder.append(">=? "); break; case LESS_THAN_OR_EQUAL: queryBuilder.append("<=? "); break; case CONTAINS: queryBuilder.append(" LIKE ? "); break; } if (entry.getSuffix() != null && !entry.getSuffix().isEmpty()) { queryBuilder.append(entry.getSuffix()); } if (count != selectQuery.where().getEntries().size()) { queryBuilder.append(entry.getOperator().name()) .append(" "); } } if (!selectQuery.order().getPairs().isEmpty()){ queryBuilder.append("ORDER BY "); int track = 0; for (Object pair : selectQuery.order().getPairs()){ track++; if (!(pair instanceof OrderPair)) throw new InternalError("Internal Error: Uncastable Object to OrderPair!"); OrderPair order = (OrderPair)pair; queryBuilder.append(order.column).append(" ").append(order.order.name()); if (track == selectQuery.order().getPairs().size()) queryBuilder.append(" "); else queryBuilder.append(", "); } } if (selectQuery.limit().getLimit()!=null){ queryBuilder.append("LIMIT "); if (selectQuery.limit().getStartFrom()!=null) queryBuilder.append(selectQuery.limit().getStartFrom()).append(", "); queryBuilder.append(selectQuery.limit().getLimit()).append(" "); } statement = connection.prepareStatement(queryBuilder.toString()); count = 0; for (Object o : selectQuery.where().getEntries()) { count++; if (!(o instanceof WhereEntry)) { throw new InternalError("Something has gone very wrong!"); } WhereEntry entry = (WhereEntry) o; if (entry.getComparator() == Comparator.CONTAINS) { statement.setString(count, "%" + entry.getComparison().getValue().toString() + "%"); } else { PreparedStatementUtils.setObject(statement, count, entry.getComparison().getValue()); } } } if (statement == null) { if (!selectQuery.order().getPairs().isEmpty()){ queryBuilder.append("ORDER BY "); int track = 0; for (Object pair : selectQuery.order().getPairs()){ track++; if (!(pair instanceof OrderPair)) throw new InternalError("Internal Error: Uncastable Object to OrderPair!"); OrderPair order = (OrderPair)pair; queryBuilder.append(order.column).append(" ").append(order.order.name()); if (track == selectQuery.order().getPairs().size()) queryBuilder.append(" "); else queryBuilder.append(", "); } } if (selectQuery.limit().getLimit()!=null){ queryBuilder.append("LIMIT "); if (selectQuery.limit().getStartFrom()!=null) queryBuilder.append(selectQuery.limit().getStartFrom()).append(", "); queryBuilder.append(selectQuery.limit().getLimit()).append(" "); } statement = connection.prepareStatement(queryBuilder.toString()); } ResultSet set = statement.executeQuery(); QueryResult<T> result = new QueryResult<T>(ResultSetUtils.buildResultList(table, (Class<T>) table.getTableClass(), set)); set.close(); return result; default: break; } } catch (SQLException e) { throw new RuntimeException(e); } return null; }
diff --git a/src/main/java/servlet/HelloServlet.java b/src/main/java/servlet/HelloServlet.java index 62cd5fe..9a28f90 100644 --- a/src/main/java/servlet/HelloServlet.java +++ b/src/main/java/servlet/HelloServlet.java @@ -1,122 +1,122 @@ package servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.net.URI; import java.net.URISyntaxException; import java.sql.*; // @WebServlet( // name = "HelloServlet", // urlPatterns = {"/hello"} // ) public class HelloServlet extends HttpServlet { // Database Connection private static Connection getConnection() throws URISyntaxException, SQLException { URI dbUri = new URI(System.getenv("DATABASE_URL")); String username = dbUri.getUserInfo().split(":")[0]; String password = dbUri.getUserInfo().split(":")[1]; String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + dbUri.getPath(); return DriverManager.getConnection(dbUrl, username, password); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // response.getWriter().print("Hello from Java!\n"); try { Connection connection = getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("DROP TABLE IF EXISTS ticks"); stmt.executeUpdate("CREATE TABLE ticks (tick timestamp)"); stmt.executeUpdate("INSERT INTO ticks VALUES (now())"); ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); while (rs.next()) { - response.setAttribute("test_var", rs.getTimestamp("tick")); + request.setAttribute("test_var", rs.getTimestamp("tick")); } } catch (SQLException e) { response.getWriter().print("SQLException: " + e.getMessage()); } catch (URISyntaxException e) { response.getWriter().print("URISyntaxException: " + e.getMessage()); } request.getRequestDispatcher("/hello.jsp").forward(request, response); } } /* import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.*; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.*; import java.net.URI; import java.net.URISyntaxException; import java.sql.*; public class HelloWorld extends HttpServlet { // Database Connection private static Connection getConnection() throws URISyntaxException, SQLException { URI dbUri = new URI(System.getenv("DATABASE_URL")); String username = dbUri.getUserInfo().split(":")[0]; String password = dbUri.getUserInfo().split(":")[1]; String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + dbUri.getPath(); return DriverManager.getConnection(dbUrl, username, password); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // response.getWriter().print("Hello from Java!\n"); try { Connection connection = getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("DROP TABLE IF EXISTS ticks"); stmt.executeUpdate("CREATE TABLE ticks (tick timestamp)"); stmt.executeUpdate("INSERT INTO ticks VALUES (now())"); ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); while (rs.next()) { // response.getWriter().print("Read from DB: " + rs.getTimestamp("tick")); } } catch (SQLException e) { response.getWriter().print("SQLException: " + e.getMessage()); } catch (URISyntaxException e) { response.getWriter().print("URISyntaxException: " + e.getMessage()); } request.getRequestDispatcher("/index.jsp").forward(request, response); } public static void main(String[] args) throws Exception{ Server server = new Server(Integer.valueOf(System.getenv("PORT"))); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); server.setHandler(context); context.addServlet(new ServletHolder(new HelloWorld()),"/*"); server.start(); server.join(); } } */
true
true
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // response.getWriter().print("Hello from Java!\n"); try { Connection connection = getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("DROP TABLE IF EXISTS ticks"); stmt.executeUpdate("CREATE TABLE ticks (tick timestamp)"); stmt.executeUpdate("INSERT INTO ticks VALUES (now())"); ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); while (rs.next()) { response.setAttribute("test_var", rs.getTimestamp("tick")); } } catch (SQLException e) { response.getWriter().print("SQLException: " + e.getMessage()); } catch (URISyntaxException e) { response.getWriter().print("URISyntaxException: " + e.getMessage()); } request.getRequestDispatcher("/hello.jsp").forward(request, response); }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // response.getWriter().print("Hello from Java!\n"); try { Connection connection = getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("DROP TABLE IF EXISTS ticks"); stmt.executeUpdate("CREATE TABLE ticks (tick timestamp)"); stmt.executeUpdate("INSERT INTO ticks VALUES (now())"); ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); while (rs.next()) { request.setAttribute("test_var", rs.getTimestamp("tick")); } } catch (SQLException e) { response.getWriter().print("SQLException: " + e.getMessage()); } catch (URISyntaxException e) { response.getWriter().print("URISyntaxException: " + e.getMessage()); } request.getRequestDispatcher("/hello.jsp").forward(request, response); }
diff --git a/src/org/hackystat/sensor/xmldata/option/TestArgListOption.java b/src/org/hackystat/sensor/xmldata/option/TestArgListOption.java index c138889..8d1c558 100644 --- a/src/org/hackystat/sensor/xmldata/option/TestArgListOption.java +++ b/src/org/hackystat/sensor/xmldata/option/TestArgListOption.java @@ -1,44 +1,46 @@ package org.hackystat.sensor.xmldata.option; import java.io.File; import java.util.ArrayList; import java.util.List; import org.hackystat.sensor.xmldata.XmlDataController; import org.junit.Assert; import org.junit.Test; /** * Tests if the arglist option operates as intended. * @author aito * */ public class TestArgListOption { /** * Tests if isValid returns the correct value depending on the specified * parameters. */ @Test public void testIsValid() { XmlDataController controller = new XmlDataController(); // Tests a valid argList parameter count, but invalid file. List<String> parameters = new ArrayList<String>(); String testPackage = "src/org/hackystat/sensor/xmldata/testdataset/"; - parameters.add(new File("") + testPackage + "testArgList.txt"); + File testArgList = new File(System.getProperty("user.dir"), testPackage + "testArgList.txt"); + //parameters.add(new File("") + testPackage + "testArgList.txt"); + parameters.add(testArgList.toString()); Option option = OptionFactory.getInstance(controller, ArgListOption.OPTION_NAME, parameters); Assert.assertTrue("ArgList accept only 1 argument.", option.isValid()); option.process(); // Tests passing invalid amount of parameters. parameters = new ArrayList<String>(); option = ArgListOption.createOption(controller, parameters); Assert.assertFalse("ArgList accept only 1 argument.", option.isValid()); // Tests passing an invalid file. parameters = new ArrayList<String>(); parameters.add("Foo.xml"); option = ArgListOption.createOption(controller, parameters); Assert.assertFalse("An invalid file should invalid this option.", option.isValid()); } }
true
true
public void testIsValid() { XmlDataController controller = new XmlDataController(); // Tests a valid argList parameter count, but invalid file. List<String> parameters = new ArrayList<String>(); String testPackage = "src/org/hackystat/sensor/xmldata/testdataset/"; parameters.add(new File("") + testPackage + "testArgList.txt"); Option option = OptionFactory.getInstance(controller, ArgListOption.OPTION_NAME, parameters); Assert.assertTrue("ArgList accept only 1 argument.", option.isValid()); option.process(); // Tests passing invalid amount of parameters. parameters = new ArrayList<String>(); option = ArgListOption.createOption(controller, parameters); Assert.assertFalse("ArgList accept only 1 argument.", option.isValid()); // Tests passing an invalid file. parameters = new ArrayList<String>(); parameters.add("Foo.xml"); option = ArgListOption.createOption(controller, parameters); Assert.assertFalse("An invalid file should invalid this option.", option.isValid()); }
public void testIsValid() { XmlDataController controller = new XmlDataController(); // Tests a valid argList parameter count, but invalid file. List<String> parameters = new ArrayList<String>(); String testPackage = "src/org/hackystat/sensor/xmldata/testdataset/"; File testArgList = new File(System.getProperty("user.dir"), testPackage + "testArgList.txt"); //parameters.add(new File("") + testPackage + "testArgList.txt"); parameters.add(testArgList.toString()); Option option = OptionFactory.getInstance(controller, ArgListOption.OPTION_NAME, parameters); Assert.assertTrue("ArgList accept only 1 argument.", option.isValid()); option.process(); // Tests passing invalid amount of parameters. parameters = new ArrayList<String>(); option = ArgListOption.createOption(controller, parameters); Assert.assertFalse("ArgList accept only 1 argument.", option.isValid()); // Tests passing an invalid file. parameters = new ArrayList<String>(); parameters.add("Foo.xml"); option = ArgListOption.createOption(controller, parameters); Assert.assertFalse("An invalid file should invalid this option.", option.isValid()); }
diff --git a/Android/cloudLogin/src/com/cloude/entropin/CloudLoginTow.java b/Android/cloudLogin/src/com/cloude/entropin/CloudLoginTow.java index 89acecc..6f2c7bd 100644 --- a/Android/cloudLogin/src/com/cloude/entropin/CloudLoginTow.java +++ b/Android/cloudLogin/src/com/cloude/entropin/CloudLoginTow.java @@ -1,93 +1,93 @@ package com.cloude.entropin; import java.net.CookieStore; import java.net.HttpURLConnection; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.net.ssl.HostnameVerifier; import javax.xml.xpath.XPathException; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.HttpResponse; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.params.ClientPNames; import org.apache.http.client.protocol.ClientContext; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.scheme.SocketFactory; import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import android.accounts.AccountManager; import android.accounts.AccountManagerCallback; import android.accounts.AccountManagerFuture; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.util.Log; public class CloudLoginTow extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try{ new Thread(new Runnable() { public void run() { GAEConnector _gaeConnector = new GAEConnector(null, "http://logincookietest.appspot.com"); if (!_gaeConnector.Authenticate(CloudLoginTow.this)) { - Log.d("debug","***AUTHENTICATION ERROR***"); + Log.d("CLOUD","***AUTHENTICATION ERROR***"); } if (_gaeConnector.isAuthenticated()) { try{ int httpStatusCode = _gaeConnector.GETContent("/test.jsp", true, true); if (httpStatusCode == 200) { String content = _gaeConnector.getLastContent(); - Log.d("debug",content); + Log.d("CLOUD",content); } }catch(Exception e){ } } } }).start(); }catch(Exception e){ } } }
false
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try{ new Thread(new Runnable() { public void run() { GAEConnector _gaeConnector = new GAEConnector(null, "http://logincookietest.appspot.com"); if (!_gaeConnector.Authenticate(CloudLoginTow.this)) { Log.d("debug","***AUTHENTICATION ERROR***"); } if (_gaeConnector.isAuthenticated()) { try{ int httpStatusCode = _gaeConnector.GETContent("/test.jsp", true, true); if (httpStatusCode == 200) { String content = _gaeConnector.getLastContent(); Log.d("debug",content); } }catch(Exception e){ } } } }).start(); }catch(Exception e){ } }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try{ new Thread(new Runnable() { public void run() { GAEConnector _gaeConnector = new GAEConnector(null, "http://logincookietest.appspot.com"); if (!_gaeConnector.Authenticate(CloudLoginTow.this)) { Log.d("CLOUD","***AUTHENTICATION ERROR***"); } if (_gaeConnector.isAuthenticated()) { try{ int httpStatusCode = _gaeConnector.GETContent("/test.jsp", true, true); if (httpStatusCode == 200) { String content = _gaeConnector.getLastContent(); Log.d("CLOUD",content); } }catch(Exception e){ } } } }).start(); }catch(Exception e){ } }
diff --git a/plugins/org.eclipse.emf.compare.ide.ui.tests/src/org/eclipse/emf/compare/ide/ui/tests/egit/CompareGitTestCase.java b/plugins/org.eclipse.emf.compare.ide.ui.tests/src/org/eclipse/emf/compare/ide/ui/tests/egit/CompareGitTestCase.java index dcbf2d795..9f4892bc5 100644 --- a/plugins/org.eclipse.emf.compare.ide.ui.tests/src/org/eclipse/emf/compare/ide/ui/tests/egit/CompareGitTestCase.java +++ b/plugins/org.eclipse.emf.compare.ide.ui.tests/src/org/eclipse/emf/compare/ide/ui/tests/egit/CompareGitTestCase.java @@ -1,73 +1,73 @@ /******************************************************************************* * Copyright (C) 2013, 2014 Obeo 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.emf.compare.ide.ui.tests.egit; import java.io.File; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.eclipse.core.runtime.preferences.InstanceScope; import org.eclipse.egit.core.Activator; import org.eclipse.egit.core.GitCorePreferences; import org.eclipse.emf.compare.ide.ui.tests.CompareTestCase; import org.eclipse.emf.compare.ide.ui.tests.egit.fixture.GitTestRepository; import org.eclipse.emf.compare.ide.ui.tests.egit.fixture.MockSystemReader; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.util.FileUtils; import org.eclipse.jgit.util.SystemReader; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; /** * The set up and tear down of this class were mostly copied from org.eclipse.egit.core.test.GitTestCase. */ @SuppressWarnings("restriction") public class CompareGitTestCase extends CompareTestCase { protected GitTestRepository repository; // The ".git" folder of the test repository private File gitDir; @BeforeClass public static void setUpClass() { // suppress auto-ignoring and auto-sharing to avoid interference IEclipsePreferences eGitPreferences = InstanceScope.INSTANCE.getNode(Activator.getPluginId()); eGitPreferences.putBoolean(GitCorePreferences.core_autoIgnoreDerivedResources, false); eGitPreferences.putBoolean(GitCorePreferences.core_autoShareProjects, false); } @Override @Before public void setUp() throws Exception { super.setUp(); // ensure there are no shared Repository instances left // when starting a new test Activator.getDefault().getRepositoryCache().clear(); final MockSystemReader mockSystemReader = new MockSystemReader(); SystemReader.setInstance(mockSystemReader); mockSystemReader.setProperty(Constants.GIT_CEILING_DIRECTORIES_KEY, ResourcesPlugin.getWorkspace() - .getRoot().getLocation().toFile().getAbsoluteFile().toString()); + .getRoot().getLocation().toFile().getParentFile().getAbsoluteFile().toString()); gitDir = new File(project.getProject().getWorkspace().getRoot().getRawLocation().toFile(), Constants.DOT_GIT); repository = new GitTestRepository(gitDir); repository.connect(project.getProject()); } @Override @After public void tearDown() throws Exception { super.tearDown(); repository.dispose(); Activator.getDefault().getRepositoryCache().clear(); if (gitDir.exists()) { FileUtils.delete(gitDir, FileUtils.RECURSIVE | FileUtils.RETRY); } } }
true
true
public void setUp() throws Exception { super.setUp(); // ensure there are no shared Repository instances left // when starting a new test Activator.getDefault().getRepositoryCache().clear(); final MockSystemReader mockSystemReader = new MockSystemReader(); SystemReader.setInstance(mockSystemReader); mockSystemReader.setProperty(Constants.GIT_CEILING_DIRECTORIES_KEY, ResourcesPlugin.getWorkspace() .getRoot().getLocation().toFile().getAbsoluteFile().toString()); gitDir = new File(project.getProject().getWorkspace().getRoot().getRawLocation().toFile(), Constants.DOT_GIT); repository = new GitTestRepository(gitDir); repository.connect(project.getProject()); }
public void setUp() throws Exception { super.setUp(); // ensure there are no shared Repository instances left // when starting a new test Activator.getDefault().getRepositoryCache().clear(); final MockSystemReader mockSystemReader = new MockSystemReader(); SystemReader.setInstance(mockSystemReader); mockSystemReader.setProperty(Constants.GIT_CEILING_DIRECTORIES_KEY, ResourcesPlugin.getWorkspace() .getRoot().getLocation().toFile().getParentFile().getAbsoluteFile().toString()); gitDir = new File(project.getProject().getWorkspace().getRoot().getRawLocation().toFile(), Constants.DOT_GIT); repository = new GitTestRepository(gitDir); repository.connect(project.getProject()); }
diff --git a/izpack-src/trunk/src/lib/com/izforge/izpack/panels/HelloPanel.java b/izpack-src/trunk/src/lib/com/izforge/izpack/panels/HelloPanel.java index 886091a8..a9f00677 100644 --- a/izpack-src/trunk/src/lib/com/izforge/izpack/panels/HelloPanel.java +++ b/izpack-src/trunk/src/lib/com/izforge/izpack/panels/HelloPanel.java @@ -1,142 +1,142 @@ /* * IzPack - Copyright 2001-2005 Julien Ponge, All Rights Reserved. * * http://www.izforge.com/izpack/ * http://developer.berlios.de/projects/izpack/ * * Copyright 2002 Jan Blok * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.izforge.izpack.panels; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.util.ArrayList; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JLabel; import javax.swing.JPanel; import com.izforge.izpack.Info; import com.izforge.izpack.gui.LabelFactory; import com.izforge.izpack.installer.InstallData; import com.izforge.izpack.installer.InstallerFrame; import com.izforge.izpack.installer.IzPanel; /** * The Hello panel class. * * @author Julien Ponge */ public class HelloPanel extends IzPanel { /** * */ private static final long serialVersionUID = 3257848774955905587L; /** The layout. */ private BoxLayout layout; /** The welcome label. */ private JLabel welcomeLabel; /** The application authors label. */ private JLabel appAuthorsLabel; /** The application URL label. */ private JLabel appURLLabel; /** * The constructor. * * @param parent The parent. * @param idata The installation data. */ public HelloPanel(InstallerFrame parent, InstallData idata) { super(parent, idata); // The 'super' layout GridBagLayout superLayout = new GridBagLayout(); setLayout(superLayout); GridBagConstraints gbConstraints = new GridBagConstraints(); gbConstraints.insets = new Insets(0, 0, 0, 0); gbConstraints.fill = GridBagConstraints.NONE; gbConstraints.anchor = GridBagConstraints.CENTER; // We initialize our 'real' layout JPanel centerPanel = new JPanel(); layout = new BoxLayout(centerPanel, BoxLayout.Y_AXIS); centerPanel.setLayout(layout); superLayout.addLayoutComponent(centerPanel, gbConstraints); add(centerPanel); // We create and put the labels String str; centerPanel.add(Box.createVerticalStrut(10)); str = parent.langpack.getString("HelloPanel.welcome1") + idata.info.getAppName() + " " + idata.info.getAppVersion() + parent.langpack.getString("HelloPanel.welcome2"); welcomeLabel = LabelFactory.create(str, parent.icons.getImageIcon("host"), JLabel.TRAILING); centerPanel.add(welcomeLabel); centerPanel.add(Box.createVerticalStrut(20)); ArrayList authors = idata.info.getAuthors(); int size = authors.size(); if (size > 0) { str = parent.langpack.getString("HelloPanel.authors"); appAuthorsLabel = LabelFactory.create(str, parent.icons.getImageIcon("information"), JLabel.TRAILING); centerPanel.add(appAuthorsLabel); JLabel label; for (int i = 0; i < size; i++) { Info.Author a = (Info.Author) authors.get(i); - String email = (a.getEmail() != null) ? (" <" + a.getEmail() + ">") : ""; + String email = (a.getEmail() != null && a.getEmail().length() > 0) ? (" <" + a.getEmail() + ">") : ""; label = LabelFactory.create(" - " + a.getName() + email, parent.icons .getImageIcon("empty"), JLabel.TRAILING); centerPanel.add(label); } centerPanel.add(Box.createVerticalStrut(20)); } if (idata.info.getAppURL() != null) { str = parent.langpack.getString("HelloPanel.url") + idata.info.getAppURL(); appURLLabel = LabelFactory.create(str, parent.icons.getImageIcon("bookmark"), JLabel.TRAILING); centerPanel.add(appURLLabel); } } /** * Indicates wether the panel has been validated or not. * * @return Always true. */ public boolean isValidated() { return true; } }
true
true
public HelloPanel(InstallerFrame parent, InstallData idata) { super(parent, idata); // The 'super' layout GridBagLayout superLayout = new GridBagLayout(); setLayout(superLayout); GridBagConstraints gbConstraints = new GridBagConstraints(); gbConstraints.insets = new Insets(0, 0, 0, 0); gbConstraints.fill = GridBagConstraints.NONE; gbConstraints.anchor = GridBagConstraints.CENTER; // We initialize our 'real' layout JPanel centerPanel = new JPanel(); layout = new BoxLayout(centerPanel, BoxLayout.Y_AXIS); centerPanel.setLayout(layout); superLayout.addLayoutComponent(centerPanel, gbConstraints); add(centerPanel); // We create and put the labels String str; centerPanel.add(Box.createVerticalStrut(10)); str = parent.langpack.getString("HelloPanel.welcome1") + idata.info.getAppName() + " " + idata.info.getAppVersion() + parent.langpack.getString("HelloPanel.welcome2"); welcomeLabel = LabelFactory.create(str, parent.icons.getImageIcon("host"), JLabel.TRAILING); centerPanel.add(welcomeLabel); centerPanel.add(Box.createVerticalStrut(20)); ArrayList authors = idata.info.getAuthors(); int size = authors.size(); if (size > 0) { str = parent.langpack.getString("HelloPanel.authors"); appAuthorsLabel = LabelFactory.create(str, parent.icons.getImageIcon("information"), JLabel.TRAILING); centerPanel.add(appAuthorsLabel); JLabel label; for (int i = 0; i < size; i++) { Info.Author a = (Info.Author) authors.get(i); String email = (a.getEmail() != null) ? (" <" + a.getEmail() + ">") : ""; label = LabelFactory.create(" - " + a.getName() + email, parent.icons .getImageIcon("empty"), JLabel.TRAILING); centerPanel.add(label); } centerPanel.add(Box.createVerticalStrut(20)); } if (idata.info.getAppURL() != null) { str = parent.langpack.getString("HelloPanel.url") + idata.info.getAppURL(); appURLLabel = LabelFactory.create(str, parent.icons.getImageIcon("bookmark"), JLabel.TRAILING); centerPanel.add(appURLLabel); } }
public HelloPanel(InstallerFrame parent, InstallData idata) { super(parent, idata); // The 'super' layout GridBagLayout superLayout = new GridBagLayout(); setLayout(superLayout); GridBagConstraints gbConstraints = new GridBagConstraints(); gbConstraints.insets = new Insets(0, 0, 0, 0); gbConstraints.fill = GridBagConstraints.NONE; gbConstraints.anchor = GridBagConstraints.CENTER; // We initialize our 'real' layout JPanel centerPanel = new JPanel(); layout = new BoxLayout(centerPanel, BoxLayout.Y_AXIS); centerPanel.setLayout(layout); superLayout.addLayoutComponent(centerPanel, gbConstraints); add(centerPanel); // We create and put the labels String str; centerPanel.add(Box.createVerticalStrut(10)); str = parent.langpack.getString("HelloPanel.welcome1") + idata.info.getAppName() + " " + idata.info.getAppVersion() + parent.langpack.getString("HelloPanel.welcome2"); welcomeLabel = LabelFactory.create(str, parent.icons.getImageIcon("host"), JLabel.TRAILING); centerPanel.add(welcomeLabel); centerPanel.add(Box.createVerticalStrut(20)); ArrayList authors = idata.info.getAuthors(); int size = authors.size(); if (size > 0) { str = parent.langpack.getString("HelloPanel.authors"); appAuthorsLabel = LabelFactory.create(str, parent.icons.getImageIcon("information"), JLabel.TRAILING); centerPanel.add(appAuthorsLabel); JLabel label; for (int i = 0; i < size; i++) { Info.Author a = (Info.Author) authors.get(i); String email = (a.getEmail() != null && a.getEmail().length() > 0) ? (" <" + a.getEmail() + ">") : ""; label = LabelFactory.create(" - " + a.getName() + email, parent.icons .getImageIcon("empty"), JLabel.TRAILING); centerPanel.add(label); } centerPanel.add(Box.createVerticalStrut(20)); } if (idata.info.getAppURL() != null) { str = parent.langpack.getString("HelloPanel.url") + idata.info.getAppURL(); appURLLabel = LabelFactory.create(str, parent.icons.getImageIcon("bookmark"), JLabel.TRAILING); centerPanel.add(appURLLabel); } }
diff --git a/src/com/voracious/dragons/client/screens/StatScreen.java b/src/com/voracious/dragons/client/screens/StatScreen.java index b79f1d6..75a30c1 100644 --- a/src/com/voracious/dragons/client/screens/StatScreen.java +++ b/src/com/voracious/dragons/client/screens/StatScreen.java @@ -1,120 +1,120 @@ package com.voracious.dragons.client.screens; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import com.voracious.dragons.client.Game; import com.voracious.dragons.client.graphics.Screen; import com.voracious.dragons.client.graphics.Sprite; import com.voracious.dragons.client.graphics.ui.Button; import com.voracious.dragons.client.utils.InputHandler; public class StatScreen extends Screen { public static final int WIDTH = 2160/3; public static final int HEIGHT = 1440/3; private Button returnButton; private Sprite background; public StatScreen(/*player's pid to do db searching*/) { super(WIDTH, HEIGHT); background = new Sprite("/mainMenuBackground.png"); returnButton=new Button("Back",0,0); returnButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { Game.setCurrentScreen(new MainMenuScreen()); } }); /*TODO Stat's to be shown: * user's username * # of finished games * # of current games * # won * # loss * % won * % loss * Ave time between moves * Ave number of turns per game */ //the PID is assumed to be the pid of the person logged in to the game /*# of finished games * SELECT COUNT(gid) * FROM GAME * WHERE (pid1=PID OR pid2=PID) AND inProgress=false * GROUP BY GAME.gid */ /*# of current games * SELECT COUNT(gid) * FROM GAME * WHERE (pid1=PID OR pid2=PID) AND inProgress=true * GROUP BY GAME.gid */ /*#won * SELECT COUNT(gid) * FROM WINNER * WHERE pid=PID * GROUP BY gid */ /*#loss * =#finished games - #won */ /*% won * =#won / #finished games */ /*%loss * =#loss / #finished games */ /*Ave time between turns * (sum of each games's sum of differences in timestamps ( * from j=1 to n-1 timestamp[j]-timestamp[j-1])) - * / (#finished Games+#current games) + * / (#tuples w/ turn pid=PID) */ /*Ave turns a game * (SELECT COUNT(*)//all tuples * FROM TURN * WHERE pid=PID * ) / (#finished Games+#current games) */ } @Override public void start(){ InputHandler.registerScreen(this); } @Override public void stop(){ InputHandler.deregisterScreen(this); } @Override public void render(Graphics2D g) { background.draw(g, 0, 0); this.returnButton.draw(g); } @Override public void tick() { } @Override public void mouseClicked(MouseEvent e){ int ex=e.getX(); int ey=e.getY(); this.returnButton.mouseClicked(ex, ey); } }
true
true
public StatScreen(/*player's pid to do db searching*/) { super(WIDTH, HEIGHT); background = new Sprite("/mainMenuBackground.png"); returnButton=new Button("Back",0,0); returnButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { Game.setCurrentScreen(new MainMenuScreen()); } }); /*TODO Stat's to be shown: * user's username * # of finished games * # of current games * # won * # loss * % won * % loss * Ave time between moves * Ave number of turns per game */ //the PID is assumed to be the pid of the person logged in to the game /*# of finished games * SELECT COUNT(gid) * FROM GAME * WHERE (pid1=PID OR pid2=PID) AND inProgress=false * GROUP BY GAME.gid */ /*# of current games * SELECT COUNT(gid) * FROM GAME * WHERE (pid1=PID OR pid2=PID) AND inProgress=true * GROUP BY GAME.gid */ /*#won * SELECT COUNT(gid) * FROM WINNER * WHERE pid=PID * GROUP BY gid */ /*#loss * =#finished games - #won */ /*% won * =#won / #finished games */ /*%loss * =#loss / #finished games */ /*Ave time between turns * (sum of each games's sum of differences in timestamps ( * from j=1 to n-1 timestamp[j]-timestamp[j-1])) * / (#finished Games+#current games) */ /*Ave turns a game * (SELECT COUNT(*)//all tuples * FROM TURN * WHERE pid=PID * ) / (#finished Games+#current games) */ }
public StatScreen(/*player's pid to do db searching*/) { super(WIDTH, HEIGHT); background = new Sprite("/mainMenuBackground.png"); returnButton=new Button("Back",0,0); returnButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { Game.setCurrentScreen(new MainMenuScreen()); } }); /*TODO Stat's to be shown: * user's username * # of finished games * # of current games * # won * # loss * % won * % loss * Ave time between moves * Ave number of turns per game */ //the PID is assumed to be the pid of the person logged in to the game /*# of finished games * SELECT COUNT(gid) * FROM GAME * WHERE (pid1=PID OR pid2=PID) AND inProgress=false * GROUP BY GAME.gid */ /*# of current games * SELECT COUNT(gid) * FROM GAME * WHERE (pid1=PID OR pid2=PID) AND inProgress=true * GROUP BY GAME.gid */ /*#won * SELECT COUNT(gid) * FROM WINNER * WHERE pid=PID * GROUP BY gid */ /*#loss * =#finished games - #won */ /*% won * =#won / #finished games */ /*%loss * =#loss / #finished games */ /*Ave time between turns * (sum of each games's sum of differences in timestamps ( * from j=1 to n-1 timestamp[j]-timestamp[j-1])) * / (#tuples w/ turn pid=PID) */ /*Ave turns a game * (SELECT COUNT(*)//all tuples * FROM TURN * WHERE pid=PID * ) / (#finished Games+#current games) */ }
diff --git a/stado/src/org/postgresql/stado/metadata/SysColumn.java b/stado/src/org/postgresql/stado/metadata/SysColumn.java index 7795f93..929bb49 100644 --- a/stado/src/org/postgresql/stado/metadata/SysColumn.java +++ b/stado/src/org/postgresql/stado/metadata/SysColumn.java @@ -1,425 +1,425 @@ /***************************************************************************** * Copyright (C) 2008 EnterpriseDB Corporation. * Copyright (C) 2011 Stado Global Development Group. * * This file is part of Stado. * * Stado 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 * (at your option) any later version. * * Stado 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 Stado. If not, see <http://www.gnu.org/licenses/>. * * You can find Stado at http://www.stado.us * ****************************************************************************/ package org.postgresql.stado.metadata; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Enumeration; import java.util.List; import java.util.Vector; import org.postgresql.stado.engine.XDBSessionContext; import org.postgresql.stado.exception.ErrorMessageRepository; import org.postgresql.stado.exception.XDBGeneratorException; import org.postgresql.stado.exception.XDBServerException; import org.postgresql.stado.optimizer.SqlExpression; import org.postgresql.stado.parser.ExpressionType; import org.postgresql.stado.parser.Parser; import org.postgresql.stado.parser.SqlCreateTableColumn; import org.postgresql.stado.parser.SqlSelect; import org.postgresql.stado.parser.core.ParseException; //redo these as properties... //----------------------------------------- public class SysColumn { private SysTable table; private int colid; private int colseq; private String colname; private int coltype; private int collength; private int colscale; private int colprecision; private boolean isnullable; private boolean isserial; private String nativecoldef; private int indextype; // not part of xsyscolumns, but convenient here private double selectivity; private String defaultExprStr = ""; private SqlExpression defaultExpr; public boolean isWithTimeZone; /** * Tracks which indexes use this column */ private Vector<SysIndex> indexUsage; /** * The best index to use if just accessing based on this column */ public SysIndex bestIndex; public int bestIndexColPos; public int bestIndexRowsPerPage; // Constructor public SysColumn(SysTable table, int colID, int colSeq, String colName, int colType, int colLength, int colScale, int colPrecision, boolean isNullable, boolean isSerial, String nativeColDef, double selectivity, String defaultExpr) { this.table = table; colid = colID; colseq = colSeq; colname = colName; coltype = colType; collength = colLength; colscale = colScale; colprecision = colPrecision; isnullable = isNullable; isserial = isSerial; nativecoldef = nativeColDef; indextype = MetaData.INDEX_TYPE_NONE; this.selectivity = selectivity; this.defaultExprStr = defaultExpr; } /* * TODO Should we execute statements against database or get the database in * the memory and then execute the statements. Presntly I am going to get to * the query the xSysForegintable */ public Enumeration<Integer> getChildColumns() { Vector<Integer> childcols = new Vector<Integer>(); String sqlstmt = "select colid from xsysforeignkeys where refcolid = '" + colid + " '"; try { ResultSet result = MetaData.getMetaData().executeQuery(sqlstmt); while (result.next()) { int colidentifier = result.getInt("colid"); childcols.add(new Integer(colidentifier)); } return childcols.elements(); } catch (SQLException e) { throw new XDBServerException( e.getMessage() + "\nQUERY: " + sqlstmt, e, ErrorMessageRepository.SQL_EXEC_FAILURE_CODE); } } @Override public int hashCode() { return table == null ? colname.hashCode() : table.hashCode() + colname.hashCode(); } @Override public boolean equals(Object other) { if (other == this) { return true; } if (other instanceof SysColumn) { SysColumn col = (SysColumn) other; return col.table == this.table && col.colname.equals(this.colname); } else { return false; } } /* * This function will fire up query the database allowing it to get * information on its selectivity */ public void setSelectivity(double selectivity) { this.selectivity = selectivity; } /** * Returns the column length in bytes */ public int getColumnLength() { int colLength; switch (this.coltype) { case java.sql.Types.BIT: colLength = 1; break; case java.sql.Types.CHAR: colLength = this.collength; break; case java.sql.Types.VARCHAR: - colLength = this.collength / 3; + colLength = this.collength; break; case java.sql.Types.SMALLINT: colLength = 2; break; case java.sql.Types.INTEGER: colLength = 4; break; case java.sql.Types.DECIMAL: colLength = 4; // should be ok? break; case java.sql.Types.NUMERIC: colLength = 4; // should be ok? break; case java.sql.Types.REAL: colLength = 8; break; case java.sql.Types.FLOAT: colLength = 8; break; case java.sql.Types.DATE: colLength = 2; break; case java.sql.Types.TIME: colLength = 2; break; case java.sql.Types.TIMESTAMP: colLength = 4; break; case java.sql.Types.DOUBLE: colLength = 8; break; case java.sql.Types.BOOLEAN: colLength = 1; break; default: colLength = 0; // throw new XDBServerException // (ErrorMessageRepository.INVALID_DATATYPE + "(" + type + " )" // ,0,ErrorMessageRepository.INVALID_DATATYPE_CODE); } return colLength; } /** * Note that this column appears in an index * * SysIndex - the index it appears in columnPos - the ordinal position of * the column within the index */ public void addIndexUsage(SysIndex aSysIndex, int columnPos) { // Also track the "best index" to use when accessing via // this column if (indexUsage == null || columnPos < bestIndexColPos || (columnPos == bestIndexColPos && aSysIndex.estRowsPerPage < bestIndexRowsPerPage)) { bestIndex = aSysIndex; bestIndexColPos = columnPos; bestIndexRowsPerPage = aSysIndex.estRowsPerPage; } if (indexUsage == null) { indexUsage = new Vector<SysIndex>(); } indexUsage.add(aSysIndex); } /** * This function will return the default value For present we use the native * column definition later on we will use a modified system generated column * definition. * * @return the native column definition */ public String getColumnDefinition() { return nativecoldef; } /** * This function is supposed to give back information on if it has a default * value set */ public boolean hasDefault() { if (defaultExpr == null || defaultExpr.equals("null")) { return false; } else { return true; } } public SysTable getSysTable() { return table; } /** * @return Returns the colid. */ public int getColID() { return colid; } /** * @return Returns the colseq. */ public int getColSeq() { return colseq; } /** * @return Returns the colname. */ public String getColName() { return colname; } /** * @return Returns the coltype. */ public int getColType() { return coltype; } /** * @return Returns the collength. */ public int getColLength() { // It is expected that column length for Numeric equals to precision return collength == 0 ? colprecision : collength; } /** * @return Returns the colscale. */ public int getColScale() { return colscale; } /** * @return Returns the colprecision. */ public int getColPrecision() { return colprecision; } /** * @return Returns the isnullable. */ public boolean isNullable() { return isnullable; } /** * @return Returns the isserial. */ public boolean isSerial() { return isserial; } /** * @return Returns the nativecoldef. */ public String getNativeColDef() { return nativecoldef; } /** * @param indextype * The indextype to set. */ public void setIndexType(int indextype) { this.indextype = indextype; } /** * @return Returns the indextype. */ public int getIndexType() { return indextype; } /** * @return Returns the selectivity. */ public double getSelectivity() { return selectivity; } /** * @return Returns the defaultExpr. */ public String getDefaultExpr() { return defaultExprStr; } /** * Return default expression for the column as an SqlExpression * @param client * @return * @throws XDBGeneratorException */ public SqlExpression getDefaultExpr(XDBSessionContext client) throws XDBGeneratorException { if (isserial) { return new SqlExpression("" + table.getSerialHandler().allocateRange(1, client), new ExpressionType(this)); } else if (SqlCreateTableColumn.XROWID_NAME.equals(colname)) { return new SqlExpression("" + table.getRowIDHandler().allocateRange(1, client), new ExpressionType(this)); } else if (defaultExpr == null) { if (defaultExprStr == null || defaultExprStr.trim().length() == 0) { return null; } Parser parser = new Parser(client); try { parser.parseStatement("SELECT " + defaultExprStr); SqlSelect select = (SqlSelect) parser.getSqlObject(); List<SqlExpression> projList = select.aQueryTree.getProjectionList(); if (projList.size() == 1) { defaultExpr = projList.get(0); defaultExpr.setExprDataType(new ExpressionType(this)); } } catch (ParseException ex) { throw new XDBServerException( "Failed to parse default expression", ex); } } return defaultExpr; } }
true
true
public int getColumnLength() { int colLength; switch (this.coltype) { case java.sql.Types.BIT: colLength = 1; break; case java.sql.Types.CHAR: colLength = this.collength; break; case java.sql.Types.VARCHAR: colLength = this.collength / 3; break; case java.sql.Types.SMALLINT: colLength = 2; break; case java.sql.Types.INTEGER: colLength = 4; break; case java.sql.Types.DECIMAL: colLength = 4; // should be ok? break; case java.sql.Types.NUMERIC: colLength = 4; // should be ok? break; case java.sql.Types.REAL: colLength = 8; break; case java.sql.Types.FLOAT: colLength = 8; break; case java.sql.Types.DATE: colLength = 2; break; case java.sql.Types.TIME: colLength = 2; break; case java.sql.Types.TIMESTAMP: colLength = 4; break; case java.sql.Types.DOUBLE: colLength = 8; break; case java.sql.Types.BOOLEAN: colLength = 1; break; default: colLength = 0; // throw new XDBServerException // (ErrorMessageRepository.INVALID_DATATYPE + "(" + type + " )" // ,0,ErrorMessageRepository.INVALID_DATATYPE_CODE); } return colLength; }
public int getColumnLength() { int colLength; switch (this.coltype) { case java.sql.Types.BIT: colLength = 1; break; case java.sql.Types.CHAR: colLength = this.collength; break; case java.sql.Types.VARCHAR: colLength = this.collength; break; case java.sql.Types.SMALLINT: colLength = 2; break; case java.sql.Types.INTEGER: colLength = 4; break; case java.sql.Types.DECIMAL: colLength = 4; // should be ok? break; case java.sql.Types.NUMERIC: colLength = 4; // should be ok? break; case java.sql.Types.REAL: colLength = 8; break; case java.sql.Types.FLOAT: colLength = 8; break; case java.sql.Types.DATE: colLength = 2; break; case java.sql.Types.TIME: colLength = 2; break; case java.sql.Types.TIMESTAMP: colLength = 4; break; case java.sql.Types.DOUBLE: colLength = 8; break; case java.sql.Types.BOOLEAN: colLength = 1; break; default: colLength = 0; // throw new XDBServerException // (ErrorMessageRepository.INVALID_DATATYPE + "(" + type + " )" // ,0,ErrorMessageRepository.INVALID_DATATYPE_CODE); } return colLength; }
diff --git a/server-integ/src/test/java/org/apache/directory/server/replication/ClientServerReplicationIT.java b/server-integ/src/test/java/org/apache/directory/server/replication/ClientServerReplicationIT.java index 88f8fcce73..c9f6b71754 100644 --- a/server-integ/src/test/java/org/apache/directory/server/replication/ClientServerReplicationIT.java +++ b/server-integ/src/test/java/org/apache/directory/server/replication/ClientServerReplicationIT.java @@ -1,387 +1,387 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.server.replication; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.apache.directory.server.annotations.CreateLdapServer; import org.apache.directory.server.annotations.CreateTransport; import org.apache.directory.server.core.CoreSession; import org.apache.directory.server.core.DirectoryService; import org.apache.directory.server.core.annotations.CreateDS; import org.apache.directory.server.core.annotations.CreateIndex; import org.apache.directory.server.core.annotations.CreatePartition; import org.apache.directory.server.core.factory.DSAnnotationProcessor; import org.apache.directory.server.core.integ.FrameworkRunner; import org.apache.directory.server.factory.ServerAnnotationProcessor; import org.apache.directory.server.ldap.LdapServer; import org.apache.directory.server.ldap.replication.ReplicationConsumer; import org.apache.directory.server.ldap.replication.SyncReplConsumer; import org.apache.directory.server.ldap.replication.SyncReplRequestHandler; import org.apache.directory.server.ldap.replication.SyncreplConfiguration; import org.apache.directory.shared.ldap.model.entry.DefaultEntry; import org.apache.directory.shared.ldap.model.entry.Entry; import org.apache.directory.shared.ldap.model.message.ModifyRequest; import org.apache.directory.shared.ldap.model.message.ModifyRequestImpl; import org.apache.directory.shared.ldap.model.name.Dn; import org.apache.directory.shared.ldap.model.name.Rdn; import org.apache.directory.shared.ldap.model.schema.SchemaManager; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; /** * Tests for replication subsystem in client-server mode. * * @author <a href="mailto:[email protected]">Apache Directory Project</a> */ public class ClientServerReplicationIT { private static LdapServer providerServer; private static LdapServer consumerServer; private static SchemaManager schemaManager; private static CoreSession providerSession; private static CoreSession consumerSession; private static AtomicInteger entryCount = new AtomicInteger(); @BeforeClass public static void setUp() throws Exception { Class justLoadToSetControlProperties = Class.forName( FrameworkRunner.class.getName() ); startProvider(); startConsumer(); } @AfterClass public static void tearDown() { consumerServer.stop(); providerServer.stop(); } @Test public void testInjectContextEntry() throws Exception { String dn = "dc=example,dc=com"; DefaultEntry entry = new DefaultEntry( schemaManager, dn ); entry.add( "objectClass", "domain" ); entry.add( "dc", "example" ); assertFalse( consumerSession.exists( dn ) ); providerSession.add( entry ); waitAndCompareEntries( entry.getDn() ); } @Test public void testModify() throws Exception { Entry provUser = createEntry(); assertFalse( consumerSession.exists( provUser.getDn() ) ); providerSession.add( provUser ); ModifyRequest modReq = new ModifyRequestImpl(); modReq.setName( provUser.getDn() ); modReq.add( "userPassword", "secret" ); providerSession.modify( modReq ); waitAndCompareEntries( provUser.getDn() ); } @Test public void testModDn() throws Exception { Entry provUser = createEntry(); assertFalse( consumerSession.exists( provUser.getDn() ) ); providerSession.add( provUser ); Dn usersContainer = new Dn( schemaManager, "ou=users,dc=example,dc=com" ); DefaultEntry entry = new DefaultEntry( schemaManager, usersContainer ); entry.add( "objectClass", "organizationalUnit" ); entry.add( "ou", "users" ); providerSession.add( entry ); waitAndCompareEntries( entry.getDn() ); // move Dn userDn = provUser.getDn(); providerSession.move( userDn, usersContainer ); userDn = usersContainer.add( userDn.getRdn() ); waitAndCompareEntries( userDn ); // now try renaming Rdn newName = new Rdn( schemaManager, userDn.getRdn().getName() + "renamed"); providerSession.rename( userDn, newName, true ); userDn = usersContainer.add( newName ); waitAndCompareEntries( userDn ); // now move and rename Dn newParent = usersContainer.getParent(); newName = new Rdn( schemaManager, userDn.getRdn().getName() + "MovedAndRenamed"); providerSession.moveAndRename( userDn, newParent, newName, false ); userDn = newParent.add( newName ); waitAndCompareEntries( userDn ); } @Test public void testDelete() throws Exception { Entry provUser = createEntry(); providerSession.add( provUser ); waitAndCompareEntries( provUser.getDn() ); providerSession.delete( provUser.getDn() ); Thread.sleep( 2000 ); assertFalse( consumerSession.exists( provUser.getDn() ) ); } @Test @Ignore("this test often fails due to a timing issue") public void testRebootConsumer() throws Exception { Entry provUser = createEntry(); providerSession.add( provUser ); waitAndCompareEntries( provUser.getDn() ); consumerServer.stop(); Dn deletedUserDn = provUser.getDn(); providerSession.delete( deletedUserDn ); provUser = createEntry(); Dn addedUserDn = provUser.getDn(); providerSession.add( provUser ); startConsumer(); Thread.sleep( 5000 ); assertFalse( consumerSession.exists( deletedUserDn ) ); waitAndCompareEntries( addedUserDn ); } private void waitAndCompareEntries( Dn dn ) throws Exception { // sleep for 2 sec (twice the refresh interval), just to let the first refresh request succeed Thread.sleep( 2000 ); Entry providerEntry = providerSession.lookup( dn, "*", "+" ); Entry consumerEntry = consumerSession.lookup( dn, "*", "+" ); assertEquals( providerEntry, consumerEntry ); } private Entry createEntry() throws Exception { String user = "user"+ entryCount.incrementAndGet(); String dn = "cn=" + user + ",dc=example,dc=com"; DefaultEntry entry = new DefaultEntry( schemaManager, dn ); entry.add( "objectClass", "person" ); entry.add( "cn", user ); entry.add( "sn", user ); return entry; } @CreateDS(allowAnonAccess = true, name = "provider-replication", partitions = { @CreatePartition( name = "example", suffix = "dc=example,dc=com", indexes = { @CreateIndex(attribute = "objectClass"), @CreateIndex(attribute = "dc"), @CreateIndex(attribute = "ou") }) }) @CreateLdapServer(transports = { @CreateTransport( port=16000, protocol = "LDAP") }) private static void startProvider() throws Exception { Method createProviderMethod = ClientServerReplicationIT.class.getDeclaredMethod( "startProvider" ); CreateDS dsAnnotation = createProviderMethod.getAnnotation( CreateDS.class ); DirectoryService provDirService = DSAnnotationProcessor.createDS( dsAnnotation ); CreateLdapServer serverAnnotation = createProviderMethod.getAnnotation( CreateLdapServer.class ); providerServer = ServerAnnotationProcessor.instantiateLdapServer( serverAnnotation, provDirService, 0 ); providerServer.setReplicationReqHandler( new SyncReplRequestHandler() ); Runnable r = new Runnable() { public void run() { try { providerServer.start(); schemaManager = providerServer.getDirectoryService().getSchemaManager(); providerSession = providerServer.getDirectoryService().getAdminSession(); } catch( Exception e ) { e.printStackTrace(); } } }; Thread t = new Thread( r ); t.setDaemon( true ); t.start(); t.join(); } @CreateDS(allowAnonAccess = true, name = "consumer-replication", partitions = { @CreatePartition( name = "example", suffix = "dc=example,dc=com", indexes = { @CreateIndex(attribute = "objectClass"), @CreateIndex(attribute = "dc"), @CreateIndex(attribute = "ou") }) }) @CreateLdapServer(transports = { @CreateTransport( port=17000, protocol = "LDAP") }) private static void startConsumer() throws Exception { Method createProviderMethod = ClientServerReplicationIT.class.getDeclaredMethod( "startConsumer" ); CreateDS dsAnnotation = createProviderMethod.getAnnotation( CreateDS.class ); DirectoryService provDirService = DSAnnotationProcessor.createDS( dsAnnotation ); CreateLdapServer serverAnnotation = createProviderMethod.getAnnotation( CreateLdapServer.class ); consumerServer = ServerAnnotationProcessor.instantiateLdapServer( serverAnnotation, provDirService, 0 ); SyncReplConsumer syncreplClient = new SyncReplConsumer(); final SyncreplConfiguration config = new SyncreplConfiguration(); config.setProviderHost( "localhost" ); config.setPort( 16000 ); config.setReplUserDn( "uid=admin,ou=system" ); config.setReplUserPassword( "secret".getBytes() ); config.setUseTls( false ); config.setBaseDn( "dc=example,dc=com" ); config.setRefreshInterval( 1000 ); syncreplClient.setConfig( config ); List<ReplicationConsumer> replConsumers = new ArrayList<ReplicationConsumer>(); replConsumers.add( syncreplClient ); consumerServer.setReplConsumers( replConsumers ); Runnable r = new Runnable() { public void run() { try { consumerServer.start(); DirectoryService ds = consumerServer.getDirectoryService(); - Dn configDn = new Dn( ds.getSchemaManager(), "ads-replProviderId=localhost,ou=system" ); + Dn configDn = new Dn( ds.getSchemaManager(), "ads-replConsumerId=localhost,ou=system" ); config.setConfigEntryDn( configDn ); Entry provConfigEntry = new DefaultEntry( ds.getSchemaManager(), configDn ); provConfigEntry.add( "objectClass", "ads-replConsumer" ); - provConfigEntry.add( "ads-replProviderId", "localhost" ); + provConfigEntry.add( "ads-replConsumerId", "localhost" ); provConfigEntry.add( "ads-searchBaseDN", config.getBaseDn() ); provConfigEntry.add( "ads-replProvHostName", config.getProviderHost() ); provConfigEntry.add( "ads-replProvPort", String.valueOf( config.getPort() ) ); provConfigEntry.add( "ads-replAliasDerefMode", config.getAliasDerefMode().getJndiValue() ); provConfigEntry.add( "ads-replAttributes", config.getAttributes() ); provConfigEntry.add( "ads-replRefreshInterval", String.valueOf( config.getRefreshInterval() ) ); provConfigEntry.add( "ads-replRefreshNPersist", String.valueOf( config.isRefreshNPersist() ) ); provConfigEntry.add( "ads-replSearchScope", config.getSearchScope().getLdapUrlValue() ); provConfigEntry.add( "ads-replSearchFilter", config.getFilter() ); provConfigEntry.add( "ads-replSearchSizeLimit", String.valueOf( config.getSearchSizeLimit() ) ); provConfigEntry.add( "ads-replSearchTimeOut", String.valueOf( config.getSearchTimeout() ) ); provConfigEntry.add( "ads-replUserDn", config.getReplUserDn() ); provConfigEntry.add( "ads-replUserPassword", config.getReplUserPassword() ); consumerSession = consumerServer.getDirectoryService().getAdminSession(); consumerSession.add( provConfigEntry ); } catch( Exception e ) { e.printStackTrace(); } } }; Thread t = new Thread( r ); t.setDaemon( true ); t.start(); t.join(); } }
false
true
private static void startConsumer() throws Exception { Method createProviderMethod = ClientServerReplicationIT.class.getDeclaredMethod( "startConsumer" ); CreateDS dsAnnotation = createProviderMethod.getAnnotation( CreateDS.class ); DirectoryService provDirService = DSAnnotationProcessor.createDS( dsAnnotation ); CreateLdapServer serverAnnotation = createProviderMethod.getAnnotation( CreateLdapServer.class ); consumerServer = ServerAnnotationProcessor.instantiateLdapServer( serverAnnotation, provDirService, 0 ); SyncReplConsumer syncreplClient = new SyncReplConsumer(); final SyncreplConfiguration config = new SyncreplConfiguration(); config.setProviderHost( "localhost" ); config.setPort( 16000 ); config.setReplUserDn( "uid=admin,ou=system" ); config.setReplUserPassword( "secret".getBytes() ); config.setUseTls( false ); config.setBaseDn( "dc=example,dc=com" ); config.setRefreshInterval( 1000 ); syncreplClient.setConfig( config ); List<ReplicationConsumer> replConsumers = new ArrayList<ReplicationConsumer>(); replConsumers.add( syncreplClient ); consumerServer.setReplConsumers( replConsumers ); Runnable r = new Runnable() { public void run() { try { consumerServer.start(); DirectoryService ds = consumerServer.getDirectoryService(); Dn configDn = new Dn( ds.getSchemaManager(), "ads-replProviderId=localhost,ou=system" ); config.setConfigEntryDn( configDn ); Entry provConfigEntry = new DefaultEntry( ds.getSchemaManager(), configDn ); provConfigEntry.add( "objectClass", "ads-replConsumer" ); provConfigEntry.add( "ads-replProviderId", "localhost" ); provConfigEntry.add( "ads-searchBaseDN", config.getBaseDn() ); provConfigEntry.add( "ads-replProvHostName", config.getProviderHost() ); provConfigEntry.add( "ads-replProvPort", String.valueOf( config.getPort() ) ); provConfigEntry.add( "ads-replAliasDerefMode", config.getAliasDerefMode().getJndiValue() ); provConfigEntry.add( "ads-replAttributes", config.getAttributes() ); provConfigEntry.add( "ads-replRefreshInterval", String.valueOf( config.getRefreshInterval() ) ); provConfigEntry.add( "ads-replRefreshNPersist", String.valueOf( config.isRefreshNPersist() ) ); provConfigEntry.add( "ads-replSearchScope", config.getSearchScope().getLdapUrlValue() ); provConfigEntry.add( "ads-replSearchFilter", config.getFilter() ); provConfigEntry.add( "ads-replSearchSizeLimit", String.valueOf( config.getSearchSizeLimit() ) ); provConfigEntry.add( "ads-replSearchTimeOut", String.valueOf( config.getSearchTimeout() ) ); provConfigEntry.add( "ads-replUserDn", config.getReplUserDn() ); provConfigEntry.add( "ads-replUserPassword", config.getReplUserPassword() ); consumerSession = consumerServer.getDirectoryService().getAdminSession(); consumerSession.add( provConfigEntry ); } catch( Exception e ) { e.printStackTrace(); } } }; Thread t = new Thread( r ); t.setDaemon( true ); t.start(); t.join(); }
private static void startConsumer() throws Exception { Method createProviderMethod = ClientServerReplicationIT.class.getDeclaredMethod( "startConsumer" ); CreateDS dsAnnotation = createProviderMethod.getAnnotation( CreateDS.class ); DirectoryService provDirService = DSAnnotationProcessor.createDS( dsAnnotation ); CreateLdapServer serverAnnotation = createProviderMethod.getAnnotation( CreateLdapServer.class ); consumerServer = ServerAnnotationProcessor.instantiateLdapServer( serverAnnotation, provDirService, 0 ); SyncReplConsumer syncreplClient = new SyncReplConsumer(); final SyncreplConfiguration config = new SyncreplConfiguration(); config.setProviderHost( "localhost" ); config.setPort( 16000 ); config.setReplUserDn( "uid=admin,ou=system" ); config.setReplUserPassword( "secret".getBytes() ); config.setUseTls( false ); config.setBaseDn( "dc=example,dc=com" ); config.setRefreshInterval( 1000 ); syncreplClient.setConfig( config ); List<ReplicationConsumer> replConsumers = new ArrayList<ReplicationConsumer>(); replConsumers.add( syncreplClient ); consumerServer.setReplConsumers( replConsumers ); Runnable r = new Runnable() { public void run() { try { consumerServer.start(); DirectoryService ds = consumerServer.getDirectoryService(); Dn configDn = new Dn( ds.getSchemaManager(), "ads-replConsumerId=localhost,ou=system" ); config.setConfigEntryDn( configDn ); Entry provConfigEntry = new DefaultEntry( ds.getSchemaManager(), configDn ); provConfigEntry.add( "objectClass", "ads-replConsumer" ); provConfigEntry.add( "ads-replConsumerId", "localhost" ); provConfigEntry.add( "ads-searchBaseDN", config.getBaseDn() ); provConfigEntry.add( "ads-replProvHostName", config.getProviderHost() ); provConfigEntry.add( "ads-replProvPort", String.valueOf( config.getPort() ) ); provConfigEntry.add( "ads-replAliasDerefMode", config.getAliasDerefMode().getJndiValue() ); provConfigEntry.add( "ads-replAttributes", config.getAttributes() ); provConfigEntry.add( "ads-replRefreshInterval", String.valueOf( config.getRefreshInterval() ) ); provConfigEntry.add( "ads-replRefreshNPersist", String.valueOf( config.isRefreshNPersist() ) ); provConfigEntry.add( "ads-replSearchScope", config.getSearchScope().getLdapUrlValue() ); provConfigEntry.add( "ads-replSearchFilter", config.getFilter() ); provConfigEntry.add( "ads-replSearchSizeLimit", String.valueOf( config.getSearchSizeLimit() ) ); provConfigEntry.add( "ads-replSearchTimeOut", String.valueOf( config.getSearchTimeout() ) ); provConfigEntry.add( "ads-replUserDn", config.getReplUserDn() ); provConfigEntry.add( "ads-replUserPassword", config.getReplUserPassword() ); consumerSession = consumerServer.getDirectoryService().getAdminSession(); consumerSession.add( provConfigEntry ); } catch( Exception e ) { e.printStackTrace(); } } }; Thread t = new Thread( r ); t.setDaemon( true ); t.start(); t.join(); }
diff --git a/plugins/org.eclipse.emf.eef.runtime/src/org/eclipse/emf/eef/runtime/ui/widgets/settings/EEFEditorSettingsBuilder.java b/plugins/org.eclipse.emf.eef.runtime/src/org/eclipse/emf/eef/runtime/ui/widgets/settings/EEFEditorSettingsBuilder.java index 45a2c48c0..19308159a 100644 --- a/plugins/org.eclipse.emf.eef.runtime/src/org/eclipse/emf/eef/runtime/ui/widgets/settings/EEFEditorSettingsBuilder.java +++ b/plugins/org.eclipse.emf.eef.runtime/src/org/eclipse/emf/eef/runtime/ui/widgets/settings/EEFEditorSettingsBuilder.java @@ -1,317 +1,318 @@ /******************************************************************************* * Copyright (c) 2008, 2012 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 org.eclipse.emf.eef.runtime.ui.widgets.settings; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.eef.runtime.impl.utils.EEFUtils; /** * @author glefur * @since 1.0 * */ public class EEFEditorSettingsBuilder { private EObject source; private EStructuralFeature feature; private List<NavigationStep> steps; /** * @param source * @param feature * @return a new instance of {@link EEFEditorSettingsBuilder}. */ public static EEFEditorSettingsBuilder create(EObject source, EStructuralFeature feature) { return new EEFEditorSettingsBuilder(source, feature); } /** * @param source * @param feature */ private EEFEditorSettingsBuilder(EObject source, EStructuralFeature feature) { this.source = source; this.feature = feature; steps = new ArrayList<NavigationStep>(); } /** * @param step * @return */ public EEFEditorSettingsBuilder nextStep(NavigationStep step) { steps.add(step); return this; } /** * @return */ public EEFEditorSettings build() { for (NavigationStep step : steps) { if (step.getReference().isMany() && step.getIndex() == NavigationStep.NOT_INITIALIZED) { throw new IllegalStateException("Navigation step misconfigured : Reference " + step.getReference().getName() + " is mulivalued. You must define an index."); } } return new EEFEditorSettingsImpl(source, feature, (List<NavigationStep>) Collections.unmodifiableList(steps)); } /** * @author glefur * */ public class EEFEditorSettingsImpl implements EEFEditorSettings { private EObject source; private EStructuralFeature feature; private List<NavigationStep> steps; private EObject significantObject; private EEFEditorSettingsImpl(EObject source, EStructuralFeature feature, List<NavigationStep> steps) { this.source = source; this.feature = feature; this.steps = steps; } /** * {@inheritDoc} * @see org.eclipse.emf.eef.runtime.ui.widgets.settings.EEFEditorSettings#getValue() */ public Object getValue() { EObject significantObject = getSignificantObject(); if (significantObject != null && significantObject.eResource() != null) { return significantObject.eGet(feature); } else { return null; } } /** * Compute and cache the object to edit following the NavigationStep. * @return object to edit. */ public EObject getSignificantObject() { if (significantObject == null) { EObject current = source; for (NavigationStep step : EEFEditorSettingsImpl.this.steps) { // reference * if (step.getReference().isMany()) { @SuppressWarnings("unchecked") List<EObject> result = (List<EObject>)current.eGet(step.getReference()); List<EObject> result2 = new ArrayList<EObject>(); if (!result.isEmpty() && (!step.getFilters().isEmpty() || step.getDiscriminator() != null)) { // add filters if (!step.getFilters().isEmpty()) { for (EEFFilter eefFilter : step.getFilters()) { for (EObject eObject : result) { if (eefFilter.select(eObject)) { result2.add(eObject); } } result = result2; result2 = new ArrayList<EObject>(); } } // add discriminator if (step.getDiscriminator() != null) { for (EObject eObject : result) { if (step.getDiscriminator().isInstance(eObject)) { result2.add(eObject); } } } } // Use init if result.isEmpty() if (result.isEmpty()) { return null; } if (step.getIndex() != NavigationStep.NOT_INITIALIZED && step.getIndex() < result.size()) { current = result.get(step.getIndex()); // Use init if current == null if (current == null) { return null; } } else { throw new IllegalStateException(); } } else { // reference 0 or 1 EObject current2 = current; current = (EObject) current2.eGet(step.getReference()); if (current == null) { return null; } } } significantObject = current; } return significantObject; } /** * Compute and cache the object to edit following the NavigationStep. * @return object to edit. */ public EObject getOrCreateSignificantObject() { if (significantObject == null) { EObject current = source; for (NavigationStep step : EEFEditorSettingsImpl.this.steps) { // reference * if (step.getReference().isMany()) { @SuppressWarnings("unchecked") List<EObject> result = (List<EObject>)current.eGet(step.getReference()); List<EObject> result2 = new ArrayList<EObject>(); if (!result.isEmpty() && (!step.getFilters().isEmpty() || step.getDiscriminator() != null)) { // add filters if (!step.getFilters().isEmpty()) { for (EEFFilter eefFilter : step.getFilters()) { for (EObject eObject : result) { if (eefFilter.select(eObject)) { result2.add(eObject); } } result = result2; result2 = new ArrayList<EObject>(); } } // add discriminator if (step.getDiscriminator() != null) { for (EObject eObject : result) { if (step.getDiscriminator().isInstance(eObject)) { result2.add(eObject); } } + result = result2; + result2 = new ArrayList<EObject>(); } // no filter and no discriminator -> get step.reference - } else { - result2 = result; +// } else { +// result2 = result; } // Use init if result.isEmpty() - if (result2.isEmpty() && step.getInit() != null) { - result2 = new ArrayList<EObject>(); - result2.add(step.getInit().init(current)); + if (result.isEmpty() && step.getInit() != null) { + result.add(step.getInit().init(current)); } - if (step.getIndex() != NavigationStep.NOT_INITIALIZED && step.getIndex() < result2.size()) { - current = result2.get(step.getIndex()); + if (step.getIndex() != NavigationStep.NOT_INITIALIZED && step.getIndex() < result.size()) { + current = result.get(step.getIndex()); // Use init if current == null if (current == null && step.getInit() != null) { EObject current2 = current; current = step.getInit().init(current2); } } else { throw new IllegalStateException(); } } else { // reference 0 or 1 EObject current2 = current; current = (EObject) current2.eGet(step.getReference()); if (current == null) { if (step.getInit() != null) { current = step.getInit().init(current2); } } } } significantObject = current; } return significantObject; } public void setValue(Object newValue) { getOrCreateSignificantObject().eSet(feature, newValue); } /** * {@inheritDoc} * @see org.eclipse.emf.eef.runtime.ui.widgets.settings.EEFEditorSettings#choiceOfValues(org.eclipse.emf.common.notify.AdapterFactory) */ public Object choiceOfValues(AdapterFactory adapterFactory) { return feature instanceof EReference ? EEFUtils.choiceOfValues(source, feature) : null; } /** * {@inheritDoc} * @see org.eclipse.emf.eef.runtime.ui.widgets.settings.EEFEditorSettings#isAffectingFeature(org.eclipse.emf.ecore.EStructuralFeature) */ public boolean isAffectingFeature(EStructuralFeature feature) { for (NavigationStep step : EEFEditorSettingsImpl.this.steps) { if (step.getReference().equals(feature)) { return true; } } return false; } /** * {@inheritDoc} * @see org.eclipse.emf.eef.runtime.ui.widgets.settings.EEFEditorSettings#isAffectingEvent(org.eclipse.emf.common.notify.Notification) */ public boolean isAffectingEvent(Notification notification) { if ( (notification.getFeature() instanceof EStructuralFeature && isAffectingFeature((EStructuralFeature) notification.getFeature())) || (getSignificantObject()!= null && getSignificantObject().equals(notification.getNotifier()))) { return true; } return false; } /** * {@inheritDoc} * @see org.eclipse.emf.eef.runtime.ui.widgets.settings.EEFEditorSettings#getSource() */ public EObject getSource() { return source; } /** * {@inheritDoc} * @see org.eclipse.emf.eef.runtime.ui.widgets.settings.EEFEditorSettings#getEType() */ public EClassifier getEType() { return feature.getEType(); } /** * {@inheritDoc} * @see org.eclipse.emf.eef.runtime.ui.widgets.settings.EEFEditorSettings#getLastReference() */ public EReference getLastReference() { if (feature instanceof EReference) { return (EReference) feature; } else if (EEFEditorSettingsImpl.this.steps.size() > 0) { return EEFEditorSettingsImpl.this.steps.get(EEFEditorSettingsImpl.this.steps.size() - 1).getReference(); } return null; } } }
false
true
public EObject getOrCreateSignificantObject() { if (significantObject == null) { EObject current = source; for (NavigationStep step : EEFEditorSettingsImpl.this.steps) { // reference * if (step.getReference().isMany()) { @SuppressWarnings("unchecked") List<EObject> result = (List<EObject>)current.eGet(step.getReference()); List<EObject> result2 = new ArrayList<EObject>(); if (!result.isEmpty() && (!step.getFilters().isEmpty() || step.getDiscriminator() != null)) { // add filters if (!step.getFilters().isEmpty()) { for (EEFFilter eefFilter : step.getFilters()) { for (EObject eObject : result) { if (eefFilter.select(eObject)) { result2.add(eObject); } } result = result2; result2 = new ArrayList<EObject>(); } } // add discriminator if (step.getDiscriminator() != null) { for (EObject eObject : result) { if (step.getDiscriminator().isInstance(eObject)) { result2.add(eObject); } } } // no filter and no discriminator -> get step.reference } else { result2 = result; } // Use init if result.isEmpty() if (result2.isEmpty() && step.getInit() != null) { result2 = new ArrayList<EObject>(); result2.add(step.getInit().init(current)); } if (step.getIndex() != NavigationStep.NOT_INITIALIZED && step.getIndex() < result2.size()) { current = result2.get(step.getIndex()); // Use init if current == null if (current == null && step.getInit() != null) { EObject current2 = current; current = step.getInit().init(current2); } } else { throw new IllegalStateException(); } } else { // reference 0 or 1 EObject current2 = current; current = (EObject) current2.eGet(step.getReference()); if (current == null) { if (step.getInit() != null) { current = step.getInit().init(current2); } } } } significantObject = current; } return significantObject; }
public EObject getOrCreateSignificantObject() { if (significantObject == null) { EObject current = source; for (NavigationStep step : EEFEditorSettingsImpl.this.steps) { // reference * if (step.getReference().isMany()) { @SuppressWarnings("unchecked") List<EObject> result = (List<EObject>)current.eGet(step.getReference()); List<EObject> result2 = new ArrayList<EObject>(); if (!result.isEmpty() && (!step.getFilters().isEmpty() || step.getDiscriminator() != null)) { // add filters if (!step.getFilters().isEmpty()) { for (EEFFilter eefFilter : step.getFilters()) { for (EObject eObject : result) { if (eefFilter.select(eObject)) { result2.add(eObject); } } result = result2; result2 = new ArrayList<EObject>(); } } // add discriminator if (step.getDiscriminator() != null) { for (EObject eObject : result) { if (step.getDiscriminator().isInstance(eObject)) { result2.add(eObject); } } result = result2; result2 = new ArrayList<EObject>(); } // no filter and no discriminator -> get step.reference // } else { // result2 = result; } // Use init if result.isEmpty() if (result.isEmpty() && step.getInit() != null) { result.add(step.getInit().init(current)); } if (step.getIndex() != NavigationStep.NOT_INITIALIZED && step.getIndex() < result.size()) { current = result.get(step.getIndex()); // Use init if current == null if (current == null && step.getInit() != null) { EObject current2 = current; current = step.getInit().init(current2); } } else { throw new IllegalStateException(); } } else { // reference 0 or 1 EObject current2 = current; current = (EObject) current2.eGet(step.getReference()); if (current == null) { if (step.getInit() != null) { current = step.getInit().init(current2); } } } } significantObject = current; } return significantObject; }
diff --git a/odata-testutil/src/test/java/com/sap/core/odata/testutil/server/TestServer.java b/odata-testutil/src/test/java/com/sap/core/odata/testutil/server/TestServer.java index 9080cbe41..c15169759 100644 --- a/odata-testutil/src/test/java/com/sap/core/odata/testutil/server/TestServer.java +++ b/odata-testutil/src/test/java/com/sap/core/odata/testutil/server/TestServer.java @@ -1,119 +1,119 @@ package com.sap.core.odata.testutil.server; import java.net.BindException; import java.net.InetSocketAddress; import java.net.URI; import org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet; import org.apache.log4j.Logger; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import com.sap.core.odata.api.ODataService; import com.sap.core.odata.api.ODataServiceFactory; import com.sap.core.odata.testutil.fit.FitStaticServiceFactory; /** * @author SAP AG */ public class TestServer { private static final Logger log = Logger.getLogger(TestServer.class); private static final int PORT_MIN = 19000; private static final int PORT_MAX = 19200; private static final int PORT_INC = 1; private static final String DEFAULT_SCHEME = "http"; private static final String DEFAULT_HOST = "localhost"; private static final String DEFAULT_PATH = "/test"; private URI endpoint; //= URI.create("http://localhost:19080/test"); // no slash at the end !!! private final String path; private int pathSplit = 0; public TestServer() { this(DEFAULT_PATH); } public TestServer(final String path) { if (path.startsWith("/")) { this.path = path; } else { this.path = "/" + path; } } public int getPathSplit() { return pathSplit; } public void setPathSplit(final int pathSplit) { this.pathSplit = pathSplit; } public URI getEndpoint() { return URI.create(endpoint + "/"); } private Server server; public void startServer(final Class<? extends ODataServiceFactory> factoryClass) { try { for (int port = PORT_MIN; port <= PORT_MAX; port += PORT_INC) { final CXFNonSpringJaxrsServlet odataServlet = new CXFNonSpringJaxrsServlet(); final ServletHolder odataServletHolder = new ServletHolder(odataServlet); odataServletHolder.setInitParameter("javax.ws.rs.Application", "com.sap.core.odata.core.rest.app.ODataApplication"); odataServletHolder.setInitParameter(ODataServiceFactory.FACTORY_LABEL, factoryClass.getCanonicalName()); if (pathSplit > 0) { odataServletHolder.setInitParameter(ODataServiceFactory.PATH_SPLIT_LABEL, Integer.toString(pathSplit)); } final ServletContextHandler contextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS); contextHandler.addServlet(odataServletHolder, path + "/*"); try { final InetSocketAddress isa = new InetSocketAddress(DEFAULT_HOST, port); server = new Server(isa); server.setHandler(contextHandler); server.start(); endpoint = new URI(DEFAULT_SCHEME, null, DEFAULT_HOST, isa.getPort(), path, null, null); log.trace("Started server at endpoint " + endpoint.toASCIIString()); break; } catch (final BindException e) { log.trace("port is busy... " + port + " [" + e.getMessage() + "]"); } } if (!server.isStarted()) { throw new BindException("no free port in range of [" + PORT_MIN + ".." + PORT_MAX + "]"); } - } catch (final Throwable e) { + } catch (final Exception e) { log.error(e); new RuntimeException(e); } } public void startServer(final ODataService service) { startServer(FitStaticServiceFactory.class); if ((server != null) && server.isStarted()) { FitStaticServiceFactory.bindService(this, service); } } public void stopServer() { try { if (server != null) { FitStaticServiceFactory.unbindService(this); server.stop(); log.trace("Stopped server at endpoint " + getEndpoint().toASCIIString()); } } catch (final Exception e) { throw new ServerException(e); } } }
true
true
public void startServer(final Class<? extends ODataServiceFactory> factoryClass) { try { for (int port = PORT_MIN; port <= PORT_MAX; port += PORT_INC) { final CXFNonSpringJaxrsServlet odataServlet = new CXFNonSpringJaxrsServlet(); final ServletHolder odataServletHolder = new ServletHolder(odataServlet); odataServletHolder.setInitParameter("javax.ws.rs.Application", "com.sap.core.odata.core.rest.app.ODataApplication"); odataServletHolder.setInitParameter(ODataServiceFactory.FACTORY_LABEL, factoryClass.getCanonicalName()); if (pathSplit > 0) { odataServletHolder.setInitParameter(ODataServiceFactory.PATH_SPLIT_LABEL, Integer.toString(pathSplit)); } final ServletContextHandler contextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS); contextHandler.addServlet(odataServletHolder, path + "/*"); try { final InetSocketAddress isa = new InetSocketAddress(DEFAULT_HOST, port); server = new Server(isa); server.setHandler(contextHandler); server.start(); endpoint = new URI(DEFAULT_SCHEME, null, DEFAULT_HOST, isa.getPort(), path, null, null); log.trace("Started server at endpoint " + endpoint.toASCIIString()); break; } catch (final BindException e) { log.trace("port is busy... " + port + " [" + e.getMessage() + "]"); } } if (!server.isStarted()) { throw new BindException("no free port in range of [" + PORT_MIN + ".." + PORT_MAX + "]"); } } catch (final Throwable e) { log.error(e); new RuntimeException(e); } }
public void startServer(final Class<? extends ODataServiceFactory> factoryClass) { try { for (int port = PORT_MIN; port <= PORT_MAX; port += PORT_INC) { final CXFNonSpringJaxrsServlet odataServlet = new CXFNonSpringJaxrsServlet(); final ServletHolder odataServletHolder = new ServletHolder(odataServlet); odataServletHolder.setInitParameter("javax.ws.rs.Application", "com.sap.core.odata.core.rest.app.ODataApplication"); odataServletHolder.setInitParameter(ODataServiceFactory.FACTORY_LABEL, factoryClass.getCanonicalName()); if (pathSplit > 0) { odataServletHolder.setInitParameter(ODataServiceFactory.PATH_SPLIT_LABEL, Integer.toString(pathSplit)); } final ServletContextHandler contextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS); contextHandler.addServlet(odataServletHolder, path + "/*"); try { final InetSocketAddress isa = new InetSocketAddress(DEFAULT_HOST, port); server = new Server(isa); server.setHandler(contextHandler); server.start(); endpoint = new URI(DEFAULT_SCHEME, null, DEFAULT_HOST, isa.getPort(), path, null, null); log.trace("Started server at endpoint " + endpoint.toASCIIString()); break; } catch (final BindException e) { log.trace("port is busy... " + port + " [" + e.getMessage() + "]"); } } if (!server.isStarted()) { throw new BindException("no free port in range of [" + PORT_MIN + ".." + PORT_MAX + "]"); } } catch (final Exception e) { log.error(e); new RuntimeException(e); } }
diff --git a/src/jp/ac/osaka_u/ist/sdl/ectec/analyzer/sourceanalyzer/CodeFragmentDetectingThreadMonitor.java b/src/jp/ac/osaka_u/ist/sdl/ectec/analyzer/sourceanalyzer/CodeFragmentDetectingThreadMonitor.java index 0c39ce4..8131bed 100644 --- a/src/jp/ac/osaka_u/ist/sdl/ectec/analyzer/sourceanalyzer/CodeFragmentDetectingThreadMonitor.java +++ b/src/jp/ac/osaka_u/ist/sdl/ectec/analyzer/sourceanalyzer/CodeFragmentDetectingThreadMonitor.java @@ -1,126 +1,126 @@ package jp.ac.osaka_u.ist.sdl.ectec.analyzer.sourceanalyzer; import java.util.Collection; import java.util.concurrent.ConcurrentMap; import jp.ac.osaka_u.ist.sdl.ectec.data.CRD; import jp.ac.osaka_u.ist.sdl.ectec.data.CodeFragmentInfo; import jp.ac.osaka_u.ist.sdl.ectec.data.registerer.CRDRegisterer; import jp.ac.osaka_u.ist.sdl.ectec.data.registerer.CodeFragmentRegisterer; import jp.ac.osaka_u.ist.sdl.ectec.settings.Constants; import jp.ac.osaka_u.ist.sdl.ectec.settings.MessagePrinter; /** * A monitor class for code fragment detecting threads * * @author k-hotta * */ public class CodeFragmentDetectingThreadMonitor { /** * a map having detected crds */ private final ConcurrentMap<Long, CRD> detectedCrds; /** * a map having detected fragments */ private final ConcurrentMap<Long, CodeFragmentInfo> detectedFragments; /** * the threshold for elements <br> * if the number of stored elements exceeds this threshold, then this * monitor interrupts the other threads and register elements into db with * the registered elements removed from the map */ private final int maxElementsCount; /** * the registerer for crds */ private final CRDRegisterer crdRegisterer; /** * the registerer for code fragments */ private final CodeFragmentRegisterer fragmentRegisterer; public CodeFragmentDetectingThreadMonitor( final ConcurrentMap<Long, CRD> detectedCrds, final ConcurrentMap<Long, CodeFragmentInfo> detectedFragments, final int maximumElementsCount, final CRDRegisterer crdRegisterer, final CodeFragmentRegisterer fragmentRegisterer) { this.detectedCrds = detectedCrds; this.detectedFragments = detectedFragments; this.maxElementsCount = maximumElementsCount; this.crdRegisterer = crdRegisterer; this.fragmentRegisterer = fragmentRegisterer; } public void monitor() throws Exception { long numberOfCrds = 0; long numberOfFragments = 0; while (true) { try { Thread.sleep(Constants.MONITORING_INTERVAL); if (detectedCrds.size() >= maxElementsCount) { final Collection<CRD> currentElements = detectedCrds .values(); crdRegisterer.register(currentElements); MessagePrinter.println("\t" + currentElements.size() + " CRDs have been registered into db"); numberOfCrds += currentElements.size(); for (final CRD crd : currentElements) { detectedCrds.remove(crd.getId()); } } if (detectedFragments.size() >= maxElementsCount) { final Collection<CodeFragmentInfo> currentElements = detectedFragments .values(); fragmentRegisterer.register(currentElements); MessagePrinter.println("\t" + currentElements.size() + " fragments have been registered into db"); numberOfFragments += currentElements.size(); for (final CodeFragmentInfo fragment : currentElements) { detectedFragments.remove(fragment.getId()); } } } catch (Exception e) { e.printStackTrace(); } // break this loop if all the other threads have died - if (Thread.activeCount() == 1) { + if (Thread.activeCount() == 2) { break; } } MessagePrinter.println(); MessagePrinter.println("\tall threads have finished their work"); MessagePrinter .println("\tregistering all the remaining elements into db "); crdRegisterer.register(detectedCrds.values()); fragmentRegisterer.register(detectedFragments.values()); numberOfCrds += detectedCrds.size(); numberOfFragments += detectedFragments.size(); MessagePrinter.println("\t\tOK"); MessagePrinter.println(); MessagePrinter.println("the numbers of detected elements are ... "); MessagePrinter.println("\tCRD: " + numberOfCrds); MessagePrinter.println("\tFragment: " + numberOfFragments); } }
true
true
public void monitor() throws Exception { long numberOfCrds = 0; long numberOfFragments = 0; while (true) { try { Thread.sleep(Constants.MONITORING_INTERVAL); if (detectedCrds.size() >= maxElementsCount) { final Collection<CRD> currentElements = detectedCrds .values(); crdRegisterer.register(currentElements); MessagePrinter.println("\t" + currentElements.size() + " CRDs have been registered into db"); numberOfCrds += currentElements.size(); for (final CRD crd : currentElements) { detectedCrds.remove(crd.getId()); } } if (detectedFragments.size() >= maxElementsCount) { final Collection<CodeFragmentInfo> currentElements = detectedFragments .values(); fragmentRegisterer.register(currentElements); MessagePrinter.println("\t" + currentElements.size() + " fragments have been registered into db"); numberOfFragments += currentElements.size(); for (final CodeFragmentInfo fragment : currentElements) { detectedFragments.remove(fragment.getId()); } } } catch (Exception e) { e.printStackTrace(); } // break this loop if all the other threads have died if (Thread.activeCount() == 1) { break; } } MessagePrinter.println(); MessagePrinter.println("\tall threads have finished their work"); MessagePrinter .println("\tregistering all the remaining elements into db "); crdRegisterer.register(detectedCrds.values()); fragmentRegisterer.register(detectedFragments.values()); numberOfCrds += detectedCrds.size(); numberOfFragments += detectedFragments.size(); MessagePrinter.println("\t\tOK"); MessagePrinter.println(); MessagePrinter.println("the numbers of detected elements are ... "); MessagePrinter.println("\tCRD: " + numberOfCrds); MessagePrinter.println("\tFragment: " + numberOfFragments); }
public void monitor() throws Exception { long numberOfCrds = 0; long numberOfFragments = 0; while (true) { try { Thread.sleep(Constants.MONITORING_INTERVAL); if (detectedCrds.size() >= maxElementsCount) { final Collection<CRD> currentElements = detectedCrds .values(); crdRegisterer.register(currentElements); MessagePrinter.println("\t" + currentElements.size() + " CRDs have been registered into db"); numberOfCrds += currentElements.size(); for (final CRD crd : currentElements) { detectedCrds.remove(crd.getId()); } } if (detectedFragments.size() >= maxElementsCount) { final Collection<CodeFragmentInfo> currentElements = detectedFragments .values(); fragmentRegisterer.register(currentElements); MessagePrinter.println("\t" + currentElements.size() + " fragments have been registered into db"); numberOfFragments += currentElements.size(); for (final CodeFragmentInfo fragment : currentElements) { detectedFragments.remove(fragment.getId()); } } } catch (Exception e) { e.printStackTrace(); } // break this loop if all the other threads have died if (Thread.activeCount() == 2) { break; } } MessagePrinter.println(); MessagePrinter.println("\tall threads have finished their work"); MessagePrinter .println("\tregistering all the remaining elements into db "); crdRegisterer.register(detectedCrds.values()); fragmentRegisterer.register(detectedFragments.values()); numberOfCrds += detectedCrds.size(); numberOfFragments += detectedFragments.size(); MessagePrinter.println("\t\tOK"); MessagePrinter.println(); MessagePrinter.println("the numbers of detected elements are ... "); MessagePrinter.println("\tCRD: " + numberOfCrds); MessagePrinter.println("\tFragment: " + numberOfFragments); }
diff --git a/Temp/src/OR/SolutionList.java b/Temp/src/OR/SolutionList.java index faf61cf..0bd146d 100644 --- a/Temp/src/OR/SolutionList.java +++ b/Temp/src/OR/SolutionList.java @@ -1,39 +1,39 @@ package OR; import java.util.LinkedList; /** * * */ public class SolutionList extends LinkedList<Double[]> { private int n; /** * creates a new solution for n variables * @param n number of variables */ public SolutionList(int n) { super(); this.n = n; } /** * adds a new Solution to the SolutionList * warning : you must add a solution with length = n + 1 * @param item the solution to Add * @return true upon insertion * @throws RuntimeException when not adding Double[n+1] */ @Override public boolean add(Double[] item) { if (item.length == n) { super.add(item); return true; } else{ - throw new RuntimeException("item must be Double[" + (n+1) +"]"); + throw new RuntimeException("item must be Double[" + (n) +"]"); } } }
true
true
public boolean add(Double[] item) { if (item.length == n) { super.add(item); return true; } else{ throw new RuntimeException("item must be Double[" + (n+1) +"]"); } }
public boolean add(Double[] item) { if (item.length == n) { super.add(item); return true; } else{ throw new RuntimeException("item must be Double[" + (n) +"]"); } }
diff --git a/src/java/no/schibstedsok/front/searchportal/view/velocity/VelocityEngineFactory.java b/src/java/no/schibstedsok/front/searchportal/view/velocity/VelocityEngineFactory.java index 0ea6782cc..d9fc6a2d9 100644 --- a/src/java/no/schibstedsok/front/searchportal/view/velocity/VelocityEngineFactory.java +++ b/src/java/no/schibstedsok/front/searchportal/view/velocity/VelocityEngineFactory.java @@ -1,171 +1,171 @@ /* Copyright (2005-2006) Schibsted SΓΈk AS * * VelocityEngineFactory.java * * Created on 3 February 2006, 13:24 * */ package no.schibstedsok.front.searchportal.view.velocity; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.xml.parsers.DocumentBuilder; import no.schibstedsok.common.ioc.ContextWrapper; import no.schibstedsok.front.searchportal.InfrastructureException; import no.schibstedsok.front.searchportal.configuration.SiteConfiguration; import no.schibstedsok.front.searchportal.configuration.loader.DocumentLoader; import no.schibstedsok.front.searchportal.configuration.loader.PropertiesLoader; import no.schibstedsok.front.searchportal.configuration.loader.ResourceContext; import no.schibstedsok.front.searchportal.configuration.loader.UrlResourceLoader; import no.schibstedsok.front.searchportal.site.Site; import no.schibstedsok.front.searchportal.site.SiteContext; import no.schibstedsok.front.searchportal.site.SiteKeyedFactory; import no.schibstedsok.front.searchportal.util.SearchConstants; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.velocity.Template; import org.apache.velocity.app.Velocity; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.exception.ParseErrorException; import org.apache.velocity.exception.ResourceNotFoundException; import org.apache.velocity.runtime.RuntimeConstants; /** * @version $Id$ * @author <a href="mailto:[email protected]">Michael Semb Wever</a> */ public final class VelocityEngineFactory implements SiteKeyedFactory{ private static final Logger LOG = Logger.getLogger(VelocityEngineFactory.class); private static final String VELOCITY_LOGGER = "org.apache.velocity"; private static final Map<Site,VelocityEngineFactory> INSTANCES = new HashMap<Site,VelocityEngineFactory>(); private static final ReentrantReadWriteLock INSTANCES_LOCK = new ReentrantReadWriteLock(); private final VelocityEngine engine; /** * The context the AnalysisRules must work against. * */ public interface Context extends SiteContext, ResourceContext { } private final Context context; /** Creates a new instance of VelocityEngineFactory */ private VelocityEngineFactory(final Context cxt) { INSTANCES_LOCK.writeLock().lock(); context = cxt; final Site site = cxt.getSite(); engine = new VelocityEngine(){ /** We override this method to dampen the <ERROR velocity: ResourceManager : unable to find resource ...> * error messages in sesam.error **/ public Template getTemplate(final String name) throws ResourceNotFoundException, ParseErrorException, Exception { final Level level = Logger.getLogger(VELOCITY_LOGGER).getLevel(); Logger.getLogger(VELOCITY_LOGGER).setLevel(Level.FATAL); final Template retValue = super.getTemplate(name); Logger.getLogger(VELOCITY_LOGGER).setLevel(level); return retValue; } }; try { final Logger logger = Logger.getLogger(VELOCITY_LOGGER); final Properties props = SiteConfiguration.valueOf( ContextWrapper.wrap(SiteConfiguration.Context.class, cxt)).getProperties(); // engine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.Log4JLogChute"); // velocity 1.5 engine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.SimpleLog4JLogSystem"); // engine.setProperty("runtime.log.logsystem.log4j.logger", logger.getName()); // velocity 1.5 engine.setProperty("runtime.log.logsystem.log4j.category", logger.getName()); engine.setProperty(Velocity.RESOURCE_LOADER, "url"); engine.setProperty("url.resource.loader.class", "no.schibstedsok.front.searchportal.view.velocity.URLVelocityTemplateLoader"); engine.setProperty("url.resource.loader.cache", "true"); engine.setProperty("url.resource.loader.modificationCheckInterval", "300"); // 5 minute update cycle. engine.setProperty("velocimacro.library", site.getTemplateDir() + "/VM_global_library.vm"); engine.setProperty(Site.NAME_KEY, site); engine.setProperty("site.fallback", Site.DEFAULT); engine.setProperty(SearchConstants.PUBLISH_SYSTEM_URL, props.getProperty(SearchConstants.PUBLISH_SYSTEM_URL)); engine.setProperty(SearchConstants.PUBLISH_SYSTEM_HOST, props.getProperty(SearchConstants.PUBLISH_SYSTEM_HOST)); engine.setProperty("input.encoding", "UTF-8"); engine.setProperty("output.encoding", "UTF-8"); - engine.setProperty("userdirective", "no.schibstedsok.front.searchportal.view.velocity.UrlEncodeDirective,no.schibstedsok.front.searchportal.view.velocity.HtmlEscapeDirective,no.schibstedsok.front.searchportal.view.velocity.CapitalizeWordsDirective,no.schibstedsok.front.searchportal.view.velocity.ChopStringDirective,no.schibstedsok.front.searchportal.view.velocity.PublishDirective,no.schibstedsok.front.searchportal.view.velocity.AccountingDirective,no.schibstedsok.front.searchportal.view.velocity.RolesDirective,no.schibstedsok.front.searchportal.view.velocity.XmlEscapeDirective"); + engine.setProperty("userdirective", "no.schibstedsok.front.searchportal.view.velocity.UrlEncodeDirective,no.schibstedsok.front.searchportal.view.velocity.HtmlEscapeDirective,no.schibstedsok.front.searchportal.view.velocity.CapitalizeWordsDirective,no.schibstedsok.front.searchportal.view.velocity.ChopStringDirective,no.schibstedsok.front.searchportal.view.velocity.PublishDirective,no.schibstedsok.front.searchportal.view.velocity.AccountingDirective,no.schibstedsok.front.searchportal.view.velocity.RolesDirective,no.schibstedsok.front.searchportal.view.velocity.XmlEscapeDirective,no.schibstedsok.front.searchportal.view.velocity.WikiDirective"); engine.init(); } catch (Exception e) { throw new InfrastructureException(e); } INSTANCES.put(site, this); INSTANCES_LOCK.writeLock().unlock(); } public VelocityEngine getEngine() { return engine; } /** Main method to retrieve the correct VelocityEngine to further obtain * AnalysisRule. * @param cxt the contextual needs the VelocityEngine must use to operate. * @return VelocityEngine for this site. */ public static VelocityEngineFactory valueOf(final Context cxt) { final Site site = cxt.getSite(); INSTANCES_LOCK.readLock().lock(); VelocityEngineFactory instance = INSTANCES.get(site); INSTANCES_LOCK.readLock().unlock(); if (instance == null) { instance = new VelocityEngineFactory(cxt); } return instance; } /** * Utility wrapper to the valueOf(Context). * <b>Makes the presumption we will be using the UrlResourceLoader to load all resources.</b> * @param site the site the VelocityEngine will work for. * @return VelocityEngine for this site. */ public static VelocityEngineFactory valueOf(final Site site) { // RegExpEvaluatorFactory.Context for this site & UrlResourceLoader. final VelocityEngineFactory instance = VelocityEngineFactory.valueOf(new VelocityEngineFactory.Context() { public Site getSite() { return site; } public PropertiesLoader newPropertiesLoader(final String resource, final Properties properties) { return UrlResourceLoader.newPropertiesLoader(this, resource, properties); } public DocumentLoader newDocumentLoader(final String resource, final DocumentBuilder builder) { return UrlResourceLoader.newDocumentLoader(this, resource, builder); } }); return instance; } public boolean remove(Site site) { try{ INSTANCES_LOCK.writeLock().lock(); return null != INSTANCES.remove(site); }finally{ INSTANCES_LOCK.writeLock().unlock(); } } }
true
true
private VelocityEngineFactory(final Context cxt) { INSTANCES_LOCK.writeLock().lock(); context = cxt; final Site site = cxt.getSite(); engine = new VelocityEngine(){ /** We override this method to dampen the <ERROR velocity: ResourceManager : unable to find resource ...> * error messages in sesam.error **/ public Template getTemplate(final String name) throws ResourceNotFoundException, ParseErrorException, Exception { final Level level = Logger.getLogger(VELOCITY_LOGGER).getLevel(); Logger.getLogger(VELOCITY_LOGGER).setLevel(Level.FATAL); final Template retValue = super.getTemplate(name); Logger.getLogger(VELOCITY_LOGGER).setLevel(level); return retValue; } }; try { final Logger logger = Logger.getLogger(VELOCITY_LOGGER); final Properties props = SiteConfiguration.valueOf( ContextWrapper.wrap(SiteConfiguration.Context.class, cxt)).getProperties(); // engine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.Log4JLogChute"); // velocity 1.5 engine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.SimpleLog4JLogSystem"); // engine.setProperty("runtime.log.logsystem.log4j.logger", logger.getName()); // velocity 1.5 engine.setProperty("runtime.log.logsystem.log4j.category", logger.getName()); engine.setProperty(Velocity.RESOURCE_LOADER, "url"); engine.setProperty("url.resource.loader.class", "no.schibstedsok.front.searchportal.view.velocity.URLVelocityTemplateLoader"); engine.setProperty("url.resource.loader.cache", "true"); engine.setProperty("url.resource.loader.modificationCheckInterval", "300"); // 5 minute update cycle. engine.setProperty("velocimacro.library", site.getTemplateDir() + "/VM_global_library.vm"); engine.setProperty(Site.NAME_KEY, site); engine.setProperty("site.fallback", Site.DEFAULT); engine.setProperty(SearchConstants.PUBLISH_SYSTEM_URL, props.getProperty(SearchConstants.PUBLISH_SYSTEM_URL)); engine.setProperty(SearchConstants.PUBLISH_SYSTEM_HOST, props.getProperty(SearchConstants.PUBLISH_SYSTEM_HOST)); engine.setProperty("input.encoding", "UTF-8"); engine.setProperty("output.encoding", "UTF-8"); engine.setProperty("userdirective", "no.schibstedsok.front.searchportal.view.velocity.UrlEncodeDirective,no.schibstedsok.front.searchportal.view.velocity.HtmlEscapeDirective,no.schibstedsok.front.searchportal.view.velocity.CapitalizeWordsDirective,no.schibstedsok.front.searchportal.view.velocity.ChopStringDirective,no.schibstedsok.front.searchportal.view.velocity.PublishDirective,no.schibstedsok.front.searchportal.view.velocity.AccountingDirective,no.schibstedsok.front.searchportal.view.velocity.RolesDirective,no.schibstedsok.front.searchportal.view.velocity.XmlEscapeDirective"); engine.init(); } catch (Exception e) { throw new InfrastructureException(e); } INSTANCES.put(site, this); INSTANCES_LOCK.writeLock().unlock(); }
private VelocityEngineFactory(final Context cxt) { INSTANCES_LOCK.writeLock().lock(); context = cxt; final Site site = cxt.getSite(); engine = new VelocityEngine(){ /** We override this method to dampen the <ERROR velocity: ResourceManager : unable to find resource ...> * error messages in sesam.error **/ public Template getTemplate(final String name) throws ResourceNotFoundException, ParseErrorException, Exception { final Level level = Logger.getLogger(VELOCITY_LOGGER).getLevel(); Logger.getLogger(VELOCITY_LOGGER).setLevel(Level.FATAL); final Template retValue = super.getTemplate(name); Logger.getLogger(VELOCITY_LOGGER).setLevel(level); return retValue; } }; try { final Logger logger = Logger.getLogger(VELOCITY_LOGGER); final Properties props = SiteConfiguration.valueOf( ContextWrapper.wrap(SiteConfiguration.Context.class, cxt)).getProperties(); // engine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.Log4JLogChute"); // velocity 1.5 engine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.SimpleLog4JLogSystem"); // engine.setProperty("runtime.log.logsystem.log4j.logger", logger.getName()); // velocity 1.5 engine.setProperty("runtime.log.logsystem.log4j.category", logger.getName()); engine.setProperty(Velocity.RESOURCE_LOADER, "url"); engine.setProperty("url.resource.loader.class", "no.schibstedsok.front.searchportal.view.velocity.URLVelocityTemplateLoader"); engine.setProperty("url.resource.loader.cache", "true"); engine.setProperty("url.resource.loader.modificationCheckInterval", "300"); // 5 minute update cycle. engine.setProperty("velocimacro.library", site.getTemplateDir() + "/VM_global_library.vm"); engine.setProperty(Site.NAME_KEY, site); engine.setProperty("site.fallback", Site.DEFAULT); engine.setProperty(SearchConstants.PUBLISH_SYSTEM_URL, props.getProperty(SearchConstants.PUBLISH_SYSTEM_URL)); engine.setProperty(SearchConstants.PUBLISH_SYSTEM_HOST, props.getProperty(SearchConstants.PUBLISH_SYSTEM_HOST)); engine.setProperty("input.encoding", "UTF-8"); engine.setProperty("output.encoding", "UTF-8"); engine.setProperty("userdirective", "no.schibstedsok.front.searchportal.view.velocity.UrlEncodeDirective,no.schibstedsok.front.searchportal.view.velocity.HtmlEscapeDirective,no.schibstedsok.front.searchportal.view.velocity.CapitalizeWordsDirective,no.schibstedsok.front.searchportal.view.velocity.ChopStringDirective,no.schibstedsok.front.searchportal.view.velocity.PublishDirective,no.schibstedsok.front.searchportal.view.velocity.AccountingDirective,no.schibstedsok.front.searchportal.view.velocity.RolesDirective,no.schibstedsok.front.searchportal.view.velocity.XmlEscapeDirective,no.schibstedsok.front.searchportal.view.velocity.WikiDirective"); engine.init(); } catch (Exception e) { throw new InfrastructureException(e); } INSTANCES.put(site, this); INSTANCES_LOCK.writeLock().unlock(); }
diff --git a/drools-compiler/src/main/java/org/drools/commons/jci/compilers/EclipseJavaCompiler.java b/drools-compiler/src/main/java/org/drools/commons/jci/compilers/EclipseJavaCompiler.java index 636ab777c9..25440a951e 100644 --- a/drools-compiler/src/main/java/org/drools/commons/jci/compilers/EclipseJavaCompiler.java +++ b/drools-compiler/src/main/java/org/drools/commons/jci/compilers/EclipseJavaCompiler.java @@ -1,398 +1,398 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.commons.jci.compilers; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Locale; import java.util.Map; import java.util.StringTokenizer; import org.drools.commons.jci.problems.CompilationProblem; import org.drools.commons.jci.readers.ResourceReader; import org.drools.commons.jci.stores.ResourceStore; import org.drools.core.util.ClassUtils; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.internal.compiler.ClassFile; import org.eclipse.jdt.internal.compiler.CompilationResult; import org.eclipse.jdt.internal.compiler.Compiler; import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies; import org.eclipse.jdt.internal.compiler.ICompilerRequestor; import org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy; import org.eclipse.jdt.internal.compiler.IProblemFactory; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader; import org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException; import org.eclipse.jdt.internal.compiler.env.ICompilationUnit; import org.eclipse.jdt.internal.compiler.env.INameEnvironment; import org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer; import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory; /** * Eclipse compiler implementation */ public final class EclipseJavaCompiler extends AbstractJavaCompiler { private final EclipseJavaCompilerSettings defaultSettings; public EclipseJavaCompiler() { this(new EclipseJavaCompilerSettings()); } public EclipseJavaCompiler( final Map pSettings ) { defaultSettings = new EclipseJavaCompilerSettings(pSettings); } public EclipseJavaCompiler( final EclipseJavaCompilerSettings pSettings ) { defaultSettings = pSettings; } final class CompilationUnit implements ICompilationUnit { final private String clazzName; final private String fileName; final private char[] typeName; final private char[][] packageName; final private ResourceReader reader; CompilationUnit( final ResourceReader pReader, final String pSourceFile ) { reader = pReader; clazzName = ClassUtils.convertResourceToClassName(pSourceFile); fileName = pSourceFile; int dot = clazzName.lastIndexOf('.'); if (dot > 0) { typeName = clazzName.substring(dot + 1).toCharArray(); } else { typeName = clazzName.toCharArray(); } final StringTokenizer izer = new StringTokenizer(clazzName, "."); packageName = new char[izer.countTokens() - 1][]; for (int i = 0; i < packageName.length; i++) { packageName[i] = izer.nextToken().toCharArray(); } } public char[] getFileName() { return fileName.toCharArray(); } public char[] getContents() { final byte[] content = reader.getBytes(fileName); if (content == null) { return null; //throw new RuntimeException("resource " + fileName + " could not be found"); } return new String(content).toCharArray(); } public char[] getMainTypeName() { return typeName; } public char[][] getPackageName() { return packageName; } } public org.drools.commons.jci.compilers.CompilationResult compile( final String[] pSourceFiles, final ResourceReader pReader, final ResourceStore pStore, final ClassLoader pClassLoader, final JavaCompilerSettings pSettings ) { final Map settingsMap = new EclipseJavaCompilerSettings(pSettings).toNativeSettings(); final Collection problems = new ArrayList(); final ICompilationUnit[] compilationUnits = new ICompilationUnit[pSourceFiles.length]; for (int i = 0; i < compilationUnits.length; i++) { final String sourceFile = pSourceFiles[i]; if (pReader.isAvailable(sourceFile)) { compilationUnits[i] = new CompilationUnit(pReader, sourceFile); } else { // log.error("source not found " + sourceFile); final CompilationProblem problem = new CompilationProblem() { public int getEndColumn() { return 0; } public int getEndLine() { return 0; } public String getFileName() { return sourceFile; } public String getMessage() { return "Source " + sourceFile + " could not be found"; } public int getStartColumn() { return 0; } public int getStartLine() { return 0; } public boolean isError() { return true; } public String toString() { return getMessage(); } }; if (problemHandler != null) { problemHandler.handle(problem); } problems.add(problem); } } if (problems.size() > 0) { final CompilationProblem[] result = new CompilationProblem[problems.size()]; problems.toArray(result); return new org.drools.commons.jci.compilers.CompilationResult(result); } final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems(); final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault()); final INameEnvironment nameEnvironment = new INameEnvironment() { public NameEnvironmentAnswer findType( final char[][] pCompoundTypeName ) { final StringBuilder result = new StringBuilder(); for (int i = 0; i < pCompoundTypeName.length; i++) { if (i != 0) { result.append('.'); } result.append(pCompoundTypeName[i]); } //log.debug("finding compoundTypeName=" + result.toString()); return findType(result.toString()); } public NameEnvironmentAnswer findType( final char[] pTypeName, final char[][] pPackageName ) { final StringBuilder result = new StringBuilder(); for (int i = 0; i < pPackageName.length; i++) { result.append(pPackageName[i]); result.append('.'); } // log.debug("finding typeName=" + new String(typeName) + " packageName=" + result.toString()); result.append(pTypeName); return findType(result.toString()); } private NameEnvironmentAnswer findType( final String pClazzName ) { final String resourceName = ClassUtils.convertClassToResourcePath(pClazzName); final byte[] clazzBytes = pStore.read( resourceName ); if (clazzBytes != null) { try { return createNameEnvironmentAnswer(pClazzName, clazzBytes); } catch (final ClassFormatException e) { throw new RuntimeException( "ClassFormatException in loading class '" + pClazzName + "' with JCI." ); } } InputStream is = null; ByteArrayOutputStream baos = null; try { is = pClassLoader.getResourceAsStream(resourceName); if (is == null) { return null; } if ( ClassUtils.isWindows() ) { // check it really is a class, this issue is due to windows case sensitivity issues for the class org.drools.Process and path org/droosl/process try { pClassLoader.loadClass( pClazzName ); } catch ( ClassNotFoundException e ) { return null; } catch ( NoClassDefFoundError e ) { return null; } } final byte[] buffer = new byte[8192]; baos = new ByteArrayOutputStream(buffer.length); int count; while ((count = is.read(buffer, 0, buffer.length)) > 0) { baos.write(buffer, 0, count); } baos.flush(); return createNameEnvironmentAnswer(pClazzName, baos.toByteArray()); } catch ( final IOException e ) { throw new RuntimeException( "could not read class", e ); } catch ( final ClassFormatException e ) { throw new RuntimeException( "wrong class format", e ); } finally { try { if (baos != null ) { baos.close(); } } catch ( final IOException oe ) { throw new RuntimeException( "could not close output stream", oe ); } try { if ( is != null ) { is.close(); } } catch ( final IOException ie ) { throw new RuntimeException( "could not close input stream", ie ); } } } private NameEnvironmentAnswer createNameEnvironmentAnswer(final String pClazzName, final byte[] clazzBytes) throws ClassFormatException { final char[] fileName = pClazzName.toCharArray(); final ClassFileReader classFileReader = new ClassFileReader(clazzBytes, fileName, true); return new NameEnvironmentAnswer(classFileReader, null); } private boolean isSourceAvailable(final String pClazzName, final ResourceReader pReader) { // FIXME: this should not be tied to the extension final String javaSource = pClazzName.replace('.', '/') + ".java"; final String classSource = pClazzName.replace('.', '/') + ".class"; - return pReader.isAvailable(javaSource) || pReader.isAvailable(javaSource); + return pReader.isAvailable(javaSource) || pReader.isAvailable(classSource); } private boolean isPackage( final String pClazzName ) { InputStream is = null; try { is = pClassLoader.getResourceAsStream(ClassUtils.convertClassToResourcePath(pClazzName)); if ( ClassUtils.isWindows() ) { // check it really is a class, this issue is due to windows case sensitivity issues for the class org.drools.Process and path org/droosl/process if ( is != null ) { try { Class cls = pClassLoader.loadClass( pClazzName ); if ( cls != null ) { return true; } } catch ( ClassNotFoundException e ) { return true; } catch ( NoClassDefFoundError e ) { return true; } } } boolean result = is == null && !isSourceAvailable(pClazzName, pReader); return result; } finally { if ( is != null ) { try { is.close(); } catch ( IOException e ) { throw new RuntimeException( "Unable to close stream for resource: " + pClazzName ); } } } } public boolean isPackage( char[][] parentPackageName, char[] pPackageName ) { final StringBuilder result = new StringBuilder(); if (parentPackageName != null) { for (int i = 0; i < parentPackageName.length; i++) { if (i != 0) { result.append('.'); } result.append(parentPackageName[i]); } } // log.debug("isPackage parentPackageName=" + result.toString() + " packageName=" + new String(packageName)); if (parentPackageName != null && parentPackageName.length > 0) { result.append('.'); } result.append(pPackageName); return isPackage(result.toString()); } public void cleanup() { } }; final ICompilerRequestor compilerRequestor = new ICompilerRequestor() { public void acceptResult( final CompilationResult pResult ) { if (pResult.hasProblems()) { final IProblem[] iproblems = pResult.getProblems(); for (int i = 0; i < iproblems.length; i++) { final IProblem iproblem = iproblems[i]; final CompilationProblem problem = new EclipseCompilationProblem(iproblem); if (problemHandler != null) { problemHandler.handle(problem); } problems.add(problem); } } if (!pResult.hasErrors()) { final ClassFile[] clazzFiles = pResult.getClassFiles(); for (int i = 0; i < clazzFiles.length; i++) { final ClassFile clazzFile = clazzFiles[i]; final char[][] compoundName = clazzFile.getCompoundName(); final StringBuilder clazzName = new StringBuilder(); for (int j = 0; j < compoundName.length; j++) { if (j != 0) { clazzName.append('.'); } clazzName.append(compoundName[j]); } pStore.write(clazzName.toString().replace('.', '/') + ".class", clazzFile.getBytes()); } } } }; final Compiler compiler = new Compiler(nameEnvironment, policy, settingsMap, compilerRequestor, problemFactory, false); compiler.compile(compilationUnits); final CompilationProblem[] result = new CompilationProblem[problems.size()]; problems.toArray(result); return new org.drools.commons.jci.compilers.CompilationResult(result); } public JavaCompilerSettings createDefaultSettings() { return this.defaultSettings; } }
true
true
public org.drools.commons.jci.compilers.CompilationResult compile( final String[] pSourceFiles, final ResourceReader pReader, final ResourceStore pStore, final ClassLoader pClassLoader, final JavaCompilerSettings pSettings ) { final Map settingsMap = new EclipseJavaCompilerSettings(pSettings).toNativeSettings(); final Collection problems = new ArrayList(); final ICompilationUnit[] compilationUnits = new ICompilationUnit[pSourceFiles.length]; for (int i = 0; i < compilationUnits.length; i++) { final String sourceFile = pSourceFiles[i]; if (pReader.isAvailable(sourceFile)) { compilationUnits[i] = new CompilationUnit(pReader, sourceFile); } else { // log.error("source not found " + sourceFile); final CompilationProblem problem = new CompilationProblem() { public int getEndColumn() { return 0; } public int getEndLine() { return 0; } public String getFileName() { return sourceFile; } public String getMessage() { return "Source " + sourceFile + " could not be found"; } public int getStartColumn() { return 0; } public int getStartLine() { return 0; } public boolean isError() { return true; } public String toString() { return getMessage(); } }; if (problemHandler != null) { problemHandler.handle(problem); } problems.add(problem); } } if (problems.size() > 0) { final CompilationProblem[] result = new CompilationProblem[problems.size()]; problems.toArray(result); return new org.drools.commons.jci.compilers.CompilationResult(result); } final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems(); final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault()); final INameEnvironment nameEnvironment = new INameEnvironment() { public NameEnvironmentAnswer findType( final char[][] pCompoundTypeName ) { final StringBuilder result = new StringBuilder(); for (int i = 0; i < pCompoundTypeName.length; i++) { if (i != 0) { result.append('.'); } result.append(pCompoundTypeName[i]); } //log.debug("finding compoundTypeName=" + result.toString()); return findType(result.toString()); } public NameEnvironmentAnswer findType( final char[] pTypeName, final char[][] pPackageName ) { final StringBuilder result = new StringBuilder(); for (int i = 0; i < pPackageName.length; i++) { result.append(pPackageName[i]); result.append('.'); } // log.debug("finding typeName=" + new String(typeName) + " packageName=" + result.toString()); result.append(pTypeName); return findType(result.toString()); } private NameEnvironmentAnswer findType( final String pClazzName ) { final String resourceName = ClassUtils.convertClassToResourcePath(pClazzName); final byte[] clazzBytes = pStore.read( resourceName ); if (clazzBytes != null) { try { return createNameEnvironmentAnswer(pClazzName, clazzBytes); } catch (final ClassFormatException e) { throw new RuntimeException( "ClassFormatException in loading class '" + pClazzName + "' with JCI." ); } } InputStream is = null; ByteArrayOutputStream baos = null; try { is = pClassLoader.getResourceAsStream(resourceName); if (is == null) { return null; } if ( ClassUtils.isWindows() ) { // check it really is a class, this issue is due to windows case sensitivity issues for the class org.drools.Process and path org/droosl/process try { pClassLoader.loadClass( pClazzName ); } catch ( ClassNotFoundException e ) { return null; } catch ( NoClassDefFoundError e ) { return null; } } final byte[] buffer = new byte[8192]; baos = new ByteArrayOutputStream(buffer.length); int count; while ((count = is.read(buffer, 0, buffer.length)) > 0) { baos.write(buffer, 0, count); } baos.flush(); return createNameEnvironmentAnswer(pClazzName, baos.toByteArray()); } catch ( final IOException e ) { throw new RuntimeException( "could not read class", e ); } catch ( final ClassFormatException e ) { throw new RuntimeException( "wrong class format", e ); } finally { try { if (baos != null ) { baos.close(); } } catch ( final IOException oe ) { throw new RuntimeException( "could not close output stream", oe ); } try { if ( is != null ) { is.close(); } } catch ( final IOException ie ) { throw new RuntimeException( "could not close input stream", ie ); } } } private NameEnvironmentAnswer createNameEnvironmentAnswer(final String pClazzName, final byte[] clazzBytes) throws ClassFormatException { final char[] fileName = pClazzName.toCharArray(); final ClassFileReader classFileReader = new ClassFileReader(clazzBytes, fileName, true); return new NameEnvironmentAnswer(classFileReader, null); } private boolean isSourceAvailable(final String pClazzName, final ResourceReader pReader) { // FIXME: this should not be tied to the extension final String javaSource = pClazzName.replace('.', '/') + ".java"; final String classSource = pClazzName.replace('.', '/') + ".class"; return pReader.isAvailable(javaSource) || pReader.isAvailable(javaSource); } private boolean isPackage( final String pClazzName ) { InputStream is = null; try { is = pClassLoader.getResourceAsStream(ClassUtils.convertClassToResourcePath(pClazzName)); if ( ClassUtils.isWindows() ) { // check it really is a class, this issue is due to windows case sensitivity issues for the class org.drools.Process and path org/droosl/process if ( is != null ) { try { Class cls = pClassLoader.loadClass( pClazzName ); if ( cls != null ) { return true; } } catch ( ClassNotFoundException e ) { return true; } catch ( NoClassDefFoundError e ) { return true; } } } boolean result = is == null && !isSourceAvailable(pClazzName, pReader); return result; } finally { if ( is != null ) { try { is.close(); } catch ( IOException e ) { throw new RuntimeException( "Unable to close stream for resource: " + pClazzName ); } } } } public boolean isPackage( char[][] parentPackageName, char[] pPackageName ) { final StringBuilder result = new StringBuilder(); if (parentPackageName != null) { for (int i = 0; i < parentPackageName.length; i++) { if (i != 0) { result.append('.'); } result.append(parentPackageName[i]); } } // log.debug("isPackage parentPackageName=" + result.toString() + " packageName=" + new String(packageName)); if (parentPackageName != null && parentPackageName.length > 0) { result.append('.'); } result.append(pPackageName); return isPackage(result.toString()); } public void cleanup() { } }; final ICompilerRequestor compilerRequestor = new ICompilerRequestor() { public void acceptResult( final CompilationResult pResult ) { if (pResult.hasProblems()) { final IProblem[] iproblems = pResult.getProblems(); for (int i = 0; i < iproblems.length; i++) { final IProblem iproblem = iproblems[i]; final CompilationProblem problem = new EclipseCompilationProblem(iproblem); if (problemHandler != null) { problemHandler.handle(problem); } problems.add(problem); } } if (!pResult.hasErrors()) { final ClassFile[] clazzFiles = pResult.getClassFiles(); for (int i = 0; i < clazzFiles.length; i++) { final ClassFile clazzFile = clazzFiles[i]; final char[][] compoundName = clazzFile.getCompoundName(); final StringBuilder clazzName = new StringBuilder(); for (int j = 0; j < compoundName.length; j++) { if (j != 0) { clazzName.append('.'); } clazzName.append(compoundName[j]); } pStore.write(clazzName.toString().replace('.', '/') + ".class", clazzFile.getBytes()); } } } }; final Compiler compiler = new Compiler(nameEnvironment, policy, settingsMap, compilerRequestor, problemFactory, false); compiler.compile(compilationUnits); final CompilationProblem[] result = new CompilationProblem[problems.size()]; problems.toArray(result); return new org.drools.commons.jci.compilers.CompilationResult(result); }
public org.drools.commons.jci.compilers.CompilationResult compile( final String[] pSourceFiles, final ResourceReader pReader, final ResourceStore pStore, final ClassLoader pClassLoader, final JavaCompilerSettings pSettings ) { final Map settingsMap = new EclipseJavaCompilerSettings(pSettings).toNativeSettings(); final Collection problems = new ArrayList(); final ICompilationUnit[] compilationUnits = new ICompilationUnit[pSourceFiles.length]; for (int i = 0; i < compilationUnits.length; i++) { final String sourceFile = pSourceFiles[i]; if (pReader.isAvailable(sourceFile)) { compilationUnits[i] = new CompilationUnit(pReader, sourceFile); } else { // log.error("source not found " + sourceFile); final CompilationProblem problem = new CompilationProblem() { public int getEndColumn() { return 0; } public int getEndLine() { return 0; } public String getFileName() { return sourceFile; } public String getMessage() { return "Source " + sourceFile + " could not be found"; } public int getStartColumn() { return 0; } public int getStartLine() { return 0; } public boolean isError() { return true; } public String toString() { return getMessage(); } }; if (problemHandler != null) { problemHandler.handle(problem); } problems.add(problem); } } if (problems.size() > 0) { final CompilationProblem[] result = new CompilationProblem[problems.size()]; problems.toArray(result); return new org.drools.commons.jci.compilers.CompilationResult(result); } final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems(); final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault()); final INameEnvironment nameEnvironment = new INameEnvironment() { public NameEnvironmentAnswer findType( final char[][] pCompoundTypeName ) { final StringBuilder result = new StringBuilder(); for (int i = 0; i < pCompoundTypeName.length; i++) { if (i != 0) { result.append('.'); } result.append(pCompoundTypeName[i]); } //log.debug("finding compoundTypeName=" + result.toString()); return findType(result.toString()); } public NameEnvironmentAnswer findType( final char[] pTypeName, final char[][] pPackageName ) { final StringBuilder result = new StringBuilder(); for (int i = 0; i < pPackageName.length; i++) { result.append(pPackageName[i]); result.append('.'); } // log.debug("finding typeName=" + new String(typeName) + " packageName=" + result.toString()); result.append(pTypeName); return findType(result.toString()); } private NameEnvironmentAnswer findType( final String pClazzName ) { final String resourceName = ClassUtils.convertClassToResourcePath(pClazzName); final byte[] clazzBytes = pStore.read( resourceName ); if (clazzBytes != null) { try { return createNameEnvironmentAnswer(pClazzName, clazzBytes); } catch (final ClassFormatException e) { throw new RuntimeException( "ClassFormatException in loading class '" + pClazzName + "' with JCI." ); } } InputStream is = null; ByteArrayOutputStream baos = null; try { is = pClassLoader.getResourceAsStream(resourceName); if (is == null) { return null; } if ( ClassUtils.isWindows() ) { // check it really is a class, this issue is due to windows case sensitivity issues for the class org.drools.Process and path org/droosl/process try { pClassLoader.loadClass( pClazzName ); } catch ( ClassNotFoundException e ) { return null; } catch ( NoClassDefFoundError e ) { return null; } } final byte[] buffer = new byte[8192]; baos = new ByteArrayOutputStream(buffer.length); int count; while ((count = is.read(buffer, 0, buffer.length)) > 0) { baos.write(buffer, 0, count); } baos.flush(); return createNameEnvironmentAnswer(pClazzName, baos.toByteArray()); } catch ( final IOException e ) { throw new RuntimeException( "could not read class", e ); } catch ( final ClassFormatException e ) { throw new RuntimeException( "wrong class format", e ); } finally { try { if (baos != null ) { baos.close(); } } catch ( final IOException oe ) { throw new RuntimeException( "could not close output stream", oe ); } try { if ( is != null ) { is.close(); } } catch ( final IOException ie ) { throw new RuntimeException( "could not close input stream", ie ); } } } private NameEnvironmentAnswer createNameEnvironmentAnswer(final String pClazzName, final byte[] clazzBytes) throws ClassFormatException { final char[] fileName = pClazzName.toCharArray(); final ClassFileReader classFileReader = new ClassFileReader(clazzBytes, fileName, true); return new NameEnvironmentAnswer(classFileReader, null); } private boolean isSourceAvailable(final String pClazzName, final ResourceReader pReader) { // FIXME: this should not be tied to the extension final String javaSource = pClazzName.replace('.', '/') + ".java"; final String classSource = pClazzName.replace('.', '/') + ".class"; return pReader.isAvailable(javaSource) || pReader.isAvailable(classSource); } private boolean isPackage( final String pClazzName ) { InputStream is = null; try { is = pClassLoader.getResourceAsStream(ClassUtils.convertClassToResourcePath(pClazzName)); if ( ClassUtils.isWindows() ) { // check it really is a class, this issue is due to windows case sensitivity issues for the class org.drools.Process and path org/droosl/process if ( is != null ) { try { Class cls = pClassLoader.loadClass( pClazzName ); if ( cls != null ) { return true; } } catch ( ClassNotFoundException e ) { return true; } catch ( NoClassDefFoundError e ) { return true; } } } boolean result = is == null && !isSourceAvailable(pClazzName, pReader); return result; } finally { if ( is != null ) { try { is.close(); } catch ( IOException e ) { throw new RuntimeException( "Unable to close stream for resource: " + pClazzName ); } } } } public boolean isPackage( char[][] parentPackageName, char[] pPackageName ) { final StringBuilder result = new StringBuilder(); if (parentPackageName != null) { for (int i = 0; i < parentPackageName.length; i++) { if (i != 0) { result.append('.'); } result.append(parentPackageName[i]); } } // log.debug("isPackage parentPackageName=" + result.toString() + " packageName=" + new String(packageName)); if (parentPackageName != null && parentPackageName.length > 0) { result.append('.'); } result.append(pPackageName); return isPackage(result.toString()); } public void cleanup() { } }; final ICompilerRequestor compilerRequestor = new ICompilerRequestor() { public void acceptResult( final CompilationResult pResult ) { if (pResult.hasProblems()) { final IProblem[] iproblems = pResult.getProblems(); for (int i = 0; i < iproblems.length; i++) { final IProblem iproblem = iproblems[i]; final CompilationProblem problem = new EclipseCompilationProblem(iproblem); if (problemHandler != null) { problemHandler.handle(problem); } problems.add(problem); } } if (!pResult.hasErrors()) { final ClassFile[] clazzFiles = pResult.getClassFiles(); for (int i = 0; i < clazzFiles.length; i++) { final ClassFile clazzFile = clazzFiles[i]; final char[][] compoundName = clazzFile.getCompoundName(); final StringBuilder clazzName = new StringBuilder(); for (int j = 0; j < compoundName.length; j++) { if (j != 0) { clazzName.append('.'); } clazzName.append(compoundName[j]); } pStore.write(clazzName.toString().replace('.', '/') + ".class", clazzFile.getBytes()); } } } }; final Compiler compiler = new Compiler(nameEnvironment, policy, settingsMap, compilerRequestor, problemFactory, false); compiler.compile(compilationUnits); final CompilationProblem[] result = new CompilationProblem[problems.size()]; problems.toArray(result); return new org.drools.commons.jci.compilers.CompilationResult(result); }
diff --git a/src/main/java/com/eggs/impl/CsvFileMenuRepository.java b/src/main/java/com/eggs/impl/CsvFileMenuRepository.java index 5297f10..88039cc 100644 --- a/src/main/java/com/eggs/impl/CsvFileMenuRepository.java +++ b/src/main/java/com/eggs/impl/CsvFileMenuRepository.java @@ -1,86 +1,87 @@ package com.eggs.impl; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import com.eggs.Menu; import com.eggs.MenuBuilder; import com.eggs.MenuRepository; public class CsvFileMenuRepository implements MenuRepository { private String[] fileNames; public CsvFileMenuRepository(String ... files) { fileNames = files; } private Menu getMenu(String path) { MenuBuilder menu = MenuBuilder.menu(); BufferedReader br = null; try { InputStream is = this.getClass().getClassLoader().getResourceAsStream(path); br = new BufferedReader(new InputStreamReader(is)); String s; int i = 0; while((s = br.readLine()) != null) { if(i == 0) menu.restaurant(s); else { String[] food = s.split(","); - menu.food(food[0], food[1], Float.parseFloat(food[2])); + if(food.length == 3) + menu.food(food[0], food[1], Float.parseFloat(food[2])); } ++i; } } catch (FileNotFoundException e) { return null; } catch (IOException e) { e.printStackTrace(); } finally { if(br != null) try { br.close(); } catch (IOException e) { e.printStackTrace(); } } return menu.build(); } public List<Menu> getAllmenu() { List<Menu> list = new ArrayList<Menu>(); for (String file : fileNames) { Menu m1 = getMenu(file); if(m1 != null) list.add(m1); } return list; } }
true
true
private Menu getMenu(String path) { MenuBuilder menu = MenuBuilder.menu(); BufferedReader br = null; try { InputStream is = this.getClass().getClassLoader().getResourceAsStream(path); br = new BufferedReader(new InputStreamReader(is)); String s; int i = 0; while((s = br.readLine()) != null) { if(i == 0) menu.restaurant(s); else { String[] food = s.split(","); menu.food(food[0], food[1], Float.parseFloat(food[2])); } ++i; } } catch (FileNotFoundException e) { return null; } catch (IOException e) { e.printStackTrace(); } finally { if(br != null) try { br.close(); } catch (IOException e) { e.printStackTrace(); } } return menu.build(); }
private Menu getMenu(String path) { MenuBuilder menu = MenuBuilder.menu(); BufferedReader br = null; try { InputStream is = this.getClass().getClassLoader().getResourceAsStream(path); br = new BufferedReader(new InputStreamReader(is)); String s; int i = 0; while((s = br.readLine()) != null) { if(i == 0) menu.restaurant(s); else { String[] food = s.split(","); if(food.length == 3) menu.food(food[0], food[1], Float.parseFloat(food[2])); } ++i; } } catch (FileNotFoundException e) { return null; } catch (IOException e) { e.printStackTrace(); } finally { if(br != null) try { br.close(); } catch (IOException e) { e.printStackTrace(); } } return menu.build(); }
diff --git a/swing/visualizer/src/main/java/org/qi4j/library/swing/visualizer/detailPanel/internal/form/common/ServiceDescriptorForm.java b/swing/visualizer/src/main/java/org/qi4j/library/swing/visualizer/detailPanel/internal/form/common/ServiceDescriptorForm.java index b2b23916d..8fc90299e 100644 --- a/swing/visualizer/src/main/java/org/qi4j/library/swing/visualizer/detailPanel/internal/form/common/ServiceDescriptorForm.java +++ b/swing/visualizer/src/main/java/org/qi4j/library/swing/visualizer/detailPanel/internal/form/common/ServiceDescriptorForm.java @@ -1,195 +1,195 @@ /* Copyright 2008 Edward Yakop. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.qi4j.library.swing.visualizer.detailPanel.internal.form.common; import com.jgoodies.forms.factories.DefaultComponentFactory; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import java.util.List; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.ListModel; import org.qi4j.library.swing.visualizer.model.LayerDetailDescriptor; import org.qi4j.library.swing.visualizer.model.ModuleDetailDescriptor; import org.qi4j.library.swing.visualizer.model.ServiceDetailDescriptor; import org.qi4j.service.ServiceDescriptor; /** * @author [email protected] * @see org.qi4j.library.swing.visualizer.model.ServiceDetailDescriptor * @since 0.5 */ public final class ServiceDescriptorForm { private JPanel placeHolder; private JComponent serviceSeparator; private JTextField serviceId; private JTextField serviceType; private JCheckBox serviceIsInstantiateAtStartup; private JTextField serviceVisibility; private JComponent locationSeparator; private JList serviceAccessibleBy; private JTextField layer; private JTextField module; public final void updateModel( ServiceDetailDescriptor aDescriptor ) { populateServiceFields( aDescriptor ); populateLocationFields( aDescriptor ); } @SuppressWarnings( "unchecked" ) private void populateServiceFields( ServiceDetailDescriptor aDescriptor ) { String identity = null; boolean instantiateOnStartup = false; String visibility = null; String className = null; ListModel accessibleToLayers = null; if( aDescriptor != null ) { ServiceDescriptor descriptor = aDescriptor.descriptor(); identity = descriptor.identity(); className = descriptor.type().getName(); instantiateOnStartup = descriptor.isInstantiateOnStartup(); visibility = descriptor.visibility().toString(); final List<LayerDetailDescriptor> detailDescriptors = aDescriptor.accessibleToLayers(); accessibleToLayers = new ListListModel( detailDescriptors ); } serviceId.setText( identity ); serviceType.setText( className ); serviceIsInstantiateAtStartup.setSelected( instantiateOnStartup ); serviceVisibility.setText( visibility ); serviceAccessibleBy.setModel( accessibleToLayers ); } private void populateLocationFields( ServiceDetailDescriptor aDescriptor ) { String moduleName = null; String layerName = null; if( aDescriptor != null ) { ModuleDetailDescriptor moduleDD = aDescriptor.module(); moduleName = moduleDD.descriptor().name(); LayerDetailDescriptor layerDD = moduleDD.layer(); layerName = layerDD.descriptor().name(); } module.setText( moduleName ); layer.setText( layerName ); } private void createUIComponents() { DefaultComponentFactory cmpFactory = DefaultComponentFactory.getInstance(); serviceSeparator = cmpFactory.createSeparator( "Service" ); locationSeparator = cmpFactory.createSeparator( "Location" ); } { // GUI initializer generated by IntelliJ IDEA GUI Designer // >>> IMPORTANT!! <<< // DO NOT EDIT OR ADD ANY CODE HERE! $$$setupUI$$$(); } /** * Method generated by IntelliJ IDEA GUI Designer * >>> IMPORTANT!! <<< * DO NOT edit this method OR call it in your code! * * @noinspection ALL */ private void $$$setupUI$$$() { createUIComponents(); placeHolder = new JPanel(); - placeHolder.setLayout( new FormLayout( "fill:max(d;4px):noGrow,fill:p:noGrow,fill:max(d;4px):noGrow,fill:max(m;160dlu):noGrow", "center:max(d;4px):noGrow,center:max(d;4px):noGrow,top:4dlu:noGrow,center:p:noGrow,top:5dlu:noGrow,center:p:noGrow,top:4dlu:noGrow,center:p:noGrow,top:4dlu:noGrow,center:p:noGrow,top:4dlu:noGrow,top:max(m;50dlu):noGrow,top:5dlu:noGrow,center:max(d;4px):noGrow,top:4dlu:noGrow,center:p:noGrow,top:4dlu:noGrow,center:max(p;4px):noGrow" ) ); + placeHolder.setLayout( new FormLayout( "fill:max(d;4px):noGrow,fill:p:noGrow,fill:max(d;4px):noGrow,fill:max(p;160dlu):noGrow", "center:max(d;4px):noGrow,center:max(d;4px):noGrow,top:4dlu:noGrow,center:p:noGrow,top:5dlu:noGrow,center:p:noGrow,top:4dlu:noGrow,center:p:noGrow,top:4dlu:noGrow,center:p:noGrow,top:4dlu:noGrow,top:max(m;50dlu):noGrow,top:5dlu:noGrow,center:max(d;4px):noGrow,top:4dlu:noGrow,center:p:noGrow,top:4dlu:noGrow,center:max(p;4px):noGrow" ) ); ( (FormLayout) placeHolder.getLayout() ).setRowGroups( new int[][]{ new int[]{ 4, 6, 8, 10 }, new int[]{ 2, 14 }, new int[]{ 16, 18 } } ); final JLabel label1 = new JLabel(); label1.setText( "Id" ); CellConstraints cc = new CellConstraints(); placeHolder.add( label1, cc.xy( 2, 4 ) ); serviceId = new JTextField(); serviceId.setEditable( false ); placeHolder.add( serviceId, cc.xy( 4, 4 ) ); final JLabel label2 = new JLabel(); label2.setText( "Class name" ); placeHolder.add( label2, cc.xy( 2, 6 ) ); final JLabel label3 = new JLabel(); label3.setText( "Is instatiate at startup" ); placeHolder.add( label3, cc.xy( 2, 10 ) ); serviceIsInstantiateAtStartup = new JCheckBox(); serviceIsInstantiateAtStartup.setEnabled( false ); serviceIsInstantiateAtStartup.setText( "" ); placeHolder.add( serviceIsInstantiateAtStartup, cc.xy( 4, 10, CellConstraints.LEFT, CellConstraints.DEFAULT ) ); serviceType = new JTextField(); serviceType.setEditable( false ); placeHolder.add( serviceType, cc.xy( 4, 6 ) ); final JLabel label4 = new JLabel(); label4.setText( "Visiblity" ); placeHolder.add( label4, cc.xy( 2, 8 ) ); serviceVisibility = new JTextField(); serviceVisibility.setEditable( false ); placeHolder.add( serviceVisibility, cc.xy( 4, 8 ) ); placeHolder.add( serviceSeparator, cc.xyw( 2, 2, 3 ) ); placeHolder.add( locationSeparator, cc.xyw( 2, 14, 3 ) ); final JLabel label5 = new JLabel(); label5.setText( "Layer" ); placeHolder.add( label5, cc.xy( 2, 16 ) ); layer = new JTextField(); layer.setEditable( false ); placeHolder.add( layer, cc.xy( 4, 16 ) ); final JLabel label6 = new JLabel(); label6.setText( "Module" ); placeHolder.add( label6, cc.xy( 2, 18 ) ); module = new JTextField(); module.setEditable( false ); placeHolder.add( module, cc.xy( 4, 18 ) ); final JLabel label7 = new JLabel(); label7.setText( "Accessible by (layer)" ); placeHolder.add( label7, cc.xy( 2, 12 ) ); serviceAccessibleBy = new JList(); serviceAccessibleBy.setSelectionMode( 0 ); serviceAccessibleBy.setVisibleRowCount( 5 ); placeHolder.add( serviceAccessibleBy, cc.xy( 4, 12, CellConstraints.DEFAULT, CellConstraints.FILL ) ); label1.setLabelFor( serviceId ); label2.setLabelFor( serviceType ); label3.setLabelFor( serviceIsInstantiateAtStartup ); label4.setLabelFor( serviceVisibility ); label5.setLabelFor( layer ); label6.setLabelFor( module ); } /** * @noinspection ALL */ public JComponent $$$getRootComponent$$$() { return placeHolder; } }
true
true
private void $$$setupUI$$$() { createUIComponents(); placeHolder = new JPanel(); placeHolder.setLayout( new FormLayout( "fill:max(d;4px):noGrow,fill:p:noGrow,fill:max(d;4px):noGrow,fill:max(m;160dlu):noGrow", "center:max(d;4px):noGrow,center:max(d;4px):noGrow,top:4dlu:noGrow,center:p:noGrow,top:5dlu:noGrow,center:p:noGrow,top:4dlu:noGrow,center:p:noGrow,top:4dlu:noGrow,center:p:noGrow,top:4dlu:noGrow,top:max(m;50dlu):noGrow,top:5dlu:noGrow,center:max(d;4px):noGrow,top:4dlu:noGrow,center:p:noGrow,top:4dlu:noGrow,center:max(p;4px):noGrow" ) ); ( (FormLayout) placeHolder.getLayout() ).setRowGroups( new int[][]{ new int[]{ 4, 6, 8, 10 }, new int[]{ 2, 14 }, new int[]{ 16, 18 } } ); final JLabel label1 = new JLabel(); label1.setText( "Id" ); CellConstraints cc = new CellConstraints(); placeHolder.add( label1, cc.xy( 2, 4 ) ); serviceId = new JTextField(); serviceId.setEditable( false ); placeHolder.add( serviceId, cc.xy( 4, 4 ) ); final JLabel label2 = new JLabel(); label2.setText( "Class name" ); placeHolder.add( label2, cc.xy( 2, 6 ) ); final JLabel label3 = new JLabel(); label3.setText( "Is instatiate at startup" ); placeHolder.add( label3, cc.xy( 2, 10 ) ); serviceIsInstantiateAtStartup = new JCheckBox(); serviceIsInstantiateAtStartup.setEnabled( false ); serviceIsInstantiateAtStartup.setText( "" ); placeHolder.add( serviceIsInstantiateAtStartup, cc.xy( 4, 10, CellConstraints.LEFT, CellConstraints.DEFAULT ) ); serviceType = new JTextField(); serviceType.setEditable( false ); placeHolder.add( serviceType, cc.xy( 4, 6 ) ); final JLabel label4 = new JLabel(); label4.setText( "Visiblity" ); placeHolder.add( label4, cc.xy( 2, 8 ) ); serviceVisibility = new JTextField(); serviceVisibility.setEditable( false ); placeHolder.add( serviceVisibility, cc.xy( 4, 8 ) ); placeHolder.add( serviceSeparator, cc.xyw( 2, 2, 3 ) ); placeHolder.add( locationSeparator, cc.xyw( 2, 14, 3 ) ); final JLabel label5 = new JLabel(); label5.setText( "Layer" ); placeHolder.add( label5, cc.xy( 2, 16 ) ); layer = new JTextField(); layer.setEditable( false ); placeHolder.add( layer, cc.xy( 4, 16 ) ); final JLabel label6 = new JLabel(); label6.setText( "Module" ); placeHolder.add( label6, cc.xy( 2, 18 ) ); module = new JTextField(); module.setEditable( false ); placeHolder.add( module, cc.xy( 4, 18 ) ); final JLabel label7 = new JLabel(); label7.setText( "Accessible by (layer)" ); placeHolder.add( label7, cc.xy( 2, 12 ) ); serviceAccessibleBy = new JList(); serviceAccessibleBy.setSelectionMode( 0 ); serviceAccessibleBy.setVisibleRowCount( 5 ); placeHolder.add( serviceAccessibleBy, cc.xy( 4, 12, CellConstraints.DEFAULT, CellConstraints.FILL ) ); label1.setLabelFor( serviceId ); label2.setLabelFor( serviceType ); label3.setLabelFor( serviceIsInstantiateAtStartup ); label4.setLabelFor( serviceVisibility ); label5.setLabelFor( layer ); label6.setLabelFor( module ); }
private void $$$setupUI$$$() { createUIComponents(); placeHolder = new JPanel(); placeHolder.setLayout( new FormLayout( "fill:max(d;4px):noGrow,fill:p:noGrow,fill:max(d;4px):noGrow,fill:max(p;160dlu):noGrow", "center:max(d;4px):noGrow,center:max(d;4px):noGrow,top:4dlu:noGrow,center:p:noGrow,top:5dlu:noGrow,center:p:noGrow,top:4dlu:noGrow,center:p:noGrow,top:4dlu:noGrow,center:p:noGrow,top:4dlu:noGrow,top:max(m;50dlu):noGrow,top:5dlu:noGrow,center:max(d;4px):noGrow,top:4dlu:noGrow,center:p:noGrow,top:4dlu:noGrow,center:max(p;4px):noGrow" ) ); ( (FormLayout) placeHolder.getLayout() ).setRowGroups( new int[][]{ new int[]{ 4, 6, 8, 10 }, new int[]{ 2, 14 }, new int[]{ 16, 18 } } ); final JLabel label1 = new JLabel(); label1.setText( "Id" ); CellConstraints cc = new CellConstraints(); placeHolder.add( label1, cc.xy( 2, 4 ) ); serviceId = new JTextField(); serviceId.setEditable( false ); placeHolder.add( serviceId, cc.xy( 4, 4 ) ); final JLabel label2 = new JLabel(); label2.setText( "Class name" ); placeHolder.add( label2, cc.xy( 2, 6 ) ); final JLabel label3 = new JLabel(); label3.setText( "Is instatiate at startup" ); placeHolder.add( label3, cc.xy( 2, 10 ) ); serviceIsInstantiateAtStartup = new JCheckBox(); serviceIsInstantiateAtStartup.setEnabled( false ); serviceIsInstantiateAtStartup.setText( "" ); placeHolder.add( serviceIsInstantiateAtStartup, cc.xy( 4, 10, CellConstraints.LEFT, CellConstraints.DEFAULT ) ); serviceType = new JTextField(); serviceType.setEditable( false ); placeHolder.add( serviceType, cc.xy( 4, 6 ) ); final JLabel label4 = new JLabel(); label4.setText( "Visiblity" ); placeHolder.add( label4, cc.xy( 2, 8 ) ); serviceVisibility = new JTextField(); serviceVisibility.setEditable( false ); placeHolder.add( serviceVisibility, cc.xy( 4, 8 ) ); placeHolder.add( serviceSeparator, cc.xyw( 2, 2, 3 ) ); placeHolder.add( locationSeparator, cc.xyw( 2, 14, 3 ) ); final JLabel label5 = new JLabel(); label5.setText( "Layer" ); placeHolder.add( label5, cc.xy( 2, 16 ) ); layer = new JTextField(); layer.setEditable( false ); placeHolder.add( layer, cc.xy( 4, 16 ) ); final JLabel label6 = new JLabel(); label6.setText( "Module" ); placeHolder.add( label6, cc.xy( 2, 18 ) ); module = new JTextField(); module.setEditable( false ); placeHolder.add( module, cc.xy( 4, 18 ) ); final JLabel label7 = new JLabel(); label7.setText( "Accessible by (layer)" ); placeHolder.add( label7, cc.xy( 2, 12 ) ); serviceAccessibleBy = new JList(); serviceAccessibleBy.setSelectionMode( 0 ); serviceAccessibleBy.setVisibleRowCount( 5 ); placeHolder.add( serviceAccessibleBy, cc.xy( 4, 12, CellConstraints.DEFAULT, CellConstraints.FILL ) ); label1.setLabelFor( serviceId ); label2.setLabelFor( serviceType ); label3.setLabelFor( serviceIsInstantiateAtStartup ); label4.setLabelFor( serviceVisibility ); label5.setLabelFor( layer ); label6.setLabelFor( module ); }
diff --git a/src/ru/ifmo/neerc/timer/TimerFrame.java b/src/ru/ifmo/neerc/timer/TimerFrame.java index fa36eb4..9ce9d6e 100644 --- a/src/ru/ifmo/neerc/timer/TimerFrame.java +++ b/src/ru/ifmo/neerc/timer/TimerFrame.java @@ -1,179 +1,179 @@ package ru.ifmo.neerc.timer; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Font; import java.awt.Toolkit; import java.util.Calendar; import java.util.Date; import javax.sql.rowset.spi.SyncResolver; import javax.swing.JFrame; import javax.swing.JLabel; import pcms2.services.site.Clock; import ru.ifmo.neerc.gui.ImagePanel; public class TimerFrame extends JFrame { public static final int BEFORE = 0; public static final int RUNNING = 1; public static final int FROZEN = 3; public static final int PAUSED = 4; public static final int LEFT5MIN = 5; public static final int LEFT1MIN = 6; public static final int OVER = 7; private JLabel timeLabel = new JLabel(); private ImagePanel panelBgImg; private Integer status; private Long cTime, cDelta; private Color[] palette; TimerFrame() { super("PCMS2 Timer"); palette = new Color[8]; for (int i = 0; i < 8; ++i) { palette[i] = Color.BLACK; } this.setUndecorated(true); setBounds(0, 0, 1024, 768); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container con = this.getContentPane(); timeLabel.setFont(new Font("Calibri", Font.BOLD, 350)); timeLabel.setHorizontalAlignment(JLabel.CENTER); timeLabel.setVerticalAlignment(JLabel.CENTER); timeLabel.setForeground(Color.green); con.setBackground(Color.BLACK); timeLabel.setText("0:00:00"); Toolkit tk = Toolkit.getDefaultToolkit(); int xSize = ((int) tk.getScreenSize().getWidth()); int ySize = ((int) tk.getScreenSize().getHeight()); setSize(xSize, ySize); con.setLayout(null); panelBgImg = new ImagePanel(); con.add(panelBgImg); panelBgImg.setLayout(new BorderLayout()); panelBgImg.add(timeLabel, BorderLayout.CENTER); panelBgImg.setBounds(0, 0, xSize, ySize); cTime = Long.valueOf(0); cDelta = Long.valueOf(0); status = Integer.valueOf(0); new Thread(new Runnable() { @Override public void run() { TimerFrame.this.setVisible(true); } }).start(); new Thread(new Runnable() { @Override public void run() { long timestamp = System.currentTimeMillis(); while (true) { long nts = System.currentTimeMillis(); long diff = nts - timestamp; timestamp = nts; long dtime = 0; synchronized (cDelta) { synchronized (cTime) { - long correction = Math.min(cDelta, diff); + long correction = Math.min(cDelta, diff / 2); synchronized (status) { if (status == Clock.RUNNING) { cTime = cTime - diff + correction; } } cDelta = cDelta - correction; dtime = cTime; } } dtime /= 1000; int seconds = (int) (dtime % 60); dtime /= 60; int minutes = (int) (dtime % 60); dtime /= 60; int hours = (int) dtime; String text = null; Color c = null; synchronized (status) { switch (status) { case Clock.BEFORE: c = palette[BEFORE]; break; case Clock.RUNNING: c = palette[RUNNING]; break; case Clock.OVER: c = palette[OVER]; break; case Clock.PAUSED: c = palette[PAUSED]; break; } } if (minutes <= 1) { c = palette[LEFT1MIN]; } else if (minutes <= 5) { c = palette[LEFT5MIN]; } if (hours > 0) { text = String.format("%d:%02d:%02d", hours, minutes, seconds); } else if (minutes > 0) { text = String.format("%02d:%02d", minutes, seconds); } else { text = String.format("%d", seconds); } timeLabel.setText(text); timeLabel.setForeground(c); try { Thread.sleep(100); } catch (InterruptedException e) { return; } } } }).start(); } public void setStatus(int status) { synchronized (this.status) { this.status = Integer.valueOf(status); this.repaint(); } } public void sync(long time) { synchronized (this.cDelta) { synchronized (this.cTime) { cDelta = time - this.cTime; if (cDelta >= 100000) { cDelta = Long.valueOf(0); this.cTime = time; } this.repaint(); } } } }
true
true
TimerFrame() { super("PCMS2 Timer"); palette = new Color[8]; for (int i = 0; i < 8; ++i) { palette[i] = Color.BLACK; } this.setUndecorated(true); setBounds(0, 0, 1024, 768); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container con = this.getContentPane(); timeLabel.setFont(new Font("Calibri", Font.BOLD, 350)); timeLabel.setHorizontalAlignment(JLabel.CENTER); timeLabel.setVerticalAlignment(JLabel.CENTER); timeLabel.setForeground(Color.green); con.setBackground(Color.BLACK); timeLabel.setText("0:00:00"); Toolkit tk = Toolkit.getDefaultToolkit(); int xSize = ((int) tk.getScreenSize().getWidth()); int ySize = ((int) tk.getScreenSize().getHeight()); setSize(xSize, ySize); con.setLayout(null); panelBgImg = new ImagePanel(); con.add(panelBgImg); panelBgImg.setLayout(new BorderLayout()); panelBgImg.add(timeLabel, BorderLayout.CENTER); panelBgImg.setBounds(0, 0, xSize, ySize); cTime = Long.valueOf(0); cDelta = Long.valueOf(0); status = Integer.valueOf(0); new Thread(new Runnable() { @Override public void run() { TimerFrame.this.setVisible(true); } }).start(); new Thread(new Runnable() { @Override public void run() { long timestamp = System.currentTimeMillis(); while (true) { long nts = System.currentTimeMillis(); long diff = nts - timestamp; timestamp = nts; long dtime = 0; synchronized (cDelta) { synchronized (cTime) { long correction = Math.min(cDelta, diff); synchronized (status) { if (status == Clock.RUNNING) { cTime = cTime - diff + correction; } } cDelta = cDelta - correction; dtime = cTime; } } dtime /= 1000; int seconds = (int) (dtime % 60); dtime /= 60; int minutes = (int) (dtime % 60); dtime /= 60; int hours = (int) dtime; String text = null; Color c = null; synchronized (status) { switch (status) { case Clock.BEFORE: c = palette[BEFORE]; break; case Clock.RUNNING: c = palette[RUNNING]; break; case Clock.OVER: c = palette[OVER]; break; case Clock.PAUSED: c = palette[PAUSED]; break; } } if (minutes <= 1) { c = palette[LEFT1MIN]; } else if (minutes <= 5) { c = palette[LEFT5MIN]; } if (hours > 0) { text = String.format("%d:%02d:%02d", hours, minutes, seconds); } else if (minutes > 0) { text = String.format("%02d:%02d", minutes, seconds); } else { text = String.format("%d", seconds); } timeLabel.setText(text); timeLabel.setForeground(c); try { Thread.sleep(100); } catch (InterruptedException e) { return; } } } }).start(); }
TimerFrame() { super("PCMS2 Timer"); palette = new Color[8]; for (int i = 0; i < 8; ++i) { palette[i] = Color.BLACK; } this.setUndecorated(true); setBounds(0, 0, 1024, 768); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container con = this.getContentPane(); timeLabel.setFont(new Font("Calibri", Font.BOLD, 350)); timeLabel.setHorizontalAlignment(JLabel.CENTER); timeLabel.setVerticalAlignment(JLabel.CENTER); timeLabel.setForeground(Color.green); con.setBackground(Color.BLACK); timeLabel.setText("0:00:00"); Toolkit tk = Toolkit.getDefaultToolkit(); int xSize = ((int) tk.getScreenSize().getWidth()); int ySize = ((int) tk.getScreenSize().getHeight()); setSize(xSize, ySize); con.setLayout(null); panelBgImg = new ImagePanel(); con.add(panelBgImg); panelBgImg.setLayout(new BorderLayout()); panelBgImg.add(timeLabel, BorderLayout.CENTER); panelBgImg.setBounds(0, 0, xSize, ySize); cTime = Long.valueOf(0); cDelta = Long.valueOf(0); status = Integer.valueOf(0); new Thread(new Runnable() { @Override public void run() { TimerFrame.this.setVisible(true); } }).start(); new Thread(new Runnable() { @Override public void run() { long timestamp = System.currentTimeMillis(); while (true) { long nts = System.currentTimeMillis(); long diff = nts - timestamp; timestamp = nts; long dtime = 0; synchronized (cDelta) { synchronized (cTime) { long correction = Math.min(cDelta, diff / 2); synchronized (status) { if (status == Clock.RUNNING) { cTime = cTime - diff + correction; } } cDelta = cDelta - correction; dtime = cTime; } } dtime /= 1000; int seconds = (int) (dtime % 60); dtime /= 60; int minutes = (int) (dtime % 60); dtime /= 60; int hours = (int) dtime; String text = null; Color c = null; synchronized (status) { switch (status) { case Clock.BEFORE: c = palette[BEFORE]; break; case Clock.RUNNING: c = palette[RUNNING]; break; case Clock.OVER: c = palette[OVER]; break; case Clock.PAUSED: c = palette[PAUSED]; break; } } if (minutes <= 1) { c = palette[LEFT1MIN]; } else if (minutes <= 5) { c = palette[LEFT5MIN]; } if (hours > 0) { text = String.format("%d:%02d:%02d", hours, minutes, seconds); } else if (minutes > 0) { text = String.format("%02d:%02d", minutes, seconds); } else { text = String.format("%d", seconds); } timeLabel.setText(text); timeLabel.setForeground(c); try { Thread.sleep(100); } catch (InterruptedException e) { return; } } } }).start(); }
diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/jsptag/ItemTag.java b/dspace-jspui/src/main/java/org/dspace/app/webui/jsptag/ItemTag.java index 9e5e5490c..bdba906ae 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/jsptag/ItemTag.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/jsptag/ItemTag.java @@ -1,1117 +1,1117 @@ /** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.jsptag; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.jstl.fmt.LocaleSupport; import javax.servlet.jsp.tagext.TagSupport; import org.apache.commons.lang.ArrayUtils; import org.apache.log4j.Logger; import org.dspace.app.util.DCInputsReaderException; import org.dspace.app.util.MetadataExposure; import org.dspace.app.util.Util; import org.dspace.app.webui.util.StyleSelection; import org.dspace.app.webui.util.UIUtil; import org.dspace.browse.BrowseException; import org.dspace.content.Bitstream; import org.dspace.content.Bundle; import org.dspace.content.Collection; import org.dspace.content.DCDate; import org.dspace.content.DCValue; import org.dspace.content.Item; import org.dspace.content.authority.MetadataAuthorityManager; import org.dspace.core.ConfigurationManager; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.core.I18nUtil; import org.dspace.core.PluginManager; import org.dspace.core.Utils; /** * <P> * JSP tag for displaying an item. * </P> * <P> * The fields that are displayed can be configured in <code>dspace.cfg</code> * using the <code>webui.itemdisplay.(style)</code> property. The form is * </P> * * <PRE> * * &lt;schema prefix&gt;.&lt;element&gt;[.&lt;qualifier&gt;|.*][(date)|(link)], ... * * </PRE> * * <P> * For example: * </P> * * <PRE> * * dc.title = Dublin Core element 'title' (unqualified) * dc.title.alternative = DC element 'title', qualifier 'alternative' * dc.title.* = All fields with Dublin Core element 'title' (any or no qualifier) * dc.identifier.uri(link) = DC identifier.uri, render as a link * dc.date.issued(date) = DC date.issued, render as a date * dc.identifier.doi(doi) = DC identifier.doi, render as link to http://dx.doi.org * dc.identifier.hdl(handle) = DC identifier.hanlde, render as link to http://hdl.handle.net * dc.relation.isPartOf(resolver) = DC relation.isPartOf, render as link to the base url of the resolver * according to the specified urn in the metadata value (doi:xxxx, hdl:xxxxx, * urn:issn:xxxx, etc.) * * </PRE> * * <P> * When using "resolver" in webui.itemdisplay to render identifiers as resolvable * links, the base URL is taken from <code>webui.resolver.<n>.baseurl</code> * where <code>webui.resolver.<n>.urn</code> matches the urn specified in the metadata value. * The value is appended to the "baseurl" as is, so the baseurl need to end with slash almost in any case. * If no urn is specified in the value it will be displayed as simple text. * * <PRE> * * webui.resolver.1.urn = doi * webui.resolver.1.baseurl = http://dx.doi.org/ * webui.resolver.2.urn = hdl * webui.resolver.2.baseurl = http://hdl.handle.net/ * * </PRE> * * For the doi and hdl urn defaults values are provided, respectively http://dx.doi.org/ and * http://hdl.handle.net/ are used.<br> * * If a metadata value with style: "doi", "handle" or "resolver" matches a URL * already, it is simply rendered as a link with no other manipulation. * </P> * * <PRE> * * <P> * If an item has no value for a particular field, it won't be displayed. The * name of the field for display will be drawn from the current UI dictionary, * using the key: * </P> * * <PRE> * * &quot;metadata.&lt;style.&gt;.&lt;field&gt;&quot; * * e.g. &quot;metadata.thesis.dc.title&quot; &quot;metadata.thesis.dc.contributor.*&quot; * &quot;metadata.thesis.dc.date.issued&quot; * * * if this key is not found will be used the more general one * * &quot;metadata.&lt;field&gt;&quot; * * e.g. &quot;metadata.dc.title&quot; &quot;metadata.dc.contributor.*&quot; * &quot;metadata.dc.date.issued&quot; * * </PRE> * * <P> * You need to specify which strategy use for select the style for an item. * </P> * * <PRE> * * plugin.single.org.dspace.app.webui.util.StyleSelection = \ * org.dspace.app.webui.util.CollectionStyleSelection * #org.dspace.app.webui.util.MetadataStyleSelection * * </PRE> * * <P> * With the Collection strategy you can also specify which collections use which * views. * </P> * * <PRE> * * webui.itemdisplay.&lt;style&gt;.collections = &lt;collection handle&gt;, ... * * </PRE> * * <P> * FIXME: This should be more database-driven * </P> * * <PRE> * * webui.itemdisplay.thesis.collections = 123456789/24, 123456789/35 * * </PRE> * * <P> * With the Metadata strategy you MUST specify which metadata use as name of the * style. * </P> * * <PRE> * * webui.itemdisplay.metadata-style = schema.element[.qualifier|.*] * * e.g. &quot;dc.type&quot; * * </PRE> * * @author Robert Tansley * @version $Revision$ */ public class ItemTag extends TagSupport { private static final String HANDLE_DEFAULT_BASEURL = "http://hdl.handle.net/"; private static final String DOI_DEFAULT_BASEURL = "http://dx.doi.org/"; /** Item to display */ private transient Item item; /** Collections this item appears in */ private transient Collection[] collections; /** The style to use - "default" or "full" */ private String style; /** Whether to show preview thumbs on the item page */ private boolean showThumbs; /** Default DC fields to display, in absence of configuration */ private static String defaultFields = "dc.title, dc.title.alternative, dc.contributor.*, dc.subject, dc.date.issued(date), dc.publisher, dc.identifier.citation, dc.relation.ispartofseries, dc.description.abstract, dc.description, dc.identifier.govdoc, dc.identifier.uri(link), dc.identifier.isbn, dc.identifier.issn, dc.identifier.ismn, dc.identifier"; /** log4j logger */ private static Logger log = Logger.getLogger(ItemTag.class); private StyleSelection styleSelection = (StyleSelection) PluginManager.getSinglePlugin(StyleSelection.class); /** Hashmap of linked metadata to browse, from dspace.cfg */ private static Map<String,String> linkedMetadata; /** Hashmap of urn base url resolver, from dspace.cfg */ private static Map<String,String> urn2baseurl; /** regex pattern to capture the style of a field, ie <code>schema.element.qualifier(style)</code> */ private Pattern fieldStylePatter = Pattern.compile(".*\\((.*)\\)"); private static final long serialVersionUID = -3841266490729417240L; static { int i; linkedMetadata = new HashMap<String, String>(); String linkMetadata; i = 1; do { linkMetadata = ConfigurationManager.getProperty("webui.browse.link."+i); if (linkMetadata != null) { String[] linkedMetadataSplit = linkMetadata.split(":"); String indexName = linkedMetadataSplit[0].trim(); String metadataName = linkedMetadataSplit[1].trim(); linkedMetadata.put(indexName, metadataName); } i++; } while (linkMetadata != null); urn2baseurl = new HashMap<String, String>(); String urn; i = 1; do { urn = ConfigurationManager.getProperty("webui.resolver."+i+".urn"); if (urn != null) { String baseurl = ConfigurationManager.getProperty("webui.resolver."+i+".baseurl"); if (baseurl != null){ urn2baseurl.put(urn, baseurl); } else { log.warn("Wrong webui.resolver configuration, you need to specify both webui.resolver.<n>.urn and webui.resolver.<n>.baseurl: missing baseurl for n = "+i); } } i++; } while (urn != null); // Set sensible default if no config is found for doi & handle if (!urn2baseurl.containsKey("doi")){ urn2baseurl.put("doi",DOI_DEFAULT_BASEURL); } if (!urn2baseurl.containsKey("hdl")){ urn2baseurl.put("hdl",HANDLE_DEFAULT_BASEURL); } } public ItemTag() { super(); getThumbSettings(); } public int doStartTag() throws JspException { try { if (style == null || style.equals("")) { style = styleSelection.getStyleForItem(item); } if (style.equals("full")) { renderFull(); } else { render(); } } catch (SQLException sqle) { throw new JspException(sqle); } catch (IOException ie) { throw new JspException(ie); } catch (DCInputsReaderException ex) { throw new JspException(ex); } return SKIP_BODY; } /** * Get the item this tag should display * * @return the item */ public Item getItem() { return item; } /** * Set the item this tag should display * * @param itemIn * the item to display */ public void setItem(Item itemIn) { item = itemIn; } /** * Get the collections this item is in * * @return the collections */ public Collection[] getCollections() { return (Collection[]) ArrayUtils.clone(collections); } /** * Set the collections this item is in * * @param collectionsIn * the collections */ public void setCollections(Collection[] collectionsIn) { collections = (Collection[]) ArrayUtils.clone(collectionsIn); } /** * Get the style this tag should display * * @return the style */ public String getStyle() { return style; } /** * Set the style this tag should display * * @param styleIn * the Style to display */ public void setStyle(String styleIn) { style = styleIn; } public void release() { style = "default"; item = null; collections = null; } /** * Render an item in the given style */ private void render() throws IOException, SQLException, DCInputsReaderException { JspWriter out = pageContext.getOut(); HttpServletRequest request = (HttpServletRequest)pageContext.getRequest(); Context context = UIUtil.obtainContext(request); Locale sessionLocale = UIUtil.getSessionLocale(request); String configLine = styleSelection.getConfigurationForStyle(style); if (configLine == null) { configLine = defaultFields; } out.println("<center><table class=\"itemDisplayTable\">"); /* * Break down the configuration into fields and display them * * FIXME?: it may be more efficient to do some processing once, perhaps * to a more efficient intermediate class, but then it would become more * difficult to reload the configuration "on the fly". */ StringTokenizer st = new StringTokenizer(configLine, ","); while (st.hasMoreTokens()) { String field = st.nextToken().trim(); boolean isDate = false; boolean isLink = false; boolean isResolver = false; boolean isNoBreakLine = false; boolean isDisplay = false; String style = null; Matcher fieldStyleMatcher = fieldStylePatter.matcher(field); if (fieldStyleMatcher.matches()){ style = fieldStyleMatcher.group(1); } String browseIndex; try { browseIndex = getBrowseField(field); } catch (BrowseException e) { log.error(e); browseIndex = null; } // Find out if the field should rendered with a particular style if (style != null) { isDate = style.contains("date"); isLink = style.contains("link"); isNoBreakLine = style.contains("nobreakline"); isDisplay = style.equals("inputform"); isResolver = style.contains("resolver") || urn2baseurl.keySet().contains(style); field = field.replaceAll("\\("+style+"\\)", ""); } // Get the separate schema + element + qualifier String[] eq = field.split("\\."); String schema = eq[0]; String element = eq[1]; String qualifier = null; if (eq.length > 2 && eq[2].equals("*")) { qualifier = Item.ANY; } else if (eq.length > 2) { qualifier = eq[2]; } // check for hidden field, even if it's configured.. if (MetadataExposure.isHidden(context, schema, element, qualifier)) { continue; } // FIXME: Still need to fix for metadata language? DCValue[] values = item.getMetadata(schema, element, qualifier, Item.ANY); if (values.length > 0) { out.print("<tr><td class=\"metadataFieldLabel\">"); String label = null; try { label = I18nUtil.getMessage("metadata." - + (style != null ? style + "." : "") + field, + + ("default".equals(this.style) ? "" : this.style + ".") + field, context); } catch (MissingResourceException e) { // if there is not a specific translation for the style we // use the default one label = LocaleSupport.getLocalizedMessage(pageContext, "metadata." + field); } out.print(label); out.print(":&nbsp;</td><td class=\"metadataFieldValue\">"); //If the values are in controlled vocabulary and the display value should be shown if (isDisplay){ List<String> displayValues = new ArrayList<String>(); displayValues = Util.getControlledVocabulariesDisplayValueLocalized(item, values, schema, element, qualifier, sessionLocale); if (displayValues != null && !displayValues.isEmpty()) { for (int d = 0; d < displayValues.size(); d++) { out.print(displayValues.get(d)); if (d<displayValues.size()-1) out.print(" <br/>"); } } out.print("</td>"); continue; } for (int j = 0; j < values.length; j++) { if (values[j] != null && values[j].value != null) { if (j > 0) { if (isNoBreakLine) { String separator = ConfigurationManager .getProperty("webui.itemdisplay.nobreakline.separator"); if (separator == null) { separator = ";&nbsp;"; } out.print(separator); } else { out.print("<br />"); } } if (isLink) { out.print("<a href=\"" + values[j].value + "\">" + Utils.addEntities(values[j].value) + "</a>"); } else if (isDate) { DCDate dd = new DCDate(values[j].value); // Parse the date out.print(UIUtil.displayDate(dd, false, false, (HttpServletRequest)pageContext.getRequest())); } else if (isResolver) { String value = values[j].value; if (value.startsWith("http://") || value.startsWith("https://") || value.startsWith("ftp://") || value.startsWith("ftps://")) { // Already a URL, print as if it was a regular link out.print("<a href=\"" + value + "\">" + Utils.addEntities(value) + "</a>"); } else { String foundUrn = null; if (!style.equals("resolver")) { foundUrn = style; } else { for (String checkUrn : urn2baseurl.keySet()) { if (value.startsWith(checkUrn)) { foundUrn = checkUrn; } } } if (foundUrn != null) { if (value.startsWith(foundUrn + ":")) { value = value.substring(foundUrn.length()+1); } String url = urn2baseurl.get(foundUrn); out.print("<a href=\"" + url + value + "\">" + Utils.addEntities(values[j].value) + "</a>"); } else { out.print(value); } } } else if (browseIndex != null) { String argument, value; if ( values[j].authority != null && values[j].confidence >= MetadataAuthorityManager.getManager() .getMinConfidence( values[j].schema, values[j].element, values[j].qualifier)) { argument = "authority"; value = values[j].authority; } else { argument = "value"; value = values[j].value; } out.print("<a class=\"" + ("authority".equals(argument)?"authority ":"") + browseIndex + "\"" + "href=\"" + request.getContextPath() + "/browse?type=" + browseIndex + "&amp;" + argument + "=" + URLEncoder.encode(value, "UTF-8") + "\">" + Utils.addEntities(values[j].value) + "</a>"); } else { out.print(Utils.addEntities(values[j].value)); } } } out.println("</td></tr>"); } } listCollections(); out.println("</table></center><br/>"); listBitstreams(); if (ConfigurationManager .getBooleanProperty("webui.licence_bundle.show")) { out.println("<br/><br/>"); showLicence(); } } /** * Render full item record */ private void renderFull() throws IOException, SQLException { JspWriter out = pageContext.getOut(); HttpServletRequest request = (HttpServletRequest)pageContext.getRequest(); Context context = UIUtil.obtainContext(request); // Get all the metadata DCValue[] values = item.getMetadata(Item.ANY, Item.ANY, Item.ANY, Item.ANY); out.println("<p align=\"center\">" + LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.ItemTag.full") + "</p>"); // Three column table - DC field, value, language out.println("<center><table class=\"itemDisplayTable\">"); out.println("<tr><th id=\"s1\" class=\"standard\">" + LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.ItemTag.dcfield") + "</th><th id=\"s2\" class=\"standard\">" + LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.ItemTag.value") + "</th><th id=\"s3\" class=\"standard\">" + LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.ItemTag.lang") + "</th></tr>"); for (int i = 0; i < values.length; i++) { if (!MetadataExposure.isHidden(context, values[i].schema, values[i].element, values[i].qualifier)) { out.print("<tr><td headers=\"s1\" class=\"metadataFieldLabel\">"); out.print(values[i].schema); out.print("." + values[i].element); if (values[i].qualifier != null) { out.print("." + values[i].qualifier); } out.print("</td><td headers=\"s2\" class=\"metadataFieldValue\">"); out.print(Utils.addEntities(values[i].value)); out.print("</td><td headers=\"s3\" class=\"metadataFieldValue\">"); if (values[i].language == null) { out.print("-"); } else { out.print(values[i].language); } out.println("</td></tr>"); } } listCollections(); out.println("</table></center><br/>"); listBitstreams(); if (ConfigurationManager .getBooleanProperty("webui.licence_bundle.show")) { out.println("<br/><br/>"); showLicence(); } } /** * List links to collections if information is available */ private void listCollections() throws IOException { JspWriter out = pageContext.getOut(); HttpServletRequest request = (HttpServletRequest) pageContext .getRequest(); if (collections != null) { out.print("<tr><td class=\"metadataFieldLabel\">"); if (item.getHandle()==null) // assume workspace item { out.print(LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.ItemTag.submitted")); } else { out.print(LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.ItemTag.appears")); } out.print("</td><td class=\"metadataFieldValue\">"); for (int i = 0; i < collections.length; i++) { out.print("<a href=\""); out.print(request.getContextPath()); out.print("/handle/"); out.print(collections[i].getHandle()); out.print("\">"); out.print(collections[i].getMetadata("name")); out.print("</a><br/>"); } out.println("</td></tr>"); } } /** * List bitstreams in the item */ private void listBitstreams() throws IOException { JspWriter out = pageContext.getOut(); HttpServletRequest request = (HttpServletRequest) pageContext .getRequest(); out.print("<table align=\"center\" class=\"miscTable\"><tr>"); out.println("<td class=\"evenRowEvenCol\"><p><strong>" + LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.ItemTag.files") + "</strong></p>"); try { Bundle[] bundles = item.getBundles("ORIGINAL"); boolean filesExist = false; for (Bundle bnd : bundles) { filesExist = bnd.getBitstreams().length > 0; if (filesExist) { break; } } // if user already has uploaded at least one file if (!filesExist) { out.println("<p>" + LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.ItemTag.files.no") + "</p>"); } else { boolean html = false; String handle = item.getHandle(); Bitstream primaryBitstream = null; Bundle[] bunds = item.getBundles("ORIGINAL"); Bundle[] thumbs = item.getBundles("THUMBNAIL"); // if item contains multiple bitstreams, display bitstream // description boolean multiFile = false; Bundle[] allBundles = item.getBundles(); for (int i = 0, filecount = 0; (i < allBundles.length) && !multiFile; i++) { filecount += allBundles[i].getBitstreams().length; multiFile = (filecount > 1); } // check if primary bitstream is html if (bunds[0] != null) { Bitstream[] bits = bunds[0].getBitstreams(); for (int i = 0; (i < bits.length) && !html; i++) { if (bits[i].getID() == bunds[0].getPrimaryBitstreamID()) { html = bits[i].getFormat().getMIMEType().equals( "text/html"); primaryBitstream = bits[i]; } } } out .println("<table cellpadding=\"6\"><tr><th id=\"t1\" class=\"standard\">" + LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.ItemTag.file") + "</th>"); if (multiFile) { out .println("<th id=\"t2\" class=\"standard\">" + LocaleSupport .getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.ItemTag.description") + "</th>"); } out.println("<th id=\"t3\" class=\"standard\">" + LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.ItemTag.filesize") + "</th><th id=\"t4\" class=\"standard\">" + LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.ItemTag.fileformat") + "</th></tr>"); // if primary bitstream is html, display a link for only that one to // HTMLServlet if (html) { // If no real Handle yet (e.g. because Item is in workflow) // we use the 'fake' Handle db-id/1234 where 1234 is the // database ID of the item. if (handle == null) { handle = "db-id/" + item.getID(); } out.print("<tr><td headers=\"t1\" class=\"standard\">"); out.print("<a target=\"_blank\" href=\""); out.print(request.getContextPath()); out.print("/html/"); out.print(handle + "/"); out .print(UIUtil.encodeBitstreamName(primaryBitstream .getName(), Constants.DEFAULT_ENCODING)); out.print("\">"); out.print(primaryBitstream.getName()); out.print("</a>"); if (multiFile) { out.print("</td><td headers=\"t2\" class=\"standard\">"); String desc = primaryBitstream.getDescription(); out.print((desc != null) ? desc : ""); } out.print("</td><td headers=\"t3\" class=\"standard\">"); out.print(UIUtil.formatFileSize(primaryBitstream.getSize())); out.print("</td><td headers=\"t4\" class=\"standard\">"); out.print(primaryBitstream.getFormatDescription()); out .print("</td><td class=\"standard\"><a target=\"_blank\" href=\""); out.print(request.getContextPath()); out.print("/html/"); out.print(handle + "/"); out .print(UIUtil.encodeBitstreamName(primaryBitstream .getName(), Constants.DEFAULT_ENCODING)); out.print("\">" + LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.ItemTag.view") + "</a></td></tr>"); } else { for (int i = 0; i < bundles.length; i++) { Bitstream[] bitstreams = bundles[i].getBitstreams(); for (int k = 0; k < bitstreams.length; k++) { // Skip internal types if (!bitstreams[k].getFormat().isInternal()) { // Work out what the bitstream link should be // (persistent // ID if item has Handle) String bsLink = "<a target=\"_blank\" href=\"" + request.getContextPath(); if ((handle != null) && (bitstreams[k].getSequenceID() > 0)) { bsLink = bsLink + "/bitstream/" + item.getHandle() + "/" + bitstreams[k].getSequenceID() + "/"; } else { bsLink = bsLink + "/retrieve/" + bitstreams[k].getID() + "/"; } bsLink = bsLink + UIUtil.encodeBitstreamName(bitstreams[k] .getName(), Constants.DEFAULT_ENCODING) + "\">"; out .print("<tr><td headers=\"t1\" class=\"standard\">"); out.print(bsLink); out.print(bitstreams[k].getName()); out.print("</a>"); if (multiFile) { out .print("</td><td headers=\"t2\" class=\"standard\">"); String desc = bitstreams[k].getDescription(); out.print((desc != null) ? desc : ""); } out .print("</td><td headers=\"t3\" class=\"standard\">"); out.print(UIUtil.formatFileSize(bitstreams[k].getSize())); out .print("</td><td headers=\"t4\" class=\"standard\">"); out.print(bitstreams[k].getFormatDescription()); out .print("</td><td class=\"standard\" align=\"center\">"); // is there a thumbnail bundle? if ((thumbs.length > 0) && showThumbs) { String tName = bitstreams[k].getName() + ".jpg"; String tAltText = LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.ItemTag.thumbnail"); Bitstream tb = thumbs[0] . getBitstreamByName(tName); if (tb != null) { String myPath = request.getContextPath() + "/retrieve/" + tb.getID() + "/" + UIUtil.encodeBitstreamName(tb .getName(), Constants.DEFAULT_ENCODING); out.print(bsLink); out.print("<img src=\"" + myPath + "\" "); out.print("alt=\"" + tAltText + "\" /></a><br />"); } } out .print(bsLink + LocaleSupport .getLocalizedMessage( pageContext, "org.dspace.app.webui.jsptag.ItemTag.view") + "</a></td></tr>"); } } } } out.println("</table>"); } } catch(SQLException sqle) { throw new IOException(sqle.getMessage(), sqle); } out.println("</td></tr></table>"); } private void getThumbSettings() { showThumbs = ConfigurationManager .getBooleanProperty("webui.item.thumbnail.show"); } /** * Link to the item licence */ private void showLicence() throws IOException { JspWriter out = pageContext.getOut(); HttpServletRequest request = (HttpServletRequest) pageContext .getRequest(); Bundle[] bundles = null; try { bundles = item.getBundles("LICENSE"); } catch(SQLException sqle) { throw new IOException(sqle.getMessage(), sqle); } out.println("<table align=\"center\" class=\"attentionTable\"><tr>"); out.println("<td class=\"attentionCell\"><p><strong>" + LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.ItemTag.itemprotected") + "</strong></p>"); for (int i = 0; i < bundles.length; i++) { Bitstream[] bitstreams = bundles[i].getBitstreams(); for (int k = 0; k < bitstreams.length; k++) { out.print("<div align=\"center\" class=\"standard\">"); out.print("<strong><a target=\"_blank\" href=\""); out.print(request.getContextPath()); out.print("/retrieve/"); out.print(bitstreams[k].getID() + "/"); out.print(UIUtil.encodeBitstreamName(bitstreams[k].getName(), Constants.DEFAULT_ENCODING)); out .print("\">" + LocaleSupport .getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.ItemTag.viewlicence") + "</a></strong></div>"); } } out.println("</td></tr></table>"); } /** * Return the browse index related to the field. <code>null</code> if the field is not a browse field * (look for <cod>webui.browse.link.<n></code> in dspace.cfg) * * @param field * @return the browse index related to the field. Null otherwise * @throws BrowseException */ private String getBrowseField(String field) throws BrowseException { for (String indexName : linkedMetadata.keySet()) { StringTokenizer bw_dcf = new StringTokenizer(linkedMetadata.get(indexName), "."); String[] bw_tokens = { "", "", "" }; int i = 0; while(bw_dcf.hasMoreTokens()) { bw_tokens[i] = bw_dcf.nextToken().toLowerCase().trim(); i++; } String bw_schema = bw_tokens[0]; String bw_element = bw_tokens[1]; String bw_qualifier = bw_tokens[2]; StringTokenizer dcf = new StringTokenizer(field, "."); String[] tokens = { "", "", "" }; int j = 0; while(dcf.hasMoreTokens()) { tokens[j] = dcf.nextToken().toLowerCase().trim(); j++; } String schema = tokens[0]; String element = tokens[1]; String qualifier = tokens[2]; if (schema.equals(bw_schema) // schema match && element.equals(bw_element) // element match && ( (bw_qualifier != null) && ((qualifier != null && qualifier.equals(bw_qualifier)) // both not null and equals || bw_qualifier.equals("*")) // browse link with jolly || (bw_qualifier == null && qualifier == null)) // both null ) { return indexName; } } return null; } }
true
true
private void render() throws IOException, SQLException, DCInputsReaderException { JspWriter out = pageContext.getOut(); HttpServletRequest request = (HttpServletRequest)pageContext.getRequest(); Context context = UIUtil.obtainContext(request); Locale sessionLocale = UIUtil.getSessionLocale(request); String configLine = styleSelection.getConfigurationForStyle(style); if (configLine == null) { configLine = defaultFields; } out.println("<center><table class=\"itemDisplayTable\">"); /* * Break down the configuration into fields and display them * * FIXME?: it may be more efficient to do some processing once, perhaps * to a more efficient intermediate class, but then it would become more * difficult to reload the configuration "on the fly". */ StringTokenizer st = new StringTokenizer(configLine, ","); while (st.hasMoreTokens()) { String field = st.nextToken().trim(); boolean isDate = false; boolean isLink = false; boolean isResolver = false; boolean isNoBreakLine = false; boolean isDisplay = false; String style = null; Matcher fieldStyleMatcher = fieldStylePatter.matcher(field); if (fieldStyleMatcher.matches()){ style = fieldStyleMatcher.group(1); } String browseIndex; try { browseIndex = getBrowseField(field); } catch (BrowseException e) { log.error(e); browseIndex = null; } // Find out if the field should rendered with a particular style if (style != null) { isDate = style.contains("date"); isLink = style.contains("link"); isNoBreakLine = style.contains("nobreakline"); isDisplay = style.equals("inputform"); isResolver = style.contains("resolver") || urn2baseurl.keySet().contains(style); field = field.replaceAll("\\("+style+"\\)", ""); } // Get the separate schema + element + qualifier String[] eq = field.split("\\."); String schema = eq[0]; String element = eq[1]; String qualifier = null; if (eq.length > 2 && eq[2].equals("*")) { qualifier = Item.ANY; } else if (eq.length > 2) { qualifier = eq[2]; } // check for hidden field, even if it's configured.. if (MetadataExposure.isHidden(context, schema, element, qualifier)) { continue; } // FIXME: Still need to fix for metadata language? DCValue[] values = item.getMetadata(schema, element, qualifier, Item.ANY); if (values.length > 0) { out.print("<tr><td class=\"metadataFieldLabel\">"); String label = null; try { label = I18nUtil.getMessage("metadata." + (style != null ? style + "." : "") + field, context); } catch (MissingResourceException e) { // if there is not a specific translation for the style we // use the default one label = LocaleSupport.getLocalizedMessage(pageContext, "metadata." + field); } out.print(label); out.print(":&nbsp;</td><td class=\"metadataFieldValue\">"); //If the values are in controlled vocabulary and the display value should be shown if (isDisplay){ List<String> displayValues = new ArrayList<String>(); displayValues = Util.getControlledVocabulariesDisplayValueLocalized(item, values, schema, element, qualifier, sessionLocale); if (displayValues != null && !displayValues.isEmpty()) { for (int d = 0; d < displayValues.size(); d++) { out.print(displayValues.get(d)); if (d<displayValues.size()-1) out.print(" <br/>"); } } out.print("</td>"); continue; } for (int j = 0; j < values.length; j++) { if (values[j] != null && values[j].value != null) { if (j > 0) { if (isNoBreakLine) { String separator = ConfigurationManager .getProperty("webui.itemdisplay.nobreakline.separator"); if (separator == null) { separator = ";&nbsp;"; } out.print(separator); } else { out.print("<br />"); } } if (isLink) { out.print("<a href=\"" + values[j].value + "\">" + Utils.addEntities(values[j].value) + "</a>"); } else if (isDate) { DCDate dd = new DCDate(values[j].value); // Parse the date out.print(UIUtil.displayDate(dd, false, false, (HttpServletRequest)pageContext.getRequest())); } else if (isResolver) { String value = values[j].value; if (value.startsWith("http://") || value.startsWith("https://") || value.startsWith("ftp://") || value.startsWith("ftps://")) { // Already a URL, print as if it was a regular link out.print("<a href=\"" + value + "\">" + Utils.addEntities(value) + "</a>"); } else { String foundUrn = null; if (!style.equals("resolver")) { foundUrn = style; } else { for (String checkUrn : urn2baseurl.keySet()) { if (value.startsWith(checkUrn)) { foundUrn = checkUrn; } } } if (foundUrn != null) { if (value.startsWith(foundUrn + ":")) { value = value.substring(foundUrn.length()+1); } String url = urn2baseurl.get(foundUrn); out.print("<a href=\"" + url + value + "\">" + Utils.addEntities(values[j].value) + "</a>"); } else { out.print(value); } } } else if (browseIndex != null) { String argument, value; if ( values[j].authority != null && values[j].confidence >= MetadataAuthorityManager.getManager() .getMinConfidence( values[j].schema, values[j].element, values[j].qualifier)) { argument = "authority"; value = values[j].authority; } else { argument = "value"; value = values[j].value; } out.print("<a class=\"" + ("authority".equals(argument)?"authority ":"") + browseIndex + "\"" + "href=\"" + request.getContextPath() + "/browse?type=" + browseIndex + "&amp;" + argument + "=" + URLEncoder.encode(value, "UTF-8") + "\">" + Utils.addEntities(values[j].value) + "</a>"); } else { out.print(Utils.addEntities(values[j].value)); } } } out.println("</td></tr>"); } } listCollections(); out.println("</table></center><br/>"); listBitstreams(); if (ConfigurationManager .getBooleanProperty("webui.licence_bundle.show")) { out.println("<br/><br/>"); showLicence(); } }
private void render() throws IOException, SQLException, DCInputsReaderException { JspWriter out = pageContext.getOut(); HttpServletRequest request = (HttpServletRequest)pageContext.getRequest(); Context context = UIUtil.obtainContext(request); Locale sessionLocale = UIUtil.getSessionLocale(request); String configLine = styleSelection.getConfigurationForStyle(style); if (configLine == null) { configLine = defaultFields; } out.println("<center><table class=\"itemDisplayTable\">"); /* * Break down the configuration into fields and display them * * FIXME?: it may be more efficient to do some processing once, perhaps * to a more efficient intermediate class, but then it would become more * difficult to reload the configuration "on the fly". */ StringTokenizer st = new StringTokenizer(configLine, ","); while (st.hasMoreTokens()) { String field = st.nextToken().trim(); boolean isDate = false; boolean isLink = false; boolean isResolver = false; boolean isNoBreakLine = false; boolean isDisplay = false; String style = null; Matcher fieldStyleMatcher = fieldStylePatter.matcher(field); if (fieldStyleMatcher.matches()){ style = fieldStyleMatcher.group(1); } String browseIndex; try { browseIndex = getBrowseField(field); } catch (BrowseException e) { log.error(e); browseIndex = null; } // Find out if the field should rendered with a particular style if (style != null) { isDate = style.contains("date"); isLink = style.contains("link"); isNoBreakLine = style.contains("nobreakline"); isDisplay = style.equals("inputform"); isResolver = style.contains("resolver") || urn2baseurl.keySet().contains(style); field = field.replaceAll("\\("+style+"\\)", ""); } // Get the separate schema + element + qualifier String[] eq = field.split("\\."); String schema = eq[0]; String element = eq[1]; String qualifier = null; if (eq.length > 2 && eq[2].equals("*")) { qualifier = Item.ANY; } else if (eq.length > 2) { qualifier = eq[2]; } // check for hidden field, even if it's configured.. if (MetadataExposure.isHidden(context, schema, element, qualifier)) { continue; } // FIXME: Still need to fix for metadata language? DCValue[] values = item.getMetadata(schema, element, qualifier, Item.ANY); if (values.length > 0) { out.print("<tr><td class=\"metadataFieldLabel\">"); String label = null; try { label = I18nUtil.getMessage("metadata." + ("default".equals(this.style) ? "" : this.style + ".") + field, context); } catch (MissingResourceException e) { // if there is not a specific translation for the style we // use the default one label = LocaleSupport.getLocalizedMessage(pageContext, "metadata." + field); } out.print(label); out.print(":&nbsp;</td><td class=\"metadataFieldValue\">"); //If the values are in controlled vocabulary and the display value should be shown if (isDisplay){ List<String> displayValues = new ArrayList<String>(); displayValues = Util.getControlledVocabulariesDisplayValueLocalized(item, values, schema, element, qualifier, sessionLocale); if (displayValues != null && !displayValues.isEmpty()) { for (int d = 0; d < displayValues.size(); d++) { out.print(displayValues.get(d)); if (d<displayValues.size()-1) out.print(" <br/>"); } } out.print("</td>"); continue; } for (int j = 0; j < values.length; j++) { if (values[j] != null && values[j].value != null) { if (j > 0) { if (isNoBreakLine) { String separator = ConfigurationManager .getProperty("webui.itemdisplay.nobreakline.separator"); if (separator == null) { separator = ";&nbsp;"; } out.print(separator); } else { out.print("<br />"); } } if (isLink) { out.print("<a href=\"" + values[j].value + "\">" + Utils.addEntities(values[j].value) + "</a>"); } else if (isDate) { DCDate dd = new DCDate(values[j].value); // Parse the date out.print(UIUtil.displayDate(dd, false, false, (HttpServletRequest)pageContext.getRequest())); } else if (isResolver) { String value = values[j].value; if (value.startsWith("http://") || value.startsWith("https://") || value.startsWith("ftp://") || value.startsWith("ftps://")) { // Already a URL, print as if it was a regular link out.print("<a href=\"" + value + "\">" + Utils.addEntities(value) + "</a>"); } else { String foundUrn = null; if (!style.equals("resolver")) { foundUrn = style; } else { for (String checkUrn : urn2baseurl.keySet()) { if (value.startsWith(checkUrn)) { foundUrn = checkUrn; } } } if (foundUrn != null) { if (value.startsWith(foundUrn + ":")) { value = value.substring(foundUrn.length()+1); } String url = urn2baseurl.get(foundUrn); out.print("<a href=\"" + url + value + "\">" + Utils.addEntities(values[j].value) + "</a>"); } else { out.print(value); } } } else if (browseIndex != null) { String argument, value; if ( values[j].authority != null && values[j].confidence >= MetadataAuthorityManager.getManager() .getMinConfidence( values[j].schema, values[j].element, values[j].qualifier)) { argument = "authority"; value = values[j].authority; } else { argument = "value"; value = values[j].value; } out.print("<a class=\"" + ("authority".equals(argument)?"authority ":"") + browseIndex + "\"" + "href=\"" + request.getContextPath() + "/browse?type=" + browseIndex + "&amp;" + argument + "=" + URLEncoder.encode(value, "UTF-8") + "\">" + Utils.addEntities(values[j].value) + "</a>"); } else { out.print(Utils.addEntities(values[j].value)); } } } out.println("</td></tr>"); } } listCollections(); out.println("</table></center><br/>"); listBitstreams(); if (ConfigurationManager .getBooleanProperty("webui.licence_bundle.show")) { out.println("<br/><br/>"); showLicence(); } }
diff --git a/DistFileSystem/src/distclient/ClntCheckPosition.java b/DistFileSystem/src/distclient/ClntCheckPosition.java index 9c79f65..c1fe8f1 100644 --- a/DistFileSystem/src/distclient/ClntCheckPosition.java +++ b/DistFileSystem/src/distclient/ClntCheckPosition.java @@ -1,115 +1,117 @@ package distclient; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; import distconfig.ConnectionCodes; import distconfig.Constants; import distconfig.DistConfig; import distnodelisting.NodeSearchTable; public class ClntCheckPosition implements Runnable { private String host; private Client client; private int id; public ClntCheckPosition(String host, Client client){ this(host, client.getId(), client); } public ClntCheckPosition(String host, int id, Client client){ this.host = host; this.client = client; this.id = Integer.parseInt(NodeSearchTable.get_Instance().get_ownID()); } @Override public void run() { try { DistConfig distConfig = DistConfig.get_Instance(); System.out.println("Connecting"); Socket sock = new Socket(host, distConfig.get_servPortNumber()); sock.setSoTimeout(5000); System.out.println("Connected"); BufferedOutputStream bos = new BufferedOutputStream ( sock.getOutputStream()); System.out.println("Got OutputStream"); PrintWriter outStream = new PrintWriter(bos, false); System.out.println("Got PrintWriter"); BufferedReader in = new BufferedReader ( new InputStreamReader ( sock.getInputStream())); System.out.println("Got InputStream"); System.out.println("Sending Code"); outStream.println(ConnectionCodes.CHECKPOSITION); outStream.flush(); ObjectInputStream ois = new ObjectInputStream(sock.getInputStream()); System.out.println("Got Object InputStream"); System.out.println("Getting Ack"); System.out.println(in.readLine()); System.out.println("Sending my ID as " + id); outStream.println(Integer.toString(id)); outStream.flush(); String tmpline = in.readLine(); System.out.println("Position Code " + tmpline); if (Integer.parseInt(tmpline) == ConnectionCodes.NEWID) { id = Integer.parseInt(in.readLine()); NodeSearchTable.get_Instance().set_own(Integer.toString(id), NodeSearchTable.get_Instance().get_ownIPAddress()); client.setId(id); System.out.println("New ID = " + id); tmpline = in.readLine(); System.out.printf("Received Code %s\n", tmpline); } if ( Integer.parseInt(tmpline) == ConnectionCodes.CORRECTPOSITION) { String[] predecessor = (String[])ois.readObject(); System.out.println("Correct Position"); System.out.println("Pred ID = " + predecessor[Constants.ID]); System.out.println("Pred IP = " + predecessor[Constants.IP_ADDRESS]); String[] successor = (String[])ois.readObject(); System.out.println("Next ID = " + successor[Constants.ID]); System.out.println("Next IP = " + successor[Constants.IP_ADDRESS]); client.setPredecessor(predecessor); client.setSuccessor(successor); + sock.close(); } else { int nextTestId = Integer.parseInt(in.readLine()); String nextTestIp = in.readLine(); System.out.println("Wrong Position"); System.out.println("next ID = " + nextTestId); System.out.println("next IP = " + nextTestIp); + sock.close(); ClntCheckPosition ccp = new ClntCheckPosition (nextTestIp, client); ccp.run(); ccp = null; } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
false
true
public void run() { try { DistConfig distConfig = DistConfig.get_Instance(); System.out.println("Connecting"); Socket sock = new Socket(host, distConfig.get_servPortNumber()); sock.setSoTimeout(5000); System.out.println("Connected"); BufferedOutputStream bos = new BufferedOutputStream ( sock.getOutputStream()); System.out.println("Got OutputStream"); PrintWriter outStream = new PrintWriter(bos, false); System.out.println("Got PrintWriter"); BufferedReader in = new BufferedReader ( new InputStreamReader ( sock.getInputStream())); System.out.println("Got InputStream"); System.out.println("Sending Code"); outStream.println(ConnectionCodes.CHECKPOSITION); outStream.flush(); ObjectInputStream ois = new ObjectInputStream(sock.getInputStream()); System.out.println("Got Object InputStream"); System.out.println("Getting Ack"); System.out.println(in.readLine()); System.out.println("Sending my ID as " + id); outStream.println(Integer.toString(id)); outStream.flush(); String tmpline = in.readLine(); System.out.println("Position Code " + tmpline); if (Integer.parseInt(tmpline) == ConnectionCodes.NEWID) { id = Integer.parseInt(in.readLine()); NodeSearchTable.get_Instance().set_own(Integer.toString(id), NodeSearchTable.get_Instance().get_ownIPAddress()); client.setId(id); System.out.println("New ID = " + id); tmpline = in.readLine(); System.out.printf("Received Code %s\n", tmpline); } if ( Integer.parseInt(tmpline) == ConnectionCodes.CORRECTPOSITION) { String[] predecessor = (String[])ois.readObject(); System.out.println("Correct Position"); System.out.println("Pred ID = " + predecessor[Constants.ID]); System.out.println("Pred IP = " + predecessor[Constants.IP_ADDRESS]); String[] successor = (String[])ois.readObject(); System.out.println("Next ID = " + successor[Constants.ID]); System.out.println("Next IP = " + successor[Constants.IP_ADDRESS]); client.setPredecessor(predecessor); client.setSuccessor(successor); } else { int nextTestId = Integer.parseInt(in.readLine()); String nextTestIp = in.readLine(); System.out.println("Wrong Position"); System.out.println("next ID = " + nextTestId); System.out.println("next IP = " + nextTestIp); ClntCheckPosition ccp = new ClntCheckPosition (nextTestIp, client); ccp.run(); ccp = null; } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
public void run() { try { DistConfig distConfig = DistConfig.get_Instance(); System.out.println("Connecting"); Socket sock = new Socket(host, distConfig.get_servPortNumber()); sock.setSoTimeout(5000); System.out.println("Connected"); BufferedOutputStream bos = new BufferedOutputStream ( sock.getOutputStream()); System.out.println("Got OutputStream"); PrintWriter outStream = new PrintWriter(bos, false); System.out.println("Got PrintWriter"); BufferedReader in = new BufferedReader ( new InputStreamReader ( sock.getInputStream())); System.out.println("Got InputStream"); System.out.println("Sending Code"); outStream.println(ConnectionCodes.CHECKPOSITION); outStream.flush(); ObjectInputStream ois = new ObjectInputStream(sock.getInputStream()); System.out.println("Got Object InputStream"); System.out.println("Getting Ack"); System.out.println(in.readLine()); System.out.println("Sending my ID as " + id); outStream.println(Integer.toString(id)); outStream.flush(); String tmpline = in.readLine(); System.out.println("Position Code " + tmpline); if (Integer.parseInt(tmpline) == ConnectionCodes.NEWID) { id = Integer.parseInt(in.readLine()); NodeSearchTable.get_Instance().set_own(Integer.toString(id), NodeSearchTable.get_Instance().get_ownIPAddress()); client.setId(id); System.out.println("New ID = " + id); tmpline = in.readLine(); System.out.printf("Received Code %s\n", tmpline); } if ( Integer.parseInt(tmpline) == ConnectionCodes.CORRECTPOSITION) { String[] predecessor = (String[])ois.readObject(); System.out.println("Correct Position"); System.out.println("Pred ID = " + predecessor[Constants.ID]); System.out.println("Pred IP = " + predecessor[Constants.IP_ADDRESS]); String[] successor = (String[])ois.readObject(); System.out.println("Next ID = " + successor[Constants.ID]); System.out.println("Next IP = " + successor[Constants.IP_ADDRESS]); client.setPredecessor(predecessor); client.setSuccessor(successor); sock.close(); } else { int nextTestId = Integer.parseInt(in.readLine()); String nextTestIp = in.readLine(); System.out.println("Wrong Position"); System.out.println("next ID = " + nextTestId); System.out.println("next IP = " + nextTestIp); sock.close(); ClntCheckPosition ccp = new ClntCheckPosition (nextTestIp, client); ccp.run(); ccp = null; } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
diff --git a/com/minebans/antispam/checks/PlayerDataChecker.java b/com/minebans/antispam/checks/PlayerDataChecker.java index 8302a51..a1ead29 100755 --- a/com/minebans/antispam/checks/PlayerDataChecker.java +++ b/com/minebans/antispam/checks/PlayerDataChecker.java @@ -1,104 +1,105 @@ package com.minebans.antispam.checks; import java.util.Collections; import java.util.Map.Entry; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import com.minebans.antispam.AntiSpam; import com.minebans.antispam.data.PlayerData; import com.minebans.antispam.events.PlayerSpamDetectedEvent; import com.minebans.antispam.util.ListUtils; public class PlayerDataChecker implements Runnable { public AntiSpam plugin; public PlayerDataChecker(AntiSpam plugin){ this.plugin = plugin; } private boolean isLoginSpammer(PlayerData playerData){ if (playerData.loginCount >= 4){ return true; } if (playerData.loginDelays.size() < 2){ return false; } if (Collections.min(playerData.loginDelays) < 140){ return true; } return (ListUtils.stddev(playerData.loginDelays) < 25); } private boolean isLogoutSpammer(PlayerData playerData){ if (playerData.logoutCount >= 4){ return true; } if (playerData.logoutDelays.size() < 2){ return false; } if (Collections.min(playerData.logoutDelays) < 140){ return true; } return (ListUtils.stddev(playerData.logoutDelays) < 25); } private boolean isChatSpamer(PlayerData playerData){ if (playerData.messageCount >= 8){ return true; } if (playerData.messageDelays.size() < 2){ return false; } if (Collections.min(playerData.messageDelays) < 100){ return true; } return (ListUtils.stddev(playerData.messageDelays) < 20); } public void run(){ String playerName; PlayerData playerData; for (Entry<String, PlayerData> entry : plugin.dataManager.getAll()){ playerName = entry.getKey(); playerData = entry.getValue(); if (this.isChatSpamer(playerData) || this.isLoginSpammer(playerData) || this.isLogoutSpammer(playerData)){ plugin.pluginManager.callEvent(new PlayerSpamDetectedEvent(playerName)); if (playerData.warningCount > 3){ plugin.mineBans.tempBanPlayer(playerName, 1800); plugin.dataManager.unregisterPlayer(playerName); + plugin.server.broadcastMessage(plugin.formatMessage(ChatColor.GREEN + playerName + " has been auto banned for spamming.")); }else{ ++playerData.warningCount; Player player = plugin.server.getPlayer(playerName); if (player != null){ player.sendMessage(plugin.formatMessage(ChatColor.RED + "You have received a warning for spamming.")); player.sendMessage(plugin.formatMessage(ChatColor.RED + "More than three of these will result in a 30 minute ban.")); } playerData.resetCounters(); playerData.resetDelays(); } }else{ playerData.resetCounters(); } } } }
true
true
public void run(){ String playerName; PlayerData playerData; for (Entry<String, PlayerData> entry : plugin.dataManager.getAll()){ playerName = entry.getKey(); playerData = entry.getValue(); if (this.isChatSpamer(playerData) || this.isLoginSpammer(playerData) || this.isLogoutSpammer(playerData)){ plugin.pluginManager.callEvent(new PlayerSpamDetectedEvent(playerName)); if (playerData.warningCount > 3){ plugin.mineBans.tempBanPlayer(playerName, 1800); plugin.dataManager.unregisterPlayer(playerName); }else{ ++playerData.warningCount; Player player = plugin.server.getPlayer(playerName); if (player != null){ player.sendMessage(plugin.formatMessage(ChatColor.RED + "You have received a warning for spamming.")); player.sendMessage(plugin.formatMessage(ChatColor.RED + "More than three of these will result in a 30 minute ban.")); } playerData.resetCounters(); playerData.resetDelays(); } }else{ playerData.resetCounters(); } } }
public void run(){ String playerName; PlayerData playerData; for (Entry<String, PlayerData> entry : plugin.dataManager.getAll()){ playerName = entry.getKey(); playerData = entry.getValue(); if (this.isChatSpamer(playerData) || this.isLoginSpammer(playerData) || this.isLogoutSpammer(playerData)){ plugin.pluginManager.callEvent(new PlayerSpamDetectedEvent(playerName)); if (playerData.warningCount > 3){ plugin.mineBans.tempBanPlayer(playerName, 1800); plugin.dataManager.unregisterPlayer(playerName); plugin.server.broadcastMessage(plugin.formatMessage(ChatColor.GREEN + playerName + " has been auto banned for spamming.")); }else{ ++playerData.warningCount; Player player = plugin.server.getPlayer(playerName); if (player != null){ player.sendMessage(plugin.formatMessage(ChatColor.RED + "You have received a warning for spamming.")); player.sendMessage(plugin.formatMessage(ChatColor.RED + "More than three of these will result in a 30 minute ban.")); } playerData.resetCounters(); playerData.resetDelays(); } }else{ playerData.resetCounters(); } } }
diff --git a/src/main/java/org/apache/james/jspf/terms/ExpModifier.java b/src/main/java/org/apache/james/jspf/terms/ExpModifier.java index 0686114..d7b281e 100644 --- a/src/main/java/org/apache/james/jspf/terms/ExpModifier.java +++ b/src/main/java/org/apache/james/jspf/terms/ExpModifier.java @@ -1,92 +1,92 @@ /*********************************************************************** * Copyright (c) 2006 The Apache Software Foundation. * * All rights reserved. * * ------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); you * * may not use this file except in compliance with the License. You * * may obtain a copy of the License at: * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * * implied. See the License for the specific language governing * * permissions and limitations under the License. * ***********************************************************************/ package org.apache.james.jspf.terms; import org.apache.james.jspf.core.SPF1Constants; import org.apache.james.jspf.core.SPF1Data; import org.apache.james.jspf.exceptions.NoneException; import org.apache.james.jspf.exceptions.PermErrorException; import org.apache.james.jspf.exceptions.TempErrorException; import org.apache.james.jspf.macro.MacroExpand; import org.apache.james.jspf.parser.SPF1Parser; /** * This class represent the exp modifier * * @author Norman Maurer <[email protected]> * @author Stefano Bagnara <[email protected]> * */ public class ExpModifier extends GenericModifier { /** * ABNF: explanation = "exp" "=" domain-spec */ public static final String REGEX = "[eE][xX][pP]" + "\\=" + SPF1Parser.DOMAIN_SPEC_REGEX; /** * Generate the explanation and set it in SPF1Data so it can be accessed * easy later if needed * * @param spfData * The SPF1Data which should used * */ public String run(SPF1Data spfData) { String exp = null; String host = this.host; // If the currentResult is not fail we have no need to run all these // methods! if (!spfData.getCurrentResult().equals(SPF1Constants.FAIL)) return null; // If we should ignore the explanation we don't have to run this class if (spfData.ignoreExplanation() == true) return null; try { host = new MacroExpand(spfData).expandDomain(host); try { exp = spfData.getDnsProbe().getTxtCatType(host); } catch (NoneException e) { // Nothing todo here.. just return the default explanation } catch (TempErrorException e) { // Nothing todo here.. just return the default explanation } - if ((exp != null) || (!exp.equals(""))) { + if ((exp != null) && (!exp.equals(""))) { spfData.setExplanation(new MacroExpand(spfData) .expandExplanation(exp)); } } catch (PermErrorException e) { // Only catch the error and set the explanation spfData.setExplanation(""); } return null; } /** * @see org.apache.james.jspf.core.Modifier#enforceSingleInstance() */ public boolean enforceSingleInstance() { return true; } }
true
true
public String run(SPF1Data spfData) { String exp = null; String host = this.host; // If the currentResult is not fail we have no need to run all these // methods! if (!spfData.getCurrentResult().equals(SPF1Constants.FAIL)) return null; // If we should ignore the explanation we don't have to run this class if (spfData.ignoreExplanation() == true) return null; try { host = new MacroExpand(spfData).expandDomain(host); try { exp = spfData.getDnsProbe().getTxtCatType(host); } catch (NoneException e) { // Nothing todo here.. just return the default explanation } catch (TempErrorException e) { // Nothing todo here.. just return the default explanation } if ((exp != null) || (!exp.equals(""))) { spfData.setExplanation(new MacroExpand(spfData) .expandExplanation(exp)); } } catch (PermErrorException e) { // Only catch the error and set the explanation spfData.setExplanation(""); } return null; }
public String run(SPF1Data spfData) { String exp = null; String host = this.host; // If the currentResult is not fail we have no need to run all these // methods! if (!spfData.getCurrentResult().equals(SPF1Constants.FAIL)) return null; // If we should ignore the explanation we don't have to run this class if (spfData.ignoreExplanation() == true) return null; try { host = new MacroExpand(spfData).expandDomain(host); try { exp = spfData.getDnsProbe().getTxtCatType(host); } catch (NoneException e) { // Nothing todo here.. just return the default explanation } catch (TempErrorException e) { // Nothing todo here.. just return the default explanation } if ((exp != null) && (!exp.equals(""))) { spfData.setExplanation(new MacroExpand(spfData) .expandExplanation(exp)); } } catch (PermErrorException e) { // Only catch the error and set the explanation spfData.setExplanation(""); } return null; }
diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmail.java b/Essentials/src/com/earth2me/essentials/commands/Commandmail.java index 9b7f57fb..b54b88a1 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmail.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmail.java @@ -1,75 +1,75 @@ package com.earth2me.essentials.commands; import java.util.List; import org.bukkit.Server; import com.earth2me.essentials.User; import com.earth2me.essentials.Util; import org.bukkit.ChatColor; import org.bukkit.entity.Player; public class Commandmail extends EssentialsCommand { public Commandmail() { super("mail"); } @Override public void run(Server server, User user, String commandLabel, String[] args) throws Exception { if (args.length >= 1 && "read".equalsIgnoreCase(args[0])) { List<String> mail = user.getMails(); if (mail.isEmpty()) { user.sendMessage(Util.i18n("noMail")); return; } for (String s : mail) { user.sendMessage(s); } user.sendMessage(Util.i18n("mailClear")); return; } if (args.length >= 3 && "send".equalsIgnoreCase(args[0])) { if (!user.isAuthorized("essentials.mail.send")) { user.sendMessage(Util.i18n("noMailSendPerm")); return; } Player player = server.getPlayer(args[1]); User u; if (player != null) { u = ess.getUser(player); } else { u = ess.getOfflineUser(args[1]); } if (u == null) { user.sendMessage(Util.format("playerNeverOnServer", args[1])); return; } charge(user); if (!u.isIgnoredPlayer(user.getName())) { u.addMail(ChatColor.stripColor(user.getDisplayName()) + ": " + getFinalArg(args, 2)); } user.sendMessage(Util.i18n("mailSent")); return; } if (args.length >= 1 && "clear".equalsIgnoreCase(args[0])) { user.setMails(null); user.sendMessage(Util.i18n("mailCleared")); return; } - user.sendMessage(Util.format("usage", "/mail [read|clear|send [to] [message]]")); + throw new NotEnoughArgumentsException(); } }
true
true
public void run(Server server, User user, String commandLabel, String[] args) throws Exception { if (args.length >= 1 && "read".equalsIgnoreCase(args[0])) { List<String> mail = user.getMails(); if (mail.isEmpty()) { user.sendMessage(Util.i18n("noMail")); return; } for (String s : mail) { user.sendMessage(s); } user.sendMessage(Util.i18n("mailClear")); return; } if (args.length >= 3 && "send".equalsIgnoreCase(args[0])) { if (!user.isAuthorized("essentials.mail.send")) { user.sendMessage(Util.i18n("noMailSendPerm")); return; } Player player = server.getPlayer(args[1]); User u; if (player != null) { u = ess.getUser(player); } else { u = ess.getOfflineUser(args[1]); } if (u == null) { user.sendMessage(Util.format("playerNeverOnServer", args[1])); return; } charge(user); if (!u.isIgnoredPlayer(user.getName())) { u.addMail(ChatColor.stripColor(user.getDisplayName()) + ": " + getFinalArg(args, 2)); } user.sendMessage(Util.i18n("mailSent")); return; } if (args.length >= 1 && "clear".equalsIgnoreCase(args[0])) { user.setMails(null); user.sendMessage(Util.i18n("mailCleared")); return; } user.sendMessage(Util.format("usage", "/mail [read|clear|send [to] [message]]")); }
public void run(Server server, User user, String commandLabel, String[] args) throws Exception { if (args.length >= 1 && "read".equalsIgnoreCase(args[0])) { List<String> mail = user.getMails(); if (mail.isEmpty()) { user.sendMessage(Util.i18n("noMail")); return; } for (String s : mail) { user.sendMessage(s); } user.sendMessage(Util.i18n("mailClear")); return; } if (args.length >= 3 && "send".equalsIgnoreCase(args[0])) { if (!user.isAuthorized("essentials.mail.send")) { user.sendMessage(Util.i18n("noMailSendPerm")); return; } Player player = server.getPlayer(args[1]); User u; if (player != null) { u = ess.getUser(player); } else { u = ess.getOfflineUser(args[1]); } if (u == null) { user.sendMessage(Util.format("playerNeverOnServer", args[1])); return; } charge(user); if (!u.isIgnoredPlayer(user.getName())) { u.addMail(ChatColor.stripColor(user.getDisplayName()) + ": " + getFinalArg(args, 2)); } user.sendMessage(Util.i18n("mailSent")); return; } if (args.length >= 1 && "clear".equalsIgnoreCase(args[0])) { user.setMails(null); user.sendMessage(Util.i18n("mailCleared")); return; } throw new NotEnoughArgumentsException(); }
diff --git a/src/main/java/ar/edu/utn/tacs/group5/controller/GetFeedController.java b/src/main/java/ar/edu/utn/tacs/group5/controller/GetFeedController.java index 1492c1b..641d90a 100644 --- a/src/main/java/ar/edu/utn/tacs/group5/controller/GetFeedController.java +++ b/src/main/java/ar/edu/utn/tacs/group5/controller/GetFeedController.java @@ -1,77 +1,72 @@ package ar.edu.utn.tacs.group5.controller; import java.io.PrintWriter; import java.util.logging.Logger; import org.apache.commons.httpclient.HttpStatus; import org.slim3.controller.Controller; import org.slim3.controller.Navigation; import ar.edu.utn.tacs.group5.model.Feed; import ar.edu.utn.tacs.group5.service.FeedService; import com.github.mustachejava.DefaultMustacheFactory; import com.github.mustachejava.Mustache; import com.github.mustachejava.MustacheFactory; import com.google.appengine.api.datastore.KeyFactory; import com.google.common.net.MediaType; public class GetFeedController extends Controller { private static final String INVALID_FEED_KEY = "The provided feed key is invalid"; private static final String ALLOWED_METHODS = "Allowed methods: GET"; static final String FEED_TEMPLATE = "feed.mustache"; private Logger logger = Logger.getLogger(this.getClass().getName()); private MustacheFactory mustacheFactory = new DefaultMustacheFactory(); private FeedService feedService = new FeedService(); @Override public Navigation run() throws Exception { - Long userId = sessionScope(Constants.USER_ID); - if (userId == null) { - response.setStatus(HttpStatus.SC_FORBIDDEN); - return null; - } if (!isGet()) { response.setStatus(HttpStatus.SC_METHOD_NOT_ALLOWED); response.getWriter().print(ALLOWED_METHODS); return null; } String encodedFeedKey = param(Constants.FEED); if (encodedFeedKey == null) { response.setStatus(HttpStatus.SC_BAD_REQUEST); return null; } logger.info("Encoded Feed key: " + encodedFeedKey); Feed feed; try { feed = feedService.getByKey(encodedFeedKey); } catch (IllegalArgumentException e) { response.setStatus(HttpStatus.SC_BAD_REQUEST); response.getWriter().print(INVALID_FEED_KEY); return null; } logger.info(feed.toString()); feed.setLink(getHostUrl() + "GetFeed?feed=" + KeyFactory.keyToString(feed.getKey())); response.setContentType(MediaType.XML_UTF_8.toString()); response.setStatus(HttpStatus.SC_OK); Mustache mustache = mustacheFactory.compile(FEED_TEMPLATE); mustache.execute(new PrintWriter(response.getWriter()), feed).flush(); return null; } private String getHostUrl() { final String hostUrl; String environment = System.getProperty("com.google.appengine.runtime.environment"); if (environment != null && "Production".contentEquals(environment)) { String applicationId = System.getProperty("com.google.appengine.application.id"); String version = System.getProperty("com.google.appengine.application.version"); hostUrl = String.format("http://%s.%s.appspot.com/", version, applicationId); } else { hostUrl = "http://localhost:8888/"; } return hostUrl; } }
true
true
public Navigation run() throws Exception { Long userId = sessionScope(Constants.USER_ID); if (userId == null) { response.setStatus(HttpStatus.SC_FORBIDDEN); return null; } if (!isGet()) { response.setStatus(HttpStatus.SC_METHOD_NOT_ALLOWED); response.getWriter().print(ALLOWED_METHODS); return null; } String encodedFeedKey = param(Constants.FEED); if (encodedFeedKey == null) { response.setStatus(HttpStatus.SC_BAD_REQUEST); return null; } logger.info("Encoded Feed key: " + encodedFeedKey); Feed feed; try { feed = feedService.getByKey(encodedFeedKey); } catch (IllegalArgumentException e) { response.setStatus(HttpStatus.SC_BAD_REQUEST); response.getWriter().print(INVALID_FEED_KEY); return null; } logger.info(feed.toString()); feed.setLink(getHostUrl() + "GetFeed?feed=" + KeyFactory.keyToString(feed.getKey())); response.setContentType(MediaType.XML_UTF_8.toString()); response.setStatus(HttpStatus.SC_OK); Mustache mustache = mustacheFactory.compile(FEED_TEMPLATE); mustache.execute(new PrintWriter(response.getWriter()), feed).flush(); return null; }
public Navigation run() throws Exception { if (!isGet()) { response.setStatus(HttpStatus.SC_METHOD_NOT_ALLOWED); response.getWriter().print(ALLOWED_METHODS); return null; } String encodedFeedKey = param(Constants.FEED); if (encodedFeedKey == null) { response.setStatus(HttpStatus.SC_BAD_REQUEST); return null; } logger.info("Encoded Feed key: " + encodedFeedKey); Feed feed; try { feed = feedService.getByKey(encodedFeedKey); } catch (IllegalArgumentException e) { response.setStatus(HttpStatus.SC_BAD_REQUEST); response.getWriter().print(INVALID_FEED_KEY); return null; } logger.info(feed.toString()); feed.setLink(getHostUrl() + "GetFeed?feed=" + KeyFactory.keyToString(feed.getKey())); response.setContentType(MediaType.XML_UTF_8.toString()); response.setStatus(HttpStatus.SC_OK); Mustache mustache = mustacheFactory.compile(FEED_TEMPLATE); mustache.execute(new PrintWriter(response.getWriter()), feed).flush(); return null; }