use of jnc.platform.win32.Handle in project killbill by killbill.
the class DefaultUserDao method updateRoleDefinition.
@Override
public void updateRoleDefinition(final String role, final List<String> permissions, final String createdBy) throws SecurityApiException {
final DateTime createdDate = clock.getUTCNow();
inTransactionWithExceptionHandling(new TransactionCallback<Void>() {
@Override
public Void inTransaction(final Handle handle, final TransactionStatus status) throws Exception {
final RolesPermissionsSqlDao rolesPermissionsSqlDao = handle.attach(RolesPermissionsSqlDao.class);
final List<RolesPermissionsModelDao> existingPermissions = rolesPermissionsSqlDao.getByRoleName(role);
// A empty list of permissions means we should remove all current permissions
final Iterable<RolesPermissionsModelDao> toBeDeleted = existingPermissions.isEmpty() ? existingPermissions : Iterables.filter(existingPermissions, new Predicate<RolesPermissionsModelDao>() {
@Override
public boolean apply(final RolesPermissionsModelDao input) {
return !permissions.contains(input.getPermission());
}
});
final Iterable<String> toBeAdded = Iterables.filter(permissions, new Predicate<String>() {
@Override
public boolean apply(final String input) {
for (RolesPermissionsModelDao e : existingPermissions) {
if (e.getPermission().equals(input)) {
return false;
}
}
return true;
}
});
for (RolesPermissionsModelDao d : toBeDeleted) {
rolesPermissionsSqlDao.unactiveEvent(d.getRecordId(), createdDate, createdBy);
}
for (final String permission : toBeAdded) {
rolesPermissionsSqlDao.create(new RolesPermissionsModelDao(role, permission, createdDate, createdBy));
}
return null;
}
});
}
use of jnc.platform.win32.Handle in project killbill by killbill.
the class BaseIdCacheLoader method compute.
@Override
public V compute(final String key, final CacheLoaderArgument cacheLoaderArgument) {
final String rawKey;
if (getCacheType().isKeyPrefixedWithTableName()) {
final String[] parts = key.split(CacheControllerDispatcher.CACHE_KEY_SEPARATOR);
rawKey = parts[1];
} else {
rawKey = key;
}
final ObjectType objectType = cacheLoaderArgument.getObjectType();
final Handle handle = cacheLoaderArgument.getHandle();
return doRetrieveOperation(rawKey, objectType, handle);
}
use of jnc.platform.win32.Handle in project killbill by killbill.
the class DatabaseExportDao method exportDataForAccountAndTable.
private void exportDataForAccountAndTable(final DatabaseExportOutputStream out, final List<ColumnInfo> columnsForTable, final InternalTenantContext context) {
TableType tableType = TableType.OTHER;
final String tableName = columnsForTable.get(0).getTableName();
// Ignore casing (for H2)
if (TableName.ACCOUNT.getTableName().equalsIgnoreCase(tableName)) {
tableType = TableType.KB_ACCOUNT;
} else if (TableName.ACCOUNT_HISTORY.getTableName().equalsIgnoreCase(tableName)) {
tableType = TableType.KB_ACCOUNT_HISTORY;
}
boolean firstColumn = true;
final StringBuilder queryBuilder = new StringBuilder("select ");
for (final ColumnInfo column : columnsForTable) {
if (!firstColumn) {
queryBuilder.append(", ");
} else {
firstColumn = false;
}
queryBuilder.append(column.getColumnName());
if (tableType == TableType.OTHER) {
// Ignore casing (for H2)
if (column.getColumnName().equalsIgnoreCase(TableType.KB_PER_ACCOUNT.getAccountRecordIdColumnName())) {
tableType = TableType.KB_PER_ACCOUNT;
} else if (column.getColumnName().equalsIgnoreCase(TableType.NOTIFICATION.getAccountRecordIdColumnName())) {
tableType = TableType.NOTIFICATION;
}
}
}
// Don't export non-account specific tables
if (tableType == TableType.OTHER) {
return;
}
// Build the query - make sure to filter by account and tenant!
queryBuilder.append(" from ").append(tableName).append(" where ").append(tableType.getAccountRecordIdColumnName()).append(" = :accountRecordId and ").append(tableType.getTenantRecordIdColumnName()).append(" = :tenantRecordId");
// Notify the stream that we're about to write data for a different table
out.newTable(tableName, columnsForTable);
dbi.withHandle(new HandleCallback<Void>() {
@Override
public Void withHandle(final Handle handle) throws Exception {
final ResultIterator<Map<String, Object>> iterator = handle.createQuery(queryBuilder.toString()).bind("accountRecordId", context.getAccountRecordId()).bind("tenantRecordId", context.getTenantRecordId()).iterator();
try {
while (iterator.hasNext()) {
final Map<String, Object> row = iterator.next();
for (final String k : row.keySet()) {
final Object value = row.get(k);
// See also LowerToCamelBeanMapper
if (value instanceof Blob) {
final Blob blob = (Blob) value;
row.put(k, blob.getBytes(0, (int) blob.length()));
} else if (value instanceof Clob) {
// TODO Update LowerToCamelBeanMapper?
final Clob clob = (Clob) value;
row.put(k, clob.getSubString(1, (int) clob.length()));
}
}
try {
out.write(row);
} catch (final IOException e) {
logger.warn("Unable to write row: {}", row, e);
throw e;
}
}
} finally {
iterator.close();
}
return null;
}
});
}
use of jnc.platform.win32.Handle in project killbill by killbill.
the class TestDefaultTagUserApi method testSaveTagWithAccountRecordId.
@Test(groups = "slow")
public void testSaveTagWithAccountRecordId() throws Exception {
final UUID accountId = UUID.randomUUID();
final Long accountRecordId = generateAccountRecordId(accountId);
final ImmutableAccountData immutableAccountData = Mockito.mock(ImmutableAccountData.class);
Mockito.when(immutableAccountInternalApi.getImmutableAccountDataByRecordId(Mockito.<Long>eq(accountRecordId), Mockito.<InternalTenantContext>any())).thenReturn(immutableAccountData);
checkPagination(0);
eventsListener.pushExpectedEvent(NextEvent.TAG);
tagUserApi.addTags(accountId, ObjectType.ACCOUNT, ImmutableList.<UUID>of(ControlTagType.AUTO_INVOICING_OFF.getId()), callContext);
assertListenerStatus();
checkPagination(1);
// Verify the tag was saved
final List<Tag> tags = tagUserApi.getTagsForObject(accountId, ObjectType.ACCOUNT, true, callContext);
Assert.assertEquals(tags.size(), 1);
Assert.assertEquals(tags.get(0).getTagDefinitionId(), ControlTagType.AUTO_INVOICING_OFF.getId());
Assert.assertEquals(tags.get(0).getObjectId(), accountId);
Assert.assertEquals(tags.get(0).getObjectType(), ObjectType.ACCOUNT);
// Verify the account_record_id was populated
dbi.withHandle(new HandleCallback<Void>() {
@Override
public Void withHandle(final Handle handle) throws Exception {
final List<Map<String, Object>> values = handle.select("select account_record_id from tags where object_id = ?", accountId.toString());
Assert.assertEquals(values.size(), 1);
Assert.assertEquals(values.get(0).keySet().size(), 1);
Assert.assertEquals(Long.valueOf(values.get(0).get("account_record_id").toString()), accountRecordId);
return null;
}
});
eventsListener.pushExpectedEvent(NextEvent.TAG);
tagUserApi.removeTags(accountId, ObjectType.ACCOUNT, ImmutableList.<UUID>of(ControlTagType.AUTO_INVOICING_OFF.getId()), callContext);
assertListenerStatus();
List<Tag> remainingTags = tagUserApi.getTagsForObject(accountId, ObjectType.ACCOUNT, false, callContext);
Assert.assertEquals(remainingTags.size(), 0);
checkPagination(0);
// Add again the tag
eventsListener.pushExpectedEvent(NextEvent.TAG);
tagUserApi.addTags(accountId, ObjectType.ACCOUNT, ImmutableList.<UUID>of(ControlTagType.AUTO_INVOICING_OFF.getId()), callContext);
assertListenerStatus();
remainingTags = tagUserApi.getTagsForObject(accountId, ObjectType.ACCOUNT, false, callContext);
Assert.assertEquals(remainingTags.size(), 1);
checkPagination(1);
// Delete again
eventsListener.pushExpectedEvent(NextEvent.TAG);
tagUserApi.removeTags(accountId, ObjectType.ACCOUNT, ImmutableList.<UUID>of(ControlTagType.AUTO_INVOICING_OFF.getId()), callContext);
assertListenerStatus();
remainingTags = tagUserApi.getTagsForObject(accountId, ObjectType.ACCOUNT, false, callContext);
Assert.assertEquals(remainingTags.size(), 0);
checkPagination(0);
}
use of jnc.platform.win32.Handle in project judge by zjnu-acm.
the class WindowsExecutor method execute.
@Override
public ExecuteResult execute(Option option) throws IOException {
Path inputFile = option.getInputFile();
Path outputPath = option.getOutputFile();
boolean redirectErrorStream = option.isRedirectErrorStream();
Path errorPath = option.getErrFile();
Path workDirectory = option.getWorkDirectory();
String command = option.getCommand();
long timeLimit = option.getTimeLimit();
long memoryLimit = option.getMemoryLimit();
long outputLimit = option.getOutputLimit();
PROCESS_INFORMATION pi;
try (Handle hIn = fileOpen(inputFile, Executor.O_RDONLY);
Handle hOut = fileOpen(outputPath, Executor.O_WRONLY | Executor.O_CREAT | Executor.O_TRUNC);
Handle hErr = redirectErrorStream ? hOut : fileOpen(errorPath, Executor.O_WRONLY | Executor.O_CREAT | Executor.O_TRUNC)) {
pi = createProcess(command, hIn.getValue(), hOut.getValue(), hErr.getValue(), redirectErrorStream, workDirectory);
}
Job job;
long process = pi.getProcess();
try {
job = new Job(JobLevel.JOB_RESTRICTED, null, 0, 0);
try {
job.assignProcessToJob(process);
} catch (Throwable t) {
job.close();
throw t;
}
} catch (Throwable t) {
Kernel32.INSTANCE.TerminateProcess(process, 1);
throw t;
}
try (Handle hProcess = Handle.of(process);
Handle hThread = Handle.of(pi.getThread())) {
JudgeProcess judgeProcess = new JudgeProcess(hProcess.getValue());
try (FileChannel cOut = FileChannel.open(outputPath);
FileChannel cErr = redirectErrorStream ? cOut : FileChannel.open(errorPath)) {
int dwCount = Kernel32.INSTANCE.ResumeThread(hThread.getValue());
Kernel32Util.assertTrue(dwCount != -1);
hThread.close();
Instant startTime = judgeProcess.getStartTime();
while (true) {
long memory = judgeProcess.getPeakMemory();
if (memory > memoryLimit) {
judgeProcess.terminate(Status.MEMORY_LIMIT_EXCEED);
judgeProcess.join(Constants.TERMINATE_TIMEOUT);
break;
}
// extra 5 seconds
long time = ChronoUnit.MILLIS.between(startTime, Instant.now()) - 5000;
if (time > timeLimit || judgeProcess.getTime() > timeLimit) {
judgeProcess.terminate(Status.TIME_LIMIT_EXCEED);
judgeProcess.join(Constants.TERMINATE_TIMEOUT);
break;
}
long dwWaitTime = timeLimit - time;
if (dwWaitTime > Constants.UPDATE_TIME_THRESHOLD) {
dwWaitTime = Constants.UPDATE_TIME_THRESHOLD;
}
if (judgeProcess.join(dwWaitTime)) {
break;
}
if (checkOle(cOut, cErr, redirectErrorStream, outputLimit)) {
judgeProcess.terminate(Status.OUTPUT_LIMIT_EXCEED);
judgeProcess.join(Constants.TERMINATE_TIMEOUT);
break;
}
}
if (checkOle(cOut, cErr, redirectErrorStream, outputLimit)) {
judgeProcess.terminate(Status.OUTPUT_LIMIT_EXCEED);
}
} finally {
judgeProcess.terminate(Status.ACCEPTED);
}
judgeProcess.join(Long.MAX_VALUE);
Status status = judgeProcess.getStatus();
int exitCode = judgeProcess.getExitCode();
if (status == Status.ACCEPTED && exitCode != 0) {
status = Status.RUNTIME_ERROR;
}
long time = judgeProcess.getTime();
if (status == Status.TIME_LIMIT_EXCEED) {
time = ((time - timeLimit - 1) % 200 + 200) % 200 + 1 + timeLimit;
}
return ExecuteResult.builder().time(time).memory(judgeProcess.getPeakMemory()).code(status).exitCode(exitCode).build();
} finally {
job.close();
}
}
Aggregations