/*
(non-Javadoc)

@see
de.tudarmstadt.ukp.kulessa.delta.consumers.sql.codec.SQLEncodrInterface
#encodeTask(de.tudarmstadt.ukp.kulessa.delta.data.tasks.Task)
426762
public SQLEncoding[] encodeTask(final Task<Diff> task)
		throws ConfigurationException, UnsupportedEncodingException,
		DecodingException, EncodingException, SQLConsumerException
	{

		SQLEncoding[] encoding = super.encodeTask(task);

		for (SQLEncoding sql : encoding) {
			this.encodedSQLSize += sql.byteSize();
		}

		return encoding;
	}
1224140
public void setTaskKeywords(java.util.Collection<String> taskKeywords) {
        if (taskKeywords == null) {
            this.taskKeywords = null;
            return;
        }

        this.taskKeywords = new java.util.ArrayList<String>(taskKeywords);
    }
502455
public synchronized void enqueue(DownloadTask task) {
        taskList.add(task);
        Collections.sort(taskList);

        if (!paused && !looping) {
            looping = true;
            startNewLooper();
        }
    }
377499
public void callExecuteTaskAsync(SimpleClientResponseAdapter.Callback cb, byte[] params) throws IOException {
        final String procedureName = "@ExecuteTask";
        Config procedureConfig = SystemProcedureCatalog.listing.get(procedureName);
        Procedure proc = procedureConfig.asCatalogProcedure();
        StoredProcedureInvocation spi = new StoredProcedureInvocation();
        spi.setProcName(procedureName);
        spi.setParams(params);
        spi.setClientHandle(m_executeTaskAdpater.registerCallback(cb));
        if (spi.getSerializedParams() == null) {
            spi = MiscUtils.roundTripForCL(spi);
        }
        synchronized (m_executeTaskAdpater) {
            m_dispatcher.createTransaction(m_executeTaskAdpater.connectionId(), spi,
                    proc.getReadonly(), proc.getSinglepartition(), proc.getEverysite(),
                    new int[] { 0 } /* Can provide anything for multi-part */,
                    spi.getSerializedSize(), System.nanoTime());
        }
    }
684753
private void loadDataAsynchronously(
            @NonNull final Task<DataType, KeyType, ViewType, ParamType> task) {
        threadPool.submit(new Runnable() {

            @Override
            public void run() {
                if (!isCanceled()) {
                    while (!notifyOnLoad(task.key, task.params)) {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            break;
                        }
                    }

                    task.result = loadData(task);
                    Message message = Message.obtain();
                    message.obj = task;
                    sendMessage(message);
                }
            }

        });
    }
489069
private void processTasks() throws SQLException
   {
      //
      // Yes... we could probably read this in one query in the right order
      // using a CTE... but life's too short.
      //
      List<Row> rows = getRows("select * from zscheduleitem where zproject=? and zparentactivity_ is null and z_ent=? order by zorderinparentactivity", m_projectID, m_entityMap.get("Activity"));
      for (Row row : rows)
      {
         Task task = m_project.addTask();
         populateTask(row, task);
         processChildTasks(task);
      }
   }
44915
public void setTasks(java.util.Collection<TaskListEntry> tasks) {
        if (tasks == null) {
            this.tasks = null;
            return;
        }

        this.tasks = new java.util.ArrayList<TaskListEntry>(tasks);
    }
