How To Use CompUtil To Parse With Plugin - alloy

When using the Alloy API to perform parsing on the following string:
Module mod = CompUtil.parseEverything_fromString("run {} for 5")
I receive the following error:
Fatal error:
Parser Exception
at edu.mit.csail.sdg.alloy4compiler.parser.CompParser.alloy_parseStream(CompParser.java:2260)
at edu.mit.csail.sdg.alloy4compiler.parser.CompUtil.parseRecursively(CompUtil.java:178)
at edu.mit.csail.sdg.alloy4compiler.parser.CompUtil.parseEverything_fromFile(CompUtil.java:280)
at edu.mit.csail.sdg.alloy4compiler.parser.CompUtil.parseEverything_fromString(CompUtil.java:333)
at edu.mit.csail.sdg.alloy4compiler.parser.CompUtil$parseEverything_fromString.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:136)
at MyOM.MyOMPlugin.Modularize(MyOMPlugin.groovy:107)
...
--------------------------------------------------------------------------
class file:
package MyOM
class MyOMPlugin extends Plugin{
void Modularize() throws Err{
//line 107 is the only line in the method and is below
Module mod = CompUtil.parseEverything_fromString("run {} for 5")
}
}
I am performing this task in a groovy class file within a groovy project. The code works fine until I run it in conjunction with the plugin I am using.
EDIT:
The parse function is what causes the parse exception and the code for that method is included below for reference:
#Override public Symbol parse() throws java.lang.Exception {
int act; // current action code
Symbol lhs_sym = null; // the Symbol/stack element returned by a reduce
short handle_size, lhs_sym_num; // information about production being reduced with
boolean logging = "yes".equals(System.getProperty("debug"));
production_tab = production_table();
action_tab = action_table();
reduce_tab = reduce_table();
init_actions();
user_init();
// start
cur_token = scan();
stack.removeAllElements();
stack.push(getSymbolFactory().startSymbol("START", 0, start_state()));
tos = 0;
for (_done_parsing = false; !_done_parsing; ) {
act = get_action(((Symbol)stack.peek()).parse_state, cur_token.sym);
if (act > 0) { // "shift"; thus, we shift to the encoded state by pushing it on the stack
if (logging) System.out.println("shift " + cur_token.sym);
cur_token.parse_state = act-1;
stack.push(cur_token);
tos++;
cur_token = scan();
} else if (act<0) { // "reduce"
if (logging) System.out.println("reduce " + ((-act)-1));
lhs_sym = do_action((-act)-1, this, stack, tos);
lhs_sym_num = production_tab[(-act)-1][0];
handle_size = production_tab[(-act)-1][1];
for (int i = 0; i < handle_size; i++) { stack.pop(); tos--; }
act = get_reduce(((Symbol)stack.peek()).parse_state, lhs_sym_num);
lhs_sym.parse_state = act;
stack.push(lhs_sym);
tos++;
} else { // "error"
if (logging) System.out.println("error");
syntax_error(cur_token);
done_parsing();
}
}
return lhs_sym;
}

Related

gRPC nodejs client can't send request to server because of serialization failure

