List of usage examples for java.util SortedSet add
boolean add(E e);
From source file:fll.scheduler.GreedySolver.java
private void outputSchedule(final File schedule) throws IOException { final List<SubjectiveStation> subjectiveStations = solverParameters.getSubjectiveStations(); try (final CSVWriter csv = new CSVWriter( new OutputStreamWriter(new FileOutputStream(schedule), Utilities.DEFAULT_CHARSET))) { final List<String> line = new ArrayList<String>(); line.add(TournamentSchedule.TEAM_NUMBER_HEADER); line.add(TournamentSchedule.TEAM_NAME_HEADER); line.add(TournamentSchedule.ORGANIZATION_HEADER); line.add(TournamentSchedule.JUDGE_GROUP_HEADER); for (final SubjectiveStation station : subjectiveStations) { line.add(station.getName()); }/*ww w .j a v a 2 s . c o m*/ for (int round = 0; round < solverParameters.getNumPerformanceRounds(); ++round) { line.add(String.format(TournamentSchedule.PERF_HEADER_FORMAT, round + 1)); line.add(String.format(TournamentSchedule.TABLE_HEADER_FORMAT, round + 1)); } csv.writeNext(line.toArray(new String[line.size()])); line.clear(); for (final SchedTeam team : getAllTeams()) { final int teamNum = (team.getGroup() + 1) * 100 + team.getIndex(); final int judgingGroup = team.getGroup(); line.add(String.valueOf(teamNum)); line.add("Team " + teamNum); line.add("Org " + teamNum); line.add(groupNames[judgingGroup]); // judging group for (int subj = 0; subj < subjectiveStations.size(); ++subj) { final SubjectiveStation station = subjectiveStations.get(subj); final LocalTime time = getTime(sz[team.getGroup()][team.getIndex()][subj], 1); if (null == time) { throw new RuntimeException( "Could not find a subjective start for group: " + groupNames[team.getGroup()] + " team: " + (team.getIndex() + 1) + " subj: " + station.getName()); } line.add(TournamentSchedule.formatTime(time)); } // find all performances for a team and then sort by time final SortedSet<PerformanceTime> perfTimes = new TreeSet<PerformanceTime>(); for (int round = 0; round < solverParameters.getNumPerformanceRounds(); ++round) { for (int table = 0; table < solverParameters.getNumTables(); ++table) { for (int side = 0; side < 2; ++side) { final LocalTime time = getTime(pz[team.getGroup()][team.getIndex()][table][side], round + 1); if (null != time) { final String tableName = String.format("Table%d", (table + 1)); final int displayedSide = side + 1; perfTimes.add(new PerformanceTime(time, tableName, displayedSide)); } } } } if (perfTimes.size() != solverParameters.getNumPerformanceRounds()) { throw new FLLRuntimeException("Expecting " + solverParameters.getNumPerformanceRounds() + " performance times, but found " + perfTimes.size() + " group: " + (team.getGroup() + 1) + " team: " + (team.getIndex() + 1) + " perfs: " + perfTimes); } for (final PerformanceTime perfTime : perfTimes) { line.add(TournamentSchedule.formatTime(perfTime.getTime())); line.add(perfTime.getTable() + " " + perfTime.getSide()); } csv.writeNext(line.toArray(new String[line.size()])); line.clear(); } } }
From source file:net.sourceforge.fenixedu.domain.ExecutionCourse.java
public static ExecutionCourse readLastByExecutionYearAndSigla(final String sigla, ExecutionYear executionYear) { SortedSet<ExecutionCourse> result = new TreeSet<ExecutionCourse>( EXECUTION_COURSE_EXECUTION_PERIOD_COMPARATOR); for (final ExecutionSemester executionSemester : executionYear.getExecutionPeriodsSet()) { for (ExecutionCourse executionCourse : executionSemester.getAssociatedExecutionCoursesSet()) { if (sigla.equalsIgnoreCase(executionCourse.getSigla())) { result.add(executionCourse); }//from w w w. ja v a 2 s .c om } } return result.isEmpty() ? null : result.last(); }
From source file:com.mobicage.rogerthat.plugins.messaging.ServiceMessageDetailActivity.java
protected void updateMessageDetail(final boolean isUpdate) { T.UI();/*w w w.j a va2 s .c om*/ // Set sender avatar ImageView avatarImage = (ImageView) findViewById(R.id.avatar); String sender = mCurrentMessage.sender; setAvatar(avatarImage, sender); // Set sender name TextView senderView = (TextView) findViewById(R.id.sender); final String senderName = mFriendsPlugin.getName(sender); senderView.setText(senderName == null ? sender : senderName); // Set timestamp TextView timestampView = (TextView) findViewById(R.id.timestamp); timestampView.setText(TimeUtils.getDayTimeStr(this, mCurrentMessage.timestamp * 1000)); // Set clickable region on top to go to friends detail final RelativeLayout messageHeader = (RelativeLayout) findViewById(R.id.message_header); messageHeader.setOnClickListener(getFriendDetailOnClickListener(mCurrentMessage.sender)); messageHeader.setVisibility(View.VISIBLE); // Set message TextView messageView = (TextView) findViewById(R.id.message); WebView web = (WebView) findViewById(R.id.webview); FrameLayout flay = (FrameLayout) findViewById(R.id.message_details); Resources resources = getResources(); flay.setBackgroundColor(resources.getColor(R.color.mc_background)); boolean showBranded = false; int darkSchemeTextColor = resources.getColor(android.R.color.primary_text_dark); int lightSchemeTextColor = resources.getColor(android.R.color.primary_text_light); senderView.setTextColor(lightSchemeTextColor); timestampView.setTextColor(lightSchemeTextColor); BrandingResult br = null; if (!TextUtils.isEmptyOrWhitespace(mCurrentMessage.branding)) { boolean brandingAvailable = false; try { brandingAvailable = mMessagingPlugin.getBrandingMgr().isBrandingAvailable(mCurrentMessage.branding); } catch (BrandingFailureException e1) { L.d(e1); } try { if (brandingAvailable) { br = mMessagingPlugin.getBrandingMgr().prepareBranding(mCurrentMessage); WebSettings settings = web.getSettings(); settings.setJavaScriptEnabled(false); settings.setBlockNetworkImage(false); web.loadUrl("file://" + br.file.getAbsolutePath()); web.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); if (br.color != null) { flay.setBackgroundColor(br.color); } if (!br.showHeader) { messageHeader.setVisibility(View.GONE); MarginLayoutParams mlp = (MarginLayoutParams) web.getLayoutParams(); mlp.setMargins(0, 0, 0, mlp.bottomMargin); } else if (br.scheme == ColorScheme.dark) { senderView.setTextColor(darkSchemeTextColor); timestampView.setTextColor(darkSchemeTextColor); } showBranded = true; } else { mMessagingPlugin.getBrandingMgr().queueGenericBranding(mCurrentMessage.branding); } } catch (BrandingFailureException e) { L.bug("Could not display message with branding: branding is available, but prepareBranding failed", e); } } if (showBranded) { web.setVisibility(View.VISIBLE); messageView.setVisibility(View.GONE); } else { web.setVisibility(View.GONE); messageView.setVisibility(View.VISIBLE); messageView.setText(mCurrentMessage.message); } // Add list of members who did not ack yet FlowLayout memberSummary = (FlowLayout) findViewById(R.id.member_summary); memberSummary.removeAllViews(); SortedSet<MemberStatusTO> memberSummarySet = new TreeSet<MemberStatusTO>(getMemberstatusComparator()); for (MemberStatusTO ms : mCurrentMessage.members) { if ((ms.status & MessagingPlugin.STATUS_ACKED) != MessagingPlugin.STATUS_ACKED && !ms.member.equals(mCurrentMessage.sender)) { memberSummarySet.add(ms); } } FlowLayout.LayoutParams flowLP = new FlowLayout.LayoutParams(2, 0); for (MemberStatusTO ms : memberSummarySet) { FrameLayout fl = new FrameLayout(this); fl.setLayoutParams(flowLP); memberSummary.addView(fl); fl.addView(createParticipantView(ms)); } memberSummary.setVisibility(memberSummarySet.size() < 2 ? View.GONE : View.VISIBLE); // Add members statuses final LinearLayout members = (LinearLayout) findViewById(R.id.members); members.removeAllViews(); final String myEmail = mService.getIdentityStore().getIdentity().getEmail(); boolean isMember = false; mSomebodyAnswered = false; for (MemberStatusTO ms : mCurrentMessage.members) { boolean showMember = true; View view = getLayoutInflater().inflate(R.layout.message_member_detail, null); // Set receiver avatar RelativeLayout rl = (RelativeLayout) view.findViewById(R.id.avatar); rl.addView(createParticipantView(ms)); // Set receiver name TextView receiverView = (TextView) view.findViewById(R.id.receiver); final String memberName = mFriendsPlugin.getName(ms.member); receiverView.setText(memberName == null ? sender : memberName); // Set received timestamp TextView receivedView = (TextView) view.findViewById(R.id.received_timestamp); if ((ms.status & MessagingPlugin.STATUS_RECEIVED) == MessagingPlugin.STATUS_RECEIVED) { final String humanTime = TimeUtils.getDayTimeStr(this, ms.received_timestamp * 1000); if (ms.member.equals(mCurrentMessage.sender)) receivedView.setText(getString(R.string.sent_at, humanTime)); else receivedView.setText(getString(R.string.received_at, humanTime)); } else { receivedView.setText(R.string.not_yet_received); } // Set replied timestamp TextView repliedView = (TextView) view.findViewById(R.id.acked_timestamp); if ((ms.status & MessagingPlugin.STATUS_ACKED) == MessagingPlugin.STATUS_ACKED) { mSomebodyAnswered = true; String acked_timestamp = TimeUtils.getDayTimeStr(this, ms.acked_timestamp * 1000); if (ms.button_id != null) { ButtonTO button = null; for (ButtonTO b : mCurrentMessage.buttons) { if (b.id.equals(ms.button_id)) { button = b; break; } } if (button == null) { repliedView.setText(getString(R.string.dismissed_at, acked_timestamp)); // Do not show sender as member if he hasn't clicked a // button showMember = !ms.member.equals(mCurrentMessage.sender); } else { repliedView.setText(getString(R.string.replied_at, button.caption, acked_timestamp)); } } else { if (ms.custom_reply == null) { // Do not show sender as member if he hasn't clicked a // button showMember = !ms.member.equals(mCurrentMessage.sender); repliedView.setText(getString(R.string.dismissed_at, acked_timestamp)); } else repliedView.setText(getString(R.string.replied_at, ms.custom_reply, acked_timestamp)); } } else { repliedView.setText(R.string.not_yet_replied); showMember = !ms.member.equals(mCurrentMessage.sender); } if (br != null && br.scheme == ColorScheme.dark) { receiverView.setTextColor(darkSchemeTextColor); receivedView.setTextColor(darkSchemeTextColor); repliedView.setTextColor(darkSchemeTextColor); } else { receiverView.setTextColor(lightSchemeTextColor); receivedView.setTextColor(lightSchemeTextColor); repliedView.setTextColor(lightSchemeTextColor); } if (showMember) members.addView(view); isMember |= ms.member.equals(myEmail); } boolean isLocked = (mCurrentMessage.flags & MessagingPlugin.FLAG_LOCKED) == MessagingPlugin.FLAG_LOCKED; boolean canEdit = isMember && !isLocked; // Add attachments LinearLayout attachmentLayout = (LinearLayout) findViewById(R.id.attachment_layout); attachmentLayout.removeAllViews(); if (mCurrentMessage.attachments.length > 0) { attachmentLayout.setVisibility(View.VISIBLE); for (final AttachmentTO attachment : mCurrentMessage.attachments) { View v = getLayoutInflater().inflate(R.layout.attachment_item, null); ImageView attachment_image = (ImageView) v.findViewById(R.id.attachment_image); if (AttachmentViewerActivity.CONTENT_TYPE_JPEG.equalsIgnoreCase(attachment.content_type) || AttachmentViewerActivity.CONTENT_TYPE_PNG.equalsIgnoreCase(attachment.content_type)) { attachment_image.setImageResource(R.drawable.attachment_img); } else if (AttachmentViewerActivity.CONTENT_TYPE_PDF.equalsIgnoreCase(attachment.content_type)) { attachment_image.setImageResource(R.drawable.attachment_pdf); } else if (AttachmentViewerActivity.CONTENT_TYPE_VIDEO_MP4 .equalsIgnoreCase(attachment.content_type)) { attachment_image.setImageResource(R.drawable.attachment_video); } else { attachment_image.setImageResource(R.drawable.attachment_unknown); L.d("attachment.content_type not known: " + attachment.content_type); } TextView attachment_text = (TextView) v.findViewById(R.id.attachment_text); attachment_text.setText(attachment.name); v.setOnClickListener(new SafeViewOnClickListener() { @Override public void safeOnClick(View v) { String downloadUrlHash = mMessagingPlugin .attachmentDownloadUrlHash(attachment.download_url); File attachmentsDir; try { attachmentsDir = mMessagingPlugin.attachmentsDir(mCurrentMessage.getThreadKey(), null); } catch (IOException e) { L.d("Unable to create attachment directory", e); UIUtils.showAlertDialog(ServiceMessageDetailActivity.this, "", R.string.unable_to_read_write_sd_card); return; } boolean attachmentAvailable = mMessagingPlugin.attachmentExists(attachmentsDir, downloadUrlHash); if (!attachmentAvailable) { try { attachmentsDir = mMessagingPlugin.attachmentsDir(mCurrentMessage.getThreadKey(), mCurrentMessage.key); } catch (IOException e) { L.d("Unable to create attachment directory", e); UIUtils.showAlertDialog(ServiceMessageDetailActivity.this, "", R.string.unable_to_read_write_sd_card); return; } attachmentAvailable = mMessagingPlugin.attachmentExists(attachmentsDir, downloadUrlHash); } if (!mService.getNetworkConnectivityManager().isConnected() && !attachmentAvailable) { AlertDialog.Builder builder = new AlertDialog.Builder( ServiceMessageDetailActivity.this); builder.setMessage(R.string.no_internet_connection_try_again); builder.setPositiveButton(R.string.rogerthat, null); AlertDialog dialog = builder.create(); dialog.show(); return; } if (IOUtils.shouldCheckExternalStorageAvailable()) { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { // Its all oke } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { if (!attachmentAvailable) { L.d("Unable to write to sd-card"); UIUtils.showAlertDialog(ServiceMessageDetailActivity.this, "", R.string.unable_to_read_write_sd_card); return; } } else { L.d("Unable to read or write to sd-card"); UIUtils.showAlertDialog(ServiceMessageDetailActivity.this, "", R.string.unable_to_read_write_sd_card); return; } } L.d("attachment.content_type: " + attachment.content_type); L.d("attachment.download_url: " + attachment.download_url); L.d("attachment.name: " + attachment.name); L.d("attachment.size: " + attachment.size); if (AttachmentViewerActivity.supportsContentType(attachment.content_type)) { Intent i = new Intent(ServiceMessageDetailActivity.this, AttachmentViewerActivity.class); i.putExtra("thread_key", mCurrentMessage.getThreadKey()); i.putExtra("message", mCurrentMessage.key); i.putExtra("content_type", attachment.content_type); i.putExtra("download_url", attachment.download_url); i.putExtra("name", attachment.name); i.putExtra("download_url_hash", downloadUrlHash); startActivity(i); } else { AlertDialog.Builder builder = new AlertDialog.Builder( ServiceMessageDetailActivity.this); builder.setMessage(getString(R.string.attachment_can_not_be_displayed_in_your_version, getString(R.string.app_name))); builder.setPositiveButton(R.string.rogerthat, null); AlertDialog dialog = builder.create(); dialog.show(); } } }); attachmentLayout.addView(v); } } else { attachmentLayout.setVisibility(View.GONE); } LinearLayout widgetLayout = (LinearLayout) findViewById(R.id.widget_layout); if (mCurrentMessage.form == null) { widgetLayout.setVisibility(View.GONE); } else { widgetLayout.setVisibility(View.VISIBLE); widgetLayout.setEnabled(canEdit); displayWidget(widgetLayout, br); } // Add buttons TableLayout tableLayout = (TableLayout) findViewById(R.id.buttons); tableLayout.removeAllViews(); for (final ButtonTO button : mCurrentMessage.buttons) { addButton(senderName, myEmail, mSomebodyAnswered, canEdit, tableLayout, button); } if (mCurrentMessage.form == null && (mCurrentMessage.flags & MessagingPlugin.FLAG_ALLOW_DISMISS) == MessagingPlugin.FLAG_ALLOW_DISMISS) { ButtonTO button = new ButtonTO(); button.caption = "Roger that!"; addButton(senderName, myEmail, mSomebodyAnswered, canEdit, tableLayout, button); } if (mCurrentMessage.broadcast_type != null) { L.d("Show broadcast spam control"); final RelativeLayout broadcastSpamControl = (RelativeLayout) findViewById(R.id.broadcast_spam_control); View broadcastSpamControlBorder = findViewById(R.id.broadcast_spam_control_border); final View broadcastSpamControlDivider = findViewById(R.id.broadcast_spam_control_divider); final LinearLayout broadcastSpamControlTextContainer = (LinearLayout) findViewById( R.id.broadcast_spam_control_text_container); TextView broadcastSpamControlText = (TextView) findViewById(R.id.broadcast_spam_control_text); final LinearLayout broadcastSpamControlSettingsContainer = (LinearLayout) findViewById( R.id.broadcast_spam_control_settings_container); TextView broadcastSpamControlSettingsText = (TextView) findViewById( R.id.broadcast_spam_control_settings_text); TextView broadcastSpamControlIcon = (TextView) findViewById(R.id.broadcast_spam_control_icon); broadcastSpamControlIcon.setTypeface(mFontAwesomeTypeFace); broadcastSpamControlIcon.setText(R.string.fa_bell); final FriendBroadcastInfo fbi = mFriendsPlugin.getFriendBroadcastFlowForMfr(mCurrentMessage.sender); if (fbi == null) { L.bug("BroadcastData was null for: " + mCurrentMessage.sender); collapseDetails(DETAIL_SECTIONS); return; } broadcastSpamControl.setVisibility(View.VISIBLE); broadcastSpamControlSettingsContainer.setOnClickListener(new SafeViewOnClickListener() { @Override public void safeOnClick(View v) { L.d("goto broadcast settings"); PressMenuIconRequestTO request = new PressMenuIconRequestTO(); request.coords = fbi.coords; request.static_flow_hash = fbi.staticFlowHash; request.hashed_tag = fbi.hashedTag; request.generation = fbi.generation; request.service = mCurrentMessage.sender; mContext = "MENU_" + UUID.randomUUID().toString(); request.context = mContext; request.timestamp = System.currentTimeMillis() / 1000; showTransmitting(null); Map<String, Object> userInput = new HashMap<String, Object>(); userInput.put("request", request.toJSONMap()); userInput.put("func", "com.mobicage.api.services.pressMenuItem"); MessageFlowRun mfr = new MessageFlowRun(); mfr.staticFlowHash = fbi.staticFlowHash; try { JsMfr.executeMfr(mfr, userInput, mService, true); } catch (EmptyStaticFlowException ex) { completeTransmit(null); AlertDialog.Builder builder = new AlertDialog.Builder(ServiceMessageDetailActivity.this); builder.setMessage(ex.getMessage()); builder.setPositiveButton(R.string.rogerthat, null); AlertDialog dialog = builder.create(); dialog.show(); return; } } }); UIUtils.showHint(this, mService, HINT_BROADCAST, R.string.hint_broadcast, mCurrentMessage.broadcast_type, mFriendsPlugin.getName(mCurrentMessage.sender)); broadcastSpamControlText .setText(getString(R.string.broadcast_subscribed_to, mCurrentMessage.broadcast_type)); broadcastSpamControlSettingsText.setText(fbi.label); int ligthAlpha = 180; int darkAlpha = 70; int alpha = ligthAlpha; if (br != null && br.scheme == ColorScheme.dark) { broadcastSpamControlIcon.setTextColor(getResources().getColor(android.R.color.black)); broadcastSpamControlBorder.setBackgroundColor(darkSchemeTextColor); broadcastSpamControlDivider.setBackgroundColor(darkSchemeTextColor); activity.setBackgroundColor(darkSchemeTextColor); broadcastSpamControlText.setTextColor(lightSchemeTextColor); broadcastSpamControlSettingsText.setTextColor(lightSchemeTextColor); int alpacolor = Color.argb(darkAlpha, Color.red(lightSchemeTextColor), Color.green(lightSchemeTextColor), Color.blue(lightSchemeTextColor)); broadcastSpamControl.setBackgroundColor(alpacolor); alpha = darkAlpha; } else { broadcastSpamControlIcon.setTextColor(getResources().getColor(android.R.color.white)); broadcastSpamControlBorder.setBackgroundColor(lightSchemeTextColor); broadcastSpamControlDivider.setBackgroundColor(lightSchemeTextColor); activity.setBackgroundColor(lightSchemeTextColor); broadcastSpamControlText.setTextColor(darkSchemeTextColor); broadcastSpamControlSettingsText.setTextColor(darkSchemeTextColor); int alpacolor = Color.argb(darkAlpha, Color.red(darkSchemeTextColor), Color.green(darkSchemeTextColor), Color.blue(darkSchemeTextColor)); broadcastSpamControl.setBackgroundColor(alpacolor); } if (br != null && br.color != null) { int alphaColor = Color.argb(alpha, Color.red(br.color), Color.green(br.color), Color.blue(br.color)); broadcastSpamControl.setBackgroundColor(alphaColor); } mService.postOnUIHandler(new SafeRunnable() { @Override protected void safeRun() throws Exception { int maxHeight = broadcastSpamControl.getHeight(); broadcastSpamControlDivider.getLayoutParams().height = maxHeight; broadcastSpamControlDivider.requestLayout(); broadcastSpamControlSettingsContainer.getLayoutParams().height = maxHeight; broadcastSpamControlSettingsContainer.requestLayout(); broadcastSpamControlTextContainer.getLayoutParams().height = maxHeight; broadcastSpamControlTextContainer.requestLayout(); int broadcastSpamControlWidth = broadcastSpamControl.getWidth(); android.view.ViewGroup.LayoutParams lp = broadcastSpamControlSettingsContainer .getLayoutParams(); lp.width = broadcastSpamControlWidth / 4; broadcastSpamControlSettingsContainer.setLayoutParams(lp); } }); } if (!isUpdate) collapseDetails(DETAIL_SECTIONS); }
From source file:com.tesora.dve.tools.aitemplatebuilder.AiTemplateBuilder.java
private Template getTemplate(final String databaseName, final Collection<TableStats> tables, final Set<? extends TemplateRangeItem> ranges) throws PEException { log("Building a template for '" + databaseName + "'..."); final SortedSet<TableStats> databaseTables = new TreeSet<TableStats>(); final SortedSet<TemplateRangeItem> databaseRanges = new TreeSet<TemplateRangeItem>( new Comparator<TemplateRangeItem>() { @Override//from w w w .j a v a 2 s .c om public int compare(TemplateRangeItem a, TemplateRangeItem b) { return a.getTemplateItemName().compareTo(b.getTemplateItemName()); } }); for (final TableStats table : tables) { if (databaseName.equals(table.getSchemaName())) { final TemplateItem distributionModel = table.getTableDistributionModel(); databaseTables.add(table); if (distributionModel instanceof Range) { databaseRanges.add(findRangeForTable(ranges, table)); } } } final String commonNamePrefix = getCommonTableNamePrefix(databaseTables); final TemplateBuilder builder = new TemplateBuilder(databaseName); /* Append range declarations. */ for (final TemplateRangeItem range : databaseRanges) { final String rangeName = removeTableNamePrefix(range.getTemplateItemName(), commonNamePrefix); builder.withRequirement( builder.toCreateRangeStatement(rangeName, "#sg#", range.getUniqueColumnTypes())); } /* Append table items. */ for (final TableStats table : databaseTables) { final String tableName = replaceTableNamePrefix(table.getTableName(), commonNamePrefix); final TemplateItem distributionModel = table.getTableDistributionModel(); if (distributionModel instanceof Range) { final TemplateRangeItem tableRange = findRangeForTable(databaseRanges, table); final String rangeName = removeTableNamePrefix(tableRange.getTemplateItemName(), commonNamePrefix); final String[] rangeColumnNames = getColumnNames(tableRange.getRangeColumnsFor(table)) .toArray(new String[] {}); builder.withRangeTable(tableName, rangeName, rangeColumnNames); } else { builder.withTable(tableName, distributionModel.getTemplateItemName()); } } return builder.toTemplate(); }
From source file:com.redhat.rhn.frontend.xmlrpc.kickstart.profile.ProfileHandler.java
/** * Set custom options for a kickstart profile. * @param loggedInUser The current user//from ww w .ja v a2 s . co m * @param ksLabel the kickstart label * @param options the custom options to set * @return a int being the number of options set * @throws FaultException A FaultException is thrown if * the profile associated with ksLabel cannot be found * * @xmlrpc.doc Set custom options for a kickstart profile. * @xmlrpc.param #session_key() * @xmlrpc.param #param("string","ksLabel") * @xmlrpc.param #param("string[]","options") * @xmlrpc.returntype #return_int_success() */ public int setCustomOptions(User loggedInUser, String ksLabel, List<String> options) throws FaultException { KickstartData ksdata = XmlRpcKickstartHelper.getInstance().lookupKsData(ksLabel, loggedInUser.getOrg()); if (ksdata == null) { throw new FaultException(-3, "kickstartProfileNotFound", "No Kickstart Profile found with label: " + ksLabel); } Long ksid = ksdata.getId(); KickstartOptionsCommand cmd = new KickstartOptionsCommand(ksid, loggedInUser); SortedSet<KickstartCommand> customSet = new TreeSet<KickstartCommand>(); if (options != null) { for (int i = 0; i < options.size(); i++) { String option = options.get(i); KickstartCommand custom = new KickstartCommand(); custom.setCommandName(KickstartFactory.lookupKickstartCommandName("custom")); // the following is a workaround to ensure that the options are rendered // on the UI on separate lines. if (i < (options.size() - 1)) { option += "\r"; } custom.setArguments(option); custom.setKickstartData(cmd.getKickstartData()); custom.setCustomPosition(customSet.size()); custom.setCreated(new Date()); custom.setModified(new Date()); customSet.add(custom); } if (cmd.getKickstartData().getCustomOptions() == null) { cmd.getKickstartData().setCustomOptions(customSet); } else { cmd.getKickstartData().setCustomOptions(customSet); } cmd.store(); } return 1; }
From source file:com.gtwm.pb.servlets.ServletSchemaMethods.java
public synchronized static void removeModule(HttpServletRequest request, SessionDataInfo sessionData, DatabaseInfo databaseDefn) throws AgileBaseException { CompanyInfo company = databaseDefn.getAuthManager().getCompanyForLoggedInUser(request); String internalModuleName = request.getParameter("internalmodulename"); if (internalModuleName == null) { throw new MissingParametersException("internalmodulename is required to remove a module"); }/*ww w.j a v a 2 s . c o m*/ ModuleInfo module = company.getModuleByInternalName(internalModuleName); // Check that the module hasn't got any reports in it Set<TableInfo> tables = company.getTables(); SortedSet<BaseReportInfo> memberReports = new TreeSet<BaseReportInfo>(); for (TableInfo table : tables) { for (BaseReportInfo report : table.getReports()) { ModuleInfo reportModule = report.getModule(); if (reportModule != null) { if (reportModule.equals(module)) { memberReports.add(report); } } } } if (memberReports.size() > 0) { throw new CantDoThatException("The module " + module + " still contains reports " + memberReports); } try { HibernateUtil.startHibernateTransaction(); HibernateUtil.activateObject(company); company.removeModule(module); HibernateUtil.currentSession().delete(module); HibernateUtil.currentSession().getTransaction().commit(); } catch (HibernateException hex) { HibernateUtil.currentSession().getTransaction().rollback(); company.addModule(module); throw new CantDoThatException("module removal failed", hex); } finally { HibernateUtil.closeSession(); } sessionData.setModule(null); }
From source file:org.eclipse.skalli.services.extension.validators.HostReachableValidator.java
protected void validate(SortedSet<Issue> issues, UUID entityId, Object value, final Severity minSeverity, int item) { if (value == null) { return;/* w w w . ja v a2 s. co m*/ } URL url = null; String label = null; if (value instanceof URL) { url = (URL) value; label = url.toExternalForm(); } else if (value instanceof Link) { Link link = (Link) value; try { url = URLUtils.stringToURL(link.getUrl()); label = link.getLabel(); } catch (MalformedURLException e) { CollectionUtils.addSafe(issues, getIssueByReachableHost(minSeverity, entityId, item, link.getUrl())); } } else { try { url = URLUtils.stringToURL(value.toString()); label = url != null ? url.toExternalForm() : value.toString(); } catch (MalformedURLException e) { CollectionUtils.addSafe(issues, getIssueByReachableHost(minSeverity, entityId, item, value.toString())); } } if (url == null) { return; } HttpClient client = Destinations.getClient(url); if (client != null) { HttpResponse response = null; try { HttpParams params = client.getParams(); HttpClientParams.setRedirecting(params, false); // we want to find 301 MOVED PERMANTENTLY HttpGet method = new HttpGet(url.toExternalForm()); LOG.info("GET " + url); //$NON-NLS-1$ response = client.execute(method); int status = response.getStatusLine().getStatusCode(); LOG.info(status + " " + response.getStatusLine().getReasonPhrase()); //$NON-NLS-1$ CollectionUtils.addSafe(issues, getIssueByResponseCode(minSeverity, entityId, item, response.getStatusLine(), label)); } catch (UnknownHostException e) { issues.add(newIssue(Severity.ERROR, entityId, item, TXT_HOST_UNKNOWN, url.getHost())); } catch (ConnectException e) { issues.add(newIssue(Severity.ERROR, entityId, item, TXT_CONNECT_FAILED, url.getHost())); } catch (MalformedURLException e) { issues.add(newIssue(Severity.ERROR, entityId, item, TXT_MALFORMED_URL, url)); } catch (IOException e) { LOG.warn(MessageFormat.format("I/O Exception on validation: {0}", e.getMessage()), e); //$NON-NLS-1$ } catch (RuntimeException e) { LOG.error(MessageFormat.format("RuntimeException on validation: {0}", e.getMessage()), e); //$NON-NLS-1$ } finally { HttpUtils.consumeQuietly(response); } } else { CollectionUtils.addSafe(issues, getIssueByReachableHost(minSeverity, entityId, item, url.getHost())); } }
From source file:com.gargoylesoftware.htmlunit.html.HtmlPage.java
private void addElement(final Map<String, SortedSet<DomElement>> map, final DomElement element, final String attribute, final boolean recurse) { // first try real attributes String value = element.getAttribute(attribute); if (DomElement.ATTRIBUTE_NOT_DEFINED == value && !(element instanceof HtmlApplet)) { // second try are JavaScript attributes // ...but applets are a bit special so ignore them final ScriptableObject scriptObject = element.getScriptableObject(); // we have to make sure the scriptObject has a slot for the given attribute. // just using get() may use e.g. getWithPreemption(). if (scriptObject.has(attribute, scriptObject)) { final Object jsValue = scriptObject.get(attribute, scriptObject); if (jsValue != null && jsValue != Scriptable.NOT_FOUND && jsValue instanceof String) { value = (String) jsValue; }// ww w. j a v a 2 s . com } } if (DomElement.ATTRIBUTE_NOT_DEFINED != value) { SortedSet<DomElement> elements = map.get(value); if (elements == null) { elements = new TreeSet<>(documentPositionComparator); elements.add(element); map.put(value, elements); } else if (!elements.contains(element)) { elements.add(element); } } if (recurse) { for (final DomElement child : element.getChildElements()) { addElement(map, child, attribute, true); } } }
From source file:net.sourceforge.fenixedu.domain.Lesson.java
public SortedSet<Interval> getAllLessonIntervalsWithoutInstanceDates() { SortedSet<Interval> dates = new TreeSet<Interval>(new Comparator<Interval>() { @Override//from ww w. j a v a 2 s .com public int compare(Interval o1, Interval o2) { return o1.getStart().compareTo(o2.getStart()); } }); if (!wasFinished()) { YearMonthDay startDateToSearch = getLessonStartDay(); YearMonthDay endDateToSearch = getLessonEndDay(); final HourMinuteSecond b = getBeginHourMinuteSecond(); final HourMinuteSecond e = getEndHourMinuteSecond(); for (final YearMonthDay yearMonthDay : getAllValidLessonDatesWithoutInstancesDates(startDateToSearch, endDateToSearch)) { final DateTime start = new DateTime(yearMonthDay.getYear(), yearMonthDay.getMonthOfYear(), yearMonthDay.getDayOfMonth(), b.getHour(), b.getMinuteOfHour(), b.getSecondOfMinute(), 0); final DateTime end = new DateTime(yearMonthDay.getYear(), yearMonthDay.getMonthOfYear(), yearMonthDay.getDayOfMonth(), e.getHour(), e.getMinuteOfHour(), e.getSecondOfMinute(), 0); dates.add(new Interval(start, end)); } } return dates; }
From source file:io.fabric8.git.internal.GitDataStore.java
@Override public Collection<String> listFiles(final String version, final Iterable<String> profiles, final String path) { assertValid();// w w w . j ava 2s .c o m return gitOperation(new GitOperation<Collection<String>>() { public Collection<String> call(Git git, GitContext context) throws Exception { SortedSet<String> answer = new TreeSet<String>(); for (String profile : profiles) { checkoutVersion(git, GitProfiles.getBranch(version, profile)); File profileDirectory = getProfileDirectory(git, profile); File file = Strings.isNotBlank(path) ? new File(profileDirectory, path) : profileDirectory; if (file.exists()) { String[] values = file.list(); if (values != null) { for (String value : values) { answer.add(value); } } } } return answer; } }, !hasVersion(version)); }