13151
private void verify(final Task<Diff> task, final Diff decodedDiff,
			final Diff originalDiff)
		throws SQLConsumerException
	{

		String orig = originalDiff.toString();
		String deco = decodedDiff.toString();

		boolean notEqual = !orig.equals(deco);

		if (notEqual && MODE_SURROGATES == SurrogateModes.REPLACE) {

			char[] origDiff = orig.toCharArray();

			// TODO: test
			if (Surrogates.scan(origDiff)) {

				String repDiff = new String(Surrogates.replace(origDiff));
				notEqual = !repDiff.equals(deco);
			}
		}

		if (notEqual) {

			if (MODE_DEBUG_OUTPUT_ACTIVATED) {

				try {
					// System.out.println("DEBUG\t" + task.toString());

					WikipediaXMLWriter writer = new WikipediaXMLWriter(
							LOGGING_PATH_DIFFTOOL + LOGGING_PATH_DEBUG
									+ task.getHeader().getArticleName()
									+ ".dbg");

					switch (task.getTaskType()) {
					case TASK_FULL:
					case TASK_PARTIAL_FIRST:
						writer.writeDiff(task);
						break;

					case TASK_PARTIAL:
					case TASK_PARTIAL_LAST: {

						int revCount = originalDiff.getRevisionCounter();
						Diff d;
						boolean fullRev = false;

						for (int diffCount = 0; !fullRev
								&& diffCount < originalDiff.size(); diffCount++) {

							d = task.get(diffCount);
							if (d.getRevisionCounter() <= revCount
									&& d.isFullRevision()) {
								fullRev = true;
								writer.writeDiff(task, diffCount);
							}
						}

						if (!fullRev) {
							writer.writeDiffFile(task);
						}

					}
						break;
					default:
						throw new IOException("Unknown TaskType");
						// TODO: Debug output
					}

					writer.close();
				}
				catch (IOException e) {
					ConsumerLogMessages.logException(logger, e);
				}
			}

			throw ErrorFactory
					.createSQLConsumerException(
							ErrorKeys.DIFFTOOL_SQLCONSUMER_ENCODING_VERIFICATION_FAILED,
							"Redecoding of "
									+ task.getHeader().getArticleName()
									+ " failed at revision "
									+ originalDiff.getRevisionCounter() + ".");
		}
	}
167155
private void processHyperlinkData(Task task, byte[] data)
   {
      if (data != null)
      {
         int offset = 12;
         String hyperlink;
         String address;
         String subaddress;

         offset += 12;
         hyperlink = MPPUtility.getUnicodeString(data, offset);
         offset += ((hyperlink.length() + 1) * 2);

         offset += 12;
         address = MPPUtility.getUnicodeString(data, offset);
         offset += ((address.length() + 1) * 2);

         offset += 12;
         subaddress = MPPUtility.getUnicodeString(data, offset);

         task.setHyperlink(hyperlink);
         task.setHyperlinkAddress(address);
         task.setHyperlinkSubAddress(subaddress);
      }
   }
347700
private void writeTasks(List<Task> tasks) throws IOException
   {
      for (Task task : tasks)
      {
         writeTask(task);
         writeTasks(task.getChildTasks());
      }
   }
907789
public Long createTask(String taskName, String data) {
		return tedDriverImpl.createTask(taskName, data, null, null, null);
	}