I'm currently working on implementing a gRPC nodejs client that should communicate with a java/kotlin gRPC server to test out the cross language codegen.
However when I try to make a call from my nodejs code I get a serialization failure and I have no idea why this is happening.
I've added as much as I can share, if you need any other code snippets, just ask.
I don't use any proto-loader, but rather have a buf-build setup that generates the code in typescript and Java.
The exact error being displayed is:
Error: 13 INTERNAL: Request message serialization failure: Expected argument of type com.example.resources.chat.v1.GetActiveChatSessionsRequest
If anyone could point me into the right direction or can help me out, would be greatly appreciated
Proto definition
syntax = "proto3";
package com.example.resources.chat.v1;
option java_package = "com.example.resources.chat.v1";
import "google/protobuf/timestamp.proto";
message ChatRoomOverviewItem {
string support_ticket_id = 1;
string chat_room_id = 2;
int32 number_of_unread_messages = 3;
google.protobuf.Timestamp last_message_received = 4;
repeated string participants = 5;
}
message GetActiveChatSessionsRequest {
string participant_id = 1;
int32 page = 2;
int32 limit = 3;
}
message GetActiveChatSessionsResponse {
bool last = 1;
int32 total_elements = 2;
int32 total_pages = 3;
int32 number_of_elements = 4;
bool first = 5;
int32 number = 6;
bool empty = 7;
repeated ChatRoomOverviewItem content = 8;
}
gRPC definition
syntax = "proto3";
package com.example.resources.chat.v1;
option java_package = "com.example.resources.chat.v1";
import "com/example/resources/chat/v1/chat.proto";
service ChatApiService {
rpc GetActiveChatSessions (GetActiveChatSessionsRequest) returns (GetActiveChatSessionsResponse);
}
NodeJS - Client
export const chatService = new ChatApiServiceClient(
process.env.CHAT_GRPC_URI || 'http://localhost:6565', ChannelCredentials.createInsecure())
---
chatApiService.getActiveChatSessions(new GetActiveChatSessionsRequest()
.setParticipantId(userId)
.setPage(req.params.page ? parseInt(req.params.page) : 0)
.setLimit(req.params.limit ? parseInt(req.params.init) : 25),
async (error, response) => {
if (error) throw error
else {
/* handle logic */
}
})
Kotlin - Server
#GRpcService
class ChatApiService(
private val streamObserverHandler: GrpcStreamObserverHandler,
private val chatRoomService: ChatRoomService,
private val chatMessageService: ChatMessageService
) : ChatApiServiceImplBase() {
override fun getActiveChatSessions(
request: Chat.GetActiveChatSessionsRequest,
responseObserver: StreamObserver<Chat.GetActiveChatSessionsResponse>
) {
streamObserverHandler.accept(
chatRoomService.getActiveChatRoomsForUser(
UUID.fromString(request.participantId),
PageRequest.of(request.page, request.limit)
),
responseObserver
)
}

cannot set 'name' of undefined when throwing exception

I was just trying Apache Thrift in nodejs before using it in my upcoming project wherein I ran into this error.
Here is my demo.thrift file
namespace js demo
typedef i32 int
enum Operation {
ADD = 1,
SUBTRACT = 2,
MULTIPLY = 3,
DIVIDE = 4
}
struct Work {
1: int num1 = 0,
2: int num2,
3: Operation op,
4: optional string comment
}
exception InvalidOperation {
1: int message,
2: string trace
}
service Calculator {
void ping()
double calculate(1: int logid, 2: Work w) throws (1: InvalidOperation oops),
oneway void zip()
}
Here is a part of the server.js
I use switch case to determine operation in server.js
// inside thrift.createServer
calculate: (logid, work, result) => {
let answer = null, oops = null;
switch(work.op) {
// Code related to Operation.ADD, Operation.SUBTRACT ...
default: {
console.log("ERROR!");
oops = InvalidOperation();
oops.message = work.op;
oops.trace = "Unknown Operation";
}
}
result(oops, answer);
}
When the client.js calls server with calculate(12345, { num1:1, num2:2, op: 10 })
Instead of returning an error it throws
TypeError: Cannot set property 'name' of undefined in demo_types.js:122
The part related to InvalidOperation in demo_types.js is
// Work related code
var InvalidOperation = module.exports.InvalidOperation = function(args) {
Thrift.TException.call(this, "InvalidOperation");
this.name = "InvalidOperation"; // points to here
this.message = null;
this.trace = null;
if (args) {
if (args.message !== undefined && args.message !== null) {
this.message = args.message;
}
if (args.trace !== undefined && args.trace !== null) {
this.trace = args.trace;
}
}
};
Thrift.inherits(InvalidOperation, Thrift.TException);
InvalidOperation.prototype.name = 'InvalidOperation';
// InvalidOperation.read & .write
Any idea why the error is being thrown?
Actually I realised why this error is being thrown. It is a plain old Javascript mistake.
oops = new InvalidOperation();
That's it.

XAdES-BES countersignature cannot resolve reference error

I implemented verification for XAdES-BES and after testing everything works now besides counter-signatures. The same error occurs not only for files signed with xades4j but also using other software so it is not related to any mistakes in my countersignature implementation. I wonder if I should implement additional ResourceResolver? I added a countersigned file as the attachment with 'REMOVED' for some private entries here.
Below is the code for verification. certDataList is a list with all certificates from the document in String and getCert will return List. DummyCertificateValidationProvider returns ValidationData with a list of previously constructed x509certs.
public boolean verify(final File file) {
if (!Dictionaries.valid()) {
return true;
}
certList = null;
try {
final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
final DocumentBuilder db = dbf.newDocumentBuilder();
final Document doc = db.parse(file);
doc.getDocumentElement().normalize();
final NodeList nList = doc.getElementsByTagName("ds:Signature");
Element elem = null;
for (int temp = 0; temp < nList.getLength(); temp++) {
final Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
elem = (Element) nNode;
}
}
final NodeList nList2 = doc.getElementsByTagName("ds:X509Certificate");
final List<String> certDataList = new ArrayList<String>();
for (int temp = 0; temp < nList2.getLength(); temp++) {
final Node nNode = nList2.item(temp);
certDataList.add(nNode.getTextContent());
}
certList = getCert(certDataList);
final CertificateValidationProvider certValidator = new DummyCertificateValidationProvider(certList);
final XadesVerificationProfile p = new XadesVerificationProfile(certValidator);
final XadesVerifier v = p.newVerifier();
final SignatureSpecificVerificationOptions opts = new SignatureSpecificVerificationOptions();
// for relative document paths
final String baseUri = "file:///" + file.getParentFile().getAbsolutePath().replace("\\", "/") + "/";
LOGGER.debug("baseUri:" + baseUri);
opts.useBaseUri(baseUri);
v.verify(elem, opts);
return true;
} catch (final IllegalArgumentException | XAdES4jException | CertificateException | IOException | ParserConfigurationException | SAXException e) {
LOGGER.error("XML not validated!", e);
}
return false;
}
Here is the stacktrace:
21:31:48,203 DEBUG ResourceResolver:158 - I was asked to create a ResourceResolver and got 0
21:31:48,203 DEBUG ResourceResolver:101 - check resolvability by class org.apache.xml.security.utils.resolver.ResourceResolver
21:31:48,204 DEBUG ResolverFragment:137 - State I can resolve reference: "#xmldsig-5de7b1d0-be70-4dde-b746-3f4d4d6de39f-sigvalue"
21:31:48,204 ERROR SignComponent:658 - XML not validated!
xades4j.XAdES4jXMLSigException: Error verifying the signature
at xades4j.verification.XadesVerifierImpl.doCoreVerification(XadesVerifierImpl.java:284)
at xades4j.verification.XadesVerifierImpl.verify(XadesVerifierImpl.java:188)
at com.signapplet.sign.SignComponent.verify(SignComponent.java:655)
...
Caused by: org.apache.xml.security.signature.MissingResourceFailureException: The Reference for URI #xmldsig-5de7b1d0-be70-4dde-b746-3f4d4d6de39f-sigvalue has no XMLSignatureInput
Original Exception was org.apache.xml.security.signature.ReferenceNotInitializedException: Cannot resolve element with ID xmldsig-5de7b1d0-be70-4dde-b746-3f4d4d6de39f-sigvalue
Original Exception was org.apache.xml.security.utils.resolver.ResourceResolverException: Cannot resolve element with ID xmldsig-5de7b1d0-be70-4dde-b746-3f4d4d6de39f-sigvalue
at org.apache.xml.security.signature.Manifest.verifyReferences(Manifest.java:414)
at org.apache.xml.security.signature.SignedInfo.verify(SignedInfo.java:259)
at org.apache.xml.security.signature.XMLSignature.checkSignatureValue(XMLSignature.java:724)
at org.apache.xml.security.signature.XMLSignature.checkSignatureValue(XMLSignature.java:656)
at xades4j.verification.XadesVerifierImpl.doCoreVerification(XadesVerifierImpl.java:277)
... 39 more
Caused by: org.apache.xml.security.signature.ReferenceNotInitializedException: Cannot resolve element with ID xmldsig-5de7b1d0-be70-4dde-b746-3f4d4d6de39f-sigvalue
Edit:
The same error occurs when I try to validate file provided with xades4j unit tests document.signed.bes.cs.xml.
Caused by: org.apache.xml.security.signature.MissingResourceFailureException: The Reference for URI #xmldsig-281967d1-74f8-482c-8222-ed58dbd1909b-sigvalue has no XMLSignatureInput
Original Exception was org.apache.xml.security.signature.ReferenceNotInitializedException: Cannot resolve element with ID xmldsig-281967d1-74f8-482c-8222-ed58dbd1909b-sigvalue
Caused by: org.apache.xml.security.signature.ReferenceNotInitializedException: Cannot resolve element with ID xmldsig-281967d1-74f8-482c-8222-ed58dbd1909b-sigvalue
The problem was with ds:Signature. In counter signatures you will have more than one ds:Signature entry. In my verification method I used the for loop:
for (int temp = 0; temp < nList.getLength(); temp++) {
final Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
elem = (Element) nNode;
}
}
As you can see, there was no break when element was found so I ended up with the last ds:Signature, not the first one so all previous signatures could not be found.

