conflict_resolution
stringlengths
27
16k
<<<<<<< import com.kickstarter.models.Activity; ======= import android.util.Pair; import com.kickstarter.libs.RefTag; >>>>>>> import com.kickstarter.models.Activity; import android.util.Pair; import com.kickstarter.libs.RefTag; <<<<<<< Observable<Project> showProject(); Observable<Void> showSignupLogin(); Observable<Void> showActivityFeed(); Observable<Activity> showActivityUpdate(); ======= Observable<Pair<Project, RefTag>> showProject(); >>>>>>> Observable<Pair<Project, RefTag>> showProject(); Observable<Void> showSignupLogin(); Observable<Void> showActivityFeed(); Observable<Activity> showActivityUpdate();
<<<<<<< import com.todoroo.astrid.data.User; import com.todoroo.astrid.files.FileMetadata; ======= >>>>>>> import com.todoroo.astrid.data.User; <<<<<<< private static final StringProperty TAGS = new StringProperty(null, "group_concat(" + TaskListFragment.TAGS_METADATA_JOIN + "." + TaskToTagMetadata.TAG_NAME.name + ", ' | ')").as("tags"); private static final StringProperty PICTURE = new StringProperty(User.TABLE.as(TaskListFragment.USER_IMAGE_JOIN), User.PICTURE.name); ======= private static final StringProperty TAGS = new StringProperty(null, "group_concat(" + TaskListFragment.TAGS_METADATA_JOIN + "." + TagService.TAG.name + ", ' | ')").as("tags"); @SuppressWarnings("nls") private static final LongProperty FILE_ID_PROPERTY = new LongProperty(Metadata.TABLE.as(TaskListFragment.FILE_METADATA_JOIN), Metadata.ID.name).as("fileId"); @SuppressWarnings("nls") private static final IntegerProperty HAS_NOTES_PROPERTY = new IntegerProperty(null, "length(" + Task.NOTES + ") > 0").as("hasNotes"); >>>>>>> private static final StringProperty TAGS = new StringProperty(null, "group_concat(" + TaskListFragment.TAGS_METADATA_JOIN + "." + TaskToTagMetadata.TAG_NAME.name + ", ' | ')").as("tags"); @SuppressWarnings("nls") private static final LongProperty FILE_ID_PROPERTY = new LongProperty(Metadata.TABLE.as(TaskListFragment.FILE_METADATA_JOIN), Metadata.ID.name).as("fileId"); @SuppressWarnings("nls") private static final IntegerProperty HAS_NOTES_PROPERTY = new IntegerProperty(null, "length(" + Task.NOTES + ") > 0").as("hasNotes"); private static final StringProperty PICTURE = new StringProperty(User.TABLE.as(TaskListFragment.USER_IMAGE_JOIN), User.PICTURE.name); <<<<<<< PICTURE, ======= HAS_NOTES_PROPERTY, // Whether or not the task has notes >>>>>>> PICTURE, HAS_NOTES_PROPERTY, // Whether or not the task has notes <<<<<<< viewHolder.imageUrl = RemoteModel.PictureHelper.getPictureUrlFromCursor(cursor, PICTURE, RemoteModel.PICTURE_THUMB); ======= viewHolder.hasFiles = cursor.get(FILE_ID_PROPERTY) > 0; viewHolder.hasNotes = cursor.get(HAS_NOTES_PROPERTY) > 0; >>>>>>> viewHolder.imageUrl = RemoteModel.PictureHelper.getPictureUrlFromCursor(cursor, PICTURE, RemoteModel.PICTURE_THUMB); viewHolder.hasFiles = cursor.get(FILE_ID_PROPERTY) > 0; viewHolder.hasNotes = cursor.get(HAS_NOTES_PROPERTY) > 0; <<<<<<< public String imageUrl; // From join query, not part of the task model ======= public boolean hasFiles; // From join query, not part of the task model public boolean hasNotes; >>>>>>> public String imageUrl; // From join query, not part of the task model public boolean hasFiles; // From join query, not part of the task model public boolean hasNotes; <<<<<<< private final Map<Long, TaskAction> taskActionLoader = Collections.synchronizedMap(new HashMap<Long, TaskAction>()); @SuppressWarnings("nls") public class ActionsLoaderThread extends Thread { public static final String FILE_COLUMN = "fileId"; private static final String METADATA_JOIN = "for_actions"; private final LongProperty fileIdProperty = new LongProperty(Metadata.TABLE.as(METADATA_JOIN), Metadata.ID.name).as(FILE_COLUMN); @Override public void run() { AndroidUtilities.sleepDeep(500L); String groupedQuery = query.get(); groupedQuery = PermaSql.replacePlaceholders(groupedQuery); Query q = Query.select(Task.ID, Task.TITLE, Task.NOTES, Task.COMPLETION_DATE, Task.USER_ID, fileIdProperty) .join(Join.left(Metadata.TABLE.as(METADATA_JOIN), Criterion.and(Field.field(METADATA_JOIN + "." + Metadata.KEY.name).eq(FileMetadata.METADATA_KEY), Task.ID.eq(Field.field(METADATA_JOIN + "." + Metadata.TASK.name))))).withQueryTemplate(groupedQuery); final TodorooCursor<Task> fetchCursor = taskService.query(q); try { Task task = new Task(); LinkActionExposer linkActionExposer = new LinkActionExposer(); for(fetchCursor.moveToFirst(); !fetchCursor.isAfterLast(); fetchCursor.moveToNext()) { task.clear(); task.readFromCursor(fetchCursor); if(task.isCompleted() || !task.isEditable()) continue; boolean hasAttachments = (fetchCursor.get(fileIdProperty) > 0); List<TaskAction> actions = linkActionExposer. getActionsForTask(ContextManager.getContext(), task, hasAttachments); if (actions.size() > 0) taskActionLoader.put(task.getId(), actions.get(0)); else taskActionLoader.remove(task.getId()); } } finally { fetchCursor.close(); } final Activity activity = fragment.getActivity(); if (activity != null) { activity.runOnUiThread(new Runnable() { @Override public void run() { if(taskActionLoader.size() > 0) { notifyDataSetChanged(); } } }); } } } ======= >>>>>>> <<<<<<< } else if(Task.USER_ID_UNASSIGNED.equals(task.getValue(Task.USER_ID))) pictureView.setDefaultImageResource(R.drawable.icn_anyone_transparent); ======= } else if(task.getValue(Task.USER_ID) == Task.USER_ID_UNASSIGNED) pictureView.setDefaultImageDrawable(ResourceDrawableCache.getImageDrawableFromId(resources, R.drawable.icn_anyone_transparent)); >>>>>>> } else if (Task.USER_ID_UNASSIGNED.equals(task.getValue(Task.USER_ID))) pictureView.setDefaultImageDrawable(ResourceDrawableCache.getImageDrawableFromId(resources, R.drawable.icn_anyone_transparent)); <<<<<<< pictureView.setDefaultImageResource(R.drawable.icn_default_person_image); if (!TextUtils.isEmpty(viewHolder.imageUrl)) { pictureView.setUrl(viewHolder.imageUrl); } else if (!TextUtils.isEmpty(task.getValue(Task.USER))) { try { JSONObject user = new JSONObject(task.getValue(Task.USER)); pictureView.setUrl(user.optString("picture")); //$NON-NLS-1$ } catch (JSONException e) { // } ======= pictureView.setDefaultImageDrawable(ResourceDrawableCache.getImageDrawableFromId(resources, R.drawable.icn_default_person_image)); try { JSONObject user = new JSONObject(task.getValue(Task.USER)); pictureView.setUrl(user.optString("picture")); //$NON-NLS-1$ } catch (JSONException e) { Log.w("astrid", "task-adapter-image", e); //$NON-NLS-1$ //$NON-NLS-2$ >>>>>>> pictureView.setDefaultImageDrawable(ResourceDrawableCache.getImageDrawableFromId(resources, R.drawable.icn_default_person_image)); if (!TextUtils.isEmpty(viewHolder.imageUrl)) { pictureView.setUrl(viewHolder.imageUrl); } else if (!TextUtils.isEmpty(task.getValue(Task.USER))) { try { JSONObject user = new JSONObject(task.getValue(Task.USER)); pictureView.setUrl(user.optString("picture")); //$NON-NLS-1$ } catch (JSONException e) { // }
<<<<<<< public void onPrepareOptionsMenu (Menu menu) { if(actFmPreferenceService.isLoggedIn() && !RemoteModel.NO_UUID.equals(uuid) && menu.findItem(MENU_COMMENTS_REFRESH_ID) == null) { MenuItem item = menu.add(Menu.NONE, MENU_COMMENTS_REFRESH_ID, Menu.NONE, R.string.ENA_refresh_comments); item.setIcon(R.drawable.icn_menu_refresh_dark); } super.onPrepareOptionsMenu(menu); } @Override ======= >>>>>>>
<<<<<<< if (requestCode == ACTIVITY_SETTINGS && resultCode == EditPreferences.RESULT_CODE_THEME_CHANGED) { getActivity().finish(); getActivity().startActivity(getActivity().getIntent()); ======= if (requestCode == ACTIVITY_SETTINGS) { if (resultCode == EditPreferences.RESULT_CODE_THEME_CHANGED) { getActivity().finish(); if (overrideFinishAnim) { AndroidUtilities.callOverridePendingTransition(getActivity(), R.anim.slide_right_in, R.anim.slide_right_out); } getActivity().startActivity(getActivity().getIntent()); } else if (resultCode == SyncProviderPreferences.RESULT_CODE_SYNCHRONIZE) { Preferences.setLong(SyncActionHelper.PREF_LAST_AUTO_SYNC, 0); // Forces autosync to occur after login } >>>>>>> if (requestCode == ACTIVITY_SETTINGS) { if (resultCode == EditPreferences.RESULT_CODE_THEME_CHANGED) { getActivity().finish(); getActivity().startActivity(getActivity().getIntent()); } else if (resultCode == SyncProviderPreferences.RESULT_CODE_SYNCHRONIZE) { Preferences.setLong(SyncActionHelper.PREF_LAST_AUTO_SYNC, 0); // Forces autosync to occur after login }
<<<<<<< preference = screen.findPreference(getString(R.string.p_forums)); preference.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference p) { showForums(); return true; } }); preference = screen.findPreference(getString(R.string.p_premium)); if (ActFmPreferenceService.isPremiumUser()) screen.removePreference(preference); else preference.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference p) { showPremium(); return true; } }); ======= >>>>>>> preference = screen.findPreference(getString(R.string.p_premium)); if (ActFmPreferenceService.isPremiumUser()) screen.removePreference(preference); else preference.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference p) { showPremium(); return true; } });
<<<<<<< View settingsContainer = getView().findViewById(R.id.settingsContainer); settingsContainer.setVisibility(View.VISIBLE); View settingsButton = getView().findViewById(R.id.settings); settingsButton.setOnClickListener(settingsListener); View membersEdit = getView().findViewById(R.id.members_edit); ======= View membersEdit = findViewById(R.id.members_edit); >>>>>>> View membersEdit = getView().findViewById(R.id.members_edit); <<<<<<< getView().findViewById(R.id.listLabel).setPadding(0, 0, 0, 0); ======= >>>>>>> <<<<<<< ImageView activity = (ImageView) getView().findViewById(R.id.activity); ======= findViewById(R.id.listLabel).setPadding(0, 0, 0, 0); ImageView activity = (ImageView) findViewById(R.id.activity); >>>>>>> getView().findViewById(R.id.listLabel).setPadding(0, 0, 0, 0); ImageView activity = (ImageView) getView().findViewById(R.id.activity); <<<<<<< ViewGroup parent = (ViewGroup) getActivity().getLayoutInflater().inflate(R.layout.task_list_body_tag_v2, root, false); ======= ViewGroup parent = (ViewGroup) getLayoutInflater().inflate(R.layout.task_list_body_tag, root, false); >>>>>>> ViewGroup parent = (ViewGroup) getActivity().getLayoutInflater().inflate(R.layout.task_list_body_tag, root, false); <<<<<<< View tabView = getView().findViewById(R.id.settings); HelpInfoPopover.showPopover(getActivity(), tabView, R.string.help_popover_list_settings); ======= View tabView = findViewById(R.id.members_edit); HelpInfoPopover.showPopover(this, tabView, R.string.help_popover_list_settings, null); >>>>>>> View tabView = getView().findViewById(R.id.members_edit); HelpInfoPopover.showPopover(getActivity(), tabView, R.string.help_popover_list_settings, null);
<<<<<<< scrollView = (ScrollView) getView().findViewById(R.id.edit_scroll); ======= setContentView(R.layout.task_edit_activity); scrollView = (ScrollView) findViewById(R.id.edit_scroll); >>>>>>> scrollView = (ScrollView) getView().findViewById(R.id.edit_scroll); <<<<<<< controls.add(peopleControlSet = new EditPeopleControlSet(getActivity(), R.layout.control_set_assigned, R.layout.control_set_assigned_display, R.string.actfm_EPA_assign_label, REQUEST_LOG_IN)); //basicControls.addView(peopleControlSet.getDisplayView()); controlSetMap.put(getString(R.string.TEA_control_who), peopleControlSet); ======= controls.add(peopleControlSet = new EditPeopleControlSet(TaskEditActivity.this, R.layout.control_set_assigned, R.layout.control_set_assigned_display, R.string.actfm_EPA_assign_label, REQUEST_LOG_IN)); controlSetMap.put(getString(R.string.TEA_ctrl_who_pref), peopleControlSet); >>>>>>> controls.add(peopleControlSet = new EditPeopleControlSet(getActivity(), R.layout.control_set_assigned, R.layout.control_set_assigned_display, R.string.actfm_EPA_assign_label, REQUEST_LOG_IN)); controlSetMap.put(getString(R.string.TEA_ctrl_who_pref), peopleControlSet); <<<<<<< TagsControlSet tagsControl = new TagsControlSet(getActivity(), R.layout.control_set_tags, R.layout.control_set_tags_display, R.string.TEA_tags_label); controls.add(tagsControl); //moreControls.addView(tagsControl.getDisplayView()); controlSetMap.put(getString(R.string.TEA_control_lists), tagsControl); ======= tagsControlSet = new TagsControlSet(TaskEditActivity.this, R.layout.control_set_tags, R.layout.control_set_tags_display, R.string.TEA_tags_label); controls.add(tagsControlSet); controlSetMap.put(getString(R.string.TEA_ctrl_lists_pref), tagsControlSet); >>>>>>> tagsControlSet = new TagsControlSet(getActivity(), R.layout.control_set_tags, R.layout.control_set_tags_display, R.string.TEA_tags_label); controls.add(tagsControlSet); controlSetMap.put(getString(R.string.TEA_ctrl_lists_pref), tagsControlSet); <<<<<<< itemOrder = getResources().getStringArray(R.array.TEA_control_sets); String moreSectionTrigger = getString(R.string.TEA_control_more_section); String whenViewDescriptor = getString(R.string.TEA_control_when); View whenView = getView().findViewById(R.id.when_container); String shareViewDescriptor = getString(R.string.TEA_control_share); ======= itemOrder = getResources().getStringArray(R.array.TEA_control_sets_prefs); String moreSectionTrigger = getString(R.string.TEA_ctrl_more_pref); String whenViewDescriptor = getString(R.string.TEA_ctrl_when_pref); View whenView = findViewById(R.id.when_container); String shareViewDescriptor = getString(R.string.TEA_ctrl_share_pref); >>>>>>> itemOrder = getResources().getStringArray(R.array.TEA_control_sets_prefs); String moreSectionTrigger = getString(R.string.TEA_ctrl_more_pref); String whenViewDescriptor = getString(R.string.TEA_ctrl_when_pref); View whenView = getView().findViewById(R.id.when_container); String shareViewDescriptor = getString(R.string.TEA_ctrl_share_pref); <<<<<<< Button saveButton2 = (Button) getView().findViewById(R.id.save2); Button saveButton3 = (Button) getView().findViewById(R.id.save3); Button saveButton4 = (Button) getView().findViewById(R.id.save4); if (saveButton2 != null) { saveButton2.setOnClickListener(mSaveListener); } if (saveButton3 != null) { saveButton3.setOnClickListener(mSaveListener); } if (saveButton4 != null) { saveButton4.setOnClickListener(mSaveListener); } Button discardButtonGeneral = (Button) getView().findViewById(R.id.discard); ======= Button discardButtonGeneral = (Button) findViewById(R.id.discard); >>>>>>> Button discardButtonGeneral = (Button) getView().findViewById(R.id.discard); <<<<<<< Button discardButton2 = (Button) getView().findViewById(R.id.discard2); Button discardButton3 = (Button) getView().findViewById(R.id.discard3); Button discardButton4 = (Button) getView().findViewById(R.id.discard4); if (discardButton2 != null) { discardButton2.setOnClickListener(mDiscardListener); } if (discardButton3 != null) { discardButton3.setOnClickListener(mDiscardListener); } if (discardButton4 != null) { discardButton4.setOnClickListener(mDiscardListener); } getView().findViewById(R.id.when_header).setOnClickListener(mExpandWhenListener); ======= findViewById(R.id.when_header).setOnClickListener(mExpandWhenListener); >>>>>>> getView().findViewById(R.id.when_header).setOnClickListener(mExpandWhenListener); <<<<<<< int theme = ThemeService.getTheme(); if (theme == R.style.Theme || theme == R.style.Theme_Transparent) { whenDialog = new Dialog(getActivity(), R.style.Theme_TEA_Dialog);//R.style.Theme_WhenDialog //whenDialogView.setBackgroundColor(getResources().getColor(android.R.color.black)); } else { whenDialog = new Dialog(getActivity(), R.style.Theme_TEA_Dialog); //R.style.Theme_White_WhenDialog //whenDialogView.setBackgroundColor(getResources().getColor(android.R.color.white)); } ======= int theme = ThemeService.getDialogTheme(); whenDialog = new Dialog(this, theme); >>>>>>> int theme = ThemeService.getDialogTheme(); whenDialog = new Dialog(getActivity(), theme); <<<<<<< DialogUtilities.dismissDialog(getActivity(), whenDialog); ======= showWhenShortcutHelp(); DialogUtilities.dismissDialog(TaskEditActivity.this, whenDialog); >>>>>>> showWhenShortcutHelp(); DialogUtilities.dismissDialog(getActivity(), whenDialog); <<<<<<< LinearLayout dest = (LinearLayout)getView().findViewById(R.id.addons_more); dest.addView(separator); view.apply(getActivity(), dest); ======= >>>>>>>
<<<<<<< ======= // dithering getWindow().setFormat(PixelFormat.RGBA_8888); getWindow().addFlags(WindowManager.LayoutParams.FLAG_DITHER); syncResultCallback = new ProgressBarSyncResultCallback(this, R.id.progressBar, new Runnable() { @Override public void run() { ContextManager.getContext().sendBroadcast(new Intent(AstridApiConstants.BROADCAST_EVENT_REFRESH)); } }); >>>>>>> // dithering getActivity().getWindow().setFormat(PixelFormat.RGBA_8888); getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DITHER); syncResultCallback = new ProgressBarSyncResultCallback(getActivity(), R.id.progressBar, new Runnable() { @Override public void run() { ContextManager.getContext().sendBroadcast(new Intent(AstridApiConstants.BROADCAST_EVENT_REFRESH)); } }); <<<<<<< AndroidUtilities.callOverridePendingTransition(getActivity(), R.anim.slide_left_in, R.anim.slide_left_out); ======= overridePendingTransition(R.anim.slide_left_in, R.anim.slide_left_out); >>>>>>> AndroidUtilities.callOverridePendingTransition(getActivity(), R.anim.slide_left_in, R.anim.slide_left_out); <<<<<<< ======= @Override public void finish() { super.finish(); if (overrideFinishAnim) { overridePendingTransition(R.anim.slide_right_in, R.anim.slide_right_out); } } >>>>>>> <<<<<<< syncService.synchronizeActiveTasks(manual, new ProgressBarSyncResultCallback(getActivity(), R.id.progressBar, new Runnable() { @Override public void run() { ContextManager.getContext().sendBroadcast(new Intent(AstridApiConstants.BROADCAST_EVENT_REFRESH)); } })); ======= syncService.synchronizeActiveTasks(manual, syncResultCallback); >>>>>>> syncService.synchronizeActiveTasks(manual, syncResultCallback); <<<<<<< Toast.makeText(getActivity(), R.string.SyP_progress_toast, Toast.LENGTH_LONG).show(); } ======= }; showSyncOptionMenu(actions, listener); >>>>>>> }; showSyncOptionMenu(actions, listener); <<<<<<< ArrayAdapter<TYPE> adapter = new ArrayAdapter<TYPE>(getActivity(), ======= if(items.length == 1) { listener.onClick(null, 0); return; } ArrayAdapter<TYPE> adapter = new ArrayAdapter<TYPE>(this, >>>>>>> if(items.length == 1) { listener.onClick(null, 0); return; } ArrayAdapter<TYPE> adapter = new ArrayAdapter<TYPE>(getActivity(),
<<<<<<< ======= import org.json.JSONObject; >>>>>>> import org.json.JSONObject; <<<<<<< import org.json.JSONObject; ======= >>>>>>> <<<<<<< JSONObject propertiesJson = GraphUtil.toJsonProperties(properties); ======= JSONObject propertiesJson = GraphUtil.toJson(properties); >>>>>>> JSONObject propertiesJson = GraphUtil.toJsonProperties(properties);
<<<<<<< ======= import com.todoroo.astrid.reminders.ReminderService; import com.todoroo.astrid.rmilk.MilkBackgroundService; import com.todoroo.astrid.rmilk.MilkUtilities; >>>>>>> import com.todoroo.astrid.reminders.ReminderService;
<<<<<<< import com.todoroo.astrid.utility.Constants; import com.twmacinta.util.MD5; ======= >>>>>>> import com.todoroo.astrid.utility.Constants;
<<<<<<< LinearLayout moreControls = (LinearLayout) findViewById(R.id.more_controls); ======= LinearLayout whenControls = (LinearLayout) whenDialogView.findViewById(R.id.when_controls); LinearLayout whenHeader = (LinearLayout) getView().findViewById(R.id.when_header); LinearLayout moreControls = (LinearLayout) getView().findViewById(R.id.more_controls); >>>>>>> LinearLayout moreControls = (LinearLayout) getView().findViewById(R.id.more_controls); <<<<<<< ======= DeadlineControlSet deadlineControl = new DeadlineControlSet( getActivity(), R.layout.control_set_deadline, R.layout.control_set_deadline_display, whenHeader, R.id.aux_date, R.id.when_shortcut_container, R.id.when_label, R.id.when_image); controls.add(deadlineControl); whenControls.addView(deadlineControl.getDisplayView()); >>>>>>> <<<<<<< //The deadline control set contains the repeat controls and the calendar controls. //NOTE: we add the gcalControl to the list AFTER the deadline control, because //otherwise the correct date may not be written to the calendar event. Order matters! DeadlineControlSet deadlineControl = new DeadlineControlSet( TaskEditActivity.this, R.layout.control_set_deadline, R.layout.control_set_deadline_display, repeatControls.getDisplayView(), gcalControl.getDisplayView()); controls.add(deadlineControl); controlSetMap.put(getString(R.string.TEA_ctrl_when_pref), deadlineControl); controls.add(gcalControl); ======= hideUntilControls = new HideUntilControlSet(getActivity(), R.layout.control_set_hide, R.layout.control_set_hide_display, R.string.hide_until_prompt); controls.add(hideUntilControls); whenControls.addView(hideUntilControls.getDisplayView()); >>>>>>> //The deadline control set contains the repeat controls and the calendar controls. //NOTE: we add the gcalControl to the list AFTER the deadline control, because //otherwise the correct date may not be written to the calendar event. Order matters! DeadlineControlSet deadlineControl = new DeadlineControlSet( TaskEditActivity.this, R.layout.control_set_deadline, R.layout.control_set_deadline_display, repeatControls.getDisplayView(), gcalControl.getDisplayView()); controls.add(deadlineControl); controlSetMap.put(getString(R.string.TEA_ctrl_when_pref), deadlineControl); controls.add(gcalControl); hideUntilControls = new HideUntilControlSet(getActivity(), R.layout.control_set_hide, R.layout.control_set_hide_display, R.string.hide_until_prompt); controls.add(hideUntilControls); <<<<<<< ======= String whenViewDescriptor = getString(R.string.TEA_ctrl_when_pref); View whenView = getView().findViewById(R.id.when_container); >>>>>>> <<<<<<< findViewById(R.id.more_header).setOnClickListener(mExpandMoreListener); ======= getView().findViewById(R.id.when_header).setOnClickListener(mExpandWhenListener); getView().findViewById(R.id.more_header).setOnClickListener(mExpandMoreListener); >>>>>>> getView().findViewById(R.id.more_header).setOnClickListener(mExpandMoreListener); <<<<<<< DialogUtilities.dismissDialog(TaskEditActivity.this, whenDialog); ======= showWhenShortcutHelp(); DialogUtilities.dismissDialog(getActivity(), whenDialog); >>>>>>> DialogUtilities.dismissDialog(getActivity(), whenDialog); <<<<<<< ======= private void showWhenShortcutHelp() { if (!Preferences.getBoolean(R.string.p_showed_when_shortcut, false)) { Preferences.setBoolean(R.string.p_showed_when_shortcut, true); Preferences.setBoolean(R.string.p_showed_when_row, true); HelpInfoPopover.showPopover(getActivity(), getView().findViewById(R.id.when_shortcut_container), R.string.help_popover_when_shortcut, null); } } >>>>>>> <<<<<<< if (!peopleControlSet.isAssignedToMe()) { Intent data = new Intent(); data.putExtra(TOKEN_TASK_WAS_ASSIGNED, true); data.putExtra(TOKEN_ASSIGNED_TO, peopleControlSet.getAssignedToString()); setResult(RESULT_OK, data); } ======= if (!peopleControlSet.isAssignedToMe()) { Intent data = new Intent(); data.putExtra(TOKEN_TASK_WAS_ASSIGNED, true); data.putExtra(TOKEN_ASSIGNED_TO, peopleControlSet.getAssignedToString()); getActivity().setResult(Activity.RESULT_OK, data); } >>>>>>> if (!peopleControlSet.isAssignedToMe()) { Intent data = new Intent(); data.putExtra(TOKEN_TASK_WAS_ASSIGNED, true); data.putExtra(TOKEN_ASSIGNED_TO, peopleControlSet.getAssignedToString()); setResult(RESULT_OK, data); getActivity().setResult(Activity.RESULT_OK, data); }
<<<<<<< ======= import com.todoroo.astrid.producteev.api.ApiUtilities; import com.todoroo.astrid.rmilk.data.MilkNote; >>>>>>> import com.todoroo.astrid.producteev.api.ApiUtilities;
<<<<<<< new StartupService().onStartupApplication(getActivity()); ======= new StartupService().onStartupApplication(this); ThemeService.applyTheme(this); ViewGroup parent = (ViewGroup) getLayoutInflater().inflate(R.layout.task_list_activity, null); parent.addView(getListBody(parent), 2); setContentView(parent); >>>>>>> new StartupService().onStartupApplication(getActivity()); <<<<<<< private void initiateAutomaticSync() { if (!actFmPreferenceService.isLoggedIn()) return; long lastFetchDate = actFmPreferenceService.getLastSyncDate(); long lastAutosyncAttempt = Preferences.getLong(LAST_AUTOSYNC_ATTEMPT, 0); long lastTry = Math.max(lastFetchDate, lastAutosyncAttempt); if(DateUtilities.now() < lastTry + 300000L) return; new Thread() { @Override public void run() { Preferences.setLong(LAST_AUTOSYNC_ATTEMPT, DateUtilities.now()); new ActFmSyncProvider().synchronize(getActivity(), false); } }.start(); } ======= >>>>>>> <<<<<<< Intent showWelcomeLogin = new Intent(getActivity(), WelcomeLogin.class); ======= Preferences.setBoolean(WelcomeLogin.KEY_SHOWED_WELCOME_LOGIN, true); Intent showWelcomeLogin = new Intent(this, WelcomeWalkthrough.class); >>>>>>> Preferences.setBoolean(WelcomeLogin.KEY_SHOWED_WELCOME_LOGIN, true); Intent showWelcomeLogin = new Intent(this, WelcomeWalkthrough.class); <<<<<<< else if(syncActions.size() == 1) { SyncAction syncAction = syncActions.iterator().next(); try { syncAction.intent.send(); Toast.makeText(getActivity(), R.string.SyP_progress_toast, Toast.LENGTH_LONG).show(); } catch (CanceledException e) { // } } else { // We have >1 sync actions, pop up a dialogue so the user can // select just one of them (only sync one at a time) final SyncAction[] actions = syncActions.toArray(new SyncAction[syncActions.size()]); DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface click, int which) { ======= else { performSyncServiceV2Sync(true); if(syncActions.size() > 0) { for(SyncAction syncAction : syncActions) { >>>>>>> else { performSyncServiceV2Sync(true); if(syncActions.size() > 0) { for(SyncAction syncAction : syncActions) { <<<<<<< actions[which].intent.send(); Toast.makeText(getActivity(), R.string.SyP_progress_toast, Toast.LENGTH_LONG).show(); ======= syncAction.intent.send(); >>>>>>> syncAction.intent.send();
<<<<<<< if (!task.containsNonNullValue(Task.UUID)) { updates = updateDao.query(Query.select(Update.PROPERTIES).where(Update.TASK_LOCAL.eq(task.getId()))); ======= if (!task.containsNonNullValue(Task.REMOTE_ID)) { updates = updateDao.query(Query.select(Update.PROPERTIES).where(Update.TASK_LOCAL.eq(task.getId())).orderBy(Order.desc(Update.CREATION_DATE))); >>>>>>> if (!task.containsNonNullValue(Task.UUID)) { updates = updateDao.query(Query.select(Update.PROPERTIES).where(Update.TASK_LOCAL.eq(task.getId())).orderBy(Order.desc(Update.CREATION_DATE))); <<<<<<< Update.TASK_UUID.eq(task.getValue(Task.UUID)), Update.TASK_LOCAL.eq(task.getId())))); ======= Update.TASK.eq(task.getValue(Task.REMOTE_ID)), Update.TASK_LOCAL.eq(task.getId()))).orderBy(Order.desc(Update.CREATION_DATE))); >>>>>>> Update.TASK_UUID.eq(task.getValue(Task.UUID)), Update.TASK_LOCAL.eq(task.getId()))).orderBy(Order.desc(Update.CREATION_DATE)));
<<<<<<< ======= import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.Assert; >>>>>>> <<<<<<< import java.io.Serializable; import java.lang.reflect.TypeVariable; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import static org.hamcrest.CoreMatchers.isA; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.mongodb.morphia.testutil.ExactClassMatcher.exactClass; ======= >>>>>>> import java.io.Serializable; import java.lang.reflect.TypeVariable; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import static org.hamcrest.CoreMatchers.isA; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.mongodb.morphia.testutil.ExactClassMatcher.exactClass;
<<<<<<< @Override public List<Trace> findTracesByDuration(String serviceId, Date startTime, int durationMin, int durationMax, int num){ Map<String, Object> map = new HashMap<String, Object>(); map.put("serviceId", serviceId); map.put("startTime", startTime); map.put("num", num); map.put("durationMin", durationMin); map.put("durationMax", durationMax); return (List<Trace>) sqlSession.selectList("findTracesByDuration", map); } @Override public List<Trace> findTracesEx(String serviceId, Date startTime, int num) { Map<String, Object> map = new HashMap<String, Object>(); map.put("startTime", startTime); map.put("num", num); map.put("serviceId", serviceId); return (List<Trace>) sqlSession.selectList("findTracesEx", map); } ======= @Override public void addTrace(Trace t) { sqlSession.insert("addTrace",t); } >>>>>>> @Override public List<Trace> findTracesByDuration(String serviceId, Date startTime, int durationMin, int durationMax, int num){ Map<String, Object> map = new HashMap<String, Object>(); map.put("serviceId", serviceId); map.put("startTime", startTime); map.put("num", num); map.put("durationMin", durationMin); map.put("durationMax", durationMax); return (List<Trace>) sqlSession.selectList("findTracesByDuration", map); } @Override public List<Trace> findTracesEx(String serviceId, Date startTime, int num) { Map<String, Object> map = new HashMap<String, Object>(); map.put("startTime", startTime); map.put("num", num); map.put("serviceId", serviceId); return (List<Trace>) sqlSession.selectList("findTracesEx", map); } public void addTrace(Trace t) { sqlSession.insert("addTrace",t); }
<<<<<<< import android.provider.MediaStore; ======= import android.provider.DocumentsContract; import android.provider.MediaStore; >>>>>>> import android.provider.DocumentsContract; import android.provider.MediaStore; <<<<<<< public static String getUriPath(Context context, Uri uri) throws URISyntaxException { if ("content".equalsIgnoreCase(uri.getScheme())) { String[] projection = { MediaStore.MediaColumns.DATA }; Cursor cursor = null; try { cursor = context.getContentResolver().query(uri, projection, null, null, null); int index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA); if (cursor.moveToFirst()) { return cursor.getString(index); } } catch (Exception e) { // pass android.util.Log.e("ReactNativeJS", e.getMessage(), e); } finally { if (cursor != null) { cursor.close(); } } } else if ("file".equalsIgnoreCase(uri.getScheme())) { return uri.getPath(); } return null; } ======= >>>>>>> <<<<<<< if (requestCode == DOCUMENT_PICKER_RESULT_CODE) { ReactContext reactContext = mReactInstanceManager.getCurrentReactContext(); if (reactContext != null) { if (resultCode == RESULT_OK) { Uri fileUri = data.getData(); try { String filePath = getUriPath(this, fileUri); android.util.Log.d("ReactNativeJS", "fileUri=" + filePath); WritableMap params = Arguments.createMap(); params.putString("path", filePath); reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit("onDocumentPickerFilePicked", params); } catch (URISyntaxException ex) { // failed to get a file path reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit("onDocumentPickerCanceled", null); } } else if (resultCode == RESULT_CANCELED) { // user canceled or request failed reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit("onDocumentPickerCanceled", null); } } } ======= if (requestCode == DOCUMENT_PICKER_RESULT_CODE) { ReactContext reactContext = mReactInstanceManager.getCurrentReactContext(); if (reactContext != null) { if (resultCode == RESULT_OK) { Uri fileUri = data.getData(); String filePath = getRealPathFromURI_API19(this, fileUri); android.util.Log.d("ReactNativeJS", "fileUri=" + filePath); WritableMap params = Arguments.createMap(); params.putString("path", filePath); reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit("onDocumentPickerFilePicked", params); } else if (resultCode == RESULT_CANCELED) { // user canceled or request failed reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit("onDocumentPickerCanceled", null); } } } >>>>>>> if (requestCode == DOCUMENT_PICKER_RESULT_CODE) { ReactContext reactContext = mReactInstanceManager.getCurrentReactContext(); if (reactContext != null) { if (resultCode == RESULT_OK) { Uri fileUri = data.getData(); String filePath = getRealPathFromURI_API19(this, fileUri); WritableMap params = Arguments.createMap(); params.putString("path", filePath); reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit("onDocumentPickerFilePicked", params); } else if (resultCode == RESULT_CANCELED) { // user canceled or request failed reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit("onDocumentPickerCanceled", null); } } }
<<<<<<< public void initIndex(List<Blog> blogList) { this.deleteAllIndex(); //清除所有索引 ======= public void initIndex(String collection, List<Blog> blogList) { this.deleteAllIndex(collection); //清除所有索引 >>>>>>> public void initIndex(String collection, List<Blog> blogList) { this.deleteAllIndex(collection); //清除所有索引 <<<<<<< SolrIndex solrIndex = solrTemplate.getById(blog.getUid(), SolrIndex.class); ======= >>>>>>> <<<<<<< if (solrIndex == null) { addIndex(blog); ======= if (solrIndex.isPresent()) { addIndex(collection, blog); >>>>>>> if (solrIndex.isPresent()) { addIndex(collection, blog); <<<<<<< if (blog.getPhotoList() != null) { String str = ""; for (String s : blog.getPhotoList()) { str = str + s + ","; } solrIndex.setPhotoList(str); ======= if (blog.getPhotoList() != null) { String str = ""; for (String s : blog.getPhotoList()) { str = str + s + ","; } solrIndex.get().setPhotoList(str); >>>>>>> if (blog.getPhotoList() != null) { String str = ""; for (String s : blog.getPhotoList()) { str = str + s + ","; } solrIndex.get().setPhotoList(str); <<<<<<< public void deleteAllIndex() { SimpleQuery query = new SimpleQuery("*:*"); solrTemplate.delete(query); solrTemplate.commit(); ======= public void deleteAllIndex(String collection) { SimpleQuery query = new SimpleQuery("*:*"); solrTemplate.delete(collection,query); solrTemplate.commit(collection); >>>>>>> public void deleteAllIndex(String collection) { SimpleQuery query = new SimpleQuery("*:*"); solrTemplate.delete(collection,query); solrTemplate.commit(collection); <<<<<<< query.setOffset((currentPage - 1) * pageSize);//从第几条记录查询 ======= query.setOffset((long)(currentPage - 1) * pageSize);//从第几条记录查询 >>>>>>> query.setOffset((long)(currentPage - 1) * pageSize);//从第几条记录查询 <<<<<<< HighlightPage<SolrIndex> page = solrTemplate.queryForHighlightPage(query, SolrIndex.class); ======= HighlightPage<SolrIndex> page = solrTemplate.queryForHighlightPage(collection, query, SolrIndex.class); >>>>>>> HighlightPage<SolrIndex> page = solrTemplate.queryForHighlightPage(collection, query, SolrIndex.class);
<<<<<<< remap.put(SysConf.NAME, file.getPicName()); remap.put(SysConf.UID, file.getUid()); ======= remap.put("name", file.getPicName()); remap.put("uid", file.getUid()); remap.put("file_old_name", file.getFileOldName()); >>>>>>> remap.put(SysConf.NAME, file.getPicName()); remap.put(SysConf.UID, file.getUid()); remap.put("file_old_name", file.getFileOldName());
<<<<<<< import org.apache.log4j.Logger; import javax.crypto.spec.SecretKeySpec; import javax.xml.bind.DatatypeConverter; import java.security.Key; import java.util.Date; import java.util.HashMap; import java.util.Map; ======= import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.crypto.spec.SecretKeySpec; import javax.xml.bind.DatatypeConverter; import java.security.Key; import java.util.Date; import java.util.HashMap; import java.util.Map; >>>>>>> import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.crypto.spec.SecretKeySpec; import javax.xml.bind.DatatypeConverter; import java.security.Key; import java.util.Date; import java.util.HashMap; import java.util.Map; <<<<<<< private final static String base64Secret = "MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY="; private final static int expiresSecond = 1000 * 60 * 2 * 60;//过期时间 private static Logger log = Logger.getLogger(JwtUtil.class); /** * 解析jwt toke 获取数据 * * @param jsonWebToken * @return */ public static Claims parseJWT(String jsonWebToken) { ======= private final static String base64Secret = "MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY="; private final static int expiresSecond = 1000 * 60 * 2 * 60;//过期时间 private static Logger log = LoggerFactory.getLogger(JwtUtil.class); /** * 解析jwt toke 获取数据 * * @param jsonWebToken * @return */ public static Claims parseJWT(String jsonWebToken) { >>>>>>> private final static String base64Secret = "MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY="; private final static int expiresSecond = 1000 * 60 * 2 * 60;//过期时间 private static Logger log = LoggerFactory.getLogger(JwtUtil.class); /** * 解析jwt toke 获取数据 * * @param jsonWebToken * @return */ public static Claims parseJWT(String jsonWebToken) { <<<<<<< try { Claims claims = Jwts.parser() .setSigningKey(DatatypeConverter.parseBase64Binary(base64Secret)) .parseClaimsJws(jsonWebToken).getBody(); return claims; } catch (Exception ex) { return null; } } /** * 生成jwt token user的 * * @param username * @param password * @param userOpenId * @return */ public static String createJWT(String userOpenId, Long userId, boolean isUser, Long shopId) { log.info("userOpenId" + userOpenId + "userId" + userId + "isUser" + isUser + "shopId" + shopId); SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); //生成签名密钥 byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Secret); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); //添加构成JWT的参数 JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT") .claim("user_id", userId) .claim("shop_id", shopId) .claim("is_user", isUser) .claim("user_open_id", userOpenId) .signWith(signatureAlgorithm, signingKey); //添加Token过期时间 if (expiresSecond >= 0) { long expMillis = nowMillis + expiresSecond; Date exp = new Date(expMillis); builder.setExpiration(exp).setNotBefore(now); } //生成JWT String compact = builder.compact(); log.info("生成jwt===========" + compact); return compact; } public static String createSysUserJWT(Long shopId, Long sysUserId, String loginUserName, String loginPassWord, boolean isShop) { SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); //生成签名密钥 byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Secret); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); //添加构成JWT的参数 JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT") .claim("shop_id", shopId) .claim("sys_user_id", sysUserId) .claim("is_shop", isShop) .claim("login_username", loginUserName) .claim("login_password", loginPassWord) ======= ===="+ compact); return compact; } public static String createSysUserJWT(Long shopId,Long sysUserId,String loginUserName,String loginPassWord,boolean isShop) { SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); //生成签名密钥 byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Secret); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); //添加构成JWT的参数 JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT") .claim("shop_id", shopId) .claim("sys_user_id", sysUserId) .claim("is_shop",isShop) .claim("login_username", loginUserName) .claim("login_password", loginPassWord) ======= try { Claims claims = Jwts.parser() .setSigningKey(DatatypeConverter.parseBase64Binary(base64Secret)) .parseClaimsJws(jsonWebToken).getBody(); return claims; } catch (Exception ex) { return null; } } /** * 生成jwt token user * * @param userOpenId * @param userId * @param isUser * @param shopId * @return */ public static String createJWT(String userOpenId, Long userId, boolean isUser, Long shopId) { log.info("userOpenId" + userOpenId + "userId" + userId + "isUser" + isUser + "shopId" + shopId); SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); //生成签名密钥 byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Secret); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); //添加构成JWT的参数 JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT") .claim("user_id", userId) .claim("shop_id", shopId) .claim("is_user", isUser) .claim("user_open_id", userOpenId) .signWith(signatureAlgorithm, signingKey); //添加Token过期时间 if (expiresSecond >= 0) { long expMillis = nowMillis + expiresSecond; Date exp = new Date(expMillis); builder.setExpiration(exp).setNotBefore(now); } //生成JWT String compact = builder.compact(); log.info("生成jwt===========" + compact); return compact; } public static String createSysUserJWT(Long shopId, Long sysUserId, String loginUserName, String loginPassWord, boolean isShop) { SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); //生成签名密钥 byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Secret); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); //添加构成JWT的参数 JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT") .claim("shop_id", shopId) .claim("sys_user_id", sysUserId) .claim("is_shop", isShop) .claim("login_username", loginUserName) .claim("login_password", loginPassWord) >>>>>>> try { Claims claims = Jwts.parser() .setSigningKey(DatatypeConverter.parseBase64Binary(base64Secret)) .parseClaimsJws(jsonWebToken).getBody(); return claims; } catch (Exception ex) { return null; } } /** * 生成jwt token user * * @param userOpenId * @param userId * @param isUser * @param shopId * @return */ public static String createJWT(String userOpenId, Long userId, boolean isUser, Long shopId) { log.info("userOpenId" + userOpenId + "userId" + userId + "isUser" + isUser + "shopId" + shopId); SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); //生成签名密钥 byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Secret); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); //添加构成JWT的参数 JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT") .claim("user_id", userId) .claim("shop_id", shopId) .claim("is_user", isUser) .claim("user_open_id", userOpenId) .signWith(signatureAlgorithm, signingKey); //添加Token过期时间 if (expiresSecond >= 0) { long expMillis = nowMillis + expiresSecond; Date exp = new Date(expMillis); builder.setExpiration(exp).setNotBefore(now); } //生成JWT String compact = builder.compact(); log.info("生成jwt===========" + compact); return compact; } public static String createSysUserJWT(Long shopId, Long sysUserId, String loginUserName, String loginPassWord, boolean isShop) { SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); //生成签名密钥 byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Secret); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); //添加构成JWT的参数 JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT") .claim("shop_id", shopId) .claim("sys_user_id", sysUserId) .claim("is_shop", isShop) .claim("login_username", loginUserName) .claim("login_password", loginPassWord)
<<<<<<< import gnu.trove.list.TFloatList; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.util.Date; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.KryoException; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; public class SimEngine { private static String dir = System.getProperty("user.dir") + System.getProperty("file.separator"); private static final Logger logger = LoggerFactory .getLogger(SimEngine.class); private ExecutorService service = Executors.newSingleThreadExecutor(); private SimTable table; private final Kryo kryo = new Kryo(); private int counter = 0; private long timestamp = -1; private boolean debug; private long cloneThrottle; private int bycount; private String name; public SimEngine(String engineName, Map<String, Object> config) { name = engineName; try { cloneThrottle = (Integer) config.get("cloneThrottle"); debug = (Boolean) config.get("debug"); bycount = (Integer) config.get("bycount"); table = new SimTable(name, config); } catch (NullPointerException e) { logger.warn("YAML not found,loading default config"); cloneThrottle = 30000; debug = true; bycount = 100; } } /** * clone 函数之前必须验证 * * @return cloneInterval 秒内clone过,则返回false,否则true **/ private boolean validateTime() { long current = new Date().getTime(); if (current - timestamp < cloneThrottle) { logger.info("Already cloned in " + cloneThrottle / 1000 + "s, abort;"); return false; } else { timestamp = current; return true; } } public void load(final String key) throws FileNotFoundException { Input input = null; String path = dir + "/data/" + key; try { logger.info("Loading...."); input = new Input(new FileInputStream(path + ".dmp")); table.read(kryo, input); logger.info("Load finish"); } catch (KryoException e) { input = new Input(new FileInputStream(path + ".bak")); table.read(kryo, input); } finally { if (input != null) { input.close(); } } } public void clear() { service.execute(new Runnable() { public void run() { logger.info("Clean begin..."); if (validateTime()) { SimTable data = table.clone(); table.reload(data); data = null; System.gc(); } logger.info("Clean finish!"); } }); } public void save(final String key) { service.execute(new Runnable() { public void run() { Runnable runner = new Runnable() { @Override public void run() { logger.info("Saving...."); if (!validateTime()) { return; } SimTable data = table.clone(); Output output = null; String path = dir + "/data/" + key; try { Process p = Runtime.getRuntime().exec( "mv " + path + ".dmp " + path + ".bak"); p.waitFor(); output = new Output(new FileOutputStream(path + ".dmp")); data.write(kryo, output); } catch (Throwable e) { throw new SimBaseException(e); } finally { if (output != null) { output.close(); } } data = null; System.gc(); logger.info("Save finish"); } }; new Thread(runner).start(); } }); } public void revise(final String[] schema) { service.execute(new Runnable() { public void run() { try { table.revise(schema); } catch (Throwable e) { logger.error("SimEngine Error:", e); } } }); } public void add(final int docid, final float[] distr) { service.execute(new Runnable() { public void run() { if (debug) { counter++; if (counter % bycount == 0) { logger.debug("add:" + counter); } int maxIndex = 0; float maxValue = 0.0f; int index = 0; for (float value: distr) { if (value > maxValue) { maxValue = value; maxIndex = index; } index++; } logger.debug(String.format("add: %s %d %d", name, docid, maxIndex)); } try { table.add(docid, distr); } catch (Throwable e) { logger.error("SimEngine Error:", e); } } }); } public void append(final int docid, final Object[] pairs) { service.execute(new Runnable() { public void run() { if (debug) { counter++; if (counter % bycount == 0) { logger.debug("add:" + counter); } } try { table.append(docid, pairs); } catch (Throwable e) { logger.error("SimEngine Error:", e); } } }); } public void put(final int docid, final float[] distr) { service.execute(new Runnable() { public void run() { try { table.put(docid, distr); } catch (Throwable e) { logger.error("SimEngine Error:", e); } } }); } public void update(final int docid, final Object[] pairs) { service.execute(new Runnable() { public void run() { try { table.update(docid, pairs); } catch (Throwable e) { logger.error("SimEngine Error:", e); } } }); } public void delete(final int docid) { service.execute(new Runnable() { public void run() { try { logger.info(String.format("delete: %s %s", name, docid)); table.delete(docid); logger.info("Delete finish"); } catch (Throwable e) { logger.error("SimEngine Error:", e); } } }); } public String[] schema() { return table.schema(); } public TFloatList get(int docid) { return table.get(docid); } public String[] retrieve(int docid) { return table.retrieve(docid); } public int[] recommend(int docid) { return table.recommend(docid); } ======= import com.guokr.simbase.events.BasisListener; import com.guokr.simbase.events.RecommendationListener; import com.guokr.simbase.events.VectorSetListener; public interface SimEngine { public void load(SimCallback callback); public void save(SimCallback callback); public void del(SimCallback callback, String key); public void bload(SimCallback callback, String key); public void bsave(SimCallback callback, String key); public void blist(SimCallback callback); public void bmk(SimCallback callback, String bkey, String[] base); public void brev(SimCallback callback, String bkey, String[] base); public void bget(SimCallback callback, String bkey); public void vlist(SimCallback callback, String bkey); public void vmk(SimCallback callback, String bkey, String vkey); public void vids(SimCallback callback, String vkey); public void vget(SimCallback callback, String vkey, int vecid); public void vadd(SimCallback callback, String vkey, int vecid, float[] vector); public void vset(SimCallback callback, String vkey, int vecid, float[] vector); public void vacc(SimCallback callback, String vkey, int vecid, float[] vector); public void vrem(SimCallback callback, String vkey, int vecid); public void iget(SimCallback callback, String vkey, int vecid); public void iadd(SimCallback callback, String vkey, int vecid, int[] pairs); public void iset(SimCallback callback, String vkey, int vecid, int[] pairs); public void iacc(SimCallback callback, String vkey, int vecid, int[] pairs); public void rlist(SimCallback callback, String vkey); public void rmk(SimCallback callback, String vkeySource, String vkeyTarget, String funcscore); public void rget(SimCallback callback, String vkeySource, int vecid, String vkeyTarget); public void rrec(SimCallback callback, String vkeySource, int vecid, String vkeyTarget); public void listen(String bkey, BasisListener listener); public void listen(String vkey, VectorSetListener listener); public void listen(String srcVkey, String tgtVkey, RecommendationListener listener); >>>>>>> import com.guokr.simbase.events.BasisListener; import com.guokr.simbase.events.RecommendationListener; import com.guokr.simbase.events.VectorSetListener; public interface SimEngine { public void load(SimCallback callback); public void save(SimCallback callback); public void del(SimCallback callback, String key); public void bload(SimCallback callback, String key); public void bsave(SimCallback callback, String key); public void blist(SimCallback callback); public void bmk(SimCallback callback, String bkey, String[] base); public void brev(SimCallback callback, String bkey, String[] base); public void bget(SimCallback callback, String bkey); public void vlist(SimCallback callback, String bkey); public void vmk(SimCallback callback, String bkey, String vkey); public void vids(SimCallback callback, String vkey); public void vget(SimCallback callback, String vkey, int vecid); public void vadd(SimCallback callback, String vkey, int vecid, float[] vector); public void vset(SimCallback callback, String vkey, int vecid, float[] vector); public void vacc(SimCallback callback, String vkey, int vecid, float[] vector); public void vrem(SimCallback callback, String vkey, int vecid); public void iget(SimCallback callback, String vkey, int vecid); public void iset(SimCallback callback, String vkey, int vecid, int[] pairs); public void iadd(SimCallback callback, String vkey, int vecid, int[] pairs); public void iacc(SimCallback callback, String vkey, int vecid, int[] pairs); public void rlist(SimCallback callback, String vkey); public void rmk(SimCallback callback, String vkeySource, String vkeyTarget, String funcscore); public void rget(SimCallback callback, String vkeySource, int vecid, String vkeyTarget); public void listen(String bkey, BasisListener listener); public void rrec(SimCallback callback, String vkeySource, int vecid, String vkeyTarget); public void listen(String vkey, VectorSetListener listener); public void listen(String srcVkey, String tgtVkey, RecommendationListener listener);
<<<<<<< public static final StringLumifyProperty ONTOLOGY_TITLE = new StringLumifyProperty("http://lumify.io#ontologyTitle"); ======= public static final BooleanLumifyProperty SEARCHABLE = new BooleanLumifyProperty("http://lumify.io#searchable"); public static final TextLumifyProperty ONTOLOGY_TITLE = new TextLumifyProperty("http://lumify.io#ontologyTitle", TextIndexHint.EXACT_MATCH); >>>>>>> public static final StringLumifyProperty ONTOLOGY_TITLE = new StringLumifyProperty("http://lumify.io#ontologyTitle"); public static final BooleanLumifyProperty SEARCHABLE = new BooleanLumifyProperty("http://lumify.io#searchable");
<<<<<<< jsonObject.getString("_conceptType"), "", "", user); Vertex graphVertex = graph.getVertex(graphVertexId, authorizations); ======= jsonObject.getString("_conceptType"), "", "", user, visibility); Vertex graphVertex = graph.getVertex(graphVertexId, user.getAuthorizations()); >>>>>>> jsonObject.getString("_conceptType"), "", "", user, visibility); Vertex graphVertex = graph.getVertex(graphVertexId, authorizations);
<<<<<<< public abstract String getTitleFormula(); ======= public Collection<OntologyProperty> getProperties() { return properties; } >>>>>>> public abstract String getTitleFormula(); public Collection<OntologyProperty> getProperties() { return properties; }
<<<<<<< import static com.google.common.truth.Truth.assertThat; ======= import java.util.LinkedHashSet; import java.util.Set; >>>>>>> import static com.google.common.truth.Truth.assertThat; import java.util.LinkedHashSet; import java.util.Set; <<<<<<< ======= import com.github.rinde.rinsim.core.SimulatorAPI; import com.github.rinde.rinsim.core.SimulatorUser; import com.github.rinde.rinsim.core.TickListener; import com.github.rinde.rinsim.core.TimeLapse; import com.github.rinde.rinsim.core.model.AbstractModel; >>>>>>> import com.github.rinde.rinsim.core.SimulatorAPI; import com.github.rinde.rinsim.core.model.DependencyProvider; import com.github.rinde.rinsim.core.model.Model.AbstractModel; import com.github.rinde.rinsim.core.model.ModelBuilder.AbstractModelBuilder; <<<<<<< .addModel(CommModel.builder()) .addModel(RoadModelBuilders.plane()) .addModel( View.builder() .with(CommRenderer.builder() .withReliabilityColors(new RGB(0, 0, 255), new RGB(255, 255, 0)) .withReliabilityPercentage() .withMessageCount() ) .with(PlaneRoadModelRenderer.builder()) .withAutoPlay() .withAutoClose() .withSpeedUp(10) .withSimulatorEndTime(1000 * 60 * 5) ) ======= .addModel(CommModel.builder().build()) .addModel(PlaneRoadModel.builder().build()) .addModel(new TestModel()) >>>>>>> .addModel(CommModel.builder()) .addModel(RoadModelBuilders.plane()) .addModel( View.builder() .with(CommRenderer.builder() .withReliabilityColors(new RGB(0, 0, 255), new RGB(255, 255, 0)) .withReliabilityPercentage() .withMessageCount() ) .with(PlaneRoadModelRenderer.builder()) .withAutoPlay() // .withAutoClose() .withSpeedUp(10) // .withSimulatorEndTime(1000 * 60 * 5) ) .addModel(TestModel.Builder.create())
<<<<<<< TickListener { ======= TickListener, RandomUser { >>>>>>> TickListener { <<<<<<< private final RandomGenerator randomGenerator; ======= private final BiMap<CommUser, CommDevice> unregisteredUsersDevices; private Optional<RandomGenerator> randomGenerator; >>>>>>> private final RandomGenerator randomGenerator; private final BiMap<CommUser, CommDevice> unregisteredUsersDevices;
<<<<<<< public Collection<String> readTimeBucket(String path)throws InterruptedException { String[] servers = cluster.getServers(); int serverCount = servers.length; ======= public Collection<ContentKey> readTimeBucket(String path)throws InterruptedException { List<String> servers = cluster.getServers(); // TODO bc 11/17/14: Can we make this read from a subset of the cluster and get all results? int quorum = servers.size(); >>>>>>> public Collection<String> readTimeBucket(String path)throws InterruptedException { List<String> servers = cluster.getServers(); // TODO bc 11/17/14: Can we make this read from a subset of the cluster and get all results? int serverCount = servers.size();
<<<<<<< import static com.altamiracorp.lumify.core.model.properties.EntityLumifyProperties.GEO_LOCATION; ======= >>>>>>> <<<<<<< import java.util.Date; import java.util.Iterator; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONException; import org.json.JSONObject; ======= import org.json.JSONObject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; >>>>>>> import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONObject; <<<<<<< public static JSONObject propertiesToJson(Iterable<Property> properties) throws JSONException { JSONObject resultsJson = new JSONObject(); Iterator<Property> propertyIterator = properties.iterator(); while (propertyIterator.hasNext()) { Property property = propertyIterator.next(); if (GEO_LOCATION.getKey().equals(property.getName())) { JSONObject geo = new JSONObject(); GeoPoint geoPoint = (GeoPoint) property.getValue(); geo.put("latitude", geoPoint.getLatitude()); geo.put("longitude", geoPoint.getLongitude()); resultsJson.put(property.getName(), geo); } else { Object value = property.getValue(); if (value instanceof StreamingPropertyValue) { continue; } if (value instanceof Date) { value = ((Date) value).getTime(); } if (value instanceof Text) { value = ((Text) value).getText(); } resultsJson.put(property.getName(), value); } } return resultsJson; } ======= >>>>>>>
<<<<<<< import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; ======= import lombok.extern.slf4j.Slf4j; import org.junit.BeforeClass; import org.junit.Test; >>>>>>> import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import lombok.extern.slf4j.Slf4j; <<<<<<< class HubUtilsTest { ======= @Slf4j public class HubUtilsTest { >>>>>>> @Slf4j class HubUtilsTest {
<<<<<<< public ClientApiWorkspaceDiff handle(String workspaceId, User user) { Workspace workspace = workspaceRepository.findById(workspaceId, true, user); ======= public ClientApiWorkspaceDiff handle(String workspaceId, User user, Locale locale, String timeZone) { Workspace workspace = workspaceRepository.findById(workspaceId, user); >>>>>>> public ClientApiWorkspaceDiff handle(String workspaceId, User user, Locale locale, String timeZone) { Workspace workspace = workspaceRepository.findById(workspaceId, true, user);
<<<<<<< protected String getValidationFormula(OWLOntology o, OWLEntity owlEntity) { return getAnnotationValueByUri(o, owlEntity, LumifyProperties.VALIDATION_FORMULA.getPropertyName()); } protected String getDisplayFormula(OWLOntology o, OWLEntity owlEntity) { return getAnnotationValueByUri(o, owlEntity, LumifyProperties.DISPLAY_FORMULA.getPropertyName()); } protected ImmutableList<String> getDependentPropertyIri(OWLOntology o, OWLEntity owlEntity) { return getAnnotationValuesByUriOrNull(o, owlEntity, LumifyProperties.DEPENDENT_PROPERTY_IRI.getPropertyName()); } protected String getTitleFormula(OWLOntology o, OWLEntity owlEntity) { return getAnnotationValueByUri(o, owlEntity, LumifyProperties.TITLE_FORMULA.getPropertyName()); } protected String getSubtitleFormula(OWLOntology o, OWLEntity owlEntity) { return getAnnotationValueByUri(o, owlEntity, LumifyProperties.SUBTITLE_FORMULA.getPropertyName()); } protected String getTimeFormula(OWLOntology o, OWLEntity owlEntity) { return getAnnotationValueByUri(o, owlEntity, LumifyProperties.TIME_FORMULA.getPropertyName()); } ======= >>>>>>> protected String getValidationFormula(OWLOntology o, OWLEntity owlEntity) { return getAnnotationValueByUri(o, owlEntity, LumifyProperties.VALIDATION_FORMULA.getPropertyName()); } protected String getDisplayFormula(OWLOntology o, OWLEntity owlEntity) { return getAnnotationValueByUri(o, owlEntity, LumifyProperties.DISPLAY_FORMULA.getPropertyName()); } protected ImmutableList<String> getDependentPropertyIri(OWLOntology o, OWLEntity owlEntity) { return getAnnotationValuesByUriOrNull(o, owlEntity, LumifyProperties.DEPENDENT_PROPERTY_IRI.getPropertyName()); }
<<<<<<< import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; ======= import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; >>>>>>> import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; <<<<<<< @Execution(ExecutionMode.SAME_THREAD) ======= @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness= Strictness.LENIENT) >>>>>>> @Execution(ExecutionMode.SAME_THREAD) @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness= Strictness.LENIENT)
<<<<<<< void testChangeStorageLoss() { HubProperties.setProperty("hub.protect.channels", "true"); ======= public void testChangeStorageLoss() throws Exception { PropertyLoader.getInstance().setProperty("hub.protect.channels", "true"); >>>>>>> void testChangeStorageLoss() { PropertyLoader.getInstance().setProperty("hub.protect.channels", "true"); <<<<<<< void testRemoveTagsLoss() { HubProperties.setProperty("hub.protect.channels", "true"); ======= public void testRemoveTagsLoss() throws Exception { PropertyLoader.getInstance().setProperty("hub.protect.channels", "true"); >>>>>>> void testRemoveTagsLoss() { PropertyLoader.getInstance().setProperty("hub.protect.channels", "true"); <<<<<<< void testTtlDaysLoss() { HubProperties.setProperty("hub.protect.channels", "true"); ======= public void testTtlDaysLoss() throws Exception { PropertyLoader.getInstance().setProperty("hub.protect.channels", "true"); >>>>>>> void testTtlDaysLoss() { PropertyLoader.getInstance().setProperty("hub.protect.channels", "true"); <<<<<<< void testMaxItemsLoss() { HubProperties.setProperty("hub.protect.channels", "true"); ======= public void testMaxItemsLoss() throws Exception { PropertyLoader.getInstance().setProperty("hub.protect.channels", "true"); >>>>>>> void testMaxItemsLoss() { PropertyLoader.getInstance().setProperty("hub.protect.channels", "true"); <<<<<<< void testReplicationLoss() { HubProperties.setProperty("hub.protect.channels", "true"); ======= public void testReplicationLoss() throws Exception { PropertyLoader.getInstance().setProperty("hub.protect.channels", "true"); >>>>>>> void testReplicationLoss() { PropertyLoader.getInstance().setProperty("hub.protect.channels", "true"); <<<<<<< void testDataLossChange() { HubProperties.setProperty("hub.protect.channels", "false"); ======= public void testDataLossChange() throws Exception { PropertyLoader.getInstance().setProperty("hub.protect.channels", "false"); >>>>>>> void testDataLossChange() { PropertyLoader.getInstance().setProperty("hub.protect.channels", "false");
<<<<<<< <<<<<<< HEAD import com.flightstats.hub.model.*; ======= import com.flightstats.hub.metrics.NewRelicIgnoreTransaction; import com.flightstats.hub.model.BulkContent; import com.flightstats.hub.model.ChannelConfig; import com.flightstats.hub.model.Content; import com.flightstats.hub.model.ContentKey; import com.flightstats.hub.model.InsertedContentKey; >>>>>>> f5383d0a8... Convert a bunch of google Optionals to java's Optionals ======= import com.flightstats.hub.metrics.NewRelicIgnoreTransaction; import com.flightstats.hub.model.BulkContent; import com.flightstats.hub.model.ChannelConfig; import com.flightstats.hub.model.Content; import com.flightstats.hub.model.ContentKey; import com.flightstats.hub.model.InsertedContentKey; >>>>>>> import com.flightstats.hub.model.BulkContent; import com.flightstats.hub.model.ChannelConfig; import com.flightstats.hub.model.Content; import com.flightstats.hub.model.ContentKey; import com.flightstats.hub.model.InsertedContentKey; <<<<<<< import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; ======= >>>>>>> import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; <<<<<<< ======= private final static Logger logger = LoggerFactory.getLogger(ChannelResource.class); >>>>>>>
<<<<<<< import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; ======= import org.junit.Before; import org.junit.Test; >>>>>>> import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; <<<<<<< @BeforeEach void setUp() throws Exception { ======= @Before public void setUp() { >>>>>>> @BeforeEach void setUp() throws Exception { <<<<<<< void testWriteRead() throws Exception { ======= public void testWriteRead() { >>>>>>> void testWriteRead() { <<<<<<< void testPathTranslation() throws Exception { ======= public void testPathTranslation() { >>>>>>> void testPathTranslation() { <<<<<<< void testAdjacentPaths() throws Exception { ======= public void testAdjacentPaths() { >>>>>>> void testAdjacentPaths() { <<<<<<< void testSpokeKeyFromFilePath() throws Exception { ======= public void testSpokeKeyFromFilePath() { >>>>>>> void testSpokeKeyFromFilePath() {
<<<<<<< public Collection<String> readTimeBucket(String path)throws InterruptedException { String[] servers = cluster.getServers(); int serverCount = servers.length; ======= public Collection<ContentKey> readTimeBucket(String path)throws InterruptedException { List<String> servers = cluster.getServers(); // TODO bc 11/17/14: Can we make this read from a subset of the cluster and get all results? int quorum = servers.size(); >>>>>>> public Collection<String> readTimeBucket(String path)throws InterruptedException { List<String> servers = cluster.getServers(); // TODO bc 11/17/14: Can we make this read from a subset of the cluster and get all results? int serverCount = servers.size();
<<<<<<< import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; ======= import lombok.extern.slf4j.Slf4j; import org.junit.BeforeClass; import org.junit.Test; >>>>>>> import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import lombok.extern.slf4j.Slf4j; <<<<<<< class S3SingleContentDaoTest { ======= @Slf4j public class S3SingleContentDaoTest { >>>>>>> @Slf4j class S3SingleContentDaoTest { <<<<<<< @BeforeAll static void setUpClass() throws Exception { HubProperties.loadProperties("useDefault"); ======= @BeforeClass public static void setUpClass() throws Exception { PropertyLoader.getInstance().load("useDefault"); >>>>>>> @BeforeAll static void setUpClass() throws Exception { PropertyLoader.getInstance().load("useDefault"); <<<<<<< void testWriteReadOld() throws Exception { ======= public void testWriteReadOld() { >>>>>>> void testWriteReadOld() {
<<<<<<< verify(httpSession).setAttribute(CurrentUser.CURRENT_USER_REQ_ATTR_NAME, user); ======= verify(httpSession).setAttribute(AuthenticationProvider.CURRENT_USER_REQ_ATTR_NAME, user.getUserId()); >>>>>>> verify(httpSession).setAttribute(CurrentUser.CURRENT_USER_REQ_ATTR_NAME, user.getUserId());
<<<<<<< void testBatchWebhookCreation() { String appUrl = HubProperties.getAppUrl(); String appEnv = HubProperties.getAppEnv(); ======= public void testBatchWebhookCreation() { final String appUrl = "http://localhost:9080/"; final String appEnv = "hub-dev"; >>>>>>> void testBatchWebhookCreation() { final String appUrl = "http://localhost:9080/"; final String appEnv = "hub-dev";
<<<<<<< @Timed(name = "all-groups.post") @ExceptionMetered private ClientResponse getClientResponse(ObjectNode response) { logger.debug("calling {} {}", group.getCallbackUrl(), group.getName()); return client.resource(group.getCallbackUrl()) .type(MediaType.APPLICATION_JSON_TYPE) .post(ClientResponse.class, response.toString()); } public void exit() { ======= public void exit(boolean delete) { deleteOnExit.set(delete); >>>>>>> @Timed(name = "all-groups.post") @ExceptionMetered private ClientResponse getClientResponse(ObjectNode response) { logger.debug("calling {} {}", group.getCallbackUrl(), group.getName()); return client.resource(group.getCallbackUrl()) .type(MediaType.APPLICATION_JSON_TYPE) .post(ClientResponse.class, response.toString()); } public void exit(boolean delete) { deleteOnExit.set(delete);
<<<<<<< class DistributedLockRunnerTest { ======= @Slf4j public class DistributedLockRunnerTest { >>>>>>> @Slf4j class DistributedLockRunnerTest { <<<<<<< @BeforeAll static void setupCurator() throws Exception { ZooKeeperState zooKeeperState = new ZooKeeperState(); CuratorFramework curator = Integration.startZooKeeper(zooKeeperState); ======= @BeforeClass public static void setupCurator() throws Exception { final ZooKeeperState zooKeeperState = new ZooKeeperState(); final CuratorFramework curator = Integration.startZooKeeper(zooKeeperState); >>>>>>> @BeforeAll static void setupCurator() throws Exception { ZooKeeperState zooKeeperState = new ZooKeeperState(); CuratorFramework curator = Integration.startZooKeeper(zooKeeperState); <<<<<<< void test_runWithLock_withTwoLockables_runsOneAtATime() throws Exception { DistributedLockRunner distributedLockRunner = new DistributedLockRunner( lockManager); CountDownLatch waitForMe = new CountDownLatch(1); CountDownLatch latch = new CountDownLatch(2); ======= public void test_runWithLock_withTwoLockables_runsOneAtATime() throws Exception { >>>>>>> void test_runWithLock_withTwoLockables_runsOneAtATime() throws Exception { <<<<<<< Consumer<LeadershipLock> lockable = leadershipLock -> doAThing(0, "lockable2", latch); tryWait(90, waitForMe); ======= Consumer<LeadershipLock> lockable = leadershipLock -> { doAThing(0, "lockable2", latch); }; try { waitForMe.await(90, TimeUnit.MILLISECONDS); } catch (Exception e) { } >>>>>>> Consumer<LeadershipLock> lockable = leadershipLock -> doAThing(0, "lockable2", latch); tryWait(90, waitForMe); <<<<<<< void test_runWithLock_afterAFailureToLock_continuesLocking() throws Exception { DistributedLockRunner distributedLockRunner = new DistributedLockRunner(lockManager); CountDownLatch waitForMe = new CountDownLatch(1); CountDownLatch latch = new CountDownLatch(2); ======= public void test_runWithLock_afterAFailureToLock_continuesLocking() throws Exception { >>>>>>> void test_runWithLock_afterAFailureToLock_continuesLocking() throws Exception { <<<<<<< Consumer<LeadershipLock> lockable = leadershipLock -> doAThing(0, "lockable3", latch); ======= Consumer<LeadershipLock> lockable = leadershipLock -> { doAThing(100, "lockable3", latch); }; >>>>>>> Consumer<LeadershipLock> lockable = leadershipLock -> doAThing(0, "lockable3", latch); <<<<<<< void test_runWithLock_withTwoSeparateLocks_isAbleToLockOnBothPaths() { DistributedLockRunner distributedLockRunner = new DistributedLockRunner(lockManager); CountDownLatch waitForOne = new CountDownLatch(1); CountDownLatch waitForTwo = new CountDownLatch(1); CountDownLatch latch = new CountDownLatch(3); ======= public void test_runWithLock_withTwoSeparateLocks_isAbleToLockOnBothPaths() { >>>>>>> void test_runWithLock_withTwoSeparateLocks_isAbleToLockOnBothPaths() { <<<<<<< doAThing(100, "lockable1", latch); tryWait(50, waitForTwo); ======= doAThing(200, "lockable1", latch); try { waitForTwo.await(50, TimeUnit.MILLISECONDS); } catch (Exception e) { fail(e.getMessage()); } >>>>>>> doAThing(100, "lockable1", latch); tryWait(50, waitForTwo); <<<<<<< tryWait(50, waitForOne); ======= try { waitForOne.await(50, TimeUnit.MILLISECONDS); } catch (Exception e) { fail(e.getMessage()); } >>>>>>> tryWait(50, waitForOne); <<<<<<< Consumer<LeadershipLock> lockable = leadershipLock -> doAThing(0, "lockable3", latch); tryWait(50, waitForOne); ======= Consumer<LeadershipLock> lockable = leadershipLock -> { doAThing(0, "lockable3", latch); }; try { waitForOne.await(50, TimeUnit.MILLISECONDS); } catch (Exception e) { fail(e.getMessage()); } >>>>>>> Consumer<LeadershipLock> lockable = leadershipLock -> doAThing(0, "lockable3", latch); tryWait(50, waitForOne);
<<<<<<< import org.junit.jupiter.api.Test; import com.flightstats.hub.config.AppProperty; import com.flightstats.hub.config.PropertyLoader; ======= import com.flightstats.hub.config.AppProperties; import com.flightstats.hub.config.PropertiesLoader; import org.junit.Test; >>>>>>> import org.junit.jupiter.api.Test; import com.flightstats.hub.config.AppProperties; import com.flightstats.hub.config.PropertiesLoader; <<<<<<< void testLimit() { Traces traces = new Traces(new AppProperty(PropertyLoader.getInstance()),"start"); ======= public void testLimit() { Traces traces = new Traces(new AppProperties(PropertiesLoader.getInstance()),"start"); >>>>>>> void testLimit() { final Traces traces = new Traces(new AppProperties(PropertiesLoader.getInstance()),"start");
<<<<<<< channelValidator.validate(configuration, false, oldConfig); if (isNull(oldConfig) && configuration.isHistorical()) { lastContentPath.initialize(configuration.getName(), ContentKey.NONE, HISTORICAL_LAST_UPDATED); } channelConfigDao.updateChannel(configuration); ======= channelValidator.validate(configuration, false); channelConfigDao.upsert(configuration); >>>>>>> channelValidator.validate(configuration, false, oldConfig); if (isNull(oldConfig) && configuration.isHistorical()) { lastContentPath.initialize(configuration.getName(), ContentKey.NONE, HISTORICAL_LAST_UPDATED); } channelConfigDao.upsert(configuration);
<<<<<<< import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; ======= import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; >>>>>>> import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; <<<<<<< class S3AccessMonitorTest { private final S3BucketName s3BucketName = new S3BucketName("test", "bucket"); ======= public class S3AccessMonitorTest { private final S3BucketName s3BucketName = new S3BucketName( new AppProperty(PropertyLoader.getInstance()), new S3Property(PropertyLoader.getInstance())); >>>>>>> class S3AccessMonitorTest { private final S3BucketName s3BucketName = new S3BucketName( new AppProperty(PropertyLoader.getInstance()), new S3Property(PropertyLoader.getInstance()));
<<<<<<< import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; ======= import org.junit.BeforeClass; import org.junit.Test; >>>>>>> import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; <<<<<<< class CuratorClusterTest { ======= @Slf4j public class CuratorClusterTest { >>>>>>> @Slf4j class CuratorClusterTest { <<<<<<< void testPath() throws Exception { logger.info("starting testPath"); CuratorCluster cluster = new CuratorCluster(curator, "/SpokeCluster", false, true, new SpokeDecommissionCluster(curator)); ======= public void testPath() throws Exception { log.info("starting testPath"); final CuratorCluster clusterTest = new CuratorCluster(curator, "/SpokeCluster", false, true, new SpokeDecommissionCluster(curator, new SpokeProperty(PropertyLoader.getInstance())), new AppProperty(PropertyLoader.getInstance()), new SpokeProperty(PropertyLoader.getInstance())); final CuratorCluster cluster = new CuratorCluster(curator, "/CuratorClusterTest", false, true, new SpokeDecommissionCluster(curator, new SpokeProperty(PropertyLoader.getInstance())), new AppProperty(PropertyLoader.getInstance()), new SpokeProperty(PropertyLoader.getInstance())); >>>>>>> void testPath() throws Exception { log.info("starting testPath"); final CuratorCluster clusterTest = new CuratorCluster(curator, "/SpokeCluster", false, true, new SpokeDecommissionCluster(curator, new SpokeProperty(PropertyLoader.getInstance())), new AppProperty(PropertyLoader.getInstance()), new SpokeProperty(PropertyLoader.getInstance())); final CuratorCluster cluster = new CuratorCluster(curator, "/CuratorClusterTest", false, true, new SpokeDecommissionCluster(curator, new SpokeProperty(PropertyLoader.getInstance())), new AppProperty(PropertyLoader.getInstance()), new SpokeProperty(PropertyLoader.getInstance()));
<<<<<<< public static long getLargePayload() { return HubProperties.getProperty("app.large.payload.MB", 40) * 1024 * 1024; } ======= public static int getCallbackTimeoutMin() { return HubProperties.getProperty("webhook.callbackTimeoutSeconds.min", 1); } public static int getCallbackTimeoutMax() { return HubProperties.getProperty("webhook.callbackTimeoutSeconds.max", 1800); } public static int getCallbackTimeoutDefault() { return HubProperties.getProperty("webhook.callbackTimeoutSeconds.default", 120); } >>>>>>> public static long getLargePayload() { return HubProperties.getProperty("app.large.payload.MB", 40) * 1024 * 1024; } public static int getCallbackTimeoutMin() { return HubProperties.getProperty("webhook.callbackTimeoutSeconds.min", 1); } public static int getCallbackTimeoutMax() { return HubProperties.getProperty("webhook.callbackTimeoutSeconds.max", 1800); } public static int getCallbackTimeoutDefault() { return HubProperties.getProperty("webhook.callbackTimeoutSeconds.default", 120); }
<<<<<<< void testStartingKey() { Webhook withDefaultsA = this.webhook.withDefaults(); Webhook withDefaultsB = this.webhook.withDefaults(); ======= public void testStartingKey() { Webhook withDefaultsA = this.webhook.withDefaults(CALLBACK_TIMEOUT_DEFAULT_IN_SEC); Webhook withDefaultsB = this.webhook.withDefaults(CALLBACK_TIMEOUT_DEFAULT_IN_SEC); >>>>>>> void testStartingKey() { Webhook withDefaultsA = this.webhook.withDefaults(CALLBACK_TIMEOUT_DEFAULT_IN_SEC); Webhook withDefaultsB = this.webhook.withDefaults(CALLBACK_TIMEOUT_DEFAULT_IN_SEC); <<<<<<< void testIsTagPrototype() { Webhook withDefaultsA = this.webhook.withDefaults(); ======= public void testIsTagPrototype() { Webhook withDefaultsA = this.webhook.withDefaults(CALLBACK_TIMEOUT_DEFAULT_IN_SEC); >>>>>>> void testIsTagPrototype() { Webhook withDefaultsA = this.webhook.withDefaults(CALLBACK_TIMEOUT_DEFAULT_IN_SEC); <<<<<<< void testSecondaryMetricsReporting() { Webhook withDefaults = this.webhook.withDefaults(); ======= public void testSecondaryMetricsReporting() { Webhook withDefaults = this.webhook.withDefaults(CALLBACK_TIMEOUT_DEFAULT_IN_SEC); >>>>>>> void testSecondaryMetricsReporting() { Webhook withDefaults = this.webhook.withDefaults(CALLBACK_TIMEOUT_DEFAULT_IN_SEC);
<<<<<<< import com.flightstats.hub.clients.callback.CallbackClientFactory; import com.flightstats.hub.clients.callback.CallbackResourceClient; ======= import com.flightstats.hub.client.CallbackClientFactory; import com.flightstats.hub.client.CallbackResourceClient; >>>>>>> import com.flightstats.hub.clients.callback.CallbackClientFactory; import com.flightstats.hub.clients.callback.CallbackResourceClient; <<<<<<< import com.flightstats.hub.model.WebhookCallback; import com.google.inject.Inject; ======= >>>>>>> import com.flightstats.hub.model.WebhookCallback;
<<<<<<< void testChangeStorageLoss() { PropertyLoader.getInstance().setProperty("hub.protect.channels", "true"); ======= public void testChangeStorageLoss() throws Exception { PropertiesLoader.getInstance().setProperty("hub.protect.channels", "true"); >>>>>>> void testChangeStorageLoss() throws Exception { PropertiesLoader.getInstance().setProperty("hub.protect.channels", "true"); <<<<<<< void testRemoveTagsLoss() { PropertyLoader.getInstance().setProperty("hub.protect.channels", "true"); ======= public void testRemoveTagsLoss() throws Exception { PropertiesLoader.getInstance().setProperty("hub.protect.channels", "true"); >>>>>>> void testRemoveTagsLoss() { PropertiesLoader.getInstance().setProperty("hub.protect.channels", "true"); <<<<<<< void testTtlDaysLoss() { PropertyLoader.getInstance().setProperty("hub.protect.channels", "true"); ======= public void testTtlDaysLoss() throws Exception { PropertiesLoader.getInstance().setProperty("hub.protect.channels", "true"); >>>>>>> void testTtlDaysLoss() { PropertiesLoader.getInstance().setProperty("hub.protect.channels", "true"); <<<<<<< void testMaxItemsLoss() { PropertyLoader.getInstance().setProperty("hub.protect.channels", "true"); ======= public void testMaxItemsLoss() throws Exception { PropertiesLoader.getInstance().setProperty("hub.protect.channels", "true"); >>>>>>> void testMaxItemsLoss() { PropertiesLoader.getInstance().setProperty("hub.protect.channels", "true"); <<<<<<< void testReplicationLoss() { PropertyLoader.getInstance().setProperty("hub.protect.channels", "true"); ======= public void testReplicationLoss() throws Exception { PropertiesLoader.getInstance().setProperty("hub.protect.channels", "true"); >>>>>>> void testReplicationLoss() { PropertiesLoader.getInstance().setProperty("hub.protect.channels", "true"); <<<<<<< void testDataLossChange() { PropertyLoader.getInstance().setProperty("hub.protect.channels", "false"); ======= public void testDataLossChange() throws Exception { PropertiesLoader.getInstance().setProperty("hub.protect.channels", "false"); >>>>>>> void testDataLossChange() { PropertiesLoader.getInstance().setProperty("hub.protect.channels", "false");
<<<<<<< import java.util.Collection; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.*; ======= import java.util.*; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; >>>>>>> import java.util.*; import java.util.concurrent.*;
<<<<<<< import javafx.collections.ObservableSet; import javafx.event.ActionEvent; ======= >>>>>>> import javafx.event.ActionEvent;
<<<<<<< context.register(BaseConfig.class, UiConfig.class, ServiceConfig.class, TaskConfig.class, CacheConfig.class, LuceneConfig.class); ======= context.getBeanFactory().registerSingleton("stage", stage); context.register(BaseConfig.class, UiConfig.class, ServiceConfig.class, TaskConfig.class, CacheConfig.class); >>>>>>> context.getBeanFactory().registerSingleton("stage", stage); context.register(BaseConfig.class, UiConfig.class, ServiceConfig.class, TaskConfig.class, CacheConfig.class, LuceneConfig.class);
<<<<<<< public ChatUser createOrGetChatUser(User user) { ChatUser chatUser = getChatUser(user.getNick()); if (chatUser != null) { return chatUser; ======= public void onConnected() { sendMessageInBackground( "NICKSERV", format("REGISTER %s %s", md5Hex(userService.getPassword()), userService.getEmail()) ).thenAccept(s -> sendMessageInBackground("NICKSERV", "IDENTIFY " + md5Hex(userService.getPassword())) .thenAccept(s1 -> pircBotX.sendIRC().joinChannel(defaultChannelName)) .exceptionally(throwable -> { notificationService.addNotification( new PersistentNotification(i18n.get("irc.identificationFailed", throwable.getLocalizedMessage()), Severity.WARN) ); return null; }) ).exceptionally(throwable -> { notificationService.addNotification( new PersistentNotification(i18n.get("irc.registrationFailed", throwable.getLocalizedMessage()), Severity.WARN) ); return null; }); } @Override public void onDisconnected(Exception e) { synchronized (chatUserLists) { chatUserLists.values().forEach(ObservableMap::clear); >>>>>>> public void onConnected() { sendMessageInBackground( "NICKSERV", format("REGISTER %s %s", md5Hex(userService.getPassword()), userService.getEmail()) ).thenAccept(s -> sendMessageInBackground("NICKSERV", "IDENTIFY " + md5Hex(userService.getPassword())) .thenAccept(s1 -> pircBotX.sendIRC().joinChannel(defaultChannelName)) .exceptionally(throwable -> { notificationService.addNotification( new PersistentNotification(i18n.get("irc.identificationFailed", throwable.getLocalizedMessage()), Severity.WARN) ); return null; }) ).exceptionally(throwable -> { notificationService.addNotification( new PersistentNotification(i18n.get("irc.registrationFailed", throwable.getLocalizedMessage()), Severity.WARN) ); return null; }); } @Override public void onDisconnected(Exception e) { synchronized (chatUserLists) { chatUserLists.values().forEach(ObservableMap::clear); } } @Override public ChatUser createOrGetChatUser(User user) { ChatUser chatUser = getChatUser(user.getNick()); if (chatUser != null) { return chatUser;
<<<<<<< import com.faforever.client.preferences.ForgedAlliancePrefs; import com.faforever.client.preferences.Preferences; import com.faforever.client.preferences.PreferencesService; ======= import com.faforever.client.patch.GameUpdateService; >>>>>>> import com.faforever.client.patch.GameUpdateService; import com.faforever.client.preferences.ForgedAlliancePrefs; import com.faforever.client.preferences.Preferences; import com.faforever.client.preferences.PreferencesService; <<<<<<< instance.lobbyServerAccessor = lobbyServerAccessor; instance.mapService = mapService; instance.forgedAllianceService = forgedAllianceService; instance.proxy = proxy; instance.preferencesService = preferencesService; when(preferencesService.getPreferences()).thenReturn(preferences); when(preferences.getForgedAlliance()).thenReturn(forgedAlliancePrefs); when(forgedAlliancePrefs.getPort()).thenReturn(GAME_PORT); ======= instance.lobbyServerAccessor = lobbyServerAccessor; instance.mapService = mapService; instance.forgedAllianceService = forgedAllianceService; instance.proxy = proxy; instance.gameUpdateService = gameUpdateService; >>>>>>> instance.lobbyServerAccessor = lobbyServerAccessor; instance.mapService = mapService; instance.forgedAllianceService = forgedAllianceService; instance.proxy = proxy; instance.gameUpdateService = gameUpdateService; instance.preferencesService = preferencesService; when(preferencesService.getPreferences()).thenReturn(preferences); when(preferences.getForgedAlliance()).thenReturn(forgedAlliancePrefs); when(forgedAlliancePrefs.getPort()).thenReturn(GAME_PORT); <<<<<<< doAnswer((InvocationOnMock invocation) -> { Callback<GameLaunchInfo> callback = (Callback<GameLaunchInfo>) invocation.getArguments()[1]; callback.success(gameLaunchInfo); return null; }).when(lobbyServerAccessor).requestNewGame(eq(newGameInfo), any(Callback.class)); when(forgedAllianceService.startGame( ======= when(instance.forgedAllianceService.startGame( >>>>>>> when(instance.forgedAllianceService.startGame(
<<<<<<< import com.faforever.client.legacy.domain.ModInfo; ======= import com.faforever.client.legacy.domain.Notice; >>>>>>> import com.faforever.client.legacy.domain.ModInfo; <<<<<<< ======= import com.faforever.client.login.LoginFailedException; import com.faforever.client.preferences.LoginPrefs; >>>>>>> import com.faforever.client.login.LoginFailedException; <<<<<<< private CompletableFuture<LoginInfo> loginFuture; private CompletableFuture<SessionInfo> sessionFuture; private CompletableFuture<GameLaunchInfo> gameLaunchFuture; private Collection<OnRankedMatchNotificationListener> onRankedMatchNotificationListeners; ======= private volatile Callback<SessionInfo> loginCallback; private Callback<GameLaunchInfo> gameLaunchCallback; private Collection<OnGameInfoListener> onGameInfoListeners; private Collection<OnGameTypeInfoListener> onGameTypeInfoListeners; private Collection<OnJoinChannelsRequestListener> onJoinChannelsRequestListeners; private Collection<OnGameLaunchInfoListener> onGameLaunchListeners; >>>>>>> private CompletableFuture<LoginInfo> loginFuture; private CompletableFuture<SessionInfo> sessionFuture; private CompletableFuture<GameLaunchInfo> gameLaunchFuture; private Collection<OnRankedMatchNotificationListener> onRankedMatchNotificationListeners; <<<<<<< if (isCancelled()) { logger.debug("Connection to FAF server has been closed"); ======= if (isCancelled() && loginCallback != null) { logger.debug("Login has been cancelled"); } else if (isCancelled()) { logger.debug("Log out"); >>>>>>> if (isCancelled()) { logger.debug("Connection to FAF server has been closed"); <<<<<<< case MOD_VAULT_INFO: ModInfo modInfo = gson.fromJson(jsonString, ModInfo.class); onModInfo(modInfo); break; case UPDATED_ACHIEVEMENTS: UpdatedAchievementsInfo updatedAchievementsInfo = gson.fromJson(jsonString, UpdatedAchievementsInfo.class); onUpdatedAchievementsListeners.forEach(listener -> listener.accept(updatedAchievementsInfo)); break; ======= case NOTICE: Notice notice = gson.fromJson(jsonString, Notice.class); dispatchNotice(notice); break; >>>>>>> case AUTHENTICATION_FAILED: AuthenticationFailedMessage message = gson.fromJson(jsonString, AuthenticationFailedMessage.class); dispatchAuthenticationFailed(message); break; case MOD_VAULT_INFO: ModInfo modInfo = gson.fromJson(jsonString, ModInfo.class); onModInfo(modInfo); break; case UPDATED_ACHIEVEMENTS: UpdatedAchievementsInfo updatedAchievementsInfo = gson.fromJson(jsonString, UpdatedAchievementsInfo.class); onUpdatedAchievementsListeners.forEach(listener -> listener.accept(updatedAchievementsInfo)); break; <<<<<<< private void onServerPing() { writeToServer(new PongMessage()); } private void onSessionInitiated(SessionInfo sessionInfo) { logger.info("FAF session initiated, session ID: {}", sessionInfo.getSession()); this.sessionId.set(sessionInfo.getSession()); sessionFuture.complete(sessionInfo); logIn(username, password); } private void onFafLoginSucceeded(LoginInfo loginInfo) { logger.info("FAF login succeeded"); if (loginFuture != null) { loginFuture.complete(loginInfo); loginFuture = null; } } private void onGameInfo(GameInfo gameInfo) { onGameInfoListeners.forEach(listener -> listener.onGameInfo(gameInfo)); } private void onGameLaunchInfo(GameLaunchInfo gameLaunchInfo) { onGameLaunchListeners.forEach(listener -> listener.onGameLaunchInfo(gameLaunchInfo)); gameLaunchFuture.complete(gameLaunchInfo); gameLaunchFuture = null; } private void onGameTypeInfo(GameTypeInfo gameTypeInfo) { onGameTypeInfoListeners.forEach(listener -> listener.onGameTypeInfo(gameTypeInfo)); } private void onRankedMatchInfo(RankedMatchNotification gameTypeInfo) { onRankedMatchNotificationListeners.forEach(listener -> listener.onRankedMatchInfo(gameTypeInfo)); } ======= private void dispatchNotice(Notice notice) { if (loginCallback != null && notice.isError()) { onFafLoginFailed(new LoginFailedException(notice)); } else { logger.warn("Unhandled notice: " + notice); } } private void onFafLoginFailed(Throwable e) { logger.info("FAF login failed: {}", e.getMessage()); Platform.runLater(() -> { if (loginCallback != null) { disconnect(); /**should end up in {@link com.faforever.client.login.LoginController#onLoginFailed} */ loginCallback.error(e); loginCallback = null; } }); } private void onFafLoginSucceeded(SessionInfo sessionInfo) { logger.info("FAF login succeeded"); Platform.runLater(() -> { if (loginCallback != null) { loginCallback.success(sessionInfo); loginCallback = null; } }); } >>>>>>> private void dispatchAuthenticationFailed(AuthenticationFailedMessage message) { loginFuture.completeExceptionally(new LoginFailedException(message.getText())); loginFuture = null; } private void onServerPing() { writeToServer(new PongMessage()); } private void onSessionInitiated(SessionInfo sessionInfo) { logger.info("FAF session initiated, session ID: {}", sessionInfo.getSession()); this.sessionId.set(sessionInfo.getSession()); sessionFuture.complete(sessionInfo); logIn(username, password); } private void onFafLoginSucceeded(LoginInfo loginInfo) { logger.info("FAF login succeeded"); if (loginFuture != null) { loginFuture.complete(loginInfo); loginFuture = null; } } private void onGameInfo(GameInfo gameInfo) { onGameInfoListeners.forEach(listener -> listener.onGameInfo(gameInfo)); } private void onGameLaunchInfo(GameLaunchInfo gameLaunchInfo) { onGameLaunchListeners.forEach(listener -> listener.onGameLaunchInfo(gameLaunchInfo)); gameLaunchFuture.complete(gameLaunchInfo); gameLaunchFuture = null; } private void onGameTypeInfo(GameTypeInfo gameTypeInfo) { onGameTypeInfoListeners.forEach(listener -> listener.onGameTypeInfo(gameTypeInfo)); } private void onRankedMatchInfo(RankedMatchNotification gameTypeInfo) { onRankedMatchNotificationListeners.forEach(listener -> listener.onRankedMatchInfo(gameTypeInfo)); }
<<<<<<< import com.faforever.client.fx.SceneFactory; import com.faforever.client.fx.WindowDecorator; ======= import com.faforever.client.chat.PlayerInfoBean; >>>>>>> <<<<<<< import com.faforever.client.legacy.io.QDataOutputStream; import com.faforever.client.map.MapPreviewLargeController; ======= import com.faforever.client.legacy.domain.GameState; >>>>>>> <<<<<<< import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.ObservableMap; ======= import com.faforever.client.util.RatingUtil; >>>>>>> import javafx.collections.FXCollections; import javafx.collections.ObservableList; <<<<<<< import javafx.scene.paint.Paint; import javafx.scene.text.Text; import javafx.scene.text.TextFlow; import javafx.stage.Modality; ======= >>>>>>> import javafx.scene.paint.Paint; import javafx.scene.text.Text; import javafx.scene.text.TextFlow; <<<<<<< private static final Pattern RATING_PATTERN = Pattern.compile("([<>+~](?:\\d\\.?\\d?k|\\d{3,4})|(?:\\d\\.?\\d?k|\\d{3,4})[<>+]|(?:\\d\\.?\\d?k|\\d{1,4})\\s?-\\s?(?:\\d\\.?\\d?k|\\d{3,4}))"); @FXML VBox teamListPane; ======= private static final Predicate<GameInfoBean> OPEN_GAMES_PREDICATE = gameInfoBean -> gameInfoBean.getStatus() == GameState.OPEN; >>>>>>> private static final Predicate<GameInfoBean> OPEN_GAMES_PREDICATE = gameInfoBean -> gameInfoBean.getStatus() == GameState.OPEN; @FXML VBox teamListPane; <<<<<<< ======= ApplicationContext applicationContext; @Autowired >>>>>>> ApplicationContext applicationContext; @Autowired <<<<<<< @Autowired SceneFactory sceneFactory; private ObservableList<GameInfoBean> gameInfoBeans; ======= @Autowired PlayerService playerService; @Autowired NotificationService notificationService; >>>>>>> @Autowired SceneFactory sceneFactory; @Autowired NotificationService notificationService; <<<<<<< private GameInfoBean currentGameInfoBean; public GamesController() { gameInfoBeans = FXCollections.observableArrayList(); } ======= private FxmlLoader fxmlLoader; >>>>>>> private GameInfoBean currentGameInfoBean;
<<<<<<< private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private final Timer timer; private Collection<OnGameTypeInfoListener> onModInfoMessageListeners; private OnPlayerInfoListener onPlayerInfoListener; private Collection<OnGameInfoListener> onGameInfoListeners; private Collection<OnRankedMatchNotificationListener> onRankedMatchNotificationListeners; ======= private final Collection<OnGameTypeInfoListener> onModInfoMessageListeners; private final Collection<OnGameInfoListener> onGameInfoListeners; >>>>>>> private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private final Timer timer;
<<<<<<< ======= } } private void initGameTypeComboBox() { gameService.addOnGameTypeInfoListener(change -> { change.getValueAdded(); gameTypeComboBox.getItems().add(change.getValueAdded()); CreateGameController.this.selectLastOrDefaultGameType(); >>>>>>>
<<<<<<< import com.faforever.client.legacy.domain.GameLaunchInfo; import com.faforever.client.rankedmatch.OnRankedMatchNotificationListener; import com.faforever.client.util.Callback; ======= >>>>>>> import com.faforever.client.legacy.domain.GameLaunchInfo; import com.faforever.client.rankedmatch.OnRankedMatchNotificationListener;
<<<<<<< import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.springframework.beans.factory.annotation.Autowired; ======= >>>>>>> import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.springframework.beans.factory.annotation.Autowired; <<<<<<< import javax.annotation.PostConstruct; ======= import javax.annotation.Resource; >>>>>>> import javax.annotation.Resource; import javax.annotation.PostConstruct;
<<<<<<< import com.faforever.client.legacy.gson.FactionSerializer; ======= import com.faforever.client.legacy.gson.ClientMessageTypeTypeAdapter; >>>>>>> import com.faforever.client.legacy.gson.FactionSerializer; import com.faforever.client.legacy.gson.ClientMessageTypeTypeAdapter;
<<<<<<< import javax.annotation.PreDestroy; ======= import javax.annotation.Resource; >>>>>>> import javax.annotation.PreDestroy; import javax.annotation.Resource;
<<<<<<< import com.faforever.client.rankedmatch.Accept1v1MatchMessage; import com.faforever.client.rankedmatch.OnRankedMatchNotificationListener; import com.faforever.client.rankedmatch.RankedMatchNotification; import com.faforever.client.rankedmatch.SearchRanked1v1Message; import com.faforever.client.rankedmatch.StopSearchRanked1v1Message; import com.faforever.client.task.PrioritizedTask; ======= import com.faforever.client.task.AbstractPrioritizedTask; >>>>>>> import com.faforever.client.rankedmatch.OnRankedMatchNotificationListener; import com.faforever.client.rankedmatch.RankedMatchNotification; import com.faforever.client.rankedmatch.SearchRanked1v1Message; import com.faforever.client.rankedmatch.StopSearchRanked1v1Message; import com.faforever.client.task.AbstractPrioritizedTask; <<<<<<< private Callback<SessionInfo> loginCallback; private Callback<GameLaunchInfo> gameLaunchCallback; private Collection<OnRankedMatchNotificationListener> onRankedMatchNotificationListeners; ======= private CompletableFuture<SessionInfo> loginFuture; private CompletableFuture<GameLaunchInfo> gameLaunchFuture; >>>>>>> private CompletableFuture<SessionInfo> loginFuture; private CompletableFuture<GameLaunchInfo> gameLaunchFuture; private Collection<OnRankedMatchNotificationListener> onRankedMatchNotificationListeners;
<<<<<<< ======= private CompletableFuture<Path> downloadReplayToTemporaryDirectory(int replayId) { ReplayDownloadTask task = applicationContext.getBean(ReplayDownloadTask.class); task.setReplayId(replayId); return taskService.submitTask(task); } >>>>>>> private CompletableFuture<Path> downloadReplayToTemporaryDirectory(int replayId) { ReplayDownloadTask task = applicationContext.getBean(ReplayDownloadTask.class); task.setReplayId(replayId); return taskService.submitTask(task); }
<<<<<<< import com.faforever.client.legacy.domain.GameState; import com.faforever.client.legacy.domain.PlayerInfo; ======= import com.faforever.client.legacy.domain.Player; >>>>>>> import com.faforever.client.legacy.domain.GameState; import com.faforever.client.legacy.domain.PlayerInfo; import com.faforever.client.legacy.domain.Player; <<<<<<< import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; ======= import org.slf4j.Logger; import org.slf4j.LoggerFactory; >>>>>>> import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; <<<<<<< import java.lang.invoke.MethodHandles; ======= import javax.annotation.Resource; import java.lang.invoke.MethodHandles; >>>>>>> import javax.annotation.Resource; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles; <<<<<<< @Autowired GameService gameService; ======= >>>>>>> @Autowired GameService gameService;
<<<<<<< private Collection<OnGameInfoListener> onGameInfoListeners; private Collection<OnGameTypeInfoListener> onGameTypeInfoListeners; private Collection<OnJoinChannelsRequestListener> onJoinChannelsRequestListeners; private Collection<OnGameLaunchInfoListener> onGameLaunchListeners; private Collection<OnRankedMatchNotificationListener> onRankedMatchNotificationListeners; ======= >>>>>>> private Collection<OnRankedMatchNotificationListener> onRankedMatchNotificationListeners; <<<<<<< private void onGameInfo(GameInfo gameInfo) { onGameInfoListeners.forEach(listener -> listener.onGameInfo(gameInfo)); } private void onGameTypeInfo(GameTypeInfo gameTypeInfo) { onGameTypeInfoListeners.forEach(listener -> listener.onGameTypeInfo(gameTypeInfo)); } private void onRankedMatchInfo(RankedMatchNotification gameTypeInfo) { onRankedMatchNotificationListeners.forEach(listener -> listener.onRankedMatchInfo(gameTypeInfo)); } ======= >>>>>>>
<<<<<<< import com.faforever.client.legacy.GameStatus; import com.faforever.client.legacy.domain.GameState; import com.faforever.client.legacy.domain.PlayerInfo; ======= import com.faforever.client.legacy.domain.Player; >>>>>>> import com.faforever.client.legacy.GameStatus; import com.faforever.client.legacy.domain.GameState; import com.faforever.client.legacy.domain.PlayerInfo; import com.faforever.client.legacy.domain.Player; <<<<<<< import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleObjectProperty; ======= import javafx.beans.property.SimpleIntegerProperty; >>>>>>> import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleIntegerProperty; <<<<<<< private final IntegerProperty gameUid; private final SimpleObjectProperty<GameStatus> gameStatus; ======= private final IntegerProperty numberOfGames; >>>>>>> private final IntegerProperty gameUid; private final SimpleObjectProperty<GameStatus> gameStatus; private final IntegerProperty numberOfGames; <<<<<<< gameStatus = new SimpleObjectProperty<>(); gameUid = new SimpleIntegerProperty(); ======= numberOfGames = new SimpleIntegerProperty(); >>>>>>> gameStatus = new SimpleObjectProperty<>(); gameUid = new SimpleIntegerProperty(); numberOfGames = new SimpleIntegerProperty(); <<<<<<< public float getLeaderboardRatingDeviation() { return leaderboardRatingDeviation.get(); } public void setLeaderboardRatingDeviation(float leaderboardRatingDeviation) { this.leaderboardRatingDeviation.set(leaderboardRatingDeviation); } public FloatProperty leaderboardRatingDeviationProperty() { return leaderboardRatingDeviation; } public void updateFromPlayerInfo(PlayerInfo playerInfo) { ======= public void updateFromPlayerInfo(Player player) { >>>>>>> public float getLeaderboardRatingDeviation() { return leaderboardRatingDeviation.get(); } public void setLeaderboardRatingDeviation(float leaderboardRatingDeviation) { this.leaderboardRatingDeviation.set(leaderboardRatingDeviation); } public FloatProperty leaderboardRatingDeviationProperty() { return leaderboardRatingDeviation; } public void updateFromPlayerInfo(Player player) {
<<<<<<< hosterLabel.textProperty().bind(gameInfoBean.hostProperty()); gameModeLabel.textProperty().bind(gameInfoBean.featuredModProperty()); mapLabel.textProperty().bind(gameInfoBean.mapTechnicalNameProperty()); ======= hostLabel.textProperty().bind(gameInfoBean.hostProperty()); mapLabel.textProperty().bind(gameInfoBean.technicalNameProperty()); gameInfoBean.featuredModProperty().addListener((observable, oldValue, newValue) -> { updateGameType(newValue); }); updateGameType(gameInfoBean.getFeaturedMod()); >>>>>>> hostLabel.textProperty().bind(gameInfoBean.hostProperty()); mapLabel.textProperty().bind(gameInfoBean.mapTechnicalNameProperty()); gameInfoBean.featuredModProperty().addListener((observable, oldValue, newValue) -> { updateGameType(newValue); }); updateGameType(gameInfoBean.getFeaturedMod());
<<<<<<< import org.mockito.Mock; ======= import org.mockito.Mock; import org.mockito.MockitoAnnotations; >>>>>>> import org.mockito.Mock; import org.mockito.MockitoAnnotations; <<<<<<< @Mock LobbyServerAccessor lobbyServerAccessor; @Mock UserService userService; ======= @Mock UserService userService; @Mock private LobbyServerAccessor lobbyServerAccessor; >>>>>>> @Mock UserService userService; @Mock LobbyServerAccessor lobbyServerAccessor;
<<<<<<< ======= public void displayAfterLogOut() { setShowLoginProgress(false); stage.show(); JavaFxUtil.centerOnScreen(stage); } @FXML void loginButtonClicked(ActionEvent actionEvent) { try { String username = usernameInput.getText(); String password = passwordInput.getText(); password = DigestUtils.sha256Hex(password); boolean autoLogin = autoLoginCheckBox.isSelected(); login(username, password, autoLogin); } catch (Throwable e) { onLoginFailed(e); } } >>>>>>> public void displayAfterLogOut() { setShowLoginProgress(false); stage.show(); JavaFxUtil.centerOnScreen(stage); } <<<<<<< Platform.runLater(() -> mainController.display(stage)); ======= stage.hide(); mainController.display(); >>>>>>> Platform.runLater(() -> mainController.display(stage)); <<<<<<< logger.warn("Login failed", e); Dialog<Void> loginFailedDialog = new Dialog<>(); loginFailedDialog.setTitle(i18n.get("login.failed.title")); loginFailedDialog.setContentText(i18n.get("login.failed.message")); loginFailedDialog.show(); loginFormPane.setVisible(true); loginProgressPane.setVisible(false); loginButton.setDisable(false); ======= if (e instanceof LoginFailedException) { logger.debug("Login failed: {}", e.getMessage()); loginErrorLabel.setText(i18n.get("login.failed.message")); } else { logger.warn("Login failed on unexpected exception", e); loginErrorLabel.setText(e.getMessage() == null ? String.valueOf(e) : e.getMessage()); } setShowLoginProgress(false); loginErrorLabel.setVisible(true); >>>>>>> logger.debug("Login failed", e); loginErrorLabel.setText(i18n.get("login.failed.message")); setShowLoginProgress(false); loginErrorLabel.setVisible(true);
<<<<<<< import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; ======= import static com.faforever.client.test.AbstractPlainJavaTest.assertEquals; import static com.faforever.client.test.AbstractPlainJavaTest.assertNull; import static org.mockito.Matchers.any; >>>>>>> import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.Matchers.any;
<<<<<<< chatConnectedLatch.countDown(); pircBotX.sendIRC().joinChannel(defaultChannelName); ======= ircConnectedLatch.countDown(); joinChannel(defaultChannelName); >>>>>>> chatConnectedLatch.countDown(); joinChannel(defaultChannelName);
<<<<<<< public void outSelect(SQLSession session, QueryEnvironment env, boolean uniqueViolation) throws SQLException, SQLHandledException { compile(new CompileOptions<V>(session.syntax)).outSelect(session, env, uniqueViolation); ======= public void outSelect(SQLSession session, QueryEnvironment env) throws SQLException, SQLHandledException { compile(new CompileOptions<>(session.syntax)).outSelect(session, env); >>>>>>> public void outSelect(SQLSession session, QueryEnvironment env, boolean uniqueViolation) throws SQLException, SQLHandledException { compile(new CompileOptions<>(session.syntax)).outSelect(session, env, uniqueViolation);
<<<<<<< LAP result = addExportPropertyAProp(LocalizedString.NONAME, type, resultInterfaces.size(), idSet, exprTypes, orders, targetProp, whereProperty != null, hasListOption, separator, noHeader, charset, attr, resultParams.toArray()); ======= ImOrderSet<String> exportIdSet = SetFact.EMPTYORDER(); for(String id : idSet) { if(!orderIds.contains(id)) { exportIdSet = exportIdSet.addOrderExcl(id); } } LAP result = addExportPropertyAProp(LocalizedString.NONAME, type, resultInterfaces.size(), idSet, exportIdSet, exprTypes, orders, targetProp, whereProperty != null, hasListOption, separator, noHeader, charset, resultParams.toArray()); >>>>>>> ImOrderSet<String> exportIdSet = SetFact.EMPTYORDER(); for(String id : idSet) { if(!orderIds.contains(id)) { exportIdSet = exportIdSet.addOrderExcl(id); } } LAP result = addExportPropertyAProp(LocalizedString.NONAME, type, resultInterfaces.size(), idSet, exportIdSet, exprTypes, orders, targetProp, whereProperty != null, hasListOption, separator, noHeader, charset, attr, resultParams.toArray());
<<<<<<< if(windowType == null) windowType = WindowFormType.FLOAT; ======= if(windowType == null) { if (!inputObjects.isEmpty()) windowType = WindowFormType.DIALOG; else windowType = WindowFormType.FLOAT; } >>>>>>> if(windowType == null) windowType = WindowFormType.FLOAT; <<<<<<< PropertyUsage fileProp, Boolean hasListOption, String separator, boolean noHeader, String charset, boolean attr, ======= PropertyUsage fileProp, Boolean hasListOption, String separator, boolean noHeader, boolean noEscape, String charset, >>>>>>> PropertyUsage fileProp, Boolean hasListOption, String separator, boolean noHeader, boolean noEscape, String charset, boolean attr, <<<<<<< whereProperty != null, hasListOption, separator, noHeader, charset, attr, resultParams.toArray()); ======= whereProperty != null, hasListOption, separator, noHeader, noEscape, charset, resultParams.toArray()); >>>>>>> whereProperty != null, hasListOption, separator, noHeader, noEscape, charset, attr, resultParams.toArray());
<<<<<<< InputStream inputStream = fileData.getInputStream(); ftpClient.changeWorkingDirectory(remoteFile); ======= InputStream inputStream = new FileInputStream(file); >>>>>>> InputStream inputStream = fileData.getInputStream();
<<<<<<< package lsfusion.server.logics.reflection; import lsfusion.interop.action.MessageClientAction; import lsfusion.server.classes.ValueClass; import lsfusion.server.data.SQLHandledException; import lsfusion.server.data.SQLSession; import lsfusion.server.logics.DataObject; import lsfusion.server.logics.ObjectValue; import lsfusion.server.logics.ReflectionLogicsModule; import lsfusion.server.logics.i18n.LocalizedString; import lsfusion.server.logics.property.ClassPropertyInterface; import lsfusion.server.logics.property.ExecutionContext; import lsfusion.server.logics.scripted.ScriptingActionProperty; import lsfusion.server.logics.service.RunService; import lsfusion.server.logics.service.ServiceDBActionProperty; import java.sql.SQLException; import java.util.Iterator; import static lsfusion.server.context.ThreadLocalContext.localize; public class RecalculateTableColumnWithDependentsActionProperty extends ScriptingActionProperty { private final ClassPropertyInterface tableColumnInterface; public RecalculateTableColumnWithDependentsActionProperty(ReflectionLogicsModule LM, ValueClass... classes) { super(LM, classes); Iterator<ClassPropertyInterface> i = interfaces.iterator(); tableColumnInterface = i.next(); } @Override public void executeCustom(final ExecutionContext<ClassPropertyInterface> context) throws SQLException, SQLHandledException { DataObject tableColumnObject = context.getDataKeyValue(tableColumnInterface); final ObjectValue propertyObject = context.getBL().reflectionLM.propertyTableColumn.readClasses(context, tableColumnObject); final String propertyCanonicalName = (String) context.getBL().reflectionLM.canonicalNameProperty.read(context, propertyObject); boolean disableAggregations = context.getBL().reflectionLM.disableAggregationsTableColumn.read(context, tableColumnObject) != null; if (!disableAggregations) { ServiceDBActionProperty.run(context, new RunService() { public void run(SQLSession session, boolean isolatedTransaction) throws SQLException, SQLHandledException { context.getDbManager().recalculateAggregationWithDependenciesTableColumn(session, context.stack, propertyCanonicalName.trim(), isolatedTransaction, true); } }); context.delayUserInterfaction(new MessageClientAction(localize(LocalizedString.createFormatted("{logics.recalculation.completed}", localize("{logics.recalculation.aggregations}"))), localize("{logics.recalculation.aggregations}"))); } } ======= package lsfusion.server.logics.reflection; import lsfusion.interop.action.MessageClientAction; import lsfusion.server.classes.ValueClass; import lsfusion.server.data.SQLHandledException; import lsfusion.server.data.SQLSession; import lsfusion.server.logics.DataObject; import lsfusion.server.logics.ObjectValue; import lsfusion.server.logics.ReflectionLogicsModule; import lsfusion.server.physics.dev.i18n.LocalizedString; import lsfusion.server.logics.property.ClassPropertyInterface; import lsfusion.server.logics.property.ExecutionContext; import lsfusion.server.language.ScriptingActionProperty; import lsfusion.server.logics.service.RunService; import lsfusion.server.logics.service.ServiceDBActionProperty; import java.sql.SQLException; import java.util.Iterator; import static lsfusion.server.context.ThreadLocalContext.localize; public class RecalculateTableColumnWithDependentsActionProperty extends ScriptingActionProperty { private final ClassPropertyInterface tableColumnInterface; public RecalculateTableColumnWithDependentsActionProperty(ReflectionLogicsModule LM, ValueClass... classes) { super(LM, classes); Iterator<ClassPropertyInterface> i = interfaces.iterator(); tableColumnInterface = i.next(); } @Override public void executeCustom(final ExecutionContext<ClassPropertyInterface> context) throws SQLException, SQLHandledException { DataObject tableColumnObject = context.getDataKeyValue(tableColumnInterface); final ObjectValue propertyObject = context.getBL().reflectionLM.propertyTableColumn.readClasses(context, tableColumnObject); final String propertyCanonicalName = (String) context.getBL().reflectionLM.canonicalNameProperty.read(context, propertyObject); ServiceDBActionProperty.run(context, new RunService() { public void run(SQLSession session, boolean isolatedTransaction) throws SQLException, SQLHandledException { context.getDbManager().recalculateAggregationWithDependenciesTableColumn(session, context.stack, propertyCanonicalName.trim(), isolatedTransaction, true); } }); context.delayUserInterfaction(new MessageClientAction(localize(LocalizedString.createFormatted("{logics.recalculation.completed}", localize("{logics.recalculation.aggregations}"))), localize("{logics.recalculation.aggregations}"))); } >>>>>>> package lsfusion.server.logics.reflection; import lsfusion.interop.action.MessageClientAction; import lsfusion.server.classes.ValueClass; import lsfusion.server.data.SQLHandledException; import lsfusion.server.data.SQLSession; import lsfusion.server.logics.DataObject; import lsfusion.server.logics.ObjectValue; import lsfusion.server.logics.ReflectionLogicsModule; import lsfusion.server.physics.dev.i18n.LocalizedString; import lsfusion.server.logics.property.ClassPropertyInterface; import lsfusion.server.logics.property.ExecutionContext; import lsfusion.server.language.ScriptingActionProperty; import lsfusion.server.logics.service.RunService; import lsfusion.server.logics.service.ServiceDBActionProperty; import java.sql.SQLException; import java.util.Iterator; import static lsfusion.server.context.ThreadLocalContext.localize; public class RecalculateTableColumnWithDependentsActionProperty extends ScriptingActionProperty { private final ClassPropertyInterface tableColumnInterface; public RecalculateTableColumnWithDependentsActionProperty(ReflectionLogicsModule LM, ValueClass... classes) { super(LM, classes); Iterator<ClassPropertyInterface> i = interfaces.iterator(); tableColumnInterface = i.next(); } @Override public void executeCustom(final ExecutionContext<ClassPropertyInterface> context) throws SQLException, SQLHandledException { DataObject tableColumnObject = context.getDataKeyValue(tableColumnInterface); final ObjectValue propertyObject = context.getBL().reflectionLM.propertyTableColumn.readClasses(context, tableColumnObject); final String propertyCanonicalName = (String) context.getBL().reflectionLM.canonicalNameProperty.read(context, propertyObject); boolean disableAggregations = context.getBL().reflectionLM.disableAggregationsTableColumn.read(context, tableColumnObject) != null; if (!disableAggregations) { ServiceDBActionProperty.run(context, new RunService() { public void run(SQLSession session, boolean isolatedTransaction) throws SQLException, SQLHandledException { context.getDbManager().recalculateAggregationWithDependenciesTableColumn(session, context.stack, propertyCanonicalName.trim(), isolatedTransaction, true); } }); context.delayUserInterfaction(new MessageClientAction(localize(LocalizedString.createFormatted("{logics.recalculation.completed}", localize("{logics.recalculation.aggregations}"))), localize("{logics.recalculation.aggregations}"))); } }
<<<<<<< package lsfusion.interop; import lsfusion.base.NavigatorInfo; import lsfusion.interop.action.ReportPath; import lsfusion.interop.event.IDaemonTask; import lsfusion.interop.form.screen.ExternalScreen; import lsfusion.interop.form.screen.ExternalScreenParameters; import lsfusion.interop.navigator.RemoteNavigatorInterface; import lsfusion.interop.remote.PendingRemoteInterface; import java.nio.charset.Charset; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.List; import java.util.Map; public interface RemoteLogicsInterface extends PendingRemoteInterface { Integer getApiVersion() throws RemoteException; String getPlatformVersion() throws RemoteException; GUIPreferences getGUIPreferences() throws RemoteException; RemoteNavigatorInterface createNavigator(boolean isFullClient, NavigatorInfo navigatorInfo, boolean forceCreateNew) throws RemoteException; Long getComputer(String hostname) throws RemoteException; ArrayList<IDaemonTask> getDaemonTasks(long compId) throws RemoteException; ExternalScreen getExternalScreen(int screenID) throws RemoteException; ExternalScreenParameters getExternalScreenParameters(int screenID, long computerId) throws RemoteException; List<String> authenticateUser(String userName, String password) throws RemoteException; VMOptions getClientVMOptions() throws RemoteException; void remindPassword(String email, String localeLanguage) throws RemoteException; byte[] readFile(String canonicalName, String... params) throws RemoteException; //external requests List<Object> exec(String action, String[] returnCanonicalNames, Object[] params, Charset charset) throws RemoteException; List<Object> eval(boolean action, Object paramScript, String[] returnCanonicalNames, Object[] params, String charset) throws RemoteException; List<Object> read(String property, Object[] params, Charset charset) throws RemoteException; boolean isSingleInstance() throws RemoteException; long generateID() throws RemoteException; String addUser(String username, String email, String password, String firstName, String lastName, String localeLanguage) throws RemoteException; void ping() throws RemoteException; void sendPingInfo(Long computerId, Map<Long, List<Long>> pingInfoMap) throws RemoteException; Map<String, String> readMemoryLimits() throws RemoteException; List<ReportPath> saveAndGetCustomReportPathList(String formSID, boolean recreate) throws RemoteException; } ======= package lsfusion.interop; import lsfusion.base.NavigatorInfo; import lsfusion.interop.action.ReportPath; import lsfusion.interop.event.IDaemonTask; import lsfusion.interop.form.screen.ExternalScreen; import lsfusion.interop.form.screen.ExternalScreenParameters; import lsfusion.interop.navigator.RemoteNavigatorInterface; import lsfusion.interop.remote.PendingRemoteInterface; import java.nio.charset.Charset; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; public interface RemoteLogicsInterface extends PendingRemoteInterface { Integer getApiVersion() throws RemoteException; String getPlatformVersion() throws RemoteException; GUIPreferences getGUIPreferences() throws RemoteException; RemoteNavigatorInterface createNavigator(boolean isFullClient, NavigatorInfo navigatorInfo, boolean forceCreateNew) throws RemoteException; Set<String> syncUsers(Set<String> userNames) throws RemoteException; Long getComputer(String hostname) throws RemoteException; ArrayList<IDaemonTask> getDaemonTasks(long compId) throws RemoteException; ExternalScreen getExternalScreen(int screenID) throws RemoteException; ExternalScreenParameters getExternalScreenParameters(int screenID, long computerId) throws RemoteException; List<String> authenticateUser(String userName, String password) throws RemoteException; VMOptions getClientVMOptions() throws RemoteException; void remindPassword(String email, String localeLanguage) throws RemoteException; byte[] readFile(String canonicalName, String... params) throws RemoteException; //external requests List<Object> exec(String action, String[] returnCanonicalNames, Object[] params, Charset charset) throws RemoteException; List<Object> eval(boolean action, Object paramScript, String[] returnCanonicalNames, Object[] params, String charset) throws RemoteException; List<Object> read(String property, Object[] params, Charset charset) throws RemoteException; String getFormCanonicalName(String navigatorElementCanonicalName) throws RemoteException; boolean isSingleInstance() throws RemoteException; long generateID() throws RemoteException; String addUser(String username, String email, String password, String firstName, String lastName, String localeLanguage) throws RemoteException; void ping() throws RemoteException; void sendPingInfo(Long computerId, Map<Long, List<Long>> pingInfoMap) throws RemoteException; Map<String, String> readMemoryLimits() throws RemoteException; List<ReportPath> saveAndGetCustomReportPathList(String formSID, boolean recreate) throws RemoteException; } >>>>>>> package lsfusion.interop; import lsfusion.base.NavigatorInfo; import lsfusion.interop.action.ReportPath; import lsfusion.interop.event.IDaemonTask; import lsfusion.interop.form.screen.ExternalScreen; import lsfusion.interop.form.screen.ExternalScreenParameters; import lsfusion.interop.navigator.RemoteNavigatorInterface; import lsfusion.interop.remote.PendingRemoteInterface; import java.nio.charset.Charset; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; public interface RemoteLogicsInterface extends PendingRemoteInterface { Integer getApiVersion() throws RemoteException; String getPlatformVersion() throws RemoteException; GUIPreferences getGUIPreferences() throws RemoteException; RemoteNavigatorInterface createNavigator(boolean isFullClient, NavigatorInfo navigatorInfo, boolean forceCreateNew) throws RemoteException; Set<String> syncUsers(Set<String> userNames) throws RemoteException; Long getComputer(String hostname) throws RemoteException; ArrayList<IDaemonTask> getDaemonTasks(long compId) throws RemoteException; ExternalScreen getExternalScreen(int screenID) throws RemoteException; ExternalScreenParameters getExternalScreenParameters(int screenID, long computerId) throws RemoteException; List<String> authenticateUser(String userName, String password) throws RemoteException; VMOptions getClientVMOptions() throws RemoteException; void remindPassword(String email, String localeLanguage) throws RemoteException; byte[] readFile(String canonicalName, String... params) throws RemoteException; //external requests List<Object> exec(String action, String[] returnCanonicalNames, Object[] params, Charset charset) throws RemoteException; List<Object> eval(boolean action, Object paramScript, String[] returnCanonicalNames, Object[] params, String charset) throws RemoteException; List<Object> read(String property, Object[] params, Charset charset) throws RemoteException; boolean isSingleInstance() throws RemoteException; long generateID() throws RemoteException; String addUser(String username, String email, String password, String firstName, String lastName, String localeLanguage) throws RemoteException; void ping() throws RemoteException; void sendPingInfo(Long computerId, Map<Long, List<Long>> pingInfoMap) throws RemoteException; Map<String, String> readMemoryLimits() throws RemoteException; List<ReportPath> saveAndGetCustomReportPathList(String formSID, boolean recreate) throws RemoteException; }
<<<<<<< import lsfusion.server.logics.property.CalcProperty; import lsfusion.server.logics.property.PropertyInterface; ======= import lsfusion.server.logics.property.ActionProperty; >>>>>>> import lsfusion.server.logics.property.ActionProperty; import lsfusion.server.logics.property.CalcProperty; import lsfusion.server.logics.property.PropertyInterface; <<<<<<< private List<Object> executeExternal(LAP<?> property, String[] returnCanonicalNames, Object[] params, Charset charset, String[] headerNames, String[][] headerValues) throws SQLException, ParseException, SQLHandledException, IOException { ======= // system actions that are needed for native clients public boolean isClientNativeRESTAction(ActionProperty action) { return false; } private List<Object> executeExternal(LAP<?> property, String[] returnCanonicalNames, Object[] params, Charset charset) throws SQLException, ParseException, SQLHandledException, IOException { if(!isClientNativeRESTAction(property.property) && !Settings.get().isEnableRESTApi()) throw new RuntimeException("REST Api is disabled. It can be enabled using setting enableRESTApi."); >>>>>>> // system actions that are needed for native clients public boolean isClientNativeRESTAction(ActionProperty action) { return false; } private List<Object> executeExternal(LAP<?> property, String[] returnCanonicalNames, Object[] params, Charset charset, String[] headerNames, String[][] headerValues) throws SQLException, ParseException, SQLHandledException, IOException { if(!isClientNativeRESTAction(property.property) && !Settings.get().isEnableRESTApi()) throw new RuntimeException("REST Api is disabled. It can be enabled using setting enableRESTApi.");
<<<<<<< ======= // checkBounds() instead of assertBounds(), because getChars works with "long" series of bytes >>>>>>> <<<<<<< final long cumBaseOffset = state.getCumBaseOffset(); long address = cumBaseOffset + offsetBytes; final long addressLimit = address + utf8LengthBytes; ======= if (dst instanceof CharBuffer && ((CharBuffer) dst).hasArray()) { getCharsFromUtf8CharBuffer(offsetBytes, ((CharBuffer) dst), utf8LengthBytes, state); return; } long address = state.getCumBaseOffset() + offsetBytes; int i = 0; >>>>>>> final long cumBaseOffset = state.getCumBaseOffset(); long address = cumBaseOffset + offsetBytes; final Object unsafeObj = state.getUnsafeObject(); if ((dst instanceof CharBuffer) && ((CharBuffer) dst).hasArray()) { getCharsFromUtf8CharBuffer(offsetBytes, ((CharBuffer) dst), utf8LengthBytes, cumBaseOffset, state); return; } int i = 0; // Optimize for 100% ASCII (Hotspot loves small simple top-level loops like this). // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII). // Need to keep this loop int-indexed, because it's faster for Hotspot JIT, it doesn't insert // savepoint polls on each iteration. for (; i < utf8LengthBytes; i++) { final byte b = unsafe.getByte(unsafeObj, address + i); if (!DecodeUtil.isOneByte(b)) { break; } dst.append((char) b); } if (i == utf8LengthBytes) { return; } getCharsFromUtf8NonAscii(dst, address + i, address + utf8LengthBytes, unsafeObj, cumBaseOffset); } /** * Optimize for heap CharBuffer manually, because Hotspot JIT doesn't itself unfold this * abstraction well (doesn't hoist array bound checks, etc.) */ private static void getCharsFromUtf8CharBuffer(final long offsetBytes, final CharBuffer cb, final int utf8LengthBytes, final long cumBaseOffset, final ResourceState state) { char[] ca = cb.array(); int cp = cb.position() + cb.arrayOffset(); int cl = cb.arrayOffset() + cb.limit(); long address = state.getCumBaseOffset() + offsetBytes; int i = 0; <<<<<<< //Encode ======= private static void getCharsFromUtf8NonAsciiCharBuffer(CharBuffer cb, char[] ca, int cp, int cl, long address, long addressLimit, Object unsafeObj) { while (address < addressLimit) { final byte byte1 = unsafe.getByte(unsafeObj, address++); if (DecodeUtil.isOneByte(byte1)) { checkCharBufferPos(cb, cp, cl); ca[cp++] = (char) byte1; // It's common for there to be multiple ASCII characters in a run mixed in, so add an // extra optimized loop to take care of these runs. while (address < addressLimit) { final byte b = unsafe.getByte(unsafeObj, address); if (!DecodeUtil.isOneByte(b)) { break; } address++; checkCharBufferPos(cb, cp, cl); ca[cp++] = (char) b; } } else if (DecodeUtil.isTwoBytes(byte1)) { if (address >= addressLimit) { cb.position(cp - cb.arrayOffset()); throw Utf8CodingException.inputBounds(address, addressLimit); } checkCharBufferPos(cb, cp, cl); DecodeUtil.handleTwoBytesCharBuffer( byte1, /* byte2 */ unsafe.getByte(unsafeObj, address++), cb, ca, cp); cp++; } else if (DecodeUtil.isThreeBytes(byte1)) { if (address >= (addressLimit - 1)) { cb.position(cp - cb.arrayOffset()); throw Utf8CodingException.inputBounds(address + 1, addressLimit); } checkCharBufferPos(cb, cp, cl); DecodeUtil.handleThreeBytesCharBuffer( byte1, /* byte2 */ unsafe.getByte(unsafeObj, address++), /* byte3 */ unsafe.getByte(unsafeObj, address++), cb, ca, cp); cp++; } else { if (address >= (addressLimit - 2)) { cb.position(cp - cb.arrayOffset()); throw Utf8CodingException.inputBounds(address + 2, addressLimit); } if (cp >= cl - 1) { cb.position(cp - cb.arrayOffset()); throw new BufferOverflowException(); } DecodeUtil.handleFourBytesCharBuffer( byte1, /* byte2 */ unsafe.getByte(unsafeObj, address++), /* byte3 */ unsafe.getByte(unsafeObj, address++), /* byte4 */ unsafe.getByte(unsafeObj, address++), cb, ca, cp); cp += 2; } } cb.position(cp - cb.arrayOffset()); } >>>>>>> private static void getCharsFromUtf8NonAsciiCharBuffer(CharBuffer cb, char[] ca, int cp, int cl, long address, long addressLimit, Object unsafeObj, long cumBaseOffset) { while (address < addressLimit) { final byte byte1 = unsafe.getByte(unsafeObj, address++); if (DecodeUtil.isOneByte(byte1)) { checkCharBufferPos(cb, cp, cl); ca[cp++] = (char) byte1; // It's common for there to be multiple ASCII characters in a run mixed in, so add an // extra optimized loop to take care of these runs. while (address < addressLimit) { final byte b = unsafe.getByte(unsafeObj, address); if (!DecodeUtil.isOneByte(b)) { break; } address++; checkCharBufferPos(cb, cp, cl); ca[cp++] = (char) b; } } else if (DecodeUtil.isTwoBytes(byte1)) { if (address >= addressLimit) { cb.position(cp - cb.arrayOffset()); long off = address - cumBaseOffset; long limit = addressLimit - cumBaseOffset; throw Utf8CodingException.shortUtf8DecodeByteSequence(byte1, off, limit, 2); } checkCharBufferPos(cb, cp, cl); DecodeUtil.handleTwoBytesCharBuffer( byte1, /* byte2 */ unsafe.getByte(unsafeObj, address++), cb, ca, cp); cp++; } else if (DecodeUtil.isThreeBytes(byte1)) { if (address >= (addressLimit - 1)) { cb.position(cp - cb.arrayOffset()); long off = address - cumBaseOffset; long limit = addressLimit - cumBaseOffset; throw Utf8CodingException.shortUtf8DecodeByteSequence(byte1, off, limit, 3); } checkCharBufferPos(cb, cp, cl); DecodeUtil.handleThreeBytesCharBuffer( byte1, /* byte2 */ unsafe.getByte(unsafeObj, address++), /* byte3 */ unsafe.getByte(unsafeObj, address++), cb, ca, cp); cp++; } else { if (address >= (addressLimit - 2)) { cb.position(cp - cb.arrayOffset()); long off = address - cumBaseOffset; long limit = addressLimit - cumBaseOffset; throw Utf8CodingException.shortUtf8DecodeByteSequence(byte1, off, limit, 4); } if (cp >= (cl - 1)) { cb.position(cp - cb.arrayOffset()); throw new BufferOverflowException(); } DecodeUtil.handleFourBytesCharBuffer( byte1, /* byte2 */ unsafe.getByte(unsafeObj, address++), /* byte3 */ unsafe.getByte(unsafeObj, address++), /* byte4 */ unsafe.getByte(unsafeObj, address++), cb, ca, cp); cp += 2; } } cb.position(cp - cb.arrayOffset()); } //Encode
<<<<<<< ======= import com.google.protobuf.ByteString; import org.testng.annotations.Test; import java.io.IOException; import java.nio.CharBuffer; import java.nio.charset.StandardCharsets; >>>>>>> import com.google.protobuf.ByteString; import org.testng.annotations.Test; import java.io.IOException; import java.nio.CharBuffer; <<<<<<< private static void assertRoundTrips(String str, int index, int size) { byte[] bytes = str.getBytes(UTF_8); ======= private static void assertRoundTrips(String str, int index, int size) throws IOException { byte[] bytes = str.getBytes(StandardCharsets.UTF_8); >>>>>>> private static void assertRoundTrips(String str, int index, int size) throws IOException { byte[] bytes = str.getBytes(UTF_8);
<<<<<<< ExternalUtils.ExternalResponse response = ExternalUtils.processRequest(remoteLogics, request.getRequestURI().getPath(), request.getRequestURI().getRawQuery(), request.getRequestBody(), new HashMap<String, String[]>(), getContentType(request)); ======= String[] headerNames = request.getRequestHeaders().keySet().toArray(new String[0]); String[] headerValues = getRequestHeaderValues(request.getRequestHeaders(), headerNames); InetSocketAddress remoteAddress = request.getRemoteAddress(); InetAddress address = remoteAddress.getAddress(); SessionInfo sessionInfo = new SessionInfo(remoteAddress.getHostName(), address != null ? address.getHostAddress() : null, null, null);// client locale does not matter since we use anonymous authentication String uriPath = request.getRequestURI().getPath(); String url = "http://" + request.getRequestHeaders().getFirst("Host") + uriPath; ExecInterface remoteExec = ExternalUtils.getExecInterface(AuthenticationToken.ANONYMOUS, sessionInfo, remoteLogics); ExternalUtils.ExternalResponse response = ExternalUtils.processRequest(remoteExec, url, uriPath, request.getRequestURI().getRawQuery(), request.getRequestBody(), getContentType(request), headerNames, headerValues, null, null, null); >>>>>>> String[] headerNames = request.getRequestHeaders().keySet().toArray(new String[0]); String[] headerValues = getRequestHeaderValues(request.getRequestHeaders(), headerNames); InetSocketAddress remoteAddress = request.getRemoteAddress(); InetAddress address = remoteAddress.getAddress(); SessionInfo sessionInfo = new SessionInfo(remoteAddress.getHostName(), address != null ? address.getHostAddress() : null, null, null);// client locale does not matter since we use anonymous authentication String uriPath = request.getRequestURI().getPath(); String url = "http://" + request.getRequestHeaders().getFirst("Host") + uriPath; ExecInterface remoteExec = ExternalUtils.getExecInterface(AuthenticationToken.ANONYMOUS, sessionInfo, remoteLogics); ExternalUtils.ExternalResponse response = ExternalUtils.processRequest(remoteExec, url, uriPath, request.getRequestURI().getRawQuery(), request.getRequestBody(), new HashMap<String, String[]>(), getContentType(request), headerNames, headerValues, null, null, null);
<<<<<<< package lsfusion.server.logics.scripted; import lsfusion.base.col.interfaces.immutable.ImMap; import lsfusion.interop.action.MessageClientAction; import lsfusion.server.data.SQLHandledException; import lsfusion.server.logics.DataObject; import lsfusion.server.logics.ObjectValue; import lsfusion.server.logics.i18n.LocalizedString; import lsfusion.server.logics.linear.LAP; import lsfusion.server.logics.linear.LCP; import lsfusion.server.logics.property.ClassPropertyInterface; import lsfusion.server.logics.property.ClassType; import lsfusion.server.logics.property.ExecutionContext; import lsfusion.server.logics.property.PropertyInterface; import lsfusion.server.logics.property.actions.SystemExplicitActionProperty; import lsfusion.server.logics.property.actions.flow.ChangeFlowType; import org.antlr.runtime.RecognitionException; import java.sql.SQLException; import java.util.List; public class EvalActionProperty<P extends PropertyInterface> extends SystemExplicitActionProperty { private final LCP<P> source; private final List<LCP<P>> params; private final ImMap<P, ClassPropertyInterface> mapSource; private boolean action; public EvalActionProperty(LocalizedString caption, LCP<P> source, List<LCP<P>> params, boolean action) { super(caption, source.getInterfaceClasses(ClassType.aroundPolicy)); mapSource = source.listInterfaces.mapSet(getOrderInterfaces()); this.source = source; this.params = params; this.action = action; } private String getScript(ExecutionContext<ClassPropertyInterface> context) throws SQLException, SQLHandledException { ImMap<P, ? extends ObjectValue> sourceToData = mapSource.join(context.getKeys()); return (String) source.read(context, source.listInterfaces.mapList(sourceToData).toArray(new ObjectValue[interfaces.size()])); } private ObjectValue[] getParams(ExecutionContext<ClassPropertyInterface> context) throws SQLException, SQLHandledException { ObjectValue[] result = new ObjectValue[params.size()]; for(int i = 0; i < params.size(); i++) { LCP<P> param = params.get(i); ImMap<P, ? extends ObjectValue> paramToData = param.listInterfaces.mapSet(getOrderInterfaces()).join(context.getKeys()); result[i] = param.readClasses(context, (DataObject[]) param.listInterfaces.mapList(paramToData).toArray(new DataObject[param.listInterfaces.size()])); } return result; } @Override protected void executeCustom(ExecutionContext<ClassPropertyInterface> context) throws SQLException, SQLHandledException { String script = getScript(context); try { LAP<?> runAction = context.getBL().evaluateRun(script, action); if (runAction != null) runAction.execute(context, getParams(context)); } catch (EvalUtils.EvaluationException | RecognitionException e) { context.delayUserInteraction(new MessageClientAction(getMessage(e), "Parse error")); throw new RuntimeException(e); } catch (Throwable e) { context.delayUserInteraction(new MessageClientAction(getMessage(e), "Execution error")); throw new RuntimeException(e); } } @Override public boolean hasFlow(ChangeFlowType type) { return true; } private String getMessage(Throwable e) { return e.getMessage() == null ? String.valueOf(e) : e.getMessage(); } } ======= package lsfusion.server.logics.scripted; import com.google.common.base.Throwables; import lsfusion.base.ExceptionUtils; import lsfusion.base.col.interfaces.immutable.ImMap; import lsfusion.interop.action.MessageClientAction; import lsfusion.server.data.SQLHandledException; import lsfusion.server.logics.DataObject; import lsfusion.server.logics.ObjectValue; import lsfusion.server.logics.debug.ActionDelegationType; import lsfusion.server.logics.debug.WatchActionProperty; import lsfusion.server.logics.i18n.LocalizedString; import lsfusion.server.logics.linear.LAP; import lsfusion.server.logics.linear.LCP; import lsfusion.server.logics.property.ClassPropertyInterface; import lsfusion.server.logics.property.ClassType; import lsfusion.server.logics.property.ExecutionContext; import lsfusion.server.logics.property.PropertyInterface; import lsfusion.server.logics.property.actions.SystemExplicitActionProperty; import lsfusion.server.logics.property.actions.flow.ChangeFlowType; import lsfusion.server.stack.ExecutionStackAspect; import org.antlr.runtime.RecognitionException; import java.sql.SQLException; import java.util.List; public class EvalActionProperty<P extends PropertyInterface> extends SystemExplicitActionProperty { private final LCP<P> source; private final List<LCP<P>> params; private final ImMap<P, ClassPropertyInterface> mapSource; public EvalActionProperty(LocalizedString caption, LCP<P> source, List<LCP<P>> params) { super(caption, source.getInterfaceClasses(ClassType.aroundPolicy)); mapSource = source.listInterfaces.mapSet(getOrderInterfaces()); this.source = source; this.params = params; } private String getScript(ExecutionContext<ClassPropertyInterface> context) throws SQLException, SQLHandledException { ImMap<P, ? extends ObjectValue> sourceToData = mapSource.join(context.getKeys()); return (String) source.read(context, source.listInterfaces.mapOrder(sourceToData).toArray(new ObjectValue[interfaces.size()])); } private ObjectValue[] getParams(ExecutionContext<ClassPropertyInterface> context) throws SQLException, SQLHandledException { ObjectValue[] result = new ObjectValue[params.size()]; for(int i = 0; i < params.size(); i++) { LCP<P> param = params.get(i); ImMap<P, ? extends ObjectValue> paramToData = param.listInterfaces.mapSet(getOrderInterfaces()).join(context.getKeys()); result[i] = param.readClasses(context, (DataObject[]) param.listInterfaces.mapOrder(paramToData).toArray(new DataObject[param.listInterfaces.size()])); } return result; } @Override protected void executeCustom(ExecutionContext<ClassPropertyInterface> context) throws SQLException, SQLHandledException { String script = getScript(context); try { LAP<?> runAction = context.getBL().evaluateRun(script); if (runAction != null) runAction.execute(context, getParams(context)); } catch (EvalUtils.EvaluationException | RecognitionException e) { throw Throwables.propagate(e); } } @Override public boolean hasFlow(ChangeFlowType type) { return true; } @Override public ActionDelegationType getDelegationType(boolean modifyContext) { return ActionDelegationType.IN_DELEGATE; // execute just like EXEC operator } private String getMessage(Throwable e) { return e.getMessage() == null ? String.valueOf(e) : e.getMessage(); } } >>>>>>> package lsfusion.server.logics.scripted; import com.google.common.base.Throwables; import lsfusion.base.ExceptionUtils; import lsfusion.base.col.interfaces.immutable.ImMap; import lsfusion.interop.action.MessageClientAction; import lsfusion.server.data.SQLHandledException; import lsfusion.server.logics.DataObject; import lsfusion.server.logics.ObjectValue; import lsfusion.server.logics.debug.ActionDelegationType; import lsfusion.server.logics.debug.WatchActionProperty; import lsfusion.server.logics.i18n.LocalizedString; import lsfusion.server.logics.linear.LAP; import lsfusion.server.logics.linear.LCP; import lsfusion.server.logics.property.ClassPropertyInterface; import lsfusion.server.logics.property.ClassType; import lsfusion.server.logics.property.ExecutionContext; import lsfusion.server.logics.property.PropertyInterface; import lsfusion.server.logics.property.actions.SystemExplicitActionProperty; import lsfusion.server.logics.property.actions.flow.ChangeFlowType; import lsfusion.server.stack.ExecutionStackAspect; import org.antlr.runtime.RecognitionException; import java.sql.SQLException; import java.util.List; public class EvalActionProperty<P extends PropertyInterface> extends SystemExplicitActionProperty { private final LCP<P> source; private final List<LCP<P>> params; private final ImMap<P, ClassPropertyInterface> mapSource; private boolean action; public EvalActionProperty(LocalizedString caption, LCP<P> source, List<LCP<P>> params, boolean action) { super(caption, source.getInterfaceClasses(ClassType.aroundPolicy)); mapSource = source.listInterfaces.mapSet(getOrderInterfaces()); this.source = source; this.params = params; this.action = action; } private String getScript(ExecutionContext<ClassPropertyInterface> context) throws SQLException, SQLHandledException { ImMap<P, ? extends ObjectValue> sourceToData = mapSource.join(context.getKeys()); return (String) source.read(context, source.listInterfaces.mapList(sourceToData).toArray(new ObjectValue[interfaces.size()])); } private ObjectValue[] getParams(ExecutionContext<ClassPropertyInterface> context) throws SQLException, SQLHandledException { ObjectValue[] result = new ObjectValue[params.size()]; for(int i = 0; i < params.size(); i++) { LCP<P> param = params.get(i); ImMap<P, ? extends ObjectValue> paramToData = param.listInterfaces.mapSet(getOrderInterfaces()).join(context.getKeys()); result[i] = param.readClasses(context, (DataObject[]) param.listInterfaces.mapList(paramToData).toArray(new DataObject[param.listInterfaces.size()])); } return result; } @Override protected void executeCustom(ExecutionContext<ClassPropertyInterface> context) throws SQLException, SQLHandledException { String script = getScript(context); try { LAP<?> runAction = context.getBL().evaluateRun(script, action); if (runAction != null) runAction.execute(context, getParams(context)); } catch (EvalUtils.EvaluationException | RecognitionException e) { throw Throwables.propagate(e); } } @Override public boolean hasFlow(ChangeFlowType type) { return true; } @Override public ActionDelegationType getDelegationType(boolean modifyContext) { return ActionDelegationType.IN_DELEGATE; // execute just like EXEC operator } private String getMessage(Throwable e) { return e.getMessage() == null ? String.valueOf(e) : e.getMessage(); } }
<<<<<<< boolean disableAggregations = context.getBL().reflectionLM.disableAggregationsTableColumn.read(context, tableColumnObject) != null; if(!disableAggregations) { try (DataSession dataSession = context.createSession()) { ServiceDBActionProperty.run(context, new RunService() { public void run(SQLSession session, boolean isolatedTransaction) throws SQLException, SQLHandledException { context.getDbManager().recalculateAggregationTableColumn(dataSession, session, propertyCanonicalName.trim(), isolatedTransaction); } }); dataSession.apply(context); } context.delayUserInterfaction(new MessageClientAction(localize(LocalizedString.createFormatted("{logics.recalculation.completed}", localize("{logics.recalculation.aggregations}"))), localize("{logics.recalculation.aggregations}"))); ======= try(ExecutionContext.NewSession<ClassPropertyInterface> newContext = context.newSession()) { final DataSession dataSession = newContext.getSession(); ServiceDBActionProperty.run(context, new RunService() { public void run(SQLSession session, boolean isolatedTransaction) throws SQLException, SQLHandledException { context.getDbManager().recalculateAggregationTableColumn(dataSession, session, propertyCanonicalName.trim(), isolatedTransaction); } }); newContext.apply(); >>>>>>> boolean disableAggregations = context.getBL().reflectionLM.disableAggregationsTableColumn.read(context, tableColumnObject) != null; if(!disableAggregations) { try(ExecutionContext.NewSession<ClassPropertyInterface> newContext = context.newSession()) { final DataSession dataSession = newContext.getSession(); ServiceDBActionProperty.run(context, new RunService() { public void run(SQLSession session, boolean isolatedTransaction) throws SQLException, SQLHandledException { context.getDbManager().recalculateAggregationTableColumn(dataSession, session, propertyCanonicalName.trim(), isolatedTransaction); } }); newContext.apply(); } context.delayUserInterfaction(new MessageClientAction(localize(LocalizedString.createFormatted("{logics.recalculation.completed}", localize("{logics.recalculation.aggregations}"))), localize("{logics.recalculation.aggregations}")));
<<<<<<< import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; ======= >>>>>>> import java.util.Map;
<<<<<<< import lsfusion.base.RawFileData; import lsfusion.interop.action.MessageClientAction; import lsfusion.server.ServerLoggers; import lsfusion.server.logics.property.ExecutionContext; ======= >>>>>>> <<<<<<< if (readResult.errorCode == 0) { String error = null; ======= if (readResult != null) { File sourceFile = new File(readResult.filePath); >>>>>>> if (readResult != null) { File sourceFile = new File(readResult.filePath); <<<<<<< ======= deleteFile(readResult.filePath); >>>>>>> deleteFile(readResult.filePath); <<<<<<< deleteSFTPFile(srcPath.path); break; default: if (!new File(readResult.filePath).delete()) { error = String.format("Failed to delete file '%s'", readResult.filePath); } ======= deleteSFTPFile(srcPath.path); >>>>>>> deleteSFTPFile(srcPath.path);
<<<<<<< this.classView = entity.classView; this.pageSize = entity.getDefaultPageSize(); ======= // текущее состояние if (this.curClassView != entity.initClassView) { this.curClassView = entity.initClassView; this.updated |= UPDATED_CLASSVIEW; } this.pageSize = entity.pageSize; >>>>>>> this.classView = entity.classView; this.pageSize = entity.pageSize; <<<<<<< private boolean pendingUpdateKeys; private boolean pendingUpdateScroll; private boolean pendingUpdateObjects; private boolean pendingUpdateFilters; private boolean pendingUpdateObject; private boolean pendingUpdatePageSize; public final Set<PropertyReaderInstance> pendingUpdateProps = new HashSet<>(); private boolean isPending() { return pendingUpdateKeys || pendingUpdateScroll || !pendingUpdateProps.isEmpty(); } // we won't check for groupMode change public void checkPending(MFormChanges changes, Runnable change) { boolean wasPending = isPending(); change.run(); boolean isPending = isPending(); if(isPending != wasPending) changes.updateStateObjects.add(this, isPending); } ======= // вообще касается всего что идет после проверки на hidden, можно было бо обобщить, но пока нет смысла private boolean pendingHiddenUpdateKeys; private boolean pendingHiddenUpdateObjects; >>>>>>> private boolean pendingUpdateKeys; private boolean pendingUpdateScroll; private boolean pendingUpdateObjects; private boolean pendingUpdateFilters; private boolean pendingUpdateObject; private boolean pendingUpdatePageSize; public final Set<PropertyReaderInstance> pendingUpdateProps = new HashSet<>(); private boolean isPending() { return pendingUpdateKeys || pendingUpdateScroll || !pendingUpdateProps.isEmpty(); } // we won't check for groupMode change public void checkPending(MFormChanges changes, Runnable change) { boolean wasPending = isPending(); change.run(); boolean isPending = isPending(); if(isPending != wasPending) changes.updateStateObjects.add(this, isPending); } <<<<<<< // FILTERS ======= // если изменились класс грида или представление boolean updateFilters = refresh || (updated & (UPDATED_GRIDCLASS | UPDATED_CLASSVIEW)) != 0; boolean objectsUpdated = false; >>>>>>> // FILTERS <<<<<<< scroll = new Pair<>(new SeekOrderObjects(keys.getValue(lowestInd), false), DIRECTION_UP); } else // наоборот вниз if (downKeys && keyNum >= keys.size() - pageSize) { // assert что pageSize не null int highestInd = keys.size() - pageSize * 2; if (highestInd < 0) // по сути HOME scroll = new Pair<>(SEEK_HOME, null); else scroll = new Pair<>(new SeekOrderObjects(keys.getValue(highestInd), false), DIRECTION_DOWN); } } return scroll; } public ImMap<ObjectInstance, DataObject> readKeys(MFormChanges result, boolean updateFilters, boolean updatePageSize, ImMap<ObjectInstance, DataObject> currentObject, SeekObjects seeks, int direction, SQLSession sql, QueryEnvironment env, Modifier modifier, ExecutionEnvironment execEnv, BaseClass baseClass, ReallyChanged reallyChanged) throws SQLException, SQLHandledException { updated = (updated | UPDATED_KEYS); if (!classView.isGrid()) { // панель ImMap<ObjectInstance, DataObject> readKeys = seeks.readKeys(sql, env, modifier, baseClass, reallyChanged); updateViewProperty(execEnv, readKeys); return readKeys; } else { int activeRow = -1; // какой ряд выбранным будем считать if (isInTree()) { // если дерево, то без поиска, но возможно с parent'ами ImOrderMap<ImMap<ObjectInstance, DataObject>, ImMap<Object, ObjectValue>> treeElements = executeTree(sql, env, modifier, baseClass, reallyChanged); ImList<ImMap<ObjectInstance, DataObject>> expandParents = treeElements.mapListValues( value -> immutableCast( value.filterFn( (key, value1) -> key instanceof ObjectInstance && value1 instanceof DataObject))); keys = treeElements.mapOrderValues(MapFact::EMPTY); ImOrderMap<ImMap<ObjectInstance, DataObject>, Boolean> groupExpandables = treeElements .filterOrderValuesMap(element -> element.containsKey("expandable") || element.containsKey("expandable2")) .mapOrderValues( (Function<ImMap<Object, ObjectValue>, Boolean>) value -> { ObjectValue expandable1 = value.get("expandable"); ObjectValue expandable2 = value.get("expandable2"); return expandable1 instanceof DataObject || expandable2 instanceof DataObject; }); result.expandables.exclAdd(this, groupExpandables.getMap()); result.parentObjects.exclAdd(this, expandParents); activeRow = keys.size() == 0 ? -1 : 0; } else { keys = MapFact.EMPTYORDER(); if(setGroupMode != null) { boolean useGroupMode = groupMode != null; if(updateFilters || updatePageSize) useGroupMode = false; if(!useGroupMode) { // we are not sure int readSize = getPageSize(); keys = SEEK_HOME.executeOrders(sql, env, modifier, baseClass, readSize, true, reallyChanged); if(keys.size() == readSize) useGroupMode = true; } if(useGroupMode) { this.groupMode = setGroupMode; keys = executeGroup(sql, env, modifier, baseClass, getGroupPageSize(), reallyChanged); } else this.groupMode = null; ======= orderSeeks = (SeekOrderObjects)seeks; if (isInTree()) { // если дерево, то без поиска, но возможно с parent'ами assert orderSeeks.values.isEmpty() && !orderSeeks.end; // if(updateFilters) { // неудобно когда дерево сворачивается каждый раз // if(expandTable !=null) { // потому как могут уже скажем классы стать не актуальными после применения // expandTable.drop(sql, env.getOpOwner()); // expandTable = null; // } // } ImOrderMap<ImMap<ObjectInstance, DataObject>, ImMap<Object, ObjectValue>> treeElements = executeTree(sql, env, modifier, baseClass, reallyChanged); ImList<ImMap<ObjectInstance, DataObject>> expandParents = treeElements.mapListValues( value -> immutableCast( value.filterFn( (key, value1) -> key instanceof ObjectInstance && value1 instanceof DataObject))); keys = treeElements.mapOrderValues(MapFact::EMPTY); ImOrderMap<ImMap<ObjectInstance, DataObject>, Boolean> groupExpandables = treeElements .filterOrderValuesMap(element -> element.containsKey("expandable") || element.containsKey("expandable2")) .mapOrderValues( (Function<ImMap<Object, ObjectValue>, Boolean>) value -> { ObjectValue expandable1 = value.get("expandable"); ObjectValue expandable2 = value.get("expandable2"); return expandable1 instanceof DataObject || expandable2 instanceof DataObject; }); result.expandables.exclAdd(this, groupExpandables.getMap()); result.parentObjects.exclAdd(this, expandParents); activeRow = keys.size() == 0 ? -1 : 0; >>>>>>> scroll = new Pair<>(new SeekOrderObjects(keys.getValue(lowestInd), false), DIRECTION_UP); } else // наоборот вниз if (downKeys && keyNum >= keys.size() - pageSize) { // assert что pageSize не null int highestInd = keys.size() - pageSize * 2; if (highestInd < 0) // по сути HOME scroll = new Pair<>(SEEK_HOME, null); else scroll = new Pair<>(new SeekOrderObjects(keys.getValue(highestInd), false), DIRECTION_DOWN); } } return scroll; } public ImMap<ObjectInstance, DataObject> readKeys(MFormChanges result, boolean updateFilters, boolean updatePageSize, ImMap<ObjectInstance, DataObject> currentObject, SeekObjects seeks, int direction, SQLSession sql, QueryEnvironment env, Modifier modifier, ExecutionEnvironment execEnv, BaseClass baseClass, ReallyChanged reallyChanged) throws SQLException, SQLHandledException { updated = (updated | UPDATED_KEYS); if (!classView.isGrid()) { // панель ImMap<ObjectInstance, DataObject> readKeys = seeks.readKeys(sql, env, modifier, baseClass, reallyChanged); updateViewProperty(execEnv, readKeys); return readKeys; } else { int activeRow = -1; // какой ряд выбранным будем считать if (isInTree()) { // если дерево, то без поиска, но возможно с parent'ами ImOrderMap<ImMap<ObjectInstance, DataObject>, ImMap<Object, ObjectValue>> treeElements = executeTree(sql, env, modifier, baseClass, reallyChanged); ImList<ImMap<ObjectInstance, DataObject>> expandParents = treeElements.mapListValues( value -> immutableCast( value.filterFn( (key, value1) -> key instanceof ObjectInstance && value1 instanceof DataObject))); keys = treeElements.mapOrderValues(MapFact::EMPTY); ImOrderMap<ImMap<ObjectInstance, DataObject>, Boolean> groupExpandables = treeElements .filterOrderValuesMap(element -> element.containsKey("expandable") || element.containsKey("expandable2")) .mapOrderValues( (Function<ImMap<Object, ObjectValue>, Boolean>) value -> { ObjectValue expandable1 = value.get("expandable"); ObjectValue expandable2 = value.get("expandable2"); return expandable1 instanceof DataObject || expandable2 instanceof DataObject; }); result.expandables.exclAdd(this, groupExpandables.getMap()); result.parentObjects.exclAdd(this, expandParents); activeRow = keys.size() == 0 ? -1 : 0; } else { keys = MapFact.EMPTYORDER(); if(setGroupMode != null) { boolean useGroupMode = groupMode != null; if(updateFilters || updatePageSize) useGroupMode = false; if(!useGroupMode) { // we are not sure int readSize = getPageSize(); keys = SEEK_HOME.executeOrders(sql, env, modifier, baseClass, readSize, true, reallyChanged); if(keys.size() == readSize) useGroupMode = true; } if(useGroupMode) { this.groupMode = setGroupMode; keys = executeGroup(sql, env, modifier, baseClass, getGroupPageSize(), reallyChanged); } else this.groupMode = null; <<<<<<< ======= // параллельно будем обновлять ключи чтобы JoinSelect'ить keyTable.writeKeys(sql, keys.keys(), env.getOpOwner()); result.gridObjects.exclAdd(this, keys.keyOrderSet()); updateViewProperty(execEnv, keyTable); if(seeks == SEEK_NULL) return MapFact.EMPTY(); if (!keys.containsKey(currentObject)) { // если нету currentObject'а, его нужно изменить if(getUpTreeGroup()==null) // если верхняя группа return activeRow>=0?keys.getKey(activeRow):MapFact.EMPTY(); else // иначе assertion что activeRow < 0, выбираем верхнюю return keys.size()>0 && !currentObject.isEmpty()?keys.getKey(0):null; } else // так как сейчас клиент требует прислать ему groupObject даже если он не изменился, если приходят ключи return currentObject; >>>>>>>
<<<<<<< addScriptedJProp(getArithProp("+"), Arrays.asList(connectionString, new LCPWithParams(addCProp(StringClass.text, LocalizedString.create(request, false))))), null, null, BaseUtils.add(params, actionLCP), context, toPropertyUsageList); ======= addScriptedJProp(getArithProp("+"), Arrays.asList(connectionString, new LCPWithParams(addCProp(StringClass.text, LocalizedString.create(eval ? "eval" : "/exec?action=$" + (params.size()+1), false))))), null, null, null, BaseUtils.add(params, action), context, toPropertyUsageList); >>>>>>> addScriptedJProp(getArithProp("+"), Arrays.asList(connectionString, new LCPWithParams(addCProp(StringClass.text, LocalizedString.create(request, false))))), null, null, null, BaseUtils.add(params, actionLCP), context, toPropertyUsageList);
<<<<<<< ======= import lsfusion.base.RawFileData; import lsfusion.base.col.ListFact; import lsfusion.base.col.interfaces.immutable.ImMap; >>>>>>> import lsfusion.base.RawFileData; import lsfusion.base.col.ListFact; import lsfusion.base.col.interfaces.immutable.ImMap; <<<<<<< public ImportXLSIterator(ImOrderMap<String, Type> fieldTypes, byte[] file, boolean xlsx, boolean noHeader, Integer singleSheetIndex) throws IOException { super(fieldTypes, noHeader); ======= public ImportXLSIterator(ImOrderMap<String, Type> fieldTypes, RawFileData file, boolean xlsx, Integer singleSheetIndex) throws IOException { super(fieldTypes); >>>>>>> public ImportXLSIterator(ImOrderMap<String, Type> fieldTypes, RawFileData file, boolean xlsx, boolean noHeader, Integer singleSheetIndex) throws IOException { super(fieldTypes, noHeader);
<<<<<<< import java.util.HashMap; ======= import java.util.List; import java.util.Map; >>>>>>> import java.util.HashMap; import java.util.List; import java.util.Map; <<<<<<< request.getRequestURI(), query, request.getInputStream(), new HashMap<String, String[]>(), contentType, headerNames, headerValues, cookieNames, cookieValues, ======= request.getRequestURI(), query, requestInputStream, contentType, headerNames, headerValues, cookieNames, cookieValues, >>>>>>> request.getRequestURI(), query, requestInputStream, new HashMap<String, String[]>(), contentType, headerNames, headerValues, cookieNames, cookieValues,
<<<<<<< public LAPWithParams addScriptedExternalLSFActionProp(LCPWithParams connectionString, LCPWithParams actionLCP, boolean eval, boolean action, List<LCPWithParams> params, List<TypedParameter> context, List<PropertyUsage> toPropertyUsageList) throws ScriptingErrorLog.SemanticErrorException { String request = eval ? (action ? "eval/action" : "eval") : "/exec?action=$" + (params.size()+1); return addScriptedExternalHTTPActionProp(addScriptedJProp(getArithProp("+"), Arrays.asList(connectionString, new LCPWithParams(addCProp(StringClass.text, LocalizedString.create(request, false))))), BaseUtils.add(params, actionLCP), context, toPropertyUsageList); ======= public LAPWithParams addScriptedExternalLSFActionProp(LCPWithParams connectionString, LCPWithParams action, boolean eval, List<LCPWithParams> params, List<TypedParameter> context, List<PropertyUsage> toPropertyUsageList) throws ScriptingErrorLog.SemanticErrorException { return addScriptedExternalHTTPActionProp(addScriptedJProp(getArithProp("+"), Arrays.asList(connectionString, new LCPWithParams(addCProp(StringClass.text, LocalizedString.create(eval ? "eval" : "/exec?action=$" + (params.size()+1), false))))), null, BaseUtils.add(params, action), context, toPropertyUsageList); >>>>>>> public LAPWithParams addScriptedExternalLSFActionProp(LCPWithParams connectionString, LCPWithParams actionLCP, boolean eval, boolean action, List<LCPWithParams> params, List<TypedParameter> context, List<PropertyUsage> toPropertyUsageList) throws ScriptingErrorLog.SemanticErrorException { String request = eval ? (action ? "eval/action" : "eval") : "/exec?action=$" + (params.size()+1); return addScriptedExternalHTTPActionProp(addScriptedJProp(getArithProp("+"), Arrays.asList(connectionString, new LCPWithParams(addCProp(StringClass.text, LocalizedString.create(request, false))))), null, BaseUtils.add(params, actionLCP), context, toPropertyUsageList);
<<<<<<< InputStream inputStream = fileData.getInputStream(); ======= InputStream inputStream = new FileInputStream(file); ftpClient.changeWorkingDirectory(remoteFile); >>>>>>> InputStream inputStream = fileData.getInputStream(); ftpClient.changeWorkingDirectory(remoteFile);
<<<<<<< ======= checkFormsTable(oldDBStructure); >>>>>>> <<<<<<< ======= if(oldDBStructure.version < NavElementDBVersion) DataSession.recalculateTableClasses(reflectionLM.navigatorElementTable, sql, LM.baseClass); if(newDBStructure.version >= 28 && oldDBStructure.version < 28 && !oldDBStructure.isEmpty()) { startLogger.info("Migrating properties to actions data started"); synchronizePropertyEntities(sql); startLogger.info("Migrating properties to actions data ended"); } >>>>>>> <<<<<<< ======= // temporary for migration public void synchronizePropertyEntities(SQLSession sql) throws SQLException, SQLHandledException, ScriptingErrorLog.SemanticErrorException { synchronizePropertyEntities(true, sql); try { recalculateAndUpdateClassStat((CustomClass) reflectionLM.findClass("Action")); recalculateAndUpdateStat(reflectionLM.findTable("action"), null); try(DataSession session = createSession(sql)) { businessLogics.schedulerLM.copyAction.execute(session, getStack()); businessLogics.securityLM.copyAccess.execute(session, getStack()); apply(session); for(String tableName : new String[]{"action", "userRoleActionOrProperty", "userRoleAction", "userActionOrProperty", "userAction"}) { recalculateAndUpdateStat((tableName.equals("action")?reflectionLM:businessLogics.securityLM).findTable(tableName), null); } ALRUMap.forceRemoveAllLRU(1.0); // чтобы synchronizeActionEntities отработал } } catch (SQLException | SQLHandledException e) { throw Throwables.propagate(e); } } private boolean needsToBeSynchronized(Property property) { return property.isNamed() && (property instanceof ActionProperty || !((CalcProperty)property).isEmpty(AlgType.syncType)); } public void synchronizePropertyEntities(boolean actions, SQLSession sql) { startLogger.info("synchronize" + (actions ? "Action" : "Property") + "Entities collecting data started"); ImportField canonicalNamePropertyField = new ImportField(reflectionLM.propertyCanonicalNameValueClass); ImportField dbNamePropertyField = new ImportField(reflectionLM.propertySIDValueClass); ImportField captionPropertyField = new ImportField(reflectionLM.propertyCaptionValueClass); ImportField loggablePropertyField = new ImportField(reflectionLM.propertyLoggableValueClass); ImportField storedPropertyField = new ImportField(reflectionLM.propertyStoredValueClass); ImportField isSetNotNullPropertyField = new ImportField(reflectionLM.propertyIsSetNotNullValueClass); ImportField returnPropertyField = new ImportField(reflectionLM.propertyClassValueClass); ImportField classPropertyField = new ImportField(reflectionLM.propertyClassValueClass); ImportField complexityPropertyField = new ImportField(LongClass.instance); ImportField tableSIDPropertyField = new ImportField(reflectionLM.propertyTableValueClass); ImportField annotationPropertyField = new ImportField(reflectionLM.propertyTableValueClass); ImportField statsPropertyField = new ImportField(ValueExpr.COUNTCLASS); ConcreteCustomClass customClass = actions ? reflectionLM.action : reflectionLM.property; LCP objectByName = actions ? reflectionLM.actionCanonicalName : reflectionLM.propertyCanonicalName; LCP nameByObject = actions ? reflectionLM.canonicalNameAction : reflectionLM.canonicalNameProperty; ImportKey<?> keyProperty = new ImportKey(customClass, objectByName.getMapping(canonicalNamePropertyField)); try { List<List<Object>> dataProperty = new ArrayList<>(); for (Property property : businessLogics.getOrderProperties()) { if (needsToBeSynchronized(property)) { if((property instanceof ActionProperty) != actions) continue; String returnClass = ""; String classProperty = ""; String tableSID = ""; Long complexityProperty = null; try { classProperty = property.getClass().getSimpleName(); if(property instanceof CalcProperty) { CalcProperty calcProperty = (CalcProperty)property; complexityProperty = calcProperty.getComplexity(); if (calcProperty.mapTable != null) { tableSID = calcProperty.mapTable.table.getName(); } else { tableSID = ""; } } returnClass = property.getValueClass(ClassType.syncPolicy).getSID(); } catch (NullPointerException | ArrayIndexOutOfBoundsException ignored) { } dataProperty.add(asList(((ActionProperty)property).getCanonicalName(),(Object) property.getDBName(), property.caption.getSourceString(), property instanceof CalcProperty && ((CalcProperty)property).isLoggable() ? true : null, property instanceof CalcProperty && ((CalcProperty) property).isStored() ? true : null, property instanceof CalcProperty && ((CalcProperty) property).reflectionNotNull ? true : null, returnClass, classProperty, complexityProperty, tableSID, property.annotation, (Settings.get().isDisableSyncStatProps() ? (Integer) Stat.DEFAULT.getCount() : businessLogics.getStatsProperty(property)))); } } startLogger.info("synchronize" + (actions ? "Action" : "Property") + "Entities integration service started"); List<ImportProperty<?>> properties = new ArrayList<>(); properties.add(new ImportProperty(canonicalNamePropertyField, nameByObject.getMapping(keyProperty))); properties.add(new ImportProperty(dbNamePropertyField, reflectionLM.dbNameProperty.getMapping(keyProperty))); properties.add(new ImportProperty(captionPropertyField, reflectionLM.captionProperty.getMapping(keyProperty))); properties.add(new ImportProperty(loggablePropertyField, reflectionLM.loggableProperty.getMapping(keyProperty))); properties.add(new ImportProperty(storedPropertyField, reflectionLM.storedProperty.getMapping(keyProperty))); properties.add(new ImportProperty(isSetNotNullPropertyField, reflectionLM.isSetNotNullProperty.getMapping(keyProperty))); properties.add(new ImportProperty(returnPropertyField, reflectionLM.returnProperty.getMapping(keyProperty))); properties.add(new ImportProperty(classPropertyField, reflectionLM.classProperty.getMapping(keyProperty))); properties.add(new ImportProperty(complexityPropertyField, reflectionLM.complexityProperty.getMapping(keyProperty))); properties.add(new ImportProperty(tableSIDPropertyField, reflectionLM.tableSIDProperty.getMapping(keyProperty))); properties.add(new ImportProperty(annotationPropertyField, reflectionLM.annotationProperty.getMapping(keyProperty))); properties.add(new ImportProperty(statsPropertyField, reflectionLM.statsProperty.getMapping(keyProperty))); List<ImportDelete> deletes = new ArrayList<>(); deletes.add(new ImportDelete(keyProperty, LM.is(customClass).getMapping(keyProperty), false)); ImportTable table = new ImportTable(asList(canonicalNamePropertyField, dbNamePropertyField, captionPropertyField, loggablePropertyField, storedPropertyField, isSetNotNullPropertyField, returnPropertyField, classPropertyField, complexityPropertyField, tableSIDPropertyField, annotationPropertyField, statsPropertyField), dataProperty); try (DataSession session = createSession(sql)) { session.pushVolatileStats("RM_PE"); IntegrationService service = new IntegrationService(session, table, Collections.singletonList(keyProperty), properties, deletes); service.synchronize(true, false); session.popVolatileStats(); session.apply(businessLogics, getStack()); startLogger.info("synchronize" + (actions ? "Action" : "Property") + "Entities finished"); } } catch (Exception e) { throw Throwables.propagate(e); } } private void modifyNavigatorElementsClasses(SQLSession session) { try { Map<String, Long> oldIds = getOldIds(session); for (NavigatorElement ne : businessLogics.getNavigatorElements()) { if (!(ne instanceof NavigatorAction)) { CustomClass cls = getNavigatorFolderOrFormClass(ne); String canonicalName = ne.getCanonicalName(); if (cls != null) { Long oldId = oldIds.get(canonicalName); modifyNavigatorElementClass(session, canonicalName, cls, oldId); } } } } catch (SQLException | SQLHandledException e) { e.printStackTrace(); } } private void modifyNavigatorFormClasses() throws SQLException, SQLHandledException { try(DataSession session = createSession(OperationOwner.unknown)) { KeyExpr keyExpr = new KeyExpr("key"); session.changeClass(new ClassChange(keyExpr, keyExpr.isClass(businessLogics.reflectionLM.navigatorForm.getUpSet()), businessLogics.reflectionLM.navigatorAction)); session.apply(businessLogics, getStack()); } } private CustomClass getNavigatorFolderOrFormClass(NavigatorElement element) { if (element instanceof NavigatorFolder) { return businessLogics.findClass("Reflection.NavigatorFolder"); } else if (element instanceof NavigatorForm) { return businessLogics.findClass("Reflection.NavigatorForm"); } return null; } private void modifyNavigatorElementClass(SQLSession session, String canonicalName, CustomClass cls, Long oldId) throws SQLException, SQLHandledException { Long newId = modifyNETable(session, canonicalName, cls); if (!isFolder(cls)) { if (newId != null && oldId != null) { modifyRoleTable(session, newId, oldId); } else { System.out.println("Error updating role table, canonicalName: " + canonicalName); } } } private boolean isFolder(CustomClass cls) { return cls.getCanonicalName().equals("Reflection.NavigatorFolder"); } private Long modifyNETable(SQLSession session, String canonicalName, CustomClass cls) throws SQLException, SQLHandledException { SQLSyntax syntax = session.syntax; String tableName = syntax.getTableName("reflection_navigatorelement"); String classFieldName = syntax.getFieldName("system__class_reflection_navigatorelement"); String cnFieldName = syntax.getFieldName("reflection_canonicalname_navigatorelement"); String query; Long newId = null; if (isFolder(cls)) { query = "UPDATE " + tableName + " SET " + classFieldName + "=" + cls.ID + " WHERE " + cnFieldName + "='" + canonicalName + "'"; } else { newId = generateID(); query = "UPDATE " + tableName + " SET " + classFieldName + "=" + cls.ID + ", " + "key0=" + newId + " WHERE " + cnFieldName + "='" + canonicalName + "'"; } session.executeDML(query); return newId; } private Map<String, Long> getOldIds(SQLSession session) throws SQLException, SQLHandledException { SQLSyntax syntax = session.syntax; String tableName = syntax.getTableName("reflection_navigatorelement"); String cnFieldName = syntax.getFieldName("reflection_canonicalname_navigatorelement"); KeyField key = new KeyField("key0", LongClass.instance); PropertyField field = new PropertyField(cnFieldName, StringClass.getv(100)); ImRevMap<KeyField, String> keyMap = MapFact.singletonRev(key, "key0"); ImRevMap<PropertyField, String> propertyMap = MapFact.singletonRev(field, cnFieldName); ReadAllResultHandler<KeyField, PropertyField> mapResultHandler = new ReadAllResultHandler<>(); String query = "SELECT key0, " + cnFieldName + " FROM " + tableName; session.executeSelect(query, OperationOwner.unknown, StaticExecuteEnvironmentImpl.EMPTY, keyMap, keyMap.reverse().mapValues(Field.<KeyField>fnTypeGetter()), propertyMap, propertyMap.reverse().mapValues(Field.<PropertyField>fnTypeGetter()), mapResultHandler); ImOrderMap<ImMap<KeyField, Object>, ImMap<PropertyField, Object>> qresult = mapResultHandler.get(); Map<String, Long> result = new HashMap<>(); for (int i = 0; i < qresult.size(); ++i) { result.put((String)qresult.getValue(i).singleValue(), (Long) qresult.getKey(i).singleValue()); } return result; } private void modifyRoleTable(SQLSession session, long id, long oldId) throws SQLException, SQLHandledException { SQLSyntax syntax = session.syntax; String roleTableName = syntax.getTableName("security_userrolenavigatorelement"); String query = "UPDATE " + roleTableName + " SET key1=" + id + " WHERE key1 = " + oldId; session.executeDML(query); } private void checkFormsTable(OldDBStructure dbStruct) { if (!dbStruct.isEmpty()) { Table table = dbStruct.getTable("Reflection_form"); if (table == null) { throw new RuntimeException("Run 1.3.1 version first"); } } } >>>>>>> <<<<<<< private boolean fillIDs(Map<String, String> sIDChanges, Map<String, String> objectSIDChanges) throws SQLException, SQLHandledException { ======= private void fillIDs(Map<String, String> sIDChanges, Map<String, String> objectSIDChanges, boolean migrateObjectClassID) throws SQLException, SQLHandledException { >>>>>>> private void fillIDs(Map<String, String> sIDChanges, Map<String, String> objectSIDChanges) throws SQLException, SQLHandledException { <<<<<<< LM.baseClass.fillIDs(session, LM.staticCaption, LM.staticName, sIDChanges, objectSIDChanges); return session.apply(businessLogics, getStack()); ======= LM.baseClass.fillIDs(session, LM.staticCaption, LM.staticName, sIDChanges, objectSIDChanges, migrateObjectClassID); apply(session); >>>>>>> LM.baseClass.fillIDs(session, LM.staticCaption, LM.staticName, sIDChanges, objectSIDChanges); session.apply(businessLogics, getStack());
<<<<<<< if (paramClass != null && !SignatureMatcher.isClassesSoftCompatible(paramClass.getResolveSet(), signature.get(i))) { errLog.emitWrongPropertyParameterError(parser, paramName, paramClass.getParsedName(), signature.get(i).toString()); ======= if (paramClass != null && !isClassesSoftCompatible(paramClass.getResolveSet(), signature.get(i))) { errLog.emitWrongPropertyParameterError(parser, paramName, paramClass.toString(), signature.get(i).toString()); >>>>>>> if (paramClass != null && !SignatureMatcher.isClassesSoftCompatible(paramClass.getResolveSet(), signature.get(i))) { errLog.emitWrongPropertyParameterError(parser, paramName, paramClass.toString(), signature.get(i).toString()); <<<<<<< public void checkSessionPropertyParameter(LCPWithParams property) throws ScriptingErrorLog.SemanticErrorException { if (property.getLP() == null) { errLog.emitSessionOperatorParameterError(parser); } } ======= public void checkComparisonCompatibility(LCPWithParams leftProp, LCPWithParams rightProp, List<TypedParameter> context) throws ScriptingErrorLog.SemanticErrorException { if (rightProp != null) { ValueClass leftClass = getValueClass(leftProp, context); ValueClass rightClass = getValueClass(rightProp, context); if (leftClass != null && rightClass != null && !isClassesSoftCompatible(leftClass.getResolveSet(), rightClass.getResolveSet())) { errLog.emitRelationalOperatorClassCommpatibilityError(parser, leftClass.getParsedName(), rightClass.getParsedName()); } } } private ValueClass getValueClass(LCPWithParams prop, List<TypedParameter> context) { if (prop.getLP() == null) { return context.get(prop.usedParams.get(0)).cls; } else { return prop.getLP().property.getValueClass(ClassType.valuePolicy); } } >>>>>>> public void checkSessionPropertyParameter(LCPWithParams property) throws ScriptingErrorLog.SemanticErrorException { if (property.getLP() == null) { errLog.emitSessionOperatorParameterError(parser); } } public void checkComparisonCompatibility(LCPWithParams leftProp, LCPWithParams rightProp, List<TypedParameter> context) throws ScriptingErrorLog.SemanticErrorException { if (rightProp != null) { ValueClass leftClass = getValueClass(leftProp, context); ValueClass rightClass = getValueClass(rightProp, context); if (leftClass != null && rightClass != null && !isClassesSoftCompatible(leftClass.getResolveSet(), rightClass.getResolveSet())) { errLog.emitRelationalOperatorClassCommpatibilityError(parser, leftClass.getParsedName(), rightClass.getParsedName()); } } } private ValueClass getValueClass(LCPWithParams prop, List<TypedParameter> context) { if (prop.getLP() == null) { return context.get(prop.usedParams.get(0)).cls; } else { return prop.getLP().property.getValueClass(ClassType.valuePolicy); } }
<<<<<<< public ImMap<ObjectInstance, DataObject> updateKeys(SQLSession sql, QueryEnvironment env, final Modifier modifier, IncrementChangeProps environmentIncrement, ExecutionEnvironment execEnv, BaseClass baseClass, boolean hidden, final boolean refresh, MFormChanges result, MSet<PropertyDrawInstance> mChangedDrawProps, Result<ChangedData> changedProps, ReallyChanged reallyChanged) throws SQLException, SQLHandledException { ======= public ImMap<ObjectInstance, DataObject> updateKeys(SQLSession sql, QueryEnvironment env, final FormInstance.FormModifier modifier, IncrementChangeProps environmentIncrement, ExecutionEnvironment execEnv, BaseClass baseClass, boolean hidden, final boolean refresh, MFormChanges result, Result<ChangedData> changedProps, ReallyChanged reallyChanged) throws SQLException, SQLHandledException { if (refresh || (updated & UPDATED_CLASSVIEW) != 0) { result.classViews.exclAdd(this, curClassView); } >>>>>>> public ImMap<ObjectInstance, DataObject> updateKeys(SQLSession sql, QueryEnvironment env, final FormInstance.FormModifier modifier, IncrementChangeProps environmentIncrement, ExecutionEnvironment execEnv, BaseClass baseClass, boolean hidden, final boolean refresh, MFormChanges result, MSet<PropertyDrawInstance> mChangedDrawProps, Result<ChangedData> changedProps, ReallyChanged reallyChanged) throws SQLException, SQLHandledException {
<<<<<<< private String getRecognitionErrorText(ScriptParser parser, String errorType, String msg, RecognitionException e) { String path = parser.getCurrentScriptPath(moduleName, e.line, "\n\t\t\t"); ======= public String getRecognitionErrorText(ScriptParser parser, String errorType, String msg, RecognitionException e) { String path = parser.getCurrentScriptPath(moduleId, e.line, "\n\t\t\t"); >>>>>>> private String getRecognitionErrorText(ScriptParser parser, String errorType, String msg, RecognitionException e) { String path = parser.getCurrentScriptPath(moduleId, e.line, "\n\t\t\t");
<<<<<<< } if (readResult.errorCode == 0) { targetProp.change(readResult.fileBytes, context); ======= if (readResult.errorCode == 0) { if(isDynamicFormatFileClass) targetProp.change((FileData)readResult.fileBytes, context); else targetProp.change((RawFileData)readResult.fileBytes, context); ReadUtils.postProcessFile(sourcePath, readResult.type, readResult.filePath, movePath, delete); } >>>>>>> } if (readResult.errorCode == 0) { if(isDynamicFormatFileClass) targetProp.change((FileData)readResult.fileBytes, context); else targetProp.change((RawFileData)readResult.fileBytes, context);
<<<<<<< this.cameraOptions.flight.mousePressed(mc, this.cameraOptions.flight.x + 1, this.cameraOptions.flight.y + 1); ======= this.cameraOptions.flight.mousePressed(this.mc, this.cameraOptions.flight.xPosition + 1, this.cameraOptions.flight.yPosition + 1); >>>>>>> this.cameraOptions.flight.mousePressed(this.mc, this.cameraOptions.flight.x + 1, this.cameraOptions.flight.y + 1); <<<<<<< this.cameraOptions.sync.mousePressed(mc, this.cameraOptions.sync.x + 1, this.cameraOptions.sync.y + 1); ======= this.cameraOptions.sync.mousePressed(this.mc, this.cameraOptions.sync.xPosition + 1, this.cameraOptions.sync.yPosition + 1); >>>>>>> this.cameraOptions.sync.mousePressed(this.mc, this.cameraOptions.sync.x + 1, this.cameraOptions.sync.y + 1); <<<<<<< /* Display flight speed */ if (this.flight.enabled) { String speed = String.format(this.stringSpeed + ": %.1f", this.flight.speed); int width = this.fontRenderer.getStringWidth(speed); int x = this.width - 10 - width; int y = this.height - 30; Gui.drawRect(x - 2, y - 2, x + width + 2, y + 9, 0x88000000); this.fontRenderer.drawStringWithShadow(speed, x, y, 0xffffff); } if (running) { this.scrub.value = (int) this.runner.ticks; this.scrub.value = MathHelper.clamp(this.scrub.value, this.scrub.min, this.scrub.max); this.frame.setValue(this.scrub.value); } if (!running && this.playing) { this.updatePlauseButton(); this.scrub.setValueFromScrub(0); ClientProxy.EVENT_BUS.post(new CameraEditorPlaybackStateEvent(false, this.scrub.value)); this.playing = false; } ======= >>>>>>>
<<<<<<< package lsfusion.gwt.form.server.form.handlers; import lsfusion.gwt.base.server.dispatch.BaseFormBoundActionHandler; import lsfusion.gwt.form.server.FormDispatchServlet; import lsfusion.gwt.form.server.FormSessionManager; import lsfusion.gwt.form.server.FormSessionObject; import lsfusion.interop.RemoteLogicsInterface; import net.customware.gwt.dispatch.shared.Action; import net.customware.gwt.dispatch.shared.Result; public abstract class FormActionHandler<A extends Action<R>, R extends Result> extends LoggableActionHandler<A, R, RemoteLogicsInterface> implements BaseFormBoundActionHandler { public FormActionHandler(FormDispatchServlet servlet) { super(servlet); } public FormSessionManager getFormSessionManager() { return ((FormDispatchServlet)servlet).getFormSessionManager(); } protected final static int defaultLastReceivedRequestIndex = -2; /** * Ищет форму в сессии с name=formSessionID * * Если форма не найдена, то выбрасывает RuntimeException * @throws RuntimeException */ public FormSessionObject getFormSessionObject(String formSessionID) throws RuntimeException { return getFormSessionManager().getFormSessionObject(formSessionID); } public FormSessionObject getFormSessionObjectOrNull(String formSessionID) throws RuntimeException { return getFormSessionManager().getFormSessionObjectOrNull(formSessionID); } } ======= package lsfusion.gwt.form.server.form.handlers; import lsfusion.gwt.base.server.dispatch.BaseFormBoundActionHandler; import lsfusion.gwt.form.server.LSFusionDispatchServlet; import lsfusion.gwt.form.server.FormSessionManager; import lsfusion.gwt.form.server.FormSessionObject; import lsfusion.interop.RemoteLogicsInterface; import net.customware.gwt.dispatch.shared.Action; import net.customware.gwt.dispatch.shared.Result; public abstract class FormActionHandler<A extends Action<R>, R extends Result> extends LoggableActionHandler<A, R, RemoteLogicsInterface> implements BaseFormBoundActionHandler { public FormActionHandler(LSFusionDispatchServlet servlet) { super(servlet); } public FormSessionManager getFormSessionManager() { return ((LSFusionDispatchServlet)servlet).getFormSessionManager(); } protected final static int defaultLastReceivedRequestIndex = -1; /** * Ищет форму в сессии с name=formSessionID * * Если форма не найдена, то выбрасывает RuntimeException * @throws RuntimeException */ public FormSessionObject getFormSessionObject(String formSessionID) throws RuntimeException { return getFormSessionManager().getFormSessionObject(formSessionID); } public FormSessionObject getFormSessionObjectOrNull(String formSessionID) throws RuntimeException { return getFormSessionManager().getFormSessionObjectOrNull(formSessionID); } } >>>>>>> package lsfusion.gwt.form.server.form.handlers; import lsfusion.gwt.base.server.dispatch.BaseFormBoundActionHandler; import lsfusion.gwt.form.server.LSFusionDispatchServlet; import lsfusion.gwt.form.server.FormSessionManager; import lsfusion.gwt.form.server.FormSessionObject; import lsfusion.interop.RemoteLogicsInterface; import net.customware.gwt.dispatch.shared.Action; import net.customware.gwt.dispatch.shared.Result; public abstract class FormActionHandler<A extends Action<R>, R extends Result> extends LoggableActionHandler<A, R, RemoteLogicsInterface> implements BaseFormBoundActionHandler { public FormActionHandler(LSFusionDispatchServlet servlet) { super(servlet); } public FormSessionManager getFormSessionManager() { return ((LSFusionDispatchServlet)servlet).getFormSessionManager(); } protected final static int defaultLastReceivedRequestIndex = -2; /** * Ищет форму в сессии с name=formSessionID * * Если форма не найдена, то выбрасывает RuntimeException * @throws RuntimeException */ public FormSessionObject getFormSessionObject(String formSessionID) throws RuntimeException { return getFormSessionManager().getFormSessionObject(formSessionID); } public FormSessionObject getFormSessionObjectOrNull(String formSessionID) throws RuntimeException { return getFormSessionManager().getFormSessionObjectOrNull(formSessionID); } }