1048125
private Project.Tasks.Task writeTask(Task mpx)
   {
      Project.Tasks.Task xml = m_factory.createProjectTasksTask();

      xml.setActive(Boolean.valueOf(mpx.getActive()));
      xml.setActualCost(DatatypeConverter.printCurrency(mpx.getActualCost()));
      xml.setActualDuration(DatatypeConverter.printDuration(this, mpx.getActualDuration()));
      xml.setActualFinish(mpx.getActualFinish());
      xml.setActualOvertimeCost(DatatypeConverter.printCurrency(mpx.getActualOvertimeCost()));
      xml.setActualOvertimeWork(DatatypeConverter.printDuration(this, mpx.getActualOvertimeWork()));
      xml.setActualOvertimeWorkProtected(DatatypeConverter.printDuration(this, mpx.getActualOvertimeWorkProtected()));
      xml.setActualStart(mpx.getActualStart());
      xml.setActualWork(DatatypeConverter.printDuration(this, mpx.getActualWork()));
      xml.setActualWorkProtected(DatatypeConverter.printDuration(this, mpx.getActualWorkProtected()));
      xml.setACWP(DatatypeConverter.printCurrency(mpx.getACWP()));
      xml.setBCWP(DatatypeConverter.printCurrency(mpx.getBCWP()));
      xml.setBCWS(DatatypeConverter.printCurrency(mpx.getBCWS()));
      xml.setCalendarUID(getTaskCalendarID(mpx));
      xml.setConstraintDate(mpx.getConstraintDate());
      xml.setConstraintType(DatatypeConverter.printConstraintType(mpx.getConstraintType()));
      xml.setContact(mpx.getContact());
      xml.setCost(DatatypeConverter.printCurrency(mpx.getCost()));
      xml.setCreateDate(mpx.getCreateDate());
      xml.setCritical(Boolean.valueOf(mpx.getCritical()));
      xml.setCV(DatatypeConverter.printCurrency(mpx.getCV()));
      xml.setDeadline(mpx.getDeadline());
      xml.setDuration(DatatypeConverter.printDurationMandatory(this, mpx.getDuration()));
      xml.setDurationText(mpx.getDurationText());
      xml.setDurationFormat(DatatypeConverter.printDurationTimeUnits(mpx.getDuration(), mpx.getEstimated()));
      xml.setEarlyFinish(mpx.getEarlyFinish());
      xml.setEarlyStart(mpx.getEarlyStart());
      xml.setEarnedValueMethod(DatatypeConverter.printEarnedValueMethod(mpx.getEarnedValueMethod()));
      xml.setEffortDriven(Boolean.valueOf(mpx.getEffortDriven()));
      xml.setEstimated(Boolean.valueOf(mpx.getEstimated()));
      xml.setExternalTask(Boolean.valueOf(mpx.getExternalTask()));
      xml.setExternalTaskProject(mpx.getProject());
      xml.setFinish(mpx.getFinish());
      xml.setFinishSlack(DatatypeConverter.printDurationInIntegerTenthsOfMinutes(mpx.getFinishSlack()));
      xml.setFinishText(mpx.getFinishText());
      xml.setFinishVariance(DatatypeConverter.printDurationInIntegerThousandthsOfMinutes(mpx.getFinishVariance()));
      xml.setFixedCost(DatatypeConverter.printCurrency(mpx.getFixedCost()));

      AccrueType fixedCostAccrual = mpx.getFixedCostAccrual();
      if (fixedCostAccrual == null)
      {
         fixedCostAccrual = AccrueType.PRORATED;
      }
      xml.setFixedCostAccrual(fixedCostAccrual);
      xml.setFreeSlack(DatatypeConverter.printDurationInIntegerTenthsOfMinutes(mpx.getFreeSlack()));
      xml.setGUID(mpx.getGUID());
      xml.setHideBar(Boolean.valueOf(mpx.getHideBar()));
      xml.setIsNull(Boolean.valueOf(mpx.getNull()));
      xml.setIsSubproject(Boolean.valueOf(mpx.getSubProject() != null));
      xml.setIsSubprojectReadOnly(Boolean.valueOf(mpx.getSubprojectReadOnly()));
      xml.setHyperlink(mpx.getHyperlink());
      xml.setHyperlinkAddress(mpx.getHyperlinkAddress());
      xml.setHyperlinkSubAddress(mpx.getHyperlinkSubAddress());
      xml.setID(NumberHelper.getBigInteger(mpx.getID()));
      xml.setIgnoreResourceCalendar(Boolean.valueOf(mpx.getIgnoreResourceCalendar()));
      xml.setLateFinish(mpx.getLateFinish());
      xml.setLateStart(mpx.getLateStart());
      xml.setLevelAssignments(Boolean.valueOf(mpx.getLevelAssignments()));
      xml.setLevelingCanSplit(Boolean.valueOf(mpx.getLevelingCanSplit()));

      if (mpx.getLevelingDelay() != null)
      {
         Duration levelingDelay = mpx.getLevelingDelay();
         double tenthMinutes = 10.0 * Duration.convertUnits(levelingDelay.getDuration(), levelingDelay.getUnits(), TimeUnit.MINUTES, m_projectFile.getProjectProperties()).getDuration();
         xml.setLevelingDelay(BigInteger.valueOf((long) tenthMinutes));
         xml.setLevelingDelayFormat(DatatypeConverter.printDurationTimeUnits(levelingDelay, false));
      }

      xml.setManual(Boolean.valueOf(mpx.getTaskMode() == TaskMode.MANUALLY_SCHEDULED));

      if (mpx.getTaskMode() == TaskMode.MANUALLY_SCHEDULED)
      {
         xml.setManualDuration(DatatypeConverter.printDuration(this, mpx.getDuration()));
         xml.setManualFinish(mpx.getFinish());
         xml.setManualStart(mpx.getStart());
      }

      xml.setMilestone(Boolean.valueOf(mpx.getMilestone()));
      xml.setName(mpx.getName());

      if (!mpx.getNotes().isEmpty())
      {
         xml.setNotes(mpx.getNotes());
      }

      xml.setOutlineLevel(NumberHelper.getBigInteger(mpx.getOutlineLevel()));
      xml.setOutlineNumber(mpx.getOutlineNumber());
      xml.setOverAllocated(Boolean.valueOf(mpx.getOverAllocated()));
      xml.setOvertimeCost(DatatypeConverter.printCurrency(mpx.getOvertimeCost()));
      xml.setOvertimeWork(DatatypeConverter.printDuration(this, mpx.getOvertimeWork()));
      xml.setPercentComplete(NumberHelper.getBigInteger(mpx.getPercentageComplete()));
      xml.setPercentWorkComplete(NumberHelper.getBigInteger(mpx.getPercentageWorkComplete()));
      xml.setPhysicalPercentComplete(NumberHelper.getBigInteger(mpx.getPhysicalPercentComplete()));
      xml.setPriority(DatatypeConverter.printPriority(mpx.getPriority()));
      xml.setRecurring(Boolean.valueOf(mpx.getRecurring()));
      xml.setRegularWork(DatatypeConverter.printDuration(this, mpx.getRegularWork()));
      xml.setRemainingCost(DatatypeConverter.printCurrency(mpx.getRemainingCost()));

      if (mpx.getRemainingDuration() == null)
      {
         Duration duration = mpx.getDuration();

         if (duration != null)
         {
            double amount = duration.getDuration();
            amount -= ((amount * NumberHelper.getDouble(mpx.getPercentageComplete())) / 100);
            xml.setRemainingDuration(DatatypeConverter.printDuration(this, Duration.getInstance(amount, duration.getUnits())));
         }
      }
      else
      {
         xml.setRemainingDuration(DatatypeConverter.printDuration(this, mpx.getRemainingDuration()));
      }

      xml.setRemainingOvertimeCost(DatatypeConverter.printCurrency(mpx.getRemainingOvertimeCost()));
      xml.setRemainingOvertimeWork(DatatypeConverter.printDuration(this, mpx.getRemainingOvertimeWork()));
      xml.setRemainingWork(DatatypeConverter.printDuration(this, mpx.getRemainingWork()));
      xml.setResume(mpx.getResume());
      xml.setResumeValid(Boolean.valueOf(mpx.getResumeValid()));
      xml.setRollup(Boolean.valueOf(mpx.getRollup()));
      xml.setStart(mpx.getStart());
      xml.setStartSlack(DatatypeConverter.printDurationInIntegerTenthsOfMinutes(mpx.getStartSlack()));
      xml.setStartText(mpx.getStartText());
      xml.setStartVariance(DatatypeConverter.printDurationInIntegerThousandthsOfMinutes(mpx.getStartVariance()));
      xml.setStop(mpx.getStop());
      xml.setSubprojectName(mpx.getSubprojectName());
      xml.setSummary(Boolean.valueOf(mpx.hasChildTasks()));
      xml.setTotalSlack(DatatypeConverter.printDurationInIntegerTenthsOfMinutes(mpx.getTotalSlack()));
      xml.setType(mpx.getType());
      xml.setUID(mpx.getUniqueID());
      xml.setWBS(mpx.getWBS());
      xml.setWBSLevel(mpx.getWBSLevel());
      xml.setWork(DatatypeConverter.printDuration(this, mpx.getWork()));
      xml.setWorkVariance(DatatypeConverter.printDurationInDecimalThousandthsOfMinutes(mpx.getWorkVariance()));

      if (mpx.getTaskMode() == TaskMode.MANUALLY_SCHEDULED)
      {
         xml.setManualDuration(DatatypeConverter.printDuration(this, mpx.getManualDuration()));
      }

      writePredecessors(xml, mpx);

      writeTaskExtendedAttributes(xml, mpx);

      writeTaskBaselines(xml, mpx);

      return (xml);
   }
