type
stringclasses 7
values | content
stringlengths 4
9.55k
| repo
stringlengths 7
96
| path
stringlengths 4
178
| language
stringclasses 1
value |
|---|---|---|---|---|
MethodDeclaration
|
componentDidMount() {
document.title = getTabTitle(`b/${this.sub}`);
this.fetchAll();
}
|
Pradeep-selva/breaddit
|
client/src/Pages/Subreaddit/container.tsx
|
TypeScript
|
MethodDeclaration
|
componentWillUnmount() {
document.title = DEFAULT_TITLE;
}
|
Pradeep-selva/breaddit
|
client/src/Pages/Subreaddit/container.tsx
|
TypeScript
|
MethodDeclaration
|
render() {
const { posts, hasFetched, subData } = this.state;
const { classes, user } = this.props;
const isUserMember = user?.JoinedSubs.includes(this.sub);
const isUserOwner = subData?.Owner === user?.UserName;
return (
<PaginationContainer handlePagination={this.fetchMore}>
<Paper
className={classes.bannerContainer}
style={{ position: "relative" }}
|
Pradeep-selva/breaddit
|
client/src/Pages/Subreaddit/container.tsx
|
TypeScript
|
MethodDeclaration
|
formatNumberNotation(subData?.Users
|
Pradeep-selva/breaddit
|
client/src/Pages/Subreaddit/container.tsx
|
TypeScript
|
ClassDeclaration
|
@NgModule({
declarations: [
ServiceComponent,
ServiceDetailsComponent
],
imports: [
CommonModule,
RouterModule.forChild([
{
path: '',
component: ServiceComponent
},
{
path: 'details',
component: ServiceDetailsComponent
}
]),
],
providers: []
})
export class ServiceModule { }
|
smsan80/repo_edm
|
edm/src/app/service/service.module.ts
|
TypeScript
|
FunctionDeclaration
|
function getMAIN1string(state): string {
if (state["MAINQ1-can-we-still-save-the-world"]) return "yesMAIN1";
else return "noMAIN1";
}
|
abcnews/interactive-untangling-the-climate-mess
|
src/embeds.tsx
|
TypeScript
|
FunctionDeclaration
|
function getSUBstring(state): string {
if (
state["SUBQ1-renewables-zero-carbon"] &&
state["SUBQ2-livestock-emissions"] &&
state["SUBQ3-transportation-off-fossil"] &&
state["SUBQ4-industry-emissions"] &&
state["SUBQ5-carbon-capture"]
)
return "allSUB";
if (
state["SUBQ1-renewables-zero-carbon"] ||
state["SUBQ2-livestock-emissions"] ||
state["SUBQ3-transportation-off-fossil"] ||
state["SUBQ4-industry-emissions"] ||
state["SUBQ5-carbon-capture"]
)
return "someSUB";
return "noSUB";
}
|
abcnews/interactive-untangling-the-climate-mess
|
src/embeds.tsx
|
TypeScript
|
FunctionDeclaration
|
function getMAIN2(state): string {
if (state["MAINQ2-can-we-still-save-the-world-again-after-article"])
return "yesMAIN2";
return "noMAIN2";
}
|
abcnews/interactive-untangling-the-climate-mess
|
src/embeds.tsx
|
TypeScript
|
FunctionDeclaration
|
function renderEmbed(embedEl: HTMLElement) {
const { id } = embedEl.dataset;
render(<EmbedSwitcher id={id} />, embedEl);
}
|
abcnews/interactive-untangling-the-climate-mess
|
src/embeds.tsx
|
TypeScript
|
ArrowFunction
|
() =>
handler({
didTimeout: false,
timeRemaining: () => Math.max(0, 50.0 - (Date.now() - startTime))
})
|
abcnews/interactive-untangling-the-climate-mess
|
src/embeds.tsx
|
TypeScript
|
ArrowFunction
|
() => Math.max(0, 50.0 - (Date.now() - startTime))
|
abcnews/interactive-untangling-the-climate-mess
|
src/embeds.tsx
|
TypeScript
|
ArrowFunction
|
({ id }) => {
const [userInputSerializedState, setUserInputSerializedState] =
useState("{}");
const userInputState = JSON.parse(userInputSerializedState);
useEffect(() => {
let hasEnded = false;
rIC(async function poll() {
const _userInputSerializedState = await idbGet<string>(
USER_INPUT_STATE_PERSISTENCE_KEY,
idbKeyvalStore
);
if (userInputSerializedState !== _userInputSerializedState) {
setUserInputSerializedState(_userInputSerializedState || "{}");
}
if (!hasEnded) {
rIC(poll);
}
});
return () => {
hasEnded = true;
};
}, [userInputState]);
const updateSerializePersistAndSetUserInputState = async fn => {
const nextUserInputState = fn(userInputState);
const nextUserInputSerializedState = JSON.stringify(nextUserInputState);
await idbSet(
USER_INPUT_STATE_PERSISTENCE_KEY,
nextUserInputSerializedState,
idbKeyvalStore
);
setUserInputSerializedState(nextUserInputSerializedState);
};
const userInputBoxCommonProps = {
userInputState,
setUserInputState: updateSerializePersistAndSetUserInputState,
windowWidth: 0
};
let component: JSX.Element | null = null;
switch (id) {
case "mainq1":
case "subq1":
case "subq2":
case "subq3":
case "subq4":
const key = id.toUpperCase();
const { color, slug } = QUESTION_CONFIGS[id];
const optimisticText = dynamicText[`${key}-optimistic`];
const pessimisticText = dynamicText[`${key}-pessimistic`];
component = (
<UserInputBox
color={color}
questionKey={`${key}-${slug}`}
preTitle={<DynText>{dynamicText[`${key}-pre-title`]}</DynText>}
title={<DynText>{dynamicText[`${key}-title`]}</DynText>}
buttons={
id.indexOf("mainq") === 0
? [
{
label: "Of course we can",
value: "certain",
response: <DynText>{optimisticText}</DynText>
},
{
label: "Yes I think we can",
value: "hopeful",
response: <DynText>{optimisticText}</DynText>
},
{
label: "Probably not",
value: "doubtful",
response: <DynText>{pessimisticText}</DynText>
},
{
label: "No way we're screwed",
value: "impossible",
response: <DynText>{pessimisticText}</DynText>
}
]
: [
{
label: "It can be done",
value: "hopeful",
response: <DynText>{optimisticText}</DynText>
},
{
label: "This sounds like a stretch",
value: "doubtful",
response: <DynText>{pessimisticText}</DynText>
}
]
}
{...userInputBoxCommonProps}
/>
|
abcnews/interactive-untangling-the-climate-mess
|
src/embeds.tsx
|
TypeScript
|
ArrowFunction
|
() => {
let hasEnded = false;
rIC(async function poll() {
const _userInputSerializedState = await idbGet<string>(
USER_INPUT_STATE_PERSISTENCE_KEY,
idbKeyvalStore
);
if (userInputSerializedState !== _userInputSerializedState) {
setUserInputSerializedState(_userInputSerializedState || "{}");
}
if (!hasEnded) {
rIC(poll);
}
});
return () => {
hasEnded = true;
};
}
|
abcnews/interactive-untangling-the-climate-mess
|
src/embeds.tsx
|
TypeScript
|
ArrowFunction
|
() => {
hasEnded = true;
}
|
abcnews/interactive-untangling-the-climate-mess
|
src/embeds.tsx
|
TypeScript
|
ArrowFunction
|
async fn => {
const nextUserInputState = fn(userInputState);
const nextUserInputSerializedState = JSON.stringify(nextUserInputState);
await idbSet(
USER_INPUT_STATE_PERSISTENCE_KEY,
nextUserInputSerializedState,
idbKeyvalStore
);
setUserInputSerializedState(nextUserInputSerializedState);
}
|
abcnews/interactive-untangling-the-climate-mess
|
src/embeds.tsx
|
TypeScript
|
ArrowFunction
|
({ userInputState }) => {
const [userStrings, setUserStrings] = useState({
renewables: 1,
transportation: 1,
carboncapture: 1,
industry: 1,
livestock: 1
});
const [questionCompleteness, setQuestionCompleteness] = useState("nothing");
const [convincedState, setConvincedState] = useState("orange");
const [subQuestionsConvinvedOf, setSubQuestionsConvinvedOf] = useState(0);
useEffect(() => {
if (!userInputState) return;
const nextUserStrings = userStrings;
if (userInputState["SUBQ1-renewables-zero-carbon"]) {
switch (userInputState["SUBQ1-renewables-zero-carbon"]) {
case "certain":
case "hopeful":
nextUserStrings.renewables = 0;
break;
case "doubtful":
case "impossible":
nextUserStrings.renewables = 1;
break;
}
}
if (userInputState["SUBQ2-livestock-emissions"]) {
switch (userInputState["SUBQ2-livestock-emissions"]) {
case "certain":
case "hopeful":
nextUserStrings.livestock = 0;
break;
case "doubtful":
case "impossible":
nextUserStrings.livestock = 1;
break;
}
}
if (userInputState["SUBQ3-transportation-off-fossil"]) {
switch (userInputState["SUBQ3-transportation-off-fossil"]) {
case "certain":
case "hopeful":
nextUserStrings.transportation = 0;
break;
case "doubtful":
case "impossible":
nextUserStrings.transportation = 1;
break;
}
}
if (userInputState["SUBQ4-industry-emissions"]) {
switch (userInputState["SUBQ4-industry-emissions"]) {
case "certain":
case "hopeful":
nextUserStrings.industry = 0;
break;
case "doubtful":
case "impossible":
nextUserStrings.industry = 1;
break;
}
}
if (userInputState["SUBQ5-carbon-capture"]) {
switch (userInputState["SUBQ5-carbon-capture"]) {
case "certain":
case "hopeful":
nextUserStrings.carboncapture = 0;
break;
case "doubtful":
case "impossible":
nextUserStrings.carboncapture = 1;
break;
}
}
setUserStrings(nextUserStrings);
let localConvincedCount = 0;
for (const area in nextUserStrings) {
if (nextUserStrings[area] === 0) localConvincedCount++;
}
setSubQuestionsConvinvedOf(localConvincedCount);
function getMAIN1string(state): string {
if (state["MAINQ1-can-we-still-save-the-world"]) return "yesMAIN1";
else return "noMAIN1";
}
function getSUBstring(state): string {
if (
state["SUBQ1-renewables-zero-carbon"] &&
state["SUBQ2-livestock-emissions"] &&
state["SUBQ3-transportation-off-fossil"] &&
state["SUBQ4-industry-emissions"] &&
state["SUBQ5-carbon-capture"]
)
return "allSUB";
if (
state["SUBQ1-renewables-zero-carbon"] ||
state["SUBQ2-livestock-emissions"] ||
state["SUBQ3-transportation-off-fossil"] ||
state["SUBQ4-industry-emissions"] ||
state["SUBQ5-carbon-capture"]
)
return "someSUB";
return "noSUB";
}
function getMAIN2(state): string {
if (state["MAINQ2-can-we-still-save-the-world-again-after-article"])
return "yesMAIN2";
return "noMAIN2";
}
const combinedCompletenessStrings =
getMAIN1string(userInputState) +
getSUBstring(userInputState) +
getMAIN2(userInputState);
setQuestionCompleteness(combinedCompletenessStrings);
const mainChangeLevels = {
certain: 4,
hopeful: 3,
doubtful: 2,
impossible: 1
};
const main1 = userInputState["MAINQ1-can-we-still-save-the-world"];
const main2 =
userInputState["MAINQ2-can-we-still-save-the-world-again-after-article"];
const mainLevel1 = mainChangeLevels[main1];
const mainLevel2 = mainChangeLevels[main2];
if (mainLevel1 && main2) {
if (mainLevel1 === mainLevel2) setConvincedState("orange");
if (mainLevel1 > mainLevel2) setConvincedState("red");
if (mainLevel1 < mainLevel2) setConvincedState("green");
}
}, [userInputState]);
return (
<div>
{INTERACTIVE_PANEL_KEYS.map(panelKey => (
<InteractivePanel
key={panelKey}
panelKey={panelKey}
questionCompleteness={questionCompleteness}
convincedState={convincedState}
subQuestionsConvinvedOf={subQuestionsConvinvedOf}
australiaConvincedOf={0}
dynamicText={dynamicText}
dynamicTextLoading={false}
userInputState={userInputState}
/>
))}
</div>
);
}
|
abcnews/interactive-untangling-the-climate-mess
|
src/embeds.tsx
|
TypeScript
|
ArrowFunction
|
() => {
if (!userInputState) return;
const nextUserStrings = userStrings;
if (userInputState["SUBQ1-renewables-zero-carbon"]) {
switch (userInputState["SUBQ1-renewables-zero-carbon"]) {
case "certain":
case "hopeful":
nextUserStrings.renewables = 0;
break;
case "doubtful":
case "impossible":
nextUserStrings.renewables = 1;
break;
}
}
if (userInputState["SUBQ2-livestock-emissions"]) {
switch (userInputState["SUBQ2-livestock-emissions"]) {
case "certain":
case "hopeful":
nextUserStrings.livestock = 0;
break;
case "doubtful":
case "impossible":
nextUserStrings.livestock = 1;
break;
}
}
if (userInputState["SUBQ3-transportation-off-fossil"]) {
switch (userInputState["SUBQ3-transportation-off-fossil"]) {
case "certain":
case "hopeful":
nextUserStrings.transportation = 0;
break;
case "doubtful":
case "impossible":
nextUserStrings.transportation = 1;
break;
}
}
if (userInputState["SUBQ4-industry-emissions"]) {
switch (userInputState["SUBQ4-industry-emissions"]) {
case "certain":
case "hopeful":
nextUserStrings.industry = 0;
break;
case "doubtful":
case "impossible":
nextUserStrings.industry = 1;
break;
}
}
if (userInputState["SUBQ5-carbon-capture"]) {
switch (userInputState["SUBQ5-carbon-capture"]) {
case "certain":
case "hopeful":
nextUserStrings.carboncapture = 0;
break;
case "doubtful":
case "impossible":
nextUserStrings.carboncapture = 1;
break;
}
}
setUserStrings(nextUserStrings);
let localConvincedCount = 0;
for (const area in nextUserStrings) {
if (nextUserStrings[area] === 0) localConvincedCount++;
}
setSubQuestionsConvinvedOf(localConvincedCount);
function getMAIN1string(state): string {
if (state["MAINQ1-can-we-still-save-the-world"]) return "yesMAIN1";
else return "noMAIN1";
}
function getSUBstring(state): string {
if (
state["SUBQ1-renewables-zero-carbon"] &&
state["SUBQ2-livestock-emissions"] &&
state["SUBQ3-transportation-off-fossil"] &&
state["SUBQ4-industry-emissions"] &&
state["SUBQ5-carbon-capture"]
)
return "allSUB";
if (
state["SUBQ1-renewables-zero-carbon"] ||
state["SUBQ2-livestock-emissions"] ||
state["SUBQ3-transportation-off-fossil"] ||
state["SUBQ4-industry-emissions"] ||
state["SUBQ5-carbon-capture"]
)
return "someSUB";
return "noSUB";
}
function getMAIN2(state): string {
if (state["MAINQ2-can-we-still-save-the-world-again-after-article"])
return "yesMAIN2";
return "noMAIN2";
}
const combinedCompletenessStrings =
getMAIN1string(userInputState) +
getSUBstring(userInputState) +
getMAIN2(userInputState);
setQuestionCompleteness(combinedCompletenessStrings);
const mainChangeLevels = {
certain: 4,
hopeful: 3,
doubtful: 2,
impossible: 1
};
const main1 = userInputState["MAINQ1-can-we-still-save-the-world"];
const main2 =
userInputState["MAINQ2-can-we-still-save-the-world-again-after-article"];
const mainLevel1 = mainChangeLevels[main1];
const mainLevel2 = mainChangeLevels[main2];
if (mainLevel1 && main2) {
if (mainLevel1 === mainLevel2) setConvincedState("orange");
if (mainLevel1 > mainLevel2) setConvincedState("red");
if (mainLevel1 < mainLevel2) setConvincedState("green");
}
}
|
abcnews/interactive-untangling-the-climate-mess
|
src/embeds.tsx
|
TypeScript
|
ArrowFunction
|
panelKey => (
<InteractivePanel
key={panelKey}
|
abcnews/interactive-untangling-the-climate-mess
|
src/embeds.tsx
|
TypeScript
|
ArrowFunction
|
() => {
idbKeyvalStore = createStore(
`${PROJECT_NAME}-db-${Math.floor(Date.now() / 1e4)}`,
`${PROJECT_NAME}-store`
);
const embedEl = document.getElementById("embed") as HTMLElement;
if (window.applenews) {
initAppleNews(embedEl, renderEmbed);
} else {
renderEmbed(embedEl);
}
}
|
abcnews/interactive-untangling-the-climate-mess
|
src/embeds.tsx
|
TypeScript
|
InterfaceDeclaration
|
interface EmbedSwitcherProps {
id?: string;
}
|
abcnews/interactive-untangling-the-climate-mess
|
src/embeds.tsx
|
TypeScript
|
InterfaceDeclaration
|
interface UserResultsBoxProps {
userInputState: Record<string, string>;
}
|
abcnews/interactive-untangling-the-climate-mess
|
src/embeds.tsx
|
TypeScript
|
FunctionDeclaration
|
function __findEndpoint(
masterClient: OPCUAClientBase,
endpointUrl: string,
params: FindEndpointOptions,
callback: FindEndpointCallback
) {
debugLog("findEndpoint : endpointUrl = ", endpointUrl);
const securityMode = params.securityMode;
const securityPolicy = params.securityPolicy;
const options: OPCUAClientBaseOptions = {
connectionStrategy: params.connectionStrategy,
// endpoint_must_exist: false,
applicationName: params.applicationName,
certificateFile: params.certificateFile,
privateKeyFile: params.privateKeyFile
};
const client = new ClientBaseImpl(options);
let selectedEndpoints: any = null;
const allEndpoints: any = null;
const tasks = [
(innerCallback: ErrorCallback) => {
// rebind backoff handler
masterClient.listeners("backoff").forEach(
(handler: any) => client.on("backoff", handler));
if (doDebug) {
client.on("backoff", (retryCount: number, delay: number) => {
debugLog("finding Endpoint => reconnecting ",
" retry count", retryCount, " next attempt in ", delay / 1000, "seconds");
});
}
client.connect(endpointUrl, (err?: Error) => {
if (err) {
// let's improve the error message with meaningful info
err.message = "Fail to connect to server at " + endpointUrl +
" to collect certificate server (in findEndpoint) \n" +
" (err =" + err.message + ")";
debugLog("Fail to connect to server ", endpointUrl, " to collect certificate server");
}
return innerCallback(err);
});
},
(innerCallback: ErrorCallback) => {
client.getEndpoints((err: Error | null, endpoints?: EndpointDescription[]) => {
if (err) {
err.message = "error in getEndpoints \n" + err.message;
return innerCallback(err);
}
if (!endpoints) {
return innerCallback(new Error("Internal Error"));
}
endpoints.forEach((endpoint: EndpointDescription) => {
if (endpoint.securityMode === securityMode && endpoint.securityPolicyUri === securityPolicy) {
selectedEndpoints = endpoint; // found it
}
});
innerCallback();
});
},
(innerCallback: ErrorCallback) => {
client.disconnect(innerCallback);
}
];
async.series(tasks, (err) => {
if (err) {
return callback(err);
}
if (!selectedEndpoints) {
callback(new Error("Cannot find an Endpoint matching " +
" security mode: " + securityMode.toString() +
" policy: " + securityPolicy.toString()));
}
const result = {
endpoints: allEndpoints,
selectedEndpoint: selectedEndpoints
};
callback(null, result);
});
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
FunctionDeclaration
|
/**
* check if certificate is trusted or untrusted
*/
function _verify_serverCertificate(serverCertificate: Certificate, callback: ErrorCallback) {
// todo:
// - use Certificate manager to deal with trusted/ untrusted certificate
// - add certificate verification and validity check
const pkiFolder = process.cwd() + "/pki";
// istanbul ignore next
if (!fs.existsSync(pkiFolder)) {
fs.mkdirSync(pkiFolder);
}
const pkiRejectedCertificateFolder = path.join(pkiFolder, "rejected");
// istanbul ignore next
if (!fs.existsSync(pkiRejectedCertificateFolder)) {
fs.mkdirSync(pkiRejectedCertificateFolder);
}
const thumbprint = makeSHA1Thumbprint(serverCertificate);
const certificateFilename = path.join(pkiRejectedCertificateFolder, thumbprint.toString("hex") + ".pem");
fs.writeFile(certificateFilename, toPem(serverCertificate, "CERTIFICATE"), () => {
setImmediate(callback);
});
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(innerCallback: ErrorCallback) => {
// rebind backoff handler
masterClient.listeners("backoff").forEach(
(handler: any) => client.on("backoff", handler));
if (doDebug) {
client.on("backoff", (retryCount: number, delay: number) => {
debugLog("finding Endpoint => reconnecting ",
" retry count", retryCount, " next attempt in ", delay / 1000, "seconds");
});
}
client.connect(endpointUrl, (err?: Error) => {
if (err) {
// let's improve the error message with meaningful info
err.message = "Fail to connect to server at " + endpointUrl +
" to collect certificate server (in findEndpoint) \n" +
" (err =" + err.message + ")";
debugLog("Fail to connect to server ", endpointUrl, " to collect certificate server");
}
return innerCallback(err);
});
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(handler: any) => client.on("backoff", handler)
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(retryCount: number, delay: number) => {
debugLog("finding Endpoint => reconnecting ",
" retry count", retryCount, " next attempt in ", delay / 1000, "seconds");
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(err?: Error) => {
if (err) {
// let's improve the error message with meaningful info
err.message = "Fail to connect to server at " + endpointUrl +
" to collect certificate server (in findEndpoint) \n" +
" (err =" + err.message + ")";
debugLog("Fail to connect to server ", endpointUrl, " to collect certificate server");
}
return innerCallback(err);
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(innerCallback: ErrorCallback) => {
client.getEndpoints((err: Error | null, endpoints?: EndpointDescription[]) => {
if (err) {
err.message = "error in getEndpoints \n" + err.message;
return innerCallback(err);
}
if (!endpoints) {
return innerCallback(new Error("Internal Error"));
}
endpoints.forEach((endpoint: EndpointDescription) => {
if (endpoint.securityMode === securityMode && endpoint.securityPolicyUri === securityPolicy) {
selectedEndpoints = endpoint; // found it
}
});
innerCallback();
});
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(err: Error | null, endpoints?: EndpointDescription[]) => {
if (err) {
err.message = "error in getEndpoints \n" + err.message;
return innerCallback(err);
}
if (!endpoints) {
return innerCallback(new Error("Internal Error"));
}
endpoints.forEach((endpoint: EndpointDescription) => {
if (endpoint.securityMode === securityMode && endpoint.securityPolicyUri === securityPolicy) {
selectedEndpoints = endpoint; // found it
}
});
innerCallback();
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(endpoint: EndpointDescription) => {
if (endpoint.securityMode === securityMode && endpoint.securityPolicyUri === securityPolicy) {
selectedEndpoints = endpoint; // found it
}
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(innerCallback: ErrorCallback) => {
client.disconnect(innerCallback);
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(err) => {
if (err) {
return callback(err);
}
if (!selectedEndpoints) {
callback(new Error("Cannot find an Endpoint matching " +
" security mode: " + securityMode.toString() +
" policy: " + securityPolicy.toString()));
}
const result = {
endpoints: allEndpoints,
selectedEndpoint: selectedEndpoints
};
callback(null, result);
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
() => {
setImmediate(callback);
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(/*err?: Error*/) => {
this._secureChannel = null;
callback();
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
() => {
/* empty */
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(err: Error, message: string) => {
errorLog("client = ", this.clientName, message, err.message);
if (this.reconnectionIsCanceled) {
this.emit("reconnection_canceled");
return callback(new Error("Reconnection has been canceled - " + this.clientName));
}
// else
// let retry a little bit later
this.emit("reconnection_attempt_has_failed", err, message); // send after callback
setTimeout(_attempt_to_recreate_secure_channel, 100);
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
() => {
if (this.reconnectionIsCanceled) {
this.emit("reconnection_canceled");
return callback(new Error("Reconnection has been canceled - " + this.clientName));
}
this._internal_create_secure_channel(infiniteConnectionRetry, (err?: Error | null) => {
if (err) {
if (err.message.match("ECONNREFUSED")) {
return callback(err);
}
if (err.message.match("Backoff aborted.")) {
return failAndRetry(err!, "cannot create secure channel");
}
if (true || err!.message.match("BadCertificateInvalid")) {
errorLog(" _internal_create_secure_channel err = ", err.message);
// the server may have shut down the channel because its certificate
// has changed ....
// let request the server certificate again ....
debugLog(chalk.bgWhite.red("ClientBaseImpl: Server Certificate has changed." +
" we need to retrieve server certificate again"));
return this.fetchServerCertificate(this.endpointUrl, (err1?: Error | null) => {
if (err1) {
return failAndRetry(err1, "trying to fetch new server certificate");
}
this._internal_create_secure_channel(infiniteConnectionRetry, (err3?: Error | null) => {
if (err3) {
return failAndRetry(err3, "trying to create new channel with new certificate");
}
callback();
});
});
}
debugLog(chalk.bgWhite.red("ClientBaseImpl: cannot reconnect .."));
failAndRetry(err!, "cannot create secure channel");
} else {
/**
* notify the observers that the reconnection process has been completed
* @event after_reconnection
* @param err
*/
this.emit("after_reconnection", err); // send after callback
assert(this._secureChannel, "expecting a secureChannel here ");
// a new channel has be created and a new connection is established
debugLog(chalk.bgWhite.red("ClientBaseImpl: RECONNECTED !!!"));
return callback();
}
});
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(err?: Error | null) => {
if (err) {
if (err.message.match("ECONNREFUSED")) {
return callback(err);
}
if (err.message.match("Backoff aborted.")) {
return failAndRetry(err!, "cannot create secure channel");
}
if (true || err!.message.match("BadCertificateInvalid")) {
errorLog(" _internal_create_secure_channel err = ", err.message);
// the server may have shut down the channel because its certificate
// has changed ....
// let request the server certificate again ....
debugLog(chalk.bgWhite.red("ClientBaseImpl: Server Certificate has changed." +
" we need to retrieve server certificate again"));
return this.fetchServerCertificate(this.endpointUrl, (err1?: Error | null) => {
if (err1) {
return failAndRetry(err1, "trying to fetch new server certificate");
}
this._internal_create_secure_channel(infiniteConnectionRetry, (err3?: Error | null) => {
if (err3) {
return failAndRetry(err3, "trying to create new channel with new certificate");
}
callback();
});
});
}
debugLog(chalk.bgWhite.red("ClientBaseImpl: cannot reconnect .."));
failAndRetry(err!, "cannot create secure channel");
} else {
/**
* notify the observers that the reconnection process has been completed
* @event after_reconnection
* @param err
*/
this.emit("after_reconnection", err); // send after callback
assert(this._secureChannel, "expecting a secureChannel here ");
// a new channel has be created and a new connection is established
debugLog(chalk.bgWhite.red("ClientBaseImpl: RECONNECTED !!!"));
return callback();
}
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(err1?: Error | null) => {
if (err1) {
return failAndRetry(err1, "trying to fetch new server certificate");
}
this._internal_create_secure_channel(infiniteConnectionRetry, (err3?: Error | null) => {
if (err3) {
return failAndRetry(err3, "trying to create new channel with new certificate");
}
callback();
});
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(err3?: Error | null) => {
if (err3) {
return failAndRetry(err3, "trying to create new channel with new certificate");
}
callback();
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
() => {
_attempt_to_recreate_secure_channel();
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
// ------------------------------------------------- STEP 2 : OpenSecureChannel
(_innerCallback: ErrorCallback) => {
secureChannel = new ClientSecureChannelLayer({
connectionStrategy,
defaultSecureTokenLifetime: this.defaultSecureTokenLifetime,
parent: this,
securityMode: this.securityMode,
securityPolicy: this.securityPolicy,
serverCertificate: this.serverCertificate,
tokenRenewalInterval: this.tokenRenewalInterval
});
this._secureChannel = secureChannel;
secureChannel.protocolVersion = this.protocolVersion;
secureChannel.create(this.endpointUrl, (err?: Error) => {
if (err) {
debugLog(chalk.yellow("Cannot create secureChannel"),
(err.message ? chalk.cyan(err.message) : ""));
this._destroy_secure_channel();
} else {
if (!this._secureChannel) {
debugLog("_secureChannel has been closed during the transaction !");
this._destroy_secure_channel();
return _innerCallback(new Error("Secure Channel Closed"));
}
assert(this._secureChannel !== null);
this._install_secure_channel_event_handlers(secureChannel);
}
assert(err || this._secureChannel !== null);
_innerCallback(err);
});
secureChannel.on("backoff", (count: number, delay: number) => {
this.emit("backoff", count, delay);
});
secureChannel.on("abort", () => {
this.emit("abort");
});
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(err?: Error) => {
if (err) {
debugLog(chalk.yellow("Cannot create secureChannel"),
(err.message ? chalk.cyan(err.message) : ""));
this._destroy_secure_channel();
} else {
if (!this._secureChannel) {
debugLog("_secureChannel has been closed during the transaction !");
this._destroy_secure_channel();
return _innerCallback(new Error("Secure Channel Closed"));
}
assert(this._secureChannel !== null);
this._install_secure_channel_event_handlers(secureChannel);
}
assert(err || this._secureChannel !== null);
_innerCallback(err);
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(count: number, delay: number) => {
this.emit("backoff", count, delay);
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
() => {
this.emit("abort");
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
// ------------------------------------------------- STEP 3 : GetEndpointsRequest
(innerCallback: ErrorCallback) => {
if (!this.knowsServerEndpoint) {
assert(this._secureChannel !== null);
this.getEndpoints((err: Error | null/*, endpoints?: EndpointDescription[]*/) => {
// Xx endpoints;
assert(this._secureChannel !== null);
innerCallback(err ? err : undefined);
});
} else {
// end points are already known
assert(this._secureChannel !== null);
innerCallback();
}
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(err: Error | null/*, endpoints?: EndpointDescription[]*/) => {
// Xx endpoints;
assert(this._secureChannel !== null);
innerCallback(err ? err : undefined);
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(err) => {
if (err) {
this._secureChannel = null;
callback(err);
} else {
assert(this._secureChannel !== null);
callback(null, secureChannel);
}
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
() => {
callback(new Error("connect already called"));
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(err?: Error) => {
if (err) {
return callback(err);
}
this.connect(endpointUrl, callback);
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(err?: Error) => setImmediate(() => callback(err))
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
() => callback(err)
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(err: Error | null /* secureChannel?: ClientSecureChannelLayer*/) => {
// xx secureChannel;
if (!err) {
this.emit("connected");
callbackOnceDelayed(err!);
} else {
OPCUAClientBase.registry.unregister(this);
uninstallPeriodicClockAdjustmement();
debugLog(chalk.red("SecureChannel creation has failed with error :", err.message));
if (err.message.match(/ECONNREF/)) {
debugLog(chalk.yellow("- The client cannot to :" + endpointUrl + ". Server is not reachable."));
err = new Error("The connection cannot be established with server " + endpointUrl + " .\n" +
"Please check that the server is up and running or your network configuration.\n" +
"Err = (" + err.message + ")");
} else {
debugLog(chalk.yellow(" - The client certificate may not be trusted by the server"));
err = new Error("The connection has been rejected by server,\n" +
"Please check that client certificate is trusted by server.\n" +
"Err = (" + err.message + ")");
}
this.emit("connection_failed", err);
callbackOnceDelayed(err!);
}
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(endpoint) => {
return endpoint.securityMode === securityMode &&
endpoint.securityPolicyUri === securityPolicy;
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(endpoint: EndpointDescription) => {
return endpoint.endpointUrl === endpointUrl &&
endpoint.securityMode === securityMode &&
endpoint.securityPolicyUri === securityPolicy;
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(err: Error | null, response?: Response) => {
this._serverEndpoints = [];
if (err) {
return callback(err);
}
if (!response || !(response instanceof GetEndpointsResponse)) {
return callback(new Error("Internal Error"));
}
if (response && response.endpoints) {
this._serverEndpoints = response.endpoints;
}
callback(null, this._serverEndpoints);
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
() => {
callback(new Error("Invalid Secure Channel"));
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(err: Error | null, response?: Response) => {
if (err) {
return callback(err);
}
if (!response || !(response instanceof FindServersResponse)) {
return callback(new Error("Internal Error"));
}
response.servers = response.servers || [];
callback(null, response.servers);
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(err: Error | null, response?: Response) => {
if (err) {
return callback(err);
}
if (!response || !(response instanceof FindServersOnNetworkResponse)) {
return new Error("Internal Error");
}
response.servers = response.servers || [];
callback(null, response.servers);
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(err?: Error) => {
debugLog("ClientBaseImpl#disconnect reconnection has been canceled");
assert(!err, " why would this fail ?");
assert(!this.isReconnecting);
// sessions cannot be cancelled properly and must be discarded.
this.disconnect(callback);
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(/*err*/) => {
this.disconnect(callback);
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(session: ClientSessionImpl) => {
this._removeSession(session);
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
() => {
this._secureChannel = tmpChannel;
tmpChannel = null;
this._destroy_secure_channel();
setImmediate(callback);
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(err: Error | null, result?: FindEndpointResult) => {
if (err) {
this.emit("connection_failed", err);
return callback(err);
}
if (!result) {
const err1 = new Error("internal error");
this.emit("connection_failed", err1);
return callback(err1);
}
const endpoint = result.selectedEndpoint;
if (!endpoint) {
// no matching end point can be found ...
const err1 = new Error("cannot find endpoint");
this.emit("connection_failed", err1);
return callback(err1);
}
assert(endpoint);
_verify_serverCertificate(endpoint.serverCertificate, (err1?: Error) => {
if (err1) {
this.emit("connection_failed", err1);
return callback(err1);
}
this.serverCertificate = endpoint.serverCertificate;
callback();
});
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(err1?: Error) => {
if (err1) {
this.emit("connection_failed", err1);
return callback(err1);
}
this.serverCertificate = endpoint.serverCertificate;
callback();
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(session: ClientSessionImpl, next: () => void) => {
assert(session._client === this);
// note: to prevent next to be call twice
let _next_already_call = false;
session.close((err?: Error) => {
if (_next_already_call) {
return;
}
_next_already_call = true;
// We should not bother if we have an error here
// Session may fail to close , if they haven't been activate and forcefully closed by server
// in a attempt to preserve resources in the case of a DDOS attack for instance.
if (err) {
const msg = session.authenticationToken ? session.authenticationToken.toString() : "";
debugLog(" failing to close session " + msg);
}
next();
});
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(err?: Error) => {
if (_next_already_call) {
return;
}
_next_already_call = true;
// We should not bother if we have an error here
// Session may fail to close , if they haven't been activate and forcefully closed by server
// in a attempt to preserve resources in the case of a DDOS attack for instance.
if (err) {
const msg = session.authenticationToken ? session.authenticationToken.toString() : "";
debugLog(" failing to close session " + msg);
}
next();
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(err) => {
// istanbul ignore next
if (this._sessions.length > 0) {
debugLog(this._sessions.map((s: ClientSessionImpl) =>
s.authenticationToken ? s.authenticationToken.toString() : "").join(" "));
}
assert(this._sessions.length === 0, " failed to disconnect exiting sessions ");
callback(err!);
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(s: ClientSessionImpl) =>
s.authenticationToken ? s.authenticationToken.toString() : ""
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(chunk: Buffer) => {
/**
* notify the observer that a message_chunk has been sent
* @event send_chunk
* @param message_chunk
*/
this.emit("send_chunk", chunk);
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(chunk: Buffer) => {
/**
* notify the observer that a message_chunk has been received
* @event receive_chunk
* @param message_chunk
*/
this.emit("receive_chunk", chunk);
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(message: Request) => {
/**
* notify the observer that a request has been sent to the server.
* @event send_request
* @param message
*/
this.emit("send_request", message);
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(message: Response) => {
/**
* notify the observer that a response has been received from the server.
* @event receive_response
* @param message
*/
this.emit("receive_response", message);
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(token: SecurityToken) => {
// secureChannel requests a new token
debugLog("SecureChannel Security Token ", token.tokenId, "live time was =", token.revisedLifetime,
" is about to expired , it's time to request a new token");
// forward message to upper level
this.emit("lifetime_75", token, secureChannel);
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
() => {
// forward message to upper level
this.emit("security_token_renewed", secureChannel);
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(err?: Error) => {
debugLog(chalk.yellow.bold(" ClientBaseImpl emitting close"), err);
if (!err || !this.reconnectOnFailure) {
// this is a normal close operation initiated byu
/**
* @event close
* @param error
*/
this.emit("close", err);
setImmediate(() => {
this._destroy_secure_channel();
});
return;
} else {
this.emit("connection_lost");
setImmediate(() => {
debugLog("recreating new secure channel ");
this._recreate_secure_channel((err1?: Error) => {
debugLog("secureChannel#on(close) => _recreate_secure_channel returns ",
err1 ? err1.message : "OK");
if (err1) {
// xx assert(!this._secureChannel);
debugLog("_recreate_secure_channel has failed");
// xx this.emit("close", err1);
return;
} else {
/**
* @event connection_reestablished
* send when the connection is reestablished after a connection break
*/
this.emit("connection_reestablished");
// now delegate to upper class the
if (this._on_connection_reestablished) {
assert(_.isFunction(this._on_connection_reestablished));
this._on_connection_reestablished((err2?: Error) => {
if (err2) {
debugLog("connection_reestablished has failed");
this.disconnect(() => {
// callback(err);
// tslint:disable-next-line: no-console
console.log("Disconnected following reconnection failure", err2.message);
});
}
});
}
}
});
});
}
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
() => {
this._destroy_secure_channel();
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
() => {
debugLog("recreating new secure channel ");
this._recreate_secure_channel((err1?: Error) => {
debugLog("secureChannel#on(close) => _recreate_secure_channel returns ",
err1 ? err1.message : "OK");
if (err1) {
// xx assert(!this._secureChannel);
debugLog("_recreate_secure_channel has failed");
// xx this.emit("close", err1);
return;
} else {
/**
* @event connection_reestablished
* send when the connection is reestablished after a connection break
*/
this.emit("connection_reestablished");
// now delegate to upper class the
if (this._on_connection_reestablished) {
assert(_.isFunction(this._on_connection_reestablished));
this._on_connection_reestablished((err2?: Error) => {
if (err2) {
debugLog("connection_reestablished has failed");
this.disconnect(() => {
// callback(err);
// tslint:disable-next-line: no-console
console.log("Disconnected following reconnection failure", err2.message);
});
}
});
}
}
});
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(err1?: Error) => {
debugLog("secureChannel#on(close) => _recreate_secure_channel returns ",
err1 ? err1.message : "OK");
if (err1) {
// xx assert(!this._secureChannel);
debugLog("_recreate_secure_channel has failed");
// xx this.emit("close", err1);
return;
} else {
/**
* @event connection_reestablished
* send when the connection is reestablished after a connection break
*/
this.emit("connection_reestablished");
// now delegate to upper class the
if (this._on_connection_reestablished) {
assert(_.isFunction(this._on_connection_reestablished));
this._on_connection_reestablished((err2?: Error) => {
if (err2) {
debugLog("connection_reestablished has failed");
this.disconnect(() => {
// callback(err);
// tslint:disable-next-line: no-console
console.log("Disconnected following reconnection failure", err2.message);
});
}
});
}
}
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(err2?: Error) => {
if (err2) {
debugLog("connection_reestablished has failed");
this.disconnect(() => {
// callback(err);
// tslint:disable-next-line: no-console
console.log("Disconnected following reconnection failure", err2.message);
});
}
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
() => {
// callback(err);
// tslint:disable-next-line: no-console
console.log("Disconnected following reconnection failure", err2.message);
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(request: Request) => {
/**
* send when a request has timed out without receiving a response
* @event timed_out_request
* @param request
*/
this.emit("timed_out_request", request);
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
ArrowFunction
|
(options: OPCUAClientBaseOptions): OPCUAClientBase => {
return new ClientBaseImpl(options);
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
public _cancel_reconnection(callback: ErrorCallback) {
assert(this.isReconnecting);
// istanbul ignore next
this.reconnectionIsCanceled = true;
if (!this._secureChannel) {
return callback(); // nothing to do
}
this._secureChannel.abortConnection((/*err?: Error*/) => {
this._secureChannel = null;
callback();
});
(this as any).once("reconnection_canceled", () => {
/* empty */
});
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
public _recreate_secure_channel(callback: ErrorCallback) {
debugLog("_recreate_secure_channel...");
if (!this.knowsServerEndpoint) {
debugLog("Cannot reconnect , server endpoint is unknown");
return callback(new Error("Cannot reconnect, server endpoint is unknown"));
}
assert(this.knowsServerEndpoint);
assert(!this.isReconnecting);
/**
* notifies the observer that the OPCUA is now trying to reestablish the connection
* after having received a connection break...
* @event start_reconnection
*
*/
this.emit("start_reconnection"); // send after callback
this._destroy_secure_channel();
assert(!this._secureChannel);
const infiniteConnectionRetry: ConnectionStrategyOptions = {
initialDelay: this.connectionStrategy.initialDelay,
maxDelay: this.connectionStrategy.maxDelay,
maxRetry: -1
};
const failAndRetry = (err: Error, message: string) => {
errorLog("client = ", this.clientName, message, err.message);
if (this.reconnectionIsCanceled) {
this.emit("reconnection_canceled");
return callback(new Error("Reconnection has been canceled - " + this.clientName));
}
// else
// let retry a little bit later
this.emit("reconnection_attempt_has_failed", err, message); // send after callback
setTimeout(_attempt_to_recreate_secure_channel, 100);
};
const _attempt_to_recreate_secure_channel = () => {
if (this.reconnectionIsCanceled) {
this.emit("reconnection_canceled");
return callback(new Error("Reconnection has been canceled - " + this.clientName));
}
this._internal_create_secure_channel(infiniteConnectionRetry, (err?: Error | null) => {
if (err) {
if (err.message.match("ECONNREFUSED")) {
return callback(err);
}
if (err.message.match("Backoff aborted.")) {
return failAndRetry(err!, "cannot create secure channel");
}
if (true || err!.message.match("BadCertificateInvalid")) {
errorLog(" _internal_create_secure_channel err = ", err.message);
// the server may have shut down the channel because its certificate
// has changed ....
// let request the server certificate again ....
debugLog(chalk.bgWhite.red("ClientBaseImpl: Server Certificate has changed." +
" we need to retrieve server certificate again"));
return this.fetchServerCertificate(this.endpointUrl, (err1?: Error | null) => {
if (err1) {
return failAndRetry(err1, "trying to fetch new server certificate");
}
this._internal_create_secure_channel(infiniteConnectionRetry, (err3?: Error | null) => {
if (err3) {
return failAndRetry(err3, "trying to create new channel with new certificate");
}
callback();
});
});
}
debugLog(chalk.bgWhite.red("ClientBaseImpl: cannot reconnect .."));
failAndRetry(err!, "cannot create secure channel");
} else {
/**
* notify the observers that the reconnection process has been completed
* @event after_reconnection
* @param err
*/
this.emit("after_reconnection", err); // send after callback
assert(this._secureChannel, "expecting a secureChannel here ");
// a new channel has be created and a new connection is established
debugLog(chalk.bgWhite.red("ClientBaseImpl: RECONNECTED !!!"));
return callback();
}
});
};
// create a secure channel
// a new secure channel must be established
setImmediate(() => {
_attempt_to_recreate_secure_channel();
});
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
public _internal_create_secure_channel(
connectionStrategy: ConnectionStrategyOptions,
callback: CreateSecureChannelCallbackFunc
) {
let secureChannel: ClientSecureChannelLayer;
assert(this._secureChannel === null);
assert(_.isString(this.endpointUrl));
async.series([
// ------------------------------------------------- STEP 2 : OpenSecureChannel
(_innerCallback: ErrorCallback) => {
secureChannel = new ClientSecureChannelLayer({
connectionStrategy,
defaultSecureTokenLifetime: this.defaultSecureTokenLifetime,
parent: this,
securityMode: this.securityMode,
securityPolicy: this.securityPolicy,
serverCertificate: this.serverCertificate,
tokenRenewalInterval: this.tokenRenewalInterval
});
this._secureChannel = secureChannel;
secureChannel.protocolVersion = this.protocolVersion;
secureChannel.create(this.endpointUrl, (err?: Error) => {
if (err) {
debugLog(chalk.yellow("Cannot create secureChannel"),
(err.message ? chalk.cyan(err.message) : ""));
this._destroy_secure_channel();
} else {
if (!this._secureChannel) {
debugLog("_secureChannel has been closed during the transaction !");
this._destroy_secure_channel();
return _innerCallback(new Error("Secure Channel Closed"));
}
assert(this._secureChannel !== null);
this._install_secure_channel_event_handlers(secureChannel);
}
assert(err || this._secureChannel !== null);
_innerCallback(err);
});
secureChannel.on("backoff", (count: number, delay: number) => {
this.emit("backoff", count, delay);
});
secureChannel.on("abort", () => {
this.emit("abort");
});
},
// ------------------------------------------------- STEP 3 : GetEndpointsRequest
(innerCallback: ErrorCallback) => {
if (!this.knowsServerEndpoint) {
assert(this._secureChannel !== null);
this.getEndpoints((err: Error | null/*, endpoints?: EndpointDescription[]*/) => {
// Xx endpoints;
assert(this._secureChannel !== null);
innerCallback(err ? err : undefined);
});
} else {
// end points are already known
assert(this._secureChannel !== null);
innerCallback();
}
}
], (err) => {
if (err) {
this._secureChannel = null;
callback(err);
} else {
assert(this._secureChannel !== null);
callback(null, secureChannel);
}
});
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
/**
* connect the OPC-UA client to a server end point.
* @async
*/
public connect(endpointUrl: string): Promise<void>;
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
public connect(endpointUrl: string, callback: ErrorCallback): void;
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
public connect(...args: any[]): any {
const endpointUrl = args[0];
const callback = args[1];
assert(_.isFunction(callback), "expecting a callback");
this.endpointUrl = endpointUrl;
debugLog("ClientBaseImpl#connect ", endpointUrl);
// prevent illegal call to connect
if (this._secureChannel !== null) {
setImmediate(() => {
callback(new Error("connect already called"));
});
return;
}
if (!this.serverCertificate && this.securityMode !== MessageSecurityMode.None) {
return this.fetchServerCertificate(endpointUrl, (err?: Error) => {
if (err) {
return callback(err);
}
this.connect(endpointUrl, callback);
});
}
// todo: make sure endpointUrl exists in the list of endpoints send by the server
// [...]
// make sure callback will only be call once regardless of outcome, and will be also deferred.
const callbackOnceDelayed: any = once((err?: Error) => setImmediate(() => callback(err)));
installPeriodicClockAdjustmement();
OPCUAClientBase.registry.register(this);
this._internal_create_secure_channel(this.connectionStrategy, (err: Error | null /* secureChannel?: ClientSecureChannelLayer*/) => {
// xx secureChannel;
if (!err) {
this.emit("connected");
callbackOnceDelayed(err!);
} else {
OPCUAClientBase.registry.unregister(this);
uninstallPeriodicClockAdjustmement();
debugLog(chalk.red("SecureChannel creation has failed with error :", err.message));
if (err.message.match(/ECONNREF/)) {
debugLog(chalk.yellow("- The client cannot to :" + endpointUrl + ". Server is not reachable."));
err = new Error("The connection cannot be established with server " + endpointUrl + " .\n" +
"Please check that the server is up and running or your network configuration.\n" +
"Err = (" + err.message + ")");
} else {
debugLog(chalk.yellow(" - The client certificate may not be trusted by the server"));
err = new Error("The connection has been rejected by server,\n" +
"Please check that client certificate is trusted by server.\n" +
"Err = (" + err.message + ")");
}
this.emit("connection_failed", err);
callbackOnceDelayed(err!);
}
});
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
public getClientNonce(): Nonce | null {
return this._secureChannel ? this._secureChannel.getClientNonce() : null;
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
public performMessageTransaction(request: Request, callback: ResponseCallback<Response>) {
if (!this._secureChannel) {
// this may happen if the Server has closed the connection abruptly for some unknown reason
// or if the tcp connection has been broken.
return callback(new Error("No SecureChannel , connection may have been canceled abruptly by server"));
}
assert(this._secureChannel);
assert(request);
assert(request.requestHeader);
assert(typeof callback === "function");
this._secureChannel.performMessageTransaction(request, callback as any);
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
/**
*
* return the endpoint information matching security mode and security policy.
* @method findEndpoint
*/
public findEndpointForSecurity(
securityMode: MessageSecurityMode,
securityPolicy: SecurityPolicy
): EndpointDescription | undefined {
securityMode = coerceMessageSecurityMode(securityMode);
securityPolicy = coerceSecurityPolicy(securityPolicy);
assert(this.knowsServerEndpoint, "Server end point are not known yet");
return _.find(this._serverEndpoints, (endpoint) => {
return endpoint.securityMode === securityMode &&
endpoint.securityPolicyUri === securityPolicy;
});
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
/**
*
* return the endpoint information matching the specified url , security mode and security policy.
* @method findEndpoint
*/
public findEndpoint(
endpointUrl: string,
securityMode: MessageSecurityMode,
securityPolicy: SecurityPolicy
): EndpointDescription | undefined {
assert(this.knowsServerEndpoint, "Server end point are not known yet");
if (!this._serverEndpoints || this._serverEndpoints.length === 0) {
return undefined;
}
return _.find(this._serverEndpoints, (endpoint: EndpointDescription) => {
return endpoint.endpointUrl === endpointUrl &&
endpoint.securityMode === securityMode &&
endpoint.securityPolicyUri === securityPolicy;
});
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
public async getEndpoints(options?: GetEndpointsOptions): Promise<EndpointDescription[]>;
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
public getEndpoints(options: GetEndpointsOptions, callback: ResponseCallback<EndpointDescription[]>): void;
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
public getEndpoints(callback: ResponseCallback<EndpointDescription[]>): void;
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
public getEndpoints(...args: any[]): any {
if (args.length === 1) {
return this.getEndpoints({}, args[0]);
}
const options = args[0] as GetEndpointsOptions;
const callback = args[1] as ResponseCallback<EndpointDescription[]>;
assert(_.isFunction(callback));
options.localeIds = options.localeIds || [];
options.profileUris = options.profileUris || [];
const request = new GetEndpointsRequest({
endpointUrl: options.endpointUrl || this.endpointUrl,
localeIds: options.localeIds,
profileUris: options.profileUris,
requestHeader: {
auditEntryId: null
}
});
this.performMessageTransaction(request, (err: Error | null, response?: Response) => {
this._serverEndpoints = [];
if (err) {
return callback(err);
}
if (!response || !(response instanceof GetEndpointsResponse)) {
return callback(new Error("Internal Error"));
}
if (response && response.endpoints) {
this._serverEndpoints = response.endpoints;
}
callback(null, this._serverEndpoints);
});
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
public getEndpointsRequest(options: any, callback: any) {
warningLog("note: ClientBaseImpl#getEndpointsRequest is deprecated, use ClientBaseImpl#getEndpoints instead");
return this.getEndpoints(options, callback);
}
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
/**
* @method findServers
*/
public findServers(options?: FindServersRequestLike): Promise<ApplicationDescription[]>;
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
MethodDeclaration
|
public findServers(options: FindServersRequestLike, callback: ResponseCallback<ApplicationDescription[]>): void;
|
goldim/node-opcua
|
packages/node-opcua-client/source/private/client_base_impl.ts
|
TypeScript
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.