Use iXMLHttpRequest2 to download zip file

I am trying to port cocos2dx application for Windows phone 8. I am trying to use iXMLHTTPRequest class to perform Network calls in C++.
I am trying to download zip file using this but dont know what and where I am doing wrong. Here is my code which I am using, Please help me to figure out the issue and what I should do to make it working.
void HTTPRequest::sendRequest(){
m_cancelHttpRequestSource = cancellation_token_source();
// Set up the GET request parameters.
std::string s_str = std::string(urlString);
std::wstring wid_str = std::wstring(s_str.begin(), s_str.end());
const wchar_t* w_char = wid_str.c_str();
auto uri = ref new Uri( ref new String(w_char));
String ^temp = uri->AbsoluteUri;
auto token = m_cancelHttpRequestSource.get_token();
// Send the request and then update the UI.
onHttpRequestCompleted(m_httpRequest.GetAsync(uri, token));
}
void HTTPRequest::onHttpRequestCompleted(concurrency::task httpRequest)
{
httpRequest.then([this](task previousTask)
{
try
{
wstring response = previousTask.get();
if (m_httpRequest.GetStatusCode() == 200)
{
size_t strSize;
FILE* fileHandle;
auto local = Windows::Storage::ApplicationData::Current->LocalFolder;
auto localFileNamePlatformString = local->Path + "\\test1.zip";
// Create an the xml file in text and Unicode encoding mode.
if ((fileHandle = _wfopen(localFileNamePlatformString->Data(), L"wb")) == NULL) // C4996
// Note: _wfopen is deprecated; consider using _wfopen_s instead
{
wprintf(L"_wfopen failed!\n");
return(0);
}
// Write a string into the file.
strSize = wcslen(response.c_str());
if (fwrite(response.c_str(), sizeof(wchar_t), strSize, fileHandle) != strSize)
{
wprintf(L"fwrite failed!\n");
}
// Close the file.
if (fclose(fileHandle))
{
wprintf(L"fclose failed!\n");
}
}
else
{
// The request failed. Show the status code and reason.
wstringstream ss;
ss << L"The server returned "
<< m_httpRequest.GetStatusCode()
<< L" ("
<< m_httpRequest.GetReasonPhrase()
<< L')';
//String ^responseText = ref new String(ss.str().c_str());
m_delegate->parserError(requestType->getCString(), "Print Status Code later");
}
}
catch (const task_canceled&)
{
// Indicate that the operation was canceled.
//String ^responseText = "The operation was canceled";
m_delegate->parserError(requestType->getCString(), "Operation has canceled");
}
catch (Exception^ e)
{
// Indicate that the operation failed.
//String ^responseText = "The operation failed";
m_delegate->parserError(requestType->getCString(), "The operation failed");
// TODO: Handle the error further.
(void)e;
}
}, task_continuation_context::use_current());
}