119702
public RemoteTask createRemoteTask(Map<String, Object> properties) throws RemoteException
    {
        try {
            return new TaskProxy(this, properties);
        } catch (RemoteException e) {
            if ((m_strBaseServletPath != null) && (m_strBaseServletPath.length() > 0))
            {
                try {
                    URL url = new URL(m_strBaseServletPath);
                    String path = url.getPath();
                    if (path.length() > 0)
                        if (m_strBaseServletPath.endsWith(path))
                    {
                        m_strBaseServletPath = m_strBaseServletPath.substring(0, m_strBaseServletPath.length() - path.length());
                        return new TaskProxy(this, properties);
                    }
                } catch (MalformedURLException e1) {
                    // Throw original error if bad URL
                }
            }
            throw e;
        }
    }
399175
public void addTaskProperties(Task task)
    {
    	if (task == null)
    		return;
        this.put(TrxMessageHeader.USER_ID, task.getProperty(DBParams.USER_ID));
//?         BaseDatabase.addDBProperties(m_mapMessageHeader, task, null);	// Note: m_mapMessageHeader is guaranteed not null by previous call.
    }
114103
public String performTask(String taskParameters) {
        GetSignedCookiesUrlTaskParameters taskParams =
            GetSignedCookiesUrlTaskParameters.deserialize(taskParameters);

        String spaceId = taskParams.getSpaceId();
        String ipAddress = taskParams.getIpAddress();
        int minutesToExpire = taskParams.getMinutesToExpire();
        if (minutesToExpire <= 0) {
            minutesToExpire = DEFAULT_MINUTES_TO_EXPIRE;
        }
        String redirectUrl = taskParams.getRedirectUrl();

        log.info("Performing " + TASK_NAME + " task with parameters: spaceId=" + spaceId +
                 ", minutesToExpire=" + minutesToExpire + ", ipAddress=" + ipAddress +
                 ", redirectUrl=" + redirectUrl);

        // Will throw if bucket does not exist
        String bucketName = unwrappedS3Provider.getBucketName(spaceId);

        // Ensure that streaming service is on
        checkThatStreamingServiceIsEnabled(spaceId, TASK_NAME);

        // Retrieve the existing distribution for the given space
        DistributionSummary existingDist = getExistingDistribution(bucketName);
        if (null == existingDist) {
            throw new UnsupportedTaskException(TASK_NAME,
                                               "The " + TASK_NAME + " task can only be used after a space " +
                                               "has been configured to enable secure streaming. Use " +
                                               StorageTaskConstants.ENABLE_STREAMING_TASK_NAME +
                                               " to enable secure streaming on this space.");
        }
        String domainName = existingDist.getDomainName();

        // Define expiration date/time
        Calendar expireCalendar = Calendar.getInstance();
        expireCalendar.add(Calendar.MINUTE, minutesToExpire);

        Map<String, String> signedCookies = new HashMap<>();
        try {
            File cfKeyPathFile = getCfKeyPathFile(this.cfKeyPath);

            // Generate signed cookies
            CloudFrontCookieSigner.CookiesForCustomPolicy cookies =
                CloudFrontCookieSigner.getCookiesForCustomPolicy(
                    SignerUtils.Protocol.https,
                    domainName,
                    cfKeyPathFile,
                    "*",
                    cfKeyId,
                    expireCalendar.getTime(),
                    null,
                    ipAddress);

            signedCookies.put(cookies.getPolicy().getKey(), cookies.getPolicy().getValue());
            signedCookies.put(cookies.getSignature().getKey(), cookies.getSignature().getValue());
            signedCookies.put(cookies.getKeyPairId().getKey(), cookies.getKeyPairId().getValue());
        } catch (InvalidKeySpecException | IOException e) {
            throw new RuntimeException("Error encountered attempting to create signed cookies in task " +
                                       TASK_NAME + ": " + e.getMessage(), e);
        }

        String token = storeCookies(signedCookies, domainName, redirectUrl);

        GetSignedCookiesUrlTaskResult taskResult = new GetSignedCookiesUrlTaskResult();
        taskResult.setSignedCookiesUrl("https://" + domainName + "/cookies?token=" + token);

        String toReturn = taskResult.serialize();
        log.info("Result of " + TASK_NAME + " task: " + toReturn);
        return toReturn;
    }