C# powershell output reader iterator getting modified when pipeline closed and disposed

I'm calling a powershell script from C#. The script is pretty small and is "gps;$host.SetShouldExit(9)", which list process, and then send back an exit code to be captured by the PSHost object.
The problem I have is when the pipeline has been stopped and disposed, the output reader PSHost collection still seems to be written to, and is filling up. So when I try and copy it to my own output object, it craps out with a OutOfMemoryException when I try to iterate over it. Sometimes it will except with a Collection was modified message. Here is the code.
private void ProcessAndExecuteBlock(ScriptBlock Block)
{
Collection<PSObject> PSCollection = new Collection<PSObject>();
Collection<Object> PSErrorCollection = new Collection<Object>();
Boolean Error = false;
int ExitCode=0;
//Send for exection.
ExecuteScript(Block.Script);
// Process the waithandles.
while (PExecutor.PLine.PipelineStateInfo.State == PipelineState.Running)
{
// Wait for either error or data waithandle.
switch (WaitHandle.WaitAny(PExecutor.Hand))
{
// Data
case 0:
Collection<PSObject> data = PExecutor.PLine.Output.NonBlockingRead();
if (data.Count > 0)
{
for (int cnt = 0; cnt <= (data.Count-1); cnt++)
{
PSCollection.Add(data[cnt]);
}
}
// Check to see if the pipeline has been closed.
if (PExecutor.PLine.Output.EndOfPipeline)
{
// Bring back the exit code.
ExitCode = RHost.ExitCode;
}
break;
case 1:
Collection<object> Errordata = PExecutor.PLine.Error.NonBlockingRead();
if (Errordata.Count > 0)
{
Error = true;
for (int count = 0; count <= (Errordata.Count - 1); count++)
{
PSErrorCollection.Add(Errordata[count]);
}
}
break;
}
}
PExecutor.Stop();
// Create the Execution Return block
ExecutionResults ER = new ExecutionResults(Block.RuleGuid,Block.SubRuleGuid, Block.MessageIdentfier);
ER.ExitCode = ExitCode;
// Add in the data results.
lock (ReadSync)
{
if (PSCollection.Count > 0)
{
ER.DataAdd(PSCollection);
}
}
// Add in the error data if any.
if (Error)
{
if (PSErrorCollection.Count > 0)
{
ER.ErrorAdd(PSErrorCollection);
}
else
{
ER.InError = true;
}
}
// We have finished, so enque the block back.
EnQueueOutput(ER);
}
and this is the PipelineExecutor class which setups the pipeline for execution.
public class PipelineExecutor
{
private Pipeline pipeline;
private WaitHandle[] Handles;
public Pipeline PLine
{
get { return pipeline; }
}
public WaitHandle[] Hand
{
get { return Handles; }
}
public PipelineExecutor(Runspace runSpace, string command)
{
pipeline = runSpace.CreatePipeline(command);
Handles = new WaitHandle[2];
Handles[0] = pipeline.Output.WaitHandle;
Handles[1] = pipeline.Error.WaitHandle;
}
public void Start()
{
if (pipeline.PipelineStateInfo.State == PipelineState.NotStarted)
{
pipeline.Input.Close();
pipeline.InvokeAsync();
}
}
public void Stop()
{
pipeline.StopAsync();
}
}
An this is the DataAdd method, where the exception arises.
public void DataAdd(Collection<PSObject> Data)
{
foreach (PSObject Ps in Data)
{
Data.Add(Ps);
}
}
I put a for loop around the Data.Add, and the Collection filled up with 600k+ so feels like the gps command is still running, but why. Any ideas.
Thanks in advance.
Found the problem. Named the resultant collection and the iterator the same, so as it was iterating, it was adding to the collection, and back into the iterator, and so forth. Doh!.

Resources