1147597
public void enqueue(BaseDownloadTask task) {
        final DownloadTaskAdapter downloadTaskAdapter = (DownloadTaskAdapter) task;
        downloadTaskAdapter.assembleDownloadTask();
        FileDownloadList.getImpl().addIndependentTask(downloadTaskAdapter);
        serialQueue.enqueue(downloadTaskAdapter.getDownloadTask());
        listenerManager.addAutoRemoveListenersWhenTaskEnd(downloadTaskAdapter.getId());
        listenerManager.attachListener(downloadTaskAdapter.getDownloadTask(),
                downloadTaskAdapter.getCompatListener());
    }
1291115
protected long createTaskInternal(final String name, final String channel, final String data, final String key1, final String key2, final Long batchId, int postponeSec, TedStatus status) {
		final String sqlLogId = "create_task";
		if (status == null)
			status = TedStatus.NEW;
		String nextts = (status == TedStatus.NEW ? dbType.sql.now() + " + " + dbType.sql.intervalSeconds(postponeSec) : "null");

		String sql = " insert into tedtask (taskId, `system`, name, channel, bno, status, createTs, nextTs, retries, data, key1, key2, batchId)" +
				" values(null, '$sys', ?, ?, null, '$status', $now, $nextts, 0, ?, ?, ?, ?)" +
				" ";
		sql = sql.replace("$nextTaskId", dbType.sql.sequenceSql("SEQ_TEDTASK_ID"));
		sql = sql.replace("$now", dbType.sql.now());
		sql = sql.replace("$sys", thisSystem);
		sql = sql.replace("$nextts", nextts);
		sql = sql.replace("$status", status.toString());

		final String finalSql = sql;
		Long taskId = JdbcSelectTed.runInConn(dataSource, new ExecInConn<Long>() {
			@Override
			public Long execute(Connection connection) throws SQLException {
				int res = JdbcSelectTedImpl.executeUpdate(connection, finalSql, asList(
						sqlParam(name, JetJdbcParamType.STRING),
						sqlParam(channel, JetJdbcParamType.STRING),
						sqlParam(data, JetJdbcParamType.STRING),
						sqlParam(key1, JetJdbcParamType.STRING),
						sqlParam(key2, JetJdbcParamType.STRING),
						sqlParam(batchId, JetJdbcParamType.LONG)
				));
				if (res != 1)
					throw new IllegalStateException("expected 1 insert");
				String sql = "select last_insert_id()";
				return JdbcSelectTedImpl.selectSingleLong(connection, sql, Collections.<SqlParam>emptyList());
			}
		});

		logger.trace("Task {} {} created successfully. ", name, taskId);
		return taskId;

	}